error_t ipv6ForwardPacket(NetInterface *srcInterface, NetBuffer *ipPacket,
   size_t ipPacketOffset)
{
   error_t error;
   uint_t i;
   uint_t metric;
   uint_t prefixLen;
   bool_t match;
   size_t length;
   size_t destOffset;
   NetInterface *destInterface;
   NetBuffer *destBuffer;
   Ipv6Header *ipHeader;
   Ipv6RoutingTableEntry *entry;
   Ipv6Addr destIpAddr;
#if (ETH_SUPPORT == ENABLED)
   NetInterface *physicalInterface;
#endif

   //Silently drop any IP packets received on an interface that has
   //not been assigned a valid link-local address
   if(ipv6GetLinkLocalAddrState(srcInterface) != IPV6_ADDR_STATE_PREFERRED)
      return ERROR_NOT_CONFIGURED;

   //If routing is not enabled on the interface, then the router cannot
   //forward packets from the interface
   if(!srcInterface->ipv6Context.isRouter)
      return ERROR_FAILURE;

   //Calculate the length of the IPv6 packet
   length = netBufferGetLength(ipPacket) - ipPacketOffset;

   //Ensure the packet length is greater than 40 bytes
   if(length < sizeof(Ipv6Header))
      return ERROR_INVALID_LENGTH;

   //Point to the IPv6 header
   ipHeader = netBufferAt(ipPacket, ipPacketOffset);

   //Sanity check
   if(ipHeader == NULL)
      return ERROR_FAILURE;

   //An IPv6 packet with a source address of unspecified must never be
   //forwarded by an IPv6 router (refer to RFC section 3513 2.5.2)
   if(ipv6CompAddr(&ipHeader->srcAddr, &IPV6_UNSPECIFIED_ADDR))
      return ERROR_INVALID_ADDRESS;

   //The unspecified address must not be used as the destination address
   //of IPv6 packets (refer to RFC section 3513 2.5.2)
   if(ipv6CompAddr(&ipHeader->destAddr, &IPV6_UNSPECIFIED_ADDR))
      return ERROR_INVALID_ADDRESS;

   //An IPv6 packet with a destination address of loopback must never be
   //forwarded by an IPv6 router (refer to RFC 3513 section 2.5.3)
   if(ipv6CompAddr(&ipHeader->destAddr, &IPV6_LOOPBACK_ADDR))
      return ERROR_INVALID_ADDRESS;

   //Check whether the destination address is a link-local address
   if(ipv6IsLinkLocalUnicastAddr(&ipHeader->destAddr))
   {
      //Forward the packet on the same network interface
      destInterface = srcInterface;
      //Next hop
      destIpAddr = ipHeader->destAddr;
   }
   else
   {
      //Lowest metric value
      metric = UINT_MAX;
      //Longest prefix length
      prefixLen = 0;
      //Outgoing network interface
      destInterface = NULL;

      //Route determination process
      for(i = 0; i < IPV6_ROUTING_TABLE_SIZE; i++)
      {
         //Point to the current entry
         entry = &ipv6RoutingTable[i];

         //Valid entry?
         if(entry->valid && entry->interface != NULL)
         {
            //Clear flag
            match = FALSE;

            //Do not forward any IP packets to an interface that has not
            //been assigned a valid link-local address...
            if(ipv6GetLinkLocalAddrState(entry->interface) == IPV6_ADDR_STATE_PREFERRED)
            {
               //If routing is enabled on the interface, then the router
               //can forward packets to the interface
               if(entry->interface->ipv6Context.isRouter)
               {
                  //Compare the destination address with the current entry for a match
                  if(ipv6CompPrefix(&ipHeader->destAddr, &entry->prefix, entry->prefixLen))
                  {
                     //The longest matching route is the most specific route to the
                     //destination IPv6 address...
                     if(entry->prefixLen > prefixLen)
                     {
                        //Give the current route the higher precedence
                        match = TRUE;
                     }
                     else if(entry->prefixLen == prefixLen)
                     {
                        //If multiple entries with the longest match are found, the
                        //router uses the lowest metric to select the best route
                        if(entry->metric < metric)
                        {
                           //Give the current route the higher precedence
                           match = TRUE;
                        }
                     }
                  }
               }
            }

            //Matching entry?
            if(match)
            {
               //Select the current route
               metric = entry->metric;
               prefixLen = entry->prefixLen;

               //Outgoing interface on which to forward the packet
               destInterface = entry->interface;

               //Next hop
               if(!ipv6CompAddr(&entry->nextHop, &IPV6_UNSPECIFIED_ADDR))
                  destIpAddr = entry->nextHop;
               else
                  destIpAddr = ipHeader->destAddr;
            }
         }
      }
   }

   //No route to the destination?
   if(destInterface == NULL)
   {
      //A Destination Unreachable message should be generated by a router
      //in response to a packet that cannot be delivered
      icmpv6SendErrorMessage(srcInterface, ICMPV6_TYPE_DEST_UNREACHABLE,
         ICMPV6_CODE_NO_ROUTE_TO_DEST, 0, ipPacket, ipPacketOffset);

      //Exit immediately
      return ERROR_NO_ROUTE;
   }

   //Check whether the length of the IPv6 packet is larger than the link MTU
   if(length > destInterface->ipv6Context.linkMtu)
   {
      //A Packet Too Big must be sent by a router in response to a packet
      //that it cannot forward because the packet is larger than the MTU
      //of the outgoing link
      icmpv6SendErrorMessage(srcInterface, ICMPV6_TYPE_PACKET_TOO_BIG,
         0, destInterface->ipv6Context.linkMtu, ipPacket, ipPacketOffset);

      //Exit immediately
      return ERROR_INVALID_LENGTH;
   }

   //Check whether the packet is explicitly addressed to the router itself
   if(!ipv6CheckDestAddr(destInterface, &ipHeader->destAddr))
   {
      //Valid unicast address?
      if(!ipv6IsMulticastAddr(&ipHeader->destAddr))
      {
         //Process IPv6 packet
         //ipv6ProcessPacket(destInterface, ipPacket, ipPacketOffset);
         //Exit immediately
         return NO_ERROR;
      }
   }

   //Check whether the IPv6 packet is about to be sent out the interface
   //on which it was received
   if(destInterface == srcInterface)
   {
#if (NDP_SUPPORT == ENABLED)
      //A router should send a Redirect message whenever it forwards a packet
      //that is not explicitly addressed to itself in which the source address
      //identifies a neighbor, and
      if(ipv6IsOnLink(srcInterface, &ipHeader->srcAddr))
      {
         //The router determines that a better first-hop node resides on the
         //same link as the sending node for the destination address of the
         //packet being forwarded, and
         if(ipv6IsOnLink(destInterface, &destIpAddr))
         {
            //The destination address of the packet is not a multicast address
            if(!ipv6IsMulticastAddr(&ipHeader->destAddr))
            {
               //Transmit a Redirect message
               ndpSendRedirect(srcInterface, &destIpAddr, ipPacket, ipPacketOffset);
            }
         }
      }
#endif
   }
   else
   {
      //Check whether the scope of the source address is smaller than the
      //scope of the destination address
      if(ipv6GetAddrScope(&ipHeader->srcAddr) < ipv6GetAddrScope(&ipHeader->destAddr))
      {
         //A Destination Unreachable message should be generated by a router
         //in response to a packet that cannot be delivered without leaving
         //the scope of the source address
         icmpv6SendErrorMessage(srcInterface, ICMPV6_TYPE_DEST_UNREACHABLE,
            ICMPV6_CODE_BEYOND_SCOPE_OF_SRC_ADDR, 0, ipPacket, ipPacketOffset);

         //Exit immediately
         return ERROR_INVALID_ADDRESS;
      }
   }

   //Hop Limit exceeded in transit?
   if(ipHeader->hopLimit <= 1)
   {
      //If a router receives a packet with a Hop Limit of zero, or if a router
      //decrements a packet's Hop Limit to zero, it must discard the packet
      //and originate an ICMPv6 Time Exceeded message
      icmpv6SendErrorMessage(srcInterface, ICMPV6_TYPE_TIME_EXCEEDED,
         ICMPV6_CODE_HOP_LIMIT_EXCEEDED, 0, ipPacket, ipPacketOffset);

      //Exit immediately
      return ERROR_FAILURE;
   }

   //The Hop-by-Hop Options header, when present, must immediately follow
   //the IPv6 header. Its presence is indicated by the value zero in the
   //Next Header field of the IPv6 header
   if(ipHeader->nextHeader == IPV6_HOP_BY_HOP_OPT_HEADER)
   {
      //Point to the extension header
      size_t headerOffset = ipPacketOffset + sizeof(Ipv6Header);

      //Calculate the offset of the Next Header field
      size_t nextHeaderOffset = ipPacketOffset +
         &ipHeader->nextHeader - (uint8_t *) ipHeader;

      //The Hop-by-Hop Options header is used to carry optional information
      //that must be examined by every node along a packet's delivery path
      error = ipv6ParseHopByHopOptHeader(srcInterface,
         ipPacket, ipPacketOffset, &headerOffset, &nextHeaderOffset);

      //Any error while processing the extension header?
      if(error)
         return error;
   }

   //Allocate a buffer to hold the IPv6 packet
   destBuffer = ethAllocBuffer(length, &destOffset);

   //Successful memory allocation?
   if(destBuffer != NULL)
   {
      //Copy IPv6 header
      error = netBufferCopy(destBuffer, destOffset, ipPacket, ipPacketOffset,
         length);

      //Check status code
      if(!error)
      {
         //Point to the IPv6 header
         ipHeader = netBufferAt(destBuffer, destOffset);
         //Every time a router forwards a packet, it decrements the Hop Limit field
         ipHeader->hopLimit--;

#if (ETH_SUPPORT == ENABLED)
         //Point to the physical interface
         physicalInterface = nicGetPhysicalInterface(destInterface);

         //Ethernet interface?
         if(physicalInterface->nicDriver != NULL &&
            physicalInterface->nicDriver->type == NIC_TYPE_ETHERNET)
         {
            MacAddr destMacAddr;
            NetTxAncillary ancillary;

            //Additional options can be passed to the stack along with the packet
            ancillary = NET_DEFAULT_TX_ANCILLARY;

            //Destination IPv6 address
            if(ipv6CompAddr(&destIpAddr, &IPV6_UNSPECIFIED_ADDR))
               destIpAddr = ipHeader->destAddr;

            //Check whether the destination IPv6 address is a multicast address?
            if(ipv6IsMulticastAddr(&destIpAddr))
            {
               //Map IPv6 multicast address to MAC-layer multicast address
               error = ipv6MapMulticastAddrToMac(&destIpAddr, &destMacAddr);
            }
            else
            {
               //Resolve host address using Neighbor Discovery protocol
               error = ndpResolve(destInterface, &destIpAddr, &destMacAddr);
            }

            //Successful address resolution?
            if(!error)
            {
               //Debug message
               TRACE_INFO("Forwarding IPv6 packet to %s (%" PRIuSIZE " bytes)...\r\n",
                  destInterface->name, length);
               //Dump IP header contents for debugging purpose
               ipv6DumpHeader(ipHeader);

               //Send Ethernet frame
               error = ethSendFrame(destInterface, NULL, &destMacAddr, ETH_TYPE_IPV6,
                  destBuffer, destOffset, &ancillary);
            }
            //Address resolution is in progress?
            else if(error == ERROR_IN_PROGRESS)
            {
               //Debug message
               TRACE_INFO("Enqueuing IPv6 packet (%" PRIuSIZE " bytes)...\r\n", length);
               //Dump IP header contents for debugging purpose
               ipv6DumpHeader(ipHeader);

               //Enqueue packets waiting for address resolution
               error = ndpEnqueuePacket(srcInterface, destInterface, &destIpAddr,
                  destBuffer, destOffset, &ancillary);
            }
            //Address resolution failed?
            else
            {
               //Debug message
               TRACE_WARNING("Cannot map IPv6 address to Ethernet address!\r\n");
            }
         }
         else
#endif
#if (PPP_SUPPORT == ENABLED)
         //PPP interface?
         if(destInterface->nicDriver != NULL &&
            destInterface->nicDriver->type == NIC_TYPE_PPP)
         {
            //Debug message
            TRACE_INFO("Forwarding IPv6 packet to %s (%" PRIuSIZE " bytes)...\r\n",
               destInterface->name, length);
            //Dump IP header contents for debugging purpose
            ipv6DumpHeader(ipHeader);

            //Send PPP frame
            error = pppSendFrame(destInterface, destBuffer, destOffset,
               PPP_PROTOCOL_IPV6);
         }
         else
#endif
         //6LoWPAN interface?
         if(destInterface->nicDriver != NULL &&
            destInterface->nicDriver->type == NIC_TYPE_6LOWPAN)
         {
            NetTxAncillary ancillary;

            //Debug message
            TRACE_INFO("Forwarding IPv6 packet to %s (%" PRIuSIZE " bytes)...\r\n",
               destInterface->name, length);
            //Dump IP header contents for debugging purpose
            ipv6DumpHeader(ipHeader);

            //Additional options can be passed to the stack along with the packet
            ancillary = NET_DEFAULT_TX_ANCILLARY;

            //Send the packet over the specified link
            error = nicSendPacket(destInterface, destBuffer, destOffset,
               &ancillary);
         }
         else
         //Unknown interface type?
         {
            //Report an error
            error = ERROR_INVALID_INTERFACE;
         }
      }

      //Free previously allocated memory
      netBufferFree(destBuffer);
   }
   else
   {
      //Failed to allocate memory
      error = ERROR_OUT_OF_MEMORY;
   }

   //Return status code
   return error;
}


