export_desktop_file (const char         *app,
                     const char         *branch,
                     const char         *arch,
                     GKeyFile           *metadata,
                     const char * const *previous_ids,
                     int                 parent_fd,
                     const char         *name,
                     struct stat        *stat_buf,
                     char              **target,
                     GCancellable       *cancellable,
                     GError            **error)
{
  gboolean ret = FALSE;
  glnx_autofd int desktop_fd = -1;
  g_autofree char *tmpfile_name = g_strdup_printf ("export-desktop-XXXXXX");
  g_autoptr(GOutputStream) out_stream = NULL;
  g_autofree gchar *data = NULL;
  gsize data_len;
  g_autofree gchar *new_data = NULL;
  gsize new_data_len;
  g_autoptr(GKeyFile) keyfile = NULL;
  g_autofree gchar *old_exec = NULL;
  gint old_argc;
  g_auto(GStrv) old_argv = NULL;
  g_auto(GStrv) groups = NULL;
  GString *new_exec = NULL;
  g_autofree char *escaped_app = maybe_quote (app);
  g_autofree char *escaped_branch = maybe_quote (branch);
  g_autofree char *escaped_arch = maybe_quote (arch);
  int i;

  if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error))
    goto out;

  if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error))
    goto out;

  keyfile = g_key_file_new ();
  if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error))
    goto out;

  if (g_str_has_suffix (name, ".service"))
    {
      g_autofree gchar *dbus_name = NULL;
      g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (".service"));

      dbus_name = g_key_file_get_string (keyfile, "D-BUS Service", "Name", NULL);

      if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0)
        {
          return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,
                                     _("D-Bus service file '%s' has wrong name"), name);
        }
    }

  if (g_str_has_suffix (name, ".desktop"))
    {
      gsize length;
      g_auto(GStrv) tags = g_key_file_get_string_list (metadata,
                                                       "Application",
                                                       "tags", &length,
                                                       NULL);

      if (tags != NULL)
        {
          g_key_file_set_string_list (keyfile,
                                      G_KEY_FILE_DESKTOP_GROUP,
                                      "X-Flatpak-Tags",
                                      (const char * const *) tags, length);
        }

      /* Add a marker so consumers can easily find out that this launches a sandbox */
      g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, "X-Flatpak", app);

      /* If the app has been renamed, add its old .desktop filename to
       * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to
       * introduce duplicates.
       */
      if (previous_ids != NULL)
        {
          const char *X_FLATPAK_RENAMED_FROM = "X-Flatpak-RenamedFrom";
          g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile,
                                                                   G_KEY_FILE_DESKTOP_GROUP,
                                                                   X_FLATPAK_RENAMED_FROM,
                                                                   NULL, NULL);
          g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free);
          g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal);
          const char *new_suffix;

          for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++)
            {
              if (!g_hash_table_contains (seen, renamed_from[i]))
                {
                  gchar *copy = g_strdup (renamed_from[i]);
                  g_hash_table_insert (seen, copy, copy);
                  g_ptr_array_add (merged, g_steal_pointer (&copy));
                }
            }

          /* If an app was renamed from com.example.Foo to net.example.Bar, and
           * the new version exports net.example.Bar-suffix.desktop, we assume the
           * old version exported com.example.Foo-suffix.desktop.
           *
           * This assertion is true because
           * flatpak_name_matches_one_wildcard_prefix() is called on all
           * exported files before we get here.
           */
          g_assert (g_str_has_prefix (name, app));
          /* ".desktop" for the "main" desktop file; something like
           * "-suffix.desktop" for extra ones.
           */
          new_suffix = name + strlen (app);

          for (i = 0; previous_ids[i] != NULL; i++)
            {
              g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL);
              if (!g_hash_table_contains (seen, previous_desktop))
                {
                  g_hash_table_insert (seen, previous_desktop, previous_desktop);
                  g_ptr_array_add (merged, g_steal_pointer (&previous_desktop));
                }
            }

          if (merged->len > 0)
            {
              g_ptr_array_add (merged, NULL);
              g_key_file_set_string_list (keyfile,
                                          G_KEY_FILE_DESKTOP_GROUP,
                                          X_FLATPAK_RENAMED_FROM,
                                          (const char * const *) merged->pdata,
                                          merged->len - 1);
            }
        }
    }

  groups = g_key_file_get_groups (keyfile, NULL);

  for (i = 0; groups[i] != NULL; i++)
    {
      g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], "X-Flatpak-RunOptions", NULL, NULL);
      g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts);

      g_key_file_remove_key (keyfile, groups[i], "X-Flatpak-RunOptions", NULL);
      g_key_file_remove_key (keyfile, groups[i], "TryExec", NULL);

      /* Remove this to make sure nothing tries to execute it outside the sandbox*/
      g_key_file_remove_key (keyfile, groups[i], "X-GNOME-Bugzilla-ExtraInfoScript", NULL);

      new_exec = g_string_new ("");
      g_string_append_printf (new_exec,
                              FLATPAK_BINDIR "/flatpak run --branch=%s --arch=%s",
                              escaped_branch,
                              escaped_arch);

      if (flatpak_run_args != NULL)
        g_string_append_printf (new_exec, "%s", flatpak_run_args);

      old_exec = g_key_file_get_string (keyfile, groups[i], "Exec", NULL);
      if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1)
        {
          int j;
          g_autofree char *command = maybe_quote (old_argv[0]);

          g_string_append_printf (new_exec, " --command=%s", command);

          for (j = 1; j < old_argc; j++)
            {
              if (strcasecmp (old_argv[j], "%f") == 0 ||
                  strcasecmp (old_argv[j], "%u") == 0)
                {
                  g_string_append (new_exec, " --file-forwarding");
                  break;
                }
            }

          g_string_append (new_exec, " ");
          g_string_append (new_exec, escaped_app);

          for (j = 1; j < old_argc; j++)
            {
              g_autofree char *arg = maybe_quote (old_argv[j]);

              if (strcasecmp (arg, "%f") == 0)
                g_string_append_printf (new_exec, " @@ %s @@", arg);
              else if (strcasecmp (arg, "%u") == 0)
                g_string_append_printf (new_exec, " @@u %s @@", arg);
              else if (strcmp (arg, "@@") == 0 || strcmp (arg, "@@u") == 0)
                g_print (_("Skipping invalid Exec argument %s\n"), arg);
              else
                g_string_append_printf (new_exec, " %s", arg);
            }
        }
      else
        {
          g_string_append (new_exec, " ");
          g_string_append (new_exec, escaped_app);
        }

      g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str);
    }

  new_data = g_key_file_to_data (keyfile, &new_data_len, error);
  if (new_data == NULL)
    goto out;

  if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error))
    goto out;

  if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error))
    goto out;

  if (!g_output_stream_close (out_stream, cancellable, error))
    goto out;

  if (target)
    *target = g_steal_pointer (&tmpfile_name);

  ret = TRUE;
out:

  if (new_exec != NULL)
    g_string_free (new_exec, TRUE);

  return ret;
}


static void setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
{
    path->incReserve(numPoints);
    path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
                 WebCoreFloatToSkScalar(points[0].y()));
    for (size_t i = 1; i < numPoints; ++i) {
         path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
                      WebCoreFloatToSkScalar(points[i].y()));
     }
    path->setIsConvex(true);
 }


void WebContentsImpl::DocumentAvailableInMainFrame(
    RenderViewHost* render_view_host) {
  for (auto& observer : observers_)
    observer.DocumentAvailableInMainFrame();
}


