void *xmalloc(size_t bytes) {
   char *temp;

   /* Align buffer on 4 byte boundery for HP UX and other 64 bit systems to prevent Bus error (core dump) */
   if (bytes & 3)
      bytes += 4 - (bytes & 3);

   temp = (char *) malloc(bytes + 12);
   if (temp == 0)
      memory_error_and_abort("xmalloc");

   /* put magic number around array and put array size */
   *(unsigned int *) (temp + 0) = bytes;
   *(unsigned int *) (temp + 4) = 0xdeadc0de;
   *(unsigned int *) (temp + bytes + 8) = 0xdeadc0de;

   return (temp + 8);
}


static bool fw_cfg_comb_valid(void *opaque, target_phys_addr_t addr,

                                  unsigned size, bool is_write)

{

    return (size == 1) || (is_write && size == 2);

}


OSD::~OSD()
{
  delete authorize_handler_cluster_registry;
  delete authorize_handler_service_registry;
  delete class_handler;
  cct->get_perfcounters_collection()->remove(recoverystate_perf);
  cct->get_perfcounters_collection()->remove(logger);
  delete recoverystate_perf;
  delete logger;
  delete store;
}


TEST_P(SslSocketTest, FailedClientCertificateHashAndSpkiVerificationNoClientCertificate) {
  envoy::config::listener::v3::Listener listener;
  envoy::config::listener::v3::FilterChain* filter_chain = listener.add_filter_chains();
  envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context;
  envoy::extensions::transport_sockets::tls::v3::TlsCertificate* server_cert =
      tls_context.mutable_common_tls_context()->add_tls_certificates();
  server_cert->mutable_certificate_chain()->set_filename(TestEnvironment::substitute(
      "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem"));
  server_cert->mutable_private_key()->set_filename(TestEnvironment::substitute(
      "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_key.pem"));
  envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext*
      server_validation_ctx =
          tls_context.mutable_common_tls_context()->mutable_validation_context();
  server_validation_ctx->mutable_trusted_ca()->set_filename(TestEnvironment::substitute(
      "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem"));
  server_validation_ctx->add_verify_certificate_hash(
      "0000000000000000000000000000000000000000000000000000000000000000");
  server_validation_ctx->add_verify_certificate_spki(TEST_SAN_URI_CERT_SPKI);
  updateFilterChain(tls_context, *filter_chain);

  envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext client;

  TestUtilOptionsV2 test_options(listener, client, false, GetParam());
  testUtilV2(test_options.setExpectedServerStats("ssl.fail_verify_no_cert")
                 .setExpectedTransportFailureReasonContains("SSLV3_ALERT_HANDSHAKE_FAILURE"));

  // Fails even with client renegotiation.
  client.set_allow_renegotiation(true);
  testUtilV2(test_options);
}


xps_clip(xps_document *doc, const fz_matrix *ctm, xps_resource *dict, char *clip_att, fz_xml *clip_tag)
{
	fz_path *path;
	int fill_rule = 0;

	if (clip_att)
		path = xps_parse_abbreviated_geometry(doc, clip_att, &fill_rule);
	else if (clip_tag)
		path = xps_parse_path_geometry(doc, dict, clip_tag, 0, &fill_rule);
	else
		path = fz_new_path(doc->ctx);
	fz_clip_path(doc->dev, path, NULL, fill_rule == 0, ctm);
	fz_free_path(doc->ctx, path);
}


Formattable::operator==(const Formattable& that) const
{
    int32_t i;

    if (this == &that) return TRUE;

    // Returns FALSE if the data types are different.
    if (fType != that.fType) return FALSE;

    // Compares the actual data values.
    UBool equal = TRUE;
    switch (fType) {
    case kDate:
        equal = (fValue.fDate == that.fValue.fDate);
        break;
    case kDouble:
        equal = (fValue.fDouble == that.fValue.fDouble);
        break;
    case kLong:
    case kInt64:
        equal = (fValue.fInt64 == that.fValue.fInt64);
        break;
    case kString:
        equal = (*(fValue.fString) == *(that.fValue.fString));
        break;
    case kArray:
        if (fValue.fArrayAndCount.fCount != that.fValue.fArrayAndCount.fCount) {
            equal = FALSE;
            break;
        }
        // Checks each element for equality.
        for (i=0; i<fValue.fArrayAndCount.fCount; ++i) {
            if (fValue.fArrayAndCount.fArray[i] != that.fValue.fArrayAndCount.fArray[i]) {
                equal = FALSE;
                break;
            }
        }
        break;
    case kObject:
        if (fValue.fObject == NULL || that.fValue.fObject == NULL) {
            equal = FALSE;
        } else {
            equal = objectEquals(fValue.fObject, that.fValue.fObject);
        }
        break;
    }

    // TODO:  compare digit lists if numeric.
    return equal;
}


static int open_input_stream(HTTPContext *c, const char *info)

{

    char buf[128];

    char input_filename[1024];

    AVFormatContext *s;

    int buf_size, i, ret;

    int64_t stream_pos;

    /* find file name */

    if (c->stream->feed) {

        strcpy(input_filename, c->stream->feed->feed_filename);

        buf_size = FFM_PACKET_SIZE;

        /* compute position (absolute time) */

        if (find_info_tag(buf, sizeof(buf), "date", info)) {

            stream_pos = parse_date(buf, 0);

            if (stream_pos == INT64_MIN)

                return -1;

        } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {

            int prebuffer = strtol(buf, 0, 10);

            stream_pos = av_gettime() - prebuffer * (int64_t)1000000;

        } else

            stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;

    } else {

        strcpy(input_filename, c->stream->feed_filename);

        buf_size = 0;

        /* compute position (relative time) */

        if (find_info_tag(buf, sizeof(buf), "date", info)) {

            stream_pos = parse_date(buf, 1);

            if (stream_pos == INT64_MIN)

                return -1;

        } else

            stream_pos = 0;

    }

    if (input_filename[0] == '\0')

        return -1;

#if 0

    { time_t when = stream_pos / 1000000;

    http_log("Stream pos = %"PRId64", time=%s", stream_pos, ctime(&when));

    }

#endif

    /* open stream */

    if ((ret = av_open_input_file(&s, input_filename, c->stream->ifmt,

                                  buf_size, c->stream->ap_in)) < 0) {

        http_log("could not open %s: %d\n", input_filename, ret);

        return -1;

    }

    s->flags |= AVFMT_FLAG_GENPTS;

    c->fmt_in = s;

    av_find_stream_info(c->fmt_in);

    /* open each parser */

    for(i=0;i<s->nb_streams;i++)

        open_parser(s, i);

    /* choose stream as clock source (we favorize video stream if

       present) for packet sending */

    c->pts_stream_index = 0;

    for(i=0;i<c->stream->nb_streams;i++) {

        if (c->pts_stream_index == 0 &&

            c->stream->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO) {

            c->pts_stream_index = i;

        }

    }

#if 1

    if (c->fmt_in->iformat->read_seek)

        av_seek_frame(c->fmt_in, -1, stream_pos, 0);

#endif

    /* set the start time (needed for maxtime and RTP packet timing) */

    c->start_time = cur_time;

    c->first_pts = AV_NOPTS_VALUE;

    return 0;

}


static int handle_vmclear(struct kvm_vcpu *vcpu)
{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
	u32 zero = 0;
	gpa_t vmptr;

	if (!nested_vmx_check_permission(vcpu))
		return 1;

	if (nested_vmx_get_vmptr(vcpu, &vmptr))
		return 1;

	if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
		nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
		return kvm_skip_emulated_instruction(vcpu);
	}

	if (vmptr == vmx->nested.vmxon_ptr) {
		nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
		return kvm_skip_emulated_instruction(vcpu);
	}

	if (vmptr == vmx->nested.current_vmptr)
		nested_release_vmcs12(vmx);

	kvm_vcpu_write_guest(vcpu,
			vmptr + offsetof(struct vmcs12, launch_state),
			&zero, sizeof(zero));

	nested_free_vmcs02(vmx, vmptr);

	nested_vmx_succeed(vcpu);
	return kvm_skip_emulated_instruction(vcpu);
}


  gray_render_cubic( RAS_ARG_ const FT_Vector*  control1,
                              const FT_Vector*  control2,
                              const FT_Vector*  to )
  {
    int         top, level;
    int*        levels;
    FT_Vector*  arc;
    int         mid_x = ( DOWNSCALE( ras.x ) + to->x +
                          3 * (control1->x + control2->x ) ) / 8;
    int         mid_y = ( DOWNSCALE( ras.y ) + to->y +
                          3 * (control1->y + control2->y ) ) / 8;
    TPos        dx = DOWNSCALE( ras.x ) + to->x - ( mid_x << 1 );
    TPos        dy = DOWNSCALE( ras.y ) + to->y - ( mid_y << 1 );

    if ( dx < 0 )
      dx = -dx;
    if ( dy < 0 )
      dy = -dy;
    if ( dx < dy )
      dx = dy;

    level = 1;
    dx /= ras.cubic_level;
    while ( dx > 0 )
    {
      dx >>= 2;
      level++;
    }

    if ( level <= 1 )
    {
      TPos  to_x, to_y;

      to_x  = UPSCALE( to->x );
      to_y  = UPSCALE( to->y );

      /* Recalculation of midpoint is needed only if */
      /* UPSCALE and DOWNSCALE have any effect.      */

#if ( PIXEL_BITS != 6 )
      mid_x = ( ras.x + to_x +
                3 * UPSCALE( control1->x + control2->x ) ) / 8;
      mid_y = ( ras.y + to_y +
                3 * UPSCALE( control1->y + control2->y ) ) / 8;
#endif

      gray_render_line( RAS_VAR_ mid_x, mid_y );
      gray_render_line( RAS_VAR_ to_x, to_y );

      return;
    }

    arc      = ras.bez_stack;
    arc[0].x = UPSCALE( to->x );
    arc[0].y = UPSCALE( to->y );
    arc[1].x = UPSCALE( control2->x );
    arc[1].y = UPSCALE( control2->y );
    arc[2].x = UPSCALE( control1->x );
    arc[2].y = UPSCALE( control1->y );
    arc[3].x = ras.x;
    arc[3].y = ras.y;

    levels    = ras.lev_stack;
    top       = 0;
    levels[0] = level;

    while ( top >= 0 )
    {
      level = levels[top];
      if ( level > 1 )
      {
        /* check that the arc crosses the current band */
        TPos  min, max, y;

        min = max = arc[0].y;
        y = arc[1].y;
        if ( y < min ) min = y;
        if ( y > max ) max = y;
        y = arc[2].y;
        if ( y < min ) min = y;
        if ( y > max ) max = y;
        y = arc[3].y;
        if ( y < min ) min = y;
        if ( y > max ) max = y;
        if ( TRUNC( min ) >= ras.max_ey || TRUNC( max ) < 0 )
          goto Draw;
        gray_split_cubic( arc );
        arc += 3;
        top ++;
        levels[top] = levels[top - 1] = level - 1;
        continue;
      }

    Draw:
      {
        TPos  to_x, to_y;

        to_x  = arc[0].x;
        to_y  = arc[0].y;
        mid_x = ( ras.x + to_x + 3 * ( arc[1].x + arc[2].x ) ) / 8;
        mid_y = ( ras.y + to_y + 3 * ( arc[1].y + arc[2].y ) ) / 8;

        gray_render_line( RAS_VAR_ mid_x, mid_y );
        gray_render_line( RAS_VAR_ to_x, to_y );
        top --;
        arc -= 3;
      }
    }

    return;
  }


gpgsm_set_colon_line_handler (void *engine, engine_colon_line_handler_t fnc,
			      void *fnc_value)
{
  engine_gpgsm_t gpgsm = engine;

  gpgsm->colon.fnc = fnc;
  gpgsm->colon.fnc_value = fnc_value;
  gpgsm->colon.any = 0;
  return 0;
}