Perl_my_pclose(pTHX_ PerlIO *ptr)
{
    /* Needs work for PerlIO ! */
    FILE * const f = PerlIO_findFILE(ptr);
    I32 result = djgpp_pclose(f);
    result = (result << 8) & 0xff00;
    PerlIO_releaseFILE(ptr,f);
    return result;
}


void ResourceDispatcherHostImpl::BeginSaveFile(
    const GURL& url,
    const content::Referrer& referrer,
    int child_id,
    int route_id,
    ResourceContext* context) {
  if (is_shutdown_)
    return;

  char url_buf[128];
  base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
  base::debug::Alias(url_buf);
  CHECK(ContainsKey(active_resource_contexts_, context));

  scoped_refptr<ResourceHandler> handler(
      new SaveFileResourceHandler(child_id,
                                  route_id,
                                  url,
                                  save_file_manager_.get()));
  request_id_--;

  const net::URLRequestContext* request_context = context->GetRequestContext();
  bool known_proto =
      request_context->job_factory()->IsHandledURL(url);
  if (!known_proto) {
    NOTREACHED();
    return;
  }

  net::URLRequest* request = new net::URLRequest(url, this);
  request->set_method("GET");
  request->set_referrer(MaybeStripReferrer(referrer.url).spec());
  webkit_glue::ConfigureURLRequestForReferrerPolicy(request, referrer.policy);
  request->set_load_flags(net::LOAD_PREFERRING_CACHE);
  request->set_context(context->GetRequestContext());

  ResourceRequestInfoImpl* extra_info =
      CreateRequestInfo(handler, child_id, route_id, false, context);
  extra_info->AssociateWithRequest(request);  // Request takes ownership.

  BeginRequestInternal(request);
}


static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t server)
{
	if (server)
		return udhcp_send_kernel_packet(packet,
			ciaddr, CLIENT_PORT,
			server, SERVER_PORT);
	return raw_bcast_from_client_config_ifindex(packet, ciaddr);
}


png_write_info(png_structp png_ptr, png_infop info_ptr)
{
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
   int i;
#endif

   png_debug(1, "in png_write_info");

   if (png_ptr == NULL || info_ptr == NULL)
      return;

   png_write_info_before_PLTE(png_ptr, info_ptr);

   if (info_ptr->valid & PNG_INFO_PLTE)
      png_write_PLTE(png_ptr, info_ptr->palette,
         (png_uint_32)info_ptr->num_palette);
   else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
      png_error(png_ptr, "Valid palette required for paletted images");

#ifdef PNG_WRITE_tRNS_SUPPORTED
   if (info_ptr->valid & PNG_INFO_tRNS)
   {
#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
      /* Invert the alpha channel (in tRNS) */
      if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
         info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
      {
         int j;
         for (j = 0; j<(int)info_ptr->num_trans; j++)
            info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
      }
#endif
      png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
         info_ptr->num_trans, info_ptr->color_type);
   }
#endif
#ifdef PNG_WRITE_bKGD_SUPPORTED
   if (info_ptr->valid & PNG_INFO_bKGD)
      png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
#endif
#ifdef PNG_WRITE_hIST_SUPPORTED
   if (info_ptr->valid & PNG_INFO_hIST)
      png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
#endif
#ifdef PNG_WRITE_oFFs_SUPPORTED
   if (info_ptr->valid & PNG_INFO_oFFs)
      png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
         info_ptr->offset_unit_type);
#endif
#ifdef PNG_WRITE_pCAL_SUPPORTED
   if (info_ptr->valid & PNG_INFO_pCAL)
      png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
         info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
         info_ptr->pcal_units, info_ptr->pcal_params);
#endif

#ifdef PNG_sCAL_SUPPORTED
   if (info_ptr->valid & PNG_INFO_sCAL)
#ifdef PNG_WRITE_sCAL_SUPPORTED
#if defined(PNG_FLOATING_POINT_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
      png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
          info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
#else /* !FLOATING_POINT */
#ifdef PNG_FIXED_POINT_SUPPORTED
      png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
          info_ptr->scal_s_width, info_ptr->scal_s_height);
#endif /* FIXED_POINT */
#endif /* FLOATING_POINT */
#else  /* !WRITE_sCAL */
      png_warning(png_ptr,
          "png_write_sCAL not supported; sCAL chunk not written.");
#endif /* WRITE_sCAL */
#endif /* sCAL */

#ifdef PNG_WRITE_pHYs_SUPPORTED
   if (info_ptr->valid & PNG_INFO_pHYs)
      png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
         info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
#endif /* pHYs */

#ifdef PNG_WRITE_tIME_SUPPORTED
   if (info_ptr->valid & PNG_INFO_tIME)
   {
      png_write_tIME(png_ptr, &(info_ptr->mod_time));
      png_ptr->mode |= PNG_WROTE_tIME;
   }
#endif /* tIME */

#ifdef PNG_WRITE_sPLT_SUPPORTED
   if (info_ptr->valid & PNG_INFO_sPLT)
     for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
       png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
#endif /* sPLT */

#ifdef PNG_WRITE_TEXT_SUPPORTED
   /* Check to see if we need to write text chunks */
   for (i = 0; i < info_ptr->num_text; i++)
   {
      png_debug2(2, "Writing header text chunk %d, type %d", i,
         info_ptr->text[i].compression);
      /* An internationalized chunk? */
      if (info_ptr->text[i].compression > 0)
      {
#ifdef PNG_WRITE_iTXt_SUPPORTED
          /* Write international chunk */
          png_write_iTXt(png_ptr,
                         info_ptr->text[i].compression,
                         info_ptr->text[i].key,
                         info_ptr->text[i].lang,
                         info_ptr->text[i].lang_key,
                         info_ptr->text[i].text);
#else
          png_warning(png_ptr, "Unable to write international text");
#endif
          /* Mark this chunk as written */
          info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
      }
      /* If we want a compressed text chunk */
      else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
      {
#ifdef PNG_WRITE_zTXt_SUPPORTED
         /* Write compressed chunk */
         png_write_zTXt(png_ptr, info_ptr->text[i].key,
            info_ptr->text[i].text, 0,
            info_ptr->text[i].compression);
#else
         png_warning(png_ptr, "Unable to write compressed text");
#endif
         /* Mark this chunk as written */
         info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
      }
      else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
      {
#ifdef PNG_WRITE_tEXt_SUPPORTED
         /* Write uncompressed chunk */
         png_write_tEXt(png_ptr, info_ptr->text[i].key,
                         info_ptr->text[i].text,
                         0);
         /* Mark this chunk as written */
         info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
#else
         /* Can't get here */
         png_warning(png_ptr, "Unable to write uncompressed text");
#endif
      }
   }
#endif /* tEXt */

#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
   if (info_ptr->unknown_chunks_num)
   {
      png_unknown_chunk *up;

      png_debug(5, "writing extra chunks");

      for (up = info_ptr->unknown_chunks;
           up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
           up++)
      {
         int keep = png_handle_as_unknown(png_ptr, up->name);
         if (keep != PNG_HANDLE_CHUNK_NEVER &&
            up->location && (up->location & PNG_HAVE_PLTE) &&
            !(up->location & PNG_HAVE_IDAT) &&
            !(up->location & PNG_AFTER_IDAT) &&
            ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
            (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
         {
            png_write_chunk(png_ptr, up->name, up->data, up->size);
         }
      }
   }
#endif
}


static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
{
    AVStream *st = s->streams[stream_index];
    APEContext *ape = s->priv_data;
    int index = av_index_search_timestamp(st, timestamp, flags);

    if (index < 0)
        return -1;

    ape->currentframe = index;
    return 0;
}


static int copy_urb_data_to_user(u8 __user *userbuffer, struct urb *urb)
{
	unsigned i, len, size;

	if (urb->number_of_packets > 0)		/* Isochronous */
		len = urb->transfer_buffer_length;
	else					/* Non-Isoc */
		len = urb->actual_length;

	if (urb->num_sgs == 0) {
		if (copy_to_user(userbuffer, urb->transfer_buffer, len))
			return -EFAULT;
		return 0;
	}

	for (i = 0; i < urb->num_sgs && len; i++) {
		size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len;
		if (copy_to_user(userbuffer, sg_virt(&urb->sg[i]), size))
			return -EFAULT;
		userbuffer += size;
		len -= size;
	}

	return 0;
}


static int find_and_lock_cache_page(struct nfs_readdir_descriptor *desc)
{
	struct inode *inode = file_inode(desc->file);
	struct nfs_inode *nfsi = NFS_I(inode);
	__be32 verf[NFS_DIR_VERIFIER_SIZE];
	int res;

	desc->page = nfs_readdir_page_get_cached(desc);
	if (!desc->page)
		return -ENOMEM;
	if (nfs_readdir_page_needs_filling(desc->page)) {
		res = nfs_readdir_xdr_to_array(desc, nfsi->cookieverf, verf,
					       &desc->page, 1);
		if (res < 0) {
			nfs_readdir_page_unlock_and_put_cached(desc);
			if (res == -EBADCOOKIE || res == -ENOTSYNC) {
				invalidate_inode_pages2(desc->file->f_mapping);
				desc->page_index = 0;
				return -EAGAIN;
			}
			return res;
		}
		/*
		 * Set the cookie verifier if the page cache was empty
		 */
		if (desc->page_index == 0)
			memcpy(nfsi->cookieverf, verf,
			       sizeof(nfsi->cookieverf));
	}
	res = nfs_readdir_search_array(desc);
	if (res == 0)
		return 0;
	nfs_readdir_page_unlock_and_put_cached(desc);
	return res;
}


bool ResourceFetcher::ResourceNeedsLoad(Resource* resource,
                                        const FetchRequest& request,
                                        RevalidationPolicy policy) {
  if (resource->GetType() == Resource::kFont && !request.IsLinkPreload())
    return false;
  if (resource->IsImage() && ShouldDeferImageLoad(resource->Url()))
    return false;
  return policy != kUse || resource->StillNeedsLoad();
}


 ACTION_P(ScheduleRenameCallback, new_path) {
   BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                           base::Bind(arg3, new_path));
 }


int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
{
	int ret = 0;

	if (type)
		return -EINVAL;

	ret = kvm_alloc_stage2_pgd(kvm);
	if (ret)
		goto out_fail_alloc;

	ret = create_hyp_mappings(kvm, kvm + 1);
	if (ret)
		goto out_free_stage2_pgd;

	/* Mark the initial VMID generation invalid */
	kvm->arch.vmid_gen = 0;

	return ret;
out_free_stage2_pgd:
	kvm_free_stage2_pgd(kvm);
out_fail_alloc:
	return ret;
}


static av_cold int vp9_decode_free(AVCodecContext *ctx)

{

    VP9Context *s = ctx->priv_data;

    int i;

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

        if (s->frames[i].tf.f->data[0])

            vp9_unref_frame(ctx, &s->frames[i]);

        av_frame_free(&s->frames[i].tf.f);

    }

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

        if (s->refs[i].f->data[0])

            ff_thread_release_buffer(ctx, &s->refs[i]);

        av_frame_free(&s->refs[i].f);

        if (s->next_refs[i].f->data[0])

            ff_thread_release_buffer(ctx, &s->next_refs[i]);

        av_frame_free(&s->next_refs[i].f);

    }

    av_freep(&s->above_partition_ctx);

    av_freep(&s->c_b);

    s->c_b_size = 0;

    av_freep(&s->b_base);

    av_freep(&s->block_base);

    return 0;

}


void qeth_buffer_reclaim_work(struct work_struct *work)
{
	struct qeth_card *card = container_of(work, struct qeth_card,
		buffer_reclaim_work.work);

	QETH_CARD_TEXT_(card, 2, "brw:%x", card->reclaim_index);
	qeth_queue_input_buffer(card, card->reclaim_index);
}