static void
init_type_builder_generics (MonoObject *type)
{


  virtual void requestInit() {
    m_use_error = false;
    m_errors.reset();
    m_entity_loader_disabled = false;
    xmlParserInputBufferCreateFilenameDefault(hphp_libxml_input_buffer);
  }


int bnxt_re_modify_qp(struct ib_qp *ib_qp, struct ib_qp_attr *qp_attr,
		      int qp_attr_mask, struct ib_udata *udata)
{
	struct bnxt_re_qp *qp = container_of(ib_qp, struct bnxt_re_qp, ib_qp);
	struct bnxt_re_dev *rdev = qp->rdev;
	struct bnxt_qplib_dev_attr *dev_attr = &rdev->dev_attr;
	enum ib_qp_state curr_qp_state, new_qp_state;
	int rc, entries;
	unsigned int flags;
	u8 nw_type;

	qp->qplib_qp.modify_flags = 0;
	if (qp_attr_mask & IB_QP_STATE) {
		curr_qp_state = __to_ib_qp_state(qp->qplib_qp.cur_qp_state);
		new_qp_state = qp_attr->qp_state;
		if (!ib_modify_qp_is_ok(curr_qp_state, new_qp_state,
					ib_qp->qp_type, qp_attr_mask)) {
			dev_err(rdev_to_dev(rdev),
				"Invalid attribute mask: %#x specified ",
				qp_attr_mask);
			dev_err(rdev_to_dev(rdev),
				"for qpn: %#x type: %#x",
				ib_qp->qp_num, ib_qp->qp_type);
			dev_err(rdev_to_dev(rdev),
				"curr_qp_state=0x%x, new_qp_state=0x%x\n",
				curr_qp_state, new_qp_state);
			return -EINVAL;
		}
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_STATE;
		qp->qplib_qp.state = __from_ib_qp_state(qp_attr->qp_state);

		if (!qp->sumem &&
		    qp->qplib_qp.state == CMDQ_MODIFY_QP_NEW_STATE_ERR) {
			dev_dbg(rdev_to_dev(rdev),
				"Move QP = %p to flush list\n",
				qp);
			flags = bnxt_re_lock_cqs(qp);
			bnxt_qplib_add_flush_qp(&qp->qplib_qp);
			bnxt_re_unlock_cqs(qp, flags);
		}
		if (!qp->sumem &&
		    qp->qplib_qp.state == CMDQ_MODIFY_QP_NEW_STATE_RESET) {
			dev_dbg(rdev_to_dev(rdev),
				"Move QP = %p out of flush list\n",
				qp);
			flags = bnxt_re_lock_cqs(qp);
			bnxt_qplib_clean_qp(&qp->qplib_qp);
			bnxt_re_unlock_cqs(qp, flags);
		}
	}
	if (qp_attr_mask & IB_QP_EN_SQD_ASYNC_NOTIFY) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_EN_SQD_ASYNC_NOTIFY;
		qp->qplib_qp.en_sqd_async_notify = true;
	}
	if (qp_attr_mask & IB_QP_ACCESS_FLAGS) {
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_ACCESS;
		qp->qplib_qp.access =
			__from_ib_access_flags(qp_attr->qp_access_flags);
		/* LOCAL_WRITE access must be set to allow RC receive */
		qp->qplib_qp.access |= BNXT_QPLIB_ACCESS_LOCAL_WRITE;
		/* Temp: Set all params on QP as of now */
		qp->qplib_qp.access |= CMDQ_MODIFY_QP_ACCESS_REMOTE_WRITE;
		qp->qplib_qp.access |= CMDQ_MODIFY_QP_ACCESS_REMOTE_READ;
	}
	if (qp_attr_mask & IB_QP_PKEY_INDEX) {
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_PKEY;
		qp->qplib_qp.pkey_index = qp_attr->pkey_index;
	}
	if (qp_attr_mask & IB_QP_QKEY) {
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_QKEY;
		qp->qplib_qp.qkey = qp_attr->qkey;
	}
	if (qp_attr_mask & IB_QP_AV) {
		const struct ib_global_route *grh =
			rdma_ah_read_grh(&qp_attr->ah_attr);
		const struct ib_gid_attr *sgid_attr;

		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_DGID |
				     CMDQ_MODIFY_QP_MODIFY_MASK_FLOW_LABEL |
				     CMDQ_MODIFY_QP_MODIFY_MASK_SGID_INDEX |
				     CMDQ_MODIFY_QP_MODIFY_MASK_HOP_LIMIT |
				     CMDQ_MODIFY_QP_MODIFY_MASK_TRAFFIC_CLASS |
				     CMDQ_MODIFY_QP_MODIFY_MASK_DEST_MAC |
				     CMDQ_MODIFY_QP_MODIFY_MASK_VLAN_ID;
		memcpy(qp->qplib_qp.ah.dgid.data, grh->dgid.raw,
		       sizeof(qp->qplib_qp.ah.dgid.data));
		qp->qplib_qp.ah.flow_label = grh->flow_label;
		/* If RoCE V2 is enabled, stack will have two entries for
		 * each GID entry. Avoiding this duplicte entry in HW. Dividing
		 * the GID index by 2 for RoCE V2
		 */
		qp->qplib_qp.ah.sgid_index = grh->sgid_index / 2;
		qp->qplib_qp.ah.host_sgid_index = grh->sgid_index;
		qp->qplib_qp.ah.hop_limit = grh->hop_limit;
		qp->qplib_qp.ah.traffic_class = grh->traffic_class;
		qp->qplib_qp.ah.sl = rdma_ah_get_sl(&qp_attr->ah_attr);
		ether_addr_copy(qp->qplib_qp.ah.dmac,
				qp_attr->ah_attr.roce.dmac);

		sgid_attr = qp_attr->ah_attr.grh.sgid_attr;
		rc = rdma_read_gid_l2_fields(sgid_attr, NULL,
					     &qp->qplib_qp.smac[0]);
		if (rc)
			return rc;

		nw_type = rdma_gid_attr_network_type(sgid_attr);
		switch (nw_type) {
		case RDMA_NETWORK_IPV4:
			qp->qplib_qp.nw_type =
				CMDQ_MODIFY_QP_NETWORK_TYPE_ROCEV2_IPV4;
			break;
		case RDMA_NETWORK_IPV6:
			qp->qplib_qp.nw_type =
				CMDQ_MODIFY_QP_NETWORK_TYPE_ROCEV2_IPV6;
			break;
		default:
			qp->qplib_qp.nw_type =
				CMDQ_MODIFY_QP_NETWORK_TYPE_ROCEV1;
			break;
		}
	}

	if (qp_attr_mask & IB_QP_PATH_MTU) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_PATH_MTU;
		qp->qplib_qp.path_mtu = __from_ib_mtu(qp_attr->path_mtu);
		qp->qplib_qp.mtu = ib_mtu_enum_to_int(qp_attr->path_mtu);
	} else if (qp_attr->qp_state == IB_QPS_RTR) {
		qp->qplib_qp.modify_flags |=
			CMDQ_MODIFY_QP_MODIFY_MASK_PATH_MTU;
		qp->qplib_qp.path_mtu =
			__from_ib_mtu(iboe_get_mtu(rdev->netdev->mtu));
		qp->qplib_qp.mtu =
			ib_mtu_enum_to_int(iboe_get_mtu(rdev->netdev->mtu));
	}

	if (qp_attr_mask & IB_QP_TIMEOUT) {
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_TIMEOUT;
		qp->qplib_qp.timeout = qp_attr->timeout;
	}
	if (qp_attr_mask & IB_QP_RETRY_CNT) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_RETRY_CNT;
		qp->qplib_qp.retry_cnt = qp_attr->retry_cnt;
	}
	if (qp_attr_mask & IB_QP_RNR_RETRY) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_RNR_RETRY;
		qp->qplib_qp.rnr_retry = qp_attr->rnr_retry;
	}
	if (qp_attr_mask & IB_QP_MIN_RNR_TIMER) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_MIN_RNR_TIMER;
		qp->qplib_qp.min_rnr_timer = qp_attr->min_rnr_timer;
	}
	if (qp_attr_mask & IB_QP_RQ_PSN) {
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_RQ_PSN;
		qp->qplib_qp.rq.psn = qp_attr->rq_psn;
	}
	if (qp_attr_mask & IB_QP_MAX_QP_RD_ATOMIC) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_MAX_RD_ATOMIC;
		/* Cap the max_rd_atomic to device max */
		qp->qplib_qp.max_rd_atomic = min_t(u32, qp_attr->max_rd_atomic,
						   dev_attr->max_qp_rd_atom);
	}
	if (qp_attr_mask & IB_QP_SQ_PSN) {
		qp->qplib_qp.modify_flags |= CMDQ_MODIFY_QP_MODIFY_MASK_SQ_PSN;
		qp->qplib_qp.sq.psn = qp_attr->sq_psn;
	}
	if (qp_attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) {
		if (qp_attr->max_dest_rd_atomic >
		    dev_attr->max_qp_init_rd_atom) {
			dev_err(rdev_to_dev(rdev),
				"max_dest_rd_atomic requested%d is > dev_max%d",
				qp_attr->max_dest_rd_atomic,
				dev_attr->max_qp_init_rd_atom);
			return -EINVAL;
		}

		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_MAX_DEST_RD_ATOMIC;
		qp->qplib_qp.max_dest_rd_atomic = qp_attr->max_dest_rd_atomic;
	}
	if (qp_attr_mask & IB_QP_CAP) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_SQ_SIZE |
				CMDQ_MODIFY_QP_MODIFY_MASK_RQ_SIZE |
				CMDQ_MODIFY_QP_MODIFY_MASK_SQ_SGE |
				CMDQ_MODIFY_QP_MODIFY_MASK_RQ_SGE |
				CMDQ_MODIFY_QP_MODIFY_MASK_MAX_INLINE_DATA;
		if ((qp_attr->cap.max_send_wr >= dev_attr->max_qp_wqes) ||
		    (qp_attr->cap.max_recv_wr >= dev_attr->max_qp_wqes) ||
		    (qp_attr->cap.max_send_sge >= dev_attr->max_qp_sges) ||
		    (qp_attr->cap.max_recv_sge >= dev_attr->max_qp_sges) ||
		    (qp_attr->cap.max_inline_data >=
						dev_attr->max_inline_data)) {
			dev_err(rdev_to_dev(rdev),
				"Create QP failed - max exceeded");
			return -EINVAL;
		}
		entries = roundup_pow_of_two(qp_attr->cap.max_send_wr);
		qp->qplib_qp.sq.max_wqe = min_t(u32, entries,
						dev_attr->max_qp_wqes + 1);
		qp->qplib_qp.sq.q_full_delta = qp->qplib_qp.sq.max_wqe -
						qp_attr->cap.max_send_wr;
		/*
		 * Reserving one slot for Phantom WQE. Some application can
		 * post one extra entry in this case. Allowing this to avoid
		 * unexpected Queue full condition
		 */
		qp->qplib_qp.sq.q_full_delta -= 1;
		qp->qplib_qp.sq.max_sge = qp_attr->cap.max_send_sge;
		if (qp->qplib_qp.rq.max_wqe) {
			entries = roundup_pow_of_two(qp_attr->cap.max_recv_wr);
			qp->qplib_qp.rq.max_wqe =
				min_t(u32, entries, dev_attr->max_qp_wqes + 1);
			qp->qplib_qp.rq.q_full_delta = qp->qplib_qp.rq.max_wqe -
						       qp_attr->cap.max_recv_wr;
			qp->qplib_qp.rq.max_sge = qp_attr->cap.max_recv_sge;
		} else {
			/* SRQ was used prior, just ignore the RQ caps */
		}
	}
	if (qp_attr_mask & IB_QP_DEST_QPN) {
		qp->qplib_qp.modify_flags |=
				CMDQ_MODIFY_QP_MODIFY_MASK_DEST_QP_ID;
		qp->qplib_qp.dest_qpn = qp_attr->dest_qp_num;
	}
	rc = bnxt_qplib_modify_qp(&rdev->qplib_res, &qp->qplib_qp);
	if (rc) {
		dev_err(rdev_to_dev(rdev), "Failed to modify HW QP");
		return rc;
	}
	if (ib_qp->qp_type == IB_QPT_GSI && rdev->qp1_sqp)
		rc = bnxt_re_modify_shadow_qp(rdev, qp, qp_attr_mask);
	return rc;
}


bool initiate_stratum(struct pool *pool)
{
	bool ret = false, recvd = false, noresume = false, sockd = false;
	char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
	json_t *val = NULL, *res_val, *err_val;
	json_error_t err;
	int n2size;

resend:
	if (!setup_stratum_socket(pool)) {
		/* FIXME: change to LOG_DEBUG when issue #88 resolved */
		applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
		sockd = false;
		goto out;
	}

	sockd = true;

	if (recvd) {
		/* Get rid of any crap lying around if we're resending */
		clear_sock(pool);
		sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
	} else {
		if (pool->sessionid)
			sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
		else
			sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
	}

	if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
		applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
		goto out;
	}

	if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
		applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
		goto out;
	}

	sret = recv_line(pool);
	if (!sret)
		goto out;

	recvd = true;

	val = JSON_LOADS(sret, &err);
	free(sret);
	if (!val) {
		applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
		goto out;
	}

	res_val = json_object_get(val, "result");
	err_val = json_object_get(val, "error");

	if (!res_val || json_is_null(res_val) ||
	    (err_val && !json_is_null(err_val))) {
		char *ss;

		if (err_val)
			ss = json_dumps(err_val, JSON_INDENT(3));
		else
			ss = strdup("(unknown reason)");

		applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);

		free(ss);

		goto out;
	}

	sessionid = get_sessionid(res_val);
	if (!sessionid)
		applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
	nonce1 = json_array_string(res_val, 1);
	if (!nonce1) {
		applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
		free(sessionid);
 		goto out;
 	}
 	n2size = json_integer_value(json_array_get(res_val, 2));
	if (!n2size) {
 		applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
 		free(sessionid);
 		free(nonce1);
		goto out;
	}

	cg_wlock(&pool->data_lock);
	pool->sessionid = sessionid;
	pool->nonce1 = nonce1;
	pool->n1_len = strlen(nonce1) / 2;
	free(pool->nonce1bin);
	pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
	if (unlikely(!pool->nonce1bin))
		quithere(1, "Failed to calloc pool->nonce1bin");
	hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
	pool->n2size = n2size;
	cg_wunlock(&pool->data_lock);

	if (sessionid)
		applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);

	ret = true;