xfs_attr_shortform_remove(xfs_da_args_t *args)
{
	xfs_attr_shortform_t *sf;
	xfs_attr_sf_entry_t *sfe;
	int base, size=0, end, totsize, i;
	xfs_mount_t *mp;
	xfs_inode_t *dp;

	trace_xfs_attr_sf_remove(args);

	dp = args->dp;
	mp = dp->i_mount;
	base = sizeof(xfs_attr_sf_hdr_t);
	sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
	sfe = &sf->list[0];
	end = sf->hdr.count;
	for (i = 0; i < end; sfe = XFS_ATTR_SF_NEXTENTRY(sfe),
					base += size, i++) {
		size = XFS_ATTR_SF_ENTSIZE(sfe);
		if (sfe->namelen != args->namelen)
			continue;
		if (memcmp(sfe->nameval, args->name, args->namelen) != 0)
			continue;
		if (!xfs_attr_namesp_match(args->flags, sfe->flags))
			continue;
		break;
	}
	if (i == end)
		return(XFS_ERROR(ENOATTR));

	/*
	 * Fix up the attribute fork data, covering the hole
	 */
	end = base + size;
	totsize = be16_to_cpu(sf->hdr.totsize);
	if (end != totsize)
		memmove(&((char *)sf)[base], &((char *)sf)[end], totsize - end);
	sf->hdr.count--;
	be16_add_cpu(&sf->hdr.totsize, -size);

	/*
	 * Fix up the start offset of the attribute fork
	 */
	totsize -= size;
	if (totsize == sizeof(xfs_attr_sf_hdr_t) &&
	    (mp->m_flags & XFS_MOUNT_ATTR2) &&
	    (dp->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
	    !(args->op_flags & XFS_DA_OP_ADDNAME)) {
		xfs_attr_fork_reset(dp, args->trans);
	} else {
		xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
		dp->i_d.di_forkoff = xfs_attr_shortform_bytesfit(dp, totsize);
		ASSERT(dp->i_d.di_forkoff);
		ASSERT(totsize > sizeof(xfs_attr_sf_hdr_t) ||
				(args->op_flags & XFS_DA_OP_ADDNAME) ||
				!(mp->m_flags & XFS_MOUNT_ATTR2) ||
				dp->i_d.di_format == XFS_DINODE_FMT_BTREE);
		xfs_trans_log_inode(args->trans, dp,
					XFS_ILOG_CORE | XFS_ILOG_ADATA);
	}

	xfs_sbversion_add_attr2(mp, args->trans);

	return(0);
}


CallbackList& callbacks() { return callbacks_; }


WirelessNetwork::WirelessNetwork(const ServiceInfo* service)
    : Network(service) {
  name_ = SafeString(service->name);
  strength_ = service->strength;
  auto_connect_ = service->auto_connect;
  favorite_ = service->favorite;
}


int dns_hostname_validation(const char *string, char **err)
{
	const char *c, *d;
	int i;

	if (strlen(string) > DNS_MAX_NAME_SIZE) {
		if (err)
			*err = DNS_TOO_LONG_FQDN;
		return 0;
	}

	c = string;
	while (*c) {
		d = c;

		i = 0;
		while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
			i++;
			if (!((*d == '-') || (*d == '_') ||
			      ((*d >= 'a') && (*d <= 'z')) ||
			      ((*d >= 'A') && (*d <= 'Z')) ||
			      ((*d >= '0') && (*d <= '9')))) {
				if (err)
					*err = DNS_INVALID_CHARACTER;
				return 0;
			}
			d++;
		}

		if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
			if (err)
				*err = DNS_LABEL_TOO_LONG;
			return 0;
		}

		if (*d == '\0')
			goto out;

		c = ++d;
	}
 out:
	return 1;
}


bool batadv_frag_send_packet(struct sk_buff *skb,
			     struct batadv_orig_node *orig_node,
			     struct batadv_neigh_node *neigh_node)
{
	struct batadv_priv *bat_priv;
	struct batadv_hard_iface *primary_if = NULL;
	struct batadv_frag_packet frag_header;
	struct sk_buff *skb_fragment;
	unsigned mtu = neigh_node->if_incoming->net_dev->mtu;
	unsigned header_size = sizeof(frag_header);
	unsigned max_fragment_size, max_packet_size;
	bool ret = false;

	/* To avoid merge and refragmentation at next-hops we never send
	 * fragments larger than BATADV_FRAG_MAX_FRAG_SIZE
	 */
	mtu = min_t(unsigned, mtu, BATADV_FRAG_MAX_FRAG_SIZE);
	max_fragment_size = (mtu - header_size - ETH_HLEN);
	max_packet_size = max_fragment_size * BATADV_FRAG_MAX_FRAGMENTS;

	/* Don't even try to fragment, if we need more than 16 fragments */
	if (skb->len > max_packet_size)
		goto out_err;

	bat_priv = orig_node->bat_priv;
	primary_if = batadv_primary_if_get_selected(bat_priv);
	if (!primary_if)
		goto out_err;

	/* Create one header to be copied to all fragments */
	frag_header.packet_type = BATADV_UNICAST_FRAG;
	frag_header.version = BATADV_COMPAT_VERSION;
	frag_header.ttl = BATADV_TTL;
	frag_header.seqno = htons(atomic_inc_return(&bat_priv->frag_seqno));
	frag_header.reserved = 0;
	frag_header.no = 0;
	frag_header.total_size = htons(skb->len);
	ether_addr_copy(frag_header.orig, primary_if->net_dev->dev_addr);
	ether_addr_copy(frag_header.dest, orig_node->orig);

	/* Eat and send fragments from the tail of skb */
	while (skb->len > max_fragment_size) {
		skb_fragment = batadv_frag_create(skb, &frag_header, mtu);
		if (!skb_fragment)
			goto out_err;

		batadv_inc_counter(bat_priv, BATADV_CNT_FRAG_TX);
		batadv_add_counter(bat_priv, BATADV_CNT_FRAG_TX_BYTES,
				   skb_fragment->len + ETH_HLEN);
		batadv_send_skb_packet(skb_fragment, neigh_node->if_incoming,
				       neigh_node->addr);
		frag_header.no++;

		/* The initial check in this function should cover this case */
		if (frag_header.no == BATADV_FRAG_MAX_FRAGMENTS - 1)
			goto out_err;
	}

	/* Make room for the fragment header. */
	if (batadv_skb_head_push(skb, header_size) < 0 ||
	    pskb_expand_head(skb, header_size + ETH_HLEN, 0, GFP_ATOMIC) < 0)
		goto out_err;

	memcpy(skb->data, &frag_header, header_size);

	/* Send the last fragment */
	batadv_inc_counter(bat_priv, BATADV_CNT_FRAG_TX);
	batadv_add_counter(bat_priv, BATADV_CNT_FRAG_TX_BYTES,
			   skb->len + ETH_HLEN);
	batadv_send_skb_packet(skb, neigh_node->if_incoming, neigh_node->addr);

	ret = true;

out_err:
	if (primary_if)
		batadv_hardif_free_ref(primary_if);

	return ret;
}


JSObject::checkPropertyUpdate(
    Runtime *runtime,
    const PropertyFlags currentFlags,
    DefinePropertyFlags dpFlags,
    const HermesValue curValueOrAccessor,
    Handle<> valueOrAccessor,
    PropOpFlags opFlags) {
  // 8.12.9 [5] Return true, if every field in Desc is absent.
  if (dpFlags.isEmpty())
    return std::make_pair(PropertyUpdateStatus::done, currentFlags);

  assert(
      (!dpFlags.isAccessor() || (!dpFlags.setWritable && !dpFlags.writable)) &&
      "can't set both accessor and writable");
  assert(
      !dpFlags.enableInternalSetter &&
      "cannot change the value of internalSetter");

  // 8.12.9 [6] Return true, if every field in Desc also occurs in current and
  // the value of every field in Desc is the same value as the corresponding
  // field in current when compared using the SameValue algorithm (9.12).
  // TODO: this would probably be much more efficient with bitmasks.
  if ((!dpFlags.setEnumerable ||
       dpFlags.enumerable == currentFlags.enumerable) &&
      (!dpFlags.setConfigurable ||
       dpFlags.configurable == currentFlags.configurable)) {
    if (dpFlags.isAccessor()) {
      if (currentFlags.accessor) {
        auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor);
        auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get());

        if ((!dpFlags.setGetter ||
             curAccessor->getter == newAccessor->getter) &&
            (!dpFlags.setSetter ||
             curAccessor->setter == newAccessor->setter)) {
          return std::make_pair(PropertyUpdateStatus::done, currentFlags);
        }
      }
    } else {
      if (!currentFlags.accessor &&
          (!dpFlags.setValue ||
           isSameValue(curValueOrAccessor, valueOrAccessor.get())) &&
          (!dpFlags.setWritable || dpFlags.writable == currentFlags.writable)) {
        return std::make_pair(PropertyUpdateStatus::done, currentFlags);
      }
    }
  }

  // 8.12.9 [7]
  // If the property is not configurable, some aspects are not changeable.
  if (!currentFlags.configurable) {
    // Trying to change non-configurable to configurable?
    if (dpFlags.configurable) {
      if (opFlags.getThrowOnError()) {
        return runtime->raiseTypeError(
            "property is not configurable"); // TODO: better message.
      }
      return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});
    }

    // Trying to change the enumerability of non-configurable property?
    if (dpFlags.setEnumerable &&
        dpFlags.enumerable != currentFlags.enumerable) {
      if (opFlags.getThrowOnError()) {
        return runtime->raiseTypeError(
            "property is not configurable"); // TODO: better message.
      }
      return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});
    }
  }

  PropertyFlags newFlags = currentFlags;

  // 8.12.9 [8] If IsGenericDescriptor(Desc) is true, then no further validation
  // is required.
  if (!(dpFlags.setValue || dpFlags.setWritable || dpFlags.setGetter ||
        dpFlags.setSetter)) {
    // Do nothing
  }
  // 8.12.9 [9]
  // Changing between accessor and data descriptor?
  else if (currentFlags.accessor != dpFlags.isAccessor()) {
    if (!currentFlags.configurable) {
      if (opFlags.getThrowOnError()) {
        return runtime->raiseTypeError(
            "property is not configurable"); // TODO: better message.
      }
      return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});
    }

    // If we change from accessor to data descriptor, Preserve the existing
    // values of the converted property’s [[Configurable]] and [[Enumerable]]
    // attributes and set the rest of the property’s attributes to their default
    // values.
    // If it's the other way around, since the accessor doesn't have the
    // [[Writable]] attribute, do nothing.
    newFlags.writable = 0;

    // If we are changing from accessor to non-accessor, we must set a new
    // value.
    if (!dpFlags.isAccessor())
      dpFlags.setValue = 1;
  }
  // 8.12.9 [10] if both are data descriptors.
  else if (!currentFlags.accessor) {
    if (!currentFlags.configurable) {
      if (!currentFlags.writable) {
        // If the current property is not writable, but the new one is.
        if (dpFlags.writable) {
          if (opFlags.getThrowOnError()) {
            return runtime->raiseTypeError(
                "property is not configurable"); // TODO: better message.
          }
          return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});
        }

        // If we are setting a different value.
        if (dpFlags.setValue &&
            !isSameValue(curValueOrAccessor, valueOrAccessor.get())) {
          if (opFlags.getThrowOnError()) {
            return runtime->raiseTypeError(
                "property is not writable"); // TODO: better message.
          }
          return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});
        }
      }
    }
  }
  // 8.12.9 [11] Both are accessors.
  else {
    auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor);
    auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get());

    // If not configurable, make sure that nothing is changing.
    if (!currentFlags.configurable) {
      if ((dpFlags.setGetter && newAccessor->getter != curAccessor->getter) ||
          (dpFlags.setSetter && newAccessor->setter != curAccessor->setter)) {
        if (opFlags.getThrowOnError()) {
          return runtime->raiseTypeError(
              "property is not configurable"); // TODO: better message.
        }
        return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});
      }
    }

    // If not setting the getter or the setter, re-use the current one.
    if (!dpFlags.setGetter)
      newAccessor->getter.set(
          runtime, curAccessor->getter, &runtime->getHeap());
    if (!dpFlags.setSetter)
      newAccessor->setter.set(
          runtime, curAccessor->setter, &runtime->getHeap());
  }

  // 8.12.9 [12] For each attribute field of Desc that is present, set the
  // correspondingly named attribute of the property named P of object O to the
  // value of the field.
  if (dpFlags.setEnumerable)
    newFlags.enumerable = dpFlags.enumerable;
  if (dpFlags.setWritable)
    newFlags.writable = dpFlags.writable;
  if (dpFlags.setConfigurable)
    newFlags.configurable = dpFlags.configurable;

  if (dpFlags.setValue)
    newFlags.accessor = false;
  else if (dpFlags.isAccessor())
    newFlags.accessor = true;
  else
    return std::make_pair(PropertyUpdateStatus::done, newFlags);

  return std::make_pair(PropertyUpdateStatus::needSet, newFlags);
}


