do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
    int swap, uint32_t namesz, uint32_t descsz,
    size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
	int os_style = -1;
	/*
	 * Sigh.  The 2.0.36 kernel in Debian 2.1, at
	 * least, doesn't correctly implement name
	 * sections, in core dumps, as specified by
	 * the "Program Linking" section of "UNIX(R) System
	 * V Release 4 Programmer's Guide: ANSI C and
	 * Programming Support Tools", because my copy
	 * clearly says "The first 'namesz' bytes in 'name'
	 * contain a *null-terminated* [emphasis mine]
	 * character representation of the entry's owner
	 * or originator", but the 2.0.36 kernel code
	 * doesn't include the terminating null in the
	 * name....
	 */
	if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
	    (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
		os_style = OS_STYLE_SVR4;
	}

	if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
		os_style = OS_STYLE_FREEBSD;
	}

	if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
	    == 0)) {
		os_style = OS_STYLE_NETBSD;
	}

	if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
		if (file_printf(ms, ", %s-style", os_style_names[os_style])
		    == -1)
			return 1;
		*flags |= FLAGS_DID_CORE_STYLE;
		*flags |= os_style;
	}

	switch (os_style) {
	case OS_STYLE_NETBSD:
		if (type == NT_NETBSD_CORE_PROCINFO) {
			char sbuf[512];
			struct NetBSD_elfcore_procinfo pi;
			memset(&pi, 0, sizeof(pi));
			memcpy(&pi, nbuf + doff, descsz);

			if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
			    "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
			    file_printable(sbuf, sizeof(sbuf),
			    CAST(char *, pi.cpi_name)),
			    elf_getu32(swap, (uint32_t)pi.cpi_pid),
			    elf_getu32(swap, pi.cpi_euid),
			    elf_getu32(swap, pi.cpi_egid),
			    elf_getu32(swap, pi.cpi_nlwps),
			    elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
			    elf_getu32(swap, pi.cpi_signo),
			    elf_getu32(swap, pi.cpi_sigcode)) == -1)
				return 1;

			*flags |= FLAGS_DID_CORE;
			return 1;
		}
		break;

	default:
		if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
			size_t i, j;
			unsigned char c;
			/*
			 * Extract the program name.  We assume
			 * it to be 16 characters (that's what it
			 * is in SunOS 5.x and Linux).
			 *
			 * Unfortunately, it's at a different offset
			 * in various OSes, so try multiple offsets.
			 * If the characters aren't all printable,
			 * reject it.
			 */
			for (i = 0; i < NOFFSETS; i++) {
				unsigned char *cname, *cp;
				size_t reloffset = prpsoffsets(i);
				size_t noffset = doff + reloffset;
				size_t k;
				for (j = 0; j < 16; j++, noffset++,
				    reloffset++) {
					/*
					 * Make sure we're not past
					 * the end of the buffer; if
					 * we are, just give up.
					 */
					if (noffset >= size)
						goto tryanother;

					/*
					 * Make sure we're not past
					 * the end of the contents;
					 * if we are, this obviously
					 * isn't the right offset.
					 */
					if (reloffset >= descsz)
						goto tryanother;

					c = nbuf[noffset];
					if (c == '\0') {
						/*
						 * A '\0' at the
						 * beginning is
						 * obviously wrong.
						 * Any other '\0'
						 * means we're done.
						 */
						if (j == 0)
							goto tryanother;
						else
							break;
					} else {
						/*
						 * A nonprintable
						 * character is also
						 * wrong.
						 */
						if (!isprint(c) || isquote(c))
							goto tryanother;
					}
				}
				/*
				 * Well, that worked.
				 */

				/*
				 * Try next offsets, in case this match is
				 * in the middle of a string.
				 */
				for (k = i + 1 ; k < NOFFSETS; k++) {
					size_t no;
					int adjust = 1;
					if (prpsoffsets(k) >= prpsoffsets(i))
						continue;
					for (no = doff + prpsoffsets(k);
					     no < doff + prpsoffsets(i); no++)
						adjust = adjust
						         && isprint(nbuf[no]);
					if (adjust)
						i = k;
				}

				cname = (unsigned char *)
				    &nbuf[doff + prpsoffsets(i)];
				for (cp = cname; cp < nbuf + size && *cp
				    && isprint(*cp); cp++)
					continue;
				/*
				 * Linux apparently appends a space at the end
				 * of the command line: remove it.
				 */
				while (cp > cname && isspace(cp[-1]))
					cp--;
				if (file_printf(ms, ", from '%.*s'",
				    (int)(cp - cname), cname) == -1)
					return 1;
				*flags |= FLAGS_DID_CORE;
				return 1;

			tryanother:
				;
			}
		}
		break;
	}
#endif
	return 0;
}


 */