out:
	if (ret) {
		if (!pool->stratum_url)
			pool->stratum_url = pool->sockaddr_url;
		pool->stratum_active = true;
		pool->swork.diff = 1;
		if (opt_protocol) {
			applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
			       get_pool_name(pool), pool->nonce1, pool->n2size);
		}
	} else {
		if (recvd && !noresume) {
			/* Reset the sessionid used for stratum resuming in case the pool
			* does not support it, or does not know how to respond to the
			* presence of the sessionid parameter. */
			cg_wlock(&pool->data_lock);
			free(pool->sessionid);
			free(pool->nonce1);
			pool->sessionid = pool->nonce1 = NULL;
			cg_wunlock(&pool->data_lock);

			applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
			noresume = true;
			json_decref(val);
			goto resend;
		}
		applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
		if (sockd) {
		  applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
			suspend_stratum(pool);
		}
	}

	json_decref(val);
	return ret;
}


static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
  char task_path[64];
//// Attach to a thread, and verify that it's still a member of the given process

  snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);

   std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);

 if (!d) {
    ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
 return;
 }

 struct dirent* de;
 while ((de = readdir(d.get())) != NULL) {
 if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
 continue;
 }

 char* end;
 pid_t tid = strtoul(de->d_name, &end, 10);
 if (*end) {
 continue;
 }

 if (tid == main_tid) {

       continue;
     }

    if (ptrace(PTRACE_ATTACH, tid, 0, 0) < 0) {
       ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
       continue;
     }

    tids.insert(tid);
 }
}


static void DeprecateAsSameValueMeasureAsOverloadedMethod1Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
  TestObject* impl = V8TestObject::ToImpl(info.Holder());

  impl->deprecateAsSameValueMeasureAsOverloadedMethod();
}


void BluetoothAdapterChromeOS::OnStopDiscovery(const base::Closure& callback) {
  callback.Run();
}


void DownloadManagerImpl::StartDownloadWithId(
    std::unique_ptr<DownloadCreateInfo> info,
    std::unique_ptr<DownloadManager::InputStream> stream,
    const DownloadUrlParameters::OnStartedCallback& on_started,
    bool new_download,
    uint32_t id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_NE(content::DownloadItem::kInvalidId, id);
  DownloadItemImpl* download = nullptr;
  if (new_download) {
    download = CreateActiveItem(id, *info);
  } else {
    auto item_iterator = downloads_.find(id);
    if (item_iterator == downloads_.end() ||
        (item_iterator->second->GetState() == DownloadItem::CANCELLED)) {
      info->request_handle->CancelRequest(true);
      if (!on_started.is_null())
        on_started.Run(nullptr, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
      if (info->result == DOWNLOAD_INTERRUPT_REASON_NONE)
        GetDownloadTaskRunner()->DeleteSoon(FROM_HERE, stream.release());
      return;
    }
    download = item_iterator->second.get();
  }

  base::FilePath default_download_directory;
#if defined(USE_X11)
  default_download_directory = GetTemporaryDownloadDirectory();
#else
  if (delegate_) {
    base::FilePath website_save_directory;  // Unused
    bool skip_dir_check = false;            // Unused
    delegate_->GetSaveDir(GetBrowserContext(), &website_save_directory,
                          &default_download_directory, &skip_dir_check);
  }
#endif

  if (delegate_) {
    if (!in_progress_download_observer_) {
      in_progress_download_observer_.reset(
          new InProgressDownloadObserver(delegate_->GetInProgressCache()));
    }
    download->RemoveObserver(in_progress_download_observer_.get());
    download->AddObserver(in_progress_download_observer_.get());
  }

  std::unique_ptr<DownloadFile> download_file;

  if (info->result == DOWNLOAD_INTERRUPT_REASON_NONE) {
    DCHECK(stream.get());
    download_file.reset(file_factory_->CreateFile(
        std::move(info->save_info), default_download_directory,
        std::move(stream), id, download->DestinationObserverAsWeakPtr()));
  }

  download->Start(std::move(download_file), std::move(info->request_handle),
                  *info);

  if (new_download) {
    for (auto& observer : observers_)
      observer.OnDownloadCreated(this, download);
  }

  if (!on_started.is_null())
    on_started.Run(download, DOWNLOAD_INTERRUPT_REASON_NONE);
}


void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2,
                         TfLiteTensor* output, bool requires_broadcast) {
  if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {
    auto input1_offset = -input1->params.zero_point;
    auto input2_offset = -input2->params.zero_point;
    const int left_shift = 8;

    int32 input1_multiplier;
    int input1_shift;
    QuantizeMultiplierSmallerThanOneExp(input1->params.scale,
                                        &input1_multiplier, &input1_shift);
    int32 input2_multiplier;
    int input2_shift;
    QuantizeMultiplierSmallerThanOneExp(input2->params.scale,
                                        &input2_multiplier, &input2_shift);

    ComparisonParams op_params;
    op_params.left_shift = left_shift;
    op_params.input1_offset = input1_offset;
    op_params.input1_multiplier = input1_multiplier;
    op_params.input1_shift = input1_shift;
    op_params.input2_offset = input2_offset;
    op_params.input2_multiplier = input2_multiplier;
    op_params.input2_shift = input2_shift;
    if (requires_broadcast) {
      reference_ops::BroadcastComparison4DSlowWithScaling<input_dtype, opname>(
          op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1),
          GetTensorShape(input2), GetTensorData<input_dtype>(input2),
          GetTensorShape(output), GetTensorData<bool>(output));
    } else {
      reference_ops::ComparisonWithScaling<input_dtype, opname>(
          op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1),
          GetTensorShape(input2), GetTensorData<input_dtype>(input2),
          GetTensorShape(output), GetTensorData<bool>(output));
    }
  }
}


int mnt_optstr_deduplicate_option(char **optstr, const char *name)
{
	int rc;
	char *begin = NULL, *end = NULL, *opt;

	if (!optstr || !name)
		return -EINVAL;

	opt = *optstr;
	do {
		struct libmnt_optloc ol = MNT_INIT_OPTLOC;

		rc = mnt_optstr_locate_option(opt, name, &ol);
		if (!rc) {
			if (begin) {
				/* remove the previous instance */
				size_t shift = strlen(*optstr);

				mnt_optstr_remove_option_at(optstr, begin, end);

				/* now all the offsets are not valid anymore - recount */
				shift -= strlen(*optstr);
				ol.begin -= shift;
				ol.end -= shift;
			}
			begin = ol.begin;
			end = ol.end;
			opt = end && *end ? end + 1 : NULL;
		}
		if (opt == NULL)
			break;
	} while (rc == 0 && *opt);

	return rc < 0 ? rc : begin ? 0 : 1;
}


static int MP4_ReadBox_load( stream_t *p_stream, MP4_Box_t *p_box )
{
    if ( p_box->i_size != 24 )
        return 0;
    MP4_READBOX_ENTER( MP4_Box_data_load_t );
    MP4_GET4BYTES( p_box->data.p_load->i_start_time );
    MP4_GET4BYTES( p_box->data.p_load->i_duration );
    MP4_GET4BYTES( p_box->data.p_load->i_flags );
    MP4_GET4BYTES( p_box->data.p_load->i_hints );
    MP4_READBOX_EXIT( 1 );
}


static Bool gf_m2ts_is_long_section(u8 table_id)
{
	switch (table_id) {
	case GF_M2TS_TABLE_ID_MPEG4_BIFS:
	case GF_M2TS_TABLE_ID_MPEG4_OD:
	case GF_M2TS_TABLE_ID_INT:
	case GF_M2TS_TABLE_ID_EIT_ACTUAL_PF:
	case GF_M2TS_TABLE_ID_EIT_OTHER_PF:
	case GF_M2TS_TABLE_ID_ST:
	case GF_M2TS_TABLE_ID_SIT:
	case GF_M2TS_TABLE_ID_DSM_CC_PRIVATE:
	case GF_M2TS_TABLE_ID_MPE_FEC:
	case GF_M2TS_TABLE_ID_DSM_CC_DOWNLOAD_DATA_MESSAGE:
	case GF_M2TS_TABLE_ID_DSM_CC_UN_MESSAGE:
		return 1;
	default:
		if (table_id >= GF_M2TS_TABLE_ID_EIT_SCHEDULE_MIN && table_id <= GF_M2TS_TABLE_ID_EIT_SCHEDULE_MAX)
			return 1;
		else
			return 0;
	}
}


void init_rl(RLTable *rl)

{

    int8_t max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];

    uint8_t index_run[MAX_RUN+1];

    int last, run, level, start, end, i;

    /* compute max_level[], max_run[] and index_run[] */

    for(last=0;last<2;last++) {

        if (last == 0) {

            start = 0;

            end = rl->last;

        } else {

            start = rl->last;

            end = rl->n;

        }

        memset(max_level, 0, MAX_RUN + 1);

        memset(max_run, 0, MAX_LEVEL + 1);

        memset(index_run, rl->n, MAX_RUN + 1);

        for(i=start;i<end;i++) {

            run = rl->table_run[i];

            level = rl->table_level[i];

            if (index_run[run] == rl->n)

                index_run[run] = i;

            if (level > max_level[run])

                max_level[run] = level;

            if (run > max_run[level])

                max_run[level] = run;

        }

        rl->max_level[last] = av_malloc(MAX_RUN + 1);

        memcpy(rl->max_level[last], max_level, MAX_RUN + 1);

        rl->max_run[last] = av_malloc(MAX_LEVEL + 1);

        memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);

        rl->index_run[last] = av_malloc(MAX_RUN + 1);

        memcpy(rl->index_run[last], index_run, MAX_RUN + 1);

    }

}