void BrowserContextDestroyer::DestroyContext(BrowserContext* context) {
void BrowserContextDestroyer::Shutdown() {
  auto destroy_all_unused_contexts = []() {
    auto it = g_contexts_pending_deletion.Get().begin();
    while (it != g_contexts_pending_deletion.Get().end()) {
      BrowserContextDestroyer* destroyer = *it;
      ++it;

      if (!destroyer->finish_destroy_scheduled_) {
        continue;
      }

      destroyer->FinishDestroyContext();
      // |destroyer| is invalid now
     }
  };

  // We make 2 passes over the list because the first pass can destroy an
  // incognito BrowserContext that subsequently schedules its owner context for
  // deletion
  destroy_all_unused_contexts();
  destroy_all_unused_contexts();
}

//// static
void BrowserContextDestroyer::RenderProcessHostAssignedToSiteInstance(
    content::RenderProcessHost* host) {
  BrowserContextDestroyer* destroyer = GetForContext(host->GetBrowserContext());
  if (!destroyer) {
    return;
   }

  CHECK(!destroyer->finish_destroy_scheduled_);

  if (destroyer->pending_host_ids_.find(host->GetID()) !=
      destroyer->pending_host_ids_.end()) {
    return;
   }

  destroyer->ObserveHost(host);
 }


void DownloadItemImpl::OnTargetPathSelected(const FilePath& target_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_EQ(TARGET_DISPOSITION_PROMPT, target_disposition_);
  target_path_ = target_path;
}


void V8TestObject::LimitedToOnlyOtherAttributeAttributeSetterCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_limitedToOnlyOtherAttribute_Setter");

  v8::Local<v8::Value> v8_value = info[0];

  test_object_v8_internal::LimitedToOnlyOtherAttributeAttributeSetter(v8_value, info);
}


IN_PROC_BROWSER_TEST_F ( PageLoadMetricsBrowserTest , AbortMultiple ) {
 ASSERT_TRUE ( embedded_test_server ( ) -> Start ( ) ) ;
 GURL url ( embedded_test_server ( ) -> GetURL ( "/title1.html" ) ) ;
 NavigateParams params ( browser ( ) , url , ui : : PAGE_TRANSITION_LINK ) ;
 content : : TestNavigationManager manager ( browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) , url ) ;
 Navigate ( & params ) ;
 EXPECT_TRUE ( manager . WaitForRequestStart ( ) ) ;
 GURL url2 ( embedded_test_server ( ) -> GetURL ( "/title2.html" ) ) ;
 NavigateParams params2 ( browser ( ) , url2 , ui : : PAGE_TRANSITION_TYPED ) ;
 content : : TestNavigationManager manager2 ( browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) , url2 ) ;
 Navigate ( & params2 ) ;
 EXPECT_TRUE ( manager2 . WaitForRequestStart ( ) ) ;
 manager . WaitForNavigationFinished ( ) ;
 GURL url3 ( embedded_test_server ( ) -> GetURL ( "/title3.html" ) ) ;
 NavigateParams params3 ( browser ( ) , url3 , ui : : PAGE_TRANSITION_TYPED ) ;
 auto waiter = CreatePageLoadMetricsWaiter ( ) ;
 waiter -> AddPageExpectation ( TimingField : : LOAD_EVENT ) ;
 Navigate ( & params3 ) ;
 waiter -> Wait ( ) ;
 manager2 . WaitForNavigationFinished ( ) ;
 histogram_tester_ . ExpectTotalCount ( internal : : kHistogramAbortNewNavigationBeforeCommit , 2 ) ;
 }


void Document::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
    ContainerNode::reportMemoryUsage(memoryObjectInfo);
    TreeScope::reportMemoryUsage(memoryObjectInfo);
    ScriptExecutionContext::reportMemoryUsage(memoryObjectInfo);
    info.addMember(m_styleResolver, "styleResolver");
    info.addMember(m_url, "url");
    info.addMember(m_baseURL, "baseURL");
    info.addMember(m_baseURLOverride, "baseURLOverride");
    info.addMember(m_baseElementURL, "baseElementURL");
    info.addMember(m_cookieURL, "cookieURL");
    info.addMember(m_firstPartyForCookies, "firstPartyForCookies");
    info.addMember(m_documentURI, "documentURI");
    info.addMember(m_baseTarget, "baseTarget");
    info.addMember(m_docType, "docType");
    info.addMember(m_implementation, "implementation");
    info.addMember(m_elemSheet, "elemSheet");
    info.addMember(m_frame, "frame");
    info.addMember(m_cachedResourceLoader, "cachedResourceLoader");
    info.addMember(m_styleSheetCollection, "styleSheetCollection");
    info.addMember(m_styleSheetList, "styleSheetList");
    info.addMember(m_formController, "formController");
    info.addMember(m_nodeIterators, "nodeIterators");
    info.addMember(m_ranges, "ranges");
    info.addMember(m_title.string(), "title.string()");
    info.addMember(m_rawTitle.string(), "rawTitle.string()");
    info.addMember(m_xmlEncoding, "xmlEncoding");
    info.addMember(m_xmlVersion, "xmlVersion");
    info.addMember(m_contentLanguage, "contentLanguage");
#if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
    info.addMember(m_annotatedRegions, "annotatedRegions");
#endif
    info.addMember(m_cssCanvasElements, "cssCanvasElements");
    info.addMember(m_iconURLs, "iconURLs");
    info.addMember(m_documentSuspensionCallbackElements, "documentSuspensionCallbackElements");
    info.addMember(m_mediaVolumeCallbackElements, "mediaVolumeCallbackElements");
    info.addMember(m_privateBrowsingStateChangedElements, "privateBrowsingStateChangedElements");
    info.addMember(m_elementsByAccessKey, "elementsByAccessKey");
    info.addMember(m_eventQueue, "eventQueue");
    info.addMember(m_mediaCanStartListeners, "mediaCanStartListeners");
    info.addMember(m_pendingTasks, "pendingTasks");
#if ENABLE(LINK_PRERENDER)
    info.addMember(m_prerenderer, "prerenderer");
#endif
    info.addMember(m_listsInvalidatedAtDocument, "listsInvalidatedAtDocument");
    info.addMember(m_styleResolverThrowawayTimer, "styleResolverThrowawayTimer");
    info.addMember(m_domWindow, "domWindow");
    info.addMember(m_parser, "parser");
    info.addMember(m_contextFeatures, "contextFeatures");
    info.addMember(m_focusedNode, "focusedNode");
    info.addMember(m_hoverNode, "hoverNode");
    info.addMember(m_documentElement, "documentElement");
    info.addMember(m_visitedLinkState, "visitedLinkState");
    info.addMember(m_styleRecalcTimer, "styleRecalcTimer");
    info.addMember(m_titleElement, "titleElement");
    info.ignoreMember(m_renderArena);
    info.addMember(m_axObjectCache, "axObjectCache");
    info.addMember(m_markers, "markers");
    info.addMember(m_cssTarget, "cssTarget");
    info.addMember(m_updateFocusAppearanceTimer, "updateFocusAppearanceTimer");
    info.addMember(m_pendingStateObject, "pendingStateObject");
    info.addMember(m_scriptRunner, "scriptRunner");
#if ENABLE(XSLT)
    info.addMember(m_transformSource, "transformSource");
    info.addMember(m_transformSourceDocument, "transformSourceDocument");
#endif
    info.addMember(m_savedRenderer, "savedRenderer");
    info.addMember(m_decoder, "decoder");
    info.addMember(m_xpathEvaluator, "xpathEvaluator");
#if ENABLE(SVG)
    info.addMember(m_svgExtensions, "svgExtensions");
#endif
    info.addMember(m_selectorQueryCache, "selectorQueryCache");
    info.addMember(m_renderer, "renderer");
    info.addMember(m_weakFactory, "weakFactory");
    info.addMember(m_idAttributeName, "idAttributeName");
#if ENABLE(FULLSCREEN_API)
    info.addMember(m_fullScreenElement, "fullScreenElement");
    info.addMember(m_fullScreenElementStack, "fullScreenElementStack");
    info.addMember(m_fullScreenRenderer, "fullScreenRenderer");
    info.addMember(m_fullScreenChangeDelayTimer, "fullScreenChangeDelayTimer");
    info.addMember(m_fullScreenChangeEventTargetQueue, "fullScreenChangeEventTargetQueue");
    info.addMember(m_fullScreenErrorEventTargetQueue, "fullScreenErrorEventTargetQueue");
    info.addMember(m_savedPlaceholderRenderStyle, "savedPlaceholderRenderStyle");
#endif
#if ENABLE(DIALOG_ELEMENT)
    info.addMember(m_topLayerElements, "topLayerElements");
#endif
    info.addMember(m_loadEventDelayTimer, "loadEventDelayTimer");
    info.addMember(m_viewportArguments, "viewportArguments");
    info.addMember(m_documentTiming, "documentTiming");
    info.addMember(m_mediaQueryMatcher, "mediaQueryMatcher");
#if ENABLE(TOUCH_EVENTS)
    info.addMember(m_touchEventTargets, "touchEventTargets");
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME)
    info.addMember(m_scriptedAnimationController, "scriptedAnimationController");
#endif
    info.addMember(m_pendingTasksTimer, "pendingTasksTimer");
#if ENABLE(TEXT_AUTOSIZING)
    info.addMember(m_textAutosizer, "textAutosizer");
#endif
    info.addMember(m_visualUpdatesSuppressionTimer, "visualUpdatesSuppressionTimer");
    info.addMember(m_namedFlows, "namedFlows");
#if ENABLE(CSP_NEXT)
    info.addMember(m_domSecurityPolicy, "domSecurityPolicy");
#endif
    info.addMember(m_sharedObjectPoolClearTimer, "sharedObjectPoolClearTimer");
    info.addMember(m_sharedObjectPool, "sharedObjectPool");
    info.addMember(m_localeCache, "localeCache");
#if ENABLE(TEMPLATE_ELEMENT)
    info.addMember(m_templateDocument, "templateDocument");
    info.addMember(m_templateDocumentHost, "templateDocumentHost");
#endif
    info.addMember(m_activeElement, "activeElement");
}


Formattable::setDate(UDate d)
{
    dispose();
    fType = kDate;
    fValue.fDate = d;
}


IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec,
 nal_header_t *ps_nal)
{
    IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
    WORD32 value;
    WORD32 i, j;
    WORD32 sps_id;

 pps_t *ps_pps;
 sps_t *ps_sps;
 slice_header_t *ps_slice_hdr;
    WORD32 disable_deblocking_filter_flag;
 bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
    WORD32 idr_pic_flag;
    WORD32 pps_id;
    WORD32 first_slice_in_pic_flag;
    WORD32 no_output_of_prior_pics_flag = 0;

     WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type;
     WORD32 num_poc_total_curr = 0;
     WORD32 slice_address;

     if(ps_codec->i4_slice_error == 1)
         return ret;

    idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) ||
 (NAL_IDR_N_LP == i1_nal_unit_type);

    BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1);
 if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
 (NAL_RSV_RAP_VCL23          >= i1_nal_unit_type))
 {
        BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1);
 }
    UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm);
    pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2);

 /* Get the current PPS structure */
    ps_pps = ps_codec->s_parse.ps_pps_base + pps_id;
 if(0 == ps_pps->i1_pps_valid)
 {
 pps_t *ps_pps_ref = ps_codec->ps_pps_base;
 while(0 == ps_pps_ref->i1_pps_valid)
 {
            ps_pps_ref++;
 if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1))
 return IHEVCD_INVALID_HEADER;
 }

        ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id);
 }

 /* Get SPS id for the current PPS */
    sps_id = ps_pps->i1_sps_id;

 /* Get the current SPS structure */
    ps_sps = ps_codec->s_parse.ps_sps_base + sps_id;

 /* When the current slice is the first in a pic,
     *  check whether the previous frame is complete
     *  If the previous frame is incomplete -
     *  treat the remaining CTBs as skip */
 if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) &&
                    first_slice_in_pic_flag)
 {
 if(ps_codec->i4_pic_present)
 {
 slice_header_t *ps_slice_hdr_next;
            ps_codec->i4_slice_error = 1;
            ps_codec->s_parse.i4_cur_slice_idx--;
 if(ps_codec->s_parse.i4_cur_slice_idx < 0)
                ps_codec->s_parse.i4_cur_slice_idx = 0;

            ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
            ps_slice_hdr_next->i2_ctb_x = 0;
            ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
 return ret;
 }
 else
 {
            ps_codec->i4_slice_error = 0;
 }
 }

 if(first_slice_in_pic_flag)
 {
        ps_codec->s_parse.i4_cur_slice_idx = 0;
 }
 else
 {
 /* If the current slice is not the first slice in the pic,
         * but the first one to be parsed, set the current slice indx to 1
         * Treat the first slice to be missing and copy the current slice header
         * to the first one */
 if(0 == ps_codec->i4_pic_present)
            ps_codec->s_parse.i4_cur_slice_idx = 1;
 }

    ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));

 if((ps_pps->i1_dependent_slice_enabled_flag) &&
 (!first_slice_in_pic_flag))
 {
        BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1);

 /* If dependendent slice, copy slice header from previous slice */
 if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0))
 {
            ihevcd_copy_slice_hdr(ps_codec,
 (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)),
 ((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1)));
 }
        ps_slice_hdr->i1_dependent_slice_flag = value;
 }
 else
 {
        ps_slice_hdr->i1_dependent_slice_flag = 0;
 }
    ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type;
    ps_slice_hdr->i1_pps_id = pps_id;
    ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag;

    ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1;
 if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
 (NAL_RSV_RAP_VCL23          >= i1_nal_unit_type))
 {
        ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
 }
    ps_slice_hdr->i1_pps_id = pps_id;

 if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
 {
        WORD32 num_bits;

 /* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */
        num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1);
        BITS_PARSE("slice_address", value, ps_bitstrm, num_bits);

        slice_address = value;
 /* If slice address is greater than the number of CTBs in a picture,
         * ignore the slice */
 if(value >= ps_sps->i4_pic_size_in_ctb)
 return IHEVCD_IGNORE_SLICE;
 }
 else
 {
        slice_address = 0;
 }

 if(!ps_slice_hdr->i1_dependent_slice_flag)
 {
        ps_slice_hdr->i1_pic_output_flag = 1;
        ps_slice_hdr->i4_pic_order_cnt_lsb = 0;
        ps_slice_hdr->i1_num_long_term_sps = 0;
        ps_slice_hdr->i1_num_long_term_pics = 0;

 for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++)
 {
            BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1);
 }
        UEV_PARSE("slice_type", value, ps_bitstrm);
        ps_slice_hdr->i1_slice_type = value;

 /* If the picture is IRAP, slice type must be equal to ISLICE */
 if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) &&
 (ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23))
            ps_slice_hdr->i1_slice_type = ISLICE;

 if((ps_slice_hdr->i1_slice_type < 0) ||
 (ps_slice_hdr->i1_slice_type > 2))
 return IHEVCD_IGNORE_SLICE;

 if(ps_pps->i1_output_flag_present_flag)
 {
            BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1);
            ps_slice_hdr->i1_pic_output_flag = value;
 }
        ps_slice_hdr->i1_colour_plane_id = 0;
 if(1 == ps_sps->i1_separate_colour_plane_flag)
 {
            BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2);
            ps_slice_hdr->i1_colour_plane_id = value;
 }
        ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0;

 if(!idr_pic_flag)
 {

            WORD32 st_rps_idx;
            WORD32 num_neg_pics;
            WORD32 num_pos_pics;
            WORD8 *pi1_used;

            BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
            ps_slice_hdr->i4_pic_order_cnt_lsb = value;

            BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1);
            ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value;

 if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag)
 {
                WORD32 numbits;

                ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0;
 if(ps_sps->i1_num_short_term_ref_pic_sets > 1)
 {
                    numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1);
                    BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits);
                    ps_slice_hdr->i1_short_term_ref_pic_set_idx = value;
 }

                st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx;
                num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics;
                num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics;
                pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used;
 }
 else
 {
                ihevcd_short_term_ref_pic_set(ps_bitstrm,
 &ps_sps->as_stref_picset[0],
                                              ps_sps->i1_num_short_term_ref_pic_sets,
                                              ps_sps->i1_num_short_term_ref_pic_sets,
 &ps_slice_hdr->s_stref_picset);

                st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets;
                num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics;
                num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics;
                pi1_used = ps_slice_hdr->s_stref_picset.ai1_used;
 }

 if(ps_sps->i1_long_term_ref_pics_present_flag)
 {
 if(ps_sps->i1_num_long_term_ref_pics_sps > 0)
 {
                    UEV_PARSE("num_long_term_sps", value, ps_bitstrm);
                    ps_slice_hdr->i1_num_long_term_sps = value;

                    ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps,
 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics);
 }
                UEV_PARSE("num_long_term_pics", value, ps_bitstrm);
                ps_slice_hdr->i1_num_long_term_pics = value;
                ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics,
 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics -
                                                            ps_slice_hdr->i1_num_long_term_sps);

 for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps +
                                ps_slice_hdr->i1_num_long_term_pics); i++)
 {
 if(i < ps_slice_hdr->i1_num_long_term_sps)
 {
 /* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */
 if (ps_sps->i1_num_long_term_ref_pics_sps > 1)
 {
                            WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps - 1);
                            BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits);
 }
 else
 {
                            value = 0;
 }
                        ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->au2_lt_ref_pic_poc_lsb_sps[value];
                        ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value];

 }
 else
 {
                        BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
                        ps_slice_hdr->ai4_poc_lsb_lt[i] = value;

                        BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1);
                        ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value;

 }
                    BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1);
                    ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value;

                    ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0;
 if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i])
 {

                        UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm);
                        ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value;
 }

 if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps))
 {
                        ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1];
 }

 }
 }

 for(i = 0; i < num_neg_pics + num_pos_pics; i++)
 {
 if(pi1_used[i])
 {
                    num_poc_total_curr++;
 }
 }
 for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++)
 {
 if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i])
 {
                    num_poc_total_curr++;
 }
 }

 if(ps_sps->i1_sps_temporal_mvp_enable_flag)
 {
                BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1);
                ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value;
 }

 }
        ps_slice_hdr->i1_slice_sao_luma_flag = 0;
        ps_slice_hdr->i1_slice_sao_chroma_flag = 0;
 if(ps_sps->i1_sample_adaptive_offset_enabled_flag)
 {
            BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1);
            ps_slice_hdr->i1_slice_sao_luma_flag = value;

            BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1);
            ps_slice_hdr->i1_slice_sao_chroma_flag = value;

 }

        ps_slice_hdr->i1_max_num_merge_cand = 1;
        ps_slice_hdr->i1_cabac_init_flag = 0;

        ps_slice_hdr->i1_num_ref_idx_l0_active = 0;
        ps_slice_hdr->i1_num_ref_idx_l1_active = 0;
        ps_slice_hdr->i1_slice_cb_qp_offset = 0;
        ps_slice_hdr->i1_slice_cr_qp_offset = 0;
 if((PSLICE == ps_slice_hdr->i1_slice_type) ||
 (BSLICE == ps_slice_hdr->i1_slice_type))
 {
            BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1);
            ps_slice_hdr->i1_num_ref_idx_active_override_flag = value;

 if(ps_slice_hdr->i1_num_ref_idx_active_override_flag)
 {
                UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm);
                ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1;

 if(BSLICE == ps_slice_hdr->i1_slice_type)
 {
                    UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm);
                    ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1;
 }

 }
 else
 {
                ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active;

 if(BSLICE == ps_slice_hdr->i1_slice_type)
 {
                    ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active;
 }
 }

            ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1);
            ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1);

 if(0 == num_poc_total_curr)
 return IHEVCD_IGNORE_SLICE;
 if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1))
 {
                ihevcd_ref_pic_list_modification(ps_bitstrm,
                                                 ps_slice_hdr, num_poc_total_curr);
 }
 else
 {
                ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0;
                ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0;
 }

 if(BSLICE == ps_slice_hdr->i1_slice_type)
 {
                BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1);
                ps_slice_hdr->i1_mvd_l1_zero_flag = value;
 }

            ps_slice_hdr->i1_cabac_init_flag = 0;
 if(ps_pps->i1_cabac_init_present_flag)
 {
                BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1);
                ps_slice_hdr->i1_cabac_init_flag = value;

 }
            ps_slice_hdr->i1_collocated_from_l0_flag = 1;
            ps_slice_hdr->i1_collocated_ref_idx = 0;
 if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag)
 {
 if(BSLICE == ps_slice_hdr->i1_slice_type)
 {
                    BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1);
                    ps_slice_hdr->i1_collocated_from_l0_flag = value;
 }

 if((ps_slice_hdr->i1_collocated_from_l0_flag  && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) ||
 (!ps_slice_hdr->i1_collocated_from_l0_flag  && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1)))
 {
                    UEV_PARSE("collocated_ref_idx", value, ps_bitstrm);
                    ps_slice_hdr->i1_collocated_ref_idx = value;
 }

 }
            ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1);

 if((ps_pps->i1_weighted_pred_flag  && (PSLICE == ps_slice_hdr->i1_slice_type)) ||
 (ps_pps->i1_weighted_bipred_flag  && (BSLICE == ps_slice_hdr->i1_slice_type)))
 {
                ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr);
 }
            UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm);
            ps_slice_hdr->i1_max_num_merge_cand = 5 - value;

 }
        ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5);
        SEV_PARSE("slice_qp_delta", value, ps_bitstrm);
        ps_slice_hdr->i1_slice_qp_delta = value;

 if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag)
 {
            SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm);
            ps_slice_hdr->i1_slice_cb_qp_offset = value;

            SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm);
            ps_slice_hdr->i1_slice_cr_qp_offset = value;

 }
        ps_slice_hdr->i1_deblocking_filter_override_flag = 0;
        ps_slice_hdr->i1_slice_disable_deblocking_filter_flag  = ps_pps->i1_pic_disable_deblocking_filter_flag;
        ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2;
        ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2;

        disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;

 if(ps_pps->i1_deblocking_filter_control_present_flag)
 {

 if(ps_pps->i1_deblocking_filter_override_enabled_flag)
 {
                BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1);
                ps_slice_hdr->i1_deblocking_filter_override_flag = value;
 }

 if(ps_slice_hdr->i1_deblocking_filter_override_flag)
 {
                BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
                ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value;
                disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag;

 if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
 {
                    SEV_PARSE("beta_offset_div2", value, ps_bitstrm);
                    ps_slice_hdr->i1_beta_offset_div2 = value;

                    SEV_PARSE("tc_offset_div2", value, ps_bitstrm);
                    ps_slice_hdr->i1_tc_offset_div2 = value;

 }
 }
 }

        ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag;
 if(ps_pps->i1_loop_filter_across_slices_enabled_flag  &&
 (ps_slice_hdr->i1_slice_sao_luma_flag  ||  ps_slice_hdr->i1_slice_sao_chroma_flag  || !disable_deblocking_filter_flag))
 {
            BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
            ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value;
 }

 }

 /* Check sanity of slice */
 if((!first_slice_in_pic_flag) &&
 (ps_codec->i4_pic_present))
 {
 slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base;

 /* According to the standard, the above conditions must be satisfied - But for error resilience,
         * only the following conditions are checked */
 if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) ||
 (ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb))
 {
 return IHEVCD_IGNORE_SLICE;
 }

 }

 if(0 == ps_codec->i4_pic_present)
 {
        ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb);
 }
 else
 {
        ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt;
 }

 if(!first_slice_in_pic_flag)
 {
 /* Check if the current slice belongs to the same pic (Pic being parsed) */
 if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
 {

 /* If the Next CTB's index is less than the slice address,
             * the previous slice is incomplete.
             * Indicate slice error, and treat the remaining CTBs as skip */
 if(slice_address > ps_codec->s_parse.i4_next_ctb_indx)

             {
                 if(ps_codec->i4_pic_present)
                 {
                    slice_header_t *ps_slice_hdr_next;
                    ps_codec->i4_slice_error = 1;
                    ps_codec->s_parse.i4_cur_slice_idx--;
                    if(ps_codec->s_parse.i4_cur_slice_idx < 0)
                        ps_codec->s_parse.i4_cur_slice_idx = 0;
                    ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
                    ps_slice_hdr_next->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
                    ps_slice_hdr_next->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
                    return ret;
                 }
                 else
                 {
 return IHEVCD_IGNORE_SLICE;
 }
 }
 /* If the slice address is less than the next CTB's index,
             * extra CTBs have been decoded in the previous slice.
             * Ignore the current slice. Treat it as incomplete */
 else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx)
 {
 return IHEVCD_IGNORE_SLICE;
 }
 else
 {
                ps_codec->i4_slice_error = 0;
 }
 }

 /* The current slice does not belong to the pic that is being parsed */
 else
 {
 /* The previous pic is incomplete.
             * Treat the remaining CTBs as skip */
 if(ps_codec->i4_pic_present)
 {
 slice_header_t *ps_slice_hdr_next;
                ps_codec->i4_slice_error = 1;
                ps_codec->s_parse.i4_cur_slice_idx--;
 if(ps_codec->s_parse.i4_cur_slice_idx < 0)
                    ps_codec->s_parse.i4_cur_slice_idx = 0;

                ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
                ps_slice_hdr_next->i2_ctb_x = 0;
                ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
 return ret;
 }

 /* If the previous pic is complete,
             * return if the current slice is dependant
             * otherwise, update the parse context's POC */
 else
 {
 if(ps_slice_hdr->i1_dependent_slice_flag)
 return IHEVCD_IGNORE_SLICE;

                ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
 }
 }
 }

 /* If the slice is the first slice in the pic, update the parse context's POC */
 else
 {
 /* If the first slice is repeated, ignore the second occurrence
         * If any other slice is repeated, the CTB addr will be greater than the slice addr,
         * and hence the second occurrence is ignored */
 if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
 return IHEVCD_IGNORE_SLICE;

        ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
 }

    ps_slice_hdr->i4_num_entry_point_offsets = 0;
 if((ps_pps->i1_tiles_enabled_flag) ||
 (ps_pps->i1_entropy_coding_sync_enabled_flag))
 {
        UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm);
        ps_slice_hdr->i4_num_entry_point_offsets = value;

 {
            WORD32 max_num_entry_point_offsets;
 if((ps_pps->i1_tiles_enabled_flag) &&
 (ps_pps->i1_entropy_coding_sync_enabled_flag))
 {
                max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1);
 }
 else if(ps_pps->i1_tiles_enabled_flag)
 {
                max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows;
 }
 else
 {
                max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1);
 }

            ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets,
 0, max_num_entry_point_offsets);
 }

 if(ps_slice_hdr->i4_num_entry_point_offsets > 0)
 {
            UEV_PARSE("offset_len_minus1", value, ps_bitstrm);
            ps_slice_hdr->i1_offset_len = value + 1;

 for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++)
 {
                BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len);

 /* TODO: pu4_entry_point_offset needs to be initialized */
 }

 }
 }

 if(ps_pps->i1_slice_header_extension_present_flag)
 {
        UEV_PARSE("slice_header_extension_length", value, ps_bitstrm);
        ps_slice_hdr->i2_slice_header_extension_length = value;

 for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++)
 {
            BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8);
 }

 }

    ihevcd_bits_flush_to_byte_boundary(ps_bitstrm);

 if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max)
 return IHEVCD_INVALID_PARAMETER;

 {
 dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
        WORD32 r_idx;

 if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
 (NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
 (NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
 (NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) ||
 (NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
 (0 == ps_codec->u4_pic_cnt))
 {
 for(i = 0; i < MAX_DPB_BUFS; i++)
 {
 if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf)
 {
 pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf;
 mv_buf_t *ps_mv_buf;

 /* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */
                    ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc);
 /* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */
                    ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf;
 for(j = 0; j < ps_codec->i4_max_dpb_size; j++)
 {
 if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc)
 {
                            ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, j, BUF_MGR_REF);
 break;
 }
                        ps_mv_buf++;
 }

 }

 }

 /* Initialize the reference lists to NULL
             * This is done to take care of the cases where the first pic is not IDR
             * but the reference list is not created for the first pic because
             * pic count is zero leaving the reference list uninitialised  */
 for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++)
 {
                ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL;
                ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL;

                ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL;
                ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL;
 }

 }
 else
 {
            ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr);
 if ((WORD32)IHEVCD_SUCCESS != ret)
 {
 return ret;
 }

 }

 }

 /* Fill the remaining entries of the reference lists with the nearest POC
     * This is done to handle cases where there is a corruption in the reference index */
 if(ps_codec->i4_pic_present)
 {
 pic_buf_t *ps_pic_buf_ref;
 mv_buf_t *ps_mv_buf_ref;
        WORD32 r_idx;
 dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
 buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr;

        ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt);
 if(NULL == ps_pic_buf_ref)
 {
            ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic;
            ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf;
 }
 else
 {
            ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc);
 }

 for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++)
 {
 if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf)
 {
                ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
                ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
 }
 }

 for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++)
 {
            ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
            ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
 }

 for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++)
 {
 if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf)
 {
                ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
                ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
 }
 }

 for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++)
 {
            ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
            ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
 }
 }

 /* Update slice address in the header */
 if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
 {
        ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
        ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;

 if(!ps_slice_hdr->i1_dependent_slice_flag)
 {
            ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x;
            ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y;
 }
 }
 else
 {
        ps_slice_hdr->i2_ctb_x = 0;
        ps_slice_hdr->i2_ctb_y = 0;

        ps_slice_hdr->i2_independent_ctb_x = 0;
        ps_slice_hdr->i2_independent_ctb_y = 0;
 }

 /* If the first slice in the pic is missing, copy the current slice header to
     * the first slice's header */
 if((!first_slice_in_pic_flag) &&
 (0 == ps_codec->i4_pic_present))
 {

         slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base;
         ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)));

        ps_codec->i4_slice_error = 1;

         ps_slice_hdr_prev->i2_ctb_x = 0;
         ps_slice_hdr_prev->i2_ctb_y = 0;

        ps_codec->s_parse.i4_ctb_x = 0;
        ps_codec->s_parse.i4_ctb_y = 0;

        ps_codec->s_parse.i4_cur_slice_idx = 0;

 if((ps_slice_hdr->i2_ctb_x == 0) &&
 (ps_slice_hdr->i2_ctb_y == 0))
 {
            ps_slice_hdr->i2_ctb_x++;
 }
 }

 {
 /* If skip B is enabled,
         * ignore pictures that are non-reference
         * TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is
         * sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/

 if((i1_nal_unit_type < NAL_BLA_W_LP) &&
 (i1_nal_unit_type % 2 == 0))
 {
 if(IVD_SKIP_B == ps_codec->e_pic_skip_mode)
 return IHEVCD_IGNORE_SLICE;
 }

 /* If skip PB is enabled,
         * decode only I slices */
 if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) &&
 (ISLICE != ps_slice_hdr->i1_slice_type))
 {
 return IHEVCD_IGNORE_SLICE;

         }
     }

     return ret;
 }