u16 __skb_tx_hash(const struct net_device *dev, struct sk_buff *skb,
		  unsigned int num_tx_queues)
{
	u32 hash;
	u16 qoffset = 0;
	u16 qcount = num_tx_queues;

	if (skb_rx_queue_recorded(skb)) {
		hash = skb_get_rx_queue(skb);
		while (unlikely(hash >= num_tx_queues))
			hash -= num_tx_queues;
		return hash;
	}

	if (dev->num_tc) {
		u8 tc = netdev_get_prio_tc_map(dev, skb->priority);

		qoffset = dev->tc_to_txq[tc].offset;
		qcount = dev->tc_to_txq[tc].count;
	}

	return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;


void SSLManager::DidStartResourceResponse(ResourceRequestDetails* details) {
  scoped_refptr<SSLRequestInfo> info(new SSLRequestInfo(
      details->url,
      details->resource_type,
      details->origin_child_id,
      details->ssl_cert_id,
      details->ssl_cert_status));

  policy()->OnRequestStarted(info.get());
}


int ssl3_read_n(SSL *s, int n, int max, int extend)
	{
	/* If extend == 0, obtain new n-byte packet; if extend == 1, increase
	 * packet by another n bytes.
	 * The packet will be in the sub-array of s->s3->rbuf.buf specified
	 * by s->packet and s->packet_length.
	 * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
	 * [plus s->packet_length bytes if extend == 1].)
	 */
	int i,len,left;
	long align=0;
	unsigned char *pkt;
	SSL3_BUFFER *rb;

	if (n <= 0) return n;

	rb    = &(s->s3->rbuf);
	if (rb->buf == NULL)
		if (!ssl3_setup_read_buffer(s))
			return -1;

	left  = rb->left;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
	align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
	align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
#endif

	if (!extend)
		{
		/* start with empty packet ... */
		if (left == 0)
			rb->offset = align;
		else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
			{
			/* check if next packet length is large
			 * enough to justify payload alignment... */
			pkt = rb->buf + rb->offset;
			if (pkt[0] == SSL3_RT_APPLICATION_DATA
			    && (pkt[3]<<8|pkt[4]) >= 128)
				{
				/* Note that even if packet is corrupted
				 * and its length field is insane, we can
				 * only be led to wrong decision about
				 * whether memmove will occur or not.
				 * Header values has no effect on memmove
				 * arguments and therefore no buffer
				 * overrun can be triggered. */
				memmove (rb->buf+align,pkt,left);
				rb->offset = align;
				}
			}
		s->packet = rb->buf + rb->offset;
		s->packet_length = 0;
		/* ... now we can act as if 'extend' was set */
		}

	/* For DTLS/UDP reads should not span multiple packets
	 * because the read operation returns the whole packet
	 * at once (as long as it fits into the buffer). */
	if (SSL_IS_DTLS(s))
		{
		if (left > 0 && n > left)
			n = left;
		}

	/* if there is enough in the buffer from a previous read, take some */
	if (left >= n)
		{
		s->packet_length+=n;
		rb->left=left-n;
		rb->offset+=n;
		return(n);
		}

	/* else we need to read more data */

	len = s->packet_length;
	pkt = rb->buf+align;
	/* Move any available bytes to front of buffer:
	 * 'len' bytes already pointed to by 'packet',
	 * 'left' extra ones at the end */
	if (s->packet != pkt) /* len > 0 */
		{
		memmove(pkt, s->packet, len+left);
		s->packet = pkt;
		rb->offset = len + align;
		}

	if (n > (int)(rb->len - rb->offset)) /* does not happen */
		{
		SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
		return -1;
		}

	if (!s->read_ahead)
		/* ignore max parameter */
		max = n;
	else
		{
		if (max < n)
			max = n;
		if (max > (int)(rb->len - rb->offset))
			max = rb->len - rb->offset;
		}

	while (left < n)
		{
		/* Now we have len+left bytes at the front of s->s3->rbuf.buf
		 * and need to read in more until we have len+n (up to
		 * len+max if possible) */

		clear_sys_error();
		if (s->rbio != NULL)
			{
			s->rwstate=SSL_READING;
			i=BIO_read(s->rbio,pkt+len+left, max-left);
			}
		else
			{
			SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
			i = -1;
			}

		if (i <= 0)
			{
			rb->left = left;
			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
				!SSL_IS_DTLS(s))
				if (len+left == 0)
					ssl3_release_read_buffer(s);
			return(i);
			}
		left+=i;
		/* reads should *never* span multiple packets for DTLS because
		 * the underlying transport protocol is message oriented as opposed
		 * to byte oriented as in the TLS case. */
		if (SSL_IS_DTLS(s))
			{
			if (n > left)
				n = left; /* makes the while condition false */
			}
		}

	/* done reading, now the book-keeping */
	rb->offset += n;
	rb->left = left - n;
	s->packet_length += n;
	s->rwstate=SSL_NOTHING;
	return(n);
	}


 xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp,
	          xmlNodePtr node, const xmlChar *mode,
 		  const xmlChar *modeURI) {
     int i;
     xsltStepOpPtr step, sel = NULL;
     xsltStepStates states = {0, 0, NULL}; /* // may require backtrack */

    if ((comp == NULL) || (node == NULL) || (ctxt == NULL)) {
	xsltTransformError(ctxt, NULL, node,
		"xsltTestCompMatch: null arg\n");
        return(-1);
    }
    if (mode != NULL) {
	if (comp->mode == NULL)
	    return(0);
	/*
	 * both mode strings must be interned on the stylesheet dictionary
	 */
	if (comp->mode != mode)
	    return(0);
    } else {
	if (comp->mode != NULL)
	    return(0);
    }
    if (modeURI != NULL) {
	if (comp->modeURI == NULL)
	    return(0);
	/*
	 * both modeURI strings must be interned on the stylesheet dictionary
	 */
	if (comp->modeURI != modeURI)
	    return(0);
    } else {
	if (comp->modeURI != NULL)
	    return(0);
    }

    i = 0;
restart:
    for (;i < comp->nbStep;i++) {
	step = &comp->steps[i];
	if (step->op != XSLT_OP_PREDICATE)
	    sel = step;
	switch (step->op) {
            case XSLT_OP_END:
		goto found;
            case XSLT_OP_ROOT:
		if ((node->type == XML_DOCUMENT_NODE) ||
#ifdef LIBXML_DOCB_ENABLED
		    (node->type == XML_DOCB_DOCUMENT_NODE) ||
#endif
		    (node->type == XML_HTML_DOCUMENT_NODE))
		    continue;
		if ((node->type == XML_ELEMENT_NODE) && (node->name[0] == ' '))
		    continue;
		goto rollback;
            case XSLT_OP_ELEM:
		if (node->type != XML_ELEMENT_NODE)
		    goto rollback;
		if (step->value == NULL)
		    continue;
		if (step->value[0] != node->name[0])
		    goto rollback;
		if (!xmlStrEqual(step->value, node->name))
		    goto rollback;

		/* Namespace test */
		if (node->ns == NULL) {
		    if (step->value2 != NULL)
			goto rollback;
		} else if (node->ns->href != NULL) {
		    if (step->value2 == NULL)
			goto rollback;
		    if (!xmlStrEqual(step->value2, node->ns->href))
			goto rollback;
		}
		continue;
            case XSLT_OP_ATTR:
		if (node->type != XML_ATTRIBUTE_NODE)
		    goto rollback;
		if (step->value != NULL) {
		    if (step->value[0] != node->name[0])
			goto rollback;
		    if (!xmlStrEqual(step->value, node->name))
			goto rollback;
		}
		/* Namespace test */
		if (node->ns == NULL) {
		    if (step->value2 != NULL)
			goto rollback;
		} else if (step->value2 != NULL) {
		    if (!xmlStrEqual(step->value2, node->ns->href))
			goto rollback;
		}
		continue;
            case XSLT_OP_PARENT:
		if ((node->type == XML_DOCUMENT_NODE) ||
		    (node->type == XML_HTML_DOCUMENT_NODE) ||
#ifdef LIBXML_DOCB_ENABLED
		    (node->type == XML_DOCB_DOCUMENT_NODE) ||
#endif
		    (node->type == XML_NAMESPACE_DECL))
		    goto rollback;
		node = node->parent;
		if (node == NULL)
		    goto rollback;
		if (step->value == NULL)
		    continue;
		if (step->value[0] != node->name[0])
		    goto rollback;
		if (!xmlStrEqual(step->value, node->name))
		    goto rollback;
		/* Namespace test */
		if (node->ns == NULL) {
		    if (step->value2 != NULL)
			goto rollback;
		} else if (node->ns->href != NULL) {
		    if (step->value2 == NULL)
			goto rollback;
		    if (!xmlStrEqual(step->value2, node->ns->href))
			goto rollback;
		}
		continue;
            case XSLT_OP_ANCESTOR:
		/* TODO: implement coalescing of ANCESTOR/NODE ops */
		if (step->value == NULL) {
		    step = &comp->steps[i+1];
		    if (step->op == XSLT_OP_ROOT)
			goto found;
		    /* added NS, ID and KEY as a result of bug 168208 */
		    if ((step->op != XSLT_OP_ELEM) &&
			(step->op != XSLT_OP_ALL) &&
			(step->op != XSLT_OP_NS) &&
			(step->op != XSLT_OP_ID) &&
			(step->op != XSLT_OP_KEY))
			goto rollback;
		}
		if (node == NULL)
		    goto rollback;
		if ((node->type == XML_DOCUMENT_NODE) ||
		    (node->type == XML_HTML_DOCUMENT_NODE) ||
#ifdef LIBXML_DOCB_ENABLED
		    (node->type == XML_DOCB_DOCUMENT_NODE) ||
#endif
		    (node->type == XML_NAMESPACE_DECL))
		    goto rollback;
		node = node->parent;
		if ((step->op != XSLT_OP_ELEM) && step->op != XSLT_OP_ALL) {
		    xsltPatPushState(ctxt, &states, i, node);
		    continue;
		}
		i++;
		if (step->value == NULL) {
		    xsltPatPushState(ctxt, &states, i - 1, node);
		    continue;
		}
		while (node != NULL) {
		    if ((node->type == XML_ELEMENT_NODE) &&
			(step->value[0] == node->name[0]) &&
			(xmlStrEqual(step->value, node->name))) {
			/* Namespace test */
			if (node->ns == NULL) {
			    if (step->value2 == NULL)
				break;
			} else if (node->ns->href != NULL) {
			    if ((step->value2 != NULL) &&
			        (xmlStrEqual(step->value2, node->ns->href)))
				break;
			}
		    }
		    node = node->parent;
		}
		if (node == NULL)
		    goto rollback;
		xsltPatPushState(ctxt, &states, i - 1, node);
		continue;
            case XSLT_OP_ID: {
		/* TODO Handle IDs decently, must be done differently */
		xmlAttrPtr id;

		if (node->type != XML_ELEMENT_NODE)
		    goto rollback;

		id = xmlGetID(node->doc, step->value);
		if ((id == NULL) || (id->parent != node))
		    goto rollback;
		break;
	    }
            case XSLT_OP_KEY: {
		xmlNodeSetPtr list;
		int indx;

		list = xsltGetKey(ctxt, step->value,
			          step->value3, step->value2);
		if (list == NULL)
		    goto rollback;
		for (indx = 0;indx < list->nodeNr;indx++)
		    if (list->nodeTab[indx] == node)
			break;
		if (indx >= list->nodeNr)
		    goto rollback;
		break;
	    }
            case XSLT_OP_NS:
		if (node->type != XML_ELEMENT_NODE)
		    goto rollback;
		if (node->ns == NULL) {
		    if (step->value != NULL)
			goto rollback;
		} else if (node->ns->href != NULL) {
		    if (step->value == NULL)
			goto rollback;
		    if (!xmlStrEqual(step->value, node->ns->href))
			goto rollback;
		}
		break;
            case XSLT_OP_ALL:
		if (node->type != XML_ELEMENT_NODE)
 		    goto rollback;
 		break;
 	    case XSLT_OP_PREDICATE: {
		xmlNodePtr oldNode;
		xmlDocPtr doc;
		int oldCS, oldCP;
		int pos = 0, len = 0;
		int isRVT;
 		/*
		 * when there is cascading XSLT_OP_PREDICATE, then use a
 		 * direct computation approach. It's not done directly
 		 * at the beginning of the routine to filter out as much
 		 * as possible this costly computation.
		 */
		if (comp->direct) {
		    if (states.states != NULL) {
 			/* Free the rollback states */
 			xmlFree(states.states);
 		    }
		    return(xsltTestCompMatchDirect(ctxt, comp, node,
 						   comp->nsList, comp->nsNr));
 		}

		doc = node->doc;
		if (XSLT_IS_RES_TREE_FRAG(doc))
		    isRVT = 1;
		else
		    isRVT = 0;
		/*
		 * Depending on the last selection, one may need to
		 * recompute contextSize and proximityPosition.
		 */
		oldCS = ctxt->xpathCtxt->contextSize;
		oldCP = ctxt->xpathCtxt->proximityPosition;
		if ((sel != NULL) &&
		    (sel->op == XSLT_OP_ELEM) &&
		    (sel->value != NULL) &&
		    (node->type == XML_ELEMENT_NODE) &&
		    (node->parent != NULL)) {
		    xmlNodePtr previous;
		    int nocache = 0;
		    previous = (xmlNodePtr)
			XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr);
		    if ((previous != NULL) &&
			(previous->parent == node->parent)) {
			/*
			 * just walk back to adjust the index
			 */
			int indx = 0;
			xmlNodePtr sibling = node;
			while (sibling != NULL) {
			    if (sibling == previous)
				break;
			    if ((sibling->type == XML_ELEMENT_NODE) &&
				(previous->name != NULL) &&
				(sibling->name != NULL) &&
				(previous->name[0] == sibling->name[0]) &&
				(xmlStrEqual(previous->name, sibling->name)))
			    {
				if ((sel->value2 == NULL) ||
				    ((sibling->ns != NULL) &&
				     (xmlStrEqual(sel->value2,
						  sibling->ns->href))))
				    indx++;
			    }
			    sibling = sibling->prev;
			}
			if (sibling == NULL) {
			    /* hum going backward in document order ... */
			    indx = 0;
			    sibling = node;
			    while (sibling != NULL) {
				if (sibling == previous)
				    break;
				if ((sibling->type == XML_ELEMENT_NODE) &&
				    (previous->name != NULL) &&
				    (sibling->name != NULL) &&
				    (previous->name[0] == sibling->name[0]) &&
				    (xmlStrEqual(previous->name, sibling->name)))
				{
				    if ((sel->value2 == NULL) ||
					((sibling->ns != NULL) &&
					(xmlStrEqual(sel->value2,
					sibling->ns->href))))
				    {
					indx--;
				    }
				}
				sibling = sibling->next;
			    }
			}
			if (sibling != NULL) {
		            pos = XSLT_RUNTIME_EXTRA(ctxt,
                                sel->indexExtra, ival) + indx;
			    /*
			     * If the node is in a Value Tree we need to
			     * save len, but cannot cache the node!
			     * (bugs 153137 and 158840)
			     */
			    if (node->doc != NULL) {
				len = XSLT_RUNTIME_EXTRA(ctxt,
				        sel->lenExtra, ival);
				if (!isRVT) {
				    XSLT_RUNTIME_EXTRA(ctxt,
					sel->previousExtra, ptr) = node;
				    XSLT_RUNTIME_EXTRA(ctxt,
				        sel->indexExtra, ival) = pos;
				}
			    }
			} else
			    pos = 0;
		    } else {
			/*
			 * recompute the index
			 */
			xmlNodePtr parent = node->parent;
			xmlNodePtr siblings = NULL;
                        if (parent) siblings = parent->children;
			while (siblings != NULL) {
			    if (siblings->type == XML_ELEMENT_NODE) {
				if (siblings == node) {
				    len++;
				    pos = len;
				} else if ((node->name != NULL) &&
					   (siblings->name != NULL) &&
				    (node->name[0] == siblings->name[0]) &&
				    (xmlStrEqual(node->name, siblings->name))) {
				    if ((sel->value2 == NULL) ||
					((siblings->ns != NULL) &&
					 (xmlStrEqual(sel->value2,
						      siblings->ns->href))))
					len++;
				}
			    }
			    siblings = siblings->next;
			}
			if ((parent == NULL) || (node->doc == NULL))
			    nocache = 1;
			else {
			    while (parent->parent != NULL)
				parent = parent->parent;
			    if (((parent->type != XML_DOCUMENT_NODE) &&
				 (parent->type != XML_HTML_DOCUMENT_NODE)) ||
				 (parent != (xmlNodePtr) node->doc))
				nocache = 1;
			}
		    }
		    if (pos != 0) {
			ctxt->xpathCtxt->contextSize = len;
			ctxt->xpathCtxt->proximityPosition = pos;
			/*
			 * If the node is in a Value Tree we cannot
			 * cache it !
			 */
			if ((!isRVT) && (node->doc != NULL) &&
			    (nocache == 0)) {
			    XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) =
				node;
			    XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) =
				pos;
			    XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) =
				len;
			}
		    }
		} else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) &&
			   (node->type == XML_ELEMENT_NODE)) {
		    xmlNodePtr previous;
		    int nocache = 0;
		    previous = (xmlNodePtr)
			XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr);
		    if ((previous != NULL) &&
			(previous->parent == node->parent)) {
			/*
			 * just walk back to adjust the index
			 */
			int indx = 0;
			xmlNodePtr sibling = node;
			while (sibling != NULL) {
			    if (sibling == previous)
				break;
			    if (sibling->type == XML_ELEMENT_NODE)
				indx++;
			    sibling = sibling->prev;
			}
			if (sibling == NULL) {
			    /* hum going backward in document order ... */
			    indx = 0;
			    sibling = node;
			    while (sibling != NULL) {
				if (sibling == previous)
				    break;
				if (sibling->type == XML_ELEMENT_NODE)
				    indx--;
				sibling = sibling->next;
			    }
			}
			if (sibling != NULL) {
			    pos = XSLT_RUNTIME_EXTRA(ctxt,
                                sel->indexExtra, ival) + indx;
			    /*
			     * If the node is in a Value Tree we cannot
			     * cache it !
			     */
			    if ((node->doc != NULL) && !isRVT) {
				len = XSLT_RUNTIME_EXTRA(ctxt,
				        sel->lenExtra, ival);
				XSLT_RUNTIME_EXTRA(ctxt,
					sel->previousExtra, ptr) = node;
				XSLT_RUNTIME_EXTRA(ctxt,
					sel->indexExtra, ival) = pos;
			    }
			} else
			    pos = 0;
		    } else {
			/*
			 * recompute the index
			 */
			xmlNodePtr parent = node->parent;
			xmlNodePtr siblings = NULL;
                        if (parent) siblings = parent->children;
			while (siblings != NULL) {
			    if (siblings->type == XML_ELEMENT_NODE) {
				len++;
				if (siblings == node) {
				    pos = len;
				}
			    }
			    siblings = siblings->next;
			}
			if ((parent == NULL) || (node->doc == NULL))
			    nocache = 1;
			else {
			    while (parent->parent != NULL)
				parent = parent->parent;
			    if (((parent->type != XML_DOCUMENT_NODE) &&
				 (parent->type != XML_HTML_DOCUMENT_NODE)) ||
				 (parent != (xmlNodePtr) node->doc))
				nocache = 1;
			}
		    }
		    if (pos != 0) {
			ctxt->xpathCtxt->contextSize = len;
			ctxt->xpathCtxt->proximityPosition = pos;
			/*
			 * If the node is in a Value Tree we cannot
			 * cache it !
			 */
			if ((node->doc != NULL) && (nocache == 0) && !isRVT) {
			    XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) =
				node;
			    XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) =
				pos;
			    XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) =
				len;
			}
		    }
		}
		oldNode = ctxt->node;
		ctxt->node = node;
		if (step->value == NULL)
		    goto wrong_index;
		if (step->comp == NULL)
		    goto wrong_index;
		if (!xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList,
			                    comp->nsNr))
		    goto wrong_index;

		if (pos != 0) {
		    ctxt->xpathCtxt->contextSize = oldCS;
		    ctxt->xpathCtxt->proximityPosition = oldCP;
		}
		ctxt->node = oldNode;
 		break;
wrong_index:
		if (pos != 0) {
		    ctxt->xpathCtxt->contextSize = oldCS;
		    ctxt->xpathCtxt->proximityPosition = oldCP;
		}
		ctxt->node = oldNode;
		goto rollback;
 	    }
             case XSLT_OP_PI:
 		if (node->type != XML_PI_NODE)
		    goto rollback;
		if (step->value != NULL) {
		    if (!xmlStrEqual(step->value, node->name))
			goto rollback;
		}
		break;
            case XSLT_OP_COMMENT:
		if (node->type != XML_COMMENT_NODE)
		    goto rollback;
		break;
            case XSLT_OP_TEXT:
		if ((node->type != XML_TEXT_NODE) &&
		    (node->type != XML_CDATA_SECTION_NODE))
		    goto rollback;
		break;
            case XSLT_OP_NODE:
		switch (node->type) {
		    case XML_ELEMENT_NODE:
		    case XML_CDATA_SECTION_NODE:
		    case XML_PI_NODE:
		    case XML_COMMENT_NODE:
		    case XML_TEXT_NODE:
			break;
		    default:
			goto rollback;
		}
		break;
	}
    }
found:
    if (states.states != NULL) {
        /* Free the rollback states */
	xmlFree(states.states);
    }
    return(1);
rollback:
    /* got an error try to rollback */
    if (states.states == NULL)
	return(0);
    if (states.nbstates <= 0) {
	xmlFree(states.states);
	return(0);
    }
    states.nbstates--;
    i = states.states[states.nbstates].step;
    node = states.states[states.nbstates].node;
#if 0
    fprintf(stderr, "Pop: %d, %s\n", i, node->name);
#endif
    goto restart;
}


static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,

                                           struct msghdr *msgh)

{

    struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);

    abi_long msg_controllen;

    abi_ulong target_cmsg_addr;

    struct target_cmsghdr *target_cmsg, *target_cmsg_start;

    socklen_t space = 0;

    msg_controllen = tswapal(target_msgh->msg_controllen);

    if (msg_controllen < sizeof (struct target_cmsghdr))

        goto the_end;

    target_cmsg_addr = tswapal(target_msgh->msg_control);

    target_cmsg = lock_user(VERIFY_WRITE, target_cmsg_addr, msg_controllen, 0);

    target_cmsg_start = target_cmsg;

    if (!target_cmsg)

        return -TARGET_EFAULT;

    while (cmsg && target_cmsg) {

        void *data = CMSG_DATA(cmsg);

        void *target_data = TARGET_CMSG_DATA(target_cmsg);

        int len = cmsg->cmsg_len - CMSG_ALIGN(sizeof (struct cmsghdr));

        int tgt_len, tgt_space;

        /* We never copy a half-header but may copy half-data;

         * this is Linux's behaviour in put_cmsg(). Note that

         * truncation here is a guest problem (which we report

         * to the guest via the CTRUNC bit), unlike truncation

         * in target_to_host_cmsg, which is a QEMU bug.

         */

        if (msg_controllen < sizeof(struct cmsghdr)) {

            target_msgh->msg_flags |= tswap32(MSG_CTRUNC);

            break;

        }

        if (cmsg->cmsg_level == SOL_SOCKET) {

            target_cmsg->cmsg_level = tswap32(TARGET_SOL_SOCKET);

        } else {

            target_cmsg->cmsg_level = tswap32(cmsg->cmsg_level);

        }

        target_cmsg->cmsg_type = tswap32(cmsg->cmsg_type);

        tgt_len = TARGET_CMSG_LEN(len);

        /* Payload types which need a different size of payload on

         * the target must adjust tgt_len here.

         */

        switch (cmsg->cmsg_level) {

        case SOL_SOCKET:

            switch (cmsg->cmsg_type) {

            case SO_TIMESTAMP:

                tgt_len = sizeof(struct target_timeval);

                break;

            default:

                break;

            }

        default:

            break;

        }

        if (msg_controllen < tgt_len) {

            target_msgh->msg_flags |= tswap32(MSG_CTRUNC);

            tgt_len = msg_controllen;

        }

        /* We must now copy-and-convert len bytes of payload

         * into tgt_len bytes of destination space. Bear in mind

         * that in both source and destination we may be dealing

         * with a truncated value!

         */

        switch (cmsg->cmsg_level) {

        case SOL_SOCKET:

            switch (cmsg->cmsg_type) {

            case SCM_RIGHTS:

            {

                int *fd = (int *)data;

                int *target_fd = (int *)target_data;

                int i, numfds = tgt_len / sizeof(int);

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

                    __put_user(fd[i], target_fd + i);

                }

                break;

            }

            case SO_TIMESTAMP:

            {

                struct timeval *tv = (struct timeval *)data;

                struct target_timeval *target_tv =

                    (struct target_timeval *)target_data;

                if (len != sizeof(struct timeval) ||

                    tgt_len != sizeof(struct target_timeval)) {

                    goto unimplemented;

                }

                /* copy struct timeval to target */

                __put_user(tv->tv_sec, &target_tv->tv_sec);

                __put_user(tv->tv_usec, &target_tv->tv_usec);

                break;

            }

            case SCM_CREDENTIALS:

            {

                struct ucred *cred = (struct ucred *)data;

                struct target_ucred *target_cred =

                    (struct target_ucred *)target_data;

                __put_user(cred->pid, &target_cred->pid);

                __put_user(cred->uid, &target_cred->uid);

                __put_user(cred->gid, &target_cred->gid);

                break;

            }

            default:

                goto unimplemented;

            }

            break;

        case SOL_IP:

            switch (cmsg->cmsg_type) {

            case IP_TTL:

            {

                uint32_t *v = (uint32_t *)data;

                uint32_t *t_int = (uint32_t *)target_data;

                __put_user(*v, t_int);

                break;

            }

            case IP_RECVERR:

            {

                struct errhdr_t {

                   struct sock_extended_err ee;

                   struct sockaddr_in offender;

                };

                struct errhdr_t *errh = (struct errhdr_t *)data;

                struct errhdr_t *target_errh =

                    (struct errhdr_t *)target_data;

                __put_user(errh->ee.ee_errno, &target_errh->ee.ee_errno);

                __put_user(errh->ee.ee_origin, &target_errh->ee.ee_origin);

                __put_user(errh->ee.ee_type,  &target_errh->ee.ee_type);

                __put_user(errh->ee.ee_code, &target_errh->ee.ee_code);

                __put_user(errh->ee.ee_pad, &target_errh->ee.ee_pad);

                __put_user(errh->ee.ee_info, &target_errh->ee.ee_info);

                __put_user(errh->ee.ee_data, &target_errh->ee.ee_data);

                host_to_target_sockaddr((unsigned long) &target_errh->offender,

                    (void *) &errh->offender, sizeof(errh->offender));

                break;

            }

            default:

                goto unimplemented;

            }

            break;

        case SOL_IPV6:

            switch (cmsg->cmsg_type) {

            case IPV6_HOPLIMIT:

            {

                uint32_t *v = (uint32_t *)data;

                uint32_t *t_int = (uint32_t *)target_data;

                __put_user(*v, t_int);

                break;

            }

            case IPV6_RECVERR:

            {

                struct errhdr6_t {

                   struct sock_extended_err ee;

                   struct sockaddr_in6 offender;

                };

                struct errhdr6_t *errh = (struct errhdr6_t *)data;

                struct errhdr6_t *target_errh =

                    (struct errhdr6_t *)target_data;

                __put_user(errh->ee.ee_errno, &target_errh->ee.ee_errno);

                __put_user(errh->ee.ee_origin, &target_errh->ee.ee_origin);

                __put_user(errh->ee.ee_type,  &target_errh->ee.ee_type);

                __put_user(errh->ee.ee_code, &target_errh->ee.ee_code);

                __put_user(errh->ee.ee_pad, &target_errh->ee.ee_pad);

                __put_user(errh->ee.ee_info, &target_errh->ee.ee_info);

                __put_user(errh->ee.ee_data, &target_errh->ee.ee_data);

                host_to_target_sockaddr((unsigned long) &target_errh->offender,

                    (void *) &errh->offender, sizeof(errh->offender));

                break;

            }

            default:

                goto unimplemented;

            }

            break;

        default:

        unimplemented:

            gemu_log("Unsupported ancillary data: %d/%d\n",

                                        cmsg->cmsg_level, cmsg->cmsg_type);

            memcpy(target_data, data, MIN(len, tgt_len));

            if (tgt_len > len) {

                memset(target_data + len, 0, tgt_len - len);

            }

        }

        target_cmsg->cmsg_len = tswapal(tgt_len);

        tgt_space = TARGET_CMSG_SPACE(len);

        if (msg_controllen < tgt_space) {

            tgt_space = msg_controllen;

        }

        msg_controllen -= tgt_space;

        space += tgt_space;

        cmsg = CMSG_NXTHDR(msgh, cmsg);

        target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg,

                                         target_cmsg_start);

    }

    unlock_user(target_cmsg, target_cmsg_addr, space);

 the_end:

    target_msgh->msg_controllen = tswapal(space);

    return 0;

}


static int sched_rt_global_validate(void)
{
	if (sysctl_sched_rt_period <= 0)
		return -EINVAL;

	if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
		(sysctl_sched_rt_runtime > sysctl_sched_rt_period))
		return -EINVAL;

	return 0;
}


  CephXTicketHandler(CephContext *cct_, uint32_t service_id_)
    : service_id(service_id_), have_key_flag(false), cct(cct_) { }


uint32_t StreamEncoderImpl::bufferLimit() { return connection_.bufferLimit(); }


void SavePackage::SaveFinished(int32 save_id, int64 size, bool is_success) {
  SaveItem* save_item = LookupItemInProcessBySaveId(save_id);
  if (!save_item)
    return;

  save_item->Finish(size, is_success);
  file_manager_->RemoveSaveFile(save_id, save_item->url(), this);

  PutInProgressItemToSavedMap(save_item);

  if (download_ && download_->IsInProgress())
    download_->UpdateProgress(completed_count(), CurrentSpeed(), "");

  if (save_item->save_source() == SaveFileCreateInfo::SAVE_FILE_FROM_DOM &&
      save_item->url() == page_url_ && !save_item->received_bytes()) {
    Cancel(false);
    return;
  }

  if (canceled()) {
    DCHECK(finished_);
    return;
  }

  DoSavingProcess();

  CheckFinish();
}


struct minidump_memory_info *r_bin_mdmp_get_mem_info(struct r_bin_mdmp_obj *obj, ut64 vaddr) {
	struct minidump_memory_info *mem_info;
	RListIter *it;

	if (!obj) return NULL;

	r_list_foreach (obj->streams.memory_infos, it, mem_info) {
		if (mem_info->allocation_base && vaddr == mem_info->base_address) {
			return mem_info;
		}
	}

	return NULL;
}


u32 parse_split(char *arg_val, u32 opt)
{
	switch (opt) {
	case 0://-split
		split_duration = atof(arg_val);
		if (split_duration < 0) split_duration = 0;
		split_size = 0;
		break;
	case 1: //-split-rap, -splitr
		split_duration = -1;
		split_size = -1;
		break;
	case 2: //-split-size, -splits
		split_size = (u32)atoi(arg_val);
		split_duration = 0;
		break;
	case 3: //-split-chunk, -splitx
	case 4: //-splitz
	case 5: //-splitg
	case 6: //-splitf
		adjust_split_end = opt-3;
		if (!strstr(arg_val, ":") && !strstr(arg_val, "-")) {
			M4_LOG(GF_LOG_ERROR, ("Chunk extraction usage: \"-split* start:end\" expressed in seconds\n"));
			return 2;
		}
		if (strstr(arg_val, "end")) {
			if (strstr(arg_val, "end-")) {
				Double dur_end=0;
				sscanf(arg_val, "%lf:end-%lf", &split_start, &dur_end);
				split_duration = -2 - dur_end;
			} else {
				sscanf(arg_val, "%lf:end", &split_start);
				split_duration = -2;
			}
		} else {
			split_range_str = arg_val;
		}
		split_size = 0;
		break;
	}
	return 0;
}


static void setup_modinfo(struct module *mod, struct load_info *info)
{
	struct module_attribute *attr;
	int i;

	for (i = 0; (attr = modinfo_attrs[i]); i++) {
		if (attr->setup)
			attr->setup(mod, get_modinfo(info, attr->attr.name));
	}
}


void PrepareDragForFileContents(const DropData& drop_data,
                                ui::OSExchangeData::Provider* provider) {
  base::FilePath file_name(drop_data.file_description_filename);
  if (file_name.BaseName().RemoveExtension().empty()) {
    const base::string16 extension = file_name.Extension();
    file_name = base::FilePath(net::GetSuggestedFilename(
        drop_data.url, "", "", "", "", "")).ReplaceExtension(extension);
  }
  provider->SetFileContents(file_name, drop_data.file_contents);
}


static void ar6000_target_failure(void *Instance, int Status)
{
    struct ar6_softc *ar = (struct ar6_softc *)Instance;
    WMI_TARGET_ERROR_REPORT_EVENT errEvent;
    static bool sip = false;

    if (Status != 0) {

        printk(KERN_ERR "ar6000_target_failure: target asserted \n");

        if (timer_pending(&ar->arHBChallengeResp.timer)) {
            A_UNTIMEOUT(&ar->arHBChallengeResp.timer);
        }

        /* try dumping target assertion information (if any) */
        ar6000_dump_target_assert_info(ar->arHifDevice,ar->arTargetType);

        /*
         * Fetch the logs from the target via the diagnostic
         * window.
         */
        ar6000_dbglog_get_debug_logs(ar);

        /* Report the error only once */
        if (!sip) {
            sip = true;
            errEvent.errorVal = WMI_TARGET_COM_ERR |
                                WMI_TARGET_FATAL_ERR;
        }
    }
}


static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
{
	scrub_pause_on(fs_info);
	scrub_pause_off(fs_info);
}


stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
{
   unsigned int len, start;
   start = (unsigned int) ftell(file);
   fseek(file, 0, SEEK_END);
   len = (unsigned int) (ftell(file) - start);
   fseek(file, start, SEEK_SET);
   return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
}


SPL_METHOD(Array, offsetGet)
{
	zval *index, *value;
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
		return;
	}
	value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC);
	RETURN_ZVAL(value, 1, 0);
} /* }}} */


ObjectData::~ObjectData() {
  if (UNLIKELY(slowDestroyCheck())) {
    // The only builtin classes that use ~ObjectData and support memoization
    // are ones with native data, and the memo slot cleanup for them happens
    // in nativeDataInstanceDtor.
    assertx(!getAttribute(UsedMemoCache) || hasNativeData());
    if (getAttribute(HasDynPropArr)) freeDynPropArray(this);
    if (getAttribute(IsWeakRefed)) {
      WeakRefData::invalidateWeakRef((uintptr_t)this);
    }
  }
}


