void Magick::Image::thumbnail(const Geometry &geometry_)
{
  MagickCore::Image
    *newImage;

  size_t
    height=rows(),
    width=columns();

  ssize_t
    x=0,
    y=0;

  ParseMetaGeometry(static_cast<std::string>(geometry_).c_str(),&x,&y,&width,
    &height);

  GetPPException;
  newImage=ThumbnailImage(constImage(),width,height,exceptionInfo);
  replaceImage(newImage);
  ThrowImageException;
}


void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen)
{
    if (bind(sockfd, my_addr, addrlen))
        perror_msg_and_die("bind");
}


static int __init alsa_seq_device_init(void)
{
	int err;

	err = bus_register(&snd_seq_bus_type);
	if (err < 0)
		return err;
	err = seq_dev_proc_init();
	if (err < 0)
		bus_unregister(&snd_seq_bus_type);
	return err;
}


static void rtsp_close_streams(RTSPState *rt)

{

    int i;

    RTSPStream *rtsp_st;

    for(i=0;i<rt->nb_rtsp_streams;i++) {

        rtsp_st = rt->rtsp_streams[i];

        if (rtsp_st) {

            if (rtsp_st->transport_priv) {

                if (rt->transport == RTSP_TRANSPORT_RDT)

                    ff_rdt_parse_close(rtsp_st->transport_priv);

                else

                    rtp_parse_close(rtsp_st->transport_priv);

            }

            if (rtsp_st->rtp_handle)

                url_close(rtsp_st->rtp_handle);

            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)

                rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);

        }

    }

    av_free(rt->rtsp_streams);

    if (rt->asf_ctx) {

        av_close_input_stream (rt->asf_ctx);

        rt->asf_ctx = NULL;

    }

    av_freep(&rt->auth_b64);

}


void EC_GROUP_clear_free(EC_GROUP *group)
	{
	if (!group) return;

	if (group->meth->group_clear_finish != 0)
		group->meth->group_clear_finish(group);
	else if (group->meth->group_finish != 0)
		group->meth->group_finish(group);

	EC_EX_DATA_clear_free_all_data(&group->extra_data);

	if (group->generator != NULL)

        EC_EX_DATA_clear_free_all_data(&group->extra_data);

       if (group->mont_data)
               BN_MONT_CTX_free(group->mont_data);

        if (group->generator != NULL)
                EC_POINT_clear_free(group->generator);
        BN_clear_free(&group->order);

	OPENSSL_cleanse(group, sizeof *group);
	OPENSSL_free(group);
	}


static void iucv_callback_txdone(struct iucv_path *path,
				 struct iucv_message *msg)
{
	struct sock *sk = path->private;
	struct sk_buff *this = NULL;
	struct sk_buff_head *list = &iucv_sk(sk)->send_skb_q;
	struct sk_buff *list_skb = list->next;
	unsigned long flags;

	bh_lock_sock(sk);
	if (!skb_queue_empty(list)) {
		spin_lock_irqsave(&list->lock, flags);

		while (list_skb != (struct sk_buff *)list) {
			if (!memcmp(&msg->tag, CB_TAG(list_skb), CB_TAG_LEN)) {
				this = list_skb;
				break;
			}
			list_skb = list_skb->next;
		}
		if (this)
			__skb_unlink(this, list);

		spin_unlock_irqrestore(&list->lock, flags);

		if (this) {
			kfree_skb(this);
			/* wake up any process waiting for sending */
			iucv_sock_wake_msglim(sk);
		}
	}

	if (sk->sk_state == IUCV_CLOSING) {
		if (skb_queue_empty(&iucv_sk(sk)->send_skb_q)) {
			sk->sk_state = IUCV_CLOSED;
			sk->sk_state_change(sk);
		}
	}
	bh_unlock_sock(sk);

}


RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) {
	int res, rel, rela, i, j;
	size_t reloc_num = 0;
	RBinElfReloc *ret = NULL;

	if (!bin || !bin->g_sections) {
		return NULL;
	}
	reloc_num = get_relocs_num (bin);
	if (!reloc_num)	{
		return NULL;
	}
	bin->reloc_num = reloc_num;
	ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc));
	if (!ret) {
		return NULL;
	}
#if DEAD_CODE
	ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text");
	if (section_text_offset == -1) {
		section_text_offset = 0;
	}
#endif
	for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) {
		bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."));
		bool is_rel  = 0 == strncmp (bin->g_sections[i].name, ".rel.",  strlen (".rel."));
		if (!is_rela && !is_rel) {
			continue;
		}
		for (j = 0; j < bin->g_sections[i].size; j += res) {
			if (bin->g_sections[i].size > bin->size) {
				break;
			}
			if (bin->g_sections[i].offset > bin->size) {
				break;
			}
			if (rel >= reloc_num) {
				bprintf ("Internal error: ELF relocation buffer too small,"
				         "please file a bug report.");
				break;
			}
			if (!bin->is_rela) {
				rela = is_rela? DT_RELA : DT_REL;
			} else {
				rela = bin->is_rela;
			}
			res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j);
			if (j + res > bin->g_sections[i].size) {
				bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i);
			}
			if (bin->ehdr.e_type == ET_REL) {
				if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) {
					ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset;
					ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva);
				} else {
					ret[rel].rva = ret[rel].offset;
				}
			} else {
				ret[rel].rva = ret[rel].offset;
				ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset);
			}
			ret[rel].last = 0;
			if (res < 0) {
				break;
			}
			rel++;
		}
	}
	ret[reloc_num].last = 1;
	return ret;
}


static int parse_label(char **c, struct pxe_menu *cfg)
{
	struct token t;
	int len;
	char *s = *c;
	struct pxe_label *label;
	int err;

	label = label_create();
	if (!label)
		return -ENOMEM;

	err = parse_sliteral(c, &label->name);
	if (err < 0) {
		printf("Expected label name: %.*s\n", (int)(*c - s), s);
		label_destroy(label);
		return -EINVAL;
	}

	list_add_tail(&label->list, &cfg->labels);

	while (1) {
		s = *c;
		get_token(c, &t, L_KEYWORD);

		err = 0;
		switch (t.type) {
		case T_MENU:
			err = parse_label_menu(c, cfg, label);
			break;

		case T_KERNEL:
		case T_LINUX:
			err = parse_label_kernel(c, label);
			break;

		case T_APPEND:
			err = parse_sliteral(c, &label->append);
			if (label->initrd)
				break;
			s = strstr(label->append, "initrd=");
			if (!s)
				break;
			s += 7;
			len = (int)(strchr(s, ' ') - s);
			label->initrd = malloc(len + 1);
			strncpy(label->initrd, s, len);
			label->initrd[len] = '\0';

			break;

		case T_INITRD:
			if (!label->initrd)
				err = parse_sliteral(c, &label->initrd);
			break;

		case T_FDT:
			if (!label->fdt)
				err = parse_sliteral(c, &label->fdt);
			break;

		case T_FDTDIR:
			if (!label->fdtdir)
				err = parse_sliteral(c, &label->fdtdir);
			break;

		case T_LOCALBOOT:
			label->localboot = 1;
			err = parse_integer(c, &label->localboot_val);
			break;

		case T_IPAPPEND:
			err = parse_integer(c, &label->ipappend);
			break;

		case T_EOL:
			break;

		default:
			/*
			 * put the token back! we don't want it - it's the end
			 * of a label and whatever token this is, it's
			 * something for the menu level context to handle.
			 */
			*c = s;
			return 1;
		}

		if (err < 0)
			return err;
	}
}


  virtual string16 Execute(
      const std::string& component_text,
      std::vector<size_t>* offsets_into_component) const {
    return IDNToUnicodeWithOffsets(component_text, languages_,
                                   offsets_into_component);
  }


static void ehci_opreg_write(void *ptr, hwaddr addr,

                             uint64_t val, unsigned size)

{

    EHCIState *s = ptr;

    uint32_t *mmio = s->opreg + (addr >> 2);

    uint32_t old = *mmio;

    int i;

    trace_usb_ehci_opreg_write(addr + s->opregbase, addr2str(addr), val);

    switch (addr) {

    case USBCMD:

        if (val & USBCMD_HCRESET) {

            ehci_reset(s);

            val = s->usbcmd;

            break;

        }

        /* not supporting dynamic frame list size at the moment */

        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {

            fprintf(stderr, "attempt to set frame list size -- value %d\n",

                    (int)val & USBCMD_FLS);

            val &= ~USBCMD_FLS;

        }

        if (val & USBCMD_IAAD) {

            /*

             * Process IAAD immediately, otherwise the Linux IAAD watchdog may

             * trigger and re-use a qh without us seeing the unlink.

             */

            s->async_stepdown = 0;

            qemu_bh_schedule(s->async_bh);

            trace_usb_ehci_doorbell_ring();

        }

        if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=

            ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {

            if (s->pstate == EST_INACTIVE) {

                SET_LAST_RUN_CLOCK(s);

            }

            s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */

            ehci_update_halt(s);

            s->async_stepdown = 0;

            qemu_bh_schedule(s->async_bh);

        }

        break;

    case USBSTS:

        val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO

        ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC

        val = s->usbsts;

        ehci_update_irq(s);

        break;

    case USBINTR:

        val &= USBINTR_MASK;

        if (ehci_enabled(s) && (USBSTS_FLR & val)) {

            qemu_bh_schedule(s->async_bh);

        }

        break;

    case FRINDEX:

        val &= 0x00003ff8; /* frindex is 14bits and always a multiple of 8 */

        break;

    case CONFIGFLAG:

        val &= 0x1;

        if (val) {

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

                handle_port_owner_write(s, i, 0);

        }

        break;

    case PERIODICLISTBASE:

        if (ehci_periodic_enabled(s)) {

            fprintf(stderr,

              "ehci: PERIODIC list base register set while periodic schedule\n"

              "      is enabled and HC is enabled\n");

        }

        break;

    case ASYNCLISTADDR:

        if (ehci_async_enabled(s)) {

            fprintf(stderr,

              "ehci: ASYNC list address register set while async schedule\n"

              "      is enabled and HC is enabled\n");

        }

        break;

    }

    *mmio = val;

    trace_usb_ehci_opreg_change(addr + s->opregbase, addr2str(addr),

                                *mmio, old);

}


GF_EXPORT
GF_Err gf_isom_get_jp2_config(GF_ISOFile *movie, u32 trackNumber, u32 sampleDesc, u8 **out_dsi, u32 *out_size)
{
	GF_TrackBox *trak;
	GF_MPEGVisualSampleEntryBox *entry;
	GF_BitStream *bs;

	trak = gf_isom_get_track_from_file(movie, trackNumber);
	if (!trak || !trak->Media || !trak->Media->information || !trak->Media->information->sampleTable || !trak->Media->information->sampleTable->SampleDescription) return GF_ISOM_INVALID_FILE;
	entry = (GF_MPEGVisualSampleEntryBox *) gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, sampleDesc-1);
	if (!entry || !entry->jp2h) return GF_BAD_PARAM;
	if (!entry->jp2h->ihdr) return GF_ISOM_INVALID_FILE;

	bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
	gf_isom_box_array_write((GF_Box*)entry->jp2h, entry->jp2h->child_boxes, bs);
	gf_bs_get_content(bs, out_dsi, out_size);
	gf_bs_del(bs);
	return GF_OK;


MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size)
{
	MonoThread *thread;
	MonoInternalThread *internal;
	HANDLE thread_handle;
	struct StartInfo *start_info;
	gsize tid;

	thread = create_thread_object (domain);
	internal = create_internal_thread_object ();
	MONO_OBJECT_SETREF (thread, internal_thread, internal);

	start_info=g_new0 (struct StartInfo, 1);
	start_info->func = func;
	start_info->obj = thread;
	start_info->start_arg = arg;

	mono_threads_lock ();
	if (shutting_down) {
		mono_threads_unlock ();
		g_free (start_info);
		return NULL;
	}
	if (threads_starting_up == NULL) {
		MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
		threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
	}

	register_thread_start_argument (thread, start_info);
 	mono_g_hash_table_insert (threads_starting_up, thread, thread);
	mono_threads_unlock ();

	if (stack_size == 0)
		stack_size = default_stacksize_for_thread (internal);

	/* Create suspended, so we can do some housekeeping before the thread
	 * starts
	 */
	thread_handle = mono_create_thread (NULL, stack_size, (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
				     CREATE_SUSPENDED, &tid);
	THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
	if (thread_handle == NULL) {
		/* The thread couldn't be created, so throw an exception */
		mono_threads_lock ();
		mono_g_hash_table_remove (threads_starting_up, thread);
		mono_threads_unlock ();
		g_free (start_info);
		mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
		return NULL;
	}

	internal->handle=thread_handle;
	internal->tid=tid;
	internal->apartment_state=ThreadApartmentState_Unknown;
	internal->small_id = mono_thread_small_id_alloc ();
	internal->thread_pinning_ref = internal;
	MONO_GC_REGISTER_ROOT (internal->thread_pinning_ref);

	internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
	InitializeCriticalSection (internal->synch_cs);

	internal->threadpool_thread = threadpool_thread;
	if (threadpool_thread)
		mono_thread_set_state (internal, ThreadState_Background);

	if (handle_store (thread))
		ResumeThread (thread_handle);

	return internal;
}


void WebView::setParentWindow(HWND parentWindow)
{
    if (m_window) {
        if (::GetParent(m_window) == parentWindow)
            return;
        if (parentWindow)
            ::SetParent(m_window, parentWindow);
        else if (!m_isBeingDestroyed) {
            ::SetParent(m_window, HWND_MESSAGE);
        }
    }

    windowAncestryDidChange();
}


static void vga_draw_cursor_line(uint8_t *d1,
                                 const uint8_t *src1,
                                 int poffset, int w,
                                 unsigned int color0,
                                 unsigned int color1,
                                 unsigned int color_xor)
{
    const uint8_t *plane0, *plane1;
    int x, b0, b1;
    uint8_t *d;

    d = d1;
    plane0 = src1;
    plane1 = src1 + poffset;
    for (x = 0; x < w; x++) {
        b0 = (plane0[x >> 3] >> (7 - (x & 7))) & 1;
        b1 = (plane1[x >> 3] >> (7 - (x & 7))) & 1;
        switch (b0 | (b1 << 1)) {
        case 0:
            break;
        case 1:
            ((uint32_t *)d)[0] ^= color_xor;
            break;
        case 2:
            ((uint32_t *)d)[0] = color0;
            break;
        case 3:
            ((uint32_t *)d)[0] = color1;
            break;
        }
        d += 4;
    }
}


rrd_info_t *rrd_graph_v(
    int argc,
    char **argv)
{
    image_desc_t im;
    rrd_info_t *grinfo;
    rrd_graph_init(&im);
    /* a dummy surface so that we can measure text sizes for placements */
    rrd_graph_options(argc, argv, &im);
    if (rrd_test_error()) {
        rrd_info_free(im.grinfo);
        im_free(&im);
        return NULL;
    }

    if (optind >= argc) {
        rrd_info_free(im.grinfo);
        im_free(&im);
        rrd_set_error("missing filename");
        return NULL;
    }

    if (strlen(argv[optind]) >= MAXPATH) {
        rrd_set_error("filename (including path) too long");
        rrd_info_free(im.grinfo);
        im_free(&im);
        return NULL;
    }

    strncpy(im.graphfile, argv[optind], MAXPATH - 1);
    im.graphfile[MAXPATH - 1] = '\0';

    if (strcmp(im.graphfile, "-") == 0) {
        im.graphfile[0] = '\0';
    }

    rrd_graph_script(argc, argv, &im, 1);

    if (rrd_test_error()) {
        rrd_info_free(im.grinfo);
        im_free(&im);
        return NULL;
    }

    /* Everything is now read and the actual work can start */
    if (graph_paint(&im) == -1) {
      rrd_info_free(im.grinfo);
      im_free(&im);
      return NULL;
    }

    /* The image is generated and needs to be output.
     ** Also, if needed, print a line with information about the image.
     */

    if (im.imginfo && *im.imginfo) {
        rrd_infoval_t info;
        char     *path;
        char     *filename;

        if (bad_format_imginfo(im.imginfo)) {
            rrd_info_free(im.grinfo);
            im_free(&im);
            return NULL;
        }
        path = strdup(im.graphfile);
        filename = basename(path);
        info.u_str =
            sprintf_alloc(im.imginfo,
                          filename,
                          (long) (im.zoom *
                                  im.ximg), (long) (im.zoom * im.yimg));
        grinfo_push(&im, sprintf_alloc("image_info"), RD_I_STR, info);
        free(info.u_str);
        free(path);
    }
    if (im.rendered_image) {
        rrd_infoval_t img;

        img.u_blo.size = im.rendered_image_size;
        img.u_blo.ptr = im.rendered_image;
        grinfo_push(&im, sprintf_alloc("image"), RD_I_BLO, img);
    }
    grinfo = im.grinfo;
    im_free(&im);
    return grinfo;
}


int BrowserRootView::OnDragUpdated(const ui::DropTargetEvent& event) {
  if (ShouldForwardToTabStrip(event)) {
    scoped_ptr<ui::DropTargetEvent> mapped_event(
        MapEventToTabStrip(event, event.data()));
    if (!forwarding_to_tab_strip_) {
      tabstrip()->OnDragEntered(*mapped_event.get());
      forwarding_to_tab_strip_ = true;
    }
    return tabstrip()->OnDragUpdated(*mapped_event.get());
  } else if (forwarding_to_tab_strip_) {
    forwarding_to_tab_strip_ = false;
    tabstrip()->OnDragExited();
  }
  return ui::DragDropTypes::DRAG_NONE;
}


int ufmt_digitvalue ( UChar c ) {
 if ( ( ( c >= DIGIT_0 ) && ( c <= DIGIT_9 ) ) || ( ( c >= LOWERCASE_A ) && ( c <= LOWERCASE_Z ) ) || ( ( c >= UPPERCASE_A ) && ( c <= UPPERCASE_Z ) ) ) {
 return c - DIGIT_0 - ( c >= 0x0041 ? ( c >= 0x0061 ? 39 : 7 ) : 0 ) ;
 }
 else {
 return - 1 ;
 }
 }


bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)
	{
	Endpoint* endp = orig ? &orig_state : &resp_state;

	while ( len )
		{
		if ( endp->in_hdr )
			{
			// We're parsing the DNP3 header and link layer, get that in full.
			if ( ! AddToBuffer(endp, PSEUDO_APP_LAYER_INDEX, &data, &len) )
				return true;

			// The first two bytes must always be 0x0564.
			if( endp->buffer[0] != 0x05 || endp->buffer[1] != 0x64 )
				{
				analyzer->Weird("dnp3_header_lacks_magic");
				return false;
				}

			// Make sure header checksum is correct.
			if ( ! CheckCRC(PSEUDO_LINK_LAYER_LEN, endp->buffer, endp->buffer + PSEUDO_LINK_LAYER_LEN, "header") )
				{
				analyzer->ProtocolViolation("broken_checksum");
				return false;
				}

			// If the checksum works out, we're pretty certainly DNP3.
			analyzer->ProtocolConfirmation();

			// DNP3 packets without transport and application
			// layers can happen, we ignore them.
			if ( (endp->buffer[PSEUDO_LENGTH_INDEX] + 3) == (char)PSEUDO_LINK_LAYER_LEN  )
				{
				ClearEndpointState(orig);
				return true;
				}

			// Double check the direction in case the first
			// received packet is a response.
			u_char ctrl = endp->buffer[PSEUDO_CONTROL_FIELD_INDEX];

			if ( orig != (bool)(ctrl & 0x80) )
				analyzer->Weird("dnp3_unexpected_flow_direction");

			// Update state.
			endp->pkt_length = endp->buffer[PSEUDO_LENGTH_INDEX];
			endp->tpflags = endp->buffer[PSEUDO_TRANSPORT_INDEX];
			endp->in_hdr = false; // Now parsing application layer.

			// For the first packet, we submit the header to
			// BinPAC.
			if ( ++endp->pkt_cnt == 1 )
				interp->NewData(orig, endp->buffer, endp->buffer + PSEUDO_LINK_LAYER_LEN);
			}

		if ( ! endp->in_hdr )
			{
			assert(endp->pkt_length);

			// We're parsing the DNP3 application layer, get that
			// in full now as well. We calculate the number of
			// raw bytes the application layer consists of from
			// the packet length by determining how much 16-byte
			// chunks fit in there, and then add 2 bytes CRC for
			// each.
			int n = PSEUDO_APP_LAYER_INDEX + (endp->pkt_length - 5) + ((endp->pkt_length - 5) / 16) * 2
					+ 2 * ( ((endp->pkt_length - 5) % 16 == 0) ? 0 : 1) - 1 ;

			if ( ! AddToBuffer(endp, n, &data, &len) )
				return true;

			// Parse the the application layer data.
			if ( ! ParseAppLayer(endp) )
				return false;

			// Done with this packet, prepare for next.
			endp->buffer_len = 0;
			endp->in_hdr = true;
			}
		}

	return true;
	}


handle_t *__ext4_journal_start_sb(struct super_block *sb, unsigned int line,
				  int type, int blocks, int rsv_blocks)
{
	journal_t *journal;
	int err;

	trace_ext4_journal_start(sb, blocks, rsv_blocks, _RET_IP_);
	err = ext4_journal_check_start(sb);
	if (err < 0)
		return ERR_PTR(err);

	journal = EXT4_SB(sb)->s_journal;
	if (!journal)
		return ext4_get_nojournal();
	return jbd2__journal_start(journal, blocks, rsv_blocks, GFP_NOFS,
				   type, line);
}


bool verify_reply(bufferlist::iterator& reply) override { return true; }


static inline struct f2fs_sm_info *SM_I(struct f2fs_sb_info *sbi)
{
	return (struct f2fs_sm_info *)(sbi->sm_info);
}


void flush_tlb_kernel_range(unsigned long start, unsigned long end)
{

	/* Balance as user space task's flush, a bit conservative */
	if (end == TLB_FLUSH_ALL ||
	    (end - start) > tlb_single_page_flush_ceiling * PAGE_SIZE) {
		on_each_cpu(do_flush_tlb_all, NULL, 1);
	} else {
		struct flush_tlb_info info;
		info.flush_start = start;
		info.flush_end = end;
		on_each_cpu(do_kernel_range_flush, &info, 1);
	}
}


void UsageTracker::DidGetClientGlobalUsage(StorageType type,
                                           int64 usage,
                                           int64 unlimited_usage) {
  DCHECK_EQ(type, type_);
  global_usage_.usage += usage;
  global_usage_.unlimited_usage += unlimited_usage;
  if (--global_usage_.pending_clients == 0) {
    if (global_usage_.usage < 0)
      global_usage_.usage = 0;
    if (global_usage_.unlimited_usage > global_usage_.usage)
      global_usage_.unlimited_usage = global_usage_.usage;
    else if (global_usage_.unlimited_usage < 0)
      global_usage_.unlimited_usage = 0;

    global_usage_callbacks_.Run(type, global_usage_.usage,
                                global_usage_.unlimited_usage);
  }
}


void RenderProcessHostImpl::ShutdownForBadMessage(
    CrashReportMode crash_report_mode) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
    return;

  if (run_renderer_in_process()) {
    CHECK(false);
  }

  Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);

  if (crash_report_mode == CrashReportMode::GENERATE_CRASH_DUMP) {
    base::debug::DumpWithoutCrashing();
  }

  BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
      PROCESS_TYPE_RENDERER);
}


bool AutofillPopupBaseView::OnMouseDragged(const ui::MouseEvent& event) {
  if (HitTestPoint(event.location())) {
    SetSelection(event.location());

    return true;
  }

  ClearSelection();
  return false;
}


CastSelectDefaultView::CastSelectDefaultView(
    SystemTrayItem* owner,
    CastConfigDelegate* cast_config_delegate,
    bool show_more)
    : TrayItemMore(owner, show_more),
      cast_config_delegate_(cast_config_delegate) {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  SetImage(rb.GetImageNamed(IDR_AURA_UBER_TRAY_CAST).ToImageSkia());

  SetLabel(rb.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_NO_DEVICE));
  UpdateLabel();
}


TIFFWriteDirectoryTagCheckedLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value)
{
	assert(count<0x20000000);
	assert(sizeof(uint64)==8);
	if( !(tif->tif_flags&TIFF_BIGTIFF) ) {
		TIFFErrorExt(tif->tif_clientdata,"TIFFWriteDirectoryTagCheckedLong8Array","LONG8 not allowed for ClassicTIFF");
		return(0);
	}
	if (tif->tif_flags&TIFF_SWAB)
		TIFFSwabArrayOfLong8(value,count);
	return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG8,count,count*8,value));
}