static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy,
				  struct cfg80211_wowlan *wowl)
{
	struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
	struct net_device *ndev = cfg_to_ndev(cfg);
	struct brcmf_if *ifp = netdev_priv(ndev);
	struct brcmf_cfg80211_vif *vif;

	brcmf_dbg(TRACE, "Enter\n");

	/* if the primary net_device is not READY there is nothing
	 * we can do but pray resume goes smoothly.
	 */
	if (!check_vif_up(ifp->vif))
		goto exit;

	/* Stop scheduled scan */
	if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO))
		brcmf_cfg80211_sched_scan_stop(wiphy, ndev);

	/* end any scanning */
	if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
		brcmf_abort_scanning(cfg);

	if (wowl == NULL) {
		brcmf_bus_wowl_config(cfg->pub->bus_if, false);
		list_for_each_entry(vif, &cfg->vif_list, list) {
			if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state))
				continue;
			/* While going to suspend if associated with AP
			 * disassociate from AP to save power while system is
			 * in suspended state
			 */
			brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED);
			/* Make sure WPA_Supplicant receives all the event
			 * generated due to DISASSOC call to the fw to keep
			 * the state fw and WPA_Supplicant state consistent
			 */
			brcmf_delay(500);
		}
		/* Configure MPC */
		brcmf_set_mpc(ifp, 1);

	} else {
		/* Configure WOWL paramaters */
		brcmf_configure_wowl(cfg, ifp, wowl);
	}

exit:
	brcmf_dbg(TRACE, "Exit\n");
	/* clear any scanning activity */
	cfg->scan_status = 0;
	return 0;
}


static void _uhash_rehash ( UHashtable * hash , UErrorCode * status ) {
 UHashElement * old = hash -> elements ;
 int32_t oldLength = hash -> length ;
 int32_t newPrimeIndex = hash -> primeIndex ;
 int32_t i ;
 if ( hash -> count > hash -> highWaterMark ) {
 if ( ++ newPrimeIndex >= PRIMES_LENGTH ) {
 return ;
 }
 }
 else if ( hash -> count < hash -> lowWaterMark ) {
 if ( -- newPrimeIndex < 0 ) {
 return ;
 }
 }
 else {
 return ;
 }
 _uhash_allocate ( hash , newPrimeIndex , status ) ;
 if ( U_FAILURE ( * status ) ) {
 hash -> elements = old ;
 hash -> length = oldLength ;
 return ;
 }
 for ( i = oldLength - 1 ;
 i >= 0 ;
 -- i ) {
 if ( ! IS_EMPTY_OR_DELETED ( old [ i ] . hashcode ) ) {
 UHashElement * e = _uhash_find ( hash , old [ i ] . key , old [ i ] . hashcode ) ;
 U_ASSERT ( e != NULL ) ;
 U_ASSERT ( e -> hashcode == HASH_EMPTY ) ;
 e -> key = old [ i ] . key ;
 e -> value = old [ i ] . value ;
 e -> hashcode = old [ i ] . hashcode ;
 ++ hash -> count ;
 }
 }
 uprv_free ( old ) ;
 }


  bool peekMap() {
    T_VIRTUAL_CALL();
    return peekMap_virt();
  }


error::Error GLES2DecoderImpl::HandleEndQueryEXT(
    uint32_t immediate_data_size,
    const volatile void* cmd_data) {
  const volatile gles2::cmds::EndQueryEXT& c =
      *static_cast<const volatile gles2::cmds::EndQueryEXT*>(cmd_data);
  GLenum target = static_cast<GLenum>(c.target);
  uint32_t submit_count = static_cast<GLuint>(c.submit_count);

  QueryManager::Query* query = query_manager_->GetActiveQuery(target);
  if (!query) {
    LOCAL_SET_GL_ERROR(
        GL_INVALID_OPERATION, "glEndQueryEXT", "No active query");
    return error::kNoError;
  }

  if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM &&
      !writes_submitted_but_not_completed_.empty()) {
    query->AddCallback(
        base::BindOnce(&GLES2DecoderImpl::ReadBackBuffersIntoShadowCopies,
                       base::Unretained(this),
                       std::move(writes_submitted_but_not_completed_)));
    writes_submitted_but_not_completed_.clear();
  }

  query_manager_->EndQuery(query, submit_count);
  return error::kNoError;
}


static bool op_attr_value_from_binary(void *attr, const void *data,
				      size_t data_len, size_t *offs)
{
	uint32_t *v = attr;

	return op_u32_from_binary_helper(v, data, data_len, offs);
}