bool SessionModelAssociator::UpdateAssociationsFromSyncModel(
    const sync_api::ReadNode& root,
    const sync_api::BaseTransaction* trans) {
  DCHECK(CalledOnValidThread());

  int64 id = root.GetFirstChildId();
  while (id != sync_api::kInvalidId) {
    sync_api::ReadNode sync_node(trans);
    if (!sync_node.InitByIdLookup(id)) {
      LOG(ERROR) << "Failed to fetch sync node for id " << id;
      return false;
    }

     const sync_pb::SessionSpecifics& specifics =
         sync_node.GetSessionSpecifics();
    const base::Time& modification_time = sync_node.GetModificationTime();
     if (specifics.session_tag() != GetCurrentMachineTag()) {
       if (!AssociateForeignSpecifics(specifics, modification_time)) {
         return false;
      }
    } else if (id != local_session_syncid_) {
      if (specifics.has_header()) {
        if (sync_api::kInvalidId != local_session_syncid_)
          return false;

        local_session_syncid_ = id;
        if (specifics.header().has_client_name()) {
          current_session_name_ = specifics.header().client_name();
        }
      } else {
        if (!specifics.has_tab())
          return false;

        tab_pool_.AddTabNode(id);
      }
    }

    id = sync_node.GetSuccessorId();
  }

  if (!tab_pool_.full())
    return false;

  return true;
}


static qboolean CGVMLoaded( void ) { return (qboolean)cls.cgameStarted; }


irc_mode_get_arguments (const char *arguments)
{
    char **argv, **argv2, *new_arguments;
    int argc, i;

    if (!arguments || !arguments[0])
        return strdup ("");

    argv = weechat_string_split (arguments, " ", NULL,
                                 WEECHAT_STRING_SPLIT_STRIP_LEFT
                                 | WEECHAT_STRING_SPLIT_STRIP_RIGHT
                                 | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS,
                                 0, &argc);
    if (!argv)
        return strdup ("");

    argv2 = malloc (sizeof (*argv) * (argc + 1));
    if (!argv2)
    {
        weechat_string_free_split (argv);
        return strdup ("");;
    }

    for (i = 0; i < argc; i++)
    {
        argv2[i] = (argv[i][0] == ':') ? argv[i] + 1 : argv[i];
    }
    argv2[argc] = NULL;

    new_arguments = weechat_string_build_with_split_string (
        (const char **)argv2, " ");

    weechat_string_free_split (argv);
    free (argv2);

    return new_arguments;
}


void HTMLFormElement::CopyNonAttributePropertiesFromElement(
    const Element& source) {
  was_demoted_ = static_cast<const HTMLFormElement&>(source).was_demoted_;
  HTMLElement::CopyNonAttributePropertiesFromElement(source);
}


void PresentationConnection::send(DOMArrayBufferView* arrayBufferView,
                                  ExceptionState& exceptionState) {
  ASSERT(arrayBufferView);
  if (!canSendMessage(exceptionState))
    return;

  m_messages.append(new Message(arrayBufferView->buffer()));
  handleMessageQueue();
}


static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData,
                                   OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
    OPJ_UINT32 x, y, written;
    OPJ_UINT8 *pix;
    const OPJ_UINT8 *beyond;

    beyond = pData + stride * height;
    pix = pData;

    x = y = written = 0U;
    while (y < height) {
        int c = getc(IN);
        if (c == EOF) {
            return OPJ_FALSE;
        }

        if (c) {
            int j, c1_int;
            OPJ_UINT8 c1;

            c1_int = getc(IN);
            if (c1_int == EOF) {
                return OPJ_FALSE;
            }
            c1 = (OPJ_UINT8)c1_int;

            for (j = 0; (j < c) && (x < width) &&
                    ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
                *pix = c1;
                written++;
            }
        } else {
            c = getc(IN);
            if (c == EOF) {
                return OPJ_FALSE;
            }

            if (c == 0x00) { /* EOL */
                x = 0;
                ++y;
                pix = pData + y * stride + x;
            } else if (c == 0x01) { /* EOP */
                break;
            } else if (c == 0x02) { /* MOVE by dxdy */
                c = getc(IN);
                if (c == EOF) {
                    return OPJ_FALSE;
                }
                x += (OPJ_UINT32)c;
                c = getc(IN);
                if (c == EOF) {
                    return OPJ_FALSE;
                }
                y += (OPJ_UINT32)c;
                pix = pData + y * stride + x;
            } else { /* 03 .. 255 */
                int j;
                for (j = 0; (j < c) && (x < width) &&
                        ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
                    int c1_int;
                    OPJ_UINT8 c1;
                    c1_int = getc(IN);
                    if (c1_int == EOF) {
                        return OPJ_FALSE;
                    }
                    c1 = (OPJ_UINT8)c1_int;
                    *pix = c1;
                    written++;
                }
                if ((OPJ_UINT32)c & 1U) { /* skip padding byte */
                    c = getc(IN);
                    if (c == EOF) {
                        return OPJ_FALSE;
                    }
                }
            }
        }
    }/* while() */

    if (written != width * height) {
        fprintf(stderr, "warning, image's actual size does not match advertized one\n");
        return OPJ_FALSE;
    }

    return OPJ_TRUE;
}


static void inverse_transform_block ( MACROBLOCKD * xd , int plane , int block , TX_SIZE tx_size , uint8_t * dst , int stride , int eob ) {
 struct macroblockd_plane * const pd = & xd -> plane [ plane ] ;
 if ( eob > 0 ) {
 TX_TYPE tx_type = DCT_DCT ;
 int16_t * const dqcoeff = BLOCK_OFFSET ( pd -> dqcoeff , block ) ;
 if ( xd -> lossless ) {
 tx_type = DCT_DCT ;
 vp9_iwht4x4_add ( dqcoeff , dst , stride , eob ) ;
 }
 else {
 const PLANE_TYPE plane_type = pd -> plane_type ;
 switch ( tx_size ) {
 case TX_4X4 : tx_type = get_tx_type_4x4 ( plane_type , xd , block ) ;
 vp9_iht4x4_add ( tx_type , dqcoeff , dst , stride , eob ) ;
 break ;
 case TX_8X8 : tx_type = get_tx_type ( plane_type , xd ) ;
 vp9_iht8x8_add ( tx_type , dqcoeff , dst , stride , eob ) ;
 break ;
 case TX_16X16 : tx_type = get_tx_type ( plane_type , xd ) ;
 vp9_iht16x16_add ( tx_type , dqcoeff , dst , stride , eob ) ;
 break ;
 case TX_32X32 : tx_type = DCT_DCT ;
 vp9_idct32x32_add ( dqcoeff , dst , stride , eob ) ;
 break ;
 default : assert ( 0 && "Invalid transform size" ) ;
 }
 }
 if ( eob == 1 ) {
 vpx_memset ( dqcoeff , 0 , 2 * sizeof ( dqcoeff [ 0 ] ) ) ;
 }
 else {
 if ( tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10 ) vpx_memset ( dqcoeff , 0 , 4 * ( 4 << tx_size ) * sizeof ( dqcoeff [ 0 ] ) ) ;
 else if ( tx_size == TX_32X32 && eob <= 34 ) vpx_memset ( dqcoeff , 0 , 256 * sizeof ( dqcoeff [ 0 ] ) ) ;
 else vpx_memset ( dqcoeff , 0 , ( 16 << ( tx_size << 1 ) ) * sizeof ( dqcoeff [ 0 ] ) ) ;
 }
 }
 }


static int opverw(RAsm *a, ut8 *data, const Opcode *op) {
	int l = 0;
	switch (op->operands_count) {
	case 1:
		if ( op->operands[0].type & OT_WORD ) {
			data[l++] = 0x0f;
			data[l++] = 0x00;
			if ( op->operands[0].type & OT_MEMORY ) {
				data[l++] = 0x28 | op->operands[0].regs[0];
			} else {
				data[l++] = 0xe8 | op->operands[0].reg;
			}
		} else {
			return -1;
		}
		break;
	default:
		return -1;
	}
	return l;
}


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;
}


void mmput(struct mm_struct *mm)
{
	might_sleep();

	if (atomic_dec_and_test(&mm->mm_users)) {
		exit_aio(mm);
		ksm_exit(mm);
		exit_mmap(mm);
		set_mm_exe_file(mm, NULL);
		if (!list_empty(&mm->mmlist)) {
			spin_lock(&mmlist_lock);
			list_del(&mm->mmlist);
			spin_unlock(&mmlist_lock);
		}
		put_swap_token(mm);
		if (mm->binfmt)
			module_put(mm->binfmt->module);
		mmdrop(mm);
	}
}


static void fill_scaling_lists ( struct dxva_context * ctx , const H264Context * h , DXVA_Qmatrix_H264 * qm ) {
 unsigned i , j ;
 memset ( qm , 0 , sizeof ( * qm ) ) ;
 if ( ctx -> workaround & FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG ) {
 for ( i = 0 ;
 i < 6 ;
 i ++ ) for ( j = 0 ;
 j < 16 ;
 j ++ ) qm -> bScalingLists4x4 [ i ] [ j ] = h -> pps . scaling_matrix4 [ i ] [ j ] ;
 for ( i = 0 ;
 i < 64 ;
 i ++ ) {
 qm -> bScalingLists8x8 [ 0 ] [ i ] = h -> pps . scaling_matrix8 [ 0 ] [ i ] ;
 qm -> bScalingLists8x8 [ 1 ] [ i ] = h -> pps . scaling_matrix8 [ 3 ] [ i ] ;
 }
 }
 else {
 for ( i = 0 ;
 i < 6 ;
 i ++ ) for ( j = 0 ;
 j < 16 ;
 j ++ ) qm -> bScalingLists4x4 [ i ] [ j ] = h -> pps . scaling_matrix4 [ i ] [ zigzag_scan [ j ] ] ;
 for ( i = 0 ;
 i < 64 ;
 i ++ ) {
 qm -> bScalingLists8x8 [ 0 ] [ i ] = h -> pps . scaling_matrix8 [ 0 ] [ ff_zigzag_direct [ i ] ] ;
 qm -> bScalingLists8x8 [ 1 ] [ i ] = h -> pps . scaling_matrix8 [ 3 ] [ ff_zigzag_direct [ i ] ] ;
 }
 }
 }


bool ChromeMetricsServiceClient::IsReportingPolicyManaged() {
  return IsMetricsReportingPolicyManaged();
}


static void cal_nmvsadcosts ( int * mvsadcost [ 2 ] ) {
 int i = 1 ;
 mvsadcost [ 0 ] [ 0 ] = 0 ;
 mvsadcost [ 1 ] [ 0 ] = 0 ;
 do {
 double z = 256 * ( 2 * ( log2f ( 8 * i ) + .6 ) ) ;
 mvsadcost [ 0 ] [ i ] = ( int ) z ;
 mvsadcost [ 1 ] [ i ] = ( int ) z ;
 mvsadcost [ 0 ] [ - i ] = ( int ) z ;
 mvsadcost [ 1 ] [ - i ] = ( int ) z ;
 }
 while ( ++ i <= MV_MAX ) ;
 }


static noinline int btrfs_mksubvol(struct path *parent,
				   char *name, int namelen,
				   struct btrfs_root *snap_src,
				   u64 *async_transid, bool readonly,
				   struct btrfs_qgroup_inherit **inherit)
{
	struct inode *dir  = parent->dentry->d_inode;
	struct dentry *dentry;
	int error;

	mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);

	dentry = lookup_one_len(name, parent->dentry, namelen);
	error = PTR_ERR(dentry);
	if (IS_ERR(dentry))
		goto out_unlock;

	error = -EEXIST;
	if (dentry->d_inode)
		goto out_dput;

	error = btrfs_may_create(dir, dentry);
	if (error)
		goto out_dput;

	down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);

	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
		goto out_up_read;

	if (snap_src) {
		error = create_snapshot(snap_src, dentry, name, namelen,
					async_transid, readonly, inherit);
	} else {
		error = create_subvol(BTRFS_I(dir)->root, dentry,
				      name, namelen, async_transid, inherit);
	}
	if (!error)
		fsnotify_mkdir(dir, dentry);
out_up_read:
	up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
out_dput:
	dput(dentry);
out_unlock:
	mutex_unlock(&dir->i_mutex);
	return error;
}


static int check_empty_slot(struct module *module, int slot)
{
	return !slots[slot] || !*slots[slot];
}


void lcdInit_ArrayBuffer(JsGraphics *gfx) {
  // create buffer
  JsVar *buf = jswrap_arraybuffer_constructor(graphicsGetMemoryRequired(gfx));
  jsvUnLock2(jsvAddNamedChild(gfx->graphicsVar, buf, "buffer"), buf);
}


void Type_NamedColor_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
    cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr);
    return;

    cmsUNUSED_PARAMETER(self);
}


void GLES2DecoderImpl::DoCompileShader(GLuint client_id) {
  TRACE_EVENT0("gpu", "GLES2DecoderImpl::DoCompileShader");
  ShaderManager::ShaderInfo* info = GetShaderInfoNotProgram(
      client_id, "glCompileShader");
  if (!info) {
    return;
  }
  const char* shader_src = info->source() ? info->source()->c_str() : "";
  ShaderTranslator* translator = NULL;
  if (use_shader_translator_) {
    translator = info->shader_type() == GL_VERTEX_SHADER ?
        vertex_translator_.get() : fragment_translator_.get();

    if (!translator->Translate(shader_src)) {
      info->SetStatus(false, translator->info_log(), NULL);
      return;
    }
    shader_src = translator->translated_shader();
    if (!feature_info_->feature_flags().angle_translated_shader_source)
      info->UpdateTranslatedSource(shader_src);
  }

  glShaderSource(info->service_id(), 1, &shader_src, NULL);
  glCompileShader(info->service_id());
  if (feature_info_->feature_flags().angle_translated_shader_source) {
    GLint max_len = 0;
    glGetShaderiv(info->service_id(),
                  GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE,
                  &max_len);
    scoped_array<char> temp(new char[max_len]);
    GLint len = 0;
    glGetTranslatedShaderSourceANGLE(
        info->service_id(), max_len, &len, temp.get());
    DCHECK(max_len == 0 || len < max_len);
    DCHECK(len == 0 || temp[len] == '\0');
    info->UpdateTranslatedSource(temp.get());
  }

  GLint status = GL_FALSE;
  glGetShaderiv(info->service_id(),  GL_COMPILE_STATUS, &status);
  if (status) {
    info->SetStatus(true, "", translator);
  } else {
    LOG_IF(ERROR, use_shader_translator_)
        << "Shader translator allowed/produced an invalid shader.";
    GLint max_len = 0;
    glGetShaderiv(info->service_id(), GL_INFO_LOG_LENGTH, &max_len);
    scoped_array<char> temp(new char[max_len]);
    GLint len = 0;
    glGetShaderInfoLog(info->service_id(), max_len, &len, temp.get());
    DCHECK(max_len == 0 || len < max_len);
    DCHECK(len == 0 || temp[len] == '\0');
    info->SetStatus(false, std::string(temp.get(), len).c_str(), NULL);
  }
};