static enum nss_status internal_setent ( int stayopen ) {
 enum nss_status status = NSS_STATUS_SUCCESS ;
 if ( stream == NULL ) {
 stream = fopen ( DATAFILE , "rce" ) ;
 if ( stream == NULL ) status = errno == EAGAIN ? NSS_STATUS_TRYAGAIN : NSS_STATUS_UNAVAIL ;
 else {
 # if ! defined O_CLOEXEC || ! defined __ASSUME_O_CLOEXEC # ifdef O_CLOEXEC if ( __have_o_cloexec <= 0 ) # endif {
 int result ;
 int flags ;
 result = flags = fcntl ( fileno ( stream ) , F_GETFD , 0 ) ;
 if ( result >= 0 ) {
 # ifdef O_CLOEXEC if ( __have_o_cloexec == 0 ) __have_o_cloexec = ( flags & FD_CLOEXEC ) == 0 ? - 1 : 1 ;
 if ( __have_o_cloexec < 0 ) # endif {
 flags |= FD_CLOEXEC ;
 result = fcntl ( fileno ( stream ) , F_SETFD , flags ) ;
 }
 }
 if ( result < 0 ) {
 fclose ( stream ) ;
 stream = NULL ;
 status = NSS_STATUS_UNAVAIL ;
 }
 }
 # endif }
 }
 else rewind ( stream ) ;
 if ( stream != NULL ) keep_stream |= stayopen ;
 return status ;
 }


void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
{
    if (!parent())
        return;

    AllowRepaintScope scoper(frameView());

    if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
        (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
        repaint();
        return;
    }

    ShapeValue* shapeOutsideValue = style()->shapeOutside();
    if (!frameView()->isInPerformLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
        ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
        markShapeOutsideDependentsForLayout();
    }

    bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
    if (!didFullRepaint)
        repaintLayerRectsForImage(image, style()->maskLayers(), false);

    if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
        layer()->contentChanged(MaskImageChanged);
}


void bt_sock_reclassify_lock(struct sock *sk, int proto)
{
	BUG_ON(!sk);
	BUG_ON(sock_owned_by_user(sk));

	sock_lock_init_class_and_name(sk,
			bt_slock_key_strings[proto], &bt_slock_key[proto],
				bt_key_strings[proto], &bt_lock_key[proto]);
}


void pci_cmd646_ide_init(PCIBus *bus, DriveInfo **hd_table,

                         int secondary_ide_enabled)

{

    PCIDevice *dev;

    dev = pci_create(bus, -1, "CMD646 IDE");

    qdev_prop_set_uint32(&dev->qdev, "secondary", secondary_ide_enabled);

    qdev_init(&dev->qdev);

    pci_ide_create_devs(dev, hd_table);

}


void LayerTilerChromium::draw(const IntRect& contentRect)
{
    if (m_skipsDraw || !m_tiles.size())
        return;

    GraphicsContext3D* context = layerRendererContext();
    const ContentLayerChromium::SharedValues* contentLayerValues = layerRenderer()->contentLayerSharedValues();
    layerRenderer()->useShader(contentLayerValues->contentShaderProgram());
    GLC(context, context->uniform1i(contentLayerValues->shaderSamplerLocation(), 0));

    int left, top, right, bottom;
    contentRectToTileIndices(contentRect, left, top, right, bottom);
    for (int j = top; j <= bottom; ++j) {
        for (int i = left; i <= right; ++i) {
            Tile* tile = m_tiles[tileIndex(i, j)].get();
            ASSERT(tile);

            tile->texture()->bindTexture();

            TransformationMatrix tileMatrix;
            IntRect tileRect = tileContentRect(i, j);
            tileMatrix.translate3d(tileRect.x() - contentRect.x() + tileRect.width() / 2.0, tileRect.y() - contentRect.y() + tileRect.height() / 2.0, 0);

            LayerChromium::drawTexturedQuad(context, layerRenderer()->projectionMatrix(), tileMatrix, m_tileSize.width(), m_tileSize.height(), 1, contentLayerValues->shaderMatrixLocation(), contentLayerValues->shaderAlphaLocation());

            tile->texture()->unreserve();
        }
    }
}


static int _nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
		struct nfs_fsinfo *info)
{
	struct nfs4_lookup_root_arg args = {
		.bitmask = nfs4_fattr_bitmap,
	};
	struct nfs4_lookup_res res = {
		.server = server,
		.fattr = info->fattr,
		.fh = fhandle,
	};
	struct rpc_message msg = {
		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP_ROOT],
		.rpc_argp = &args,
		.rpc_resp = &res,
	};
	nfs_fattr_init(info->fattr);
	return rpc_call_sync(server->client, &msg, 0);
}


static int i40e_get_capabilities(struct i40e_pf *pf,
				 enum i40e_admin_queue_opc list_type)
{
	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
	u16 data_size;
	int buf_len;
	int err;

	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
	do {
		cap_buf = kzalloc(buf_len, GFP_KERNEL);
		if (!cap_buf)
			return -ENOMEM;

		/* this loads the data into the hw struct for us */
		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
						    &data_size, list_type,
						    NULL);
		/* data loaded, buffer no longer needed */
		kfree(cap_buf);

		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
			/* retry with a larger buffer */
			buf_len = data_size;
		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK) {
			dev_info(&pf->pdev->dev,
				 "capability discovery failed, err %s aq_err %s\n",
				 i40e_stat_str(&pf->hw, err),
				 i40e_aq_str(&pf->hw,
					     pf->hw.aq.asq_last_status));
			return -ENODEV;
		}
	} while (err);

	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
		if (list_type == i40e_aqc_opc_list_func_capabilities) {
			dev_info(&pf->pdev->dev,
				 "pf=%d, num_vfs=%d, msix_pf=%d, msix_vf=%d, fd_g=%d, fd_b=%d, pf_max_q=%d num_vsi=%d\n",
				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
				 pf->hw.func_caps.num_msix_vectors,
				 pf->hw.func_caps.num_msix_vectors_vf,
				 pf->hw.func_caps.fd_filters_guaranteed,
				 pf->hw.func_caps.fd_filters_best_effort,
				 pf->hw.func_caps.num_tx_qp,
				 pf->hw.func_caps.num_vsis);
		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
			dev_info(&pf->pdev->dev,
				 "switch_mode=0x%04x, function_valid=0x%08x\n",
				 pf->hw.dev_caps.switch_mode,
				 pf->hw.dev_caps.valid_functions);
			dev_info(&pf->pdev->dev,
				 "SR-IOV=%d, num_vfs for all function=%u\n",
				 pf->hw.dev_caps.sr_iov_1_1,
				 pf->hw.dev_caps.num_vfs);
			dev_info(&pf->pdev->dev,
				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
				 pf->hw.dev_caps.num_vsis,
				 pf->hw.dev_caps.num_rx_qp,
				 pf->hw.dev_caps.num_tx_qp);
		}
	}
	if (list_type == i40e_aqc_opc_list_func_capabilities) {
#define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
		       + pf->hw.func_caps.num_vfs)
		if (pf->hw.revision_id == 0 &&
		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
			dev_info(&pf->pdev->dev,
				 "got num_vsis %d, setting num_vsis to %d\n",
				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
		}
	}
	return 0;
}


get_h_kerning(hb_font_t *font, void *font_data, hb_codepoint_t first,
                 hb_codepoint_t second, void *user_data)
{
    FT_Face face = font_data;
    FT_Vector kern;

    if (FT_Get_Kerning(face, first, second, FT_KERNING_DEFAULT, &kern))
        return 0;

    return kern.x;
}


QPDF::allowExtractAll()
{
    int R = 0;
    int P = 0;
    bool status = true;
    if (isEncrypted(R, P))
    {
	status = is_bit_set(P, 5);
    }
    return status;
}


static int nf_tables_delsetelem(struct sock *nlsk, struct sk_buff *skb,
				const struct nlmsghdr *nlh,
				const struct nlattr * const nla[])
{
	const struct nlattr *attr;
	struct nft_set *set;
	struct nft_ctx ctx;
	int rem, err = 0;

	if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
		return -EINVAL;

	err = nft_ctx_init_from_elemattr(&ctx, skb, nlh, nla, false);
	if (err < 0)
		return err;

	set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]);
	if (IS_ERR(set))
		return PTR_ERR(set);
	if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
		return -EBUSY;

	nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
		err = nft_del_setelem(&ctx, set, attr);
		if (err < 0)
			break;

		set->nelems--;
	}
	return err;
}