static jboolean android_net_wifi_set_Country_Code_Hal(JNIEnv *env,jclass cls, jint iface,
        jstring country_code) {

 JNIHelper helper(env);
    wifi_interface_handle handle = getIfaceHandle(helper, cls, iface);

 ScopedUtfChars chars(env, country_code);
 const char *country = chars.c_str();

    ALOGD("set country code: %s", country);
    wifi_error res = hal_fn.wifi_set_country_code(handle, country);
 return res == WIFI_SUCCESS;
}


Jsi_ListEntry* Jsi_ListSearchNext (Jsi_ListSearch *searchPtr)
{
    Jsi_ListEntry *lptr = searchPtr->nextEntryPtr;
    searchPtr->nextEntryPtr = (lptr?(searchPtr->flags & JSI_LIST_REVERSE ? Jsi_ListEntryPrev(lptr): Jsi_ListEntryNext(lptr)):NULL);
    return lptr;
}


BerElement * ber_alloc_t ( int options ) {
 BerElement * ber ;
 ber = ( BerElement * ) LBER_CALLOC ( 1 , sizeof ( BerElement ) ) ;
 if ( ber == NULL ) {
 return NULL ;
 }
 ber -> ber_valid = LBER_VALID_BERELEMENT ;
 ber -> ber_tag = LBER_DEFAULT ;
 ber -> ber_options = options ;
 ber -> ber_debug = ber_int_debug ;
 assert ( LBER_VALID ( ber ) ) ;
 return ber ;
 }


status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
{
 int32_t useAshmem;
 status_t status = readInt32(&useAshmem);
 if (status) return status;

 if (!useAshmem) {
        ALOGV("readBlob: read in place");
 const void* ptr = readInplace(len);
 if (!ptr) return BAD_VALUE;

        outBlob->init(false /*mapped*/, const_cast<void*>(ptr), len);
 return NO_ERROR;
 }

    ALOGV("readBlob: read from ashmem");
 int fd = readFileDescriptor();
 if (fd == int(BAD_TYPE)) return BAD_VALUE;

 void* ptr = ::mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
 if (ptr == MAP_FAILED) return NO_MEMORY;

    outBlob->init(true /*mapped*/, ptr, len);
 return NO_ERROR;
}


armv6pmu_handle_irq(int irq_num,
		    void *dev)
{
	unsigned long pmcr = armv6_pmcr_read();
	struct perf_sample_data data;
	struct cpu_hw_events *cpuc;
	struct pt_regs *regs;
	int idx;

	if (!armv6_pmcr_has_overflowed(pmcr))
		return IRQ_NONE;

	regs = get_irq_regs();

	/*
	 * The interrupts are cleared by writing the overflow flags back to
	 * the control register. All of the other bits don't have any effect
	 * if they are rewritten, so write the whole value back.
	 */
	armv6_pmcr_write(pmcr);

	perf_sample_data_init(&data, 0);

	cpuc = &__get_cpu_var(cpu_hw_events);
	for (idx = 0; idx <= armpmu->num_events; ++idx) {
		struct perf_event *event = cpuc->events[idx];
		struct hw_perf_event *hwc;

		if (!test_bit(idx, cpuc->active_mask))
			continue;

		/*
		 * We have a single interrupt for all counters. Check that
		 * each counter has overflowed before we process it.
		 */
		if (!armv6_pmcr_counter_has_overflowed(pmcr, idx))
			continue;

		hwc = &event->hw;
		armpmu_event_update(event, hwc, idx, 1);
		data.period = event->hw.last_period;
		if (!armpmu_event_set_period(event, hwc, idx))
			continue;

		if (perf_event_overflow(event, 0, &data, regs))
			armpmu->disable(hwc, idx);
	}

	/*
	 * Handle the pending perf events.
	 *
	 * Note: this call *must* be run with interrupts disabled. For
	 * platforms that can have the PMU interrupts raised as an NMI, this
	 * will not work.
	 */
	irq_work_run();

	return IRQ_HANDLED;
}


const char *StreamTcpSsnStateAsString(const TcpSession *ssn)
{
    if (ssn == NULL)
        return NULL;
    return StreamTcpStateAsString(ssn->state);
}


static inline void drop_fpu(struct task_struct *tsk)
{
	/*
	 * Forget coprocessor state..
	 */
	preempt_disable();
	tsk->thread.fpu_counter = 0;
	__drop_fpu(tsk);
	clear_used_math();
	preempt_enable();
}


void RenderThreadImpl::OnNetworkTypeChanged(
    net::NetworkChangeNotifier::ConnectionType type) {
  EnsureWebKitInitialized();
  bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
  WebNetworkStateNotifier::setOnLine(online);
  FOR_EACH_OBSERVER(
      RenderProcessObserver, observers_, NetworkStateChanged(online));
  WebNetworkStateNotifier::setWebConnectionType(
      NetConnectionTypeToWebConnectionType(type));
}