get_cert_location(TCHAR *path, DWORD *store_name, TCHAR **store_path,
                  TCHAR **thumbprint)
{
  TCHAR *sep;
  TCHAR *store_path_start;
  size_t store_name_len;

  sep = _tcschr(path, TEXT('\\'));
  if(!sep)
    return CURLE_SSL_CERTPROBLEM;

  store_name_len = sep - path;

  if(_tcsnccmp(path, TEXT("CurrentUser"), store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_CURRENT_USER;
  else if(_tcsnccmp(path, TEXT("LocalMachine"), store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE;
  else if(_tcsnccmp(path, TEXT("CurrentService"), store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_CURRENT_SERVICE;
  else if(_tcsnccmp(path, TEXT("Services"), store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_SERVICES;
  else if(_tcsnccmp(path, TEXT("Users"), store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_USERS;
  else if(_tcsnccmp(path, TEXT("CurrentUserGroupPolicy"),
                    store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY;
  else if(_tcsnccmp(path, TEXT("LocalMachineGroupPolicy"),
                    store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY;
  else if(_tcsnccmp(path, TEXT("LocalMachineEnterprise"),
                    store_name_len) == 0)
    *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE;
  else
    return CURLE_SSL_CERTPROBLEM;

  store_path_start = sep + 1;

  sep = _tcschr(store_path_start, TEXT('\\'));
  if(!sep)
    return CURLE_SSL_CERTPROBLEM;

  *thumbprint = sep + 1;
  if(_tcslen(*thumbprint) != CERT_THUMBPRINT_STR_LEN)
    return CURLE_SSL_CERTPROBLEM;

  *sep = TEXT('\0');
  *store_path = _tcsdup(store_path_start);
  *sep = TEXT('\\');
  if(!*store_path)
    return CURLE_OUT_OF_MEMORY;

  return CURLE_OK;
}


static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
                              MOVTrack *track, AVStream *st)
{
    int64_t pos = avio_tell(pb);
    int entry_backup = track->entry;
    int chunk_backup = track->chunkCount;
    int ret;

    /* If we want to have an empty moov, but some samples already have been
     * buffered (delay_moov), pretend that no samples have been written yet. */
    if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
        track->chunkCount = track->entry = 0;

    avio_wb32(pb, 0); /* size */
    ffio_wfourcc(pb, "trak");
    mov_write_tkhd_tag(pb, mov, track, st);

    av_assert2(mov->use_editlist >= 0);

    if (track->start_dts != AV_NOPTS_VALUE) {
        if (mov->use_editlist)
            mov_write_edts_tag(pb, mov, track);  // PSP Movies and several other cases require edts box
        else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
            av_log(mov->fc, AV_LOG_WARNING,
                   "Not writing any edit list even though one would have been required\n");
    }

    if (track->tref_tag)
        mov_write_tref_tag(pb, track);

    if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
        return ret;
    if (track->mode == MODE_PSP)
        mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
    if (track->tag == MKTAG('r','t','p',' '))
        mov_write_udta_sdp(pb, track);
    if (track->mode == MODE_MOV) {
        if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
            double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
            if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
                mov_write_tapt_tag(pb, track);
            }
        }
        if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
            mov_write_tapt_tag(pb, track);
        }
    }
    mov_write_track_udta_tag(pb, mov, st);
    track->entry = entry_backup;
    track->chunkCount = chunk_backup;
    return update_size(pb, pos);
}


static void calc_vol(unsigned char *regbyte, int volume, int main_vol)
{
	int level = (~*regbyte & 0x3f);

	if (main_vol > 127)
		main_vol = 127;
	volume = (volume * main_vol) / 127;

	if (level)
		level += fm_volume_table[volume];

	if (level > 0x3f)
		level = 0x3f;
	if (level < 0)
		level = 0;

	*regbyte = (*regbyte & 0xc0) | (~level & 0x3f);
}


static void init_vlcs(void)

{

    static int done = 0;

    if (!done) {

        done = 1;

        init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12,

                 vlc_dc_lum_bits, 1, 1,

                 vlc_dc_lum_code, 2, 2);

        init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12,

                 vlc_dc_chroma_bits, 1, 1,

                 vlc_dc_chroma_code, 2, 2);

        init_vlc(&mv_vlc, MV_VLC_BITS, 17,

                 &mbMotionVectorTable[0][1], 2, 1,

                 &mbMotionVectorTable[0][0], 2, 1);

        init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 36,

                 &mbAddrIncrTable[0][1], 2, 1,

                 &mbAddrIncrTable[0][0], 2, 1);

        init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 64,

                 &mbPatTable[0][1], 2, 1,

                 &mbPatTable[0][0], 2, 1);

        init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 7,

                 &table_mb_ptype[0][1], 2, 1,

                 &table_mb_ptype[0][0], 2, 1);

        init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11,

                 &table_mb_btype[0][1], 2, 1,

                 &table_mb_btype[0][0], 2, 1);

        init_rl(&rl_mpeg1);

        init_rl(&rl_mpeg2);

        init_2d_vlc_rl(&rl_mpeg1);

        init_2d_vlc_rl(&rl_mpeg2);

    }

}


TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);
  const TfLiteTensor* segment_ids =
      GetInput(context, node, kInputSegmentIdsTensor);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  if (IsDynamicTensor(output)) {
    TF_LITE_ENSURE_OK(context,
                      ResizeOutputTensor(context, data, segment_ids, output));
  }

#define TF_LITE_SEGMENT_SUM(dtype)                                      \
  reference_ops::SegmentSum<dtype>(                                     \
      GetTensorShape(data), GetTensorData<dtype>(data),                 \
      GetTensorShape(segment_ids), GetTensorData<int32_t>(segment_ids), \
      GetTensorShape(output), GetTensorData<dtype>(output));
  switch (data->type) {
    case kTfLiteInt32:
      TF_LITE_SEGMENT_SUM(int32_t);
      break;
    case kTfLiteFloat32:
      TF_LITE_SEGMENT_SUM(float);
      break;
    default:
      context->ReportError(context,
                           "Currently SegmentSum doesn't support type: %s",
                           TfLiteTypeGetName(data->type));
      return kTfLiteError;
  }
#undef TF_LITE_SEGMENT_SUM
  return kTfLiteOk;
}


static CARD32 rfbAuthReenable(OsTimerPtr timer, CARD32 now, pointer arg)
{
  rfbAuthTooManyTries = FALSE;
  return 0;
}


Jsi_RC Jsi_InitSqlite(Jsi_Interp *interp, int release)
{
    if (release) return Jsi_DoneSqlite(interp);
    Jsi_Hash* dbSys;
#if JSI_USE_STUBS
    if (Jsi_StubsInit(interp, 0) != JSI_OK)
        return JSI_ERROR;
#endif

    if (!(dbSys = Jsi_UserObjRegister(interp, &sqliteobject)))
        return Jsi_LogError("Failed to init sqlite extension");

    Jsi_Value *info = Jsi_ValueNew1(interp);
    Jsi_JSONParseFmt(interp, &info, "{libVer:\"%s\", hdrVer:\"%s\", hdrNum:%d, hdrSrcId:\"%s\", pkgVer:%d}",
        (char *)sqlite3_libversion(), SQLITE_VERSION, SQLITE_VERSION_NUMBER, SQLITE_SOURCE_ID, jsi_DbPkgVersion);
    Jsi_PkgOpts dbPkgOpts = { db_ObjCmd_Specs, &dbObjCmd, sqliteCmds, info };
    Jsi_RC rc = Jsi_PkgProvideEx(interp, "Sqlite", jsi_DbPkgVersion, Jsi_InitSqlite, &dbPkgOpts);
    Jsi_DecrRefCount(interp, info);
    if (rc != JSI_OK)
        return JSI_ERROR;

    if (!Jsi_CommandCreateSpecs(interp, sqliteobject.name, sqliteCmds, dbSys, JSI_CMDSPEC_ISOBJ))
        return JSI_ERROR;

#ifdef JSI_DB_TEST
    if (getenv("RUN_DB_TEST"))
        TestSqlite(interp);
#endif
    jsi_DbVfs **dbVfsPtrPtr = (jsi_DbVfs **)Jsi_InterpGetData(interp, JSI_SQLITE_DB_VFS, NULL);
    if (dbVfsPtrPtr)
        *dbVfsPtrPtr = &SqliteDbVfs;
    return JSI_OK;
}


int sws_init_context(SwsContext *c, SwsFilter *srcFilter, SwsFilter *dstFilter)

{

    int i, j;

    int usesVFilter, usesHFilter;

    int unscaled;

    SwsFilter dummyFilter= {NULL, NULL, NULL, NULL};

    int srcW= c->srcW;

    int srcH= c->srcH;

    int dstW= c->dstW;

    int dstH= c->dstH;

    int dst_stride = FFALIGN(dstW * sizeof(int16_t)+66, 16);

    int flags, cpu_flags;

    enum PixelFormat srcFormat= c->srcFormat;

    enum PixelFormat dstFormat= c->dstFormat;

    cpu_flags = av_get_cpu_flags();

    flags     = c->flags;

    emms_c();

    if (!rgb15to16) sws_rgb2rgb_init();

    unscaled = (srcW == dstW && srcH == dstH);

    handle_jpeg(&srcFormat);

    handle_jpeg(&dstFormat);

    if(srcFormat!=c->srcFormat || dstFormat!=c->dstFormat){

        av_log(c, AV_LOG_WARNING, "deprecated pixel format used, make sure you did set range correctly\n");

        c->srcFormat= srcFormat;

        c->dstFormat= dstFormat;

    }

    if (!sws_isSupportedInput(srcFormat)) {

        av_log(c, AV_LOG_ERROR, "%s is not supported as input pixel format\n", av_get_pix_fmt_name(srcFormat));

        return AVERROR(EINVAL);

    }

    if (!sws_isSupportedOutput(dstFormat)) {

        av_log(c, AV_LOG_ERROR, "%s is not supported as output pixel format\n", av_get_pix_fmt_name(dstFormat));

        return AVERROR(EINVAL);

    }

    i= flags & ( SWS_POINT

                |SWS_AREA

                |SWS_BILINEAR

                |SWS_FAST_BILINEAR

                |SWS_BICUBIC

                |SWS_X

                |SWS_GAUSS

                |SWS_LANCZOS

                |SWS_SINC

                |SWS_SPLINE

                |SWS_BICUBLIN);

    if(!i || (i & (i-1))) {

        av_log(c, AV_LOG_ERROR, "Exactly one scaler algorithm must be chosen\n");

        return AVERROR(EINVAL);

    }

    /* sanity check */

    if (srcW<4 || srcH<1 || dstW<8 || dstH<1) { //FIXME check if these are enough and try to lowwer them after fixing the relevant parts of the code

        av_log(c, AV_LOG_ERROR, "%dx%d -> %dx%d is invalid scaling dimension\n",

               srcW, srcH, dstW, dstH);

        return AVERROR(EINVAL);

    }

    if (!dstFilter) dstFilter= &dummyFilter;

    if (!srcFilter) srcFilter= &dummyFilter;

    c->lumXInc= ((srcW<<16) + (dstW>>1))/dstW;

    c->lumYInc= ((srcH<<16) + (dstH>>1))/dstH;

    c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[dstFormat]);

    c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[srcFormat]);

    c->vRounder= 4* 0x0001000100010001ULL;

    usesVFilter = (srcFilter->lumV && srcFilter->lumV->length>1) ||

                  (srcFilter->chrV && srcFilter->chrV->length>1) ||

                  (dstFilter->lumV && dstFilter->lumV->length>1) ||

                  (dstFilter->chrV && dstFilter->chrV->length>1);

    usesHFilter = (srcFilter->lumH && srcFilter->lumH->length>1) ||

                  (srcFilter->chrH && srcFilter->chrH->length>1) ||

                  (dstFilter->lumH && dstFilter->lumH->length>1) ||

                  (dstFilter->chrH && dstFilter->chrH->length>1);

    getSubSampleFactors(&c->chrSrcHSubSample, &c->chrSrcVSubSample, srcFormat);

    getSubSampleFactors(&c->chrDstHSubSample, &c->chrDstVSubSample, dstFormat);

    // reuse chroma for 2 pixels RGB/BGR unless user wants full chroma interpolation

    if (isAnyRGB(dstFormat) && !(flags&SWS_FULL_CHR_H_INT)) {

        if (dstW&1) {

            av_log(c, AV_LOG_DEBUG, "Forcing full internal H chroma due to odd output size\n");

            flags |= SWS_FULL_CHR_H_INT;

            c->flags = flags;

        } else

            c->chrDstHSubSample = 1;

    }

    // drop some chroma lines if the user wants it

    c->vChrDrop= (flags&SWS_SRC_V_CHR_DROP_MASK)>>SWS_SRC_V_CHR_DROP_SHIFT;

    c->chrSrcVSubSample+= c->vChrDrop;

    // drop every other pixel for chroma calculation unless user wants full chroma

    if (isAnyRGB(srcFormat) && !(flags&SWS_FULL_CHR_H_INP)

      && srcFormat!=PIX_FMT_RGB8      && srcFormat!=PIX_FMT_BGR8

      && srcFormat!=PIX_FMT_RGB4      && srcFormat!=PIX_FMT_BGR4

      && srcFormat!=PIX_FMT_RGB4_BYTE && srcFormat!=PIX_FMT_BGR4_BYTE

      && ((dstW>>c->chrDstHSubSample) <= (srcW>>1) || (flags&SWS_FAST_BILINEAR)))

        c->chrSrcHSubSample=1;

    // Note the -((-x)>>y) is so that we always round toward +inf.

    c->chrSrcW= -((-srcW) >> c->chrSrcHSubSample);

    c->chrSrcH= -((-srcH) >> c->chrSrcVSubSample);

    c->chrDstW= -((-dstW) >> c->chrDstHSubSample);

    c->chrDstH= -((-dstH) >> c->chrDstVSubSample);

    /* unscaled special cases */

    if (unscaled && !usesHFilter && !usesVFilter && (c->srcRange == c->dstRange || isAnyRGB(dstFormat))) {

        ff_get_unscaled_swscale(c);

        if (c->swScale) {

            if (flags&SWS_PRINT_INFO)

                av_log(c, AV_LOG_INFO, "using unscaled %s -> %s special converter\n",

                       av_get_pix_fmt_name(srcFormat), av_get_pix_fmt_name(dstFormat));

            return 0;

        }

    }

    c->srcBpc = 1 + av_pix_fmt_descriptors[srcFormat].comp[0].depth_minus1;

    if (c->srcBpc < 8)

        c->srcBpc = 8;

    c->dstBpc = 1 + av_pix_fmt_descriptors[dstFormat].comp[0].depth_minus1;

    if (c->dstBpc < 8)

        c->dstBpc = 8;

    if (isAnyRGB(srcFormat) || srcFormat == PIX_FMT_PAL8)

        c->srcBpc = 16;

    if (c->dstBpc == 16)

        dst_stride <<= 1;

    FF_ALLOC_OR_GOTO(c, c->formatConvBuffer, FFALIGN(srcW*2+78, 16) * 2, fail);

    if (HAVE_MMX2 && cpu_flags & AV_CPU_FLAG_MMX2 && c->srcBpc == 8 && c->dstBpc <= 10) {

        c->canMMX2BeUsed= (dstW >=srcW && (dstW&31)==0 && (srcW&15)==0) ? 1 : 0;

        if (!c->canMMX2BeUsed && dstW >=srcW && (srcW&15)==0 && (flags&SWS_FAST_BILINEAR)) {

            if (flags&SWS_PRINT_INFO)

                av_log(c, AV_LOG_INFO, "output width is not a multiple of 32 -> no MMX2 scaler\n");

        }

        if (usesHFilter || isNBPS(c->srcFormat) || is16BPS(c->srcFormat) || isAnyRGB(c->srcFormat)) c->canMMX2BeUsed=0;

    }

    else

        c->canMMX2BeUsed=0;

    c->chrXInc= ((c->chrSrcW<<16) + (c->chrDstW>>1))/c->chrDstW;

    c->chrYInc= ((c->chrSrcH<<16) + (c->chrDstH>>1))/c->chrDstH;

    // match pixel 0 of the src to pixel 0 of dst and match pixel n-2 of src to pixel n-2 of dst

    // but only for the FAST_BILINEAR mode otherwise do correct scaling

    // n-2 is the last chrominance sample available

    // this is not perfect, but no one should notice the difference, the more correct variant

    // would be like the vertical one, but that would require some special code for the

    // first and last pixel

    if (flags&SWS_FAST_BILINEAR) {

        if (c->canMMX2BeUsed) {

            c->lumXInc+= 20;

            c->chrXInc+= 20;

        }

        //we don't use the x86 asm scaler if MMX is available

        else if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX && c->dstBpc <= 10) {

            c->lumXInc = ((srcW-2)<<16)/(dstW-2) - 20;

            c->chrXInc = ((c->chrSrcW-2)<<16)/(c->chrDstW-2) - 20;

        }

    }

    /* precalculate horizontal scaler filter coefficients */

    {

#if HAVE_MMX2

// can't downscale !!!

        if (c->canMMX2BeUsed && (flags & SWS_FAST_BILINEAR)) {

            c->lumMmx2FilterCodeSize = initMMX2HScaler(      dstW, c->lumXInc, NULL, NULL, NULL, 8);

            c->chrMmx2FilterCodeSize = initMMX2HScaler(c->chrDstW, c->chrXInc, NULL, NULL, NULL, 4);

#ifdef MAP_ANONYMOUS

            c->lumMmx2FilterCode = mmap(NULL, c->lumMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

            c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

#elif HAVE_VIRTUALALLOC

            c->lumMmx2FilterCode = VirtualAlloc(NULL, c->lumMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

            c->chrMmx2FilterCode = VirtualAlloc(NULL, c->chrMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

#else

            c->lumMmx2FilterCode = av_malloc(c->lumMmx2FilterCodeSize);

            c->chrMmx2FilterCode = av_malloc(c->chrMmx2FilterCodeSize);

#endif

#ifdef MAP_ANONYMOUS

            if (c->lumMmx2FilterCode == MAP_FAILED || c->chrMmx2FilterCode == MAP_FAILED)

#else

            if (!c->lumMmx2FilterCode || !c->chrMmx2FilterCode)

#endif

            {

                av_log(c, AV_LOG_ERROR, "Failed to allocate MMX2FilterCode\n");

                return AVERROR(ENOMEM);

            }

            FF_ALLOCZ_OR_GOTO(c, c->hLumFilter   , (dstW        /8+8)*sizeof(int16_t), fail);

            FF_ALLOCZ_OR_GOTO(c, c->hChrFilter   , (c->chrDstW  /4+8)*sizeof(int16_t), fail);

            FF_ALLOCZ_OR_GOTO(c, c->hLumFilterPos, (dstW      /2/8+8)*sizeof(int32_t), fail);

            FF_ALLOCZ_OR_GOTO(c, c->hChrFilterPos, (c->chrDstW/2/4+8)*sizeof(int32_t), fail);

            initMMX2HScaler(      dstW, c->lumXInc, c->lumMmx2FilterCode, c->hLumFilter, (uint32_t*)c->hLumFilterPos, 8);

            initMMX2HScaler(c->chrDstW, c->chrXInc, c->chrMmx2FilterCode, c->hChrFilter, (uint32_t*)c->hChrFilterPos, 4);

#ifdef MAP_ANONYMOUS

            mprotect(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize, PROT_EXEC | PROT_READ);

            mprotect(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize, PROT_EXEC | PROT_READ);

#endif

        } else

#endif /* HAVE_MMX2 */

        {

            const int filterAlign=

                (HAVE_MMX     && cpu_flags & AV_CPU_FLAG_MMX) ? 4 :

                (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_ALTIVEC) ? 8 :

                1;

            if (initFilter(&c->hLumFilter, &c->hLumFilterPos, &c->hLumFilterSize, c->lumXInc,

                           srcW      ,       dstW, filterAlign, 1<<14,

                           (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC)  : flags, cpu_flags,

                           srcFilter->lumH, dstFilter->lumH, c->param) < 0)

                goto fail;

            if (initFilter(&c->hChrFilter, &c->hChrFilterPos, &c->hChrFilterSize, c->chrXInc,

                           c->chrSrcW, c->chrDstW, filterAlign, 1<<14,

                           (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags, cpu_flags,

                           srcFilter->chrH, dstFilter->chrH, c->param) < 0)

                goto fail;

        }

    } // initialize horizontal stuff

    /* precalculate vertical scaler filter coefficients */

    {

        const int filterAlign=

            (HAVE_MMX     && cpu_flags & AV_CPU_FLAG_MMX) ? 2 :

            (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_ALTIVEC) ? 8 :

            1;

        if (initFilter(&c->vLumFilter, &c->vLumFilterPos, &c->vLumFilterSize, c->lumYInc,

                       srcH      ,        dstH, filterAlign, (1<<12),

                       (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC)  : flags, cpu_flags,

                       srcFilter->lumV, dstFilter->lumV, c->param) < 0)

            goto fail;

        if (initFilter(&c->vChrFilter, &c->vChrFilterPos, &c->vChrFilterSize, c->chrYInc,

                       c->chrSrcH, c->chrDstH, filterAlign, (1<<12),

                       (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags, cpu_flags,

                       srcFilter->chrV, dstFilter->chrV, c->param) < 0)

            goto fail;

#if HAVE_ALTIVEC

        FF_ALLOC_OR_GOTO(c, c->vYCoeffsBank, sizeof (vector signed short)*c->vLumFilterSize*c->dstH, fail);

        FF_ALLOC_OR_GOTO(c, c->vCCoeffsBank, sizeof (vector signed short)*c->vChrFilterSize*c->chrDstH, fail);

        for (i=0;i<c->vLumFilterSize*c->dstH;i++) {

            int j;

            short *p = (short *)&c->vYCoeffsBank[i];

            for (j=0;j<8;j++)

                p[j] = c->vLumFilter[i];

        }

        for (i=0;i<c->vChrFilterSize*c->chrDstH;i++) {

            int j;

            short *p = (short *)&c->vCCoeffsBank[i];

            for (j=0;j<8;j++)

                p[j] = c->vChrFilter[i];

        }

#endif

    }

    // calculate buffer sizes so that they won't run out while handling these damn slices

    c->vLumBufSize= c->vLumFilterSize;

    c->vChrBufSize= c->vChrFilterSize;

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

        int chrI= (int64_t)i*c->chrDstH / dstH;

        int nextSlice= FFMAX(c->vLumFilterPos[i   ] + c->vLumFilterSize - 1,

                           ((c->vChrFilterPos[chrI] + c->vChrFilterSize - 1)<<c->chrSrcVSubSample));

        nextSlice>>= c->chrSrcVSubSample;

        nextSlice<<= c->chrSrcVSubSample;

        if (c->vLumFilterPos[i   ] + c->vLumBufSize < nextSlice)

            c->vLumBufSize= nextSlice - c->vLumFilterPos[i];

        if (c->vChrFilterPos[chrI] + c->vChrBufSize < (nextSlice>>c->chrSrcVSubSample))

            c->vChrBufSize= (nextSlice>>c->chrSrcVSubSample) - c->vChrFilterPos[chrI];

    }

    // allocate pixbufs (we use dynamic allocation because otherwise we would need to

    // allocate several megabytes to handle all possible cases)

    FF_ALLOC_OR_GOTO(c, c->lumPixBuf, c->vLumBufSize*2*sizeof(int16_t*), fail);

    FF_ALLOC_OR_GOTO(c, c->chrUPixBuf, c->vChrBufSize*2*sizeof(int16_t*), fail);

    FF_ALLOC_OR_GOTO(c, c->chrVPixBuf, c->vChrBufSize*2*sizeof(int16_t*), fail);

    if (CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat) && isALPHA(c->dstFormat))

        FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf, c->vLumBufSize*2*sizeof(int16_t*), fail);

    //Note we need at least one pixel more at the end because of the MMX code (just in case someone wanna replace the 4000/8000)

    /* align at 16 bytes for AltiVec */

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

        FF_ALLOCZ_OR_GOTO(c, c->lumPixBuf[i+c->vLumBufSize], dst_stride+16, fail);

        c->lumPixBuf[i] = c->lumPixBuf[i+c->vLumBufSize];

    }

    // 64 / c->scalingBpp is the same as 16 / sizeof(scaling_intermediate)

    c->uv_off   = (dst_stride>>1) + 64 / (c->dstBpc &~ 7);

    c->uv_offx2 = dst_stride + 16;

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

        FF_ALLOC_OR_GOTO(c, c->chrUPixBuf[i+c->vChrBufSize], dst_stride*2+32, fail);

        c->chrUPixBuf[i] = c->chrUPixBuf[i+c->vChrBufSize];

        c->chrVPixBuf[i] = c->chrVPixBuf[i+c->vChrBufSize] = c->chrUPixBuf[i] + (dst_stride >> 1) + 8;

    }

    if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf)

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

            FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf[i+c->vLumBufSize], dst_stride+16, fail);

            c->alpPixBuf[i] = c->alpPixBuf[i+c->vLumBufSize];

        }

    //try to avoid drawing green stuff between the right end and the stride end

    for (i=0; i<c->vChrBufSize; i++)

        if(av_pix_fmt_descriptors[c->dstFormat].comp[0].depth_minus1 == 15){

            av_assert0(c->dstBpc > 10);

            for(j=0; j<dst_stride/2+1; j++)

                ((int32_t*)(c->chrUPixBuf[i]))[j] = 1<<18;

        } else

            for(j=0; j<dst_stride+1; j++)

                ((int16_t*)(c->chrUPixBuf[i]))[j] = 1<<14;

    assert(c->chrDstH <= dstH);

    if (flags&SWS_PRINT_INFO) {

        if      (flags&SWS_FAST_BILINEAR) av_log(c, AV_LOG_INFO, "FAST_BILINEAR scaler, ");

        else if (flags&SWS_BILINEAR)      av_log(c, AV_LOG_INFO, "BILINEAR scaler, ");

        else if (flags&SWS_BICUBIC)       av_log(c, AV_LOG_INFO, "BICUBIC scaler, ");

        else if (flags&SWS_X)             av_log(c, AV_LOG_INFO, "Experimental scaler, ");

        else if (flags&SWS_POINT)         av_log(c, AV_LOG_INFO, "Nearest Neighbor / POINT scaler, ");

        else if (flags&SWS_AREA)          av_log(c, AV_LOG_INFO, "Area Averaging scaler, ");

        else if (flags&SWS_BICUBLIN)      av_log(c, AV_LOG_INFO, "luma BICUBIC / chroma BILINEAR scaler, ");

        else if (flags&SWS_GAUSS)         av_log(c, AV_LOG_INFO, "Gaussian scaler, ");

        else if (flags&SWS_SINC)          av_log(c, AV_LOG_INFO, "Sinc scaler, ");

        else if (flags&SWS_LANCZOS)       av_log(c, AV_LOG_INFO, "Lanczos scaler, ");

        else if (flags&SWS_SPLINE)        av_log(c, AV_LOG_INFO, "Bicubic spline scaler, ");

        else                              av_log(c, AV_LOG_INFO, "ehh flags invalid?! ");

        av_log(c, AV_LOG_INFO, "from %s to %s%s ",

               av_get_pix_fmt_name(srcFormat),

#ifdef DITHER1XBPP

               dstFormat == PIX_FMT_BGR555 || dstFormat == PIX_FMT_BGR565 ||

               dstFormat == PIX_FMT_RGB444BE || dstFormat == PIX_FMT_RGB444LE ||

               dstFormat == PIX_FMT_BGR444BE || dstFormat == PIX_FMT_BGR444LE ? "dithered " : "",

#else

               "",

#endif

               av_get_pix_fmt_name(dstFormat));

        if      (HAVE_MMX2     && cpu_flags & AV_CPU_FLAG_MMX2)    av_log(c, AV_LOG_INFO, "using MMX2\n");

        else if (HAVE_AMD3DNOW && cpu_flags & AV_CPU_FLAG_3DNOW)   av_log(c, AV_LOG_INFO, "using 3DNOW\n");

        else if (HAVE_MMX      && cpu_flags & AV_CPU_FLAG_MMX)     av_log(c, AV_LOG_INFO, "using MMX\n");

        else if (HAVE_ALTIVEC  && cpu_flags & AV_CPU_FLAG_ALTIVEC) av_log(c, AV_LOG_INFO, "using AltiVec\n");

        else                                   av_log(c, AV_LOG_INFO, "using C\n");

        av_log(c, AV_LOG_VERBOSE, "%dx%d -> %dx%d\n", srcW, srcH, dstW, dstH);

        av_log(c, AV_LOG_DEBUG, "lum srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",

               c->srcW, c->srcH, c->dstW, c->dstH, c->lumXInc, c->lumYInc);

        av_log(c, AV_LOG_DEBUG, "chr srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",

               c->chrSrcW, c->chrSrcH, c->chrDstW, c->chrDstH, c->chrXInc, c->chrYInc);

    }

    c->swScale= ff_getSwsFunc(c);

    return 0;