void RenderWidgetHostImpl::ForwardInputEvent(const WebInputEvent& input_event,
                                             int event_size,
                                             bool is_keyboard_shortcut) {
  TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::ForwardInputEvent");

  if (!process_->HasConnection())
    return;

  DCHECK(!process_->IgnoreInputEvents());

  if (overscroll_controller_.get() &&
      !overscroll_controller_->WillDispatchEvent(input_event)) {
    if (input_event.type == WebKit::WebInputEvent::MouseWheel) {
      mouse_wheel_pending_ = false;
    } else if (WebInputEvent::isGestureEventType(input_event.type) &&
               gesture_event_filter_->HasQueuedGestureEvents()) {
      gesture_event_filter_->ProcessGestureAck(true, input_event.type);
    } else if (WebInputEvent::isTouchEventType(input_event.type)) {
      touch_event_queue_->ProcessTouchAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
    }
    return;
  }

  in_process_event_types_.push(input_event.type);

  if (input_event.type != WebInputEvent::MouseWheel) {
    for (size_t i = 0; i < coalesced_mouse_wheel_events_.size(); ++i) {
      SendInputEvent(coalesced_mouse_wheel_events_[i],
                     sizeof(WebMouseWheelEvent), false);
    }
    coalesced_mouse_wheel_events_.clear();
  }

  SendInputEvent(input_event, event_size, is_keyboard_shortcut);

  next_mouse_move_.reset();

  StartHangMonitorTimeout(
      TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
}


mrb_closure_new_cfunc(mrb_state *mrb, mrb_func_t func, int nlocals)
{
  return mrb_proc_new_cfunc_with_env(mrb, func, nlocals, NULL);
}


bool AXObject::hasAttribute(const QualifiedName& attribute) const {
  Node* elementNode = getNode();
  if (!elementNode)
    return false;

  if (!elementNode->isElementNode())
    return false;

  Element* element = toElement(elementNode);
  return element->fastHasAttribute(attribute);
}


static void lsi_execute_script(LSIState *s)
{
    PCIDevice *pci_dev = PCI_DEVICE(s);
    uint32_t insn;
    uint32_t addr, addr_high;
    int opcode;
    int insn_processed = 0;

    s->istat1 |= LSI_ISTAT1_SRUN;
again:

     s->istat1 |= LSI_ISTAT1_SRUN;
 again:
    if (++insn_processed > LSI_MAX_INSN) {
        /* Some windows drivers make the device spin waiting for a memory
           location to change.  If we have been executed a lot of code then
           assume this is the case and force an unexpected device disconnect.
           This is apparently sufficient to beat the drivers into submission.
         */
        if (!(s->sien0 & LSI_SIST0_UDC)) {
            qemu_log_mask(LOG_GUEST_ERROR,
                          "lsi_scsi: inf. loop with UDC masked");
        }
        lsi_script_scsi_interrupt(s, LSI_SIST0_UDC, 0);
        lsi_disconnect(s);
        trace_lsi_execute_script_stop();
        return;
    }
     insn = read_dword(s, s->dsp);
     if (!insn) {
         /* If we receive an empty opcode increment the DSP by 4 bytes
        s->dbc = insn & 0xffffff;
        s->rbc = s->dbc;
        /* ??? Set ESA.  */
        s->ia = s->dsp - 8;
        if (insn & (1 << 29)) {
            /* Indirect addressing.  */
            addr = read_dword(s, addr);
        } else if (insn & (1 << 28)) {
            uint32_t buf[2];
            int32_t offset;
            /* Table indirect addressing.  */

            /* 32-bit Table indirect */
            offset = sextract32(addr, 0, 24);
            pci_dma_read(pci_dev, s->dsa + offset, buf, 8);
            /* byte count is stored in bits 0:23 only */
            s->dbc = cpu_to_le32(buf[0]) & 0xffffff;
            s->rbc = s->dbc;
            addr = cpu_to_le32(buf[1]);

            /* 40-bit DMA, upper addr bits [39:32] stored in first DWORD of
             * table, bits [31:24] */
            if (lsi_dma_40bit(s))
                addr_high = cpu_to_le32(buf[0]) >> 24;
            else if (lsi_dma_ti64bit(s)) {
                int selector = (cpu_to_le32(buf[0]) >> 24) & 0x1f;
                switch (selector) {
                case 0 ... 0x0f:
                    /* offset index into scratch registers since
                     * TI64 mode can use registers C to R */
                    addr_high = s->scratch[2 + selector];
                    break;
                case 0x10:
                    addr_high = s->mmrs;
                    break;
                case 0x11:
                    addr_high = s->mmws;
                    break;
                case 0x12:
                    addr_high = s->sfs;
                    break;
                case 0x13:
                    addr_high = s->drs;
                    break;
                case 0x14:
                    addr_high = s->sbms;
                    break;
                case 0x15:
                    addr_high = s->dbms;
                    break;
                default:
                    qemu_log_mask(LOG_GUEST_ERROR,
                          "lsi_scsi: Illegal selector specified (0x%x > 0x15) "
                          "for 64-bit DMA block move", selector);
                    break;
                }
            }
        } else if (lsi_dma_64bit(s)) {
            /* fetch a 3rd dword if 64-bit direct move is enabled and
               only if we're not doing table indirect or indirect addressing */
            s->dbms = read_dword(s, s->dsp);
            s->dsp += 4;
            s->ia = s->dsp - 12;
        }
        if ((s->sstat1 & PHASE_MASK) != ((insn >> 24) & 7)) {
            trace_lsi_execute_script_blockmove_badphase(
                    scsi_phase_name(s->sstat1),
                    scsi_phase_name(insn >> 24));
            lsi_script_scsi_interrupt(s, LSI_SIST0_MA, 0);
            break;
        }
        s->dnad = addr;
        s->dnad64 = addr_high;
        switch (s->sstat1 & 0x7) {
        case PHASE_DO:
            s->waiting = LSI_DMA_SCRIPTS;
            lsi_do_dma(s, 1);
            if (s->waiting)
                s->waiting = LSI_DMA_IN_PROGRESS;
            break;
        case PHASE_DI:
            s->waiting = LSI_DMA_SCRIPTS;
            lsi_do_dma(s, 0);
            if (s->waiting)
                s->waiting = LSI_DMA_IN_PROGRESS;
            break;
        case PHASE_CMD:
            lsi_do_command(s);
            break;
        case PHASE_ST:
            lsi_do_status(s);
            break;
        case PHASE_MO:
            lsi_do_msgout(s);
            break;
        case PHASE_MI:
            lsi_do_msgin(s);
            break;
        default:
            qemu_log_mask(LOG_UNIMP, "lsi_scsi: Unimplemented phase %s\n",
                          scsi_phase_name(s->sstat1));
        }
        s->dfifo = s->dbc & 0xff;
        s->ctest5 = (s->ctest5 & 0xfc) | ((s->dbc >> 8) & 3);
        s->sbc = s->dbc;
        s->rbc -= s->dbc;
        s->ua = addr + s->dbc;
        break;

    case 1: /* IO or Read/Write instruction.  */
        opcode = (insn >> 27) & 7;
        if (opcode < 5) {
            uint32_t id;

            if (insn & (1 << 25)) {
                id = read_dword(s, s->dsa + sextract32(insn, 0, 24));
            } else {
                id = insn;
            }
            id = (id >> 16) & 0xf;
            if (insn & (1 << 26)) {
                addr = s->dsp + sextract32(addr, 0, 24);
            }
            s->dnad = addr;
            switch (opcode) {
            case 0: /* Select */
                s->sdid = id;
                if (s->scntl1 & LSI_SCNTL1_CON) {
                    trace_lsi_execute_script_io_alreadyreselected();
                    s->dsp = s->dnad;
                    break;
                }
                s->sstat0 |= LSI_SSTAT0_WOA;
                s->scntl1 &= ~LSI_SCNTL1_IARB;
                if (!scsi_device_find(&s->bus, 0, id, 0)) {
                    lsi_bad_selection(s, id);
                    break;
                }
                trace_lsi_execute_script_io_selected(id,
                                             insn & (1 << 3) ? " ATN" : "");
                /* ??? Linux drivers compain when this is set.  Maybe
                   it only applies in low-level mode (unimplemented).
                lsi_script_scsi_interrupt(s, LSI_SIST0_CMP, 0); */
                s->select_tag = id << 8;
                s->scntl1 |= LSI_SCNTL1_CON;
                if (insn & (1 << 3)) {
                    s->socl |= LSI_SOCL_ATN;
                    s->sbcl |= LSI_SBCL_ATN;
                }
                s->sbcl |= LSI_SBCL_BSY;
                lsi_set_phase(s, PHASE_MO);
                s->waiting = LSI_NOWAIT;
                break;
            case 1: /* Disconnect */
                trace_lsi_execute_script_io_disconnect();
                s->scntl1 &= ~LSI_SCNTL1_CON;
                /* FIXME: this is not entirely correct; the target need not ask
                 * for reselection until it has to send data, while here we force a
                 * reselection as soon as the bus is free.  The correct flow would
                 * reselect before lsi_transfer_data and disconnect as soon as
                 * DMA ends.
                 */
                if (!s->current) {
                    lsi_request *p = get_pending_req(s);
                    if (p) {
                        lsi_reselect(s, p);
                    }
                }
                break;
            case 2: /* Wait Reselect */
                if (s->istat0 & LSI_ISTAT0_SIGP) {
                    s->dsp = s->dnad;
                } else if (!lsi_irq_on_rsl(s)) {
                        lsi_wait_reselect(s);
                }
                break;
            case 3: /* Set */
                trace_lsi_execute_script_io_set(
                        insn & (1 << 3) ? " ATN" : "",
                        insn & (1 << 6) ? " ACK" : "",
                        insn & (1 << 9) ? " TM" : "",
                        insn & (1 << 10) ? " CC" : "");
                if (insn & (1 << 3)) {
                    s->socl |= LSI_SOCL_ATN;
                    s->sbcl |= LSI_SBCL_ATN;
                    lsi_set_phase(s, PHASE_MO);
                }

                if (insn & (1 << 6)) {
                    s->sbcl |= LSI_SBCL_ACK;
                }

                if (insn & (1 << 9)) {
                    qemu_log_mask(LOG_UNIMP,
                        "lsi_scsi: Target mode not implemented\n");
                }
                if (insn & (1 << 10))
                    s->carry = 1;
                break;
            case 4: /* Clear */
                trace_lsi_execute_script_io_clear(
                        insn & (1 << 3) ? " ATN" : "",
                        insn & (1 << 6) ? " ACK" : "",
                        insn & (1 << 9) ? " TM" : "",
                        insn & (1 << 10) ? " CC" : "");
                if (insn & (1 << 3)) {
                    s->socl &= ~LSI_SOCL_ATN;
                    s->sbcl &= ~LSI_SBCL_ATN;
                }

                if (insn & (1 << 6)) {
                    s->sbcl &= ~LSI_SBCL_ACK;
                }

                if (insn & (1 << 10))
                    s->carry = 0;
                break;
            }
        } else {
            uint8_t op0;
            uint8_t op1;
            uint8_t data8;
            int reg;
            int operator;

            static const char *opcode_names[3] =
                {"Write", "Read", "Read-Modify-Write"};
            static const char *operator_names[8] =
                {"MOV", "SHL", "OR", "XOR", "AND", "SHR", "ADD", "ADC"};

            reg = ((insn >> 16) & 0x7f) | (insn & 0x80);
            data8 = (insn >> 8) & 0xff;
            opcode = (insn >> 27) & 7;
            operator = (insn >> 24) & 7;
            trace_lsi_execute_script_io_opcode(
                    opcode_names[opcode - 5], reg,
                    operator_names[operator], data8, s->sfbr,
                    (insn & (1 << 23)) ? " SFBR" : "");
            op0 = op1 = 0;
            switch (opcode) {
            case 5: /* From SFBR */
                op0 = s->sfbr;
                op1 = data8;
                break;
            case 6: /* To SFBR */
                if (operator)
                    op0 = lsi_reg_readb(s, reg);
                op1 = data8;
                break;
            case 7: /* Read-modify-write */
                if (operator)
                    op0 = lsi_reg_readb(s, reg);
                if (insn & (1 << 23)) {
                    op1 = s->sfbr;
                } else {
                    op1 = data8;
                }
                break;
            }

            switch (operator) {
            case 0: /* move */
                op0 = op1;
                break;
            case 1: /* Shift left */
                op1 = op0 >> 7;
                op0 = (op0 << 1) | s->carry;
                s->carry = op1;
                break;
            case 2: /* OR */
                op0 |= op1;
                break;
            case 3: /* XOR */
                op0 ^= op1;
                break;
            case 4: /* AND */
                op0 &= op1;
                break;
            case 5: /* SHR */
                op1 = op0 & 1;
                op0 = (op0 >> 1) | (s->carry << 7);
                s->carry = op1;
                break;
            case 6: /* ADD */
                op0 += op1;
                s->carry = op0 < op1;
                break;
            case 7: /* ADC */
                op0 += op1 + s->carry;
                if (s->carry)
                    s->carry = op0 <= op1;
                else
                    s->carry = op0 < op1;
                break;
            }

            switch (opcode) {
            case 5: /* From SFBR */
            case 7: /* Read-modify-write */
                lsi_reg_writeb(s, reg, op0);
                break;
            case 6: /* To SFBR */
                s->sfbr = op0;
                break;
            }
        }
        break;

    case 2: /* Transfer Control.  */
        {
            int cond;
            int jmp;

            if ((insn & 0x002e0000) == 0) {
                trace_lsi_execute_script_tc_nop();
                break;
            }
            if (s->sist1 & LSI_SIST1_STO) {
                trace_lsi_execute_script_tc_delayedselect_timeout();
                lsi_stop_script(s);
                break;
            }
            cond = jmp = (insn & (1 << 19)) != 0;
            if (cond == jmp && (insn & (1 << 21))) {
                trace_lsi_execute_script_tc_compc(s->carry == jmp);
                cond = s->carry != 0;
            }
            if (cond == jmp && (insn & (1 << 17))) {
                trace_lsi_execute_script_tc_compp(scsi_phase_name(s->sstat1),
                        jmp ? '=' : '!', scsi_phase_name(insn >> 24));
                cond = (s->sstat1 & PHASE_MASK) == ((insn >> 24) & 7);
            }
            if (cond == jmp && (insn & (1 << 18))) {
                uint8_t mask;

                mask = (~insn >> 8) & 0xff;
                trace_lsi_execute_script_tc_compd(
                        s->sfbr, mask, jmp ? '=' : '!', insn & mask);
                cond = (s->sfbr & mask) == (insn & mask);
            }
            if (cond == jmp) {
                if (insn & (1 << 23)) {
                    /* Relative address.  */
                    addr = s->dsp + sextract32(addr, 0, 24);
                }
                switch ((insn >> 27) & 7) {
                case 0: /* Jump */
                    trace_lsi_execute_script_tc_jump(addr);
                    s->adder = addr;
                    s->dsp = addr;
                    break;
                case 1: /* Call */
                    trace_lsi_execute_script_tc_call(addr);
                    s->temp = s->dsp;
                    s->dsp = addr;
                    break;
                case 2: /* Return */
                    trace_lsi_execute_script_tc_return(s->temp);
                    s->dsp = s->temp;
                    break;
                case 3: /* Interrupt */
                    trace_lsi_execute_script_tc_interrupt(s->dsps);
                    if ((insn & (1 << 20)) != 0) {
                        s->istat0 |= LSI_ISTAT0_INTF;
                        lsi_update_irq(s);
                    } else {
                        lsi_script_dma_interrupt(s, LSI_DSTAT_SIR);
                    }
                    break;
                default:
                    trace_lsi_execute_script_tc_illegal();
                    lsi_script_dma_interrupt(s, LSI_DSTAT_IID);
                    break;
                }
            } else {
                trace_lsi_execute_script_tc_cc_failed();
            }
        }
        break;

    case 3:
        if ((insn & (1 << 29)) == 0) {
            /* Memory move.  */
            uint32_t dest;
            /* ??? The docs imply the destination address is loaded into
               the TEMP register.  However the Linux drivers rely on
               the value being presrved.  */
            dest = read_dword(s, s->dsp);
            s->dsp += 4;
            lsi_memcpy(s, dest, addr, insn & 0xffffff);
        } else {
            uint8_t data[7];
            int reg;
            int n;
            int i;

            if (insn & (1 << 28)) {
                addr = s->dsa + sextract32(addr, 0, 24);
            }
            n = (insn & 7);
            reg = (insn >> 16) & 0xff;
            if (insn & (1 << 24)) {
                pci_dma_read(pci_dev, addr, data, n);
                trace_lsi_execute_script_mm_load(reg, n, addr, *(int *)data);
                for (i = 0; i < n; i++) {
                    lsi_reg_writeb(s, reg + i, data[i]);
                }
            } else {
                trace_lsi_execute_script_mm_store(reg, n, addr);
                for (i = 0; i < n; i++) {
                    data[i] = lsi_reg_readb(s, reg + i);
                }
                pci_dma_write(pci_dev, addr, data, n);
            }
        }
    }
    if (insn_processed > 10000 && s->waiting == LSI_NOWAIT) {
        /* Some windows drivers make the device spin waiting for a memory
           location to change.  If we have been executed a lot of code then
           assume this is the case and force an unexpected device disconnect.
           This is apparently sufficient to beat the drivers into submission.
         */
        if (!(s->sien0 & LSI_SIST0_UDC)) {
            qemu_log_mask(LOG_GUEST_ERROR,
                          "lsi_scsi: inf. loop with UDC masked");
        }
        lsi_script_scsi_interrupt(s, LSI_SIST0_UDC, 0);
        lsi_disconnect(s);
    } else if (s->istat1 & LSI_ISTAT1_SRUN && s->waiting == LSI_NOWAIT) {
        if (s->dcntl & LSI_DCNTL_SSM) {
             }
         }
     }


DEFINE_TRACE(WebGL2RenderingContextBase) {
  visitor->Trace(read_framebuffer_binding_);
  visitor->Trace(transform_feedback_binding_);
  visitor->Trace(default_transform_feedback_);
  visitor->Trace(bound_copy_read_buffer_);
  visitor->Trace(bound_copy_write_buffer_);
  visitor->Trace(bound_pixel_pack_buffer_);
  visitor->Trace(bound_pixel_unpack_buffer_);
  visitor->Trace(bound_uniform_buffer_);
  visitor->Trace(bound_indexed_uniform_buffers_);
  visitor->Trace(current_boolean_occlusion_query_);
  visitor->Trace(current_transform_feedback_primitives_written_query_);
  visitor->Trace(current_elapsed_query_);
  visitor->Trace(sampler_units_);
  visitor->Trace(get_buffer_sub_data_async_callbacks_);
  WebGLRenderingContextBase::Trace(visitor);
}


  sfnt_open_font( FT_Stream  stream,
                  TT_Face    face )
  {
    FT_Memory  memory = stream->memory;
    FT_Error   error;
    FT_ULong   tag, offset;

    static const FT_Frame_Field  ttc_header_fields[] =
    {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  TTC_HeaderRec

      FT_FRAME_START( 8 ),
        FT_FRAME_LONG( version ),
        FT_FRAME_LONG( count   ),  /* this is ULong in the specs */
      FT_FRAME_END
    };

    face->ttc_header.tag     = 0;
    face->ttc_header.version = 0;
    face->ttc_header.count   = 0;

  retry:
    offset = FT_STREAM_POS();

    if ( FT_READ_ULONG( tag ) )
      return error;

    if ( tag == TTAG_wOFF )
    {
      FT_TRACE2(( "sfnt_open_font: file is a WOFF; synthesizing SFNT\n" ));

      if ( FT_STREAM_SEEK( offset ) )
        return error;

      error = woff_open_font( stream, face );
      if ( error )
        return error;

      /* Swap out stream and retry! */
      stream = face->root.stream;
      goto retry;
    }

    if ( tag != 0x00010000UL &&
         tag != TTAG_ttcf    &&
         tag != TTAG_OTTO    &&
         tag != TTAG_true    &&
         tag != TTAG_typ1    &&
         tag != 0x00020000UL )
    {
      FT_TRACE2(( "  not a font using the SFNT container format\n" ));
      return FT_THROW( Unknown_File_Format );
    }

    face->ttc_header.tag = TTAG_ttcf;

    if ( tag == TTAG_ttcf )
    {
      FT_Int  n;

      FT_TRACE3(( "sfnt_open_font: file is a collection\n" ));

      if ( FT_STREAM_READ_FIELDS( ttc_header_fields, &face->ttc_header ) )
        return error;

      FT_TRACE3(( "                with %ld subfonts\n",
                  face->ttc_header.count ));

      if ( face->ttc_header.count == 0 )
        return FT_THROW( Invalid_Table );

      /* a rough size estimate: let's conservatively assume that there   */
      /* is just a single table info in each subfont header (12 + 16*1 = */
      /* 28 bytes), thus we have (at least) `12 + 4*count' bytes for the */
      /* size of the TTC header plus `28*count' bytes for all subfont    */
      /* headers                                                         */
      if ( (FT_ULong)face->ttc_header.count > stream->size / ( 28 + 4 ) )
        return FT_THROW( Array_Too_Large );

      /* now read the offsets of each font in the file */
      if ( FT_NEW_ARRAY( face->ttc_header.offsets, face->ttc_header.count ) )
        return error;

      if ( FT_FRAME_ENTER( face->ttc_header.count * 4L ) )
        return error;

      for ( n = 0; n < face->ttc_header.count; n++ )
        face->ttc_header.offsets[n] = FT_GET_ULONG();

      FT_FRAME_EXIT();
    }
    else
    {
      FT_TRACE3(( "sfnt_open_font: synthesize TTC\n" ));

      face->ttc_header.version = 1 << 16;
      face->ttc_header.count   = 1;

      if ( FT_NEW( face->ttc_header.offsets ) )
        return error;

      face->ttc_header.offsets[0] = offset;
    }

    return error;
  }


void WebGL2RenderingContextBase::texSubImage3D(
    ExecutionContext* execution_context,
    GLenum target,
    GLint level,
    GLint xoffset,
    GLint yoffset,
    GLint zoffset,
    GLsizei width,
    GLsizei height,
    GLsizei depth,
    GLenum format,
    GLenum type,
    HTMLCanvasElement* canvas,
    ExceptionState& exception_state) {
  if (isContextLost())
    return;
  if (bound_pixel_unpack_buffer_) {
    SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D",
                      "a buffer is bound to PIXEL_UNPACK_BUFFER");
    return;
  }

  TexImageHelperHTMLCanvasElement(execution_context->GetSecurityOrigin(),
                                  kTexSubImage3D, target, level, 0, format,
                                  type, xoffset, yoffset, zoffset, canvas,
                                  GetTextureSourceSubRectangle(width, height),
                                  depth, unpack_image_height_, exception_state);
}