TEST_F ( ProtocolHandlerRegistryTest , TestNotifications ) {
 ProtocolHandler ph1 = CreateProtocolHandler ( "test" , "test1" ) ;
 NotificationCounter counter ( profile ( ) ) ;
 registry ( ) -> OnAcceptRegisterProtocolHandler ( ph1 ) ;
 ASSERT_TRUE ( counter . notified ( ) ) ;
 counter . Clear ( ) ;
 registry ( ) -> Disable ( ) ;
 ASSERT_TRUE ( counter . notified ( ) ) ;
 counter . Clear ( ) ;
 registry ( ) -> Enable ( ) ;
 ASSERT_TRUE ( counter . notified ( ) ) ;
 counter . Clear ( ) ;
 registry ( ) -> RemoveHandler ( ph1 ) ;
 ASSERT_TRUE ( counter . notified ( ) ) ;
 counter . Clear ( ) ;
 }


static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename )
{
	fileInPack_t	*buildBuffer;
	pack_t			*pack;
	unzFile			uf;
	int				err;
	unz_global_info gi;
	char			filename_inzip[MAX_ZPATH];
	unz_file_info	file_info;
	int				len;
	size_t			i;
	long			hash;
	int				fs_numHeaderLongs;
	int				*fs_headerLongs;
	char			*namePtr;

	fs_numHeaderLongs = 0;

	uf = unzOpen(zipfile);
	err = unzGetGlobalInfo (uf,&gi);

	if (err != UNZ_OK)
		return NULL;

	len = 0;
	unzGoToFirstFile(uf);
	for (i = 0; i < gi.number_entry; i++)
	{
		err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
		if (err != UNZ_OK) {
			break;
		}
		len += strlen(filename_inzip) + 1;
		unzGoToNextFile(uf);
	}

	buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue );
	namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
	fs_headerLongs = (int *)Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int), TAG_FILESYS, qtrue );
	fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );

	// get the hash table size from the number of files in the zip
	// because lots of custom pk3 files have less than 32 or 64 files
	for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
		if (i > gi.number_entry) {
			break;
		}
	}

	pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue );
	pack->hashSize = i;
	pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
	for(int j = 0; j < pack->hashSize; j++) {
		pack->hashTable[j] = NULL;
	}

	Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
	Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );

	// strip .pk3 if needed
	if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
		pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
	}

	pack->handle = uf;
	pack->numfiles = gi.number_entry;
	unzGoToFirstFile(uf);

	for (i = 0; i < gi.number_entry; i++)
	{
		err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
		if (err != UNZ_OK) {
			break;
		}
		if (file_info.uncompressed_size > 0) {
			fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
		}
		Q_strlwr( filename_inzip );
		hash = FS_HashFileName(filename_inzip, pack->hashSize);
		buildBuffer[i].name = namePtr;
		strcpy( buildBuffer[i].name, filename_inzip );
		namePtr += strlen(filename_inzip) + 1;
		// store the file position in the zip
		buildBuffer[i].pos = unzGetOffset(uf);
		buildBuffer[i].len = file_info.uncompressed_size;
		buildBuffer[i].next = pack->hashTable[hash];
		pack->hashTable[hash] = &buildBuffer[i];
		unzGoToNextFile(uf);
	}

	pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
	pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
	pack->checksum = LittleLong( pack->checksum );
	pack->pure_checksum = LittleLong( pack->pure_checksum );

	Z_Free(fs_headerLongs);

	pack->buildBuffer = buildBuffer;
	return pack;
}


static void restore_query_logs()
{
  int rc;
  rc= mysql_query(mysql, "set @@global.general_log=@save_global_general_log");
  myquery(rc);

  rc= mysql_query(mysql, "set @@global.slow_query_log=@save_global_slow_query_log");
  myquery(rc);
}


GF_Err video_sample_entry_Read(GF_Box *s, GF_BitStream *bs)
{
	GF_MPEGVisualSampleEntryBox *mp4v = (GF_MPEGVisualSampleEntryBox*)s;
	GF_Err e;
	e = gf_isom_video_sample_entry_read((GF_VisualSampleEntryBox *)s, bs);
	if (e) return e;
	e = gf_isom_box_array_read(s, bs, video_sample_entry_AddBox);
	if (e) return e;
	/*this is an AVC sample desc*/
	if (mp4v->avc_config || mp4v->svc_config || mp4v->mvc_config) AVC_RewriteESDescriptor(mp4v);
	/*this is an HEVC sample desc*/
	if (mp4v->hevc_config || mp4v->lhvc_config || (mp4v->type==GF_ISOM_BOX_TYPE_HVT1))
		HEVC_RewriteESDescriptor(mp4v);
	return GF_OK;
}


void perf_event_enable(struct perf_event *event)
{
	struct perf_event_context *ctx;

	ctx = perf_event_ctx_lock(event);
	_perf_event_enable(event);
	perf_event_ctx_unlock(event, ctx);
}


static int __perf_event_enable(void *info)
{
	struct perf_event *event = info;
	struct perf_event_context *ctx = event->ctx;
	struct perf_event *leader = event->group_leader;
	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
	int err;

	/*
	 * There's a time window between 'ctx->is_active' check
	 * in perf_event_enable function and this place having:
	 *   - IRQs on
	 *   - ctx->lock unlocked
	 *
	 * where the task could be killed and 'ctx' deactivated
	 * by perf_event_exit_task.
	 */
	if (!ctx->is_active)
		return -EINVAL;

	raw_spin_lock(&ctx->lock);
	update_context_time(ctx);

	if (event->state >= PERF_EVENT_STATE_INACTIVE)
		goto unlock;

	/*
	 * set current task's cgroup time reference point
	 */
	perf_cgroup_set_timestamp(current, ctx);

	__perf_event_mark_enabled(event);

	if (!event_filter_match(event)) {
		if (is_cgroup_event(event))
			perf_cgroup_defer_enabled(event);
		goto unlock;
	}

	/*
	 * If the event is in a group and isn't the group leader,
	 * then don't put it on unless the group is on.
	 */
	if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
		goto unlock;

	if (!group_can_go_on(event, cpuctx, 1)) {
		err = -EEXIST;
	} else {
		if (event == leader)
			err = group_sched_in(event, cpuctx, ctx);
		else
			err = event_sched_in(event, cpuctx, ctx);
	}

	if (err) {
		/*
		 * If this event can't go on and it's part of a
		 * group, then the whole group has to come off.
		 */
		if (leader != event) {
			group_sched_out(leader, cpuctx, ctx);
			perf_cpu_hrtimer_restart(cpuctx);
		}
		if (leader->attr.pinned) {
			update_group_times(leader);
			leader->state = PERF_EVENT_STATE_ERROR;
		}
	}

unlock:
	raw_spin_unlock(&ctx->lock);

	return 0;
}


static int cx24116_writereg(struct cx24116_state *state, int reg, int data)
{
	u8 buf[] = { reg, data };
	struct i2c_msg msg = { .addr = state->config->demod_address,
		.flags = 0, .buf = buf, .len = 2 };
	int err;

	if (debug > 1)
		printk("cx24116: %s: write reg 0x%02x, value 0x%02x\n",
			__func__, reg, data);

	err = i2c_transfer(state->i2c, &msg, 1);
	if (err != 1) {
		printk(KERN_ERR "%s: writereg error(err == %i, reg == 0x%02x,"
			 " value == 0x%02x)\n", __func__, err, reg, data);
		return -EREMOTEIO;
	}

	return 0;
}


static bool tlist_matches_coltypelist ( List * tlist , List * coltypelist ) {
 ListCell * tlistitem ;
 ListCell * clistitem ;
 clistitem = list_head ( coltypelist ) ;
 foreach ( tlistitem , tlist ) {
 TargetEntry * tle = ( TargetEntry * ) lfirst ( tlistitem ) ;
 Oid coltype ;
 if ( tle -> resjunk ) continue ;
 if ( clistitem == NULL ) return false ;
 coltype = lfirst_oid ( clistitem ) ;
 clistitem = lnext ( clistitem ) ;
 if ( exprType ( ( Node * ) tle -> expr ) != coltype ) return false ;
 }
 if ( clistitem != NULL ) return false ;
 return true ;
 }


static void asymmetric_key_destroy(struct key *key)
{
	struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
	if (subtype) {
		subtype->destroy(key->payload.data);
		module_put(subtype->owner);
		key->type_data.p[0] = NULL;
	}
	kfree(key->type_data.p[1]);
	key->type_data.p[1] = NULL;
}


bool IsSensitiveURL(const GURL& url,
                    bool is_request_from_browser_or_webui_renderer) {
  bool sensitive_chrome_url = false;
  const char kGoogleCom[] = "google.com";
  const char kClient[] = "clients";
  url::Origin origin = url::Origin::Create(url);
  if (origin.DomainIs(kGoogleCom)) {
    base::StringPiece host = url.host_piece();
    while (host.ends_with("."))
      host.remove_suffix(1u);
    if (is_request_from_browser_or_webui_renderer) {
      base::StringPiece::size_type pos = host.rfind(kClient);
      if (pos != base::StringPiece::npos) {
        bool match = true;
        if (pos > 0 && host[pos - 1] != '.') {
          match = false;
        } else {
          for (base::StringPiece::const_iterator
                   i = host.begin() + pos + strlen(kClient),
                   end = host.end() - (strlen(kGoogleCom) + 1);
               i != end; ++i) {
            if (!isdigit(*i)) {
              match = false;
              break;
            }
          }
        }
        sensitive_chrome_url = sensitive_chrome_url || match;
      }
    }

    sensitive_chrome_url = sensitive_chrome_url ||
                           (url.DomainIs("chrome.google.com") &&
                             base::StartsWith(url.path_piece(), "/webstore",
                                              base::CompareCase::SENSITIVE));
   }
   return sensitive_chrome_url || extension_urls::IsWebstoreUpdateUrl(url) ||
          extension_urls::IsBlacklistUpdateUrl(url) ||
          extension_urls::IsSafeBrowsingUrl(origin, url.path_piece());
}


PHP_FUNCTION(dns_check_record)
{
#ifndef MAXPACKET
#define MAXPACKET  8192 /* max packet size used internally by BIND */
#endif
	u_char ans[MAXPACKET];
	char *hostname, *rectype = NULL;
	int hostname_len, rectype_len = 0;
	int type = T_MX, i;
#if defined(HAVE_DNS_SEARCH)
	struct sockaddr_storage from;
	uint32_t fromsize = sizeof(from);
	dns_handle_t handle;
#elif defined(HAVE_RES_NSEARCH)
	struct __res_state state;
	struct __res_state *handle = &state;
#endif

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) {
		return;
	}

	if (hostname_len == 0) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Host cannot be empty");
		RETURN_FALSE;
	}

	if (rectype) {
		if (!strcasecmp("A",     rectype)) type = T_A;
		else if (!strcasecmp("NS",    rectype)) type = DNS_T_NS;
		else if (!strcasecmp("MX",    rectype)) type = DNS_T_MX;
		else if (!strcasecmp("PTR",   rectype)) type = DNS_T_PTR;
		else if (!strcasecmp("ANY",   rectype)) type = DNS_T_ANY;
		else if (!strcasecmp("SOA",   rectype)) type = DNS_T_SOA;
		else if (!strcasecmp("TXT",   rectype)) type = DNS_T_TXT;
		else if (!strcasecmp("CNAME", rectype)) type = DNS_T_CNAME;
		else if (!strcasecmp("AAAA",  rectype)) type = DNS_T_AAAA;
		else if (!strcasecmp("SRV",   rectype)) type = DNS_T_SRV;
		else if (!strcasecmp("NAPTR", rectype)) type = DNS_T_NAPTR;
		else if (!strcasecmp("A6",    rectype)) type = DNS_T_A6;
		else {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%s' not supported", rectype);
			RETURN_FALSE;
		}
	}

#if defined(HAVE_DNS_SEARCH)
	handle = dns_open(NULL);
	if (handle == NULL) {
		RETURN_FALSE;
	}
#elif defined(HAVE_RES_NSEARCH)
    memset(&state, 0, sizeof(state));
    if (res_ninit(handle)) {
			RETURN_FALSE;
	}
#else
	res_init();