fail: //FIXME replace things by appropriate error codes

    return -1;

}


void snd_ctl_free_one(struct snd_kcontrol *kcontrol)
{
	if (kcontrol) {
		if (kcontrol->private_free)
			kcontrol->private_free(kcontrol);
		kfree(kcontrol);
	}
}


qf_init_process_nextline(
	qf_list_T	*qfl,
	efm_T		*fmt_first,
	qfstate_T	*state,
	qffields_T	*fields)
{
    int		    status;

    // Get the next line from a file/buffer/list/string
    status = qf_get_nextline(state);
    if (status != QF_OK)
	return status;

    status = qf_parse_line(qfl, state->linebuf, state->linelen,
	    fmt_first, fields);
    if (status != QF_OK)
	return status;

    return qf_add_entry(qfl,
		qfl->qf_directory,
		(*fields->namebuf || qfl->qf_directory != NULL)
		? fields->namebuf
		: ((qfl->qf_currfile != NULL && fields->valid)
		    ? qfl->qf_currfile : (char_u *)NULL),
		fields->module,
		0,
		fields->errmsg,
		fields->lnum,
		fields->end_lnum,
		fields->col,
		fields->end_col,
		fields->use_viscol,
		fields->pattern,
		fields->enr,
		fields->type,
		fields->valid);
}