int TouchEventConverterEvdev::GetTouchPoints() const {
  return touch_points_;
}


aiff_open (SF_PRIVATE *psf)
{	COMM_CHUNK comm_fmt ;
	int error, subformat ;

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

	subformat = SF_CODEC (psf->sf.format) ;

	if ((psf->container_data = calloc (1, sizeof (AIFF_PRIVATE))) == NULL)
		return SFE_MALLOC_FAILED ;

	if (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->filelength > 0))
	{	if ((error = aiff_read_header (psf, &comm_fmt)))
			return error ;

		psf->next_chunk_iterator = aiff_next_chunk_iterator ;
		psf->get_chunk_size = aiff_get_chunk_size ;
		psf->get_chunk_data = aiff_get_chunk_data ;

		psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
		} ;

	if (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)
	{	if (psf->is_pipe)
			return SFE_NO_PIPE_WRITE ;

		if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_AIFF)
			return SFE_BAD_OPEN_FORMAT ;

		if (psf->file.mode == SFM_WRITE && (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE))
		{	if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
				return SFE_MALLOC_FAILED ;
			psf->peak_info->peak_loc = SF_PEAK_START ;
			} ;

		if (psf->file.mode != SFM_RDWR || psf->filelength < 40)
		{	psf->filelength = 0 ;
			psf->datalength = 0 ;
			psf->dataoffset = 0 ;
			psf->sf.frames = 0 ;
			} ;

		psf->strings.flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;

		if ((error = aiff_write_header (psf, SF_FALSE)))
			return error ;

		psf->write_header	= aiff_write_header ;
		psf->set_chunk		= aiff_set_chunk ;
		} ;

	psf->container_close = aiff_close ;
	psf->command = aiff_command ;

	switch (SF_CODEC (psf->sf.format))
	{	case SF_FORMAT_PCM_U8 :
				error = pcm_init (psf) ;
				break ;

		case SF_FORMAT_PCM_S8 :
				error = pcm_init (psf) ;
				break ;

		case SF_FORMAT_PCM_16 :
		case SF_FORMAT_PCM_24 :
		case SF_FORMAT_PCM_32 :
				error = pcm_init (psf) ;
				break ;

		case SF_FORMAT_ULAW :
				error = ulaw_init (psf) ;
				break ;

		case SF_FORMAT_ALAW :
				error = alaw_init (psf) ;
				break ;

		/* Lite remove start */
		case SF_FORMAT_FLOAT :
				error = float32_init (psf) ;
				break ;

		case SF_FORMAT_DOUBLE :
				error = double64_init (psf) ;
				break ;

		case SF_FORMAT_DWVW_12 :
				if (psf->sf.frames > comm_fmt.numSampleFrames)
					psf->sf.frames = comm_fmt.numSampleFrames ;
				break ;

		case SF_FORMAT_DWVW_16 :
				error = dwvw_init (psf, 16) ;
				if (psf->sf.frames > comm_fmt.numSampleFrames)
					psf->sf.frames = comm_fmt.numSampleFrames ;
				break ;

		case SF_FORMAT_DWVW_24 :
				error = dwvw_init (psf, 24) ;
				if (psf->sf.frames > comm_fmt.numSampleFrames)
					psf->sf.frames = comm_fmt.numSampleFrames ;
				break ;

		case SF_FORMAT_DWVW_N :
				if (psf->file.mode != SFM_READ)
				{	error = SFE_DWVW_BAD_BITWIDTH ;
					break ;
					} ;
				if (comm_fmt.sampleSize >= 8 && comm_fmt.sampleSize < 24)
				{	error = dwvw_init (psf, comm_fmt.sampleSize) ;
					if (psf->sf.frames > comm_fmt.numSampleFrames)
						psf->sf.frames = comm_fmt.numSampleFrames ;
					break ;
					} ;
				psf_log_printf (psf, "AIFC/DWVW : Bad bitwidth %d\n", comm_fmt.sampleSize) ;
				error = SFE_DWVW_BAD_BITWIDTH ;
				break ;

		case SF_FORMAT_IMA_ADPCM :
				/*
				**	IMA ADPCM encoded AIFF files always have a block length
				**	of 34 which decodes to 64 samples.
				*/
				error = aiff_ima_init (psf, AIFC_IMA4_BLOCK_LEN, AIFC_IMA4_SAMPLES_PER_BLOCK) ;
				break ;
		/* Lite remove end */

		case SF_FORMAT_GSM610 :
				error = gsm610_init (psf) ;
				if (psf->sf.frames > comm_fmt.numSampleFrames)
					psf->sf.frames = comm_fmt.numSampleFrames ;
				break ;

		default : return SFE_UNIMPLEMENTED ;
		} ;

	if (psf->file.mode != SFM_WRITE && psf->sf.frames - comm_fmt.numSampleFrames != 0)
	{	psf_log_printf (psf,
			"*** Frame count read from 'COMM' chunk (%u) not equal to frame count\n"
			"*** calculated from length of 'SSND' chunk (%u).\n",
			comm_fmt.numSampleFrames, (uint32_t) psf->sf.frames) ;
		} ;

	return error ;
} /* aiff_open */