#endif

	RETVAL_TRUE;
	i = php_dns_search(handle, hostname, C_IN, type, ans, sizeof(ans));

	if (i < 0) {
		RETVAL_FALSE;
	}

	php_dns_free_handle(handle);
}


static int handle_primary_tcp_pkt(NetFilterState *nf,

                                  Connection *conn,

                                  Packet *pkt)

{

    struct tcphdr *tcp_pkt;

    tcp_pkt = (struct tcphdr *)pkt->transport_header;

    if (trace_event_get_state(TRACE_COLO_FILTER_REWRITER_DEBUG)) {

        trace_colo_filter_rewriter_pkt_info(__func__,

                    inet_ntoa(pkt->ip->ip_src), inet_ntoa(pkt->ip->ip_dst),

                    ntohl(tcp_pkt->th_seq), ntohl(tcp_pkt->th_ack),

                    tcp_pkt->th_flags);

        trace_colo_filter_rewriter_conn_offset(conn->offset);

    }

    if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_SYN)) {

        /*

         * we use this flag update offset func

         * run once in independent tcp connection

         */

        conn->syn_flag = 1;

    }

    if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_ACK)) {

        if (conn->syn_flag) {

            /*

             * offset = secondary_seq - primary seq

             * ack packet sent by guest from primary node,

             * so we use th_ack - 1 get primary_seq

             */

            conn->offset -= (ntohl(tcp_pkt->th_ack) - 1);

            conn->syn_flag = 0;

        }

        /* handle packets to the secondary from the primary */

        tcp_pkt->th_ack = htonl(ntohl(tcp_pkt->th_ack) + conn->offset);

        net_checksum_calculate((uint8_t *)pkt->data, pkt->size);

    }

    return 0;

}


flatpak_context_free (FlatpakContext *context)
{
  g_hash_table_destroy (context->env_vars);
  g_hash_table_destroy (context->persistent);
  g_hash_table_destroy (context->filesystems);
  g_hash_table_destroy (context->session_bus_policy);
  g_hash_table_destroy (context->system_bus_policy);
  g_hash_table_destroy (context->generic_policy);
  g_slice_free (FlatpakContext, context);
}


mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
{
	switch(reset_phase) {
	case MPT_IOC_SETUP_RESET:
		dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
		    "%s: MPT_IOC_SETUP_RESET\n", ioc->name, __func__));
		break;
	case MPT_IOC_PRE_RESET:
		dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
		    "%s: MPT_IOC_PRE_RESET\n", ioc->name, __func__));
		break;
	case MPT_IOC_POST_RESET:
		dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
		    "%s: MPT_IOC_POST_RESET\n", ioc->name, __func__));
		if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_PENDING) {
			ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_DID_IOCRESET;
			complete(&ioc->ioctl_cmds.done);
		}
		break;
	default:
		break;
	}

	return 1;
}


static int rtentry_to_fib_config(struct net *net, int cmd, struct rtentry *rt,
				 struct fib_config *cfg)
{
	__be32 addr;
	int plen;

	memset(cfg, 0, sizeof(*cfg));
	cfg->fc_nlinfo.nl_net = net;

	if (rt->rt_dst.sa_family != AF_INET)
		return -EAFNOSUPPORT;

	/*
	 * Check mask for validity:
	 * a) it must be contiguous.
	 * b) destination must have all host bits clear.
	 * c) if application forgot to set correct family (AF_INET),
	 *    reject request unless it is absolutely clear i.e.
	 *    both family and mask are zero.
	 */
	plen = 32;
	addr = sk_extract_addr(&rt->rt_dst);
	if (!(rt->rt_flags & RTF_HOST)) {
		__be32 mask = sk_extract_addr(&rt->rt_genmask);

		if (rt->rt_genmask.sa_family != AF_INET) {
			if (mask || rt->rt_genmask.sa_family)
				return -EAFNOSUPPORT;
		}

		if (bad_mask(mask, addr))
			return -EINVAL;

		plen = inet_mask_len(mask);
	}

	cfg->fc_dst_len = plen;
	cfg->fc_dst = addr;

	if (cmd != SIOCDELRT) {
		cfg->fc_nlflags = NLM_F_CREATE;
		cfg->fc_protocol = RTPROT_BOOT;
	}

	if (rt->rt_metric)
		cfg->fc_priority = rt->rt_metric - 1;

	if (rt->rt_flags & RTF_REJECT) {
		cfg->fc_scope = RT_SCOPE_HOST;
		cfg->fc_type = RTN_UNREACHABLE;
		return 0;
	}

	cfg->fc_scope = RT_SCOPE_NOWHERE;
	cfg->fc_type = RTN_UNICAST;

	if (rt->rt_dev) {
		char *colon;
		struct net_device *dev;
		char devname[IFNAMSIZ];

		if (copy_from_user(devname, rt->rt_dev, IFNAMSIZ-1))
			return -EFAULT;

		devname[IFNAMSIZ-1] = 0;
		colon = strchr(devname, ':');
		if (colon)
			*colon = 0;
		dev = __dev_get_by_name(net, devname);
		if (!dev)
			return -ENODEV;
		cfg->fc_oif = dev->ifindex;
		if (colon) {
			struct in_ifaddr *ifa;
			struct in_device *in_dev = __in_dev_get_rtnl(dev);
			if (!in_dev)
				return -ENODEV;
			*colon = ':';
			for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next)
				if (strcmp(ifa->ifa_label, devname) == 0)
					break;
			if (!ifa)
				return -ENODEV;
			cfg->fc_prefsrc = ifa->ifa_local;
		}
	}

	addr = sk_extract_addr(&rt->rt_gateway);
	if (rt->rt_gateway.sa_family == AF_INET && addr) {
		unsigned int addr_type;

		cfg->fc_gw = addr;
		addr_type = inet_addr_type_table(net, addr, cfg->fc_table);
		if (rt->rt_flags & RTF_GATEWAY &&
		    addr_type == RTN_UNICAST)
			cfg->fc_scope = RT_SCOPE_UNIVERSE;
	}

	if (cmd == SIOCDELRT)
		return 0;

	if (rt->rt_flags & RTF_GATEWAY && !cfg->fc_gw)
		return -EINVAL;

	if (cfg->fc_scope == RT_SCOPE_NOWHERE)
		cfg->fc_scope = RT_SCOPE_LINK;

	if (rt->rt_flags & (RTF_MTU | RTF_WINDOW | RTF_IRTT)) {
		struct nlattr *mx;
		int len = 0;

		mx = kzalloc(3 * nla_total_size(4), GFP_KERNEL);
		if (!mx)
			return -ENOMEM;

		if (rt->rt_flags & RTF_MTU)
			len = put_rtax(mx, len, RTAX_ADVMSS, rt->rt_mtu - 40);

		if (rt->rt_flags & RTF_WINDOW)
			len = put_rtax(mx, len, RTAX_WINDOW, rt->rt_window);

		if (rt->rt_flags & RTF_IRTT)
			len = put_rtax(mx, len, RTAX_RTT, rt->rt_irtt << 3);

		cfg->fc_mx = mx;
		cfg->fc_mx_len = len;
	}

	return 0;
}


int64 MockRenderThread::GetIdleNotificationDelayInMs() const {
  return 0;
}


TEST_CASE("Invalid escape sequence test", "[general]")
{
    parser parser(R"(
        ROOT <- _
        _ <- '\'
    )");

    bool ret = parser;
    REQUIRE(ret == false);
}


bool AudioContext::tryLock()
{
    ASSERT(isAudioThread());
    if (!isAudioThread()) {
        lock();
        return true;
    }
    return m_contextGraphMutex.tryLock();
}


krb5_gss_inquire_mech_for_saslname(OM_uint32 *minor_status,
                                   const gss_buffer_t sasl_mech_name,
                                   gss_OID *mech_type)
{
    *minor_status = 0;

    if (sasl_mech_name->length == GS2_KRB5_SASL_NAME_LEN &&
        memcmp(sasl_mech_name->value,
               GS2_KRB5_SASL_NAME, GS2_KRB5_SASL_NAME_LEN) == 0) {
        if (mech_type != NULL)
            *mech_type = (gss_OID)gss_mech_krb5;
        return GSS_S_COMPLETE;
    } else if (sasl_mech_name->length == GS2_IAKERB_SASL_NAME_LEN &&
               memcmp(sasl_mech_name->value,
                      GS2_IAKERB_SASL_NAME, GS2_IAKERB_SASL_NAME_LEN) == 0) {
        if (mech_type != NULL)
            *mech_type = (gss_OID)gss_mech_iakerb;
        return GSS_S_COMPLETE;
    }

    return GSS_S_BAD_MECH;
}


static bool DecompressRle(unsigned char *dst,
                          const unsigned long uncompressed_size,
                          const unsigned char *src, unsigned long src_size) {
  if (uncompressed_size == src_size) {
    // Data is not compressed(Issue 40).
    memcpy(dst, src, src_size);
    return true;
  }

  // Workaround for issue #112.
  // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`.
  if (src_size <= 2) {
    return false;
  }

  std::vector<unsigned char> tmpBuf(uncompressed_size);

  int ret = rleUncompress(static_cast<int>(src_size),
                          static_cast<int>(uncompressed_size),
                          reinterpret_cast<const signed char *>(src),
                          reinterpret_cast<char *>(&tmpBuf.at(0)));
  if (ret != static_cast<int>(uncompressed_size)) {
    return false;
  }

  //
  // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  // ImfRleCompressor.cpp
  //

  // Predictor.
  {
    unsigned char *t = &tmpBuf.at(0) + 1;
    unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;

    while (t < stop) {
      int d = int(t[-1]) + int(t[0]) - 128;
      t[0] = static_cast<unsigned char>(d);
      ++t;
    }
  }

  // Reorder the pixel data.
  {
    const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
    const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
                     (uncompressed_size + 1) / 2;
    char *s = reinterpret_cast<char *>(dst);
    char *stop = s + uncompressed_size;

    for (;;) {
      if (s < stop)
        *(s++) = *(t1++);
      else
        break;

      if (s < stop)
        *(s++) = *(t2++);
      else
        break;
    }
  }

  return true;
}


void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
   if (state_ == WORKER_READY) {
     if (sessions().size() == 1) {
       BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                              base::BindOnce(&SetDevToolsAttachedOnIO,
                                             context_weak_, version_id_, true));
    }
    session->SetRenderer(worker_process_id_, nullptr);
    session->AttachToAgent(agent_ptr_);
  }
   session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
   session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
   session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
 }


void LayoutBlockFlow::deleteLineBoxTree()
{
    if (containsFloats())
        m_floatingObjects->clearLineBoxTreePointers();

    m_lineBoxes.deleteLineBoxTree();
}


mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
{
	int i, lastp;
	MonoClass *klass = method->klass;
	MonoTableInfo *methodt;
	MonoTableInfo *paramt;
	MonoMethodSignature *signature;
	guint32 idx;

	signature = mono_method_signature (method);
	g_assert (signature); /*FIXME there is no way to signal error from this function*/

	for (i = 0; i < signature->param_count + 1; ++i)
		mspecs [i] = NULL;

	if (method->klass->image->dynamic) {
		MonoReflectionMethodAux *method_aux =
			g_hash_table_lookup (
				((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
		if (method_aux && method_aux->param_marshall) {
			MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
			for (i = 0; i < signature->param_count + 1; ++i)
				if (dyn_specs [i]) {
					mspecs [i] = g_new0 (MonoMarshalSpec, 1);
					memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
					mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
					mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
				}
		}
		return;
	}

	mono_class_init (klass);

	methodt = &klass->image->tables [MONO_TABLE_METHOD];
	paramt = &klass->image->tables [MONO_TABLE_PARAM];
	idx = mono_method_get_index (method);
	if (idx > 0) {
		guint32 cols [MONO_PARAM_SIZE];
		guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);

		if (idx < methodt->rows)
			lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
		else
			lastp = paramt->rows + 1;

		for (i = param_index; i < lastp; ++i) {
			mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);

			if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
				const char *tp;
				tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
				g_assert (tp);
				mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
			}
		}

		return;
	}
}


