static bool reconstruct_chained_fixup(struct MACH0_(obj_t) *bin) {
	if (!bin->dyld_info) {
		return false;
	}
	if (!bin->nsegs) {
		return false;
	}
	bin->chained_starts = R_NEWS0 (struct r_dyld_chained_starts_in_segment *, bin->nsegs);
	if (!bin->chained_starts) {
		return false;
	}
	size_t wordsize = get_word_size (bin);
	ut8 *p = NULL;
	size_t j, count, skip, bind_size;
	int seg_idx = 0;
	ut64 seg_off = 0;
	bind_size = bin->dyld_info->bind_size;
	if (!bind_size || bind_size < 1) {
		return false;
	}
	if (bin->dyld_info->bind_off > bin->size) {
		return false;
	}
	if (bin->dyld_info->bind_off + bind_size > bin->size) {
		return false;
	}
	ut8 *opcodes = calloc (1, bind_size + 1);
	if (!opcodes) {
		return false;
	}
	if (r_buf_read_at (bin->b, bin->dyld_info->bind_off, opcodes, bind_size) != bind_size) {
		bprintf ("Error: read (dyld_info bind) at 0x%08"PFMT64x"\n", (ut64)(size_t)bin->dyld_info->bind_off);
		R_FREE (opcodes);
		return false;
	}
	struct r_dyld_chained_starts_in_segment *cur_seg = NULL;
	size_t cur_seg_idx = 0;
	ut8 *end;
	bool done = false;
	for (p = opcodes, end = opcodes + bind_size; !done && p < end;) {
		ut8 imm = *p & BIND_IMMEDIATE_MASK, op = *p & BIND_OPCODE_MASK;
		p++;
		switch (op) {
		case BIND_OPCODE_DONE:
			done = true;
			break;
		case BIND_OPCODE_THREADED: {
			switch (imm) {
			case BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB: {
				read_uleb128 (&p, end);
				break;
			}
			case BIND_SUBOPCODE_THREADED_APPLY: {
				const size_t ps = 0x1000;
				if (!cur_seg || cur_seg_idx != seg_idx) {
					cur_seg_idx = seg_idx;
					cur_seg = bin->chained_starts[seg_idx];
					if (!cur_seg) {
						cur_seg = R_NEW0 (struct r_dyld_chained_starts_in_segment);
						if (!cur_seg) {
							break;
						}
						bin->chained_starts[seg_idx] = cur_seg;
						cur_seg->pointer_format = DYLD_CHAINED_PTR_ARM64E;
						cur_seg->page_size = ps;
						cur_seg->page_count = ((bin->segs[seg_idx].vmsize + (ps - 1)) & ~(ps - 1)) / ps;
						if (cur_seg->page_count > 0) {
							cur_seg->page_start = malloc (sizeof (ut16) * cur_seg->page_count);
							if (!cur_seg->page_start) {
								break;
							}
							memset (cur_seg->page_start, 0xff, sizeof (ut16) * cur_seg->page_count);
						}
					}
				}
				if (cur_seg) {
					ut32 page_index = (ut32)(seg_off / ps);
					size_t maxsize = cur_seg->page_count * sizeof (ut16);
					if (page_index < maxsize && cur_seg->page_start) {
						cur_seg->page_start[page_index] = seg_off & 0xfff;
					}
				}
				break;
			}
			default:
				bprintf ("Error: Unexpected BIND_OPCODE_THREADED sub-opcode: 0x%x\n", imm);
			}
			break;
		}
		case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
		case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
		case BIND_OPCODE_SET_TYPE_IMM:
			break;
		case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
			read_uleb128 (&p, end);
			break;
		case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
			while (*p++ && p < end) {
				/* empty loop */
			}
			break;
		case BIND_OPCODE_SET_ADDEND_SLEB:
			r_sleb128 ((const ut8 **)&p, end);
			break;
		case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
			seg_idx = imm;
			if (seg_idx >= bin->nsegs) {
				bprintf ("Error: BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB"
					" has unexistent segment %d\n", seg_idx);
				R_FREE (opcodes);
				return false;
			} else {
				seg_off = read_uleb128 (&p, end);
			}
			break;
		case BIND_OPCODE_ADD_ADDR_ULEB:
			seg_off += read_uleb128 (&p, end);
			break;
		case BIND_OPCODE_DO_BIND:
			break;
		case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
			seg_off += read_uleb128 (&p, end) + wordsize;
			break;
		case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
			seg_off += (ut64)imm * (ut64)wordsize + wordsize;
			break;
		case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
			count = read_uleb128 (&p, end);
			skip = read_uleb128 (&p, end);
			for (j = 0; j < count; j++) {
				seg_off += skip + wordsize;
			}
			break;
		default:
			bprintf ("Error: unknown bind opcode 0x%02x in dyld_info\n", *p);
			R_FREE (opcodes);
			return false;
		}
	}
	R_FREE (opcodes);

	return true;
}


bool IsTabDraggingSourceWindow(aura::Window* window) {
  if (!window)
    return false;

  MruWindowTracker::WindowList window_list =
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk);
  if (window_list.empty())
    return false;

  aura::Window* dragged_window = nullptr;
  for (auto* window : window_list) {
    if (wm::IsDraggingTabs(window)) {
      dragged_window = window;
      break;
    }
  }
  if (!dragged_window)
    return false;

  return dragged_window->GetProperty(ash::kTabDraggingSourceWindowKey) ==
         window;
}


Response PageHandler::ScreencastFrameAck(int session_id) {
  if (session_id == session_id_)
    --frames_in_flight_;
  return Response::OK();
}


numstr(int x)
{
	static char buf[20];

	snprintf(buf, sizeof(buf), "%#x", x);
	return buf;
}


static int srec_sizeof_headers ( bfd * abfd ATTRIBUTE_UNUSED , struct bfd_link_info * info ATTRIBUTE_UNUSED ) {
 return 0 ;
 }


std::unique_ptr<NavigationRequest> NavigationRequest::CreateBrowserInitiated(
    FrameTreeNode* frame_tree_node,
    const GURL& dest_url,
    const Referrer& dest_referrer,
    const FrameNavigationEntry& frame_entry,
    const NavigationEntryImpl& entry,
    FrameMsg_Navigate_Type::Value navigation_type,
    PreviewsState previews_state,
    bool is_same_document_history_load,
    bool is_history_navigation_in_new_child,
    const scoped_refptr<network::ResourceRequestBody>& post_body,
    const base::TimeTicks& navigation_start,
    NavigationControllerImpl* controller,
    std::unique_ptr<NavigationUIData> navigation_ui_data) {
  scoped_refptr<network::ResourceRequestBody> request_body;
  std::string post_content_type;
  if (post_body) {
    request_body = post_body;
  } else if (frame_entry.method() == "POST") {
    request_body = frame_entry.GetPostData(&post_content_type);
    post_content_type =
        base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL)
            .as_string();
  }
  bool is_form_submission = !!request_body;

  base::Optional<url::Origin> initiator =
      frame_tree_node->IsMainFrame()
          ? base::Optional<url::Origin>()
          : base::Optional<url::Origin>(
                frame_tree_node->frame_tree()->root()->current_origin());

  bool browser_initiated = !entry.is_renderer_initiated();

  CommonNavigationParams common_params = entry.ConstructCommonNavigationParams(
      frame_entry, request_body, dest_url, dest_referrer, navigation_type,
      previews_state, navigation_start);

  RequestNavigationParams request_params =
      entry.ConstructRequestNavigationParams(
          frame_entry, common_params.url, common_params.method,
          is_history_navigation_in_new_child,
          entry.GetSubframeUniqueNames(frame_tree_node),
          controller->GetPendingEntryIndex() == -1,
          controller->GetIndexOfEntry(&entry),
          controller->GetLastCommittedEntryIndex(),
          controller->GetEntryCount());
  request_params.post_content_type = post_content_type;

  std::unique_ptr<NavigationRequest> navigation_request(new NavigationRequest(
      frame_tree_node, common_params,
      mojom::BeginNavigationParams::New(
          entry.extra_headers(), net::LOAD_NORMAL,
          false /* skip_service_worker */, REQUEST_CONTEXT_TYPE_LOCATION,
          blink::WebMixedContentContextType::kBlockable, is_form_submission,
          GURL() /* searchable_form_url */,
          std::string() /* searchable_form_encoding */, initiator,
          GURL() /* client_side_redirect_url */,
          base::nullopt /* devtools_initiator_info */),
      request_params, browser_initiated, false /* from_begin_navigation */,
      &frame_entry, &entry, std::move(navigation_ui_data)));
  return navigation_request;
}


void aio_complete(struct kiocb *iocb, long res, long res2)
{
	struct kioctx	*ctx = iocb->ki_ctx;
	struct aio_ring	*ring;
	struct io_event	*ev_page, *event;
	unsigned long	flags;
	unsigned tail, pos;

	/*
	 * Special case handling for sync iocbs:
	 *  - events go directly into the iocb for fast handling
	 *  - the sync task with the iocb in its stack holds the single iocb
	 *    ref, no other paths have a way to get another ref
	 *  - the sync task helpfully left a reference to itself in the iocb
	 */
	if (is_sync_kiocb(iocb)) {
		iocb->ki_user_data = res;
		smp_wmb();
		iocb->ki_ctx = ERR_PTR(-EXDEV);
		wake_up_process(iocb->ki_obj.tsk);
		return;
	}

	if (iocb->ki_list.next) {
		unsigned long flags;

		spin_lock_irqsave(&ctx->ctx_lock, flags);
		list_del(&iocb->ki_list);
		spin_unlock_irqrestore(&ctx->ctx_lock, flags);
	}

	/*
	 * Add a completion event to the ring buffer. Must be done holding
	 * ctx->completion_lock to prevent other code from messing with the tail
	 * pointer since we might be called from irq context.
	 */
	spin_lock_irqsave(&ctx->completion_lock, flags);

	tail = ctx->tail;
	pos = tail + AIO_EVENTS_OFFSET;

	if (++tail >= ctx->nr_events)
		tail = 0;

	ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
	event = ev_page + pos % AIO_EVENTS_PER_PAGE;

	event->obj = (u64)(unsigned long)iocb->ki_obj.user;
	event->data = iocb->ki_user_data;
	event->res = res;
	event->res2 = res2;

	kunmap_atomic(ev_page);
	flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);

	pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
		 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
		 res, res2);

	/* after flagging the request as done, we
	 * must never even look at it again
	 */
	smp_wmb();	/* make event visible before updating tail */

	ctx->tail = tail;

	ring = kmap_atomic(ctx->ring_pages[0]);
	ring->tail = tail;
	kunmap_atomic(ring);
	flush_dcache_page(ctx->ring_pages[0]);

	spin_unlock_irqrestore(&ctx->completion_lock, flags);

	pr_debug("added to ring %p at [%u]\n", iocb, tail);

	/*
	 * Check if the user asked us to deliver the result through an
	 * eventfd. The eventfd_signal() function is safe to be called
	 * from IRQ context.
	 */
	if (iocb->ki_eventfd != NULL)
		eventfd_signal(iocb->ki_eventfd, 1);

	/* everything turned out well, dispose of the aiocb. */
	kiocb_free(iocb);

	/*
	 * We have to order our ring_info tail store above and test
	 * of the wait list below outside the wait lock.  This is
	 * like in wake_up_bit() where clearing a bit has to be
	 * ordered with the unlocked test.
	 */
	smp_mb();

	if (waitqueue_active(&ctx->wait))
		wake_up(&ctx->wait);

	percpu_ref_put(&ctx->reqs);
}


StoreData (const char * file_name, const void * data, const int data_size) {

  if (!data) {
    return FALSE;
  }

  priv_state priv = set_root_priv();
  dprintf (D_FULLDEBUG, "in StoreData(), euid=%d\n", geteuid());

  int fd = safe_open_wrapper_follow(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0600 );
  if (fd == -1) {
    dprintf (D_ALWAYS, "Unable to store in %s\n", file_name);
    set_priv(priv);
    return FALSE;
  }

  fchmod (fd, S_IRUSR | S_IWUSR);
  fchown (fd, get_user_uid(), get_user_gid());

  write (fd, data, data_size);

  close (fd);

  set_priv(priv);
  return TRUE;
}


action_insert_thumb (ExifData *ed, ExifLog *log, ExifParams p)
{
	FILE *f;

	if (!ed) return;

	/* Get rid of the thumbnail */
	action_remove_thumb (ed, log, p);

	/* Insert new thumbnail */
	f = fopen (p.set_thumb, "rb");
	if (!f) {
		exif_log (log, -1, "exif", _("Could not open "
			"'%s' (%s)!"), p.set_thumb, strerror (errno));
	} else {
		long fsize;
		if (fseek (f, 0, SEEK_END) < 0) {
			fclose(f);
			exif_log (log, -1, "exif", _("Could not determine size of "
				"'%s' (%s)."), p.set_thumb, strerror (errno));
			return;
		}
		fsize = ftell (f);
		if (fsize < 0) {
			fclose(f);
			exif_log (log, -1, "exif", _("Could not determine size of "
				"'%s' (%s)."), p.set_thumb, strerror (errno));
			return;
		}
		ed->size = fsize;
		ed->data = malloc (sizeof (char) * ed->size);
		if (ed->size && !ed->data) {
			EXIF_LOG_NO_MEMORY (log, "exif", sizeof (char) * ed->size);
			exit (1);
		}
		if (fseek (f, 0, SEEK_SET) < 0) {
			fclose(f);
			exif_log (log, -1, "exif", _("Could not determine size of "
				"'%s' (%s)."), p.set_thumb, strerror (errno));
			return;
		}
		if (fread (ed->data, sizeof (char), ed->size, f) != ed->size)
			exif_log (log, -1, "exif", _("Could not read "
				"'%s' (%s)."), p.set_thumb, strerror (errno));
		if (fclose (f) < 0)
			exif_log (log, -1, "exif", _("Could not read "
				"'%s' (%s)."), p.set_thumb, strerror (errno));
	}
}