static Jsi_RC InfoArgv0Cmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
    Jsi_Value **ret, Jsi_Func *funcPtr)
{
    if (interp->argv0)
        Jsi_ValueDup2(interp, ret, interp->argv0);
     return JSI_OK;
}


static uint32_t file_block_getter ( uint8_t * p , uint32_t s , Gif_Reader * grr ) {
 size_t nread = fread ( p , 1 , s , grr -> f ) ;
 if ( nread < s ) memset ( p + nread , 0 , s - nread ) ;
 grr -> pos += nread ;
 return nread ;
 }


static void lis_close(struct tls_listener *listener)
{
    if (listener->is_registered) {
	pjsip_tpmgr_unregister_tpfactory(listener->tpmgr, &listener->factory);
	listener->is_registered = PJ_FALSE;
    }

    if (listener->ssock) {
	pj_ssl_sock_close(listener->ssock);
	listener->ssock = NULL;
    }
}


int callback_glewlwyd_scheme_check_forbid_profile (const struct _u_request * request, struct _u_response * response, void * user_data) {
  struct config_elements * config = (struct config_elements *)user_data;
  json_t * j_param = ulfius_get_json_body_request(request, NULL), * j_scheme = get_user_auth_scheme_module(config, json_string_value(json_object_get(j_param, "scheme_name")));
  int ret = U_CALLBACK_CONTINUE;

  if (check_result_value(j_scheme, G_OK)) {
    if (json_object_get(json_object_get(j_scheme, "module"), "forbid_user_profile") == json_true()) {
      response->status = 403;
      ret = U_CALLBACK_COMPLETE;
    }
  } else if (check_result_value(j_scheme, G_ERROR_NOT_FOUND)) {
    response->status = 404;
  } else {
    y_log_message(Y_LOG_LEVEL_ERROR, "callback_glewlwyd_scheme_check_forbid_profile - Error auth_register_get_user_scheme");
    response->status = 500;
  }
  json_decref(j_param);
  json_decref(j_scheme);
  return ret;
}


static always_inline void gen_op_subfeo_64 (void)

{

    gen_op_move_T2_T0();

    gen_op_subfe_64();

    gen_op_check_subfo_64();

}


open_pn_file(modebits)
mode_t modebits;
{
	char *path;
	int fd, err;

	if ((path = name_of_pn_file()) == NULL)
		return (-1);
	fd = open(path, modebits, S_IRUSR | S_IWUSR);
	err = errno;
	free(path);
	errno = err;
	return (fd);
}


void DocumentLoader::commitLoad(const char* data, int length)
{
    RefPtr<Frame> protectFrame(m_frame);
    RefPtr<DocumentLoader> protectLoader(this);

    commitIfReady();
    FrameLoader* frameLoader = DocumentLoader::frameLoader();
    if (!frameLoader)
        return;
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
    if (ArchiveFactory::isArchiveMimeType(response().mimeType()))
        return;
#endif
    frameLoader->client()->committedLoad(this, data, length);
}


void ShellWindowViews::Close() {
  window_->Close();
}


TfLiteRegistration* Register_L2_POOL_REF() {
  static TfLiteRegistration r = {pooling::Init, pooling::Free,
                                 pooling::GenericPrepare<pooling::kL2>,
                                 pooling::L2Eval<pooling::kReference>};
  return &r;
}


   base::Version ruleset_format_version() {
     return policy_->ruleset_format_version_;
   }


R_API void r_sys_backtrace(void) {
#ifdef HAVE_BACKTRACE
	void *array[10];
	size_t size = backtrace (array, 10);
	eprintf ("Backtrace %zd stack frames.\n", size);
	backtrace_symbols_fd (array, size, 2);
#elif __APPLE__
	void **fp = (void **) __builtin_frame_address (0);
	void *saved_pc = __builtin_return_address (0);
	void *saved_fp = __builtin_frame_address (1);
	int depth = 0;

	printf ("[%d] pc == %p fp == %p\n", depth++, saved_pc, saved_fp);
	fp = saved_fp;
	while (fp) {
		saved_fp = *fp;
		fp = saved_fp;
		if (!*fp) {
			break;
		}
		saved_pc = *(fp + 2);
		printf ("[%d] pc == %p fp == %p\n", depth++, saved_pc, saved_fp);
	}
#else
#ifdef _MSC_VER
#pragma message ("TODO: r_sys_bt : unimplemented")
#else
#warning TODO: r_sys_bt : unimplemented
#endif
#endif
}


define_function(fsum_2)
{
  double a = float_argument(1);
  double b = float_argument(2);

  return_float(a + b);
}


status_to_message(u_int32_t status)
{
	const char *status_messages[] = {
		"Success",			/* SSH_FX_OK */
		"End of file",			/* SSH_FX_EOF */
		"No such file",			/* SSH_FX_NO_SUCH_FILE */
		"Permission denied",		/* SSH_FX_PERMISSION_DENIED */
		"Failure",			/* SSH_FX_FAILURE */
		"Bad message",			/* SSH_FX_BAD_MESSAGE */
		"No connection",		/* SSH_FX_NO_CONNECTION */
		"Connection lost",		/* SSH_FX_CONNECTION_LOST */
		"Operation unsupported",	/* SSH_FX_OP_UNSUPPORTED */
		"Unknown error"			/* Others */
	};
	return (status_messages[MINIMUM(status,SSH2_FX_MAX)]);
}


static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
  size_t
    count,
    length;

  register ssize_t
    i;

  /*
    Max length is 255.
  */
  count=0;
  length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
  if (length ==  0)
    count+=WriteBlobByte(image,0);
  else
    {
      count+=WriteBlobByte(image,(unsigned char) length);
      count+=WriteBlob(image,length,(const unsigned char *) value);
    }
  length++;
  if ((length % padding) == 0)
    return(count);
  for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
    count+=WriteBlobByte(image,0);
  return(count);
}


bool gup_fast_permitted(unsigned long start, int nr_pages, int write)
{
	unsigned long len, end;

	len = (unsigned long) nr_pages << PAGE_SHIFT;
	end = start + len;
	return end >= start;
}


ar6000_cac_event(struct ar6_softc *ar, u8 ac, u8 cacIndication,
                 u8 statusCode, u8 *tspecSuggestion)
{
    WMM_TSPEC_IE    *tspecIe;

    /*
     * This is the TSPEC IE suggestion from AP.
     * Suggestion provided by AP under some error
     * cases, could be helpful for the host app.
     * Check documentation.
     */
    tspecIe = (WMM_TSPEC_IE *)tspecSuggestion;

    /*
     * What do we do, if we get TSPEC rejection? One thought
     * that comes to mind is implictly delete the pstream...
     */
    A_PRINTF("AR6000 CAC notification. "
                "AC = %d, cacIndication = 0x%x, statusCode = 0x%x\n",
                 ac, cacIndication, statusCode);
}


wextglob_skipname (pat, dname, flags)
     wchar_t *pat, *dname;
     int flags;
{
#if EXTENDED_GLOB
  wchar_t *pp, *pe, *t, n, *se;
  int r, negate, wild, nullpat;

  negate = *pat == L'!';
  wild = *pat == L'*' || *pat == L'?';
  pp = pat + 2;
  se = pp + wcslen (pp) - 1;	/*(*/
  pe = glob_patscan_wc (pp, se, 0);

  if (pe == se && *pe == ')' && (t = wcschr (pp, L'|')) == 0)
    {
      *pe = L'\0';
      r = wskipname (pp, dname, flags); /*(*/
      *pe = L')';
      if (wild && pe[1] != L'\0')
        return (wskipname (pe+1, dname, flags));
      return r;
    }

  /* Is the extglob pattern between the parens the null pattern?  The null
     pattern can match nothing, so should we check any remaining portion of
     the pattern? */
  nullpat = pe >= (pat + 2) && pe[-2] == L'(' && pe[-1] == L')';

  /* check every subpattern */
  while (t = glob_patscan_wc (pp, pe, '|'))
    {
      n = t[-1];	/* ( */
      if (wextglob_pattern_p (pp) && n == L')')
	t[-1] = n;	/* no-op for now */
      else
	t[-1] = L'\0';
      r = wskipname (pp, dname, flags);
      t[-1] = n;
      if (r == 0)
	return 0;
      pp = t;
    }

  if (pp == pe)		/* glob_patscan_wc might find end of pattern */
    return r;

  /* but if it doesn't then we didn't match a leading dot */
  if (wild && *pe != L'\0')
    return (wskipname (pe, dname, flags));
  return 1;
#else
  return (wskipname (pat, dname, flags));
#endif
}