ofpact_put(struct ofpbuf *ofpacts, enum ofpact_type type, size_t len)
{
    struct ofpact *ofpact;

    ofpacts->header = ofpbuf_put_uninit(ofpacts, len);
    ofpact = ofpacts->header;
    ofpact_init(ofpact, type, len);
    return ofpact;
}


static int ext4_end_io_nolock(ext4_io_end_t *io)
{
	struct inode *inode = io->inode;
	loff_t offset = io->offset;
	ssize_t size = io->size;
	int ret = 0;

	ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p,"
		   "list->prev 0x%p\n",
	           io, inode->i_ino, io->list.next, io->list.prev);

	if (list_empty(&io->list))
		return ret;

	if (io->flag != EXT4_IO_UNWRITTEN)
		return ret;

	ret = ext4_convert_unwritten_extents(inode, offset, size);
	if (ret < 0) {
		printk(KERN_EMERG "%s: failed to convert unwritten"
			"extents to written extents, error is %d"
			" io is still on inode %lu aio dio list\n",
                       __func__, ret, inode->i_ino);
		return ret;
	}

	/* clear the DIO AIO unwritten flag */
	io->flag = 0;
	return ret;
}


int security_get_user_sids(u32 fromsid,
			   char *username,
			   u32 **sids,
			   u32 *nel)
{
	struct context *fromcon, usercon;
	u32 *mysids = NULL, *mysids2, sid;
	u32 mynel = 0, maxnel = SIDS_NEL;
	struct user_datum *user;
	struct role_datum *role;
	struct ebitmap_node *rnode, *tnode;
	int rc = 0, i, j;

	*sids = NULL;
	*nel = 0;

	if (!ss_initialized)
		goto out;

	read_lock(&policy_rwlock);

	context_init(&usercon);

	rc = -EINVAL;
	fromcon = sidtab_search(&sidtab, fromsid);
	if (!fromcon)
		goto out_unlock;

	rc = -EINVAL;
	user = hashtab_search(policydb.p_users.table, username);
	if (!user)
		goto out_unlock;

	usercon.user = user->value;

	rc = -ENOMEM;
	mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
	if (!mysids)
		goto out_unlock;

	ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
		role = policydb.role_val_to_struct[i];
		usercon.role = i + 1;
		ebitmap_for_each_positive_bit(&role->types, tnode, j) {
			usercon.type = j + 1;

			if (mls_setup_user_range(fromcon, user, &usercon))
				continue;

			rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
			if (rc)
				goto out_unlock;
			if (mynel < maxnel) {
				mysids[mynel++] = sid;
			} else {
				rc = -ENOMEM;
				maxnel += SIDS_NEL;
				mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
				if (!mysids2)
					goto out_unlock;
				memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
				kfree(mysids);
				mysids = mysids2;
				mysids[mynel++] = sid;
			}
		}
	}
	rc = 0;
out_unlock:
	read_unlock(&policy_rwlock);
	if (rc || !mynel) {
		kfree(mysids);
		goto out;
	}

	rc = -ENOMEM;
	mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
	if (!mysids2) {
		kfree(mysids);
		goto out;
	}
	for (i = 0, j = 0; i < mynel; i++) {
		struct av_decision dummy_avd;
		rc = avc_has_perm_noaudit(fromsid, mysids[i],
					  SECCLASS_PROCESS, /* kernel value */
					  PROCESS__TRANSITION, AVC_STRICT,
					  &dummy_avd);
		if (!rc)
			mysids2[j++] = mysids[i];
		cond_resched();
	}
	rc = 0;
	kfree(mysids);
	*sids = mysids2;
	*nel = j;
out:
	return rc;
}


void OSD::_add_heartbeat_peer(int p)
{
  if (p == whoami)
    return;
  HeartbeatInfo *hi;

  map<int,HeartbeatInfo>::iterator i = heartbeat_peers.find(p);
  if (i == heartbeat_peers.end()) {
    pair<ConnectionRef,ConnectionRef> cons = service.get_con_osd_hb(p, osdmap->get_epoch());
    if (!cons.first)
      return;
    hi = &heartbeat_peers[p];
    hi->peer = p;
    HeartbeatSession *s = new HeartbeatSession(p);
    hi->con_back = cons.first.get();
    hi->con_back->set_priv(s->get());
    if (cons.second) {
      hi->con_front = cons.second.get();
      hi->con_front->set_priv(s->get());
      dout(10) << "_add_heartbeat_peer: new peer osd." << p
	       << " " << hi->con_back->get_peer_addr()
	       << " " << hi->con_front->get_peer_addr()
	       << dendl;
    } else {
      hi->con_front.reset(NULL);
      dout(10) << "_add_heartbeat_peer: new peer osd." << p
	       << " " << hi->con_back->get_peer_addr()
	       << dendl;
    }
    s->put();
  } else {
    hi = &i->second;
  }
  hi->epoch = osdmap->get_epoch();
}


isis_print_id(const uint8_t *cp, int id_len)
{
    int i;
    static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
    char *pos = id;

    for (i = 1; i <= SYSTEM_ID_LEN; i++) {
        snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
	pos += strlen(pos);
	if (i == 2 || i == 4)
	    *pos++ = '.';
	}
    if (id_len >= NODE_ID_LEN) {
        snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
	pos += strlen(pos);
    }
    if (id_len == LSP_ID_LEN)
        snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
    return (id);
}


vim_strsave_fnameescape(char_u *fname, int what)
{
    char_u	*p;
#ifdef BACKSLASH_IN_FILENAME
    char_u	buf[20];
    int		j = 0;

    // Don't escape '[', '{' and '!' if they are in 'isfname' and for the
    // ":buffer" command.
    for (p = what == VSE_BUFFER ? BUFFER_ESC_CHARS : PATH_ESC_CHARS;
								*p != NUL; ++p)
	if ((*p != '[' && *p != '{' && *p != '!') || !vim_isfilec(*p))
	    buf[j++] = *p;
    buf[j] = NUL;
    p = vim_strsave_escaped(fname, buf);
#else
    p = vim_strsave_escaped(fname, what == VSE_SHELL ? SHELL_ESC_CHARS
		    : what == VSE_BUFFER ? BUFFER_ESC_CHARS : PATH_ESC_CHARS);
    if (what == VSE_SHELL && csh_like_shell() && p != NULL)
    {
	char_u	    *s;

	// For csh and similar shells need to put two backslashes before '!'.
	// One is taken by Vim, one by the shell.
	s = vim_strsave_escaped(p, (char_u *)"!");
	vim_free(p);
	p = s;
    }
#endif

    // '>' and '+' are special at the start of some commands, e.g. ":edit" and
    // ":write".  "cd -" has a special meaning.
    if (p != NULL && (*p == '>' || *p == '+' || (*p == '-' && p[1] == NUL)))
	escape_fname(&p);

    return p;
}


ZSTD_encodeSequences_bmi2(
            void* dst, size_t dstCapacity,
            FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
            FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
            FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
            seqDef const* sequences, size_t nbSeq, int longOffsets)
{
    return ZSTD_encodeSequences_body(dst, dstCapacity,
                                    CTable_MatchLength, mlCodeTable,
                                    CTable_OffsetBits, ofCodeTable,
                                    CTable_LitLength, llCodeTable,
                                    sequences, nbSeq, longOffsets);
}


void mono_thread_suspend_all_other_threads (void)
{
	struct wait_data wait_data;
	struct wait_data *wait = &wait_data;
	int i;
	gsize self = GetCurrentThreadId ();
	gpointer *events;
	guint32 eventidx = 0;
	gboolean starting, finished;

	memset (wait, 0, sizeof (struct wait_data));
	/*
	 * The other threads could be in an arbitrary state at this point, i.e.
	 * they could be starting up, shutting down etc. This means that there could be
	 * threads which are not even in the threads hash table yet.
	 */

	/*
	 * First we set a barrier which will be checked by all threads before they
	 * are added to the threads hash table, and they will exit if the flag is set.
	 * This ensures that no threads could be added to the hash later.
	 * We will use shutting_down as the barrier for now.
	 */
	g_assert (shutting_down);

	/*
	 * We make multiple calls to WaitForMultipleObjects since:
	 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
	 * - some threads could exit without becoming suspended
	 */
	finished = FALSE;
	while (!finished) {
		/*
		 * Make a copy of the hashtable since we can't do anything with
		 * threads while threads_mutex is held.
		 */
		wait->num = 0;
		/*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
		memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
		mono_threads_lock ();
		mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
		mono_threads_unlock ();

		events = g_new0 (gpointer, wait->num);
		eventidx = 0;
		/* Get the suspended events that we'll be waiting for */
		for (i = 0; i < wait->num; ++i) {
			MonoInternalThread *thread = wait->threads [i];
			gboolean signal_suspend = FALSE;

			if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
				//CloseHandle (wait->handles [i]);
				wait->threads [i] = NULL; /* ignore this thread in next loop */
				continue;
			}

			ensure_synch_cs_set (thread);

			EnterCriticalSection (thread->synch_cs);

			if (thread->suspended_event == NULL) {
				thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
				if (thread->suspended_event == NULL) {
					/* Forget this one and go on to the next */
					LeaveCriticalSection (thread->synch_cs);
					continue;
				}
			}

			if ((thread->state & ThreadState_Suspended) != 0 ||
				(thread->state & ThreadState_StopRequested) != 0 ||
				(thread->state & ThreadState_Stopped) != 0) {
				LeaveCriticalSection (thread->synch_cs);
				CloseHandle (wait->handles [i]);
				wait->threads [i] = NULL; /* ignore this thread in next loop */
				continue;
			}

			if ((thread->state & ThreadState_SuspendRequested) == 0)
				signal_suspend = TRUE;

			events [eventidx++] = thread->suspended_event;

			/* Convert abort requests into suspend requests */
			if ((thread->state & ThreadState_AbortRequested) != 0)
				thread->state &= ~ThreadState_AbortRequested;

			thread->state |= ThreadState_SuspendRequested;

			LeaveCriticalSection (thread->synch_cs);

			/* Signal the thread to suspend */
			if (signal_suspend)
				signal_thread_state_change (thread);
		}

		if (eventidx > 0) {
			WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
			for (i = 0; i < wait->num; ++i) {
				MonoInternalThread *thread = wait->threads [i];

				if (thread == NULL)
					continue;

				ensure_synch_cs_set (thread);

				EnterCriticalSection (thread->synch_cs);
				if ((thread->state & ThreadState_Suspended) != 0) {
					CloseHandle (thread->suspended_event);
					thread->suspended_event = NULL;
				}
				LeaveCriticalSection (thread->synch_cs);
			}
		} else {
			/*
			 * If there are threads which are starting up, we wait until they
			 * are suspended when they try to register in the threads hash.
			 * This is guaranteed to finish, since the threads which can create new
			 * threads get suspended after a while.
			 * FIXME: The finalizer thread can still create new threads.
			 */
			mono_threads_lock ();
			if (threads_starting_up)
				starting = mono_g_hash_table_size (threads_starting_up) > 0;
			else
				starting = FALSE;
			mono_threads_unlock ();
			if (starting)
				Sleep (100);
			else
				finished = TRUE;
		}

		g_free (events);
	}
}


void AutofillMetricsTest::CreateAmbiguousProfiles() {
  personal_data_->ClearProfiles();
  CreateTestAutofillProfiles();

  AutofillProfile profile;
  test::SetProfileInfo(&profile, "John", "Decca", "Public", "john@gmail.com",
                       "Company", "123 Main St.", "unit 7", "Springfield",
                       "Texas", "79401", "US", "2345678901");
  profile.set_guid("00000000-0000-0000-0000-000000000003");
  personal_data_->AddProfile(profile);
  personal_data_->Refresh();
}


static bool check_caller_access_to_node(struct fuse* fuse,
 const struct fuse_in_header *hdr, const struct node* node, int mode) {
 return check_caller_access_to_name(fuse, hdr, node->parent, node->name, mode);
}


static bool cmd_identify_packet(IDEState *s, uint8_t cmd)
{
    ide_atapi_identify(s);
    s->status = READY_STAT | SEEK_STAT;
    ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
    ide_set_irq(s->bus);
    return false;
}