GF_Box *pitm_box_new()
{
	ISOM_DECL_BOX_ALLOC(GF_PrimaryItemBox, GF_ISOM_BOX_TYPE_PITM);
	return (GF_Box *)tmp;
}


IHEVCD_ERROR_T ihevcd_parse_user_data_registered_itu_t_t35(codec_t *ps_codec,
                                                           UWORD32 u4_payload_size)
{
 parse_ctxt_t *ps_parse = &ps_codec->s_parse;
 bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm;
    UWORD32 value;
 user_data_registered_itu_t_t35_t *ps_user_data_registered_itu_t_t35;
    UWORD32 i;
    UWORD32 j = 0;

    ps_parse->s_sei_params.i1_user_data_registered_present_flag = 1;
    ps_user_data_registered_itu_t_t35 =
 &ps_parse->s_sei_params.as_user_data_registered_itu_t_t35[ps_parse->s_sei_params.i4_sei_user_data_cnt];
    ps_parse->s_sei_params.i4_sei_user_data_cnt++;

    ps_user_data_registered_itu_t_t35->i4_payload_size = u4_payload_size;

 if(u4_payload_size > MAX_USERDATA_PAYLOAD)
 {
        u4_payload_size = MAX_USERDATA_PAYLOAD;
 }

    ps_user_data_registered_itu_t_t35->i4_valid_payload_size = u4_payload_size;

    BITS_PARSE("itu_t_t35_country_code", value, ps_bitstrm, 8);
    ps_user_data_registered_itu_t_t35->u1_itu_t_t35_country_code = value;

 if(0xFF != ps_user_data_registered_itu_t_t35->u1_itu_t_t35_country_code)
 {
        i = 1;
 }
 else
 {
        BITS_PARSE("itu_t_t35_country_code_extension_byte", value, ps_bitstrm,
 8);
        ps_user_data_registered_itu_t_t35->u1_itu_t_t35_country_code_extension_byte =
                        value;

        i = 2;
 }

 do
 {
        BITS_PARSE("itu_t_t35_payload_byte", value, ps_bitstrm, 8);
        ps_user_data_registered_itu_t_t35->u1_itu_t_t35_payload_byte[j++] =
                        value;

        i++;
 }while(i < u4_payload_size);

 return (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}


static void FVMenuOblique(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) {
    FontView *fv = (FontView *) GDrawGetUserData(gw);
    ObliqueDlg(fv,NULL);
}


emnc10_opaque_literal_attr(tvbuff_t *tvb, guint32 offset,
			   const char *token, guint8 codepage _U_, guint32 *length)
{
	guint32 data_len = tvb_get_guintvar(tvb, offset, length);
	char *str = NULL;

	if ( token && (strcmp(token, "timestamp") == 0) )
		{
			str = date_time_from_opaque(tvb, offset + *length, data_len);
		}
	if (str == NULL) { /* Error, or not parsed */
		str = wmem_strdup_printf(wmem_packet_scope(), "(%d bytes of unparsed opaque data)", data_len);
	}
	*length += data_len;

	return str;
}


static void reflectedCustomURLAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
    CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
    TestObjectV8Internal::reflectedCustomURLAttrAttributeSetter(jsValue, info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


  tt_cmap2_validate( FT_Byte*      table,
                     FT_Validator  valid )
  {
    FT_Byte*  p;
    FT_UInt   length;

    FT_UInt   n, max_subs;
    FT_Byte*  keys;        /* keys table     */
    FT_Byte*  subs;        /* sub-headers    */
    FT_Byte*  glyph_ids;   /* glyph ID array */

    if ( table + 2 + 2 > valid->limit )
      FT_INVALID_TOO_SHORT;

    p      = table + 2;           /* skip format */
    length = TT_NEXT_USHORT( p );

    if ( table + length > valid->limit || length < 6 + 512 )
      FT_INVALID_TOO_SHORT;

    keys = table + 6;

    /* parse keys to compute sub-headers count */
    p        = keys;
    max_subs = 0;
    for ( n = 0; n < 256; n++ )
    {
      FT_UInt  idx = TT_NEXT_USHORT( p );

      /* value must be multiple of 8 */
      if ( valid->level >= FT_VALIDATE_PARANOID && ( idx & 7 ) != 0 )
        FT_INVALID_DATA;

      idx >>= 3;

      if ( idx > max_subs )
        max_subs = idx;
    }

    FT_ASSERT( p == table + 518 );

    subs      = p;
    glyph_ids = subs + (max_subs + 1) * 8;
    if ( glyph_ids > valid->limit )
      FT_INVALID_TOO_SHORT;

    /* parse sub-headers */
    for ( n = 0; n <= max_subs; n++ )
    {
      FT_UInt  first_code, code_count, offset;
      FT_Int   delta;

      first_code = TT_NEXT_USHORT( p );
      code_count = TT_NEXT_USHORT( p );
      delta      = TT_NEXT_SHORT( p );
      offset     = TT_NEXT_USHORT( p );

      /* many Dynalab fonts have empty sub-headers */
      if ( code_count == 0 )
        continue;

      /* check range within 0..255 */
      if ( valid->level >= FT_VALIDATE_PARANOID )
      {
        if ( first_code >= 256 || first_code + code_count > 256 )
          FT_INVALID_DATA;
      }

      /* check offset */
      if ( offset != 0 )
      {
        FT_Byte*  ids;

        ids = p - 2 + offset;
        if ( ids < glyph_ids || ids + code_count*2 > table + length )
          FT_INVALID_OFFSET;

        /* check glyph IDs */
        if ( valid->level >= FT_VALIDATE_TIGHT )
        {
          FT_Byte*  limit = p + code_count * 2;
          FT_UInt   idx;

          for ( ; p < limit; )
          {
            idx = TT_NEXT_USHORT( p );
            if ( idx != 0 )
            {
              idx = ( idx + delta ) & 0xFFFFU;
              if ( idx >= TT_VALID_GLYPH_COUNT( valid ) )
                FT_INVALID_GLYPH_ID;
            }
          }
        }
      }
    }

    return FT_Err_Ok;
  }


ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name, gint32 *size, MonoReflectionModule **ref_module)
{
	char *n = mono_string_to_utf8 (name);
	MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
	guint32 i;
	guint32 cols [MONO_MANIFEST_SIZE];
	guint32 impl, file_idx;
	const char *val;
	MonoImage *module;

	MONO_ARCH_SAVE_REGS;

	for (i = 0; i < table->rows; ++i) {
		mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
		val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
		if (strcmp (val, n) == 0)
			break;
	}
	g_free (n);
	if (i == table->rows)
		return NULL;
	/* FIXME */
	impl = cols [MONO_MANIFEST_IMPLEMENTATION];
	if (impl) {
		/*
		 * this code should only be called after obtaining the
		 * ResourceInfo and handling the other cases.
		 */
		g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
		file_idx = impl >> MONO_IMPLEMENTATION_BITS;

		module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
		if (!module)
			return NULL;
	}
	else
		module = assembly->assembly->image;

	mono_gc_wbarrier_generic_store (ref_module, (MonoObject*) mono_module_get_object (mono_domain_get (), module));

	return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
}


do_c_expr_indent(void)
{
# ifdef FEAT_EVAL
    if (*curbuf->b_p_inde != NUL)
	fixthisline(get_expr_indent);
    else
# endif
	fixthisline(get_c_indent);
}


void ChildProcessSecurityPolicy::Add(int renderer_id) {
  AutoLock lock(lock_);
  if (security_state_.count(renderer_id) != 0) {
    NOTREACHED() << "Add renderers at most once.";
    return;
  }

  security_state_[renderer_id] = new SecurityState();
}


sysObjectID_handler(snmp_varbind_t *varbind, snmp_oid_t *oid)
{
  OID(sysObjectID_oid, 1, 3, 6, 1, 4, 1, 54352);
  snmp_api_set_oid(varbind, oid, &sysObjectID_oid);
}


int remoteDispatchClientRequest ( struct qemud_server * server , struct qemud_client * client , struct qemud_client_message * msg ) {
 int ret ;
 remote_error rerr ;
 bool qemu_call ;
 VIR_DEBUG ( "prog=%d ver=%d type=%d status=%d serial=%d proc=%d" , msg -> hdr . prog , msg -> hdr . vers , msg -> hdr . type , msg -> hdr . status , msg -> hdr . serial , msg -> hdr . proc ) ;
 memset ( & rerr , 0 , sizeof rerr ) ;
 if ( msg -> hdr . prog == REMOTE_PROGRAM ) qemu_call = false ;
 else if ( msg -> hdr . prog == QEMU_PROGRAM ) qemu_call = true ;
 else {
 remoteDispatchFormatError ( & rerr , _ ( "program mismatch (actual %x, expected %x or %x)" ) , msg -> hdr . prog , REMOTE_PROGRAM , QEMU_PROGRAM ) ;
 goto error ;
 }
 if ( ! qemu_call && msg -> hdr . vers != REMOTE_PROTOCOL_VERSION ) {
 remoteDispatchFormatError ( & rerr , _ ( "version mismatch (actual %x, expected %x)" ) , msg -> hdr . vers , REMOTE_PROTOCOL_VERSION ) ;
 goto error ;
 }
 else if ( qemu_call && msg -> hdr . vers != QEMU_PROTOCOL_VERSION ) {
 remoteDispatchFormatError ( & rerr , _ ( "version mismatch (actual %x, expected %x)" ) , msg -> hdr . vers , QEMU_PROTOCOL_VERSION ) ;
 goto error ;
 }
 switch ( msg -> hdr . type ) {
 case REMOTE_CALL : return remoteDispatchClientCall ( server , client , msg , qemu_call ) ;
 case REMOTE_STREAM : VIR_INFO ( "Ignoring unexpected stream data serial=%d proc=%d status=%d" , msg -> hdr . serial , msg -> hdr . proc , msg -> hdr . status ) ;
 qemudClientMessageRelease ( client , msg ) ;
 break ;
 default : remoteDispatchFormatError ( & rerr , _ ( "type (%d) != REMOTE_CALL" ) , ( int ) msg -> hdr . type ) ;
 goto error ;
 }
 return 0 ;
 error : ret = remoteSerializeReplyError ( client , & rerr , & msg -> hdr ) ;
 if ( ret >= 0 ) VIR_FREE ( msg ) ;
 return ret ;
 }


int cpu_x86_gen_code(uint8_t *gen_code_buf, int max_code_size,

                     int *gen_code_size_ptr,

                     uint8_t *pc_start,  uint8_t *cs_base, int flags)

{

    DisasContext dc1, *dc = &dc1;

    uint8_t *pc_ptr;

    uint16_t *gen_opc_end;

    int gen_code_size;

    long ret;

#ifdef DEBUG_DISAS

    struct disassemble_info disasm_info;

#endif

    /* generate intermediate code */

    dc->code32 = (flags >> GEN_FLAG_CODE32_SHIFT) & 1;

    dc->ss32 = (flags >> GEN_FLAG_SS32_SHIFT) & 1;

    dc->addseg = (flags >> GEN_FLAG_ADDSEG_SHIFT) & 1;

    dc->f_st = (flags >> GEN_FLAG_ST_SHIFT) & 7;

    dc->cc_op = CC_OP_DYNAMIC;

    dc->cs_base = cs_base;

    gen_opc_ptr = gen_opc_buf;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    gen_opparam_ptr = gen_opparam_buf;

    dc->is_jmp = 0;

    pc_ptr = pc_start;

    do {

        ret = disas_insn(dc, pc_ptr);

        if (ret == -1) {

            /* we trigger an illegal instruction operation only if it

               is the first instruction. Otherwise, we simply stop

               generating the code just before it */

            if (pc_ptr == pc_start)

                return -1;

            else

                break;

        }

        pc_ptr = (void *)ret;

    } while (!dc->is_jmp && gen_opc_ptr < gen_opc_end);

    /* we must store the eflags state if it is not already done */

    if (dc->cc_op != CC_OP_DYNAMIC)

        gen_op_set_cc_op(dc->cc_op);

    if (dc->is_jmp != 1) {

        /* we add an additionnal jmp to update the simulated PC */

        gen_op_jmp_im(ret - (unsigned long)dc->cs_base);

    }

    *gen_opc_ptr = INDEX_op_end;

    /* optimize flag computations */

#ifdef DEBUG_DISAS

    if (loglevel) {

        uint8_t *pc;

        int count;

        INIT_DISASSEMBLE_INFO(disasm_info, logfile, fprintf);

#if 0

        disasm_info.flavour = bfd_get_flavour (abfd);

        disasm_info.arch = bfd_get_arch (abfd);

        disasm_info.mach = bfd_get_mach (abfd);

#endif

        disasm_info.endian = BFD_ENDIAN_LITTLE;

        if (dc->code32)

            disasm_info.mach = bfd_mach_i386_i386;

        else

            disasm_info.mach = bfd_mach_i386_i8086;

        fprintf(logfile, "----------------\n");

        fprintf(logfile, "IN:\n");

        disasm_info.buffer = pc_start;

        disasm_info.buffer_vma = (unsigned long)pc_start;

        disasm_info.buffer_length = pc_ptr - pc_start;

        pc = pc_start;

        while (pc < pc_ptr) {

            fprintf(logfile, "0x%08lx:  ", (long)pc);

            count = print_insn_i386((unsigned long)pc, &disasm_info);

            fprintf(logfile, "\n");

            pc += count;

        }

        fprintf(logfile, "\n");

        fprintf(logfile, "OP:\n");

        dump_ops(gen_opc_buf);

        fprintf(logfile, "\n");

    }

#endif

    /* optimize flag computations */

    optimize_flags(gen_opc_buf, gen_opc_ptr - gen_opc_buf);

#ifdef DEBUG_DISAS

    if (loglevel) {

        fprintf(logfile, "AFTER FLAGS OPT:\n");

        dump_ops(gen_opc_buf);

        fprintf(logfile, "\n");

    }

#endif

    /* generate machine code */

    gen_code_size = dyngen_code(gen_code_buf, gen_opc_buf, gen_opparam_buf);

    flush_icache_range((unsigned long)gen_code_buf, (unsigned long)(gen_code_buf + gen_code_size));

    *gen_code_size_ptr = gen_code_size;

#ifdef DEBUG_DISAS

    if (loglevel) {

        uint8_t *pc;

        int count;

        INIT_DISASSEMBLE_INFO(disasm_info, logfile, fprintf);

#if 0

        disasm_info.flavour = bfd_get_flavour (abfd);

        disasm_info.arch = bfd_get_arch (abfd);

        disasm_info.mach = bfd_get_mach (abfd);

#endif

#ifdef WORDS_BIGENDIAN

        disasm_info.endian = BFD_ENDIAN_BIG;

#else

        disasm_info.endian = BFD_ENDIAN_LITTLE;

#endif

        disasm_info.mach = bfd_mach_i386_i386;

        pc = gen_code_buf;

        disasm_info.buffer = pc;

        disasm_info.buffer_vma = (unsigned long)pc;

        disasm_info.buffer_length = *gen_code_size_ptr;

        fprintf(logfile, "OUT: [size=%d]\n", *gen_code_size_ptr);

        while (pc < gen_code_buf + *gen_code_size_ptr) {

            fprintf(logfile, "0x%08lx:  ", (long)pc);

            count = print_insn_i386((unsigned long)pc, &disasm_info);

            fprintf(logfile, "\n");

            pc += count;

        }

        fprintf(logfile, "\n");

        fflush(logfile);

    }

#endif

    return 0;

}


void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer)
{
	int index;
	UINT32 cPackages;
	SecPkgInfoA* pPackageInfo = (SecPkgInfoA*) contextBuffer;

	cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST));

	for (index = 0; index < (int) cPackages; index++)
	{
		if (pPackageInfo[index].Name)
			free(pPackageInfo[index].Name);

		if (pPackageInfo[index].Comment)
			free(pPackageInfo[index].Comment);
	}

	free(pPackageInfo);
}