PHP_FUNCTION(gethostbynamel)
{
	char *hostname;
	int hostname_len;
	struct hostent *hp;
	struct in_addr in;
	int i;

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

	hp = gethostbyname(hostname);
	if (hp == NULL || hp->h_addr_list == NULL) {
		RETURN_FALSE;
	}

	array_init(return_value);

	for (i = 0 ; hp->h_addr_list[i] != 0 ; i++) {
		in = *(struct in_addr *) hp->h_addr_list[i];
		add_next_index_string(return_value, inet_ntoa(in), 1);
	}
}


 void TouchEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) {
   input_event inputs[kNumTouchEvdevSlots * 6 + 1];
   ssize_t read_size = read(fd, inputs, sizeof(inputs));
   if (read_size < 0) {
    if (errno == EINTR || errno == EAGAIN)
      return;
    if (errno != ENODEV)
      PLOG(ERROR) << "error reading device " << path_.value();
    Stop();
    return;
  }

  if (ignore_events_)
    return;

  for (unsigned i = 0; i < read_size / sizeof(*inputs); i++) {
    if (!has_mt_) {
      EmulateMultitouchEvent(inputs[i]);
    }

    ProcessMultitouchEvent(inputs[i]);
  }
}


static int peer_has_vnet_hdr ( VirtIONet * n ) {
 if ( ! n -> nic -> nc . peer ) return 0 ;
 if ( n -> nic -> nc . peer -> info -> type != NET_CLIENT_TYPE_TAP ) return 0 ;
 n -> has_vnet_hdr = tap_has_vnet_hdr ( n -> nic -> nc . peer ) ;
 return n -> has_vnet_hdr ;
 }


TEST_P(ProtocolIntegrationTest, UpstreamDisconnectBeforeResponseCompleteWireBytesCountUpstream) {
  // we only care about upstream protocol.
  if (downstreamProtocol() != Http::CodecType::HTTP2) {
    return;
  }
  useAccessLog("%UPSTREAM_WIRE_BYTES_SENT% %UPSTREAM_WIRE_BYTES_RECEIVED% "
               "%UPSTREAM_HEADER_BYTES_SENT% %UPSTREAM_HEADER_BYTES_RECEIVED%");

  testRouterUpstreamDisconnectBeforeResponseComplete();

  expectUpstreamBytesSentAndReceived(BytesCountExpectation(159, 47, 128, 27),
                                     BytesCountExpectation(113, 13, 113, 13),
                                     BytesCountExpectation(113, 5, 113, 3));
}


void Transform::greyscale( RawTile& rawtile ){

  if( rawtile.bpc != 8 || rawtile.channels != 3 ) return;

  unsigned int np = rawtile.width * rawtile.height;
  unsigned char* buffer = new unsigned char[rawtile.width * rawtile.height];

  // Calculate using fixed-point arithmetic
  //  - benchmarks to around 25% faster than floating point
#if defined(__ICC) || defined(__INTEL_COMPILER)
#pragma ivdep
#elif defined(_OPENMP)
#pragma omp parallel for if( rawtile.width*rawtile.height > PARALLEL_THRESHOLD )
#endif
  for( unsigned int i=0; i<np; i++ ){
    unsigned int n = i*rawtile.channels;
    unsigned char R = ((unsigned char*)rawtile.data)[n++];
    unsigned char G = ((unsigned char*)rawtile.data)[n++];
    unsigned char B = ((unsigned char*)rawtile.data)[n++];
    buffer[i] = (unsigned char)( ( 1254097*R + 2462056*G + 478151*B ) >> 22 );
  }

  // Delete our old data buffer and instead point to our grayscale data
  delete[] (unsigned char*) rawtile.data;
  rawtile.data = (void*) buffer;

  // Update our number of channels and data length
  rawtile.channels = 1;
  rawtile.dataLength = np;
}


int tls12_get_sigid(const EVP_PKEY *pk)
{
    return tls12_find_id(EVP_PKEY_id(pk), tls12_sig, OSSL_NELEM(tls12_sig));
}


void EnterpriseEnrollmentScreen::OnAuthSubmitted(
    const std::string& user,
    const std::string& password,
    const std::string& captcha,
    const std::string& access_code) {
  UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
                            policy::kMetricEnrollmentStarted,
                            policy::kMetricEnrollmentSize);
  captcha_token_.clear();
  user_ = user;
  auth_fetcher_.reset(
      new GaiaAuthFetcher(this, GaiaConstants::kChromeSource,
                          g_browser_process->system_request_context()));

  if (access_code.empty()) {
    auth_fetcher_->StartClientLogin(user, password,
                                    GaiaConstants::kDeviceManagementService,
                                    captcha_token_, captcha,
                                    GaiaAuthFetcher::HostedAccountsAllowed);
  } else {
    auth_fetcher_->StartClientLogin(user, access_code,
                                    GaiaConstants::kDeviceManagementService,
                                    std::string(), std::string(),
                                    GaiaAuthFetcher::HostedAccountsAllowed);
  }
}


static int decode_stream_header(NUTContext *nut){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    StreamContext *stc;

    int class, nom, denom, stream_id;

    uint64_t tmp, end;

    AVStream *st;

    end= get_packetheader(nut, bc, 1);

    end += url_ftell(bc) - 4;

    GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base.num);

    stc= &nut->stream[stream_id];

    st = s->streams[stream_id];

    if (!st)

        return AVERROR_NOMEM;

    class = get_v(bc);

    tmp = get_fourcc(bc);

    st->codec->codec_tag= tmp;

    switch(class)

    {

        case 0:

            st->codec->codec_type = CODEC_TYPE_VIDEO;

            st->codec->codec_id = codec_get_bmp_id(tmp);

            if (st->codec->codec_id == CODEC_ID_NONE)

                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");

            break;

        case 1:

            st->codec->codec_type = CODEC_TYPE_AUDIO;

            st->codec->codec_id = codec_get_wav_id(tmp);

            if (st->codec->codec_id == CODEC_ID_NONE)

                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");

            break;

        case 2:

//            st->codec->codec_type = CODEC_TYPE_TEXT;

//            break;

        case 3:

            st->codec->codec_type = CODEC_TYPE_DATA;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);

            return -1;

    }

    GET_V(stc->time_base_id    , tmp < nut->time_base_count);

    GET_V(stc->msb_pts_shift   , tmp < 16);

    stc->max_pts_distance= get_v(bc);

    GET_V(stc->decode_delay    , tmp < 1000); //sanity limit, raise this if moors law is true

    st->codec->has_b_frames= stc->decode_delay;

    get_v(bc); //stream flags

    GET_V(st->codec->extradata_size, tmp < (1<<30));

    if(st->codec->extradata_size){

        st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

        get_buffer(bc, st->codec->extradata, st->codec->extradata_size);

    }

    if (st->codec->codec_type == CODEC_TYPE_VIDEO){

        GET_V(st->codec->width , tmp > 0)

        GET_V(st->codec->height, tmp > 0)

        st->codec->sample_aspect_ratio.num= get_v(bc);

        st->codec->sample_aspect_ratio.den= get_v(bc);

        if((!st->codec->sample_aspect_ratio.num) != (!st->codec->sample_aspect_ratio.den)){

            av_log(s, AV_LOG_ERROR, "invalid aspect ratio\n");

            return -1;

        }

        get_v(bc); /* csp type */

    }else if (st->codec->codec_type == CODEC_TYPE_AUDIO){

        GET_V(st->codec->sample_rate , tmp > 0)

        tmp= get_v(bc); // samplerate_den

        if(tmp > st->codec->sample_rate){

            av_log(s, AV_LOG_ERROR, "bleh, libnut muxed this ;)\n");

            st->codec->sample_rate= tmp;

        }

        GET_V(st->codec->channels, tmp > 0)

    }

    if(skip_reserved(bc, end) || check_checksum(bc)){

        av_log(s, AV_LOG_ERROR, "Stream header %d checksum mismatch\n", stream_id);

        return -1;

    }

    stc->time_base= nut->time_base[stc->time_base_id];

    av_set_pts_info(s->streams[stream_id], 63, stc->time_base.num, stc->time_base.den);

    return 0;

}


static struct qcms_modular_transform * qcms_modular_transform_create_output ( qcms_profile * out ) {
 struct qcms_modular_transform * first_transform = NULL ;
 struct qcms_modular_transform * * next_transform = & first_transform ;
 if ( out -> B2A0 ) {
 struct qcms_modular_transform * lut_transform ;
 lut_transform = qcms_modular_transform_create_lut ( out -> B2A0 ) ;
 if ( ! lut_transform ) goto fail ;
 append_transform ( lut_transform , & next_transform ) ;
 }
 else if ( out -> mBA && out -> mBA -> num_in_channels == 3 && out -> mBA -> num_out_channels == 3 ) {
 struct qcms_modular_transform * lut_transform ;
 lut_transform = qcms_modular_transform_create_mAB ( out -> mBA ) ;
 if ( ! lut_transform ) goto fail ;
 append_transform ( lut_transform , & next_transform ) ;
 }
 else if ( out -> redTRC && out -> greenTRC && out -> blueTRC ) {
 struct qcms_modular_transform * transform ;
 transform = qcms_modular_transform_alloc ( ) ;
 if ( ! transform ) goto fail ;
 append_transform ( transform , & next_transform ) ;
 transform -> matrix = matrix_invert ( build_colorant_matrix ( out ) ) ;
 transform -> transform_module_fn = qcms_transform_module_matrix ;
 transform = qcms_modular_transform_alloc ( ) ;
 if ( ! transform ) goto fail ;
 append_transform ( transform , & next_transform ) ;
 transform -> matrix . m [ 0 ] [ 0 ] = 1.999969482421875f ;
 transform -> matrix . m [ 0 ] [ 1 ] = 0.f ;
 transform -> matrix . m [ 0 ] [ 2 ] = 0.f ;
 transform -> matrix . m [ 1 ] [ 0 ] = 0.f ;
 transform -> matrix . m [ 1 ] [ 1 ] = 1.999969482421875f ;
 transform -> matrix . m [ 1 ] [ 2 ] = 0.f ;
 transform -> matrix . m [ 2 ] [ 0 ] = 0.f ;
 transform -> matrix . m [ 2 ] [ 1 ] = 0.f ;
 transform -> matrix . m [ 2 ] [ 2 ] = 1.999969482421875f ;
 transform -> matrix . invalid = false ;
 transform -> transform_module_fn = qcms_transform_module_matrix ;
 transform = qcms_modular_transform_alloc ( ) ;
 if ( ! transform ) goto fail ;
 append_transform ( transform , & next_transform ) ;
 build_output_lut ( out -> redTRC , & transform -> output_gamma_lut_r , & transform -> output_gamma_lut_r_length ) ;
 build_output_lut ( out -> greenTRC , & transform -> output_gamma_lut_g , & transform -> output_gamma_lut_g_length ) ;
 build_output_lut ( out -> blueTRC , & transform -> output_gamma_lut_b , & transform -> output_gamma_lut_b_length ) ;
 transform -> transform_module_fn = qcms_transform_module_gamma_lut ;
 if ( ! transform -> output_gamma_lut_r || ! transform -> output_gamma_lut_g || ! transform -> output_gamma_lut_b ) {
 goto fail ;
 }
 }
 else {
 assert ( 0 && "Unsupported output profile workflow." ) ;
 return NULL ;
 }
 return first_transform ;
 fail : qcms_modular_transform_release ( first_transform ) ;
 return EMPTY_TRANSFORM_LIST ;
 }


OMX_ERRORTYPE  omx_vdec::set_callbacks(OMX_IN OMX_HANDLETYPE        hComp,
        OMX_IN OMX_CALLBACKTYPE* callbacks,
        OMX_IN OMX_PTR             appData)
{
 (void) hComp;
    m_cb       = *callbacks;
    DEBUG_PRINT_LOW("Callbacks Set %p %p %p",m_cb.EmptyBufferDone,\
            m_cb.EventHandler,m_cb.FillBufferDone);
    m_app_data =    appData;
 return OMX_ErrorNotImplemented;
}


inline const char *Holder::trace_name() const {
  if (trace_name_.empty()) { trace_name_ = "[" + outer_->name + "]"; }
  return trace_name_.c_str();
}


int SandboxIPCHandler::FindOrAddPath(const SkString& path) {
  int count = paths_.size();
  for (int i = 0; i < count; ++i) {
    if (path == paths_[i])
      return i;
  }
  paths_.emplace_back(path);
  return count;
}


static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out)
{
	jpc_rgn_t *rgn = &ms->parms.rgn;
	fprintf(out, "compno = %d; roisty = %d; roishift = %d\n",
	  rgn->compno, rgn->roisty, rgn->roishift);
	return 0;
}


void WebGLRenderingContextBase::EmitGLWarning(const char* function_name,
                                              const char* description) {
  if (synthesized_errors_to_console_) {
    String message =
        String("WebGL: ") + String(function_name) + ": " + String(description);
    PrintGLErrorToConsole(message);
  }
  probe::didFireWebGLWarning(canvas());
}


static double tget_double(const uint8_t **p, int le)

{

    av_alias64 i = { .u64 = le ? AV_RL64(*p) : AV_RB64(*p)};

    *p += 8;

    return i.f64;

}


CSSRuleList* CSSStyleSheet::rules(ExceptionState& exception_state) {
  return cssRules(exception_state);
}


void xmc4400EthEventHandler(NetInterface *interface)
{
   error_t error;

   //Packet received?
   if((ETH0->STATUS & ETH_STATUS_RI_Msk) != 0)
   {
      //Clear interrupt flag
      ETH0->STATUS = ETH_STATUS_RI_Msk;

      //Process all pending packets
      do
      {
         //Read incoming packet
         error = xmc4400EthReceivePacket(interface);

         //No more data in the receive buffer?
      } while(error != ERROR_BUFFER_EMPTY);
   }

   //Re-enable DMA interrupts
   ETH0->INTERRUPT_ENABLE = ETH_INTERRUPT_ENABLE_NIE_Msk |
      ETH_INTERRUPT_ENABLE_RIE_Msk | ETH_INTERRUPT_ENABLE_TIE_Msk;
}