void InputMethodController::DeleteSurroundingTextInCodePoints(int before,
                                                              int after) {
  DCHECK_GE(before, 0);
  DCHECK_GE(after, 0);
  if (!GetEditor().CanEdit())
    return;
  const PlainTextRange selection_offsets(GetSelectionOffsets());
  if (selection_offsets.IsNull())
    return;
  Element* const root_editable_element =
      GetFrame().Selection().RootEditableElementOrDocumentElement();
  if (!root_editable_element)
    return;

  const TextIteratorBehavior& behavior =
      TextIteratorBehavior::Builder()
          .SetEmitsObjectReplacementCharacter(true)
          .Build();
  const String& text = PlainText(
      EphemeralRange::RangeOfContents(*root_editable_element), behavior);

  if (text.Is8Bit())
    return DeleteSurroundingText(before, after);

  const int selection_start = static_cast<int>(selection_offsets.Start());
  const int selection_end = static_cast<int>(selection_offsets.End());

  const int before_length =
      CalculateBeforeDeletionLengthsInCodePoints(text, before, selection_start);
  if (IsInvalidDeletionLength(before_length))
    return;
  const int after_length =
      CalculateAfterDeletionLengthsInCodePoints(text, after, selection_end);
  if (IsInvalidDeletionLength(after_length))
    return;

  return DeleteSurroundingText(before_length, after_length);
}


void PepperDeviceEnumerationHostHelper::OnNotifyDeviceChange(
    uint32_t callback_id,
    int /* request_id */,
    const std::vector<ppapi::DeviceRefData>& devices) {
  resource_host_->host()->SendUnsolicitedReply(
      resource_host_->pp_resource(),
      PpapiPluginMsg_DeviceEnumeration_NotifyDeviceChange(callback_id,
                                                          devices));
}


int OmniboxViewWin::OnPerformDrop(const views::DropTargetEvent& event) {
  return OnPerformDropImpl(event, false);
}


static LayoutUnit justifyContentSpaceBetweenChildren(LayoutUnit availableFreeSpace, EJustifyContent justifyContent, unsigned numberOfChildren)
{
    if (availableFreeSpace > 0 && numberOfChildren > 1) {
        if (justifyContent == JustifySpaceBetween)
            return availableFreeSpace / (numberOfChildren - 1);
        if (justifyContent == JustifySpaceAround)
            return availableFreeSpace / numberOfChildren;
    }
    return 0;
}


void lodepng_color_mode_init(LodePNGColorMode* info)
{
  info->key_defined = 0;
  info->key_r = info->key_g = info->key_b = 0;
  info->colortype = LCT_RGBA;
  info->bitdepth = 8;
  info->palette = 0;
  info->palettesize = 0;
}


void Document::clearAXObjectCache()
{
    ASSERT(topDocument() == this);
    m_axObjectCache.clear();
}


static void memcpy_to_page(struct page *page, size_t offset, const char *from, size_t len)
{
	char *to = kmap_atomic(page);
	memcpy(to + offset, from, len);
	kunmap_atomic(to);
}


static void win_chr_readfile(CharDriverState *chr)

{

    WinCharState *s = chr->opaque;

    int ret, err;

    uint8_t buf[1024];

    DWORD size;

    ZeroMemory(&s->orecv, sizeof(s->orecv));

    s->orecv.hEvent = s->hrecv;

    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);

    if (!ret) {

        err = GetLastError();

        if (err == ERROR_IO_PENDING) {

            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);

        }

    }

    if (size > 0) {

        qemu_chr_read(chr, buf, size);

    }

}


static int alpha_check_constraints(struct perf_event **events,
				   unsigned long *evtypes, int n_ev)
{

	/* No HW events is possible from hw_perf_group_sched_in(). */
	if (n_ev == 0)
		return 0;

	if (n_ev > alpha_pmu->num_pmcs)
		return -1;

	return alpha_pmu->check_constraints(events, evtypes, n_ev);
}


static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index,

                                  Jpeg2000CodingStyle *codsty,

                                  Jpeg2000ResLevel *rlevel, int precno,

                                  int layno, uint8_t *expn, int numgbits)

{

    int bandno, cblkno, ret, nb_code_blocks;

    int cwsno;

    if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {

        if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {

            s->g = tile->tile_part[++(*tp_index)].tpg;

        }

    }

    if (bytestream2_peek_be32(&s->g) == 0xFF910004)

        bytestream2_skip(&s->g, 6);

    if (!(ret = get_bits(s, 1))) {

        jpeg2000_flush(s);

        return 0;

    } else if (ret < 0)

        return ret;

    for (bandno = 0; bandno < rlevel->nbands; bandno++) {

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        if (band->coord[0][0] == band->coord[0][1] ||

            band->coord[1][0] == band->coord[1][1])

            continue;

        nb_code_blocks =  prec->nb_codeblocks_height *

                          prec->nb_codeblocks_width;

        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {

            Jpeg2000Cblk *cblk = prec->cblk + cblkno;

            int incl, newpasses, llen;

            if (cblk->npasses)

                incl = get_bits(s, 1);

            else

                incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;

            if (!incl)

                continue;

            else if (incl < 0)

                return incl;

            if (!cblk->npasses) {

                int v = expn[bandno] + numgbits - 1 -

                        tag_tree_decode(s, prec->zerobits + cblkno, 100);

                if (v < 0) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "nonzerobits %d invalid\n", v);

                    return AVERROR_INVALIDDATA;

                }

                cblk->nonzerobits = v;

            }

            if ((newpasses = getnpasses(s)) < 0)

                return newpasses;

            av_assert2(newpasses > 0);

            if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) {

                avpriv_request_sample(s->avctx, "Too many passes\n");

                return AVERROR_PATCHWELCOME;

            }

            if ((llen = getlblockinc(s)) < 0)

                return llen;

            if (cblk->lblock + llen + av_log2(newpasses) > 16) {

                avpriv_request_sample(s->avctx,

                                      "Block with length beyond 16 bits\n");

                return AVERROR_PATCHWELCOME;

            }

            cblk->lblock += llen;

            cblk->nb_lengthinc = 0;

            cblk->nb_terminationsinc = 0;

            do {

                int newpasses1 = 0;

                while (newpasses1 < newpasses) {

                    newpasses1 ++;

                    if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) {

                        cblk->nb_terminationsinc ++;

                        break;

                    }

                }

                if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0)

                    return ret;

                if (ret > sizeof(cblk->data)) {

                    avpriv_request_sample(s->avctx,

                                        "Block with lengthinc greater than %"SIZE_SPECIFIER"",

                                        sizeof(cblk->data));

                    return AVERROR_PATCHWELCOME;

                }

                cblk->lengthinc[cblk->nb_lengthinc++] = ret;

                cblk->npasses  += newpasses1;

                newpasses -= newpasses1;

            } while(newpasses);

        }

    }

    jpeg2000_flush(s);

    if (codsty->csty & JPEG2000_CSTY_EPH) {

        if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)

            bytestream2_skip(&s->g, 2);

        else

            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");

    }

    for (bandno = 0; bandno < rlevel->nbands; bandno++) {

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;

        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {

            Jpeg2000Cblk *cblk = prec->cblk + cblkno;

            for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) {

                if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno]

                    || sizeof(cblk->data) < cblk->length + cblk->lengthinc[cwsno] + 4

                ) {

                    av_log(s->avctx, AV_LOG_ERROR,

                        "Block length %"PRIu16" or lengthinc %d is too large, left %d\n",

                        cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g));

                    return AVERROR_INVALIDDATA;

                }

                bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]);

                cblk->length   += cblk->lengthinc[cwsno];

                cblk->lengthinc[cwsno] = 0;

                if (cblk->nb_terminationsinc) {

                    cblk->nb_terminationsinc--;

                    cblk->nb_terminations++;

                    cblk->data[cblk->length++] = 0xFF;

                    cblk->data[cblk->length++] = 0xFF;

                    cblk->data_start[cblk->nb_terminations] = cblk->length;

                }

            }

        }

    }

    return 0;

}


void MainWindow::closeEvent(QCloseEvent* event)
{
    if (continueJobsRunning() && continueModified()) {
        if (!m_htmlEditor || m_htmlEditor->close()) {
            LOG_DEBUG() << "begin";
            JOBS.cleanup();
            writeSettings();
            if (m_exitCode == EXIT_SUCCESS) {
                MLT.stop();
            } else {
                if (multitrack())
                    m_timelineDock->model()->close();
                if (playlist())
                    m_playlistDock->model()->close();
                else
                    onMultitrackClosed();
            }
            QThreadPool::globalInstance()->clear();
            AudioLevelsTask::closeAll();
            event->accept();
            emit aboutToShutDown();
            if (m_exitCode == EXIT_SUCCESS) {
                QApplication::quit();
                LOG_DEBUG() << "end";
                ::_Exit(0);
            } else {
                QApplication::exit(m_exitCode);
                LOG_DEBUG() << "end";
            }
            return;
        }
    }
    event->ignore();
}