static int kvm_put_msrs ( X86CPU * cpu , int level ) {
 CPUX86State * env = & cpu -> env ;
 int i ;
 int ret ;
 kvm_msr_buf_reset ( cpu ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_SYSENTER_CS , env -> sysenter_cs ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_SYSENTER_ESP , env -> sysenter_esp ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_SYSENTER_EIP , env -> sysenter_eip ) ;
 kvm_msr_entry_add ( cpu , MSR_PAT , env -> pat ) ;
 if ( has_msr_star ) {
 kvm_msr_entry_add ( cpu , MSR_STAR , env -> star ) ;
 }
 if ( has_msr_hsave_pa ) {
 kvm_msr_entry_add ( cpu , MSR_VM_HSAVE_PA , env -> vm_hsave ) ;
 }
 if ( has_msr_tsc_aux ) {
 kvm_msr_entry_add ( cpu , MSR_TSC_AUX , env -> tsc_aux ) ;
 }
 if ( has_msr_tsc_adjust ) {
 kvm_msr_entry_add ( cpu , MSR_TSC_ADJUST , env -> tsc_adjust ) ;
 }
 if ( has_msr_misc_enable ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_MISC_ENABLE , env -> msr_ia32_misc_enable ) ;
 }
 if ( has_msr_smbase ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_SMBASE , env -> smbase ) ;
 }
 if ( has_msr_smi_count ) {
 kvm_msr_entry_add ( cpu , MSR_SMI_COUNT , env -> msr_smi_count ) ;
 }
 if ( has_msr_bndcfgs ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_BNDCFGS , env -> msr_bndcfgs ) ;
 }
 if ( has_msr_xss ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_XSS , env -> xss ) ;
 }
 if ( has_msr_spec_ctrl ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_SPEC_CTRL , env -> spec_ctrl ) ;
 }
 if ( has_msr_virt_ssbd ) {
 kvm_msr_entry_add ( cpu , MSR_VIRT_SSBD , env -> virt_ssbd ) ;
 }
 # ifdef TARGET_X86_64 if ( lm_capable_kernel ) {
 kvm_msr_entry_add ( cpu , MSR_CSTAR , env -> cstar ) ;
 kvm_msr_entry_add ( cpu , MSR_KERNELGSBASE , env -> kernelgsbase ) ;
 kvm_msr_entry_add ( cpu , MSR_FMASK , env -> fmask ) ;
 kvm_msr_entry_add ( cpu , MSR_LSTAR , env -> lstar ) ;
 }
 # endif if ( level >= KVM_PUT_RESET_STATE ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_TSC , env -> tsc ) ;
 kvm_msr_entry_add ( cpu , MSR_KVM_SYSTEM_TIME , env -> system_time_msr ) ;
 kvm_msr_entry_add ( cpu , MSR_KVM_WALL_CLOCK , env -> wall_clock_msr ) ;
 if ( env -> features [ FEAT_KVM ] & ( 1 << KVM_FEATURE_ASYNC_PF ) ) {
 kvm_msr_entry_add ( cpu , MSR_KVM_ASYNC_PF_EN , env -> async_pf_en_msr ) ;
 }
 if ( env -> features [ FEAT_KVM ] & ( 1 << KVM_FEATURE_PV_EOI ) ) {
 kvm_msr_entry_add ( cpu , MSR_KVM_PV_EOI_EN , env -> pv_eoi_en_msr ) ;
 }
 if ( env -> features [ FEAT_KVM ] & ( 1 << KVM_FEATURE_STEAL_TIME ) ) {
 kvm_msr_entry_add ( cpu , MSR_KVM_STEAL_TIME , env -> steal_time_msr ) ;
 }
 if ( has_architectural_pmu_version > 0 ) {
 if ( has_architectural_pmu_version > 1 ) {
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_FIXED_CTR_CTRL , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_CTRL , 0 ) ;
 }
 for ( i = 0 ;
 i < num_architectural_pmu_fixed_counters ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_FIXED_CTR0 + i , env -> msr_fixed_counters [ i ] ) ;
 }
 for ( i = 0 ;
 i < num_architectural_pmu_gp_counters ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_P6_PERFCTR0 + i , env -> msr_gp_counters [ i ] ) ;
 kvm_msr_entry_add ( cpu , MSR_P6_EVNTSEL0 + i , env -> msr_gp_evtsel [ i ] ) ;
 }
 if ( has_architectural_pmu_version > 1 ) {
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_STATUS , env -> msr_global_status ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_OVF_CTRL , env -> msr_global_ovf_ctrl ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_FIXED_CTR_CTRL , env -> msr_fixed_ctr_ctrl ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_CTRL , env -> msr_global_ctrl ) ;
 }
 }
 if ( current_cpu == first_cpu ) {
 if ( has_msr_hv_hypercall ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_GUEST_OS_ID , env -> msr_hv_guest_os_id ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_HYPERCALL , env -> msr_hv_hypercall ) ;
 }
 if ( cpu -> hyperv_time ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_REFERENCE_TSC , env -> msr_hv_tsc ) ;
 }
 if ( cpu -> hyperv_reenlightenment ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_REENLIGHTENMENT_CONTROL , env -> msr_hv_reenlightenment_control ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_TSC_EMULATION_CONTROL , env -> msr_hv_tsc_emulation_control ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_TSC_EMULATION_STATUS , env -> msr_hv_tsc_emulation_status ) ;
 }
 }
 if ( cpu -> hyperv_vapic ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_APIC_ASSIST_PAGE , env -> msr_hv_vapic ) ;
 }
 if ( has_msr_hv_crash ) {
 int j ;
 for ( j = 0 ;
 j < HV_CRASH_PARAMS ;
 j ++ ) kvm_msr_entry_add ( cpu , HV_X64_MSR_CRASH_P0 + j , env -> msr_hv_crash_params [ j ] ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_CRASH_CTL , HV_CRASH_CTL_NOTIFY ) ;
 }
 if ( has_msr_hv_runtime ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_VP_RUNTIME , env -> msr_hv_runtime ) ;
 }
 if ( cpu -> hyperv_synic ) {
 int j ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SVERSION , HV_SYNIC_VERSION ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SCONTROL , env -> msr_hv_synic_control ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SIEFP , env -> msr_hv_synic_evt_page ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SIMP , env -> msr_hv_synic_msg_page ) ;
 for ( j = 0 ;
 j < ARRAY_SIZE ( env -> msr_hv_synic_sint ) ;
 j ++ ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SINT0 + j , env -> msr_hv_synic_sint [ j ] ) ;
 }
 }
 if ( has_msr_hv_stimer ) {
 int j ;
 for ( j = 0 ;
 j < ARRAY_SIZE ( env -> msr_hv_stimer_config ) ;
 j ++ ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_STIMER0_CONFIG + j * 2 , env -> msr_hv_stimer_config [ j ] ) ;
 }
 for ( j = 0 ;
 j < ARRAY_SIZE ( env -> msr_hv_stimer_count ) ;
 j ++ ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_STIMER0_COUNT + j * 2 , env -> msr_hv_stimer_count [ j ] ) ;
 }
 }
 if ( env -> features [ FEAT_1_EDX ] & CPUID_MTRR ) {
 uint64_t phys_mask = MAKE_64BIT_MASK ( 0 , cpu -> phys_bits ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRdefType , env -> mtrr_deftype ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix64K_00000 , env -> mtrr_fixed [ 0 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix16K_80000 , env -> mtrr_fixed [ 1 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix16K_A0000 , env -> mtrr_fixed [ 2 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_C0000 , env -> mtrr_fixed [ 3 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_C8000 , env -> mtrr_fixed [ 4 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_D0000 , env -> mtrr_fixed [ 5 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_D8000 , env -> mtrr_fixed [ 6 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_E0000 , env -> mtrr_fixed [ 7 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_E8000 , env -> mtrr_fixed [ 8 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_F0000 , env -> mtrr_fixed [ 9 ] ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_F8000 , env -> mtrr_fixed [ 10 ] ) ;
 for ( i = 0 ;
 i < MSR_MTRRcap_VCNT ;
 i ++ ) {
 uint64_t mask = env -> mtrr_var [ i ] . mask ;
 mask &= phys_mask ;
 kvm_msr_entry_add ( cpu , MSR_MTRRphysBase ( i ) , env -> mtrr_var [ i ] . base ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRphysMask ( i ) , mask ) ;
 }
 }
 if ( env -> features [ FEAT_7_0_EBX ] & CPUID_7_0_EBX_INTEL_PT ) {
 int addr_num = kvm_arch_get_supported_cpuid ( kvm_state , 0x14 , 1 , R_EAX ) & 0x7 ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_CTL , env -> msr_rtit_ctrl ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_STATUS , env -> msr_rtit_status ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_OUTPUT_BASE , env -> msr_rtit_output_base ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_OUTPUT_MASK , env -> msr_rtit_output_mask ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_CR3_MATCH , env -> msr_rtit_cr3_match ) ;
 for ( i = 0 ;
 i < addr_num ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_ADDR0_A + i , env -> msr_rtit_addrs [ i ] ) ;
 }
 }
 }
 if ( env -> mcg_cap ) {
 int i ;
 kvm_msr_entry_add ( cpu , MSR_MCG_STATUS , env -> mcg_status ) ;
 kvm_msr_entry_add ( cpu , MSR_MCG_CTL , env -> mcg_ctl ) ;
 if ( has_msr_mcg_ext_ctl ) {
 kvm_msr_entry_add ( cpu , MSR_MCG_EXT_CTL , env -> mcg_ext_ctl ) ;
 }
 for ( i = 0 ;
 i < ( env -> mcg_cap & 0xff ) * 4 ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_MC0_CTL + i , env -> mce_banks [ i ] ) ;
 }
 }
 ret = kvm_vcpu_ioctl ( CPU ( cpu ) , KVM_SET_MSRS , cpu -> kvm_msr_buf ) ;
 if ( ret < 0 ) {
 return ret ;
 }
 if ( ret < cpu -> kvm_msr_buf -> nmsrs ) {
 struct kvm_msr_entry * e = & cpu -> kvm_msr_buf -> entries [ ret ] ;
 error_report ( "error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64 , ( uint32_t ) e -> index , ( uint64_t ) e -> data ) ;
 }
 assert ( ret == cpu -> kvm_msr_buf -> nmsrs ) ;
 return 0 ;
 }


find_or_create_image(GraphicsManager *self, uint32_t id, bool *existing) {
    if (id) {
        for (size_t i = 0; i < self->image_count; i++) {
            if (self->images[i].client_id == id) {
                *existing = true;
                return self->images + i;
            }
        }
    }
    *existing = false;
    ensure_space_for(self, images, Image, self->image_count + 1, images_capacity, 64, true);
    Image *ans = self->images + self->image_count++;
    zero_at_ptr(ans);
    return ans;
}


static void destruct(struct dcn20_resource_pool *pool)
{
	unsigned int i;

	for (i = 0; i < pool->base.stream_enc_count; i++) {
		if (pool->base.stream_enc[i] != NULL) {
			kfree(DCN10STRENC_FROM_STRENC(pool->base.stream_enc[i]));
			pool->base.stream_enc[i] = NULL;
		}
	}

#ifdef CONFIG_DRM_AMD_DC_DSC_SUPPORT
	for (i = 0; i < pool->base.res_cap->num_dsc; i++) {
		if (pool->base.dscs[i] != NULL)
			dcn20_dsc_destroy(&pool->base.dscs[i]);
	}
#endif

	if (pool->base.mpc != NULL) {
		kfree(TO_DCN20_MPC(pool->base.mpc));
		pool->base.mpc = NULL;
	}
	if (pool->base.hubbub != NULL) {
		kfree(pool->base.hubbub);
		pool->base.hubbub = NULL;
	}
	for (i = 0; i < pool->base.pipe_count; i++) {
		if (pool->base.dpps[i] != NULL)
			dcn20_dpp_destroy(&pool->base.dpps[i]);

		if (pool->base.ipps[i] != NULL)
			pool->base.ipps[i]->funcs->ipp_destroy(&pool->base.ipps[i]);

		if (pool->base.hubps[i] != NULL) {
			kfree(TO_DCN20_HUBP(pool->base.hubps[i]));
			pool->base.hubps[i] = NULL;
		}

		if (pool->base.irqs != NULL) {
			dal_irq_service_destroy(&pool->base.irqs);
		}
	}

	for (i = 0; i < pool->base.res_cap->num_ddc; i++) {
		if (pool->base.engines[i] != NULL)
			dce110_engine_destroy(&pool->base.engines[i]);
		if (pool->base.hw_i2cs[i] != NULL) {
			kfree(pool->base.hw_i2cs[i]);
			pool->base.hw_i2cs[i] = NULL;
		}
		if (pool->base.sw_i2cs[i] != NULL) {
			kfree(pool->base.sw_i2cs[i]);
			pool->base.sw_i2cs[i] = NULL;
		}
	}

	for (i = 0; i < pool->base.res_cap->num_opp; i++) {
		if (pool->base.opps[i] != NULL)
			pool->base.opps[i]->funcs->opp_destroy(&pool->base.opps[i]);
	}

	for (i = 0; i < pool->base.res_cap->num_timing_generator; i++) {
		if (pool->base.timing_generators[i] != NULL)	{
			kfree(DCN10TG_FROM_TG(pool->base.timing_generators[i]));
			pool->base.timing_generators[i] = NULL;
		}
	}

	for (i = 0; i < pool->base.res_cap->num_dwb; i++) {
		if (pool->base.dwbc[i] != NULL) {
			kfree(TO_DCN20_DWBC(pool->base.dwbc[i]));
			pool->base.dwbc[i] = NULL;
		}
		if (pool->base.mcif_wb[i] != NULL) {
			kfree(TO_DCN20_MMHUBBUB(pool->base.mcif_wb[i]));
			pool->base.mcif_wb[i] = NULL;
		}
	}

	for (i = 0; i < pool->base.audio_count; i++) {
		if (pool->base.audios[i])
			dce_aud_destroy(&pool->base.audios[i]);
	}

	for (i = 0; i < pool->base.clk_src_count; i++) {
		if (pool->base.clock_sources[i] != NULL) {
			dcn20_clock_source_destroy(&pool->base.clock_sources[i]);
			pool->base.clock_sources[i] = NULL;
		}
	}

	if (pool->base.dp_clock_source != NULL) {
		dcn20_clock_source_destroy(&pool->base.dp_clock_source);
		pool->base.dp_clock_source = NULL;
	}

	if (pool->base.abm != NULL)
		dce_abm_destroy(&pool->base.abm);

	if (pool->base.dmcu != NULL)
		dce_dmcu_destroy(&pool->base.dmcu);

	if (pool->base.dccg != NULL)
		dcn_dccg_destroy(&pool->base.dccg);

	if (pool->base.pp_smu != NULL)
		dcn20_pp_smu_destroy(&pool->base.pp_smu);

}


void WebBluetoothServiceImpl::RemoteCharacteristicGetDescriptors(
    const std::string& characteristic_instance_id,
    blink::mojom::WebBluetoothGATTQueryQuantity quantity,
    const base::Optional<BluetoothUUID>& descriptors_uuid,
    RemoteCharacteristicGetDescriptorsCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  RecordGetDescriptorsDescriptor(quantity, descriptors_uuid);

  if (descriptors_uuid &&
      BluetoothBlocklist::Get().IsExcluded(descriptors_uuid.value())) {
    RecordGetDescriptorsOutcome(quantity, UMAGetDescriptorOutcome::BLOCKLISTED);
    std::move(callback).Run(
        blink::mojom::WebBluetoothResult::BLOCKLISTED_DESCRIPTOR_UUID,
        base::nullopt /* descriptor */);
    return;
  }

  const CacheQueryResult query_result =
      QueryCacheForCharacteristic(characteristic_instance_id);

  if (query_result.outcome == CacheQueryOutcome::BAD_RENDERER) {
    return;
  }

  if (query_result.outcome != CacheQueryOutcome::SUCCESS) {
    RecordGetDescriptorsOutcome(quantity, query_result.outcome);
    std::move(callback).Run(query_result.GetWebResult(),
                            base::nullopt /* descriptor */);
    return;
  }

  auto descriptors = descriptors_uuid
                         ? query_result.characteristic->GetDescriptorsByUUID(
                               descriptors_uuid.value())
                         : query_result.characteristic->GetDescriptors();

  std::vector<blink::mojom::WebBluetoothRemoteGATTDescriptorPtr>
      response_descriptors;
  for (device::BluetoothRemoteGattDescriptor* descriptor : descriptors) {
    if (BluetoothBlocklist::Get().IsExcluded(descriptor->GetUUID())) {
      continue;
    }
    std::string descriptor_instance_id = descriptor->GetIdentifier();
    auto insert_result = descriptor_id_to_characteristic_id_.insert(
        {descriptor_instance_id, characteristic_instance_id});
    if (!insert_result.second)
      DCHECK(insert_result.first->second == characteristic_instance_id);

    auto descriptor_ptr(blink::mojom::WebBluetoothRemoteGATTDescriptor::New());
    descriptor_ptr->instance_id = descriptor_instance_id;
    descriptor_ptr->uuid = descriptor->GetUUID();
    response_descriptors.push_back(std::move(descriptor_ptr));

    if (quantity == blink::mojom::WebBluetoothGATTQueryQuantity::SINGLE) {
      break;
    }
  }

  if (!response_descriptors.empty()) {
    RecordGetDescriptorsOutcome(quantity, UMAGetDescriptorOutcome::SUCCESS);
    std::move(callback).Run(blink::mojom::WebBluetoothResult::SUCCESS,
                            std::move(response_descriptors));
    return;
  }
  RecordGetDescriptorsOutcome(
      quantity, descriptors_uuid ? UMAGetDescriptorOutcome::NOT_FOUND
                                 : UMAGetDescriptorOutcome::NO_DESCRIPTORS);
  std::move(callback).Run(
      descriptors_uuid ? blink::mojom::WebBluetoothResult::DESCRIPTOR_NOT_FOUND
                       : blink::mojom::WebBluetoothResult::NO_DESCRIPTORS_FOUND,
      base::nullopt /* descriptors */);
}


void ff_qsv_decode_reset(AVCodecContext *avctx, QSVContext *q)

{

    QSVFrame *cur;

    AVPacket pkt;

    int ret = 0;

    mfxVideoParam param = { { 0 } };

    if (q->reinit_pending) {

        close_decoder(q);

    } else if (q->engine_ready) {

        ret = MFXVideoDECODE_GetVideoParam(q->session, &param);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "MFX decode get param error %d\n", ret);

        }

        ret = MFXVideoDECODE_Reset(q->session, &param);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "MFX decode reset error %d\n", ret);

        }

        /* Free all frames*/

        cur = q->work_frames;

        while (cur) {

            q->work_frames = cur->next;

            av_frame_free(&cur->frame);

            av_freep(&cur);

            cur = q->work_frames;

        }

    }

    /* Reset output surfaces */

    av_fifo_reset(q->async_fifo);

    /* Reset input packets fifo */

    while (av_fifo_size(q->pkt_fifo)) {

        av_fifo_generic_read(q->pkt_fifo, &pkt, sizeof(pkt), NULL);

        av_packet_unref(&pkt);

    }

    /* Reset input bitstream fifo */

    av_fifo_reset(q->input_fifo);

}


static void init_reg_state(struct bpf_verifier_env *env,
			   struct bpf_func_state *state)
{
	struct bpf_reg_state *regs = state->regs;
	int i;

	for (i = 0; i < MAX_BPF_REG; i++) {
		mark_reg_not_init(env, regs, i);
		regs[i].live = REG_LIVE_NONE;
		regs[i].parent = NULL;
	}

	/* frame pointer */
	regs[BPF_REG_FP].type = PTR_TO_STACK;
	mark_reg_known_zero(env, regs, BPF_REG_FP);
	regs[BPF_REG_FP].frameno = state->frameno;

	/* 1st arg to a function */
	regs[BPF_REG_1].type = PTR_TO_CTX;
	mark_reg_known_zero(env, regs, BPF_REG_1);
}


bool xmp_set_array_item(XmpPtr xmp, const char *schema, const char *name,
                        int32_t index, const char *value, uint32_t optionBits)
{
    CHECK_PTR(xmp, false);
    RESET_ERROR;

    bool ret = false;
    auto txmp = reinterpret_cast<SXMPMeta *>(xmp);
    try {
        txmp->SetArrayItem(schema, name, index, value, optionBits);
        ret = true;
    }
    catch (const XMP_Error &e) {
        set_error(e);
    }
    catch (...) {
    }
    return ret;
}


size_t jsvGetString(const JsVar *v, char *str, size_t len) {
  assert(len>0);
  const char *s = jsvGetConstString(v);
  if (s) {
    /* don't use strncpy here because we don't
      * want to pad the entire buffer with zeros */
     len--;
     int l = 0;
    while (s[l] && l<len) {
       str[l] = s[l];
       l++;
     }
    str[l] = 0;
    return l;
  } else if (jsvIsInt(v)) {
    itostr(v->varData.integer, str, 10);
    return strlen(str);
  } else if (jsvIsFloat(v)) {
    ftoa_bounded(v->varData.floating, str, len);
    return strlen(str);
  } else if (jsvHasCharacterData(v)) {
    assert(!jsvIsStringExt(v));
    size_t l = len;
    JsvStringIterator it;
    jsvStringIteratorNewConst(&it, v, 0);
    while (jsvStringIteratorHasChar(&it)) {
      if (l--<=1) {
        *str = 0;
        jsvStringIteratorFree(&it);
        return len;
      }
      *(str++) = jsvStringIteratorGetChar(&it);
      jsvStringIteratorNext(&it);
    }
    jsvStringIteratorFree(&it);
    *str = 0;
    return len-l;
  } else {
    JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
    if (stringVar) {
      size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
      jsvUnLock(stringVar);
      return l;
    } else {
      str[0] = 0;
      jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
      return 0;
    }
  }
}


lseg_parallel(PG_FUNCTION_ARGS)
{
	LSEG	   *l1 = PG_GETARG_LSEG_P(0);
	LSEG	   *l2 = PG_GETARG_LSEG_P(1);

#ifdef NOT_USED
	PG_RETURN_BOOL(FPeq(l1->m, l2->m));
#endif
	PG_RETURN_BOOL(FPeq(point_sl(&l1->p[0], &l1->p[1]),
						point_sl(&l2->p[0], &l2->p[1])));
}


void mark_client_saved_ready(ClientPtr client)
{
    if (xorg_list_is_empty(&client->ready))
        xorg_list_append(&client->ready, &saved_ready_clients);
}


avifResult avifDecoderNthImage(avifDecoder * decoder, uint32_t frameIndex)
{
    int requestedIndex = (int)frameIndex;
    if (requestedIndex == decoder->imageIndex) {
        // We're here already, nothing to do
        return AVIF_RESULT_OK;
    }

    if (requestedIndex == (decoder->imageIndex + 1)) {
        // it's just the next image, nothing special here
        return avifDecoderNextImage(decoder);
    }

    if (requestedIndex >= decoder->imageCount) {
        // Impossible index
        return AVIF_RESULT_NO_IMAGES_REMAINING;
    }

    // If we get here, a decoder flush is necessary
    decoder->imageIndex = ((int)avifDecoderNearestKeyframe(decoder, frameIndex)) - 1; // prepare to read nearest keyframe
    avifDecoderFlush(decoder);
    for (;;) {
        avifResult result = avifDecoderNextImage(decoder);
        if (result != AVIF_RESULT_OK) {
            return result;
        }

        if (requestedIndex == decoder->imageIndex) {
            break;
        }
    }
    return AVIF_RESULT_OK;
}


bool Resource::MustRevalidateDueToCacheHeaders() const {
  return !CanUseResponse(GetResponse(), response_timestamp_) ||
         GetResourceRequest().CacheControlContainsNoCache() ||
         GetResourceRequest().CacheControlContainsNoStore();
}


struct evhttp_connection * evhttp_request_get_connection ( struct evhttp_request * req ) {
 return req -> evcon ;
 }


void usb_device_attach(USBDevice *dev, Error **errp)

{

    USBBus *bus = usb_bus_from_device(dev);

    USBPort *port = dev->port;

    char devspeed[32], portspeed[32];

    assert(port != NULL);

    assert(!dev->attached);

    usb_mask_to_str(devspeed, sizeof(devspeed), dev->speedmask);

    usb_mask_to_str(portspeed, sizeof(portspeed), port->speedmask);

    trace_usb_port_attach(bus->busnr, port->path,

                          devspeed, portspeed);

    if (!(port->speedmask & dev->speedmask)) {

        error_setg(errp, "Warning: speed mismatch trying to attach"

                   " usb device \"%s\" (%s speed)"

                   " to bus \"%s\", port \"%s\" (%s speed)",

                   dev->product_desc, devspeed,

                   bus->qbus.name, port->path, portspeed);

        return;

    }

    dev->attached++;

    usb_attach(port);

}


static void ssl_update_checksum_sha384( ssl_context *ssl, unsigned char *buf,
                                        size_t len )
{
    sha4_update( &ssl->handshake->fin_sha4, buf, len );
}


IndexedDBTransaction::TaskStack::~TaskStack() { clear(); }


static u32 rateset_to_mask(struct ieee80211_supported_band *sband,
			   u8 *rates, u8 rates_len)
{
	u8 i;
	u32 mask = 0;

	for (i = 0; i < rates_len; i++) {
		int rate = (rates[i] & 0x7f) * 5;
		int ridx;
		for (ridx = 0; ridx < sband->n_bitrates; ridx++) {
			struct ieee80211_rate *srate =
				&sband->bitrates[ridx];
			if (rate == srate->bitrate) {
				mask |= 1 << ridx;
				break;
			}
		}
		if (ridx == sband->n_bitrates)
			return 0; /* rate not found */
	}

	return mask;


void InputDispatcher::monitor() {
    mLock.lock();
    mLooper->wake();
    mDispatcherIsAliveCondition.wait(mLock);
    mLock.unlock();
}


static void binder_free_ref(struct binder_ref *ref)
{
	if (ref->node)
		binder_free_node(ref->node);
	kfree(ref->death);
	kfree(ref);
}


static int _compare_path_table_joliet ( const void * v1 , const void * v2 ) {
 const struct isoent * p1 , * p2 ;
 const unsigned char * s1 , * s2 ;
 int cmp , l ;
 p1 = * ( ( const struct isoent * * ) ( uintptr_t ) v1 ) ;
 p2 = * ( ( const struct isoent * * ) ( uintptr_t ) v2 ) ;
 cmp = p1 -> parent -> dir_number - p2 -> parent -> dir_number ;
 if ( cmp != 0 ) return ( cmp ) ;
 s1 = ( const unsigned char * ) p1 -> identifier ;
 s2 = ( const unsigned char * ) p2 -> identifier ;
 l = p1 -> ext_off ;
 if ( l > p2 -> ext_off ) l = p2 -> ext_off ;
 cmp = memcmp ( s1 , s2 , l ) ;
 if ( cmp != 0 ) return ( cmp ) ;
 if ( p1 -> ext_off < p2 -> ext_off ) {
 s2 += l ;
 l = p2 -> ext_off - p1 -> ext_off ;
 while ( l -- ) if ( 0 != * s2 ++ ) return ( - * ( const unsigned char * ) ( s2 - 1 ) ) ;
 }
 else if ( p1 -> ext_off > p2 -> ext_off ) {
 s1 += l ;
 l = p1 -> ext_off - p2 -> ext_off ;
 while ( l -- ) if ( 0 != * s1 ++ ) return ( * ( const unsigned char * ) ( s1 - 1 ) ) ;
 }
 return ( 0 ) ;
 }


size_t tls12_get_psigalgs(SSL *s, int sent, const unsigned char **psigs)
{
    /*
     * If Suite B mode use Suite B sigalgs only, ignore any other
     * preferences.
     */
#ifndef OPENSSL_NO_EC
    switch (tls1_suiteb(s)) {
    case SSL_CERT_FLAG_SUITEB_128_LOS:
        *psigs = suiteb_sigalgs;
        return sizeof(suiteb_sigalgs);

    case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
        *psigs = suiteb_sigalgs;
        return 2;

    case SSL_CERT_FLAG_SUITEB_192_LOS:
        *psigs = suiteb_sigalgs + 2;
        return 2;
    }
#endif
    /* If server use client authentication sigalgs if not NULL */
    if (s->server == sent && s->cert->client_sigalgs) {
        *psigs = s->cert->client_sigalgs;
        return s->cert->client_sigalgslen;
    } else if (s->cert->conf_sigalgs) {
        *psigs = s->cert->conf_sigalgs;
        return s->cert->conf_sigalgslen;
    } else {
        *psigs = tls12_sigalgs;
        return sizeof(tls12_sigalgs);
    }
}


process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
{
	char buf[PATH_MAX];
	int r;

	if (config != NULL) {
		if (strcasecmp(config, "none") != 0 &&
		    !read_config_file(config, pw, host, host_arg, &options,
		    SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
			fatal("Can't open user config file %.100s: "
			    "%.100s", config, strerror(errno));
	} else {
		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
		    _PATH_SSH_USER_CONFFILE);
		if (r > 0 && (size_t)r < sizeof(buf))
			(void)read_config_file(buf, pw, host, host_arg,
			    &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
			    (post_canon ? SSHCONF_POSTCANON : 0));

		/* Read systemwide configuration file after user config. */
		(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
		    host, host_arg, &options,
		    post_canon ? SSHCONF_POSTCANON : 0);
	}
}


bool Extension::LoadName(string16* error) {
  string16 localized_name;
  if (!manifest_->GetString(keys::kName, &localized_name)) {
    *error = ASCIIToUTF16(errors::kInvalidName);
    return false;
  }
  non_localized_name_ = UTF16ToUTF8(localized_name);
  base::i18n::AdjustStringForLocaleDirection(&localized_name);
  name_ = UTF16ToUTF8(localized_name);
  return true;
}


static cmsBool SaveOneChromaticity ( cmsFloat64Number x , cmsFloat64Number y , cmsIOHANDLER * io ) {
 if ( ! _cmsWriteUInt32Number ( io , _cmsDoubleTo15Fixed16 ( x ) ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , _cmsDoubleTo15Fixed16 ( y ) ) ) return FALSE ;
 return TRUE ;
 }


table_regex_match(const char *string, const char *pattern)
{
	regex_t preg;
	int	cflags = REG_EXTENDED|REG_NOSUB;
	int ret;

	if (strncmp(pattern, "(?i)", 4) == 0) {
		cflags |= REG_ICASE;
		pattern += 4;
	}

	if (regcomp(&preg, pattern, cflags) != 0)
		return (0);

	ret = regexec(&preg, string, 0, NULL, 0);

	regfree(&preg);

	if (ret != 0)
		return (0);

	return (1);
}


void GlobalHistogramAllocator::ConstructFilePathsForUploadDir(
    const FilePath& active_dir,
    const FilePath& upload_dir,
    const std::string& name,
    FilePath* out_upload_path,
    FilePath* out_active_path,
    FilePath* out_spare_path) {
  if (out_upload_path) {
    *out_upload_path = ConstructFilePathForUploadDir(
        upload_dir, name, Time::Now(), GetCurrentProcId());
  }

  if (out_active_path) {
    *out_active_path =
        ConstructFilePath(active_dir, name + std::string("-active"));
  }

  if (out_spare_path) {
    *out_spare_path =
        ConstructFilePath(active_dir, name + std::string("-spare"));
  }
}


status_t Parcel::readIntPtr(intptr_t *pArg) const
{
 return readAligned(pArg);
}


pch_name (enum nametype type)
{
  return type == NONE ? NULL : p_name[type];
}


std::string Instance::GetLocalizedString(PP_ResourceString id) {
  pp::Var rv(pp::PDF::GetLocalizedString(this, id));
  if (!rv.is_string())
    return std::string();

  return rv.AsString();
}


void SoundChannel::nextEvent()
{
    sp<Sample> sample;
 int nextChannelID;
 float leftVolume;
 float rightVolume;
 int priority;
 int loop;
 float rate;

 {
 Mutex::Autolock lock(&mLock);
        nextChannelID = mNextEvent.channelID();
 if (nextChannelID  == 0) {
            ALOGV("stolen channel has no event");
 return;
 }

        sample = mNextEvent.sample();
        leftVolume = mNextEvent.leftVolume();
        rightVolume = mNextEvent.rightVolume();
        priority = mNextEvent.priority();
        loop = mNextEvent.loop();
        rate = mNextEvent.rate();
 }

    ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
    play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
}


static int netlink_getsockopt(struct socket *sock, int level, int optname,
			      char __user *optval, int __user *optlen)
{
	struct sock *sk = sock->sk;
	struct netlink_sock *nlk = nlk_sk(sk);
	int len, val, err;

	if (level != SOL_NETLINK)
		return -ENOPROTOOPT;

	if (get_user(len, optlen))
		return -EFAULT;
	if (len < 0)
		return -EINVAL;

	switch (optname) {
	case NETLINK_PKTINFO:
		if (len < sizeof(int))
			return -EINVAL;
		len = sizeof(int);
		val = nlk->flags & NETLINK_F_RECV_PKTINFO ? 1 : 0;
		if (put_user(len, optlen) ||
		    put_user(val, optval))
			return -EFAULT;
		err = 0;
		break;
	case NETLINK_BROADCAST_ERROR:
		if (len < sizeof(int))
			return -EINVAL;
		len = sizeof(int);
		val = nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR ? 1 : 0;
		if (put_user(len, optlen) ||
		    put_user(val, optval))
			return -EFAULT;
		err = 0;
		break;
	case NETLINK_NO_ENOBUFS:
		if (len < sizeof(int))
			return -EINVAL;
		len = sizeof(int);
		val = nlk->flags & NETLINK_F_RECV_NO_ENOBUFS ? 1 : 0;
		if (put_user(len, optlen) ||
		    put_user(val, optval))
			return -EFAULT;
		err = 0;
		break;
	case NETLINK_LIST_MEMBERSHIPS: {
		int pos, idx, shift;

		err = 0;
		netlink_lock_table();
		for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
			if (len - pos < sizeof(u32))
				break;

			idx = pos / sizeof(unsigned long);
			shift = (pos % sizeof(unsigned long)) * 8;
			if (put_user((u32)(nlk->groups[idx] >> shift),
				     (u32 __user *)(optval + pos))) {
				err = -EFAULT;
				break;
			}
		}
		if (put_user(ALIGN(nlk->ngroups / 8, sizeof(u32)), optlen))
			err = -EFAULT;
		netlink_unlock_table();
		break;
	}
	case NETLINK_CAP_ACK:
		if (len < sizeof(int))
			return -EINVAL;
		len = sizeof(int);
		val = nlk->flags & NETLINK_F_CAP_ACK ? 1 : 0;
		if (put_user(len, optlen) ||
		    put_user(val, optval))
			return -EFAULT;
		err = 0;
		break;
	default:
		err = -ENOPROTOOPT;
	}
	return err;
}


R_API st64 r_buf_fwrite_at(RBuffer *b, ut64 addr, const ut8 *buf, const char *fmt, int n) {
	r_return_val_if_fail (b && buf && fmt && !b->readonly, -1);
	st64 o_addr = r_buf_seek (b, 0, R_BUF_CUR);
	st64 r = r_buf_seek (b, addr, R_BUF_SET);
	if (r < 0) {
		return r;
	}
	r = r_buf_fwrite (b, buf, fmt, n);
	r_buf_seek (b, o_addr, R_BUF_SET);
	return r;
}


static void encode_frame(vpx_codec_ctx_t *codec,
static int encode_frame(vpx_codec_ctx_t *codec,
                        vpx_image_t *img,
                        int frame_index,
                        int flags,
                        VpxVideoWriter *writer) {
  int got_pkts = 0;
   vpx_codec_iter_t iter = NULL;
   const vpx_codec_cx_pkt_t *pkt = NULL;
   const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1,
                                               flags, VPX_DL_GOOD_QUALITY);
 if (res != VPX_CODEC_OK)

     die_codec(codec, "Failed to encode frame");

   while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
    got_pkts = 1;

     if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
       const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
       if (!vpx_video_writer_write_frame(writer,
                                        pkt->data.frame.buf,
                                        pkt->data.frame.sz,

                                         pkt->data.frame.pts)) {
         die_codec(codec, "Failed to write compressed frame");
       }
       printf(keyframe ? "K" : ".");
       fflush(stdout);
     }
   }

  return got_pkts;
 }