PERL_STATIC_INLINE IV*
S_get_invlist_previous_index_addr(SV* invlist)
{
    /* Return the address of the IV that is reserved to hold the cached index
     * */
    PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;

    assert(is_invlist(invlist));

    return &(((XINVLIST*) SvANY(invlist))->prev_index);


 void HWNDMessageHandler::OnEnterSizeMove() {
  in_size_move_loop_ = true;

  // Please refer to the comments in the OnSize function about the scrollbar
  // hack.
  // Hide the Windows scrollbar if the scroll styles are present to ensure
  // that a paint flicker does not occur while sizing.
  if (needs_scroll_styles_)
    ShowScrollBar(hwnd(), SB_BOTH, FALSE);

   delegate_->HandleBeginWMSizeMove();
   SetMsgHandled(FALSE);
 }


static int pci_unin_agp_init_device(SysBusDevice *dev)

{

    UNINState *s;

    int pci_mem_config, pci_mem_data;

    /* Uninorth AGP bus */

    s = FROM_SYSBUS(UNINState, dev);

    pci_mem_config = cpu_register_io_memory(pci_unin_config_read,

                                            pci_unin_config_write, s);

    pci_mem_data = cpu_register_io_memory(pci_unin_main_read,

                                          pci_unin_main_write, &s->host_state);

    sysbus_init_mmio(dev, 0x1000, pci_mem_config);

    sysbus_init_mmio(dev, 0x1000, pci_mem_data);

    return 0;

}


test_bson_append_maxkey (void)
{
   bson_t *b;
   bson_t *b2;

   b = bson_new ();
   BSON_ASSERT (bson_append_maxkey (b, "maxkey", -1));
   b2 = get_bson ("test37.bson");
   BSON_ASSERT_BSON_EQUAL (b, b2);
   bson_destroy (b);
   bson_destroy (b2);
}


static const char * read_line_input(char * line, int maxSize, Bool showContent) {
	char read;
	int i = 0;
	if (fflush( stderr ))
		perror("Failed to flush buffer %s");
	do {
		line[i] = '\0';
		if (i >= maxSize - 1)
			return line;
		read = getch();
		if (read == 8 || read == 127) {
			if (i > 0) {
				fprintf(stderr, "\b \b");
				i--;
			}
		} else if (read > 32) {
			fputc(showContent ? read : '*', stderr);
			line[i++] = read;
		}
		fflush(stderr);
	} while (read != '\n');
	if (!read)
		return 0;
	return line;
}


    inline void writeString(const char* str) {
      U32 len = strlen(str);
      writeU32(len);
      writeBytes(str, len);
    }


void setJSTestObjDateSequenceAttr(ExecState* exec, JSObject* thisObject, JSValue value)
{
    JSTestObj* castedThis = jsCast<JSTestObj*>(thisObject);
    TestObj* impl = static_cast<TestObj*>(castedThis->impl());
    impl->setDateSequenceAttr(toNativeArray<Date>(exec, value));
}


static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
{
	struct task_group *tg = css_tg(css);

	/*
	 * Relies on the RCU grace period between css_released() and this.
	 */
	sched_free_group(tg);
}


static int sd_major(int major_idx)
{
	switch (major_idx) {
	case 0:
		return SCSI_DISK0_MAJOR;
	case 1 ... 7:
		return SCSI_DISK1_MAJOR + major_idx - 1;
	case 8 ... 15:
		return SCSI_DISK8_MAJOR + major_idx - 8;
	default:
		BUG();
		return 0;	/* shut up gcc */
	}
}


int enc_untrusted_pwrite64(int fd, const void *buf, size_t count,
                           off_t offset) {
  return EnsureInitializedAndDispatchSyscall(asylo::system_call::kSYS_pwrite64,
                                             fd, buf, count, offset);
}


int kvm_arch_put_registers(CPUState *env, int level)

{

    int ret;

    assert(cpu_is_stopped(env) || qemu_cpu_self(env));

    ret = kvm_getput_regs(env, 1);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_xsave(env);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_xcrs(env);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_sregs(env);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_msrs(env, level);

    if (ret < 0) {

        return ret;

    }

    if (level >= KVM_PUT_RESET_STATE) {

        ret = kvm_put_mp_state(env);

        if (ret < 0) {

            return ret;

        }

    }

    ret = kvm_put_vcpu_events(env, level);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_debugregs(env);

    if (ret < 0) {

        return ret;

    }

    /* must be last */

    ret = kvm_guest_debug_workarounds(env);

    if (ret < 0) {

        return ret;

    }

    return 0;

}


static void exposeJSAccessorsLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
    TestObjectPythonV8Internal::exposeJSAccessorsLongAttributeAttributeGetter(info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


int ipmi_unregister_for_cmd(struct ipmi_user *user,
			    unsigned char netfn,
			    unsigned char cmd,
			    unsigned int  chans)
{
	struct ipmi_smi *intf = user->intf;
	struct cmd_rcvr *rcvr;
	struct cmd_rcvr *rcvrs = NULL;
	int i, rv = -ENOENT, index;

	user = acquire_ipmi_user(user, &index);
	if (!user)
		return -ENODEV;

	mutex_lock(&intf->cmd_rcvrs_mutex);
	for (i = 0; i < IPMI_NUM_CHANNELS; i++) {
		if (((1 << i) & chans) == 0)
			continue;
		rcvr = find_cmd_rcvr(intf, netfn, cmd, i);
		if (rcvr == NULL)
			continue;
		if (rcvr->user == user) {
			rv = 0;
			rcvr->chans &= ~chans;
			if (rcvr->chans == 0) {
				list_del_rcu(&rcvr->link);
				rcvr->next = rcvrs;
				rcvrs = rcvr;
			}
		}
	}
	mutex_unlock(&intf->cmd_rcvrs_mutex);
	synchronize_rcu();
	release_ipmi_user(user, index);
	while (rcvrs) {
		smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_COMMANDS);
		rcvr = rcvrs;
		rcvrs = rcvr->next;
		kfree(rcvr);
	}

	return rv;
}


bool webkit_web_frame_pause_transition(WebKitWebFrame* frame, const gchar* name, double time, const gchar* element)
{
    ASSERT(core(frame));
    Element* coreElement = core(frame)->document()->getElementById(AtomicString(element));
    if (!coreElement || !coreElement->renderer())
        return false;
    return core(frame)->animation()->pauseTransitionAtTime(coreElement->renderer(), AtomicString(name), time);
}


static inline void __user *kvm_get_attr_addr(struct kvm_device_attr *attr)
{
	void __user *uaddr = (void __user*)(unsigned long)attr->addr;

	if ((u64)(unsigned long)uaddr != attr->addr)
		return ERR_PTR_USR(-EFAULT);
	return uaddr;
}


void Ogg::XiphComment::setGenre(const String &s)
{
  addField("GENRE", s);
}


void RenderViewImpl::OnSelectAll() {
  if (!webview())
    return;

  base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
  webview()->focusedFrame()->executeCommand(
      WebString::fromUTF8("SelectAll"));
}


ast_for_itercomp(struct compiling *c, const node *n, int type)
{
    /* testlist_comp: (test|star_expr)
     *                ( comp_for | (',' (test|star_expr))* [','] ) */
    expr_ty elt;
    asdl_seq *comps;
    node *ch;

    assert(NCH(n) > 1);

    ch = CHILD(n, 0);
    elt = ast_for_expr(c, ch);
    if (!elt)
        return NULL;
    if (elt->kind == Starred_kind) {
        ast_error(c, ch, "iterable unpacking cannot be used in comprehension");
        return NULL;
    }

    comps = ast_for_comprehension(c, CHILD(n, 1));
    if (!comps)
        return NULL;

    if (type == COMP_GENEXP)
        return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
    else if (type == COMP_LISTCOMP)
        return ListComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
    else if (type == COMP_SETCOMP)
        return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
    else
        /* Should never happen */
        return NULL;
}


fep_client_forward_key_event (FepClient      *client,
                              unsigned int    keyval,
                              FepModifierType modifiers)
{
  FepControlMessage message;

  message.command = FEP_CONTROL_FORWARD_KEY_EVENT;
  _fep_control_message_alloc_args (&message, 2);
  _fep_control_message_write_uint32_arg (&message, 0, keyval);
  _fep_control_message_write_uint32_arg (&message, 1, modifiers);

  if (client->filter_running)
    client->messages = _fep_append_control_message (client->messages, &message);
  else
    _fep_write_control_message (client->control, &message);
  _fep_control_message_free_args (&message);
}


static void fft(AC3MDCTContext *mdct, IComplex *z, int ln)

{

    int j, l, np, np2;

    int nblocks, nloops;

    register IComplex *p,*q;

    int tmp_re, tmp_im;

    np = 1 << ln;

    /* reverse */

    for (j = 0; j < np; j++) {

        int k = av_reverse[j] >> (8 - ln);

        if (k < j)

            FFSWAP(IComplex, z[k], z[j]);

    }

    /* pass 0 */

    p = &z[0];

    j = np >> 1;

    do {

        BF(p[0].re, p[0].im, p[1].re, p[1].im,

           p[0].re, p[0].im, p[1].re, p[1].im);

        p += 2;

    } while (--j);

    /* pass 1 */

    p = &z[0];

    j = np >> 2;

    do {

        BF(p[0].re, p[0].im, p[2].re,  p[2].im,

           p[0].re, p[0].im, p[2].re,  p[2].im);

        BF(p[1].re, p[1].im, p[3].re,  p[3].im,

           p[1].re, p[1].im, p[3].im, -p[3].re);

        p+=4;

    } while (--j);

    /* pass 2 .. ln-1 */

    nblocks = np >> 3;

    nloops  =  1 << 2;

    np2     = np >> 1;

    do {

        p = z;

        q = z + nloops;

        for (j = 0; j < nblocks; j++) {

            BF(p->re, p->im, q->re, q->im,

               p->re, p->im, q->re, q->im);

            p++;

            q++;

            for(l = nblocks; l < np2; l += nblocks) {

                CMUL(tmp_re, tmp_im, mdct->costab[l], -mdct->sintab[l], q->re, q->im);

                BF(p->re, p->im, q->re,  q->im,

                   p->re, p->im, tmp_re, tmp_im);

                p++;

                q++;

            }

            p += nloops;

            q += nloops;

        }

        nblocks = nblocks >> 1;

        nloops  = nloops  << 1;

    } while (nblocks);

}


rpmVerifyAttrs rpmfilesVerify(rpmfiles fi, int ix, rpmVerifyAttrs omitMask)
{
    rpm_mode_t fmode = rpmfilesFMode(fi, ix);
    rpmfileAttrs fileAttrs = rpmfilesFFlags(fi, ix);
    rpmVerifyAttrs flags = rpmfilesVFlags(fi, ix);
    const char * fn = rpmfilesFN(fi, ix);
    struct stat sb;
    rpmVerifyAttrs vfy = RPMVERIFY_NONE;

    /*
     * Check to see if the file was installed - if not pretend all is OK.
     */
    switch (rpmfilesFState(fi, ix)) {
    case RPMFILE_STATE_NETSHARED:
    case RPMFILE_STATE_NOTINSTALLED:
	goto exit;
	break;
    case RPMFILE_STATE_REPLACED:
	/* For replaced files we can only verify if it exists at all */
	flags = RPMVERIFY_LSTATFAIL;
	break;
    case RPMFILE_STATE_WRONGCOLOR:
	/*
	 * Files with wrong color are supposed to share some attributes
	 * with the actually installed file - verify what we can.
	 */
	flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE |
		   RPMVERIFY_MTIME | RPMVERIFY_RDEV);
	break;
    case RPMFILE_STATE_NORMAL:
    /* File from a non-installed package, try to verify nevertheless */
    case RPMFILE_STATE_MISSING:
	break;
    }

    if (fn == NULL || lstat(fn, &sb) != 0) {
	vfy |= RPMVERIFY_LSTATFAIL;
	goto exit;
    }

    /* If we expected a directory but got a symlink to one, follow the link */
    if (S_ISDIR(fmode) && S_ISLNK(sb.st_mode)) {
	struct stat dsb;
	/* ...if it actually points to a directory  */
	if (stat(fn, &dsb) == 0 && S_ISDIR(dsb.st_mode)) {
	    uid_t fuid;
	    /* ...and is by a legit user, to match fsmVerify() behavior */
	    if (sb.st_uid == 0 ||
			(rpmugUid(rpmfilesFUser(fi, ix), &fuid) == 0 &&
			 sb.st_uid == fuid)) {
		sb = dsb; /* struct assignment */
	    }
	}
    }

    /* Links have no mode, other types have no linkto */
    if (S_ISLNK(sb.st_mode))
	flags &= ~(RPMVERIFY_MODE);
    else
	flags &= ~(RPMVERIFY_LINKTO);

    /* Not all attributes of non-regular files can be verified */
    if (!S_ISREG(sb.st_mode))
	flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE |
		   RPMVERIFY_MTIME | RPMVERIFY_CAPS);

    /* Content checks of %ghost files are meaningless. */
    if (fileAttrs & RPMFILE_GHOST)
	flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE |
		   RPMVERIFY_MTIME | RPMVERIFY_LINKTO);

    /* Don't verify any features in omitMask. */
    flags &= ~(omitMask | RPMVERIFY_FAILURES);

    if (flags & RPMVERIFY_FILEDIGEST) {
	const unsigned char *digest;
	int algo;
	size_t diglen;

	/* XXX If --nomd5, then prelinked library sizes are not corrected. */
	if ((digest = rpmfilesFDigest(fi, ix, &algo, &diglen))) {
	    unsigned char fdigest[diglen];
	    rpm_loff_t fsize;

	    if (rpmDoDigest(algo, fn, 0, fdigest, &fsize)) {
		vfy |= (RPMVERIFY_READFAIL|RPMVERIFY_FILEDIGEST);
	    } else {
		sb.st_size = fsize;
		if (memcmp(fdigest, digest, diglen))
		    vfy |= RPMVERIFY_FILEDIGEST;
	    }
	} else {
	    vfy |= RPMVERIFY_FILEDIGEST;
	}
    }

    if (flags & RPMVERIFY_LINKTO) {
	char linkto[1024+1];
	int size = 0;

	if ((size = readlink(fn, linkto, sizeof(linkto)-1)) == -1)
	    vfy |= (RPMVERIFY_READLINKFAIL|RPMVERIFY_LINKTO);
	else {
	    const char * flink = rpmfilesFLink(fi, ix);
	    linkto[size] = '\0';
	    if (flink == NULL || !rstreq(linkto, flink))
		vfy |= RPMVERIFY_LINKTO;
	}
    }

    if (flags & RPMVERIFY_FILESIZE) {
	if (sb.st_size != rpmfilesFSize(fi, ix))
	    vfy |= RPMVERIFY_FILESIZE;
    }

    if (flags & RPMVERIFY_MODE) {
	rpm_mode_t metamode = fmode;
	rpm_mode_t filemode;

	/*
	 * Platforms (like AIX) where sizeof(rpm_mode_t) != sizeof(mode_t)
	 * need the (rpm_mode_t) cast here.
	 */
	filemode = (rpm_mode_t)sb.st_mode;

	/*
	 * Comparing the type of %ghost files is meaningless, but perms are OK.
	 */
	if (fileAttrs & RPMFILE_GHOST) {
	    metamode &= ~0xf000;
	    filemode &= ~0xf000;
	}

	if (metamode != filemode)
	    vfy |= RPMVERIFY_MODE;

#if WITH_ACL
	/*
	 * For now, any non-default acl's on a file is a difference as rpm
	 * cannot have set them.
	 */
	acl_t facl = acl_get_file(fn, ACL_TYPE_ACCESS);
	if (facl) {
	    if (acl_equiv_mode(facl, NULL) == 1) {
		vfy |= RPMVERIFY_MODE;
	    }
	    acl_free(facl);
	}
#endif
    }

    if (flags & RPMVERIFY_RDEV) {
	if (S_ISCHR(fmode) != S_ISCHR(sb.st_mode)
	 || S_ISBLK(fmode) != S_ISBLK(sb.st_mode))
	{
	    vfy |= RPMVERIFY_RDEV;
	} else if (S_ISDEV(fmode) && S_ISDEV(sb.st_mode)) {
	    rpm_rdev_t st_rdev = (sb.st_rdev & 0xffff);
	    rpm_rdev_t frdev = (rpmfilesFRdev(fi, ix) & 0xffff);
	    if (st_rdev != frdev)
		vfy |= RPMVERIFY_RDEV;
	}
    }

#if WITH_CAP
    if (flags & RPMVERIFY_CAPS) {
	/*
 	 * Empty capability set ("=") is not exactly the same as no
 	 * capabilities at all but suffices for now...
 	 */
	cap_t cap, fcap;
	cap = cap_from_text(rpmfilesFCaps(fi, ix));
	if (!cap) {
	    cap = cap_from_text("=");
	}
	fcap = cap_get_file(fn);
	if (!fcap) {
	    fcap = cap_from_text("=");
	}

	if (cap_compare(cap, fcap) != 0)
	    vfy |= RPMVERIFY_CAPS;

	cap_free(fcap);
	cap_free(cap);
    }
#endif

    if ((flags & RPMVERIFY_MTIME) && (sb.st_mtime != rpmfilesFMtime(fi, ix))) {
	vfy |= RPMVERIFY_MTIME;
    }

    if (flags & RPMVERIFY_USER) {
	const char * name = rpmugUname(sb.st_uid);
	const char * fuser = rpmfilesFUser(fi, ix);
	uid_t uid;
	int namematch = 0;
	int idmatch = 0;

	if (name && fuser)
	   namematch =  rstreq(name, fuser);
	if (fuser && rpmugUid(fuser, &uid) == 0)
	    idmatch = (uid == sb.st_uid);

	if (namematch != idmatch) {
	    rpmlog(RPMLOG_WARNING,
		    _("Duplicate username or UID for user %s\n"), fuser);
	}

	if (!(namematch || idmatch))
	    vfy |= RPMVERIFY_USER;
    }

    if (flags & RPMVERIFY_GROUP) {
	const char * name = rpmugGname(sb.st_gid);
	const char * fgroup = rpmfilesFGroup(fi, ix);
	gid_t gid;
	int namematch = 0;
	int idmatch = 0;

	if (name && fgroup)
	    namematch = rstreq(name, fgroup);
	if (fgroup && rpmugGid(fgroup, &gid) == 0)
	    idmatch = (gid == sb.st_gid);

	if (namematch != idmatch) {
	    rpmlog(RPMLOG_WARNING,
		    _("Duplicate groupname or GID for group %s\n"), fgroup);
	}

	if (!(namematch || idmatch))
	    vfy |= RPMVERIFY_GROUP;
    }

exit:
    return vfy;
}


void Shutdown(struct mg_connection* connection,
              const struct mg_request_info* request_info,
              void* user_data) {
  base::WaitableEvent* shutdown_event =
      reinterpret_cast<base::WaitableEvent*>(user_data);
  mg_printf(connection, "HTTP/1.1 200 OK\r\n\r\n");
   shutdown_event->Signal();
 }


static int __set_item(struct pppoe_net *pn, struct pppox_sock *po)
{
	int hash = hash_item(po->pppoe_pa.sid, po->pppoe_pa.remote);
	struct pppox_sock *ret;

	ret = pn->hash_table[hash];
	while (ret) {
		if (cmp_2_addr(&ret->pppoe_pa, &po->pppoe_pa) &&
		    ret->pppoe_ifindex == po->pppoe_ifindex)
			return -EALREADY;

		ret = ret->next;
	}

	po->next = pn->hash_table[hash];
	pn->hash_table[hash] = po;

	return 0;
}


static bool cmd_set_features(IDEState *s, uint8_t cmd)