DriverInit(const char *server, const char *moduleName, const char *threadName,
           const Ns_DriverInitData *init,
           NsServer *servPtr, const char *path,
           const char *bindaddrs, const char *defserver, const char *host)
{
    const char     *defproto;
    Driver         *drvPtr;
    DrvWriter      *wrPtr;
    DrvSpooler     *spPtr;
    int             i;
    unsigned short  defport;

    NS_NONNULL_ASSERT(threadName != NULL);
    NS_NONNULL_ASSERT(init != NULL);
    NS_NONNULL_ASSERT(path != NULL);
    NS_NONNULL_ASSERT(bindaddrs != NULL);
    NS_NONNULL_ASSERT(host != NULL);

    /*
     * Set the protocol and port defaults.
     */
    if (init->protocol != NULL) {
        defproto = init->protocol;
        defport = init->defaultPort;
    } else {
        defproto = "unknown";
        defport = 0u;
    }
    Ns_Log(DriverDebug, "DriverInit server <%s> threadName %s proto %s port %hu",
           server, threadName, defproto, defport);

    /*
     * Allocate a new driver instance and set configurable parameters.
     */

    drvPtr = ns_calloc(1u, sizeof(Driver));

    Ns_MutexInit(&drvPtr->lock);
    Ns_MutexSetName2(&drvPtr->lock, "ns:drv", threadName);

    Ns_MutexInit(&drvPtr->spooler.lock);
    Ns_MutexSetName2(&drvPtr->spooler.lock, "ns:drv:spool", threadName);

    Ns_MutexInit(&drvPtr->writer.lock);
    Ns_MutexSetName2(&drvPtr->writer.lock, "ns:drv:writer", threadName);

    if (ns_sockpair(drvPtr->trigger) != 0) {
        Ns_Fatal("ns_sockpair() failed: %s", ns_sockstrerror(ns_sockerrno));
    }

    drvPtr->server         = server;
    drvPtr->type           = init->name;
    drvPtr->moduleName     = ns_strdup(moduleName);
    drvPtr->threadName     = ns_strdup(threadName);
    drvPtr->defserver      = defserver;
    drvPtr->listenProc     = init->listenProc;
    drvPtr->acceptProc     = init->acceptProc;
    drvPtr->recvProc       = init->recvProc;
    drvPtr->sendProc       = init->sendProc;
    drvPtr->sendFileProc   = init->sendFileProc;
    drvPtr->keepProc       = init->keepProc;
    drvPtr->requestProc    = init->requestProc;
    drvPtr->closeProc      = init->closeProc;
    drvPtr->clientInitProc = init->clientInitProc;
    drvPtr->arg            = init->arg;
    drvPtr->opts           = init->opts;
    drvPtr->servPtr        = servPtr;
    drvPtr->defport        = defport;

    drvPtr->bufsize        = (size_t)Ns_ConfigMemUnitRange(path, "bufsize", 16384, 1024, INT_MAX);
    drvPtr->maxinput       = Ns_ConfigMemUnitRange(path, "maxinput", 1024*1024, 1024, LLONG_MAX);
    drvPtr->maxupload      = Ns_ConfigMemUnitRange(path, "maxupload", 0, 0, (Tcl_WideInt)drvPtr->maxinput);
    drvPtr->readahead      = Ns_ConfigMemUnitRange(path, "readahead", (Tcl_WideInt)drvPtr->bufsize,
                                                   (Tcl_WideInt)drvPtr->bufsize, drvPtr->maxinput);

    drvPtr->maxline        = Ns_ConfigIntRange(path, "maxline",      8192, 256, INT_MAX);
    drvPtr->maxheaders     = Ns_ConfigIntRange(path, "maxheaders",    128,   8, INT_MAX);
    drvPtr->maxqueuesize   = Ns_ConfigIntRange(path, "maxqueuesize", 1024,   1, INT_MAX);

    Ns_ConfigTimeUnitRange(path, "sendwait",
                           "30s", 1, 0, INT_MAX, 0, &drvPtr->sendwait);
    Ns_ConfigTimeUnitRange(path, "recvwait",
                           "30s", 1, 0, INT_MAX, 0, &drvPtr->recvwait);
    Ns_ConfigTimeUnitRange(path, "closewait",
                           "2s", 0, 0, INT_MAX, 0, &drvPtr->closewait);
    Ns_ConfigTimeUnitRange(path, "keepwait",
                           "5s", 0, 0, INT_MAX, 0, &drvPtr->keepwait);

    drvPtr->backlog        = Ns_ConfigIntRange(path, "backlog",       256,   1, INT_MAX);
    drvPtr->driverthreads  = Ns_ConfigIntRange(path, "driverthreads",   1,   1, 32);
    drvPtr->reuseport      = Ns_ConfigBool(path,     "reuseport",       NS_FALSE);
    drvPtr->acceptsize     = Ns_ConfigIntRange(path, "acceptsize", drvPtr->backlog, 1, INT_MAX);

    drvPtr->keepmaxuploadsize   = (size_t)Ns_ConfigMemUnitRange(path, "keepalivemaxuploadsize",
                                                            0, 0, INT_MAX);
    drvPtr->keepmaxdownloadsize = (size_t)Ns_ConfigMemUnitRange(path, "keepalivemaxdownloadsize",
                                                            0, 0, INT_MAX);
    drvPtr->recvTimeout = drvPtr->recvwait;

    Tcl_InitHashTable(&drvPtr->hosts, TCL_STRING_KEYS);

    if (drvPtr->driverthreads > 1) {
#if !defined(SO_REUSEPORT)
        drvPtr->driverthreads = 1;
        drvPtr->reuseport = NS_FALSE;
#else
        /*
         * When driver threads > 1, "reuseport" has to be active.
         */
        drvPtr->reuseport = NS_TRUE;
#endif
    }
    if (drvPtr->reuseport) {
        /*
         * Reuseport was specified
         */
#if !defined(SO_REUSEPORT)
        Ns_Log(Warning,
               "parameter %s reuseport was specified, but is not supported by the operating system",
               path);
        drvPtr->reuseport = NS_FALSE;
#endif
    }

    drvPtr->uploadpath = ns_strdup(Ns_ConfigString(path, "uploadpath", nsconf.tmpDir));

    /*
     * If activated, "maxupload" has to be at least "readahead" bytes. Tell
     * the user in case the config values are overruled.
     */
    if ((drvPtr->maxupload > 0) &&
        (drvPtr->maxupload < drvPtr->readahead)) {
        Ns_Log(Warning,
               "parameter %s maxupload % " TCL_LL_MODIFIER
               "d invalid; can be either 0 or must be >= %" TCL_LL_MODIFIER
               "d (size of readahead)",
               path, drvPtr->maxupload, drvPtr->readahead);
        drvPtr->maxupload = drvPtr->readahead;
    }

    /*
     * Determine the port and then set the HTTP location string either
     * as specified in the config file or constructed from the
     * protocol, hostname and port.
     */

    drvPtr->protocol     = ns_strdup(defproto);
    drvPtr->address      = ns_strdup(bindaddrs);
    drvPtr->port         = (unsigned short)Ns_ConfigIntRange(path, "port", (int)defport, 0, 65535);
    drvPtr->location     = Ns_ConfigGetValue(path, "location");

    if (drvPtr->location != NULL && (strstr(drvPtr->location, "://") != NULL)) {
        drvPtr->location = ns_strdup(drvPtr->location);
    } else {
        Tcl_DString ds, *dsPtr = &ds;

        Ns_DStringInit(dsPtr);
        Ns_HttpLocationString(dsPtr, drvPtr->protocol, host, drvPtr->port, defport);
        drvPtr->location = Ns_DStringExport(dsPtr);
    }

    drvPtr->nextPtr = firstDrvPtr;
    firstDrvPtr = drvPtr;

    /*
     * Add driver specific extra headers.
     */
    drvPtr->extraHeaders = Ns_ConfigSet(path, "extraheaders");

    /*
     * Check if upload spooler are enabled
     */
    spPtr = &drvPtr->spooler;
    spPtr->threads = Ns_ConfigIntRange(path, "spoolerthreads", 0, 0, 32);

    if (spPtr->threads > 0) {
        Ns_Log(Notice, "%s: enable %d spooler thread(s) "
               "for uploads >= %" TCL_LL_MODIFIER "d bytes", threadName,
               spPtr->threads, drvPtr->readahead);

        for (i = 0; i < spPtr->threads; i++) {
            SpoolerQueue *queuePtr = ns_calloc(1u, sizeof(SpoolerQueue));
            char          buffer[100];

            snprintf(buffer, sizeof(buffer), "ns:driver:spooler:%d", i);
            Ns_MutexSetName2(&queuePtr->lock, buffer, "queue");
            queuePtr->id = i;
            Push(queuePtr, spPtr->firstPtr);
        }
    } else {
        Ns_Log(Notice, "%s: enable %d spooler thread(s) ",
               threadName, spPtr->threads);
    }

    /*
     * Enable writer threads
     */

    wrPtr = &drvPtr->writer;
    wrPtr->threads = Ns_ConfigIntRange(path, "writerthreads", 0, 0, 32);

    if (wrPtr->threads > 0) {
        wrPtr->writersize = (size_t)Ns_ConfigMemUnitRange(path, "writersize",
                                                          1024*1024, 1024, INT_MAX);
        wrPtr->bufsize = (size_t)Ns_ConfigMemUnitRange(path, "writerbufsize",
                                                   8192, 512, INT_MAX);
        wrPtr->rateLimit = Ns_ConfigIntRange(path, "writerratelimit", 0, 0, INT_MAX);
        wrPtr->doStream = Ns_ConfigBool(path, "writerstreaming", NS_FALSE)
            ? NS_WRITER_STREAM_ACTIVE : NS_WRITER_STREAM_NONE;
        Ns_Log(Notice, "%s: enable %d writer thread(s) "
               "for downloads >= %" PRIdz " bytes, bufsize=%" PRIdz " bytes, HTML streaming %d",
               threadName, wrPtr->threads, wrPtr->writersize, wrPtr->bufsize, wrPtr->doStream);

        for (i = 0; i < wrPtr->threads; i++) {
            SpoolerQueue *queuePtr = ns_calloc(1u, sizeof(SpoolerQueue));
            char          buffer[100];

            snprintf(buffer, sizeof(buffer), "ns:driver:writer:%d", i);
            Ns_MutexSetName2(&queuePtr->lock, buffer, "queue");
            queuePtr->id = i;
            Push(queuePtr, wrPtr->firstPtr);
        }
    } else {
        Ns_Log(Notice, "%s: enable %d writer thread(s) ",
               threadName, wrPtr->threads);
    }

    return NS_OK;
}


encode_SET_L4_port(const struct ofpact_l4_port *l4_port,
                   enum ofp_version ofp_version, enum ofp_raw_action_type raw,
                   enum mf_field_id field, struct ofpbuf *out)
{
    uint16_t port = l4_port->port;

    if (ofp_version >= OFP12_VERSION && field != MFF_N_IDS) {
        put_set_field(out, ofp_version, field, port);
    } else {
        ofpact_put_raw(out, ofp_version, raw, port);
    }
}


AVFormatContext *ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st,

                                       URLContext *handle, int packet_size)

{

    AVFormatContext *rtpctx;

    int ret;

    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);

    if (!rtp_format)

        return NULL;

    /* Allocate an AVFormatContext for each output stream */

    rtpctx = avformat_alloc_context();

    if (!rtpctx)

        return NULL;

    rtpctx->oformat = rtp_format;

    if (!av_new_stream(rtpctx, 0)) {

        av_free(rtpctx);

        return NULL;

    }

    /* Copy the max delay setting; the rtp muxer reads this. */

    rtpctx->max_delay = s->max_delay;

    /* Copy other stream parameters. */

    rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;

    /* Set the synchronized start time. */

    rtpctx->start_time_realtime = s->start_time_realtime;

    avcodec_copy_context(rtpctx->streams[0]->codec, st->codec);

    if (handle) {

        url_fdopen(&rtpctx->pb, handle);

    } else

        url_open_dyn_packet_buf(&rtpctx->pb, packet_size);

    ret = av_write_header(rtpctx);

    if (ret) {

        if (handle) {

            avio_close(rtpctx->pb);

        } else {

            uint8_t *ptr;

            avio_close_dyn_buf(rtpctx->pb, &ptr);

            av_free(ptr);

        }

        avformat_free_context(rtpctx);

        return NULL;

    }

    return rtpctx;

}


browser_sync::ClientAction ConvertClientActionPBToLocalClientAction(
    const sync_pb::ClientToServerResponse::Error::Action& action) {
  switch (action) {
    case ClientToServerResponse::Error::UPGRADE_CLIENT:
      return browser_sync::UPGRADE_CLIENT;
    case ClientToServerResponse::Error::CLEAR_USER_DATA_AND_RESYNC:
      return browser_sync::CLEAR_USER_DATA_AND_RESYNC;
    case ClientToServerResponse::Error::ENABLE_SYNC_ON_ACCOUNT:
      return browser_sync::ENABLE_SYNC_ON_ACCOUNT;
    case ClientToServerResponse::Error::STOP_AND_RESTART_SYNC:
      return browser_sync::STOP_AND_RESTART_SYNC;
    case ClientToServerResponse::Error::DISABLE_SYNC_ON_CLIENT:
      return browser_sync::DISABLE_SYNC_ON_CLIENT;
    case ClientToServerResponse::Error::UNKNOWN_ACTION:
      return browser_sync::UNKNOWN_ACTION;
    default:
      NOTREACHED();
      return browser_sync::UNKNOWN_ACTION;
  }
}


bool ResourceDispatcherHost::CompleteRead(URLRequest* request,
                                          int* bytes_read) {
  if (!request->status().is_success()) {
    NOTREACHED();
    return false;
  }

  ResourceDispatcherHostRequestInfo* info = InfoForRequest(request);
  if (!info->resource_handler()->OnReadCompleted(info->request_id(),
                                                 bytes_read)) {
    CancelRequest(info->child_id(), info->request_id(), false, false);
    return false;
  }

  return *bytes_read != 0;
}


NOEXPORT int service_initialize(void) {
    SERVICE_TABLE_ENTRY serviceTable[]={{0, 0}, {0, 0}};

    serviceTable[0].lpServiceName=SERVICE_NAME;
    serviceTable[0].lpServiceProc=service_main;
    /* disable taskbar for security */
    /* global_options.option.taskbar=0; */
    if(!StartServiceCtrlDispatcher(serviceTable)) {
        error_box(TEXT("StartServiceCtrlDispatcher"));
        return 1;
    }
    return 0; /* NT service started */
}


PrintMsg_Print_Params::PrintMsg_Print_Params()
  : page_size(),
    content_size(),
    printable_area(),
    margin_top(0),
    margin_left(0),
    dpi(0),
    min_shrink(0),
    max_shrink(0),
    desired_dpi(0),
     document_cookie(0),
     selection_only(false),
     supports_alpha_blend(false),
    preview_ui_id(-1),
     preview_request_id(0),
     is_first_request(false),
     print_scaling_option(WebKit::WebPrintScalingOptionSourceSize),
    print_to_pdf(false),
    display_header_footer(false),
    date(),
    title(),
    url() {
}


void __init msg_init(void)
{
	msg_init_ns(&init_ipc_ns);

	printk(KERN_INFO "msgmni has been set to %d\n",
		init_ipc_ns.msg_ctlmni);

	ipc_init_proc_interface("sysvipc/msg",
				"       key      msqid perms      cbytes       qnum lspid lrpid   uid   gid  cuid  cgid      stime      rtime      ctime\n",
				IPC_MSG_IDS, sysvipc_msg_proc_show);
}


static int process_signals(void)
{
	if (sig_exit_handler_called) {
		log_info("caught signal %d", sig_exit_handler_sig);
		return 1;
	}
	if (sig_usr1_handler_called) {
		sig_usr1_handler_called = 0;
		tickets_log_info();
	}
	if (sig_chld_handler_called) {
		sig_chld_handler_called = 0;
		wait_child(SIGCHLD);
	}

	return 0;
}


void RootWindow::SynthesizeMouseMoveEvent() {
  if (!synthesize_mouse_move_)
    return;
  synthesize_mouse_move_ = false;
#if !defined(OS_WIN)
  gfx::Point orig_mouse_location = last_mouse_location_;
  layer()->transform().TransformPoint(orig_mouse_location);

  MouseEvent event(ui::ET_MOUSE_MOVED,
                   orig_mouse_location,
                   orig_mouse_location,
                   ui::EF_IS_SYNTHESIZED);
  DispatchMouseEvent(&event);
#endif
}


static inline void ftrace_trace_stack(struct trace_array *tr,
				      struct ring_buffer *buffer,
				      unsigned long flags,
				      int skip, int pc, struct pt_regs *regs)
{
}


void SandboxIPCHandler::HandleGetStyleForStrike(
    int fd,
    base::PickleIterator iter,
    const std::vector<base::ScopedFD>& fds) {
  std::string family;
  bool bold;
  bool italic;
  uint16_t pixel_size;

  if (!iter.ReadString(&family) || !iter.ReadBool(&bold) ||
      !iter.ReadBool(&italic) || !iter.ReadUInt16(&pixel_size)) {
    return;
  }

  gfx::FontRenderParamsQuery query;
  query.families.push_back(family);
  query.pixel_size = pixel_size;
  query.style = italic ? gfx::Font::ITALIC : 0;
  query.weight = bold ? gfx::Font::Weight::BOLD : gfx::Font::Weight::NORMAL;
  const gfx::FontRenderParams params = gfx::GetFontRenderParams(query, nullptr);

  base::Pickle reply;
  reply.WriteInt(params.use_bitmaps);
  reply.WriteInt(params.autohinter);
  reply.WriteInt(params.hinting != gfx::FontRenderParams::HINTING_NONE);
  reply.WriteInt(ConvertHinting(params.hinting));
  reply.WriteInt(params.antialiasing);
  reply.WriteInt(ConvertSubpixelRendering(params.subpixel_rendering));
  reply.WriteInt(params.subpixel_positioning);

  SendRendererReply(fds, reply, -1);
}