void Textfield::ExecuteTextEditCommand(ui::TextEditCommand command) {
  DestroyTouchSelection();

  bool add_to_kill_buffer = false;

  switch (command) {
    case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE:
    case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_PARAGRAPH:
    case ui::TextEditCommand::DELETE_TO_END_OF_LINE:
    case ui::TextEditCommand::DELETE_TO_END_OF_PARAGRAPH:
      add_to_kill_buffer = text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD;
      FALLTHROUGH;
    case ui::TextEditCommand::DELETE_WORD_BACKWARD:
    case ui::TextEditCommand::DELETE_WORD_FORWARD:
      if (HasSelection())
        command = ui::TextEditCommand::DELETE_FORWARD;
      break;
    default:
      break;
  }

  if (!Textfield::IsTextEditCommandEnabled(command))
    return;

  bool text_changed = false;
  bool cursor_changed = false;
  bool rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT;
  gfx::VisualCursorDirection begin = rtl ? gfx::CURSOR_RIGHT : gfx::CURSOR_LEFT;
  gfx::VisualCursorDirection end = rtl ? gfx::CURSOR_LEFT : gfx::CURSOR_RIGHT;
  gfx::SelectionModel selection_model = GetSelectionModel();

  OnBeforeUserAction();
  switch (command) {
    case ui::TextEditCommand::DELETE_BACKWARD:
      text_changed = cursor_changed = model_->Backspace(add_to_kill_buffer);
      break;
    case ui::TextEditCommand::DELETE_FORWARD:
      text_changed = cursor_changed = model_->Delete(add_to_kill_buffer);
      break;
    case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE:
    case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_PARAGRAPH:
      model_->MoveCursor(gfx::LINE_BREAK, begin, gfx::SELECTION_RETAIN);
      text_changed = cursor_changed = model_->Backspace(add_to_kill_buffer);
      break;
    case ui::TextEditCommand::DELETE_TO_END_OF_LINE:
    case ui::TextEditCommand::DELETE_TO_END_OF_PARAGRAPH:
      model_->MoveCursor(gfx::LINE_BREAK, end, gfx::SELECTION_RETAIN);
      text_changed = cursor_changed = model_->Delete(add_to_kill_buffer);
      break;
    case ui::TextEditCommand::DELETE_WORD_BACKWARD:
      model_->MoveCursor(gfx::WORD_BREAK, begin, gfx::SELECTION_RETAIN);
      text_changed = cursor_changed = model_->Backspace(add_to_kill_buffer);
      break;
    case ui::TextEditCommand::DELETE_WORD_FORWARD:
      model_->MoveCursor(gfx::WORD_BREAK, end, gfx::SELECTION_RETAIN);
      text_changed = cursor_changed = model_->Delete(add_to_kill_buffer);
      break;
    case ui::TextEditCommand::MOVE_BACKWARD:
      model_->MoveCursor(gfx::CHARACTER_BREAK, begin, gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_BACKWARD_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::CHARACTER_BREAK, begin, gfx::SELECTION_RETAIN);
      break;
    case ui::TextEditCommand::MOVE_FORWARD:
      model_->MoveCursor(gfx::CHARACTER_BREAK, end, gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_FORWARD_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::CHARACTER_BREAK, end, gfx::SELECTION_RETAIN);
      break;
    case ui::TextEditCommand::MOVE_LEFT:
      model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT,
                         gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_LEFT_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT,
                         gfx::SELECTION_RETAIN);
      break;
    case ui::TextEditCommand::MOVE_RIGHT:
      model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT,
                         gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_RIGHT_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT,
                         gfx::SELECTION_RETAIN);
      break;
    case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT:
    case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE:
    case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_PARAGRAPH:
    case ui::TextEditCommand::MOVE_UP:
    case ui::TextEditCommand::MOVE_PAGE_UP:
      model_->MoveCursor(gfx::LINE_BREAK, begin, gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::
        MOVE_TO_BEGINNING_OF_DOCUMENT_AND_MODIFY_SELECTION:
    case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION:
    case ui::TextEditCommand::
        MOVE_TO_BEGINNING_OF_PARAGRAPH_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::LINE_BREAK, begin, kLineSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION:
    case ui::TextEditCommand::MOVE_UP_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::LINE_BREAK, begin, gfx::SELECTION_RETAIN);
      break;
    case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT:
    case ui::TextEditCommand::MOVE_TO_END_OF_LINE:
    case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH:
    case ui::TextEditCommand::MOVE_DOWN:
    case ui::TextEditCommand::MOVE_PAGE_DOWN:
      model_->MoveCursor(gfx::LINE_BREAK, end, gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT_AND_MODIFY_SELECTION:
    case ui::TextEditCommand::MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION:
    case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::LINE_BREAK, end, kLineSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION:
    case ui::TextEditCommand::MOVE_DOWN_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::LINE_BREAK, end, gfx::SELECTION_RETAIN);
      break;
    case ui::TextEditCommand::MOVE_PARAGRAPH_BACKWARD_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::LINE_BREAK, begin,
                         kMoveParagraphSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_PARAGRAPH_FORWARD_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::LINE_BREAK, end, kMoveParagraphSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_WORD_BACKWARD:
      model_->MoveCursor(gfx::WORD_BREAK, begin, gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_WORD_BACKWARD_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::WORD_BREAK, begin, kWordSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_WORD_FORWARD:
      model_->MoveCursor(gfx::WORD_BREAK, end, gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_WORD_FORWARD_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::WORD_BREAK, end, kWordSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_WORD_LEFT:
      model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT,
                         gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_WORD_LEFT_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT,
                         kWordSelectionBehavior);
      break;
    case ui::TextEditCommand::MOVE_WORD_RIGHT:
      model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT,
                         gfx::SELECTION_NONE);
      break;
    case ui::TextEditCommand::MOVE_WORD_RIGHT_AND_MODIFY_SELECTION:
      model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT,
                         kWordSelectionBehavior);
      break;
    case ui::TextEditCommand::UNDO:
      text_changed = cursor_changed = model_->Undo();
      break;
    case ui::TextEditCommand::REDO:
      text_changed = cursor_changed = model_->Redo();
      break;
    case ui::TextEditCommand::CUT:
      text_changed = cursor_changed = Cut();
      break;
    case ui::TextEditCommand::COPY:
      Copy();
      break;
    case ui::TextEditCommand::PASTE:
      text_changed = cursor_changed = Paste();
      break;
    case ui::TextEditCommand::SELECT_ALL:
      SelectAll(false);
      break;
    case ui::TextEditCommand::TRANSPOSE:
      text_changed = cursor_changed = model_->Transpose();
      break;
    case ui::TextEditCommand::YANK:
      text_changed = cursor_changed = model_->Yank();
      break;
    case ui::TextEditCommand::INSERT_TEXT:
    case ui::TextEditCommand::SET_MARK:
    case ui::TextEditCommand::UNSELECT:
    case ui::TextEditCommand::INVALID_COMMAND:
      NOTREACHED();
      break;
  }

  cursor_changed |= GetSelectionModel() != selection_model;
  if (cursor_changed && HasSelection())
    UpdateSelectionClipboard();
  UpdateAfterChange(text_changed, cursor_changed);
  OnAfterUserAction();
}


static VALUE cState_object_nl_set ( VALUE self , VALUE object_nl ) {
 unsigned long len ;
 GET_STATE ( self ) ;
 Check_Type ( object_nl , T_STRING ) ;
 len = RSTRING_LEN ( object_nl ) ;
 if ( len == 0 ) {
 if ( state -> object_nl ) {
 ruby_xfree ( state -> object_nl ) ;
 state -> object_nl = NULL ;
 }
 }
 else {
 if ( state -> object_nl ) ruby_xfree ( state -> object_nl ) ;
 state -> object_nl = strdup ( RSTRING_PTR ( object_nl ) ) ;
 state -> object_nl_len = len ;
 }
 return Qnil ;
 }


static unsigned int startup_pirq(struct irq_data *data)
{
	return __startup_pirq(data->irq);
}


static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value)
{
  size_t oldsize = p->size, i;
  if(!ucvector_resize(p, size)) return 0;
  for(i = oldsize; i < size; i++) p->data[i] = value;
  return 1;
}


  ~AudioSourceProviderClientLockScope() {
    if (m_client)
      m_client->unlock();
  }


TEST(HTTPDownstreamTest, ByteEventsDrained) {
  // Test that byte events are drained before socket is closed
  EventBase evb;

  NiceMock<MockController> mockController;
  auto codec = makeDownstreamParallelCodec();
  auto byteEventTracker = new MockByteEventTracker(nullptr);
  auto transport = newMockTransport(&evb);
  auto transactionTimeouts = makeInternalTimeoutSet(&evb);

  // Create the downstream session
  auto session = new HTTPDownstreamSession(
    transactionTimeouts.get(),
    AsyncTransportWrapper::UniquePtr(transport),
    localAddr, peerAddr,
    &mockController, std::move(codec),
    mockTransportInfo,
    nullptr);
  session->setByteEventTracker(
      std::unique_ptr<ByteEventTracker>(byteEventTracker));

  InSequence enforceOrder;

  session->startNow();

  // Byte events should be drained first
  EXPECT_CALL(*byteEventTracker, drainByteEvents())
    .Times(1);
  EXPECT_CALL(*transport, closeNow())
    .Times(AtLeast(1));

  // Close the socket
  session->dropConnection();
  evb.loop();
}


static pfunc found_string(struct jv_parser* p) {
  char* in = p->tokenbuf;
  char* out = p->tokenbuf;
  char* end = p->tokenbuf + p->tokenpos;

  while (in < end) {
    char c = *in++;
    if (c == '\\') {
      if (in >= end)
        return "Expected escape character at end of string";
      c = *in++;
      switch (c) {
      case '\\':
      case '"':
      case '/': *out++ = c;    break;
      case 'b': *out++ = '\b'; break;
      case 'f': *out++ = '\f'; break;
      case 't': *out++ = '\t'; break;
      case 'n': *out++ = '\n'; break;
      case 'r': *out++ = '\r'; break;

      case 'u':
        /* ahh, the complicated case */
        if (in + 4 > end)
          return "Invalid \\uXXXX escape";
        int hexvalue = unhex4(in);
        if (hexvalue < 0)
          return "Invalid characters in \\uXXXX escape";
        unsigned long codepoint = (unsigned long)hexvalue;
        in += 4;
        if (0xD800 <= codepoint && codepoint <= 0xDBFF) {
          /* who thought UTF-16 surrogate pairs were a good idea? */
          if (in + 6 > end || in[0] != '\\' || in[1] != 'u')
            return "Invalid \\uXXXX\\uXXXX surrogate pair escape";
          unsigned long surrogate = unhex4(in+2);
          if (!(0xDC00 <= surrogate && surrogate <= 0xDFFF))
            return "Invalid \\uXXXX\\uXXXX surrogate pair escape";
          in += 6;
          codepoint = 0x10000 + (((codepoint - 0xD800) << 10)
                                 |(surrogate - 0xDC00));
        }
        if (codepoint > 0x10FFFF)
          codepoint = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER
        out += jvp_utf8_encode(codepoint, out);
        break;

      default:
        return "Invalid escape";
      }
    } else {
      if (c > 0 && c < 0x001f)
        return "Invalid string: control characters from U+0000 through U+001F must be escaped";
      *out++ = c;
    }
  }
  TRY(value(p, jv_string_sized(p->tokenbuf, out - p->tokenbuf)));
  p->tokenpos = 0;
  return 0;
}


int dns_packet_append_label(DnsPacket *p, const char *d, size_t l, bool canonical_candidate, size_t *start) {
        uint8_t *w;
        int r;

        /* Append a label to a packet. Optionally, does this in DNSSEC
         * canonical form, if this label is marked as a candidate for
         * it, and the canonical form logic is enabled for the
         * packet */

        assert(p);
        assert(d);

        if (l > DNS_LABEL_MAX)
                return -E2BIG;

        r = dns_packet_extend(p, 1 + l, (void**) &w, start);
        if (r < 0)
                return r;

        *(w++) = (uint8_t) l;

        if (p->canonical_form && canonical_candidate) {
                size_t i;

                /* Generate in canonical form, as defined by DNSSEC
                 * RFC 4034, Section 6.2, i.e. all lower-case. */

                for (i = 0; i < l; i++)
                        w[i] = (uint8_t) ascii_tolower(d[i]);
        } else
                /* Otherwise, just copy the string unaltered. This is
                 * essential for DNS-SD, where the casing of labels
                 * matters and needs to be retained. */
                memcpy(w, d, l);

        return 0;
}