{

    uint16_t *identify_data;

    if (!s->bs) {

        ide_abort_command(s);

        return true;

    }

    /* XXX: valid for CDROM ? */

    switch (s->feature) {

    case 0x02: /* write cache enable */

        bdrv_set_enable_write_cache(s->bs, true);

        identify_data = (uint16_t *)s->identify_data;

        put_le16(identify_data + 85, (1 << 14) | (1 << 5) | 1);

        return true;

    case 0x82: /* write cache disable */

        bdrv_set_enable_write_cache(s->bs, false);

        identify_data = (uint16_t *)s->identify_data;

        put_le16(identify_data + 85, (1 << 14) | 1);

        ide_flush_cache(s);

        return false;

    case 0xcc: /* reverting to power-on defaults enable */

    case 0x66: /* reverting to power-on defaults disable */

    case 0xaa: /* read look-ahead enable */

    case 0x55: /* read look-ahead disable */

    case 0x05: /* set advanced power management mode */

    case 0x85: /* disable advanced power management mode */

    case 0x69: /* NOP */

    case 0x67: /* NOP */

    case 0x96: /* NOP */

    case 0x9a: /* NOP */

    case 0x42: /* enable Automatic Acoustic Mode */

    case 0xc2: /* disable Automatic Acoustic Mode */

        return true;

    case 0x03: /* set transfer mode */

        {

            uint8_t val = s->nsector & 0x07;

            identify_data = (uint16_t *)s->identify_data;

            switch (s->nsector >> 3) {

            case 0x00: /* pio default */

            case 0x01: /* pio mode */

                put_le16(identify_data + 62, 0x07);

                put_le16(identify_data + 63, 0x07);

                put_le16(identify_data + 88, 0x3f);

                break;

            case 0x02: /* sigle word dma mode*/

                put_le16(identify_data + 62, 0x07 | (1 << (val + 8)));

                put_le16(identify_data + 63, 0x07);

                put_le16(identify_data + 88, 0x3f);

                break;

            case 0x04: /* mdma mode */

                put_le16(identify_data + 62, 0x07);

                put_le16(identify_data + 63, 0x07 | (1 << (val + 8)));

                put_le16(identify_data + 88, 0x3f);

                break;

            case 0x08: /* udma mode */

                put_le16(identify_data + 62, 0x07);

                put_le16(identify_data + 63, 0x07);

                put_le16(identify_data + 88, 0x3f | (1 << (val + 8)));

                break;

            default:

                goto abort_cmd;

            }

            return true;

        }

    }

abort_cmd:

    ide_abort_command(s);

    return true;

}


void MediaPlayerService::addBatteryData(uint32_t params)
{
 Mutex::Autolock lock(mLock);

 int32_t time = systemTime() / 1000000L;

 if ((params & kBatteryDataSpeakerOn)
 || (params & kBatteryDataOtherAudioDeviceOn)) {

 int deviceOn[NUM_AUDIO_DEVICES];
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
            deviceOn[i] = 0;
 }

 if ((params & kBatteryDataSpeakerOn)
 && (params & kBatteryDataOtherAudioDeviceOn)) {
            deviceOn[SPEAKER_AND_OTHER] = 1;
 } else if (params & kBatteryDataSpeakerOn) {
            deviceOn[SPEAKER] = 1;
 } else {
            deviceOn[OTHER_AUDIO_DEVICE] = 1;
 }

 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){

 if (mBatteryAudio.refCount > 0) { // if playing audio
 if (!deviceOn[i]) {
                        mBatteryAudio.lastTime[i] += time;
                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
                        mBatteryAudio.lastTime[i] = 0;
 } else {
                        mBatteryAudio.lastTime[i] = 0 - time;
 }
 }

                mBatteryAudio.deviceOn[i] = deviceOn[i];
 }
 }
 return;
 }

 if (params & kBatteryDataAudioFlingerStart) {
 if (mBatteryAudio.refCount == 0) {
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
 if (mBatteryAudio.deviceOn[i]) {
                    mBatteryAudio.lastTime[i] -= time;
 }
 }
 }

        mBatteryAudio.refCount ++;
 return;

 } else if (params & kBatteryDataAudioFlingerStop) {
 if (mBatteryAudio.refCount <= 0) {
            ALOGW("Battery track warning: refCount is <= 0");
 return;
 }

 if (mBatteryAudio.refCount == 1) {
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
 if (mBatteryAudio.deviceOn[i]) {
                    mBatteryAudio.lastTime[i] += time;
                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
                    mBatteryAudio.lastTime[i] = 0;
 }
 }
 }

        mBatteryAudio.refCount --;
 return;
 }

 int uid = IPCThreadState::self()->getCallingUid();
 if (uid == AID_MEDIA) {
 return;
 }
 int index = mBatteryData.indexOfKey(uid);

 if (index < 0) { // create a new entry for this UID
 BatteryUsageInfo info;
        info.audioTotalTime = 0;
        info.videoTotalTime = 0;
        info.audioLastTime = 0;
        info.videoLastTime = 0;
        info.refCount = 0;

 if (mBatteryData.add(uid, info) == NO_MEMORY) {
            ALOGE("Battery track error: no memory for new app");
 return;
 }
 }

 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);

 if (params & kBatteryDataCodecStarted) {
 if (params & kBatteryDataTrackAudio) {
            info.audioLastTime -= time;
            info.refCount ++;
 }
 if (params & kBatteryDataTrackVideo) {
            info.videoLastTime -= time;
            info.refCount ++;
 }
 } else {
 if (info.refCount == 0) {
            ALOGW("Battery track warning: refCount is already 0");
 return;
 } else if (info.refCount < 0) {
            ALOGE("Battery track error: refCount < 0");
            mBatteryData.removeItem(uid);
 return;
 }

 if (params & kBatteryDataTrackAudio) {
            info.audioLastTime += time;
            info.refCount --;
 }
 if (params & kBatteryDataTrackVideo) {
            info.videoLastTime += time;
            info.refCount --;
 }

 if (info.refCount == 0) {
            info.audioTotalTime += info.audioLastTime;
            info.audioLastTime = 0;
            info.videoTotalTime += info.videoLastTime;
            info.videoLastTime = 0;
 }
 }
}


static void ps_def(struct SYMBOL *s,
			char *p,
			char use)	/* cf user_ps_add() */
{
	if (!svg && epsf <= 1) {		/* if PS output */
		if (secure
//		 || use == 'g'		// SVG
		 || use == 's')		// PS for SVG
			return;
	} else {				/* if SVG output */
		if (use == 'p'		// PS for PS
		 || (use == 'g'		// SVG
		  && file_initialized > 0))
			return;
	}
	if (s->abc_prev)
		s->state = s->abc_prev->state;
	if (s->state == ABC_S_TUNE) {
		if (use == 'g')		// SVG
			return;
		sym_link(s, FMTCHG);
		s->aux = PSSEQ;
		s->text = p;
//		s->flags |= ABC_F_INVIS;
		return;
	}
	if (use == 'g') {			// SVG
		svg_ps(p);
		if (!svg && epsf <= 1)
			return;
	}
	if (file_initialized > 0 || mbf != outbuf)
		a2b("%s\n", p);
	else
		user_ps_add(p, use);
}


static int smacker_decode_header_tree(SmackVContext *smk, BitstreamContext *bc,
                                      int **recodes, int *last, int size)
{
    int res;
    HuffContext huff;
    HuffContext tmp1, tmp2;
    VLC vlc[2] = { { 0 } };
    int escapes[3];
    DBCtx ctx;
    int err = 0;

    if(size >= UINT_MAX>>4){ // (((size + 3) >> 2) + 3) << 2 must not overflow
        av_log(smk->avctx, AV_LOG_ERROR, "size too large\n");
        return AVERROR_INVALIDDATA;
    }

    tmp1.length = 256;
    tmp1.maxlength = 0;
    tmp1.current = 0;
    tmp1.bits = av_mallocz(256 * 4);
    tmp1.lengths = av_mallocz(256 * sizeof(int));
    tmp1.values = av_mallocz(256 * sizeof(int));

    tmp2.length = 256;
    tmp2.maxlength = 0;
    tmp2.current = 0;
    tmp2.bits = av_mallocz(256 * 4);
    tmp2.lengths = av_mallocz(256 * sizeof(int));
    tmp2.values = av_mallocz(256 * sizeof(int));
    if (!tmp1.bits || !tmp1.lengths || !tmp1.values ||
        !tmp2.bits || !tmp2.lengths || !tmp2.values) {
        err = AVERROR(ENOMEM);
        goto error;
    }

    if (bitstream_read_bit(bc)) {
        smacker_decode_tree(bc, &tmp1, 0, 0);
        bitstream_skip(bc, 1);
        res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length,
                    tmp1.lengths, sizeof(int), sizeof(int),
                    tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
        if(res < 0) {
            av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
            err = res;
            goto error;
        }
    } else {
        av_log(smk->avctx, AV_LOG_ERROR, "Skipping low bytes tree\n");
    }
    if (bitstream_read_bit(bc)) {
        smacker_decode_tree(bc, &tmp2, 0, 0);
        bitstream_skip(bc, 1);
        res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length,
                    tmp2.lengths, sizeof(int), sizeof(int),
                    tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
        if(res < 0) {
            av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
            err = res;
            goto error;
        }
    } else {
        av_log(smk->avctx, AV_LOG_ERROR, "Skipping high bytes tree\n");
    }

    escapes[0]  = bitstream_read(bc, 8);
    escapes[0] |= bitstream_read(bc, 8) << 8;
    escapes[1]  = bitstream_read(bc, 8);
    escapes[1] |= bitstream_read(bc, 8) << 8;
    escapes[2]  = bitstream_read(bc, 8);
    escapes[2] |= bitstream_read(bc, 8) << 8;

    last[0] = last[1] = last[2] = -1;

    ctx.escapes[0] = escapes[0];
    ctx.escapes[1] = escapes[1];
    ctx.escapes[2] = escapes[2];
    ctx.v1 = &vlc[0];
    ctx.v2 = &vlc[1];
    ctx.recode1 = tmp1.values;
    ctx.recode2 = tmp2.values;
    ctx.last = last;

    huff.length = ((size + 3) >> 2) + 4;
    huff.maxlength = 0;
    huff.current = 0;
    huff.values = av_mallocz(huff.length * sizeof(int));
    if (!huff.values) {
        err = AVERROR(ENOMEM);
        goto error;
    }

    if ((res = smacker_decode_bigtree(bc, &huff, &ctx)) < 0)
        err = res;
    bitstream_skip(bc, 1);
    if(ctx.last[0] == -1) ctx.last[0] = huff.current++;
    if(ctx.last[1] == -1) ctx.last[1] = huff.current++;
    if(ctx.last[2] == -1) ctx.last[2] = huff.current++;
    if (ctx.last[0] >= huff.length ||
        ctx.last[1] >= huff.length ||
        ctx.last[2] >= huff.length) {
        av_log(smk->avctx, AV_LOG_ERROR, "Huffman codes out of range\n");
        err = AVERROR_INVALIDDATA;
    }

    *recodes = huff.values;

error:
    if(vlc[0].table)
        ff_free_vlc(&vlc[0]);
    if(vlc[1].table)
        ff_free_vlc(&vlc[1]);
    av_free(tmp1.bits);
    av_free(tmp1.lengths);
    av_free(tmp1.values);
    av_free(tmp2.bits);
    av_free(tmp2.lengths);
    av_free(tmp2.values);

    return err;
}


static void delete_pid_file(myf flags)
{
#ifndef EMBEDDED_LIBRARY
  if (pid_file_created)
  {
    mysql_file_delete(key_file_pid, pidfile_name, flags);
    pid_file_created= false;
  }
#endif /* EMBEDDED_LIBRARY */
  return;
}


int64_t OpLevelCostEstimator::CountMatMulOperations(
    const OpInfo& op_info, MatMulDimensions* mat_mul,
    bool* found_unknown_shapes) {
  double ops = 0;

  if (op_info.inputs_size() < 2) {
    LOG(ERROR) << "Need 2 inputs but got " << op_info.inputs_size();
    // TODO(pcma): Try to separate invalid inputs from unknown shapes
    *found_unknown_shapes = true;
    return 0;
  }

  auto& a_matrix = op_info.inputs(0);
  auto& b_matrix = op_info.inputs(1);

  bool transpose_a = false;
  bool transpose_b = false;

  double m_dim, n_dim, k_dim, k_dim_b = 0;

  for (const auto& item : op_info.attr()) {
    VLOG(1) << "Key:" << item.first
            << " Value:" << SummarizeAttrValue(item.second);
    if (item.first == "transpose_a" && item.second.b() == true)
      transpose_a = true;
    if (item.first == "transpose_b" && item.second.b() == true)
      transpose_b = true;
  }
  VLOG(1) << "transpose_a:" << transpose_a;
  VLOG(1) << "transpose_b:" << transpose_b;
  auto a_matrix_shape =
      MaybeGetMinimumShape(a_matrix.shape(), 2, found_unknown_shapes);
  auto b_matrix_shape =
      MaybeGetMinimumShape(b_matrix.shape(), 2, found_unknown_shapes);
  if (transpose_a) {
    m_dim = a_matrix_shape.dim(1).size();
    k_dim = a_matrix_shape.dim(0).size();
  } else {
    m_dim = a_matrix_shape.dim(0).size();
    k_dim = a_matrix_shape.dim(1).size();
  }
  if (transpose_b) {
    k_dim_b = b_matrix_shape.dim(1).size();
    n_dim = b_matrix_shape.dim(0).size();
  } else {
    k_dim_b = b_matrix_shape.dim(0).size();
    n_dim = b_matrix_shape.dim(1).size();
  }

  VLOG(1) << "M, N, K: " << m_dim << "," << n_dim << "," << k_dim;
  // Only check equality when both sizes are known (in other words, when
  // neither is set to a minimum dimension size of 1).
  if (k_dim_b != 1 && k_dim != 1 && k_dim_b != k_dim) {
    LOG(ERROR) << "Incompatible Matrix dimensions";
    return ops;
  } else {
    // One of k_dim and k_dim_b might be 1 (minimum dimension size).
    k_dim = std::max(k_dim, k_dim_b);
  }

  ops = m_dim * n_dim * k_dim * 2;
  VLOG(1) << "Operations for Matmul: " << ops;

  if (mat_mul != nullptr) {
    mat_mul->m = m_dim;
    mat_mul->n = n_dim;
    mat_mul->k = k_dim;
  }
  return ops;
}