static uint64_t megasas_sgl_get_addr(MegasasCmd *cmd,
                                     union mfi_sgl *sgl)
{
    uint64_t addr;

    if (megasas_frame_is_ieee_sgl(cmd)) {
        addr = le64_to_cpu(sgl->sg_skinny->addr);
    } else if (megasas_frame_is_sgl64(cmd)) {
        addr = le64_to_cpu(sgl->sg64->addr);
    } else {
        addr = le32_to_cpu(sgl->sg32->addr);
    }
    return addr;
}


static void proto_tree_set_int ( field_info * fi , gint32 value ) {
 header_field_info * hfinfo ;
 guint32 integer ;
 gint no_of_bits ;
 hfinfo = fi -> hfinfo ;
 integer = ( guint32 ) value ;
 if ( hfinfo -> bitmask ) {
 integer &= ( guint32 ) ( hfinfo -> bitmask ) ;
 integer >>= hfinfo_bitshift ( hfinfo ) ;
 no_of_bits = ws_count_ones ( hfinfo -> bitmask ) ;
 integer = ws_sign_ext32 ( integer , no_of_bits ) ;
 }
 fvalue_set_sinteger ( & fi -> value , integer ) ;
 }


static unsigned int udf_count_free(struct super_block *sb)
{
	unsigned int accum = 0;
	struct udf_sb_info *sbi;
	struct udf_part_map *map;

	sbi = UDF_SB(sb);
	if (sbi->s_lvid_bh) {
		struct logicalVolIntegrityDesc *lvid =
			(struct logicalVolIntegrityDesc *)
			sbi->s_lvid_bh->b_data;
		if (le32_to_cpu(lvid->numOfPartitions) > sbi->s_partition) {
			accum = le32_to_cpu(
					lvid->freeSpaceTable[sbi->s_partition]);
			if (accum == 0xFFFFFFFF)
				accum = 0;
		}
	}

	if (accum)
		return accum;

	map = &sbi->s_partmaps[sbi->s_partition];
	if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
		accum += udf_count_free_bitmap(sb,
					       map->s_uspace.s_bitmap);
	}
	if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP) {
		accum += udf_count_free_bitmap(sb,
					       map->s_fspace.s_bitmap);
	}
	if (accum)
		return accum;

	if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
		accum += udf_count_free_table(sb,
					      map->s_uspace.s_table);
	}
	if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE) {
		accum += udf_count_free_table(sb,
					      map->s_fspace.s_table);
	}

	return accum;
}


static int read_fragment_table(long long *directory_table_end)
{
	int res, i;
	int bytes = SQUASHFS_FRAGMENT_BYTES(sBlk.s.fragments);
	int  indexes = SQUASHFS_FRAGMENT_INDEXES(sBlk.s.fragments);
	long long fragment_table_index[indexes];

	TRACE("read_fragment_table: %d fragments, reading %d fragment indexes "
		"from 0x%llx\n", sBlk.s.fragments, indexes,
		sBlk.s.fragment_table_start);

	if(sBlk.s.fragments == 0) {
		*directory_table_end = sBlk.s.fragment_table_start;
		return TRUE;
	}

	fragment_table = malloc(bytes);
	if(fragment_table == NULL)
		EXIT_UNSQUASH("read_fragment_table: failed to allocate "
			"fragment table\n");

	res = read_fs_bytes(fd, sBlk.s.fragment_table_start,
		SQUASHFS_FRAGMENT_INDEX_BYTES(sBlk.s.fragments),
		fragment_table_index);
	if(res == FALSE) {
		ERROR("read_fragment_table: failed to read fragment table "
			"index\n");
		return FALSE;
	}
	SQUASHFS_INSWAP_FRAGMENT_INDEXES(fragment_table_index, indexes);

	for(i = 0; i < indexes; i++) {
		int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
					bytes & (SQUASHFS_METADATA_SIZE - 1);
		int length = read_block(fd, fragment_table_index[i], NULL,
			expected, ((char *) fragment_table) + (i *
			SQUASHFS_METADATA_SIZE));
		TRACE("Read fragment table block %d, from 0x%llx, length %d\n",
			i, fragment_table_index[i], length);
		if(length == FALSE) {
			ERROR("read_fragment_table: failed to read fragment "
				"table index\n");
			return FALSE;
		}
	}

	for(i = 0; i < sBlk.s.fragments; i++)
		SQUASHFS_INSWAP_FRAGMENT_ENTRY(&fragment_table[i]);

	*directory_table_end = fragment_table_index[0];
	return TRUE;
}


void ndpi_ptree_destroy(ndpi_ptree_t *tree) {
  if(tree) {
    if(tree->v4)
      ndpi_Destroy_Patricia(tree->v4, free_ptree_data);
    if(tree->v6)
      ndpi_Destroy_Patricia(tree->v6, free_ptree_data);

    ndpi_free(tree);
  }
}


int TabStripModel::GetIndexOfTabContents(const TabContents* contents) const {
  return GetIndexOfWebContents(contents->web_contents());
}


 static v8::Handle<v8::Value> getObjectParameter(const v8::Arguments& args, ObjectType objectType)
 {
     if (args.Length() != 2)
        return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());

     ExceptionCode ec = 0;
     WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
    unsigned target = toInt32(args[0]);
    unsigned pname = toInt32(args[1]);
    WebGLGetInfo info;
    switch (objectType) {
    case kBuffer:
        info = context->getBufferParameter(target, pname, ec);
        break;
    case kRenderbuffer:
        info = context->getRenderbufferParameter(target, pname, ec);
        break;
    case kTexture:
        info = context->getTexParameter(target, pname, ec);
        break;
    case kVertexAttrib:
        info = context->getVertexAttrib(target, pname, ec);
        break;
    default:
        notImplemented();
        break;
    }
    if (ec) {
        V8Proxy::setDOMException(ec, args.GetIsolate());
        return v8::Undefined();
    }
    return toV8Object(info, args.GetIsolate());
}


int DownloadFileManager::NumberOfActiveDownloads() const {
   return downloads_.size();
 }


void test_truncate(const char *path)
{
	if (truncate(path, 0) == 0) {
		fprintf(stderr, "leak at truncate of %s\n", path);
		exit(1);
	}
}


static int putreg32(struct task_struct *child, unsigned regno, u32 value)
{
	struct pt_regs *regs = task_pt_regs(child);

	switch (regno) {

	SEG32(cs);
	SEG32(ds);
	SEG32(es);
	SEG32(fs);
	SEG32(gs);
	SEG32(ss);

	R32(ebx, bx);
	R32(ecx, cx);
	R32(edx, dx);
	R32(edi, di);
	R32(esi, si);
	R32(ebp, bp);
	R32(eax, ax);
	R32(eip, ip);
	R32(esp, sp);

	case offsetof(struct user32, regs.orig_eax):
		/*
		 * A 32-bit debugger setting orig_eax means to restore
		 * the state of the task restarting a 32-bit syscall.
		 * Make sure we interpret the -ERESTART* codes correctly
		 * in case the task is not actually still sitting at the
		 * exit from a 32-bit syscall with TS_COMPAT still set.
		 */
		regs->orig_ax = value;
		if (syscall_get_nr(child, regs) >= 0)
			task_thread_info(child)->status |= TS_COMPAT;
		break;

	case offsetof(struct user32, regs.eflags):
		return set_flags(child, value);

	case offsetof(struct user32, u_debugreg[0]) ...
		offsetof(struct user32, u_debugreg[7]):
		regno -= offsetof(struct user32, u_debugreg[0]);
		return ptrace_set_debugreg(child, regno / 4, value);

	default:
		if (regno > sizeof(struct user32) || (regno & 3))
			return -EIO;

		/*
		 * Other dummy fields in the virtual user structure
		 * are ignored
		 */
		break;
	}
	return 0;
}


void Document::adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(FloatRect& rect, RenderObject* renderer)
{
    if (!view())
        return;

    float inverseFrameScale = 1;
    if (frame())
        inverseFrameScale = 1 / frame()->frameScaleFactor();

    LayoutRect visibleContentRect = view()->visibleContentRect();
    rect.move(-visibleContentRect.x(), -visibleContentRect.y());
    adjustFloatRectForAbsoluteZoom(rect, renderer);
    if (inverseFrameScale != 1)
        rect.scale(inverseFrameScale);
}


TensorSliceReader::GetVariableToDataTypeMap() const {
  VarToDataTypeMap name_to_dtype;
  if (status().ok()) {
    for (auto& e : Tensors()) {
      name_to_dtype[e.first] = e.second->type();
    }
  }
  return name_to_dtype;
}


static int bin_fields(RCore *r, int mode, int va) {
	RList *fields;
	RListIter *iter;
	RBinField *field;
	int i = 0;
	RBin *bin = r->bin;

	if (!(fields = r_bin_get_fields (bin))) {
		return false;
	}
	if (IS_MODE_JSON (mode)) {
		r_cons_print ("[");
	} else if (IS_MODE_RAD (mode)) {
		r_cons_println ("fs header");
	} else if (IS_MODE_NORMAL (mode)) {
		r_cons_println ("[Header fields]");
	}
	r_list_foreach (fields, iter, field) {
		ut64 addr = rva (bin, field->paddr, field->vaddr, va);

		if (IS_MODE_RAD (mode)) {
			char *n = __filterQuotedShell (field->name);
			r_name_filter (n, -1);
			r_cons_printf ("\"f header.%s 1 0x%08"PFMT64x"\"\n", n, addr);
			if (field->comment && *field->comment) {
				char *e = sdb_encode ((const ut8*)field->comment, -1);
				r_cons_printf ("CCu %s @ 0x%"PFMT64x"\n", e, addr);
				free (e);
				char *f = __filterShell (field->format);
				r_cons_printf ("Cf %d .%s @ 0x%"PFMT64x"\n", field->size, f, addr);
				free (f);
			}
			if (field->format && *field->format) {
				r_cons_printf ("pf.%s %s\n", n, field->format);
			}
			free (n);
		} else if (IS_MODE_JSON (mode)) {
			r_cons_printf ("%s{\"name\":\"%s\","
				"\"vaddr\":%"PFMT64d","
				"\"paddr\":%"PFMT64d,
				iter->p? ",": "",
				field->name,
				field->vaddr,
				field->paddr
				);
			if (field->comment && *field->comment) {
				// TODO: filter comment before json
				r_cons_printf (",\"comment\":\"%s\"", field->comment);
			}
			if (field->format && *field->format) {
				// TODO: filter comment before json
				r_cons_printf (",\"format\":\"%s\"", field->format);
			}
			char *o = r_core_cmd_strf (r, "pfj.%s@0x%"PFMT64x, field->format, field->vaddr);
			if (o && *o) {
				r_cons_printf (",\"pf\":%s", o);
			}
			free (o);
			r_cons_printf ("}");
		} else if (IS_MODE_NORMAL (mode)) {
			const bool haveComment = (field->comment && *field->comment);
			r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s%s%s\n",
				field->vaddr, field->paddr, field->name,
				haveComment? "; ": "",
				haveComment? field->comment: "");
		}
		i++;
	}
	if (IS_MODE_JSON (mode)) {
		r_cons_printf ("]");
	} else if (IS_MODE_NORMAL (mode)) {
		r_cons_printf ("\n%i fields\n", i);
	}

	return true;
}


static void coroutine_fn v9fs_xattrwalk(void *opaque)
{
    int64_t size;
    V9fsString name;
    ssize_t err = 0;
    size_t offset = 7;
    int32_t fid, newfid;
    V9fsFidState *file_fidp;
    V9fsFidState *xattr_fidp = NULL;
    V9fsPDU *pdu = opaque;
    V9fsState *s = pdu->s;

    v9fs_string_init(&name);
    err = pdu_unmarshal(pdu, offset, "dds", &fid, &newfid, &name);
    if (err < 0) {
        goto out_nofid;
    }
    trace_v9fs_xattrwalk(pdu->tag, pdu->id, fid, newfid, name.data);

    file_fidp = get_fid(pdu, fid);
    if (file_fidp == NULL) {
        err = -ENOENT;
        goto out_nofid;
    }
    xattr_fidp = alloc_fid(s, newfid);
    if (xattr_fidp == NULL) {
        err = -EINVAL;
        goto out;
    }
    v9fs_path_copy(&xattr_fidp->path, &file_fidp->path);
    if (!v9fs_string_size(&name)) {
        /*
         * listxattr request. Get the size first
         */
        size = v9fs_co_llistxattr(pdu, &xattr_fidp->path, NULL, 0);
        if (size < 0) {
            err = size;
            clunk_fid(s, xattr_fidp->fid);
            goto out;
        }
        /*
         * Read the xattr value
         */
        xattr_fidp->fs.xattr.len = size;
        xattr_fidp->fid_type = P9_FID_XATTR;
        xattr_fidp->fs.xattr.copied_len = -1;
        if (size) {
            xattr_fidp->fs.xattr.value = g_malloc(size);
            err = v9fs_co_llistxattr(pdu, &xattr_fidp->path,
                                     xattr_fidp->fs.xattr.value,
                                     xattr_fidp->fs.xattr.len);
            if (err < 0) {
                clunk_fid(s, xattr_fidp->fid);
                goto out;
            }
        }
        err = pdu_marshal(pdu, offset, "q", size);
        if (err < 0) {
            goto out;
        }
        err += offset;
    } else {
        /*
         * specific xattr fid. We check for xattr
         * presence also collect the xattr size
         */
        size = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
                                 &name, NULL, 0);
        if (size < 0) {
            err = size;
            clunk_fid(s, xattr_fidp->fid);
            goto out;
        }
        /*
         * Read the xattr value
         */
        xattr_fidp->fs.xattr.len = size;
        xattr_fidp->fid_type = P9_FID_XATTR;
        xattr_fidp->fs.xattr.copied_len = -1;
        if (size) {
            xattr_fidp->fs.xattr.value = g_malloc(size);
            err = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
                                    &name, xattr_fidp->fs.xattr.value,
                                    xattr_fidp->fs.xattr.len);
            if (err < 0) {
                clunk_fid(s, xattr_fidp->fid);
                goto out;
            }
        }
        err = pdu_marshal(pdu, offset, "q", size);
        if (err < 0) {
            goto out;
        }
        err += offset;
    }
    trace_v9fs_xattrwalk_return(pdu->tag, pdu->id, size);