njs_generate_switch_default(njs_vm_t *vm, njs_generator_t *generator,
    njs_parser_node_t *branch)
{
    njs_parser_node_t           *node;
    njs_generator_patch_t       *next;
    njs_generator_switch_ctx_t  *ctx;

    ctx = generator->context;

    if (branch->token_type == NJS_TOKEN_DEFAULT) {
        njs_code_set_jump_offset(generator, njs_vmcode_jump_t,
                                 ctx->jump_offset);
        ctx->jump = NULL;
        node = branch;

    } else {
        njs_code_update_offset(generator, ctx->patch);

        next = ctx->patch->next;

        njs_mp_free(vm->mem_pool, ctx->patch);

        ctx->patch = next;
        node = branch->right;
    }

    njs_generator_next(generator, njs_generate, node->right);

    branch = branch->left;

    if (branch == NULL) {
        return njs_generator_after(vm, generator,
                                   njs_queue_first(&generator->stack), branch,
                                   njs_generator_pop, NULL, 0);
    }

    return njs_generator_after(vm, generator,
                               njs_queue_first(&generator->stack), branch,
                               njs_generate_switch_default, ctx, 0);
}


void blkconf_serial(BlockConf *conf, char **serial)

{

    DriveInfo *dinfo;

    if (!*serial) {

        /* try to fall back to value set with legacy -drive serial=... */

        dinfo = drive_get_by_blockdev(conf->bs);

        if (*dinfo->serial) {

            *serial = g_strdup(dinfo->serial);

        }

    }

}


OMX_ERRORTYPE SoftAVC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) {
 switch (index) {
 case OMX_IndexParamVideoBitrate:
 {

             OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
                 (OMX_VIDEO_PARAM_BITRATETYPE *)params;

            if (!isValidOMXParam(bitRate)) {
                return OMX_ErrorBadParameter;
            }

             if (bitRate->nPortIndex != 1) {
                 return OMX_ErrorUndefined;
             }

            bitRate->eControlRate = OMX_Video_ControlRateVariable;
            bitRate->nTargetBitrate = mBitrate;
 return OMX_ErrorNone;
 }

 case OMX_IndexParamVideoAvc:

         {
             OMX_VIDEO_PARAM_AVCTYPE *avcParams = (OMX_VIDEO_PARAM_AVCTYPE *)params;

            if (!isValidOMXParam(avcParams)) {
                return OMX_ErrorBadParameter;
            }

             if (avcParams->nPortIndex != 1) {
                 return OMX_ErrorUndefined;
             }

            OMX_VIDEO_AVCLEVELTYPE omxLevel = OMX_VIDEO_AVCLevel41;
 if (OMX_ErrorNone
 != ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
 return OMX_ErrorUndefined;
 }

            avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
            avcParams->eLevel = omxLevel;
            avcParams->nRefFrames = 1;
            avcParams->bUseHadamard = OMX_TRUE;
            avcParams->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI
 | OMX_VIDEO_PictureTypeP | OMX_VIDEO_PictureTypeB);
            avcParams->nRefIdx10ActiveMinus1 = 0;
            avcParams->nRefIdx11ActiveMinus1 = 0;
            avcParams->bWeightedPPrediction = OMX_FALSE;
            avcParams->bconstIpred = OMX_FALSE;
            avcParams->bDirect8x8Inference = OMX_FALSE;
            avcParams->bDirectSpatialTemporal = OMX_FALSE;
            avcParams->nCabacInitIdc = 0;
 return OMX_ErrorNone;
 }

 default:
 return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
 }
}


R_API char *r_bin_java_print_methodtype_cp_stringify(RBinJavaCPTypeObj *obj) {
	ut32 size = 255, consumed = 0;
	char *value = malloc (size);
	if (value) {
		memset (value, 0, size);
		consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
			obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
			obj->info.cp_method_type.descriptor_index);
		if (consumed >= size - 1) {
			free (value);
			size += size >> 1;
			value = malloc (size);
			if (value) {
				memset (value, 0, size);
				(void)snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
					obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
					obj->info.cp_method_type.descriptor_index);
			}
		}
	}
	return value;
}


static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
			       struct cftype *cft)
{
	struct task_group *tg = css_tg(css);

	return (u64) scale_load_down(tg->shares);
}


void OmniboxEditModel::Revert() {
  SetInputInProgress(false);
  paste_state_ = NONE;
  InternalSetUserText(base::string16());
  keyword_.clear();
  is_keyword_hint_ = false;
  has_temporary_text_ = false;
  view_->SetWindowTextAndCaretPos(permanent_text_,
                                  has_focus() ? permanent_text_.length() : 0,
                                  false, true);
  AutocompleteActionPredictor* action_predictor =
      predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
  action_predictor->ClearTransitionalMatches();
  action_predictor->CancelPrerender();
}


void enc28j60SoftReset(NetInterface *interface)
{
   //Pull the CS pin low
   interface->spiDriver->assertCs();

   //Write opcode
   interface->spiDriver->transfer(ENC28J60_CMD_SRC);

   //Terminate the operation by raising the CS pin
   interface->spiDriver->deassertCs();
}


void RenderFrameImpl::reportFindInPageSelection(
    int request_id,
    int active_match_ordinal,
    const blink::WebRect& selection_rect) {
  render_view_->Send(new ViewHostMsg_Find_Reply(
      render_view_->GetRoutingID(), request_id, -1, selection_rect,
      active_match_ordinal, false));
}


static int s390_last_break_set(struct task_struct *target,
			       const struct user_regset *regset,
			       unsigned int pos, unsigned int count,
			       const void *kbuf, const void __user *ubuf)
{
	return 0;
}


void TestRenderViewHost::SimulateWasShown() {
  GetWidget()->WasShown(ui::LatencyInfo());
}


inline int CountLeadingSignBits(T integer_input) {
  static_assert(std::is_signed<T>::value, "Only signed integer types handled.");
#if defined(__GNUC__) && !defined(__clang__)
  return integer_input ? __builtin_clrsb(integer_input)
                       : std::numeric_limits<T>::digits;
#else
  using U = typename std::make_unsigned<T>::type;
  return integer_input >= 0
             ? CountLeadingZeros(static_cast<U>(integer_input)) - 1
         : integer_input != std::numeric_limits<T>::min()
             ? CountLeadingZeros(2 * static_cast<U>(-integer_input) - 1)
             : 0;
#endif
}


static boolean EmptyOutputBuffer(j_compress_ptr cinfo)
{
  DestinationManager
    *destination;

  destination=(DestinationManager *) cinfo->dest;
  destination->manager.free_in_buffer=(size_t) WriteBlob(destination->image,
    MagickMinBufferExtent,destination->buffer);
  if (destination->manager.free_in_buffer != MagickMinBufferExtent)
    ERREXIT(cinfo,JERR_FILE_WRITE);
  destination->manager.next_output_byte=destination->buffer;
  return(TRUE);
}