static int mount_entry(const char *fsname, const char *target,
		       const char *fstype, unsigned long mountflags,
		       const char *data, int optional)
{
#ifdef HAVE_STATVFS
	struct statvfs sb;
#endif

	if (mount(fsname, target, fstype, mountflags & ~MS_REMOUNT, data)) {
		if (optional) {
			INFO("failed to mount '%s' on '%s' (optional): %s", fsname,
			     target, strerror(errno));
			return 0;
		}
		else {
			SYSERROR("failed to mount '%s' on '%s'", fsname, target);
			return -1;
		}
	}

	if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
		DEBUG("remounting %s on %s to respect bind or remount options",
		      fsname ? fsname : "(none)", target ? target : "(none)");
		unsigned long rqd_flags = 0;
		if (mountflags & MS_RDONLY)
			rqd_flags |= MS_RDONLY;
#ifdef HAVE_STATVFS
		if (statvfs(fsname, &sb) == 0) {
			unsigned long required_flags = rqd_flags;
			if (sb.f_flag & MS_NOSUID)
				required_flags |= MS_NOSUID;
			if (sb.f_flag & MS_NODEV)
				required_flags |= MS_NODEV;
			if (sb.f_flag & MS_RDONLY)
				required_flags |= MS_RDONLY;
			if (sb.f_flag & MS_NOEXEC)
				required_flags |= MS_NOEXEC;
			DEBUG("(at remount) flags for %s was %lu, required extra flags are %lu", fsname, sb.f_flag, required_flags);
			/*
			 * If this was a bind mount request, and required_flags
			 * does not have any flags which are not already in
			 * mountflags, then skip the remount
			 */
			if (!(mountflags & MS_REMOUNT)) {
				if (!(required_flags & ~mountflags) && rqd_flags == 0) {
					DEBUG("mountflags already was %lu, skipping remount",
						mountflags);
					goto skipremount;
				}
			}
			mountflags |= required_flags;
		}
#endif

		if (mount(fsname, target, fstype,
			  mountflags | MS_REMOUNT, data)) {
			if (optional) {
				INFO("failed to mount '%s' on '%s' (optional): %s",
					 fsname, target, strerror(errno));
				return 0;
			}
			else {
				SYSERROR("failed to mount '%s' on '%s'",
					 fsname, target);
				return -1;
			}
		}
	}

#ifdef HAVE_STATVFS
skipremount:
#endif
	DEBUG("mounted '%s' on '%s', type '%s'", fsname, target, fstype);

	return 0;
}


void TreeView::TreeNodeChanged(TreeModel* model, TreeModelNode* node) {
  if (node_to_details_map_.find(node) == node_to_details_map_.end()) {
    return;
  }
  const NodeDetails* details = GetNodeDetails(node);
  TV_ITEM tv_item = {0};
  tv_item.mask = TVIF_TEXT;
  tv_item.hItem = details->tree_item;
  tv_item.pszText = LPSTR_TEXTCALLBACK;
  TreeView_SetItem(tree_view_, &tv_item);
}


PHP_FUNCTION(pg_fetch_result)
{
	zval *result, *field=NULL;
	zend_long row;
	PGresult *pgsql_result;
	pgsql_result_handle *pg_result;
	int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();

	if (argc == 2) {
		if (zend_parse_parameters(argc, "rz", &result, &field) == FAILURE) {
			return;
		}
	} else {
		if (zend_parse_parameters(argc, "rlz", &result, &row, &field) == FAILURE) {
			return;
		}
	}

	ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);

	pgsql_result = pg_result->result;
	if (argc == 2) {
		if (pg_result->row < 0) {
			pg_result->row = 0;
		}
		pgsql_row = pg_result->row;
		if (pgsql_row >= PQntuples(pgsql_result)) {
			RETURN_FALSE;
		}
	} else {
		if (row < 0 || row >= PQntuples(pgsql_result)) {
			php_error_docref(NULL, E_WARNING, "Unable to jump to row %pd on PostgreSQL result index %pd",
							row, Z_LVAL_P(result));
			RETURN_FALSE;
		}
		pgsql_row = (int)row;
	}
	switch (Z_TYPE_P(field)) {
		case IS_STRING:
			field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field));
			if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
				php_error_docref(NULL, E_WARNING, "Bad column offset specified");
				RETURN_FALSE;
			}
			break;
		default:
			convert_to_long_ex(field);
			if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) {
				php_error_docref(NULL, E_WARNING, "Bad column offset specified");
				RETURN_FALSE;
			}
			field_offset = (int)Z_LVAL_P(field);
			break;
	}

	if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
		RETVAL_NULL();
	} else {
		RETVAL_STRINGL(PQgetvalue(pgsql_result, pgsql_row, field_offset),
				PQgetlength(pgsql_result, pgsql_row, field_offset));
	}
}


TEST_F ( ProtocolHandlerRegistryTest , TestDefaultSaveLoad ) {
 ProtocolHandler ph1 = CreateProtocolHandler ( "test" , "test1" ) ;
 ProtocolHandler ph2 = CreateProtocolHandler ( "test" , "test2" ) ;
 registry ( ) -> OnDenyRegisterProtocolHandler ( ph1 ) ;
 registry ( ) -> OnDenyRegisterProtocolHandler ( ph2 ) ;
 registry ( ) -> OnAcceptRegisterProtocolHandler ( ph2 ) ;
 registry ( ) -> Disable ( ) ;
 RecreateRegistry ( true ) ;
 ASSERT_FALSE ( registry ( ) -> enabled ( ) ) ;
 registry ( ) -> Enable ( ) ;
 ASSERT_FALSE ( registry ( ) -> IsDefault ( ph1 ) ) ;
 ASSERT_TRUE ( registry ( ) -> IsDefault ( ph2 ) ) ;
 RecreateRegistry ( true ) ;
 ASSERT_TRUE ( registry ( ) -> enabled ( ) ) ;
 }


QPDFWriter::bytesNeeded(unsigned long long n)
{
    int bytes = 0;
    while (n)
    {
	++bytes;
	n >>= 8;
    }
    return bytes;
}


void SyncManager::SyncInternal::RaiseAuthNeededEvent() {
  ObserverList<SyncManager::Observer> temp_obs_list;
  CopyObservers(&temp_obs_list);
  FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list,
      OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS)));
}


static int ovl_rename2(struct inode *olddir, struct dentry *old,
		       struct inode *newdir, struct dentry *new,
		       unsigned int flags)
{
	int err;
	enum ovl_path_type old_type;
	enum ovl_path_type new_type;
	struct dentry *old_upperdir;
	struct dentry *new_upperdir;
	struct dentry *olddentry;
	struct dentry *newdentry;
	struct dentry *trap;
	bool old_opaque;
	bool new_opaque;
	bool new_create = false;
	bool cleanup_whiteout = false;
	bool overwrite = !(flags & RENAME_EXCHANGE);
	bool is_dir = d_is_dir(old);
	bool new_is_dir = false;
	struct dentry *opaquedir = NULL;
	const struct cred *old_cred = NULL;
	struct cred *override_cred = NULL;

	err = -EINVAL;
	if (flags & ~(RENAME_EXCHANGE | RENAME_NOREPLACE))
		goto out;

	flags &= ~RENAME_NOREPLACE;

	err = ovl_check_sticky(old);
	if (err)
		goto out;

	/* Don't copy up directory trees */
	old_type = ovl_path_type(old);
	err = -EXDEV;
	if (OVL_TYPE_MERGE_OR_LOWER(old_type) && is_dir)
		goto out;

	if (new->d_inode) {
		err = ovl_check_sticky(new);
		if (err)
			goto out;

		if (d_is_dir(new))
			new_is_dir = true;

		new_type = ovl_path_type(new);
		err = -EXDEV;
		if (!overwrite && OVL_TYPE_MERGE_OR_LOWER(new_type) && new_is_dir)
			goto out;

		err = 0;
		if (!OVL_TYPE_UPPER(new_type) && !OVL_TYPE_UPPER(old_type)) {
			if (ovl_dentry_lower(old)->d_inode ==
			    ovl_dentry_lower(new)->d_inode)
				goto out;
		}
		if (OVL_TYPE_UPPER(new_type) && OVL_TYPE_UPPER(old_type)) {
			if (ovl_dentry_upper(old)->d_inode ==
			    ovl_dentry_upper(new)->d_inode)
				goto out;
		}
	} else {
		if (ovl_dentry_is_opaque(new))
			new_type = __OVL_PATH_UPPER;
		else
			new_type = __OVL_PATH_UPPER | __OVL_PATH_PURE;
	}

	err = ovl_want_write(old);
	if (err)
		goto out;

	err = ovl_copy_up(old);
	if (err)
		goto out_drop_write;

	err = ovl_copy_up(new->d_parent);
	if (err)
		goto out_drop_write;
	if (!overwrite) {
		err = ovl_copy_up(new);
		if (err)
			goto out_drop_write;
	}

	old_opaque = !OVL_TYPE_PURE_UPPER(old_type);
	new_opaque = !OVL_TYPE_PURE_UPPER(new_type);

	if (old_opaque || new_opaque) {
		err = -ENOMEM;
		override_cred = prepare_creds();
		if (!override_cred)
			goto out_drop_write;

		/*
		 * CAP_SYS_ADMIN for setting xattr on whiteout, opaque dir
		 * CAP_DAC_OVERRIDE for create in workdir
		 * CAP_FOWNER for removing whiteout from sticky dir
		 * CAP_FSETID for chmod of opaque dir
		 * CAP_CHOWN for chown of opaque dir
		 */
		cap_raise(override_cred->cap_effective, CAP_SYS_ADMIN);
		cap_raise(override_cred->cap_effective, CAP_DAC_OVERRIDE);
		cap_raise(override_cred->cap_effective, CAP_FOWNER);
		cap_raise(override_cred->cap_effective, CAP_FSETID);
		cap_raise(override_cred->cap_effective, CAP_CHOWN);
		old_cred = override_creds(override_cred);
	}

	if (overwrite && OVL_TYPE_MERGE_OR_LOWER(new_type) && new_is_dir) {
		opaquedir = ovl_check_empty_and_clear(new);
		err = PTR_ERR(opaquedir);
		if (IS_ERR(opaquedir)) {
			opaquedir = NULL;
			goto out_revert_creds;
		}
	}

	if (overwrite) {
		if (old_opaque) {
			if (new->d_inode || !new_opaque) {
				/* Whiteout source */
				flags |= RENAME_WHITEOUT;
			} else {
				/* Switch whiteouts */
				flags |= RENAME_EXCHANGE;
			}
		} else if (is_dir && !new->d_inode && new_opaque) {
			flags |= RENAME_EXCHANGE;
			cleanup_whiteout = true;
		}
	}

	old_upperdir = ovl_dentry_upper(old->d_parent);
	new_upperdir = ovl_dentry_upper(new->d_parent);

	trap = lock_rename(new_upperdir, old_upperdir);

	olddentry = ovl_dentry_upper(old);
	newdentry = ovl_dentry_upper(new);
	if (newdentry) {
		if (opaquedir) {
			newdentry = opaquedir;
			opaquedir = NULL;
		} else {
			dget(newdentry);
		}
	} else {
		new_create = true;
		newdentry = lookup_one_len(new->d_name.name, new_upperdir,
					   new->d_name.len);
		err = PTR_ERR(newdentry);
		if (IS_ERR(newdentry))
			goto out_unlock;
	}

	err = -ESTALE;
	if (olddentry->d_parent != old_upperdir)
		goto out_dput;
	if (newdentry->d_parent != new_upperdir)
		goto out_dput;
	if (olddentry == trap)
		goto out_dput;
	if (newdentry == trap)
		goto out_dput;

	if (is_dir && !old_opaque && new_opaque) {
		err = ovl_set_opaque(olddentry);
		if (err)
			goto out_dput;
	}
	if (!overwrite && new_is_dir && old_opaque && !new_opaque) {
		err = ovl_set_opaque(newdentry);
		if (err)
			goto out_dput;
	}

	if (old_opaque || new_opaque) {
		err = ovl_do_rename(old_upperdir->d_inode, olddentry,
				    new_upperdir->d_inode, newdentry,
				    flags);
	} else {
		/* No debug for the plain case */
		BUG_ON(flags & ~RENAME_EXCHANGE);
		err = vfs_rename(old_upperdir->d_inode, olddentry,
				 new_upperdir->d_inode, newdentry,
				 NULL, flags);
	}

	if (err) {
		if (is_dir && !old_opaque && new_opaque)
			ovl_remove_opaque(olddentry);
		if (!overwrite && new_is_dir && old_opaque && !new_opaque)
			ovl_remove_opaque(newdentry);
		goto out_dput;
	}

	if (is_dir && old_opaque && !new_opaque)
		ovl_remove_opaque(olddentry);
	if (!overwrite && new_is_dir && !old_opaque && new_opaque)
		ovl_remove_opaque(newdentry);

	/*
	 * Old dentry now lives in different location. Dentries in
	 * lowerstack are stale. We cannot drop them here because
	 * access to them is lockless. This could be only pure upper
	 * or opaque directory - numlower is zero. Or upper non-dir
	 * entry - its pureness is tracked by flag opaque.
	 */
	if (old_opaque != new_opaque) {
		ovl_dentry_set_opaque(old, new_opaque);
		if (!overwrite)
			ovl_dentry_set_opaque(new, old_opaque);
	}

	if (cleanup_whiteout)
		ovl_cleanup(old_upperdir->d_inode, newdentry);

	ovl_dentry_version_inc(old->d_parent);
	ovl_dentry_version_inc(new->d_parent);

out_dput:
	dput(newdentry);
out_unlock:
	unlock_rename(new_upperdir, old_upperdir);
out_revert_creds:
	if (old_opaque || new_opaque) {
		revert_creds(old_cred);
		put_cred(override_cred);
	}
out_drop_write:
	ovl_drop_write(old);
out:
	dput(opaquedir);
	return err;
}