out:
    put_fid(pdu, file_fidp);
    if (xattr_fidp) {
        put_fid(pdu, xattr_fidp);
    }
out_nofid:
    pdu_complete(pdu, err);
    v9fs_string_free(&name);
}


  PictureLayerImplTest()
      : proxy_(base::MessageLoopProxy::current()),
        host_impl_(LowResTilingsSettings(), &proxy_, &shared_bitmap_manager_),
        root_id_(6),
        id_(7),
        pending_layer_(nullptr),
        old_pending_layer_(nullptr),
        active_layer_(nullptr) {
    host_impl_.SetViewportSize(gfx::Size(10000, 10000));
  }


void ContainerNode::focusStateChanged()
{
    if (!layoutObject())
        return;

    if (styleChangeType() < SubtreeStyleChange) {
        if (computedStyle()->affectedByFocus() && computedStyle()->hasPseudoStyle(FIRST_LETTER))
            setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::createWithExtraData(StyleChangeReason::PseudoClass, StyleChangeExtraData::Focus));
        else if (isElementNode() && toElement(this)->childrenOrSiblingsAffectedByFocus())
            document().styleEngine().pseudoStateChangedForElement(CSSSelector::PseudoFocus, *toElement(this));
        else if (computedStyle()->affectedByFocus())
            setNeedsStyleRecalc(LocalStyleChange, StyleChangeReasonForTracing::createWithExtraData(StyleChangeReason::PseudoClass, StyleChangeExtraData::Focus));
    }

    LayoutTheme::theme().controlStateChanged(*layoutObject(), FocusControlState);
}


MagickExport MagickBooleanType SetBlobExtent(Image *image,
  const MagickSizeType extent)
{
  BlobInfo
    *magick_restrict blob_info;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(image->blob != (BlobInfo *) NULL);
  assert(image->blob->type != UndefinedStream);
  blob_info=image->blob;
  switch (blob_info->type)
  {
    case UndefinedStream:
      break;
    case StandardStream:
      return(MagickFalse);
    case FileStream:
    {
      MagickOffsetType
        offset;

      ssize_t
        count;

      if (extent != (MagickSizeType) ((off_t) extent))
        return(MagickFalse);
      offset=SeekBlob(image,0,SEEK_END);
      if (offset < 0)
        return(MagickFalse);
      if ((MagickSizeType) offset >= extent)
        break;
      offset=SeekBlob(image,(MagickOffsetType) extent-1,SEEK_SET);
      if (offset < 0)
        break;
      count=(ssize_t) fwrite((const unsigned char *) "",1,1,
        blob_info->file_info.file);
#if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
      if (blob_info->synchronize != MagickFalse)
        {
          int
            file;

          file=fileno(blob_info->file_info.file);
          if ((file == -1) || (offset < 0))
            return(MagickFalse);
          (void) posix_fallocate(file,offset,extent-offset);
        }
#endif
      offset=SeekBlob(image,offset,SEEK_SET);
      if (count != 1)
        return(MagickFalse);
      break;
    }
    case PipeStream:
    case ZipStream:
      return(MagickFalse);
    case BZipStream:
      return(MagickFalse);
    case FifoStream:
      return(MagickFalse);
    case BlobStream:
    {
      if (extent != (MagickSizeType) ((size_t) extent))
        return(MagickFalse);
      if (blob_info->mapped != MagickFalse)
        {
          MagickOffsetType
            offset;

          ssize_t
            count;

          (void) UnmapBlob(blob_info->data,blob_info->length);
          RelinquishMagickResource(MapResource,blob_info->length);
          if (extent != (MagickSizeType) ((off_t) extent))
            return(MagickFalse);
          offset=SeekBlob(image,0,SEEK_END);
          if (offset < 0)
            return(MagickFalse);
          if ((MagickSizeType) offset >= extent)
            break;
          offset=SeekBlob(image,(MagickOffsetType) extent-1,SEEK_SET);
          count=(ssize_t) fwrite((const unsigned char *) "",1,1,
            blob_info->file_info.file);
#if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
          if (blob_info->synchronize != MagickFalse)
            {
              int
                file;

              file=fileno(blob_info->file_info.file);
              if ((file == -1) || (offset < 0))
                return(MagickFalse);
              (void) posix_fallocate(file,offset,extent-offset);
            }
#endif
          offset=SeekBlob(image,offset,SEEK_SET);
          if (count != 1)
            return(MagickFalse);
          (void) AcquireMagickResource(MapResource,extent);
          blob_info->data=(unsigned char*) MapBlob(fileno(
            blob_info->file_info.file),WriteMode,0,(size_t) extent);
          blob_info->extent=(size_t) extent;
          blob_info->length=(size_t) extent;
          (void) SyncBlob(image);
          break;
        }
      blob_info->extent=(size_t) extent;
      blob_info->data=(unsigned char *) ResizeQuantumMemory(blob_info->data,
        blob_info->extent+1,sizeof(*blob_info->data));
      (void) SyncBlob(image);
      if (blob_info->data == (unsigned char *) NULL)
        {
          (void) DetachBlob(blob_info);
          return(MagickFalse);
        }
      break;
    }
    case CustomStream:
      break;
  }
  return(MagickTrue);
}


static void set_last_buddy(struct sched_entity *se)
{
	if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
		return;

	for_each_sched_entity(se) {
		if (SCHED_WARN_ON(!se->on_rq))
			return;
		cfs_rq_of(se)->last = se;
	}
}


static int vpc_open(BlockDriverState *bs, QDict *options, int flags,

                    Error **errp)

{

    BDRVVPCState *s = bs->opaque;

    int i;

    VHDFooter *footer;

    VHDDynDiskHeader *dyndisk_header;

    uint8_t buf[HEADER_SIZE];

    uint32_t checksum;

    int disk_type = VHD_DYNAMIC;

    int ret;

    ret = bdrv_pread(bs->file, 0, s->footer_buf, HEADER_SIZE);

    if (ret < 0) {

        goto fail;

    }

    footer = (VHDFooter *) s->footer_buf;

    if (strncmp(footer->creator, "conectix", 8)) {

        int64_t offset = bdrv_getlength(bs->file);

        if (offset < 0) {

            ret = offset;

            goto fail;

        } else if (offset < HEADER_SIZE) {

            ret = -EINVAL;

            goto fail;

        }

        /* If a fixed disk, the footer is found only at the end of the file */

        ret = bdrv_pread(bs->file, offset-HEADER_SIZE, s->footer_buf,

                         HEADER_SIZE);

        if (ret < 0) {

            goto fail;

        }

        if (strncmp(footer->creator, "conectix", 8)) {

            error_setg(errp, "invalid VPC image");

            ret = -EINVAL;

            goto fail;

        }

        disk_type = VHD_FIXED;

    }

    checksum = be32_to_cpu(footer->checksum);

    footer->checksum = 0;

    if (vpc_checksum(s->footer_buf, HEADER_SIZE) != checksum)

        fprintf(stderr, "block-vpc: The header checksum of '%s' is "

            "incorrect.\n", bs->filename);

    /* Write 'checksum' back to footer, or else will leave it with zero. */

    footer->checksum = be32_to_cpu(checksum);

    // The visible size of a image in Virtual PC depends on the geometry

    // rather than on the size stored in the footer (the size in the footer

    // is too large usually)

    bs->total_sectors = (int64_t)

        be16_to_cpu(footer->cyls) * footer->heads * footer->secs_per_cyl;

    /* images created with disk2vhd report a far higher virtual size

     * than expected with the cyls * heads * sectors_per_cyl formula.

     * use the footer->size instead if the image was created with

     * disk2vhd.

     */

    if (!strncmp(footer->creator_app, "d2v", 4)) {

        bs->total_sectors = be64_to_cpu(footer->size) / BDRV_SECTOR_SIZE;

    }

    /* Allow a maximum disk size of approximately 2 TB */

    if (bs->total_sectors >= 65535LL * 255 * 255) {

        ret = -EFBIG;

        goto fail;

    }

    if (disk_type == VHD_DYNAMIC) {

        ret = bdrv_pread(bs->file, be64_to_cpu(footer->data_offset), buf,

                         HEADER_SIZE);

        if (ret < 0) {

            goto fail;

        }

        dyndisk_header = (VHDDynDiskHeader *) buf;

        if (strncmp(dyndisk_header->magic, "cxsparse", 8)) {

            ret = -EINVAL;

            goto fail;

        }

        s->block_size = be32_to_cpu(dyndisk_header->block_size);

        s->bitmap_size = ((s->block_size / (8 * 512)) + 511) & ~511;

        s->max_table_entries = be32_to_cpu(dyndisk_header->max_table_entries);

        s->pagetable = g_malloc(s->max_table_entries * 4);

        s->bat_offset = be64_to_cpu(dyndisk_header->table_offset);

        ret = bdrv_pread(bs->file, s->bat_offset, s->pagetable,

                         s->max_table_entries * 4);

        if (ret < 0) {

            goto fail;

        }

        s->free_data_block_offset =

            (s->bat_offset + (s->max_table_entries * 4) + 511) & ~511;

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

            be32_to_cpus(&s->pagetable[i]);

            if (s->pagetable[i] != 0xFFFFFFFF) {

                int64_t next = (512 * (int64_t) s->pagetable[i]) +

                    s->bitmap_size + s->block_size;

                if (next > s->free_data_block_offset) {

                    s->free_data_block_offset = next;

                }

            }

        }

        if (s->free_data_block_offset > bdrv_getlength(bs->file)) {

            error_setg(errp, "block-vpc: free_data_block_offset points after "

                             "the end of file. The image has been truncated.");

            ret = -EINVAL;

            goto fail;

        }

        s->last_bitmap_offset = (int64_t) -1;

#ifdef CACHE

        s->pageentry_u8 = g_malloc(512);

        s->pageentry_u32 = s->pageentry_u8;

        s->pageentry_u16 = s->pageentry_u8;

        s->last_pagetable = -1;

#endif

    }

    qemu_co_mutex_init(&s->lock);

    /* Disable migration when VHD images are used */

    error_set(&s->migration_blocker,

              QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,

              "vpc", bs->device_name, "live migration");

    migrate_add_blocker(s->migration_blocker);

    return 0;

fail:

    g_free(s->pagetable);

#ifdef CACHE

    g_free(s->pageentry_u8);

#endif

    return ret;

}


int rxrpc_kernel_get_error_number(struct sk_buff *skb)
{
	struct rxrpc_skb_priv *sp = rxrpc_skb(skb);

	return sp->error;
}


int av_get_channel_layout_nb_channels(int64_t channel_layout)

{

    int count;

    uint64_t x = channel_layout;

    for (count = 0; x; count++)

        x &= x-1; // unset lowest set bit

    return count;

}