int uwsgi_php_request ( struct wsgi_request * wsgi_req ) {
 char real_filename [ PATH_MAX + 1 ] ;
 char * path_info = NULL ;
 size_t real_filename_len = 0 ;
 struct stat php_stat ;
 char * filename = NULL ;
 int force_empty_script_name = 0 ;
 zend_file_handle file_handle ;
 # ifdef ZTS TSRMLS_FETCH ( ) ;
 # endif SG ( server_context ) = ( void * ) wsgi_req ;
 if ( uwsgi_parse_vars ( wsgi_req ) ) {
 return - 1 ;
 }
 char * orig_path_info = wsgi_req -> path_info ;
 uint16_t orig_path_info_len = wsgi_req -> path_info_len ;
 if ( uphp . docroot ) {
 wsgi_req -> document_root = uphp . docroot ;
 }
 else if ( ! wsgi_req -> document_root_len ) {
 wsgi_req -> document_root = uwsgi . cwd ;
 }
 else {
 char * sanitized_docroot = ecalloc ( 1 , PATH_MAX + 1 ) ;
 if ( ! uwsgi_expand_path ( wsgi_req -> document_root , wsgi_req -> document_root_len , sanitized_docroot ) ) {
 efree ( sanitized_docroot ) ;
 return - 1 ;
 }
 wsgi_req -> document_root = sanitized_docroot ;
 }
 wsgi_req -> document_root_len = strlen ( wsgi_req -> document_root ) ;
 if ( uphp . app ) {
 # ifdef UWSGI_PCRE struct uwsgi_regexp_list * bypass = uphp . app_bypass ;
 while ( bypass ) {
 if ( uwsgi_regexp_match ( bypass -> pattern , bypass -> pattern_extra , wsgi_req -> uri , wsgi_req -> uri_len ) >= 0 ) {
 goto oldstyle ;
 }
 bypass = bypass -> next ;
 }
 # endif strcpy ( real_filename , uphp . app ) ;
 if ( wsgi_req -> path_info_len == 1 && wsgi_req -> path_info [ 0 ] == '/' ) {
 goto appready ;
 }
 if ( uphp . app_qs ) {
 size_t app_qs_len = strlen ( uphp . app_qs ) ;
 size_t qs_len = wsgi_req -> path_info_len + app_qs_len ;
 if ( wsgi_req -> query_string_len > 0 ) {
 qs_len += 1 + wsgi_req -> query_string_len ;
 }
 char * qs = ecalloc ( 1 , qs_len + 1 ) ;
 memcpy ( qs , uphp . app_qs , app_qs_len ) ;
 memcpy ( qs + app_qs_len , wsgi_req -> path_info , wsgi_req -> path_info_len ) ;
 if ( wsgi_req -> query_string_len > 0 ) {
 char * ptr = qs + app_qs_len + wsgi_req -> path_info_len ;
 * ptr = '&' ;
 memcpy ( ptr + 1 , wsgi_req -> query_string , wsgi_req -> query_string_len ) ;
 }
 wsgi_req -> query_string = qs ;
 wsgi_req -> query_string_len = qs_len ;
 }
 appready : wsgi_req -> path_info = "" ;
 wsgi_req -> path_info_len = 0 ;
 force_empty_script_name = 1 ;
 goto secure2 ;
 }
 # ifdef UWSGI_PCRE oldstyle : # endif filename = uwsgi_concat4n ( wsgi_req -> document_root , wsgi_req -> document_root_len , "/" , 1 , wsgi_req -> path_info , wsgi_req -> path_info_len , "" , 0 ) ;
 if ( uwsgi_php_walk ( wsgi_req , filename , wsgi_req -> document_root , wsgi_req -> document_root_len , & path_info ) ) {
 free ( filename ) ;
 if ( uphp . fallback || uphp . fallback2 ) {
 if ( uphp . fallback ) {
 filename = uwsgi_str ( uphp . fallback ) ;
 }
 else {
 filename = uwsgi_concat2n ( wsgi_req -> document_root , strlen ( wsgi_req -> document_root ) , uphp . fallback2 , strlen ( uphp . fallback2 ) ) ;
 wsgi_req -> script_name = uphp . fallback2 ;
 wsgi_req -> script_name_len = strlen ( uphp . fallback2 ) ;
 }
 if ( uphp . fallback_qs ) {
 size_t fqs_len = strlen ( uphp . fallback_qs ) ;
 size_t new_qs_len = orig_path_info_len + fqs_len + 1 + wsgi_req -> query_string_len ;
 char * new_qs = ecalloc ( 1 , new_qs_len + 1 ) ;
 memcpy ( new_qs , uphp . fallback_qs , fqs_len ) ;
 new_qs [ fqs_len ] = '=' ;
 memcpy ( new_qs + fqs_len + 1 , orig_path_info , orig_path_info_len ) ;
 if ( wsgi_req -> query_string_len ) {
 new_qs [ fqs_len + 1 + orig_path_info_len ] = '&' ;
 memcpy ( new_qs + fqs_len + 2 + orig_path_info_len , wsgi_req -> query_string , wsgi_req -> query_string_len ) ;
 }
 wsgi_req -> query_string = new_qs ;
 wsgi_req -> query_string_len = new_qs_len ;
 }
 }
 else {
 uwsgi_404 ( wsgi_req ) ;
 return - 1 ;
 }
 }
 if ( path_info ) {
 wsgi_req -> path_info = path_info ;
 wsgi_req -> path_info_len = orig_path_info_len - ( path_info - orig_path_info ) ;
 }
 else {
 wsgi_req -> path_info = "" ;
 wsgi_req -> path_info_len = 0 ;
 }
 if ( ! realpath ( filename , real_filename ) ) {
 free ( filename ) ;
 uwsgi_404 ( wsgi_req ) ;
 return - 1 ;
 }
 free ( filename ) ;
 real_filename_len = strlen ( real_filename ) ;
 if ( uphp . allowed_docroot ) {
 struct uwsgi_string_list * usl = uphp . allowed_docroot ;
 while ( usl ) {
 if ( ! uwsgi_starts_with ( real_filename , real_filename_len , usl -> value , usl -> len ) ) {
 goto secure ;
 }
 usl = usl -> next ;
 }
 uwsgi_403 ( wsgi_req ) ;
 uwsgi_log ( "PHP security error: %s is not under an allowed docroot\n" , real_filename ) ;
 return - 1 ;
 }
 else if ( uphp . docroot ) {
 if ( ! uwsgi_starts_with ( real_filename , real_filename_len , uphp . docroot , uphp . docroot_len ) ) {
 goto secure ;
 }
 uwsgi_403 ( wsgi_req ) ;
 uwsgi_log ( "PHP security error: %s is not under the default docroot\n" , real_filename ) ;
 return - 1 ;
 }
 secure : if ( stat ( real_filename , & php_stat ) ) {
 uwsgi_404 ( wsgi_req ) ;
 return UWSGI_OK ;
 }
 if ( S_ISDIR ( php_stat . st_mode ) ) {
 if ( orig_path_info_len == 0 || ( orig_path_info_len > 0 && orig_path_info [ orig_path_info_len - 1 ] != '/' ) ) {
 wsgi_req -> path_info = orig_path_info ;
 wsgi_req -> path_info_len = orig_path_info_len ;
 uwsgi_redirect_to_slash ( wsgi_req ) ;
 return UWSGI_OK ;
 }
 struct uwsgi_string_list * upi = uphp . index ;
 real_filename [ real_filename_len ] = '/' ;
 real_filename_len ++ ;
 int found = 0 ;
 while ( upi ) {
 if ( real_filename_len + upi -> len + 1 < PATH_MAX ) {
 memcpy ( real_filename + real_filename_len , upi -> value , upi -> len + 1 ) ;
 if ( ! access ( real_filename , R_OK ) ) {
 found = 1 ;
 break ;
 }
 }
 upi = upi -> next ;
 }
 if ( ! found ) {
 uwsgi_404 ( wsgi_req ) ;
 return UWSGI_OK ;
 }
 real_filename_len = strlen ( real_filename ) ;
 }
 if ( uphp . allowed_ext ) {
 struct uwsgi_string_list * usl = uphp . allowed_ext ;
 while ( usl ) {
 if ( real_filename_len >= usl -> len ) {
 if ( ! uwsgi_strncmp ( real_filename + ( real_filename_len - usl -> len ) , usl -> len , usl -> value , usl -> len ) ) {
 goto secure2 ;
 }
 }
 usl = usl -> next ;
 }
 uwsgi_403 ( wsgi_req ) ;
 uwsgi_log ( "PHP security error: %s does not end with an allowed extension\n" , real_filename ) ;
 return - 1 ;
 }
 secure2 : wsgi_req -> file = real_filename ;
 wsgi_req -> file_len = strlen ( wsgi_req -> file ) ;
 if ( uphp . allowed_scripts ) {
 struct uwsgi_string_list * usl = uphp . allowed_scripts ;
 while ( usl ) {
 if ( ! uwsgi_strncmp ( wsgi_req -> file , wsgi_req -> file_len , usl -> value , usl -> len ) ) {
 goto secure3 ;
 }
 usl = usl -> next ;
 }
 uwsgi_403 ( wsgi_req ) ;
 uwsgi_log ( "PHP security error: %s is not an allowed script\n" , real_filename ) ;
 return - 1 ;
 }
 secure3 : if ( force_empty_script_name ) {
 wsgi_req -> script_name = "" ;
 wsgi_req -> script_name_len = 0 ;
 }
 else if ( ! uphp . fallback2 ) {
 wsgi_req -> script_name = orig_path_info ;
 if ( path_info ) {
 wsgi_req -> script_name_len = path_info - orig_path_info ;
 }
 else {
 wsgi_req -> script_name_len = orig_path_info_len ;
 }
 }
 # ifdef UWSGI_DEBUG uwsgi_log ( "php filename = %s script_name = %.*s (%d) document_root = %.*s (%d)\n" , real_filename , wsgi_req -> script_name_len , wsgi_req -> script_name , wsgi_req -> script_name_len , wsgi_req -> document_root_len , wsgi_req -> document_root , wsgi_req -> document_root_len ) ;
 # endif SG ( request_info ) . request_uri = estrndup ( wsgi_req -> uri , wsgi_req -> uri_len ) ;
 SG ( request_info ) . request_method = estrndup ( wsgi_req -> method , wsgi_req -> method_len ) ;
 SG ( request_info ) . proto_num = 1001 ;
 SG ( request_info ) . query_string = estrndup ( wsgi_req -> query_string , wsgi_req -> query_string_len ) ;
 SG ( request_info ) . content_length = wsgi_req -> post_cl ;
 SG ( request_info ) . content_type = estrndup ( wsgi_req -> content_type , wsgi_req -> content_type_len ) ;
 SG ( sapi_headers ) . http_response_code = 200 ;
 SG ( request_info ) . path_translated = wsgi_req -> file ;
 file_handle . type = ZEND_HANDLE_FILENAME ;
 file_handle . filename = real_filename ;
 file_handle . free_filename = 0 ;
 file_handle . opened_path = NULL ;
 if ( php_request_startup ( TSRMLS_C ) == FAILURE ) {
 uwsgi_500 ( wsgi_req ) ;
 return - 1 ;
 }
 struct uwsgi_string_list * usl = NULL ;
 uwsgi_foreach ( usl , uphp . exec_before ) {
 if ( zend_eval_string_ex ( usl -> value , NULL , "uWSGI php exec before" , 1 TSRMLS_CC ) == FAILURE ) goto end ;
 }
 php_execute_script ( & file_handle TSRMLS_CC ) ;
 uwsgi_foreach ( usl , uphp . exec_after ) {
 if ( zend_eval_string_ex ( usl -> value , NULL , "uWSGI php exec after" , 1 TSRMLS_CC ) == FAILURE ) goto end ;
 }
 end : php_request_shutdown ( NULL ) ;
 return 0 ;
 }


xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
    xmlChar *name;
    const xmlChar *ptr;
    xmlChar cur;
    xmlEntityPtr ent = NULL;

    if ((str == NULL) || (*str == NULL))
        return(NULL);
    ptr = *str;
    cur = *ptr;
    if (cur != '&')
	return(NULL);

    ptr++;
    name = xmlParseStringName(ctxt, &ptr);
    if (name == NULL) {
	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
		       "xmlParseStringEntityRef: no name\n");
	*str = ptr;
	return(NULL);
    }
    if (*ptr != ';') {
	xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
        xmlFree(name);
	*str = ptr;
	return(NULL);
    }
    ptr++;

    /*
     * Predefined entites override any extra definition
     */
    if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
        ent = xmlGetPredefinedEntity(name);
        if (ent != NULL) {
            xmlFree(name);
            *str = ptr;
            return(ent);
        }
    }

    /*
     * Increate the number of entity references parsed
     */
    ctxt->nbentities++;

    /*
     * Ask first SAX for entity resolution, otherwise try the
     * entities which may have stored in the parser context.
     */
    if (ctxt->sax != NULL) {
	if (ctxt->sax->getEntity != NULL)
	    ent = ctxt->sax->getEntity(ctxt->userData, name);
	if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX))
	    ent = xmlGetPredefinedEntity(name);
	if ((ent == NULL) && (ctxt->userData==ctxt)) {
 	    ent = xmlSAX2GetEntity(ctxt, name);
 	}
     }
    if (ctxt->instate == XML_PARSER_EOF) {
	xmlFree(name);
	return(NULL);
    }

     /*
      * [ WFC: Entity Declared ]
     * In a document without any DTD, a document with only an
     * internal DTD subset which contains no parameter entity
     * references, or a document with "standalone='yes'", the
     * Name given in the entity reference must match that in an
     * entity declaration, except that well-formed documents
     * need not declare any of the following entities: amp, lt,
     * gt, apos, quot.
     * The declaration of a parameter entity must precede any
     * reference to it.
     * Similarly, the declaration of a general entity must
     * precede any reference to it which appears in a default
     * value in an attribute-list declaration. Note that if
     * entities are declared in the external subset or in
     * external parameter entities, a non-validating processor
     * is not obligated to read and process their declarations;
     * for such documents, the rule that an entity must be
     * declared is a well-formedness constraint only if
     * standalone='yes'.
     */
    if (ent == NULL) {
	if ((ctxt->standalone == 1) ||
	    ((ctxt->hasExternalSubset == 0) &&
	     (ctxt->hasPErefs == 0))) {
	    xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
		     "Entity '%s' not defined\n", name);
	} else {
	    xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
			  "Entity '%s' not defined\n",
			  name);
	}
	/* TODO ? check regressions ctxt->valid = 0; */
    }

    /*
     * [ WFC: Parsed Entity ]
     * An entity reference must not contain the name of an
     * unparsed entity
     */
    else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
	xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
		 "Entity reference to unparsed entity %s\n", name);
    }

    /*
     * [ WFC: No External Entity References ]
     * Attribute values cannot contain direct or indirect
     * entity references to external entities.
     */
    else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
	     (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
	xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
	 "Attribute references external entity '%s'\n", name);
    }
    /*
     * [ WFC: No < in Attribute Values ]
     * The replacement text of any entity referred to directly or
     * indirectly in an attribute value (other than "<") must
     * not contain a <.
     */
    else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
	     (ent != NULL) && (ent->content != NULL) &&
	     (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
	     (xmlStrchr(ent->content, '<'))) {
	xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
     "'<' in entity '%s' is not allowed in attributes values\n",
			  name);
    }

    /*
     * Internal check, no parameter entities here ...
     */
    else {
	switch (ent->etype) {
	    case XML_INTERNAL_PARAMETER_ENTITY:
	    case XML_EXTERNAL_PARAMETER_ENTITY:
		xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
	     "Attempt to reference the parameter entity '%s'\n",
				  name);
	    break;
	    default:
	    break;
	}
    }

    /*
     * [ WFC: No Recursion ]
     * A parsed entity must not contain a recursive reference
     * to itself, either directly or indirectly.
     * Done somewhere else
     */

    xmlFree(name);
    *str = ptr;
    return(ent);
}


gpc_b16c(Pixel *out, const Pixel *in, const Background *back)
{
 if (in->a <= 0)
 {
      out->r = back->ir;
      out->g = back->ig;
      out->b = back->ib;
 }

 else
 {
 double a = in->a/65535.;
 double a1 = 1-a;

      a /= 65535;
      out->r = sRGB(in->r * a + back->dr * a1);
      out->g = sRGB(in->g * a + back->dg * a1);
      out->b = sRGB(in->b * a + back->db * a1);
 }

   out->a = 255;
}


bool jswrap_graphics_idle() {
  graphicsIdle();
  return false;
}


static inline void report_user_fault(struct pt_regs *regs, long int_code,
				     int signr, unsigned long address)
{
	if ((task_pid_nr(current) > 1) && !show_unhandled_signals)
		return;
	if (!unhandled_signal(current, signr))
		return;
	if (!printk_ratelimit())
		return;
	printk("User process fault: interruption code 0x%lX ", int_code);
	print_vma_addr(KERN_CONT "in ", regs->psw.addr & PSW_ADDR_INSN);
	printk("\n");
	printk("failing address: %lX\n", address);
	show_regs(regs);
}


png_crc_finish(png_structp png_ptr, png_uint_32 skip)
{
   png_size_t i;
   png_size_t istop = png_ptr->zbuf_size;

   for (i = (png_size_t)skip; i > istop; i -= istop)
   {
      png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
   }
   if (i)
   {
      png_crc_read(png_ptr, png_ptr->zbuf, i);
   }

   if (png_crc_error(png_ptr))
   {
      if (((png_ptr->chunk_name[0] & 0x20) &&                /* Ancillary */
          !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
          (!(png_ptr->chunk_name[0] & 0x20) &&             /* Critical  */
          (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
      {
         png_chunk_warning(png_ptr, "CRC error");
      }
      else
      {
         png_chunk_error(png_ptr, "CRC error");
      }
      return (1);
   }

   return (0);
}