mrb_mod_extend_object(mrb_state *mrb, mrb_value mod)
{
  mrb_value obj = mrb_get_arg1(mrb);

  mrb_check_type(mrb, mod, MRB_TT_MODULE);
  mrb_include_module(mrb, mrb_class_ptr(mrb_singleton_class(mrb, obj)), mrb_class_ptr(mod));
  return mod;
}


int check_params(char *buf, int buf_size,

                 const char * const *params, const char *str)

{

    const char *p;

    int i;

    p = str;

    while (*p != '\0') {

        p = get_opt_name(buf, buf_size, p, '=');

        if (*p != '=') {

            return -1;

        }

        p++;

        for (i = 0; params[i] != NULL; i++) {

            if (!strcmp(params[i], buf)) {

                break;

            }

        }

        if (params[i] == NULL) {

            return -1;

        }

        p = get_opt_value(NULL, 0, p);

        if (*p != ',') {

            break;

        }

        p++;

    }

    return 0;

}


  void SignalDone() {
    DCHECK_CURRENTLY_ON(BrowserThread::IO);
    if (!is_removing_)
      return;
    is_removing_ = false;
    event_->Signal();
  }


  Page* DetectOnceOnBlankPage() {
    WebViewImpl* web_view = web_view_helper_.InitializeAndLoad("about:blank");
    Page* page = web_view->MainFrameImpl()->GetFrame()->GetPage();
    EXPECT_FALSE(page->Paused());
    RunDetection(true, false);
    return page;
  }


static ssize_t ucma_query_path(struct ucma_context *ctx,
			       void __user *response, int out_len)
{
	struct rdma_ucm_query_path_resp *resp;
	int i, ret = 0;

	if (out_len < sizeof(*resp))
		return -ENOSPC;

	resp = kzalloc(out_len, GFP_KERNEL);
	if (!resp)
		return -ENOMEM;

	resp->num_paths = ctx->cm_id->route.num_paths;
	for (i = 0, out_len -= sizeof(*resp);
	     i < resp->num_paths && out_len > sizeof(struct ib_path_rec_data);
	     i++, out_len -= sizeof(struct ib_path_rec_data)) {

		resp->path_data[i].flags = IB_PATH_GMP | IB_PATH_PRIMARY |
					   IB_PATH_BIDIRECTIONAL;
		ib_sa_pack_path(&ctx->cm_id->route.path_rec[i],
				&resp->path_data[i].path_rec);
	}

	if (copy_to_user(response, resp,
			 sizeof(*resp) + (i * sizeof(struct ib_path_rec_data))))
		ret = -EFAULT;

	kfree(resp);
	return ret;
}


error_t esp32EthInit(NetInterface *interface)
{
   error_t error;

   //Debug message
   TRACE_INFO("Initializing ESP32 Ethernet MAC...\r\n");

   //Save underlying network interface
   nicDriverInterface = interface;

   //Enable EMAC module
   periph_module_enable(PERIPH_EMAC_MODULE);
   //Enable Ethernet MAC clock
   DPORT_REG_SET_BIT(EMAC_CLK_EN_REG, EMAC_CLK_EN);

   //GPIO configuration
   esp32EthInitGpio(interface);

   //Perform a software reset
   REG_SET_BIT(EMAC_DMABUSMODE_REG, EMAC_SW_RST);
   //Wait for the reset to complete
   while(REG_GET_BIT(EMAC_DMABUSMODE_REG, EMAC_SW_RST))
   {
   }

   //Adjust MDC clock range
   REG_SET_FIELD(EMAC_GMIIADDR_REG, EMAC_MIICSRCLK, 1);

   //Valid Ethernet PHY or switch driver?
   if(interface->phyDriver != NULL)
   {
      //Ethernet PHY initialization
      error = interface->phyDriver->init(interface);
   }
   else if(interface->switchDriver != NULL)
   {
      //Ethernet switch initialization
      error = interface->switchDriver->init(interface);
   }
   else
   {
      //The interface is not properly configured
      error = ERROR_FAILURE;
   }

   //Any error to report?
   if(error)
   {
      return error;
   }

   //Use default MAC configuration
   REG_WRITE(EMAC_GMACCONFIG_REG, 0);
   REG_SET_BIT(EMAC_GMACCONFIG_REG, EMAC_EMACMII);
   REG_SET_BIT(EMAC_GMACCONFIG_REG, EMAC_EMACRXOWN);

   //Set the MAC address of the station
   REG_WRITE(EMAC_ADDR0HIGH_REG, interface->macAddr.w[2]);
   REG_WRITE(EMAC_ADDR0LOW_REG, interface->macAddr.w[0] | (interface->macAddr.w[1] << 16));

   //The MAC supports 3 additional addresses for unicast perfect filtering
   REG_WRITE(EMAC_ADDR1HIGH_REG, 0);
   REG_WRITE(EMAC_ADDR1LOW_REG, 0);
   REG_WRITE(EMAC_ADDR2HIGH_REG, 0);
   REG_WRITE(EMAC_ADDR2LOW_REG, 0);
   REG_WRITE(EMAC_ADDR3HIGH_REG, 0);
   REG_WRITE(EMAC_ADDR3LOW_REG, 0);

   //Configure the receive filter
   REG_WRITE(EMAC_GMACFF_REG, 0);
   //Disable flow control
   REG_WRITE(EMAC_GMACFC_REG, 0);

   //Enable store and forward mode
   REG_WRITE(EMAC_DMAOPERATION_MODE_REG, 0);
   REG_SET_BIT(EMAC_DMAOPERATION_MODE_REG, EMAC_RX_STORE_FORWARD);
   REG_SET_BIT(EMAC_DMAOPERATION_MODE_REG, EMAC_TX_STR_FWD);

   //Configure DMA bus mode
   REG_SET_FIELD(EMAC_DMABUSMODE_REG, EMAC_RX_DMA_PBL, 1);
   REG_SET_FIELD(EMAC_DMABUSMODE_REG, EMAC_PROG_BURST_LEN, 1);
   REG_SET_BIT(EMAC_DMABUSMODE_REG, EMAC_ALT_DESC_SIZE);

   //Initialize DMA descriptor lists
   esp32EthInitDmaDesc(interface);

   //Disable MAC interrupts
   REG_SET_BIT(EMAC_INTMASK_REG, EMAC_LPIINTMASK);
   REG_SET_BIT(EMAC_INTMASK_REG, EMAC_PMTINTMASK);

   //Enable the desired DMA interrupts
   REG_WRITE(EMAC_DMAIN_EN_REG, EMAC_DMAIN_NISE_M | EMAC_DMAIN_RIE_M |
      EMAC_DMAIN_TIE_M);

   //Register interrupt handler
   esp_intr_alloc(ETS_ETH_MAC_INTR_SOURCE, 0, esp32EthIrqHandler, NULL, NULL);

   //Enable MAC transmission and reception
   REG_SET_BIT(EMAC_GMACCONFIG_REG, EMAC_EMACTX);
   REG_SET_BIT(EMAC_GMACCONFIG_REG, EMAC_EMACRX);

   //Enable DMA transmission and reception
   REG_SET_BIT(EMAC_DMAOPERATION_MODE_REG, EMAC_START_STOP_TRANSMISSION_COMMAND);
   REG_SET_BIT(EMAC_DMAOPERATION_MODE_REG, EMAC_START_STOP_RX);

   //Accept any packets from the upper layer
   osSetEvent(&interface->nicTxEvent);

   //Successful initialization
   return NO_ERROR;
}


OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter(
        OMX_INDEXTYPE index, const OMX_PTR params) {
 switch (index) {
 case OMX_IndexParamStandardComponentRole:
 {

             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
                 (const OMX_PARAM_COMPONENTROLETYPE *)params;

             if (strncmp((const char *)roleParams->cRole,
                         "audio_encoder.amrnb",
                         OMX_MAX_STRINGNAME_SIZE - 1)) {
 return OMX_ErrorUndefined;
 }

 return OMX_ErrorNone;
 }

 case OMX_IndexParamAudioPortFormat:
 {

             const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
                 (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;

             if (formatParams->nPortIndex > 1) {
                 return OMX_ErrorUndefined;
             }

 if (formatParams->nIndex > 0) {
 return OMX_ErrorNoMore;
 }

 if ((formatParams->nPortIndex == 0
 && formatParams->eEncoding != OMX_AUDIO_CodingPCM)
 || (formatParams->nPortIndex == 1
 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) {
 return OMX_ErrorUndefined;
 }

 return OMX_ErrorNone;
 }

 case OMX_IndexParamAudioAmr:
 {

             OMX_AUDIO_PARAM_AMRTYPE *amrParams =
                 (OMX_AUDIO_PARAM_AMRTYPE *)params;

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

 if (amrParams->nChannels != 1
 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff
 || amrParams->eAMRFrameFormat
 != OMX_AUDIO_AMRFrameFormatFSF
 || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0
 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) {
 return OMX_ErrorUndefined;
 }

            mBitRate = amrParams->nBitRate;
            mMode = amrParams->eAMRBandMode - 1;

            amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
            amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;

 return OMX_ErrorNone;
 }

 case OMX_IndexParamAudioPcm:
 {

             OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;

             if (pcmParams->nPortIndex != 0) {
                 return OMX_ErrorUndefined;
             }

 if (pcmParams->nChannels != 1
 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) {
 return OMX_ErrorUndefined;
 }

 return OMX_ErrorNone;
 }

 default:
 return SimpleSoftOMXComponent::internalSetParameter(index, params);
 }
}


OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len)
{
	OJPEGState* sp=(OJPEGState*)tif->tif_data;
	if (sp->in_buffer_togo==0)
	{
		if (OJPEGReadBufferFill(sp)==0)
			return(0);
		assert(sp->in_buffer_togo>0);
	}
	*len=sp->in_buffer_togo;
	*mem=(void*)sp->in_buffer_cur;
	sp->in_buffer_togo=0;
	if (sp->in_buffer_file_togo==0)
	{
		switch(sp->in_buffer_source)
		{
			case osibsStrile:
				if (sp->in_buffer_next_strile<sp->in_buffer_strile_count)
					sp->out_state=ososRst;
				else
					sp->out_state=ososEoi;
				break;
			case osibsEof:
				sp->out_state=ososEoi;
				break;
			default:
				break;
		}
	}
	return(1);
}


static int recv_stream(struct kiocb *iocb, struct socket *sock,
		       struct msghdr *m, size_t buf_len, int flags)
{
	struct sock *sk = sock->sk;
	struct tipc_port *tport = tipc_sk_port(sk);
	struct sk_buff *buf;
	struct tipc_msg *msg;
	long timeout;
	unsigned int sz;
	int sz_to_copy, target, needed;
	int sz_copied = 0;
	u32 err;
	int res = 0;

	/* Catch invalid receive attempts */
	if (unlikely(!buf_len))
		return -EINVAL;

	lock_sock(sk);

	if (unlikely((sock->state == SS_UNCONNECTED) ||
		     (sock->state == SS_CONNECTING))) {
		res = -ENOTCONN;
		goto exit;
	}

	target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);

restart:
	/* Look for a message in receive queue; wait if necessary */
	while (skb_queue_empty(&sk->sk_receive_queue)) {
		if (sock->state == SS_DISCONNECTING) {
			res = -ENOTCONN;
			goto exit;
		}
		if (timeout <= 0L) {
			res = timeout ? timeout : -EWOULDBLOCK;
			goto exit;
		}
		release_sock(sk);
		timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
							   tipc_rx_ready(sock),
							   timeout);
		lock_sock(sk);
	}

	/* Look at first message in receive queue */
	buf = skb_peek(&sk->sk_receive_queue);
	msg = buf_msg(buf);
	sz = msg_data_sz(msg);
	err = msg_errcode(msg);

	/* Discard an empty non-errored message & try again */
	if ((!sz) && (!err)) {
		advance_rx_queue(sk);
		goto restart;
	}

	/* Optionally capture sender's address & ancillary data of first msg */
	if (sz_copied == 0) {
		set_orig_addr(m, msg);
		res = anc_data_recv(m, msg, tport);
		if (res)
			goto exit;
	}

	/* Capture message data (if valid) & compute return value (always) */
	if (!err) {
		u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);

		sz -= offset;
		needed = (buf_len - sz_copied);
		sz_to_copy = (sz <= needed) ? sz : needed;

		res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
					      m->msg_iov, sz_to_copy);
		if (res)
			goto exit;

		sz_copied += sz_to_copy;

		if (sz_to_copy < sz) {
			if (!(flags & MSG_PEEK))
				TIPC_SKB_CB(buf)->handle =
				(void *)(unsigned long)(offset + sz_to_copy);
			goto exit;
		}
	} else {
		if (sz_copied != 0)
			goto exit; /* can't add error msg to valid data */

		if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
			res = 0;
		else
			res = -ECONNRESET;
	}

	/* Consume received message (optional) */
	if (likely(!(flags & MSG_PEEK))) {
		if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
			tipc_acknowledge(tport->ref, tport->conn_unacked);
		advance_rx_queue(sk);
	}

	/* Loop around if more data is required */
	if ((sz_copied < buf_len) &&	/* didn't get all requested data */
	    (!skb_queue_empty(&sk->sk_receive_queue) ||
	    (sz_copied < target)) &&	/* and more is ready or required */
	    (!(flags & MSG_PEEK)) &&	/* and aren't just peeking at data */
	    (!err))			/* and haven't reached a FIN */
		goto restart;

exit:
	release_sock(sk);
	return sz_copied ? sz_copied : res;
}


static int nfc_llcp_setsockopt(struct socket *sock, int level, int optname,
			       char __user *optval, unsigned int optlen)
{
	struct sock *sk = sock->sk;
	struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
	u32 opt;
	int err = 0;

	pr_debug("%p optname %d\n", sk, optname);

	if (level != SOL_NFC)
		return -ENOPROTOOPT;

	lock_sock(sk);

	switch (optname) {
	case NFC_LLCP_RW:
		if (sk->sk_state == LLCP_CONNECTED ||
		    sk->sk_state == LLCP_BOUND ||
		    sk->sk_state == LLCP_LISTEN) {
			err = -EINVAL;
			break;
		}

		if (get_user(opt, (u32 __user *) optval)) {
			err = -EFAULT;
			break;
		}

		if (opt > LLCP_MAX_RW) {
			err = -EINVAL;
			break;
		}

		llcp_sock->rw = (u8) opt;

		break;

	case NFC_LLCP_MIUX:
		if (sk->sk_state == LLCP_CONNECTED ||
		    sk->sk_state == LLCP_BOUND ||
		    sk->sk_state == LLCP_LISTEN) {
			err = -EINVAL;
			break;
		}

		if (get_user(opt, (u32 __user *) optval)) {
			err = -EFAULT;
			break;
		}

		if (opt > LLCP_MAX_MIUX) {
			err = -EINVAL;
			break;
		}

		llcp_sock->miux = cpu_to_be16((u16) opt);

		break;

	default:
		err = -ENOPROTOOPT;
		break;
	}

	release_sock(sk);

	pr_debug("%p rw %d miux %d\n", llcp_sock,
		 llcp_sock->rw, llcp_sock->miux);

	return err;
}


static void dtap_gcc_term_req ( tvbuff_t * tvb , proto_tree * tree , packet_info * pinfo _U_ , guint32 offset , guint len ) {
 guint32 curr_offset ;
 guint32 consumed ;
 guint curr_len ;
 curr_offset = offset ;
 curr_len = len ;
 ELEM_MAND_V ( GSM_A_PDU_TYPE_DTAP , DE_GCC_CALL_REF , NULL ) ;
 }


UTF8toLatin1(TScreen *screen, Char *s, unsigned long len, unsigned long *result)
{
    static Char *buffer;
    static Cardinal used;

    Cardinal offset = 0;

    if (len != 0) {
	PtyData data;

	fakePtyData(&data, s, s + len);
	while (decodeUtf8(screen, &data)) {
	    Bool fails = False;
	    Bool extra = False;
	    IChar value;
	    skipPtyData(&data, value);
	    if (value == UCS_REPL) {
		fails = True;
	    } else if (value < 256) {
		AddChar(&buffer, &used, offset, CharOf(value));
	    } else {
		unsigned eqv = ucs2dec(screen, value);
		if (xtermIsDecGraphic(eqv)) {
		    AddChar(&buffer, &used, offset, DECtoASCII(eqv));
		} else {
		    eqv = AsciiEquivs(value);
		    if (eqv == value) {
			fails = True;
		    } else {
			AddChar(&buffer, &used, offset, eqv);
		    }
		    if (isWide((wchar_t) value))
			extra = True;
		}
	    }

	    /*
	     * If we're not able to plug in a single-byte result, insert the
	     * defaultString (which normally is a single "#", but could be
	     * whatever the user wants).
	     */
	    if (fails) {
		const Char *p;

		for (p = (const Char *) screen->default_string; *p != '\0'; ++p) {
		    AddChar(&buffer, &used, offset, *p);
		}
	    }
	    if (extra)
		AddChar(&buffer, &used, offset, ' ');
	}
	AddChar(&buffer, &used, offset, '\0');
	*result = (unsigned long) (offset - 1);
    } else {
	*result = 0;
    }
    return buffer;
}


static struct tree *file_info(struct augeas *aug, const char *fname) {
    char *path = NULL;
    struct tree *result = NULL;
    int r;

    r = pathjoin(&path, 2, AUGEAS_META_FILES, fname);
    ERR_NOMEM(r < 0, aug);

    result = tree_fpath(aug, path);
    ERR_BAIL(aug);
 error:
    free(path);
    return result;
}


void CoreNetwork::disablePingTimeout()
{
    _pingTimer.stop();
    _sendPings = false;
    resetPingTimeout();
}


COMPAT_SYSCALL_DEFINE2(rt_sigpending, compat_sigset_t __user *, uset,
		compat_size_t, sigsetsize)
{
#ifdef __BIG_ENDIAN
	sigset_t set;
	int err = do_sigpending(&set, sigsetsize);
	if (!err) {
		compat_sigset_t set32;
		sigset_to_compat(&set32, &set);
		/* we can get here only if sigsetsize <= sizeof(set) */
		if (copy_to_user(uset, &set32, sigsetsize))
			err = -EFAULT;
	}
	return err;
#else
	return sys_rt_sigpending((sigset_t __user *)uset, sigsetsize);
#endif
}


static int dns_resolver_match_preparse(struct key_match_data *match_data)
{
	match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
	match_data->cmp = dns_resolver_cmp;
	return 0;
}


jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
{
	jas_matrix_t *y;
	int i;
	int j;
	y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x),
	  jas_seq2d_yend(x));
	assert(y);
	for (i = 0; i < x->numrows_; ++i) {
		for (j = 0; j < x->numcols_; ++j) {
			*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
		}
	}
	return y;
}


GF_Err pasp_Write(GF_Box *s, GF_BitStream *bs)
{
	GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox *)s;
	GF_Err e = gf_isom_box_write_header(s, bs);
	if (e) return e;
	gf_bs_write_u32(bs, ptr->hSpacing);
	gf_bs_write_u32(bs, ptr->vSpacing);
	return GF_OK;
}


int sctp_verify_init(struct net *net, const struct sctp_endpoint *ep,
		     const struct sctp_association *asoc, sctp_cid_t cid,
		     sctp_init_chunk_t *peer_init, struct sctp_chunk *chunk,
		     struct sctp_chunk **errp)
{
	union sctp_params param;
	bool has_cookie = false;
	int result;

	/* Check for missing mandatory parameters. Note: Initial TSN is
	 * also mandatory, but is not checked here since the valid range
	 * is 0..2**32-1. RFC4960, section 3.3.3.
	 */
	if (peer_init->init_hdr.num_outbound_streams == 0 ||
	    peer_init->init_hdr.num_inbound_streams == 0 ||
	    peer_init->init_hdr.init_tag == 0 ||
	    ntohl(peer_init->init_hdr.a_rwnd) < SCTP_DEFAULT_MINWINDOW)
		return sctp_process_inv_mandatory(asoc, chunk, errp);

	sctp_walk_params(param, peer_init, init_hdr.params) {
		if (param.p->type == SCTP_PARAM_STATE_COOKIE)
			has_cookie = true;
	}

	/* There is a possibility that a parameter length was bad and
	 * in that case we would have stoped walking the parameters.
	 * The current param.p would point at the bad one.
	 * Current consensus on the mailing list is to generate a PROTOCOL
	 * VIOLATION error.  We build the ERROR chunk here and let the normal
	 * error handling code build and send the packet.
	 */
	if (param.v != (void *)chunk->chunk_end)
		return sctp_process_inv_paramlength(asoc, param.p, chunk, errp);

	/* The only missing mandatory param possible today is
	 * the state cookie for an INIT-ACK chunk.
	 */
	if ((SCTP_CID_INIT_ACK == cid) && !has_cookie)
		return sctp_process_missing_param(asoc, SCTP_PARAM_STATE_COOKIE,
						  chunk, errp);

	/* Verify all the variable length parameters */
	sctp_walk_params(param, peer_init, init_hdr.params) {
		result = sctp_verify_param(net, ep, asoc, param, cid,
					   chunk, errp);
		switch (result) {
		case SCTP_IERROR_ABORT:
		case SCTP_IERROR_NOMEM:
			return 0;
		case SCTP_IERROR_ERROR:
			return 1;
		case SCTP_IERROR_NO_ERROR:
		default:
			break;
		}

	} /* for (loop through all parameters) */

	return 1;
}


void ChromeContentBrowserClient::NavigationRequestRedirected(
    int frame_tree_node_id,
    const GURL& url,
    base::Optional<net::HttpRequestHeaders>* modified_request_headers) {
  WebContents* web_contents =
      WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  content::BrowserContext* browser_context = web_contents->GetBrowserContext();

  if (!browser_context->IsOffTheRecord()) {
    policy::PolicyHeaderService* policy_header_service =
        policy::PolicyHeaderServiceFactory::GetForBrowserContext(
            browser_context);
    if (policy_header_service) {
      std::unique_ptr<net::HttpRequestHeaders> extra_headers;
      policy_header_service->AddPolicyHeaders(url, &extra_headers);
      if (extra_headers)
        *modified_request_headers = std::move(*extra_headers);
    }
  }
}


GF_Err trex_Write(GF_Box *s, GF_BitStream *bs)
{
	GF_Err e;
	GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *) s;
	if (!s) return GF_BAD_PARAM;
	e = gf_isom_full_box_write(s, bs);
	if (e) return e;

	gf_bs_write_u32(bs, ptr->trackID);
	//we always write 1 in trex default sample desc as using 0 breaks chrome/opera/...
	gf_bs_write_u32(bs, ptr->def_sample_desc_index ? ptr->def_sample_desc_index : 1);
	gf_bs_write_u32(bs, ptr->def_sample_duration);
	gf_bs_write_u32(bs, ptr->def_sample_size);
	gf_bs_write_u32(bs, ptr->def_sample_flags);
	return GF_OK;