static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
	u32 eb;

	eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
	     (1u << NM_VECTOR) | (1u << DB_VECTOR);
	if ((vcpu->guest_debug &
	     (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
	    (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
		eb |= 1u << BP_VECTOR;
	if (to_vmx(vcpu)->rmode.vm86_active)
		eb = ~0;
	if (enable_ept)
		eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
	if (vcpu->fpu_active)
		eb &= ~(1u << NM_VECTOR);

	/* When we are running a nested L2 guest and L1 specified for it a
	 * certain exception bitmap, we must trap the same exceptions and pass
	 * them to L1. When running L2, we will only handle the exceptions
	 * specified above if L1 did not want them.
	 */
	if (is_guest_mode(vcpu))
		eb |= get_vmcs12(vcpu)->exception_bitmap;

	vmcs_write32(EXCEPTION_BITMAP, eb);
}


static void gic_dist_writeb ( void * opaque , hwaddr offset , uint32_t value ) {
 GICState * s = ( GICState * ) opaque ;
 int irq ;
 int i ;
 int cpu ;
 cpu = gic_get_current_cpu ( s ) ;
 if ( offset < 0x100 ) {
 if ( offset == 0 ) {
 s -> enabled = ( value & 1 ) ;
 DPRINTF ( "Distribution %sabled\n" , s -> enabled ? "En" : "Dis" ) ;
 }
 else if ( offset < 4 ) {
 }
 else if ( offset >= 0x80 ) {
 }
 else {
 goto bad_reg ;
 }
 }
 else if ( offset < 0x180 ) {
 irq = ( offset - 0x100 ) * 8 + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) goto bad_reg ;
 if ( irq < 16 ) value = 0xff ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) {
 if ( value & ( 1 << i ) ) {
 int mask = ( irq < GIC_INTERNAL ) ? ( 1 << cpu ) : GIC_TARGET ( irq + i ) ;
 int cm = ( irq < GIC_INTERNAL ) ? ( 1 << cpu ) : ALL_CPU_MASK ;
 if ( ! GIC_TEST_ENABLED ( irq + i , cm ) ) {
 DPRINTF ( "Enabled IRQ %d\n" , irq + i ) ;
 }
 GIC_SET_ENABLED ( irq + i , cm ) ;
 if ( GIC_TEST_LEVEL ( irq + i , mask ) && ! GIC_TEST_TRIGGER ( irq + i ) ) {
 DPRINTF ( "Set %d pending mask %x\n" , irq + i , mask ) ;
 GIC_SET_PENDING ( irq + i , mask ) ;
 }
 }
 }
 }
 else if ( offset < 0x200 ) {
 irq = ( offset - 0x180 ) * 8 + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) goto bad_reg ;
 if ( irq < 16 ) value = 0 ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) {
 if ( value & ( 1 << i ) ) {
 int cm = ( irq < GIC_INTERNAL ) ? ( 1 << cpu ) : ALL_CPU_MASK ;
 if ( GIC_TEST_ENABLED ( irq + i , cm ) ) {
 DPRINTF ( "Disabled IRQ %d\n" , irq + i ) ;
 }
 GIC_CLEAR_ENABLED ( irq + i , cm ) ;
 }
 }
 }
 else if ( offset < 0x280 ) {
 irq = ( offset - 0x200 ) * 8 + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) goto bad_reg ;
 if ( irq < 16 ) irq = 0 ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) {
 if ( value & ( 1 << i ) ) {
 GIC_SET_PENDING ( irq + i , GIC_TARGET ( irq + i ) ) ;
 }
 }
 }
 else if ( offset < 0x300 ) {
 irq = ( offset - 0x280 ) * 8 + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) goto bad_reg ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) {
 if ( value & ( 1 << i ) ) {
 GIC_CLEAR_PENDING ( irq + i , ALL_CPU_MASK ) ;
 }
 }
 }
 else if ( offset < 0x400 ) {
 goto bad_reg ;
 }
 else if ( offset < 0x800 ) {
 irq = ( offset - 0x400 ) + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) goto bad_reg ;
 if ( irq < GIC_INTERNAL ) {
 s -> priority1 [ irq ] [ cpu ] = value ;
 }
 else {
 s -> priority2 [ irq - GIC_INTERNAL ] = value ;
 }
 }
 else if ( offset < 0xc00 ) {
 if ( s -> num_cpu != 1 || s -> revision == REV_11MPCORE ) {
 irq = ( offset - 0x800 ) + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) {
 goto bad_reg ;
 }
 if ( irq < 29 ) {
 value = 0 ;
 }
 else if ( irq < GIC_INTERNAL ) {
 value = ALL_CPU_MASK ;
 }
 s -> irq_target [ irq ] = value & ALL_CPU_MASK ;
 }
 }
 else if ( offset < 0xf00 ) {
 irq = ( offset - 0xc00 ) * 4 + GIC_BASE_IRQ ;
 if ( irq >= s -> num_irq ) goto bad_reg ;
 if ( irq < GIC_INTERNAL ) value |= 0xaa ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 if ( value & ( 1 << ( i * 2 ) ) ) {
 GIC_SET_MODEL ( irq + i ) ;
 }
 else {
 GIC_CLEAR_MODEL ( irq + i ) ;
 }
 if ( value & ( 2 << ( i * 2 ) ) ) {
 GIC_SET_TRIGGER ( irq + i ) ;
 }
 else {
 GIC_CLEAR_TRIGGER ( irq + i ) ;
 }
 }
 }
 else {
 goto bad_reg ;
 }
 gic_update ( s ) ;
 return ;
 bad_reg : qemu_log_mask ( LOG_GUEST_ERROR , "gic_dist_writeb: Bad offset %x\n" , ( int ) offset ) ;
 }


netlink_send(int fd, struct cn_msg *msg)
{
	struct nlmsghdr *nlh;
	unsigned int size;
	struct msghdr message;
	char buffer[64];
	struct iovec iov[2];

	size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);

	nlh = (struct nlmsghdr *)buffer;
	nlh->nlmsg_seq = 0;
	nlh->nlmsg_pid = getpid();
	nlh->nlmsg_type = NLMSG_DONE;
	nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
	nlh->nlmsg_flags = 0;

	iov[0].iov_base = nlh;
	iov[0].iov_len = sizeof(*nlh);

	iov[1].iov_base = msg;
	iov[1].iov_len = size;

	memset(&message, 0, sizeof(message));
	message.msg_name = &addr;
	message.msg_namelen = sizeof(addr);
	message.msg_iov = iov;
	message.msg_iovlen = 2;

	return sendmsg(fd, &message, 0);
}


static int wavpack_encode_block(WavPackEncodeContext *s,

                                int32_t *samples_l, int32_t *samples_r,

                                uint8_t *out, int out_size)

{

    int block_size, start, end, data_size, tcount, temp, m = 0;

    int i, j, ret, got_extra = 0, nb_samples = s->block_samples;

    uint32_t crc = 0xffffffffu;

    struct Decorr *dpp;

    PutByteContext pb;

    if (!(s->flags & WV_MONO) && s->optimize_mono) {

        int32_t lor = 0, diff = 0;

        for (i = 0; i < nb_samples; i++) {

            lor  |= samples_l[i] | samples_r[i];

            diff |= samples_l[i] - samples_r[i];

            if (lor && diff)

                break;

        }

        if (i == nb_samples && lor && !diff) {

            s->flags &= ~(WV_JOINT_STEREO | WV_CROSS_DECORR);

            s->flags |= WV_FALSE_STEREO;

            if (!s->false_stereo) {

                s->false_stereo = 1;

                s->num_terms = 0;

                CLEAR(s->w);

            }

        } else if (s->false_stereo) {

            s->false_stereo = 0;

            s->num_terms = 0;

            CLEAR(s->w);

        }

    }

    if (s->flags & SHIFT_MASK) {

        int shift = (s->flags & SHIFT_MASK) >> SHIFT_LSB;

        int mag = (s->flags & MAG_MASK) >> MAG_LSB;

        if (s->flags & WV_MONO_DATA)

            shift_mono(samples_l, nb_samples, shift);

        else

            shift_stereo(samples_l, samples_r, nb_samples, shift);

        if ((mag -= shift) < 0)

            s->flags &= ~MAG_MASK;

        else

            s->flags -= (1 << MAG_LSB) * shift;

    }

    if ((s->flags & WV_FLOAT_DATA) || (s->flags & MAG_MASK) >> MAG_LSB >= 24) {

        av_fast_padded_malloc(&s->orig_l, &s->orig_l_size, sizeof(int32_t) * nb_samples);

        memcpy(s->orig_l, samples_l, sizeof(int32_t) * nb_samples);

        if (!(s->flags & WV_MONO_DATA)) {

            av_fast_padded_malloc(&s->orig_r, &s->orig_r_size, sizeof(int32_t) * nb_samples);

            memcpy(s->orig_r, samples_r, sizeof(int32_t) * nb_samples);

        }

        if (s->flags & WV_FLOAT_DATA)

            got_extra = scan_float(s, samples_l, samples_r, nb_samples);

        else

            got_extra = scan_int32(s, samples_l, samples_r, nb_samples);

        s->num_terms = 0;

    } else {

        scan_int23(s, samples_l, samples_r, nb_samples);

        if (s->shift != s->int32_zeros + s->int32_ones + s->int32_dups) {

            s->shift = s->int32_zeros + s->int32_ones + s->int32_dups;

            s->num_terms = 0;

        }

    }

    if (!s->num_passes && !s->num_terms) {

        s->num_passes = 1;

        if (s->flags & WV_MONO_DATA)

            ret = wv_mono(s, samples_l, 1, 0);

        else

            ret = wv_stereo(s, samples_l, samples_r, 1, 0);

        s->num_passes = 0;

    }

    if (s->flags & WV_MONO_DATA) {

        for (i = 0; i < nb_samples; i++)

            crc += (crc << 1) + samples_l[i];

        if (s->num_passes)

            ret = wv_mono(s, samples_l, !s->num_terms, 1);

    } else {

        for (i = 0; i < nb_samples; i++)

            crc += (crc << 3) + (samples_l[i] << 1) + samples_l[i] + samples_r[i];

        if (s->num_passes)

            ret = wv_stereo(s, samples_l, samples_r, !s->num_terms, 1);

    }

    if (ret < 0)

        return ret;

    if (!s->ch_offset)

        s->flags |= WV_INITIAL_BLOCK;

    s->ch_offset += 1 + !(s->flags & WV_MONO);

    if (s->ch_offset == s->avctx->channels)

        s->flags |= WV_FINAL_BLOCK;

    bytestream2_init_writer(&pb, out, out_size);

    bytestream2_put_le32(&pb, MKTAG('w', 'v', 'p', 'k'));

    bytestream2_put_le32(&pb, 0);

    bytestream2_put_le16(&pb, 0x410);

    bytestream2_put_le16(&pb, 0);

    bytestream2_put_le32(&pb, 0);

    bytestream2_put_le32(&pb, s->sample_index);

    bytestream2_put_le32(&pb, nb_samples);

    bytestream2_put_le32(&pb, s->flags);

    bytestream2_put_le32(&pb, crc);

    if (s->flags & WV_INITIAL_BLOCK &&

        s->avctx->channel_layout != AV_CH_LAYOUT_MONO &&

        s->avctx->channel_layout != AV_CH_LAYOUT_STEREO) {

        put_metadata_block(&pb, WP_ID_CHANINFO, 5);

        bytestream2_put_byte(&pb, s->avctx->channels);

        bytestream2_put_le32(&pb, s->avctx->channel_layout);

        bytestream2_put_byte(&pb, 0);

    }

    if ((s->flags & SRATE_MASK) == SRATE_MASK) {

        put_metadata_block(&pb, WP_ID_SAMPLE_RATE, 3);

        bytestream2_put_le24(&pb, s->avctx->sample_rate);

        bytestream2_put_byte(&pb, 0);

    }

    put_metadata_block(&pb, WP_ID_DECTERMS, s->num_terms);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        bytestream2_put_byte(&pb, ((dpp->value + 5) & 0x1f) | ((dpp->delta << 5) & 0xe0));

    }

    if (s->num_terms & 1)

        bytestream2_put_byte(&pb, 0);

#define WRITE_DECWEIGHT(type) do {            \

        temp = store_weight(type);    \

        bytestream2_put_byte(&pb, temp);      \

        type = restore_weight(temp);  \

    } while (0)

    bytestream2_put_byte(&pb, WP_ID_DECWEIGHTS);

    bytestream2_put_byte(&pb, 0);

    start = bytestream2_tell_p(&pb);

    for (i = s->num_terms - 1; i >= 0; --i) {

        struct Decorr *dpp = &s->decorr_passes[i];

        if (store_weight(dpp->weightA) ||

            (!(s->flags & WV_MONO_DATA) && store_weight(dpp->weightB)))

                break;

    }

    tcount = i + 1;

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (i < tcount) {

            WRITE_DECWEIGHT(dpp->weightA);

            if (!(s->flags & WV_MONO_DATA))

                WRITE_DECWEIGHT(dpp->weightB);

        } else {

            dpp->weightA = dpp->weightB = 0;

        }

    }

    end = bytestream2_tell_p(&pb);

    out[start - 2] = WP_ID_DECWEIGHTS | (((end - start) & 1) ? WP_IDF_ODD: 0);

    out[start - 1] = (end - start + 1) >> 1;

    if ((end - start) & 1)

        bytestream2_put_byte(&pb, 0);

#define WRITE_DECSAMPLE(type) do {        \

        temp = log2s(type);               \

        type = wp_exp2(temp);             \

        bytestream2_put_le16(&pb, temp);  \

    } while (0)

    bytestream2_put_byte(&pb, WP_ID_DECSAMPLES);

    bytestream2_put_byte(&pb, 0);

    start = bytestream2_tell_p(&pb);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (i == 0) {

            if (dpp->value > MAX_TERM) {

                WRITE_DECSAMPLE(dpp->samplesA[0]);

                WRITE_DECSAMPLE(dpp->samplesA[1]);

                if (!(s->flags & WV_MONO_DATA)) {

                    WRITE_DECSAMPLE(dpp->samplesB[0]);

                    WRITE_DECSAMPLE(dpp->samplesB[1]);

                }

            } else if (dpp->value < 0) {

                WRITE_DECSAMPLE(dpp->samplesA[0]);

                WRITE_DECSAMPLE(dpp->samplesB[0]);

            } else {

                for (j = 0; j < dpp->value; j++) {

                    WRITE_DECSAMPLE(dpp->samplesA[j]);

                    if (!(s->flags & WV_MONO_DATA))

                        WRITE_DECSAMPLE(dpp->samplesB[j]);

                }

            }

        } else {

            CLEAR(dpp->samplesA);

            CLEAR(dpp->samplesB);

        }

    }

    end = bytestream2_tell_p(&pb);

    out[start - 1] = (end - start) >> 1;

#define WRITE_CHAN_ENTROPY(chan) do {               \

        for (i = 0; i < 3; i++) {                   \

            temp = wp_log2(s->w.c[chan].median[i]); \

            bytestream2_put_le16(&pb, temp);        \

            s->w.c[chan].median[i] = wp_exp2(temp); \

        }                                           \

    } while (0)

    put_metadata_block(&pb, WP_ID_ENTROPY, 6 * (1 + (!(s->flags & WV_MONO_DATA))));

    WRITE_CHAN_ENTROPY(0);

    if (!(s->flags & WV_MONO_DATA))

        WRITE_CHAN_ENTROPY(1);

    if (s->flags & WV_FLOAT_DATA) {

        put_metadata_block(&pb, WP_ID_FLOATINFO, 4);

        bytestream2_put_byte(&pb, s->float_flags);

        bytestream2_put_byte(&pb, s->float_shift);

        bytestream2_put_byte(&pb, s->float_max_exp);

        bytestream2_put_byte(&pb, 127);

    }

    if (s->flags & WV_INT32_DATA) {

        put_metadata_block(&pb, WP_ID_INT32INFO, 4);

        bytestream2_put_byte(&pb, s->int32_sent_bits);

        bytestream2_put_byte(&pb, s->int32_zeros);

        bytestream2_put_byte(&pb, s->int32_ones);

        bytestream2_put_byte(&pb, s->int32_dups);

    }

    if (s->flags & WV_MONO_DATA && !s->num_passes) {

        for (i = 0; i < nb_samples; i++) {

            int32_t code = samples_l[i];

            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++) {

                int32_t sam;

                if (dpp->value > MAX_TERM) {

                    if (dpp->value & 1)

                        sam = 2 * dpp->samplesA[0] - dpp->samplesA[1];

                    else

                        sam = (3 * dpp->samplesA[0] - dpp->samplesA[1]) >> 1;

                    dpp->samplesA[1] = dpp->samplesA[0];

                    dpp->samplesA[0] = code;

                } else {

                    sam = dpp->samplesA[m];

                    dpp->samplesA[(m + dpp->value) & (MAX_TERM - 1)] = code;

                }

                code -= APPLY_WEIGHT(dpp->weightA, sam);

                UPDATE_WEIGHT(dpp->weightA, dpp->delta, sam, code);

            }

            m = (m + 1) & (MAX_TERM - 1);

            samples_l[i] = code;

        }

        if (m) {

            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++)

                if (dpp->value > 0 && dpp->value <= MAX_TERM) {

                int32_t temp_A[MAX_TERM], temp_B[MAX_TERM];

                int k;

                memcpy(temp_A, dpp->samplesA, sizeof(dpp->samplesA));

                memcpy(temp_B, dpp->samplesB, sizeof(dpp->samplesB));

                for (k = 0; k < MAX_TERM; k++) {

                    dpp->samplesA[k] = temp_A[m];

                    dpp->samplesB[k] = temp_B[m];

                    m = (m + 1) & (MAX_TERM - 1);

                }

            }

        }

    } else if (!s->num_passes) {

        if (s->flags & WV_JOINT_STEREO) {

            for (i = 0; i < nb_samples; i++)

                samples_r[i] += ((samples_l[i] -= samples_r[i]) >> 1);

        }

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

            struct Decorr *dpp = &s->decorr_passes[i];

            if (((s->flags & MAG_MASK) >> MAG_LSB) >= 16 || dpp->delta != 2)

                decorr_stereo_pass2(dpp, samples_l, samples_r, nb_samples);

            else

                decorr_stereo_pass_id2(dpp, samples_l, samples_r, nb_samples);

        }

    }

    bytestream2_put_byte(&pb, WP_ID_DATA | WP_IDF_LONG);

    init_put_bits(&s->pb, pb.buffer + 3, bytestream2_get_bytes_left_p(&pb));

    if (s->flags & WV_MONO_DATA) {

        for (i = 0; i < nb_samples; i++)

            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);

    } else {

        for (i = 0; i < nb_samples; i++) {

            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);

            wavpack_encode_sample(s, &s->w.c[1], s->samples[1][i]);

        }

    }

    encode_flush(s);

    flush_put_bits(&s->pb);

    data_size = put_bits_count(&s->pb) >> 3;

    bytestream2_put_le24(&pb, (data_size + 1) >> 1);

    bytestream2_skip_p(&pb, data_size);

    if (data_size & 1)

        bytestream2_put_byte(&pb, 0);

    if (got_extra) {

        bytestream2_put_byte(&pb, WP_ID_EXTRABITS | WP_IDF_LONG);

        init_put_bits(&s->pb, pb.buffer + 7, bytestream2_get_bytes_left_p(&pb));

        if (s->flags & WV_FLOAT_DATA)

            pack_float(s, s->orig_l, s->orig_r, nb_samples);

        else

            pack_int32(s, s->orig_l, s->orig_r, nb_samples);

        flush_put_bits(&s->pb);

        data_size = put_bits_count(&s->pb) >> 3;

        bytestream2_put_le24(&pb, (data_size + 5) >> 1);

        bytestream2_put_le32(&pb, s->crc_x);

        bytestream2_skip_p(&pb, data_size);

        if (data_size & 1)

            bytestream2_put_byte(&pb, 0);

    }

    block_size = bytestream2_tell_p(&pb);

    AV_WL32(out + 4, block_size - 8);

    return block_size;

}


int git_checkout_head(
	git_repository *repo,
	const git_checkout_options *opts)
{
	assert(repo);
	return git_checkout_tree(repo, NULL, opts);
}


mrb_ary_eq(mrb_state *mrb, mrb_value ary1)
{
  mrb_value ary2 = mrb_get_arg1(mrb);

  mrb->c->ci->mid = 0;
  if (mrb_obj_equal(mrb, ary1, ary2)) return mrb_true_value();
  if (!mrb_array_p(ary2)) {
    return mrb_false_value();
  }
  if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return mrb_false_value();

  return ary2;
}


size_t zmalloc_usable(void *ptr) {
    return zmalloc_size(ptr)-PREFIX_SIZE;
}


explicit MapSizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}


GF_Err pixi_dump(GF_Box *a, FILE * trace)
{
	u32 i;
	GF_PixelInformationPropertyBox *ptr = (GF_PixelInformationPropertyBox *)a;
	if (!a) return GF_BAD_PARAM;
	gf_isom_box_dump_start(a, "PixelInformationPropertyBox", trace);
	fprintf(trace, ">\n");
	for (i = 0; i < ptr->num_channels; i++) {
		fprintf(trace, "<BitPerChannel bits_per_channel=\"%d\"/>\n", ptr->bits_per_channel[i]);
	}
	if (!ptr->size)
		fprintf(trace, "<BitPerChannel bits_per_channel=\"\"/>\n");

	gf_isom_box_dump_done("PixelInformationPropertyBox", a, trace);
	return GF_OK;
}


static bool send_app_scn(rfc_slot_t *slot) {
 if(slot->scn_notified == true) {
 return true;
 }
  slot->scn_notified = true;
 return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) == sizeof(slot->scn);
}


void __hci_req_update_adv_data(struct hci_request *req, u8 instance)
{
	struct hci_dev *hdev = req->hdev;
	u8 len;

	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
		return;

	if (ext_adv_capable(hdev)) {
		struct hci_cp_le_set_ext_adv_data cp;

		memset(&cp, 0, sizeof(cp));

		len = create_instance_adv_data(hdev, instance, cp.data);

		/* There's nothing to do if the data hasn't changed */
		if (hdev->adv_data_len == len &&
		    memcmp(cp.data, hdev->adv_data, len) == 0)
			return;

		memcpy(hdev->adv_data, cp.data, sizeof(cp.data));
		hdev->adv_data_len = len;

		cp.length = len;
		cp.handle = instance;
		cp.operation = LE_SET_ADV_DATA_OP_COMPLETE;
		cp.frag_pref = LE_SET_ADV_DATA_NO_FRAG;

		hci_req_add(req, HCI_OP_LE_SET_EXT_ADV_DATA, sizeof(cp), &cp);
	} else {
		struct hci_cp_le_set_adv_data cp;

		memset(&cp, 0, sizeof(cp));

		len = create_instance_adv_data(hdev, instance, cp.data);

		/* There's nothing to do if the data hasn't changed */
		if (hdev->adv_data_len == len &&
		    memcmp(cp.data, hdev->adv_data, len) == 0)
			return;

		memcpy(hdev->adv_data, cp.data, sizeof(cp.data));
		hdev->adv_data_len = len;

		cp.length = len;

		hci_req_add(req, HCI_OP_LE_SET_ADV_DATA, sizeof(cp), &cp);
	}
}


int kvm_arch_init(MachineState *ms, KVMState *s)

{

    MachineClass *mc = MACHINE_GET_CLASS(ms);

    mc->default_cpu_type = S390_CPU_TYPE_NAME("host");

    cap_sync_regs = kvm_check_extension(s, KVM_CAP_SYNC_REGS);

    cap_async_pf = kvm_check_extension(s, KVM_CAP_ASYNC_PF);

    cap_mem_op = kvm_check_extension(s, KVM_CAP_S390_MEM_OP);

    cap_s390_irq = kvm_check_extension(s, KVM_CAP_S390_INJECT_IRQ);

    if (!kvm_check_extension(s, KVM_CAP_S390_GMAP)

        || !kvm_check_extension(s, KVM_CAP_S390_COW)) {

        phys_mem_set_alloc(legacy_s390_alloc);

    }

    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_SIGP, 0);

    kvm_vm_enable_cap(s, KVM_CAP_S390_VECTOR_REGISTERS, 0);

    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_STSI, 0);

    if (ri_allowed()) {

        if (kvm_vm_enable_cap(s, KVM_CAP_S390_RI, 0) == 0) {

            cap_ri = 1;

        }

    }

    if (gs_allowed()) {

        if (kvm_vm_enable_cap(s, KVM_CAP_S390_GS, 0) == 0) {

            cap_gs = 1;

        }

    }

    /*

     * The migration interface for ais was introduced with kernel 4.13

     * but the capability itself had been active since 4.12. As migration

     * support is considered necessary let's disable ais in the 2.10

     * machine.

     */

    /* kvm_vm_enable_cap(s, KVM_CAP_S390_AIS, 0); */

    return 0;

}


void ProfileSyncService::OnEncryptionComplete() {
  DVLOG(1) << "Encryption complete";
  if (encryption_pending_ && encrypt_everything_) {
    encryption_pending_ = false;
    NotifyObservers();
  }
}


ASN1_BIT_STRING * c2i_ASN1_BIT_STRING ( ASN1_BIT_STRING * * a , const unsigned char * * pp , long len ) {
 ASN1_BIT_STRING * ret = NULL ;
 const unsigned char * p ;
 unsigned char * s ;
 int i ;
 if ( len < 1 ) {
 i = ASN1_R_STRING_TOO_SHORT ;
 goto err ;
 }
 if ( ( a == NULL ) || ( ( * a ) == NULL ) ) {
 if ( ( ret = M_ASN1_BIT_STRING_new ( ) ) == NULL ) return ( NULL ) ;
 }
 else ret = ( * a ) ;
 p = * pp ;
 i = * ( p ++ ) ;
 if ( i > 7 ) {
 i = ASN1_R_INVALID_BIT_STRING_BITS_LEFT ;
 goto err ;
 }
 ret -> flags &= ~ ( ASN1_STRING_FLAG_BITS_LEFT | 0x07 ) ;
 ret -> flags |= ( ASN1_STRING_FLAG_BITS_LEFT | i ) ;
 if ( len -- > 1 ) {
 s = ( unsigned char * ) OPENSSL_malloc ( ( int ) len ) ;
 if ( s == NULL ) {
 i = ERR_R_MALLOC_FAILURE ;
 goto err ;
 }
 memcpy ( s , p , ( int ) len ) ;
 s [ len - 1 ] &= ( 0xff << i ) ;
 p += len ;
 }
 else s = NULL ;
 ret -> length = ( int ) len ;
 if ( ret -> data != NULL ) OPENSSL_free ( ret -> data ) ;
 ret -> data = s ;
 ret -> type = V_ASN1_BIT_STRING ;
 if ( a != NULL ) ( * a ) = ret ;
 * pp = p ;
 return ( ret ) ;
 err : ASN1err ( ASN1_F_C2I_ASN1_BIT_STRING , i ) ;
 if ( ( ret != NULL ) && ( ( a == NULL ) || ( * a != ret ) ) ) M_ASN1_BIT_STRING_free ( ret ) ;
 return ( NULL ) ;
 }


OMX_ERRORTYPE  omx_vdec::set_config(OMX_IN OMX_HANDLETYPE      hComp,
        OMX_IN OMX_INDEXTYPE configIndex,
        OMX_IN OMX_PTR        configData)
{
 (void) hComp;
 if (m_state == OMX_StateInvalid) {
        DEBUG_PRINT_ERROR("Get Config in Invalid State");
 return OMX_ErrorInvalidState;
 }

    OMX_ERRORTYPE ret = OMX_ErrorNone;
    OMX_VIDEO_CONFIG_NALSIZE *pNal;

    DEBUG_PRINT_LOW("Set Config Called");

 if (configIndex == (OMX_INDEXTYPE)OMX_IndexVendorVideoExtraData) {
        OMX_VENDOR_EXTRADATATYPE *config = (OMX_VENDOR_EXTRADATATYPE *) configData;
        DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData called");
 if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc") ||
 !strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc")) {
            DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData AVC");
            OMX_U32 extra_size;

            nal_length = (config->pData[4] & 0x03) + 1;

            extra_size = 0;
 if (nal_length > 2) {
 /* Presently we assume that only one SPS and one PPS in AvC1 Atom */
                extra_size = (nal_length - 2) * 2;
 }

            OMX_U8 *pSrcBuf = (OMX_U8 *) (&config->pData[6]);
            OMX_U8 *pDestBuf;
            m_vendor_config.nPortIndex = config->nPortIndex;

            m_vendor_config.nDataSize = config->nDataSize - 6 - 1 + extra_size;
            m_vendor_config.pData = (OMX_U8 *) malloc(m_vendor_config.nDataSize);
            OMX_U32 len;
            OMX_U8 index = 0;
            pDestBuf = m_vendor_config.pData;

            DEBUG_PRINT_LOW("Rxd SPS+PPS nPortIndex[%u] len[%u] data[%p]",
 (unsigned int)m_vendor_config.nPortIndex,
 (unsigned int)m_vendor_config.nDataSize,
                    m_vendor_config.pData);
 while (index < 2) {
 uint8 *psize;
                len = *pSrcBuf;
                len = len << 8;
                len |= *(pSrcBuf + 1);
                psize = (uint8 *) & len;
                memcpy(pDestBuf + nal_length, pSrcBuf + 2,len);
 for (unsigned int i = 0; i < nal_length; i++) {
                    pDestBuf[i] = psize[nal_length - 1 - i];
 }
                pDestBuf += len + nal_length;
                pSrcBuf += len + 2;
                index++;
                pSrcBuf++; // skip picture param set
                len = 0;
 }
 } else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4") ||
 !strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2")) {
            m_vendor_config.nPortIndex = config->nPortIndex;
            m_vendor_config.nDataSize = config->nDataSize;
            m_vendor_config.pData = (OMX_U8 *) malloc((config->nDataSize));
            memcpy(m_vendor_config.pData, config->pData,config->nDataSize);
 } else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1")) {
 if (m_vendor_config.pData) {
                free(m_vendor_config.pData);
                m_vendor_config.pData = NULL;
                m_vendor_config.nDataSize = 0;
 }

 if (((*((OMX_U32 *) config->pData)) &
                        VC1_SP_MP_START_CODE_MASK) ==
                    VC1_SP_MP_START_CODE) {
                DEBUG_PRINT_LOW("set_config - VC1 simple/main profile");
                m_vendor_config.nPortIndex = config->nPortIndex;
                m_vendor_config.nDataSize = config->nDataSize;
                m_vendor_config.pData =
 (OMX_U8 *) malloc(config->nDataSize);
                memcpy(m_vendor_config.pData, config->pData,
                        config->nDataSize);
                m_vc1_profile = VC1_SP_MP_RCV;
 } else if (*((OMX_U32 *) config->pData) == VC1_AP_SEQ_START_CODE) {
                DEBUG_PRINT_LOW("set_config - VC1 Advance profile");
                m_vendor_config.nPortIndex = config->nPortIndex;
                m_vendor_config.nDataSize = config->nDataSize;
                m_vendor_config.pData =
 (OMX_U8 *) malloc((config->nDataSize));
                memcpy(m_vendor_config.pData, config->pData,
                        config->nDataSize);
                m_vc1_profile = VC1_AP;
 } else if ((config->nDataSize == VC1_STRUCT_C_LEN)) {
                DEBUG_PRINT_LOW("set_config - VC1 Simple/Main profile struct C only");
                m_vendor_config.nPortIndex = config->nPortIndex;
                m_vendor_config.nDataSize  = config->nDataSize;
                m_vendor_config.pData = (OMX_U8*)malloc(config->nDataSize);
                memcpy(m_vendor_config.pData,config->pData,config->nDataSize);
                m_vc1_profile = VC1_SP_MP_RCV;
 } else {
                DEBUG_PRINT_LOW("set_config - Error: Unknown VC1 profile");
 }
 }
 return ret;
 } else if (configIndex == OMX_IndexConfigVideoNalSize) {

         struct v4l2_control temp;
         temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT;

        VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_NALSIZE);
         pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData);
         switch (pNal->nNaluBytes) {
             case 0:
                temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES;
 break;
 case 2:
                temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH;
 break;
 case 4:
                temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH;
 break;
 default:
 return OMX_ErrorUnsupportedSetting;
 }

 if (!arbitrary_bytes) {
 /* In arbitrary bytes mode, the assembler strips out nal size and replaces
             * with start code, so only need to notify driver in frame by frame mode */
 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &temp)) {
                DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT");
 return OMX_ErrorHardware;
 }
 }

        nal_length = pNal->nNaluBytes;
        m_frame_parser.init_nal_length(nal_length);

        DEBUG_PRINT_LOW("OMX_IndexConfigVideoNalSize called with Size %d", nal_length);
 return ret;
 } else if ((int)configIndex == (int)OMX_IndexVendorVideoFrameRate) {
        OMX_VENDOR_VIDEOFRAMERATE *config = (OMX_VENDOR_VIDEOFRAMERATE *) configData;
        DEBUG_PRINT_HIGH("Index OMX_IndexVendorVideoFrameRate %u", (unsigned int)config->nFps);

 if (config->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) {
 if (config->bEnabled) {
 if ((config->nFps >> 16) > 0) {
                    DEBUG_PRINT_HIGH("set_config: frame rate set by omx client : %u",
 (unsigned int)config->nFps >> 16);
                    Q16ToFraction(config->nFps, drv_ctx.frame_rate.fps_numerator,
                            drv_ctx.frame_rate.fps_denominator);

 if (!drv_ctx.frame_rate.fps_numerator) {
                        DEBUG_PRINT_ERROR("Numerator is zero setting to 30");
                        drv_ctx.frame_rate.fps_numerator = 30;
 }

 if (drv_ctx.frame_rate.fps_denominator) {
                        drv_ctx.frame_rate.fps_numerator = (int)
                            drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator;
 }

                    drv_ctx.frame_rate.fps_denominator = 1;
                    frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 /
                        drv_ctx.frame_rate.fps_numerator;

 struct v4l2_outputparm oparm;
 /*XXX: we're providing timing info as seconds per frame rather than frames
                     * per second.*/
                    oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator;
                    oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator;

 struct v4l2_streamparm sparm;
                    sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
                    sparm.parm.output = oparm;
 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) {
                        DEBUG_PRINT_ERROR("Unable to convey fps info to driver, \
                                performance might be affected");
                        ret = OMX_ErrorHardware;
 }
                    client_set_fps = true;
 } else {
                    DEBUG_PRINT_ERROR("Frame rate not supported.");
                    ret = OMX_ErrorUnsupportedSetting;
 }
 } else {
                DEBUG_PRINT_HIGH("set_config: Disabled client's frame rate");
                client_set_fps = false;
 }
 } else {
            DEBUG_PRINT_ERROR(" Set_config: Bad Port idx %d",
 (int)config->nPortIndex);
            ret = OMX_ErrorBadPortIndex;
 }

 return ret;
 } else if ((int)configIndex == (int)OMX_QcomIndexConfigPerfLevel) {
        OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf =
 (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData;
 struct v4l2_control control;

        DEBUG_PRINT_LOW("Set perf level: %d", perf->ePerfLevel);

        control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL;

 switch (perf->ePerfLevel) {
 case OMX_QCOM_PerfLevelNominal:
                control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL;
 break;
 case OMX_QCOM_PerfLevelTurbo:
                control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO;
 break;
 default:
                ret = OMX_ErrorUnsupportedSetting;
 break;
 }

 if (ret == OMX_ErrorNone) {
            ret = (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) ?
                OMX_ErrorUnsupportedSetting : OMX_ErrorNone;
 }

 return ret;
 } else if ((int)configIndex == (int)OMX_IndexConfigPriority) {
        OMX_PARAM_U32TYPE *priority = (OMX_PARAM_U32TYPE *)configData;
        DEBUG_PRINT_LOW("Set_config: priority %d", priority->nU32);

 struct v4l2_control control;

        control.id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY;
 if (priority->nU32 == 0)
            control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE;
 else
            control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE;

 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
            DEBUG_PRINT_ERROR("Failed to set Priority");
            ret = OMX_ErrorUnsupportedSetting;
 }
 return ret;
 } else if ((int)configIndex == (int)OMX_IndexConfigOperatingRate) {
        OMX_PARAM_U32TYPE *rate = (OMX_PARAM_U32TYPE *)configData;
        DEBUG_PRINT_LOW("Set_config: operating-rate %u fps", rate->nU32 >> 16);

 struct v4l2_control control;

        control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE;
        control.value = rate->nU32;

 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
            ret = errno == -EBUSY ? OMX_ErrorInsufficientResources :
                    OMX_ErrorUnsupportedSetting;
            DEBUG_PRINT_ERROR("Failed to set operating rate %u fps (%s)",
                    rate->nU32 >> 16, errno == -EBUSY ? "HW Overload" : strerror(errno));
 }
 return ret;
 }

 return OMX_ErrorNotImplemented;
}


mux_session_confirm(int id, int success, void *arg)
{
	struct mux_session_confirm_ctx *cctx = arg;
	const char *display;
	Channel *c, *cc;
	int i;
	Buffer reply;

	if (cctx == NULL)
		fatal("%s: cctx == NULL", __func__);
	if ((c = channel_by_id(id)) == NULL)
		fatal("%s: no channel for id %d", __func__, id);
	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
		fatal("%s: channel %d lacks control channel %d", __func__,
		    id, c->ctl_chan);

	if (!success) {
		debug3("%s: sending failure reply", __func__);
		/* prepare reply */
		buffer_init(&reply);
		buffer_put_int(&reply, MUX_S_FAILURE);
		buffer_put_int(&reply, cctx->rid);
		buffer_put_cstring(&reply, "Session open refused by peer");
		goto done;
	}

	display = getenv("DISPLAY");
	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
 		char *proto, *data;

 		/* Get reasonable local authentication information. */
		if (client_x11_get_proto(display, options.xauth_location,
 		    options.forward_x11_trusted, options.forward_x11_timeout,
		    &proto, &data) == 0) {
			/* Request forwarding with authentication spoofing. */
			debug("Requesting X11 forwarding with authentication "
			    "spoofing.");
			x11_request_forwarding_with_spoofing(id, display, proto,
			    data, 1);
			/* XXX exit_on_forward_failure */
			client_expect_confirm(id, "X11 forwarding",
			    CONFIRM_WARN);
		}
 	}

 	if (cctx->want_agent_fwd && options.forward_agent) {
		packet_send();
	}

	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);

	debug3("%s: sending success reply", __func__);
	/* prepare reply */
	buffer_init(&reply);
	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
	buffer_put_int(&reply, cctx->rid);
	buffer_put_int(&reply, c->self);

 done:
	/* Send reply */
	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
	buffer_free(&reply);

	if (cc->mux_pause <= 0)
		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
	cc->mux_pause = 0; /* start processing messages again */
	c->open_confirm_ctx = NULL;
	buffer_free(&cctx->cmd);
	free(cctx->term);
	if (cctx->env != NULL) {
		for (i = 0; cctx->env[i] != NULL; i++)
			free(cctx->env[i]);
		free(cctx->env);
	}
	free(cctx);
}


void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)

{

    PerThreadContext *p = avctx->internal->thread_ctx;

    FrameThreadContext *fctx;

    AVFrame *dst, *tmp;

FF_DISABLE_DEPRECATION_WARNINGS

    int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||

                          avctx->thread_safe_callbacks                   ||

                          (

#if FF_API_GET_BUFFER

                           !avctx->get_buffer &&

#endif

                           avctx->get_buffer2 == avcodec_default_get_buffer2);

FF_ENABLE_DEPRECATION_WARNINGS

    if (!f->f->buf[0])

        return;

    if (avctx->debug & FF_DEBUG_BUFFERS)

        av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);

    av_buffer_unref(&f->progress);

    f->owner    = NULL;

    if (can_direct_free) {

        av_frame_unref(f->f);

        return;

    }

    fctx = p->parent;

    pthread_mutex_lock(&fctx->buffer_mutex);

    if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))

        goto fail;

    tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,

                          (p->num_released_buffers + 1) *

                          sizeof(*p->released_buffers));

    if (!tmp)

        goto fail;

    p->released_buffers = tmp;

    dst = &p->released_buffers[p->num_released_buffers];

    av_frame_move_ref(dst, f->f);

    p->num_released_buffers++;

fail:

    pthread_mutex_unlock(&fctx->buffer_mutex);

}


RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
  return frame_tree_.root()->render_manager();
}


static void perWorldBindingsReadonlyTestInterfaceEmptyAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
    TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
    RefPtr<TestInterfaceEmpty> result(imp->perWorldBindingsReadonlyTestInterfaceEmptyAttribute());
    if (result && DOMDataStore::setReturnValueFromWrapper<V8TestInterfaceEmpty>(info.GetReturnValue(), result.get()))
        return;
    v8::Handle<v8::Value> wrapper = toV8(result.get(), info.Holder(), info.GetIsolate());
    if (!wrapper.IsEmpty()) {
        V8HiddenValue::setHiddenValue(info.GetIsolate(), info.Holder(), v8AtomicString(info.GetIsolate(), "perWorldBindingsReadonlyTestInterfaceEmptyAttribute"), wrapper);
        v8SetReturnValue(info, wrapper);
    }
}


static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser)
{
	if (ser->irq >= NR_IRQS || ser->irq < 0 ||
			ser->baud_base < 9600 || ser->type < PORT_UNKNOWN ||
			ser->type == PORT_STARTECH)
		return -EINVAL;
	return 0;
}