bool BackendImpl::ShouldReportAgain() {
  if (uma_report_)
    return uma_report_ == 2;

  uma_report_++;
  int64_t last_report = stats_.GetCounter(Stats::LAST_REPORT);
  Time last_time = Time::FromInternalValue(last_report);
  if (!last_report || (Time::Now() - last_time).InDays() >= 7) {
    stats_.SetCounter(Stats::LAST_REPORT, Time::Now().ToInternalValue());
    uma_report_++;
    return true;
  }
  return false;
}


static int rtl8150_get_settings(struct net_device *netdev, struct ethtool_cmd *ecmd)
{
	rtl8150_t *dev = netdev_priv(netdev);
	short lpa, bmcr;

	ecmd->supported = (SUPPORTED_10baseT_Half |
			  SUPPORTED_10baseT_Full |
			  SUPPORTED_100baseT_Half |
			  SUPPORTED_100baseT_Full |
			  SUPPORTED_Autoneg |
			  SUPPORTED_TP | SUPPORTED_MII);
	ecmd->port = PORT_TP;
	ecmd->transceiver = XCVR_INTERNAL;
	ecmd->phy_address = dev->phy;
	get_registers(dev, BMCR, 2, &bmcr);
	get_registers(dev, ANLP, 2, &lpa);
	if (bmcr & BMCR_ANENABLE) {
		u32 speed = ((lpa & (LPA_100HALF | LPA_100FULL)) ?
			     SPEED_100 : SPEED_10);
		ethtool_cmd_speed_set(ecmd, speed);
		ecmd->autoneg = AUTONEG_ENABLE;
		if (speed == SPEED_100)
			ecmd->duplex = (lpa & LPA_100FULL) ?
			    DUPLEX_FULL : DUPLEX_HALF;
		else
			ecmd->duplex = (lpa & LPA_10FULL) ?
			    DUPLEX_FULL : DUPLEX_HALF;
	} else {
		ecmd->autoneg = AUTONEG_DISABLE;
		ethtool_cmd_speed_set(ecmd, ((bmcr & BMCR_SPEED100) ?
					     SPEED_100 : SPEED_10));
		ecmd->duplex = (bmcr & BMCR_FULLDPLX) ?
		    DUPLEX_FULL : DUPLEX_HALF;
	}
	return 0;
}


HandleSignalsState DataPipeConsumerDispatcher::GetHandleSignalsStateNoLock()
    const {
  lock_.AssertAcquired();

  HandleSignalsState rv;
  if (shared_ring_buffer_.IsValid() && bytes_available_) {
    if (!in_two_phase_read_) {
      rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_READABLE;
      if (new_data_available_)
        rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE;
    }
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE;
  } else if (!peer_closed_ && shared_ring_buffer_.IsValid()) {
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE;
  }

  if (shared_ring_buffer_.IsValid()) {
    if (new_data_available_ || !peer_closed_)
      rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE;
  }

  if (peer_closed_) {
    rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  } else {
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_REMOTE;
    if (peer_remote_)
      rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_REMOTE;
  }
  rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;

  return rv;
}


void Browser::RegisterAppPrefs(const std::string& app_name, Profile* profile) {
  std::string window_pref(prefs::kBrowserWindowPlacement);
  window_pref.append("_");
  window_pref.append(app_name);
  PrefService* prefs = profile->GetPrefs();
  if (!prefs->FindPreference(window_pref.c_str())) {
    prefs->RegisterDictionaryPref(window_pref.c_str(),
                                  PrefService::UNSYNCABLE_PREF);
  }
}


do_conv(pam_handle_t *pamh, int msg_style, int num_msg,
    char messages[PAM_MAX_NUM_MSG][PAM_MAX_MSG_SIZE], void *conv_apdp,
    struct pam_response *ret_respp[])
{
	struct pam_message	*msg;
	struct pam_message	*m;
	int			i;
	int			k;
	int			retcode;
	struct pam_conv		*pam_convp;

	if ((retcode = pam_get_item(pamh, PAM_CONV,
	    (void **)&pam_convp)) != PAM_SUCCESS) {
		return (retcode);
	}

	/*
	 * When pam_set_item() is called to set PAM_CONV and the
	 * item is NULL, memset(pip->pi_addr, 0, size) is called.
	 * So at this point, we should check whether pam_convp->conv
	 * is NULL or not.
	 */
	if ((pam_convp == NULL) || (pam_convp->conv == NULL))
		return (PAM_SYSTEM_ERR);

	i = 0;
	k = num_msg;

	msg = calloc(num_msg, sizeof (struct pam_message));
	if (msg == NULL) {
		return (PAM_BUF_ERR);
	}
	m = msg;

	while (k--) {
		/*
		 * fill out the message structure to display prompt message
		 */
		m->msg_style = msg_style;
		m->msg = messages[i];
		pam_trace(PAM_DEBUG_CONV,
		    "pam_conv_msg(%p:%d[%d]=%s)",
		    (void *)pamh, msg_style, i, messages[i]);
		m++;
		i++;
	}

	/*
	 * The UNIX pam modules always calls __pam_get_authtok() and
	 * __pam_display_msg() with a NULL pointer as the conv_apdp.
	 * In case the conv_apdp is NULL and the pam_convp->appdata_ptr
	 * is not NULL, we should pass the pam_convp->appdata_ptr
	 * to the conversation function.
	 */
	if (conv_apdp == NULL && pam_convp->appdata_ptr != NULL)
		conv_apdp = pam_convp->appdata_ptr;

	/*
	 * Call conv function to display the prompt.
	 */
	retcode = (pam_convp->conv)(num_msg, &msg, ret_respp, conv_apdp);
	pam_trace(PAM_DEBUG_CONV,
	    "pam_conv_resp(%p pam_conv = %s) ret_respp = %p",
	    (void *)pamh, pam_strerror(pamh, retcode), (void *)ret_respp);
	if (*ret_respp == NULL) {
		pam_trace(PAM_DEBUG_CONV,
		    "pam_conv_resp(%p No response requested)", (void *)pamh);
	} else if ((pam_debug & (PAM_DEBUG_CONV | PAM_DEBUG_AUTHTOK)) != 0) {
		struct pam_response *r = *ret_respp;

		for (i = 0; i < num_msg; i++, r++) {
			if (r->resp == NULL) {
				pam_trace(PAM_DEBUG_CONV,
				    "pam_conv_resp(%p:"
				    "[%d] NULL response string)",
				    (void *)pamh, i);
			} else {
				if (msg_style == PAM_PROMPT_ECHO_OFF) {
#ifdef	DEBUG
					pam_trace(PAM_DEBUG_AUTHTOK,
					    "pam_conv_resp(%p:[%d]=%s, "
					    "code=%d)",
					    (void *)pamh, i, r->resp,
					    r->resp_retcode);
#endif	/* DEBUG */
					pam_trace(PAM_DEBUG_CONV,
					    "pam_conv_resp(%p:[%d] len=%lu, "
					    "code=%d)",
					    (void *)pamh, i,
					    (ulong_t)strlen(r->resp),
					    r->resp_retcode);
				} else {
					pam_trace(PAM_DEBUG_CONV,
					    "pam_conv_resp(%p:[%d]=%s, "
					    "code=%d)",
					    (void *)pamh, i, r->resp,
					    r->resp_retcode);
				}
			}
		}
	}

	if (msg)
		free(msg);
	return (retcode);
}


static int read_u64(struct archive_read* a, uint64_t* pvalue) {
	const uint8_t* p;
	if(!read_ahead(a, 8, &p))
		return 0;

	*pvalue = archive_le64dec(p);
	return ARCHIVE_OK == consume(a, 8) ? 1 : 0;
}


void WebPageProxy::showCorrectionPanel(int32_t panelType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings)
{
    m_pageClient->showCorrectionPanel((WebCore::CorrectionPanelInfo::PanelType)panelType, boundingBoxOfReplacedString, replacedString, replacementString, alternativeReplacementStrings);
}


PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& es)
{
    if (!isValidName(target)) {
        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
        return 0;
    }
    if (isHTMLDocument()) {
        es.throwUninformativeAndGenericDOMException(NotSupportedError);
        return 0;
    }
    return ProcessingInstruction::create(*this, target, data);
}


GF_Box *stts_New()
{
	ISOM_DECL_BOX_ALLOC(GF_TimeToSampleBox, GF_ISOM_BOX_TYPE_STTS);
	return (GF_Box *)tmp;
}


int FS_GetFileList(  const char *path, const char *extension, char *listbuf, int bufsize ) {
	int nFiles, i, nTotal, nLen;
	char **pFiles = NULL;

	*listbuf = 0;
	nFiles = 0;
	nTotal = 0;

	if ( Q_stricmp( path, "$modlist" ) == 0 ) {
		return FS_GetModList( listbuf, bufsize );
	}

	pFiles = FS_ListFiles( path, extension, &nFiles );

	for ( i = 0; i < nFiles; i++ ) {
		nLen = strlen( pFiles[i] ) + 1;
		if ( nTotal + nLen + 1 < bufsize ) {
			strcpy( listbuf, pFiles[i] );
			listbuf += nLen;
			nTotal += nLen;
		} else {
			nFiles = i;
			break;
		}
	}

	FS_FreeFileList( pFiles );

	return nFiles;
}


void RenderProcessHostImpl::WidgetHidden() {
  if (backgrounded_)
    return;

  DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
  visible_widgets_--;
  DCHECK_GE(visible_widgets_, 0);
  if (visible_widgets_ == 0) {
    DCHECK(!backgrounded_);
    SetBackgrounded(true);
  }
}


alloc_limit_assert (char *fn_name, size_t size)
{
    if (alloc_limit && size > alloc_limit)
    {
	alloc_limit_failure (fn_name, size);
	exit (-1);
    }
}


void gf_m2ts_demux_dmscc_init(GF_M2TS_Demuxer *ts) {

	char temp_dir[GF_MAX_PATH];
	u32 length;
	GF_Err e;

	ts->dsmcc_controler = gf_list_new();
	ts->process_dmscc = 1;

	strcpy(temp_dir, gf_get_default_cache_directory() );
	length = (u32) strlen(temp_dir);
	if(temp_dir[length-1] == GF_PATH_SEPARATOR) {
		temp_dir[length-1] = 0;
	}

	ts->dsmcc_root_dir = (char*)gf_calloc(strlen(temp_dir)+strlen("CarouselData")+2,sizeof(char));
	sprintf(ts->dsmcc_root_dir,"%s%cCarouselData",temp_dir,GF_PATH_SEPARATOR);
	e = gf_mkdir(ts->dsmcc_root_dir);
	if(e) {
		GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[Process DSMCC] Error during the creation of the directory %s \n",ts->dsmcc_root_dir));
	}

}


char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) {
	int nfiles;
	char            **listCopy;
	char            *list[MAX_FOUND_FILES];
	searchpath_t    *search;
	int i;
	int pathLength;
	int extensionLength;
	int length, pathDepth, temp;
	pack_t          *pak;
	fileInPack_t    *buildBuffer;
	char zpath[MAX_ZPATH];

	if ( !fs_searchpaths ) {
		Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
	}

	if ( !path ) {
		*numfiles = 0;
		return NULL;
	}
	if ( !extension ) {
		extension = "";
	}

	pathLength = strlen( path );
	if ( path[pathLength - 1] == '\\' || path[pathLength - 1] == '/' ) {
		pathLength--;
	}
	extensionLength = strlen( extension );
	nfiles = 0;
	FS_ReturnPath( path, zpath, &pathDepth );

	//
	// search through the path, one element at a time, adding to list
	//
	for ( search = fs_searchpaths ; search ; search = search->next ) {
		// is the element a pak file?
		if ( search->pack ) {

			//ZOID:  If we are pure, don't search for files on paks that
			// aren't on the pure list
			if ( !FS_PakIsPure( search->pack ) ) {
				continue;
			}

			// look through all the pak file elements
			pak = search->pack;
			buildBuffer = pak->buildBuffer;
			for ( i = 0; i < pak->numfiles; i++ ) {
				char    *name;
				int zpathLen, depth;

				// check for directory match
				name = buildBuffer[i].name;
				//
				if ( filter ) {
					// case insensitive
					if ( !Com_FilterPath( filter, name, qfalse ) ) {
						continue;
					}
					// unique the match
					nfiles = FS_AddFileToList( name, list, nfiles );
				} else {

					zpathLen = FS_ReturnPath( name, zpath, &depth );

					if ( ( depth - pathDepth ) > 2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
						continue;
					}

					// check for extension match
					length = strlen( name );
					if ( length < extensionLength ) {
						continue;
					}

					if ( Q_stricmp( name + length - extensionLength, extension ) ) {
						continue;
					}
					// unique the match

					temp = pathLength;
					if ( pathLength ) {
						temp++;     // include the '/'
					}
					nfiles = FS_AddFileToList( name + temp, list, nfiles );
				}
			}
		} else if ( search->dir ) { // scan for files in the filesystem
			char    *netpath;
			int numSysFiles;
			char    **sysFiles;
			char    *name;

			// don't scan directories for files if we are pure or restricted
			if ( fs_numServerPaks && !allowNonPureFilesOnDisk ) {
				continue;
			} else {
				netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
				sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
				for ( i = 0 ; i < numSysFiles ; i++ ) {
					// unique the match
					name = sysFiles[i];
					nfiles = FS_AddFileToList( name, list, nfiles );
				}
				Sys_FreeFileList( sysFiles );
			}
		}
	}

	// return a copy of the list
	*numfiles = nfiles;

	if ( !nfiles ) {
		return NULL;
	}

	listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
	for ( i = 0 ; i < nfiles ; i++ ) {
		listCopy[i] = list[i];
	}
	listCopy[i] = NULL;

	return listCopy;
}


static void percpu_modfree(struct module *mod)
{
	free_percpu(mod->percpu);
}


const struct hid_device_id *hid_match_id(struct hid_device *hdev,
		const struct hid_device_id *id)
{
	for (; id->bus; id++)
		if (hid_match_one_id(hdev, id))
			return id;

	return NULL;
}


IsoPresentation_parseUserData(IsoPresentation* self, ByteBuffer* readBuffer)
{
    uint8_t* buffer = readBuffer->buffer;
    int maxBufPos = readBuffer->size;
    bool hasAbstractSyntaxName = false;

    int bufPos = 0;

    if (maxBufPos < 9)
        return 0;

    if (buffer[bufPos++] != 0x61)
        return 0;

    int len;

    bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, maxBufPos);

    if (bufPos < 0) {
        if (DEBUG_PRES)
            printf("PRES: invalid message!\n");
        return 0;
    }

    if (buffer[bufPos++] != 0x30)
        return 0;

    bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, maxBufPos);

    if (bufPos < 0) {
        if (DEBUG_PRES)
            printf("PRES: invalid message!\n");
        return 0;
    }

    while (bufPos < maxBufPos) {
        uint8_t tag = buffer[bufPos++];
        uint8_t lenField = buffer[bufPos];

        bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, maxBufPos);

        if (bufPos < 0) {
            if (DEBUG_PRES)
                printf("PRES: wrong parameter length\n");
            return 0;
        }

        switch (tag) {
        case 0x02: /* abstract-syntax-name */
            self->nextContextId = buffer[bufPos];
            hasAbstractSyntaxName = true;
            bufPos += len;
            break;

        case 0x06: /* transfer-syntax-name */
            {
                /* check if basic-encoding (2.1.1 - 51 01) */
                if ((buffer[bufPos] != 0x51) || (buffer[bufPos + 1] != 0x01)) {
                    if (DEBUG_PRES) {
                        printf("PRES: unknown transfer-syntax-name\n");
                    }

                    return 0;
                }

                bufPos += len;
            }
            break;

        case 0xa0: /* presentation data */
            {
                if (hasAbstractSyntaxName == false) {
                    if (DEBUG_PRES)
                        printf("PRES: abstract-syntax-name missing!\n");

                    return 0;
                }

                int userDataLength = len;

                if (lenField == 0x80)
                    userDataLength = userDataLength - 2;

                ByteBuffer_wrap(&(self->nextPayload), buffer + bufPos, userDataLength, userDataLength);

                return 1;
            }
            break;
        }
    }

    return 0;
}


void LayerWebKitThread::updateLayerHierarchy()
{
    m_layerCompositingThread->setSuperlayer(superlayer() ? superlayer()->m_layerCompositingThread.get() : 0);

    Vector<RefPtr<LayerCompositingThread> > sublayers;
    size_t listSize = m_overlays.size();
    for (size_t i = 0; i < listSize; ++i)
        sublayers.append(m_overlays[i]->m_layerCompositingThread.get());
    listSize = m_sublayers.size();
    for (size_t i = 0; i < listSize; ++i)
        sublayers.append(m_sublayers[i]->m_layerCompositingThread.get());
    m_layerCompositingThread->setSublayers(sublayers);
}


bool DecodeResourceHandleList(std::unique_ptr<port::StringListDecoder> d,
                              ResourceHandle* ps, int64_t n) {
  std::vector<uint32> sizes(n);
  if (!d->ReadSizes(&sizes)) return false;

  ResourceHandleProto proto;
  for (int i = 0; i < n; ++i) {
    if (!proto.ParseFromArray(d->Data(sizes[i]), sizes[i])) {
      return false;
    }
    if (!ps[i].FromProto(proto).ok()) {
      return false;
    }
  }
  return true;
}


  PosibErr<bool> Config::retrieve_bool(ParmStr key) const
  {
    RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki);
    if (ki->type != KeyInfoBool) return make_err(key_not_bool, ki->name);

    const Entry * cur = lookup(ki->name);

    String value(cur ? cur->value : get_default(ki));

    if (value == "false") return false;
    else                  return true;
  }


enc_canon_props(char_u *name)
{
    int		i;

    i = enc_canon_search(name);
    if (i >= 0)
	return enc_canon_table[i].prop;
#ifdef MSWIN
    if (name[0] == 'c' && name[1] == 'p' && VIM_ISDIGIT(name[2]))
    {
	CPINFO	cpinfo;

	// Get info on this codepage to find out what it is.
	if (GetCPInfo(atoi((char *)name + 2), &cpinfo) != 0)
	{
	    if (cpinfo.MaxCharSize == 1) // some single-byte encoding
		return ENC_8BIT;
	    if (cpinfo.MaxCharSize == 2
		    && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0))
		// must be a DBCS encoding
		return ENC_DBCS;
	}
	return 0;
    }
#endif
    if (STRNCMP(name, "2byte-", 6) == 0)
	return ENC_DBCS;
    if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0)
	return ENC_8BIT;
    return 0;
}


static void vgacon_cursor(struct vc_data *c, int mode)
{
	if (c->vc_mode != KD_TEXT)
		return;

	vgacon_restore_screen(c);

	switch (mode) {
	case CM_ERASE:
		write_vga(14, (c->vc_pos - vga_vram_base) / 2);
	        if (vga_video_type >= VIDEO_TYPE_VGAC)
			vgacon_set_cursor_size(c->state.x, 31, 30);
		else
			vgacon_set_cursor_size(c->state.x, 31, 31);
		break;

	case CM_MOVE:
	case CM_DRAW:
		write_vga(14, (c->vc_pos - vga_vram_base) / 2);
		switch (CUR_SIZE(c->vc_cursor_type)) {
		case CUR_UNDERLINE:
			vgacon_set_cursor_size(c->state.x,
					       c->vc_font.height -
					       (c->vc_font.height <
						10 ? 2 : 3),
					       c->vc_font.height -
					       (c->vc_font.height <
						10 ? 1 : 2));
			break;
		case CUR_TWO_THIRDS:
			vgacon_set_cursor_size(c->state.x,
					       c->vc_font.height / 3,
					       c->vc_font.height -
					       (c->vc_font.height <
						10 ? 1 : 2));
			break;
		case CUR_LOWER_THIRD:
			vgacon_set_cursor_size(c->state.x,
					       (c->vc_font.height * 2) / 3,
					       c->vc_font.height -
					       (c->vc_font.height <
						10 ? 1 : 2));
			break;
		case CUR_LOWER_HALF:
			vgacon_set_cursor_size(c->state.x,
					       c->vc_font.height / 2,
					       c->vc_font.height -
					       (c->vc_font.height <
						10 ? 1 : 2));
			break;
		case CUR_NONE:
			if (vga_video_type >= VIDEO_TYPE_VGAC)
				vgacon_set_cursor_size(c->state.x, 31, 30);
			else
				vgacon_set_cursor_size(c->state.x, 31, 31);
			break;
		default:
			vgacon_set_cursor_size(c->state.x, 1,
					       c->vc_font.height);
			break;
		}
		break;
	}
}


Settings* Document::GetSettings() const {
  return frame_ ? frame_->GetSettings() : nullptr;
}


int Jsi_NumberIsInfinity(Jsi_Number a) {
#if JSI__MUSL==1 || defined(__FreeBSD__) || defined(__WIN32)
    if (!isinf(a))
        return 0;
    return (a<0 ? -1 : 1);
#else
    return isinf(a);
#endif
}


static void js_initvar(js_State *J, const char *name, int idx)
{
	jsR_defproperty(J, J->E->variables, name, JS_DONTENUM | JS_DONTCONF, stackidx(J, idx), NULL, NULL);
}


  void Compute(OpKernelContext* context) override {
    const Tensor& tensor_in = context->input(0);
    const Tensor& tensor_out = context->input(1);
    const Tensor& out_grad_backprop = context->input(2);

    // For maxpooling3d, tensor_in should have 5 dimensions.
    OP_REQUIRES(context, tensor_in.dims() == 5,
                errors::InvalidArgument("tensor_in must be 5-dimensional"));
    OP_REQUIRES(context, tensor_out.dims() == 5,
                errors::InvalidArgument("tensor_out must be 5-dimensional"));
    // For maxpooling3d, out_grad_backprop should have 5 dimensions.
    OP_REQUIRES(
        context, out_grad_backprop.dims() == 5,
        errors::InvalidArgument("out_grad_backprop must be 5-dimensional"));

    Pool3dParameters params{context,  ksize_,       stride_,
                            padding_, data_format_, tensor_in.shape()};
    if (!context->status().ok()) return;  // params is invalid

    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
                                {2}, 0, tensor_out.shape(), &output));

    // Given access patterns in LaunchMaxPooling3dGradGradOp, these tensors must
    // have elements.
    OP_REQUIRES(context, tensor_in.NumElements() > 0,
                errors::InvalidArgument("received empty tensor tensor_in: ",
                                        tensor_in.DebugString()));
    OP_REQUIRES(context, tensor_out.NumElements() > 0,
                errors::InvalidArgument("received empty tensor tensor_out: ",
                                        tensor_out.DebugString()));
    OP_REQUIRES(
        context, out_grad_backprop.NumElements() > 0,
        errors::InvalidArgument("received empty tensor out_grad_backprop: ",
                                out_grad_backprop.DebugString()));
    OP_REQUIRES(context,
                tensor_in.NumElements() == out_grad_backprop.NumElements(),
                errors::InvalidArgument("tensor_in and out_grad_backprop must "
                                        "have same number of elements, got <",
                                        tensor_in.DebugString(), "> and <",
                                        out_grad_backprop.DebugString(), ">"));
    OP_REQUIRES(
        context, tensor_out.NumElements() == output->NumElements(),
        errors::InvalidArgument(
            "tensor_out and output must have same number of elements, got <",
            tensor_out.DebugString(), "> and <", output->DebugString(), ">"));

    LaunchMaxPooling3dGradGradOp<Device, T>::launch(
        context, params, tensor_in, tensor_out, out_grad_backprop, output);
  }


utf_char2len(int c)
{
    if (c < 0x80)
	return 1;
    if (c < 0x800)
	return 2;
    if (c < 0x10000)
	return 3;
    if (c < 0x200000)
	return 4;
    if (c < 0x4000000)
	return 5;
    return 6;
}


static int gif_read_header1(GifState *s)

{

    uint8_t sig[6];

    int v, n;

    int background_color_index;

    if (bytestream2_get_bytes_left(&s->gb) < 13)

        return AVERROR_INVALIDDATA;

    /* read gif signature */

    bytestream2_get_bufferu(&s->gb, sig, 6);

    if (memcmp(sig, gif87a_sig, 6) != 0 &&

        memcmp(sig, gif89a_sig, 6) != 0)

        return AVERROR_INVALIDDATA;

    /* read screen header */

    s->transparent_color_index = -1;

    s->screen_width = bytestream2_get_le16u(&s->gb);

    s->screen_height = bytestream2_get_le16u(&s->gb);

    if(   (unsigned)s->screen_width  > 32767

       || (unsigned)s->screen_height > 32767){

        av_log(s->avctx, AV_LOG_ERROR, "picture size too large\n");

        return AVERROR_INVALIDDATA;

    }

    av_fast_malloc(&s->idx_line, &s->idx_line_size, s->screen_width);

    if (!s->idx_line)

        return AVERROR(ENOMEM);

    v = bytestream2_get_byteu(&s->gb);

    s->color_resolution = ((v & 0x70) >> 4) + 1;

    s->has_global_palette = (v & 0x80);

    s->bits_per_pixel = (v & 0x07) + 1;

    background_color_index = bytestream2_get_byteu(&s->gb);

    n = bytestream2_get_byteu(&s->gb);

    if (n) {

        s->avctx->sample_aspect_ratio.num = n + 15;

        s->avctx->sample_aspect_ratio.den = 64;

    }

    av_dlog(s->avctx, "screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",

           s->screen_width, s->screen_height, s->bits_per_pixel,

           s->has_global_palette);

    if (s->has_global_palette) {

        s->background_color_index = background_color_index;

        n = 1 << s->bits_per_pixel;

        if (bytestream2_get_bytes_left(&s->gb) < n * 3)

            return AVERROR_INVALIDDATA;

        gif_read_palette(s, s->global_palette, n);

        s->bg_color = s->global_palette[s->background_color_index];

    } else

        s->background_color_index = -1;

    return 0;

}


static int default_fdset_dup_fd_remove(int dup_fd)

{

    return -1;

}


error::Error GLES2DecoderImpl::HandleGetVertexAttribPointerv(
    uint32_t immediate_data_size,
    const volatile void* cmd_data) {
  const volatile gles2::cmds::GetVertexAttribPointerv& c =
      *static_cast<const volatile gles2::cmds::GetVertexAttribPointerv*>(
          cmd_data);
  GLuint index = static_cast<GLuint>(c.index);
  GLenum pname = static_cast<GLenum>(c.pname);
  typedef cmds::GetVertexAttribPointerv::Result Result;
  Result* result = GetSharedMemoryAs<Result*>(
        c.pointer_shm_id, c.pointer_shm_offset, Result::ComputeSize(1));
  if (!result) {
    return error::kOutOfBounds;
  }
  if (result->size != 0) {
    return error::kInvalidArguments;
  }
  if (!validators_->vertex_pointer.IsValid(pname)) {
    LOCAL_SET_GL_ERROR_INVALID_ENUM(
        "glGetVertexAttribPointerv", pname, "pname");
    return error::kNoError;
  }
  if (index >= group_->max_vertex_attribs()) {
    LOCAL_SET_GL_ERROR(
        GL_INVALID_VALUE, "glGetVertexAttribPointerv", "index out of range.");
    return error::kNoError;
  }
  result->SetNumResults(1);
  *result->GetData() =
      state_.vertex_attrib_manager->GetVertexAttrib(index)->offset();
  return error::kNoError;
}


static int dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
{
    dtls1_set_message_header(s, htype, len, 0, len);
    s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
    s->init_off = 0;
    /* Buffer the message to handle re-xmits */

    if (!dtls1_buffer_message(s, 0))
        return 0;

    return 1;
}


error::Error GLES2DecoderImpl::HandleGetProgramInfoLog(
    uint32 immediate_data_size, const cmds::GetProgramInfoLog& c) {
  GLuint program_id = c.program;
  uint32 bucket_id = static_cast<uint32>(c.bucket_id);
  Bucket* bucket = CreateBucket(bucket_id);
  Program* program = GetProgramInfoNotShader(
      program_id, "glGetProgramInfoLog");
  if (!program || !program->log_info()) {
    bucket->SetFromString("");
    return error::kNoError;
  }
  bucket->SetFromString(program->log_info()->c_str());
  return error::kNoError;
}


void * ps2_mouse_init ( void ( * update_irq ) ( void * , int ) , void * update_arg ) {
 PS2MouseState * s = ( PS2MouseState * ) g_malloc0 ( sizeof ( PS2MouseState ) ) ;
 trace_ps2_mouse_init ( s ) ;
 s -> common . update_irq = update_irq ;
 s -> common . update_arg = update_arg ;
 vmstate_register ( NULL , 0 , & vmstate_ps2_mouse , s ) ;
 qemu_input_handler_register ( ( DeviceState * ) s , & ps2_mouse_handler ) ;
 qemu_register_reset ( ps2_mouse_reset , s ) ;
 return s ;
 }


}

static char *format_date(u64 time, char *szTime)
{
	time_t now;
	if (!time) {
		strcpy(szTime, "UNKNOWN DATE");
	} else {
		time -= 2082844800;
		now = (u32) time;
		sprintf(szTime, "GMT %s", asctime(gf_gmtime(&now)) );
	}


int ext4_can_truncate(struct inode *inode)
{
	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
		return 0;
	if (S_ISREG(inode->i_mode))
		return 1;
	if (S_ISDIR(inode->i_mode))
		return 1;
	if (S_ISLNK(inode->i_mode))
		return !ext4_inode_is_fast_symlink(inode);
	return 0;
}


bitmap_decompress(uint8 * output, int width, int height, uint8 * input, int size, int Bpp)
{
	RD_BOOL rv = False;

	switch (Bpp)
	{
		case 1:
			rv = bitmap_decompress1(output, width, height, input, size);
			break;
		case 2:
			rv = bitmap_decompress2(output, width, height, input, size);
			break;
		case 3:
			rv = bitmap_decompress3(output, width, height, input, size);
			break;
		case 4:
			rv = bitmap_decompress4(output, width, height, input, size);
			break;
		default:
			logger(Core, Debug, "bitmap_decompress(), unhandled BPP %d", Bpp);
			break;
	}
	return rv;
}


void WindowTreeHostManager::PreDisplayConfigurationChange(bool clear_focus) {
  FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
  focus_activation_store_->Store(clear_focus);
  display::Screen* screen = display::Screen::GetScreen();
  gfx::Point point_in_screen = screen->GetCursorScreenPoint();
  cursor_location_in_screen_coords_for_restore_ = point_in_screen;

  display::Display display = screen->GetDisplayNearestPoint(point_in_screen);
  cursor_display_id_for_restore_ = display.id();

  gfx::Point point_in_native = point_in_screen;
  aura::Window* root_window = GetRootWindowForDisplayId(display.id());
  ::wm::ConvertPointFromScreen(root_window, &point_in_native);
  root_window->GetHost()->ConvertPointToNativeScreen(&point_in_native);
  cursor_location_in_native_coords_for_restore_ = point_in_native;
}


static int f_midi_in_close(struct snd_rawmidi_substream *substream)
{
	struct f_midi *midi = substream->rmidi->private_data;

	VDBG(midi, "%s()\n", __func__);
	return 0;
}


static ossl_inline int sk_ ## t1 ## _find_ex ( STACK_OF ( t1 ) * sk , t2 * ptr ) {
 return OPENSSL_sk_find_ex ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ;
 }
 static ossl_inline void sk_ ## t1 ## _sort ( STACK_OF ( t1 ) * sk ) {
 OPENSSL_sk_sort ( ( OPENSSL_STACK * ) sk ) ;
 }
 static ossl_inline int sk_ ## t1 ## _is_sorted ( const STACK_OF ( t1 ) * sk ) {
 return OPENSSL_sk_is_sorted ( ( const OPENSSL_STACK * ) sk ) ;
 }
 static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _dup ( const STACK_OF ( t1 ) * sk ) {
 return ( STACK_OF ( t1 ) * ) OPENSSL_sk_dup ( ( const OPENSSL_STACK * ) sk ) ;
 }
 static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _deep_copy ( const STACK_OF ( t1 ) * sk , sk_ ## t1 ## _copyfunc copyfunc , sk_ ## t1 ## _freefunc freefunc ) {
 return ( STACK_OF ( t1 ) * ) OPENSSL_sk_deep_copy ( ( const OPENSSL_STACK * ) sk , ( OPENSSL_sk_copyfunc ) copyfunc , ( OPENSSL_sk_freefunc ) freefunc ) ;
 }
 static ossl_inline sk_ ## t1 ## _compfunc sk_ ## t1 ## _set_cmp_func ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _compfunc compare ) {
 return ( sk_ ## t1 ## _compfunc ) OPENSSL_sk_set_cmp_func ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_compfunc ) compare ) ;
 }
 # define DEFINE_SPECIAL_STACK_OF ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , t2 , t2 ) # define DEFINE_STACK_OF ( t ) SKM_DEFINE_STACK_OF ( t , t , t ) # define DEFINE_SPECIAL_STACK_OF_CONST ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , const t2 , t2 ) # define DEFINE_STACK_OF_CONST ( t ) SKM_DEFINE_STACK_OF ( t , const t , t ) typedef char * OPENSSL_STRING ;
 typedef const char * OPENSSL_CSTRING ;
 DEFINE_SPECIAL_STACK_OF ( OPENSSL_STRING , char )


Status AutoParallel::Optimize(Cluster* cluster, const GrapplerItem& item,
                              GraphDef* output) {
  TF_RETURN_IF_ERROR(Initialize(item));
  BuildGraph(output);
  return Status::OK();
}


static avifBool avifParseSampleSizeBox(avifSampleTable * sampleTable, const uint8_t * raw, size_t rawLen)
{
    BEGIN_STREAM(s, raw, rawLen);

    CHECK(avifROStreamReadAndEnforceVersion(&s, 0));

    uint32_t allSamplesSize, sampleCount;
    CHECK(avifROStreamReadU32(&s, &allSamplesSize)); // unsigned int(32) sample_size;
    CHECK(avifROStreamReadU32(&s, &sampleCount));    // unsigned int(32) sample_count;

    if (allSamplesSize > 0) {
        sampleTable->allSamplesSize = allSamplesSize;
    } else {
        for (uint32_t i = 0; i < sampleCount; ++i) {
            avifSampleTableSampleSize * sampleSize = (avifSampleTableSampleSize *)avifArrayPushPtr(&sampleTable->sampleSizes);
            CHECK(avifROStreamReadU32(&s, &sampleSize->size)); // unsigned int(32) entry_size;
        }
    }
    return AVIF_TRUE;
}


explicit InterpreterInfo(Subgraph* subgraph) : subgraph_(subgraph) {}


static void mips_tlb_flush_extra (CPUState *env, int first)

{

    /* Discard entries from env->tlb[first] onwards.  */

    while (env->tlb_in_use > first) {

        invalidate_tlb(--env->tlb_in_use, 0);

    }

}


static __sum16 __tcp_checksum_complete_user(struct sock *sk,
					    struct sk_buff *skb)
{
	__sum16 result;

	if (sock_owned_by_user(sk)) {
		local_bh_enable();
		result = __tcp_checksum_complete(skb);
		local_bh_disable();
	} else {
		result = __tcp_checksum_complete(skb);
	}
	return result;
}


xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) {
    const xmlChar *in;
    int nbchar = 0;
    int line = ctxt->input->line;
    int col = ctxt->input->col;
    int ccol;

    SHRINK;
    GROW;
    /*
     * Accelerated common case where input don't need to be
     * modified before passing it to the handler.
     */
    if (!cdata) {
	in = ctxt->input->cur;
	do {
get_more_space:
	    while (*in == 0x20) { in++; ctxt->input->col++; }
	    if (*in == 0xA) {
		do {
		    ctxt->input->line++; ctxt->input->col = 1;
		    in++;
		} while (*in == 0xA);
		goto get_more_space;
	    }
	    if (*in == '<') {
		nbchar = in - ctxt->input->cur;
		if (nbchar > 0) {
		    const xmlChar *tmp = ctxt->input->cur;
		    ctxt->input->cur = in;

		    if ((ctxt->sax != NULL) &&
		        (ctxt->sax->ignorableWhitespace !=
		         ctxt->sax->characters)) {
			if (areBlanks(ctxt, tmp, nbchar, 1)) {
			    if (ctxt->sax->ignorableWhitespace != NULL)
				ctxt->sax->ignorableWhitespace(ctxt->userData,
						       tmp, nbchar);
			} else {
			    if (ctxt->sax->characters != NULL)
				ctxt->sax->characters(ctxt->userData,
						      tmp, nbchar);
			    if (*ctxt->space == -1)
			        *ctxt->space = -2;
			}
		    } else if ((ctxt->sax != NULL) &&
		               (ctxt->sax->characters != NULL)) {
			ctxt->sax->characters(ctxt->userData,
					      tmp, nbchar);
		    }
		}
		return;
	    }

get_more:
            ccol = ctxt->input->col;
	    while (test_char_data[*in]) {
		in++;
		ccol++;
	    }
	    ctxt->input->col = ccol;
	    if (*in == 0xA) {
		do {
		    ctxt->input->line++; ctxt->input->col = 1;
		    in++;
		} while (*in == 0xA);
		goto get_more;
	    }
	    if (*in == ']') {
		if ((in[1] == ']') && (in[2] == '>')) {
		    xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
		    ctxt->input->cur = in;
		    return;
		}
		in++;
		ctxt->input->col++;
		goto get_more;
	    }
	    nbchar = in - ctxt->input->cur;
	    if (nbchar > 0) {
		if ((ctxt->sax != NULL) &&
		    (ctxt->sax->ignorableWhitespace !=
		     ctxt->sax->characters) &&
		    (IS_BLANK_CH(*ctxt->input->cur))) {
		    const xmlChar *tmp = ctxt->input->cur;
		    ctxt->input->cur = in;

		    if (areBlanks(ctxt, tmp, nbchar, 0)) {
		        if (ctxt->sax->ignorableWhitespace != NULL)
			    ctxt->sax->ignorableWhitespace(ctxt->userData,
							   tmp, nbchar);
		    } else {
		        if (ctxt->sax->characters != NULL)
			    ctxt->sax->characters(ctxt->userData,
						  tmp, nbchar);
			if (*ctxt->space == -1)
			    *ctxt->space = -2;
		    }
                    line = ctxt->input->line;
                    col = ctxt->input->col;
		} else if (ctxt->sax != NULL) {
		    if (ctxt->sax->characters != NULL)
			ctxt->sax->characters(ctxt->userData,
					      ctxt->input->cur, nbchar);
                    line = ctxt->input->line;
                    col = ctxt->input->col;
		}
                /* something really bad happened in the SAX callback */
                if (ctxt->instate != XML_PARSER_CONTENT)
                    return;
	    }
	    ctxt->input->cur = in;
	    if (*in == 0xD) {
		in++;
		if (*in == 0xA) {
		    ctxt->input->cur = in;
		    in++;
		    ctxt->input->line++; ctxt->input->col = 1;
		    continue; /* while */
		}
		in--;
	    }
	    if (*in == '<') {
		return;
	    }
	    if (*in == '&') {
		return;
	    }
	    SHRINK;
	    GROW;
            if (ctxt->instate == XML_PARSER_EOF)
		return;
	    in = ctxt->input->cur;
	} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
	nbchar = 0;
    }
    ctxt->input->line = line;
    ctxt->input->col = col;
    xmlParseCharDataComplex(ctxt, cdata);
}


void vp9_idct32x32_1_add_sse2 ( const int16_t * input , uint8_t * dest , int stride ) {
 __m128i dc_value ;
 const __m128i zero = _mm_setzero_si128 ( ) ;
 int a , i ;
 a = dct_const_round_shift ( input [ 0 ] * cospi_16_64 ) ;
 a = dct_const_round_shift ( a * cospi_16_64 ) ;
 a = ROUND_POWER_OF_TWO ( a , 6 ) ;
 dc_value = _mm_set1_epi16 ( a ) ;
 for ( i = 0 ;
 i < 4 ;
 ++ i ) {
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 RECON_AND_STORE ( dest , dc_value ) ;
 dest += 8 - ( stride * 32 ) ;
 }
 }


is_ccb_file( const char *name )
{
	if( strstr(name,".ccb_reconnect") ) {
		return TRUE;
	}
	return FALSE;
}


static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock,
		    struct buffer_head *bh_result, int create)
{
	int ret = 0;
	struct ocfs2_inode_info *oi = OCFS2_I(inode);

	down_read(&oi->ip_alloc_sem);
	ret = ocfs2_get_block(inode, iblock, bh_result, create);
	up_read(&oi->ip_alloc_sem);

	return ret;
}


void Magick::Image::contrastStretch(const double blackPoint_,
  const double whitePoint_)
{
  modifyImage();
  GetPPException;
  ContrastStretchImage(image(),blackPoint_,whitePoint_,exceptionInfo);
  ThrowImageException;
}


bool PopupContainer::handleKeyEvent(const PlatformKeyboardEvent& event)
{
    UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
    return m_listBox->handleKeyEvent(event);
}


int ff_get_best_fcode ( MpegEncContext * s , int16_t ( * mv_table ) [ 2 ] , int type ) {
 if ( s -> me_method >= ME_EPZS ) {
 int score [ 8 ] ;
 int i , y , range = s -> avctx -> me_range ? s -> avctx -> me_range : ( INT_MAX / 2 ) ;
 uint8_t * fcode_tab = s -> fcode_tab ;
 int best_fcode = - 1 ;
 int best_score = - 10000000 ;
 if ( s -> msmpeg4_version ) range = FFMIN ( range , 16 ) ;
 else if ( s -> codec_id == AV_CODEC_ID_MPEG2VIDEO && s -> avctx -> strict_std_compliance >= FF_COMPLIANCE_NORMAL ) range = FFMIN ( range , 256 ) ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) score [ i ] = s -> mb_num * ( 8 - i ) ;
 for ( y = 0 ;
 y < s -> mb_height ;
 y ++ ) {
 int x ;
 int xy = y * s -> mb_stride ;
 for ( x = 0 ;
 x < s -> mb_width ;
 x ++ ) {
 if ( s -> mb_type [ xy ] & type ) {
 int mx = mv_table [ xy ] [ 0 ] ;
 int my = mv_table [ xy ] [ 1 ] ;
 int fcode = FFMAX ( fcode_tab [ mx + MAX_MV ] , fcode_tab [ my + MAX_MV ] ) ;
 int j ;
 if ( mx >= range || mx < - range || my >= range || my < - range ) continue ;
 for ( j = 0 ;
 j < fcode && j < 8 ;
 j ++ ) {
 if ( s -> pict_type == AV_PICTURE_TYPE_B || s -> current_picture . mc_mb_var [ xy ] < s -> current_picture . mb_var [ xy ] ) score [ j ] -= 170 ;
 }
 }
 xy ++ ;
 }
 }
 for ( i = 1 ;
 i < 8 ;
 i ++ ) {
 if ( score [ i ] > best_score ) {
 best_score = score [ i ] ;
 best_fcode = i ;
 }
 }
 return best_fcode ;
 }
 else {
 return 1 ;
 }
 }


static int cms_signerinfo_verify_cert(CMS_SignerInfo *si,
					X509_STORE *store,
					STACK_OF(X509) *certs,
					STACK_OF(X509_CRL) *crls,
					unsigned int flags)
	{
	X509_STORE_CTX ctx;
	X509 *signer;
	int i, j, r = 0;
	CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL);
	if (!X509_STORE_CTX_init(&ctx, store, signer, certs))
		{
		CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CERT,
						CMS_R_STORE_INIT_ERROR);
		goto err;
		}
	X509_STORE_CTX_set_default(&ctx, "smime_sign");
	if (crls)
		X509_STORE_CTX_set0_crls(&ctx, crls);

	i = X509_verify_cert(&ctx);
	if (i <= 0)
		{
		j = X509_STORE_CTX_get_error(&ctx);
		CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CERT,
						CMS_R_CERTIFICATE_VERIFY_ERROR);
		ERR_add_error_data(2, "Verify error:",
					 X509_verify_cert_error_string(j));
		goto err;
		}
	r = 1;
	err:
	X509_STORE_CTX_cleanup(&ctx);
	return r;

	}


void gf_sm_update_bitwrapper_buffer(GF_Node *node, const char *fileName)
{
	u32 data_size = 0;
	char *data = NULL;
	char *buffer;
	M_BitWrapper *bw = (M_BitWrapper *)node;

	if (!bw->buffer.buffer) return;
	buffer = bw->buffer.buffer;
	if (!strnicmp(buffer, "file://", 7)) {
		char *url = gf_url_concatenate(fileName, buffer+7);
		if (url) {
			FILE *f = gf_fopen(url, "rb");
			if (f) {
				fseek(f, 0, SEEK_END);
				data_size = (u32) ftell(f);
				fseek(f, 0, SEEK_SET);
				data = gf_malloc(sizeof(char)*data_size);
				if (data) {
					if (fread(data, 1, data_size, f) != data_size) {
						GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] error reading bitwrapper file %s\n", url));
					}
				}
				gf_fclose(f);
			}
			gf_free(url);
		}
	} else {
		Bool base_64 = 0;
		if (!strnicmp(buffer, "data:application/octet-string", 29)) {
			char *sep = strchr(bw->buffer.buffer, ',');
			base_64 = strstr(bw->buffer.buffer, ";base64") ? 1 : 0;
			if (sep) buffer = sep+1;
		}

		if (base_64) {
			data_size = 2 * (u32) strlen(buffer);
			data = (char*)gf_malloc(sizeof(char)*data_size);
			if (data)
				data_size = gf_base64_decode(buffer, (u32) strlen(buffer), data, data_size);
		} else {
			u32 i, c;
			char s[3];
			data_size = (u32) strlen(buffer) / 3;
			data = (char*)gf_malloc(sizeof(char) * data_size);
			if (data) {
				s[2] = 0;
				for (i=0; i<data_size; i++) {
					s[0] = buffer[3*i+1];
					s[1] = buffer[3*i+2];
					sscanf(s, "%02X", &c);
					data[i] = (unsigned char) c;
				}
			}
		}
	}
	gf_free(bw->buffer.buffer);
	bw->buffer.buffer = NULL;
	bw->buffer_len = 0;
	if (data) {
		bw->buffer.buffer = data;
		bw->buffer_len = data_size;
	}

}


void PrintRenderFrameHelper::PrintPageInternal(
    const PrintMsg_Print_Params& params,
    int page_number,
    int page_count,
    blink::WebLocalFrame* frame,
    PdfMetafileSkia* metafile,
    gfx::Size* page_size_in_dpi,
    gfx::Rect* content_area_in_dpi) {
  double css_scale_factor =
      params.scale_factor >= kEpsilon ? params.scale_factor : 1.0f;

  gfx::Size original_page_size = params.page_size;
  PageSizeMargins page_layout_in_points;
  ComputePageLayoutInPointsForCss(frame, page_number, params,
                                  ignore_css_margins_, &css_scale_factor,
                                  &page_layout_in_points);

  gfx::Size page_size;
  gfx::Rect content_area;
  GetPageSizeAndContentAreaFromPageLayout(page_layout_in_points, &page_size,
                                          &content_area);

  if (page_size_in_dpi)
    *page_size_in_dpi = original_page_size;

  if (content_area_in_dpi) {
    *content_area_in_dpi =
        gfx::Rect(0, 0, page_size_in_dpi->width(), page_size_in_dpi->height());
  }

  gfx::Rect canvas_area =
      params.display_header_footer ? gfx::Rect(page_size) : content_area;

#if defined(OS_WIN)
  float webkit_page_shrink_factor = frame->GetPrintPageShrink(page_number);
  float scale_factor = css_scale_factor * webkit_page_shrink_factor;
#else
  float scale_factor = css_scale_factor;
#endif

  cc::PaintCanvas* canvas =
      metafile->GetVectorCanvasForNewPage(page_size, canvas_area, scale_factor);
  if (!canvas)
    return;

  MetafileSkiaWrapper::SetMetafileOnCanvas(canvas, metafile);

  if (params.display_header_footer) {
#if defined(OS_WIN)
    const float fudge_factor = 1;
#else
    const float fudge_factor = kPrintingMinimumShrinkFactor;
#endif
    PrintHeaderAndFooter(canvas, page_number + 1, page_count, *frame,
                         scale_factor / fudge_factor, page_layout_in_points,
                         params);
  }

  float webkit_scale_factor = RenderPageContent(
      frame, page_number, canvas_area, content_area, scale_factor, canvas);
  DCHECK_GT(webkit_scale_factor, 0.0f);

  bool ret = metafile->FinishPage();
  DCHECK(ret);
}


void ip6_flush_pending_frames(struct sock *sk)
{
	__ip6_flush_pending_frames(sk, &sk->sk_write_queue,
				   &inet_sk(sk)->cork, &inet6_sk(sk)->cork);
}


static int present_and_same_family(const struct sadb_address *src,
				   const struct sadb_address *dst)
{
	const struct sockaddr *s_addr, *d_addr;

	if (!src || !dst)
		return 0;

	s_addr = (const struct sockaddr *)(src + 1);
	d_addr = (const struct sockaddr *)(dst + 1);
	if (s_addr->sa_family != d_addr->sa_family)
		return 0;
	if (s_addr->sa_family != AF_INET
#if IS_ENABLED(CONFIG_IPV6)
	    && s_addr->sa_family != AF_INET6
#endif
		)
		return 0;

	return 1;
}


bt_status_t btif_storage_remove_hid_info(bt_bdaddr_t *remote_bd_addr)
{
 bdstr_t bdstr;
    bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));

    btif_config_remove(bdstr, "HidAttrMask");
    btif_config_remove(bdstr, "HidSubClass");
    btif_config_remove(bdstr, "HidAppId");
    btif_config_remove(bdstr, "HidVendorId");
    btif_config_remove(bdstr, "HidProductId");
    btif_config_remove(bdstr, "HidVersion");
    btif_config_remove(bdstr, "HidCountryCode");
    btif_config_remove(bdstr, "HidSSRMaxLatency");
    btif_config_remove(bdstr, "HidSSRMinTimeout");
    btif_config_remove(bdstr, "HidDescriptor");
    btif_config_save();
 return BT_STATUS_SUCCESS;
}


static void ide_set_signature(IDEState *s)

{

    s->select &= 0xf0; /* clear head */

    /* put signature */

    s->nsector = 1;

    s->sector = 1;

    if (s->drive_kind == IDE_CD) {

        s->lcyl = 0x14;

        s->hcyl = 0xeb;

    } else if (s->bs) {

        s->lcyl = 0;

        s->hcyl = 0;

    } else {

        s->lcyl = 0xff;

        s->hcyl = 0xff;

    }

}


static void acct_clear(void)
{
    memset(&acct_info, 0, sizeof(acct_info));
}


IN_PROC_BROWSER_TEST_F ( MessageCenterNotificationsTest , QueueWhenCenterVisible ) {
 # if defined ( OS_WIN ) && defined ( USE_ASH ) if ( base : : CommandLine : : ForCurrentProcess ( ) -> HasSwitch ( switches : : kAshBrowserTests ) ) return ;
 # endif TestAddObserver observer ( message_center ( ) ) ;
 TestDelegate * delegate ;
 TestDelegate * delegate2 ;
 manager ( ) -> Add ( CreateTestNotification ( "n" , & delegate ) , profile ( ) ) ;
 const std : : string id_n = manager ( ) -> GetMessageCenterNotificationIdForTest ( "n" , profile ( ) ) ;
 message_center ( ) -> SetVisibility ( message_center : : VISIBILITY_MESSAGE_CENTER ) ;
 manager ( ) -> Add ( CreateTestNotification ( "n2" , & delegate2 ) , profile ( ) ) ;
 const std : : string id_n2 = manager ( ) -> GetMessageCenterNotificationIdForTest ( "n2" , profile ( ) ) ;
 EXPECT_EQ ( base : : StringPrintf ( "add-%s_update-%s_update-%s" , id_n . c_str ( ) , id_n . c_str ( ) , id_n . c_str ( ) ) , observer . log ( id_n ) ) ;
 message_center ( ) -> SetVisibility ( message_center : : VISIBILITY_TRANSIENT ) ;
 EXPECT_EQ ( base : : StringPrintf ( "add-%s" , id_n2 . c_str ( ) ) , observer . log ( id_n2 ) ) ;
 delegate -> Release ( ) ;
 delegate2 -> Release ( ) ;
 }


static int setseparationspace(i_ctx_t * i_ctx_p, ref *sepspace, int *stage, int *cont, int CIESubst)
{
    os_ptr op = osp;   /* required by "push" macro */
    int code = 0;
    ref sname, proc;
    ref name_none, name_all;
    separation_type sep_type;
    ref_colorspace cspace_old;
    gs_color_space *pcs;
    gs_color_space * pacs;
    gs_function_t *pfn = NULL;
    gs_client_color cc;

    if (i_ctx_p->language_level < 2)
        return_error(gs_error_undefined);

    *cont = 0;
    if ((*stage) == 0) {
        code = array_get(imemory, sepspace, 3, &proc);
        if (code < 0)
            return code;
        /* Check to see if we already have a function (eg from a PDF file) */
        pfn = ref_function(&proc);
        if (pfn == NULL) {
            /* Convert tint transform to a PostScript function */
            code = convert_transform(i_ctx_p, sepspace, &proc);
            if (code < 0)
                return code;
            if (code > 0) {
                *cont = 1;
                (*stage)++;
                return code;
            }
            /* We can only get here if the transform converted to a function
             * without requiring a continuation. Most likely this means its a
             * type 4 function. If so then it is still on the stack.
             */
            op = osp;
            pfn = ref_function(op);
            pop (1);
        }
    } else {
        /* The function is returned on the operand stack */
        op = osp;
        pfn = ref_function(op);
        pop (1);
    }

    *stage = 0;
    if ((code = name_ref(imemory, (const byte *)"All", 3, &name_all, 0)) < 0)
        return code;
    if ((code = name_ref(imemory, (const byte *)"None", 4, &name_none, 0)) < 0)
        return code;
    /* Check separation name is a string or name object */
    code = array_get(imemory, sepspace, 1, &sname);
    if (code < 0)
        return code;

    if (r_has_type(&sname, t_string)) {
        code = name_from_string(imemory, &sname, &sname);
        if (code < 0)
            return code;
    }
    sep_type = ( name_eq(&sname, &name_all) ? SEP_ALL :
                 name_eq(&sname, &name_none) ? SEP_NONE : SEP_OTHER);

    /* The alternate color space has been selected as the current color space */
    pacs = gs_currentcolorspace(igs);

    cspace_old = istate->colorspace[0];
    /* Now set the current color space as Separation */
    code = gs_cspace_new_Separation(&pcs, pacs, imemory);
    if (code < 0)
        return code;
    pcs->params.separation.sep_type = sep_type;
    pcs->params.separation.sep_name = name_index(imemory, &sname);
    pcs->params.separation.get_colorname_string = gs_get_colorname_string;
    code = array_get(imemory, sepspace, 1, &proc);
    if (code < 0)
        return code;
    istate->colorspace[0].procs.special.separation.layer_name = proc;
    code = array_get(imemory, sepspace, 3, &proc);
    if (code < 0)
        return code;
    istate->colorspace[0].procs.special.separation.tint_transform = proc;
    if (code >= 0)
        code = gs_cspace_set_sepr_function(pcs, pfn);
    if (code >= 0)
        code = gs_setcolorspace(igs, pcs);
    /* release reference from construction */
    rc_decrement_only_cs(pcs, "setseparationspace");
    if (code < 0) {
        istate->colorspace[0] = cspace_old;
        return code;
    }
    cc.pattern = 0x00;
    cc.paint.values[0] = 1.0;
    code = gs_setcolor(igs, &cc);
    return code;
}


status_t ProCamera2Client::submitRequest(camera_metadata_t* request,
 bool streaming) {
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

 Mutex::Autolock icl(mBinderSerializationLock);

 if (!mDevice.get()) return DEAD_OBJECT;

 if (!mExclusiveLock) {
 return PERMISSION_DENIED;
 }

 CameraMetadata metadata(request);

 if (!enforceRequestPermissions(metadata)) {
 return PERMISSION_DENIED;
 }

 if (streaming) {
 return mDevice->setStreamingRequest(metadata);
 } else {
 return mDevice->capture(metadata);
 }

 return OK;
}


void pdin_box_del(GF_Box *s)
{
	GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox*)s;
	if (ptr == NULL) return;
	if (ptr->rates) gf_free(ptr->rates);
	if (ptr->times) gf_free(ptr->times);
	gf_free(ptr);


TEST_F ( SSLErrorAssistantTest , DynamicInterstitialListOverridable ) {
 ASSERT_TRUE ( embedded_test_server ( ) -> Start ( ) ) ;
 EXPECT_EQ ( 1u , ssl_info ( ) . public_key_hashes . size ( ) ) ;
 auto config_proto = std : : make_unique < chrome_browser_ssl : : SSLErrorAssistantConfig > ( ) ;
 config_proto -> set_version_id ( kLargeVersionId ) ;
 chrome_browser_ssl : : DynamicInterstitial * filter = config_proto -> add_dynamic_interstitial ( ) ;
 filter -> set_interstitial_type ( chrome_browser_ssl : : DynamicInterstitial : : INTERSTITIAL_PAGE_SSL ) ;
 filter -> set_cert_error ( chrome_browser_ssl : : DynamicInterstitial : : ERR_CERT_COMMON_NAME_INVALID ) ;
 filter -> add_sha256_hash ( "sha256uthatch" ) ;
 filter -> add_sha256_hash ( ssl_info ( ) . public_key_hashes [ 0 ] . ToString ( ) ) ;
 filter -> add_sha256_hash ( "sha256/treecreeper" ) ;
 filter -> set_mitm_software_name ( "UwS" ) ;
 filter -> set_issuer_common_name_regex ( "[0-9]+.0.[0-9]+.1" ) ;
 filter -> set_issuer_organization_regex ( "T[a-z]+t CA" ) ;
 filter -> set_show_only_for_nonoverridable_errors ( true ) ;
 error_assistant ( ) -> SetErrorAssistantProto ( std : : move ( config_proto ) ) ;
 EXPECT_FALSE ( error_assistant ( ) -> MatchDynamicInterstitial ( ssl_info ( ) , true ) ) ;
 }


void BluetoothDeviceChooserController::OnStartDiscoverySessionSuccess(
    std::unique_ptr<device::BluetoothDiscoverySession> discovery_session) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DVLOG(1) << "Started discovery session.";
  if (chooser_.get()) {
    discovery_session_ = std::move(discovery_session);
    discovery_session_timer_.Reset();
  } else {
    StopDiscoverySession(std::move(discovery_session));
  }
}


WebPlugin* ChromeContentRendererClient::CreatePlugin(
      RenderView* render_view,
      WebFrame* frame,
      const WebPluginParams& original_params) {
  bool found = false;
  CommandLine* cmd = CommandLine::ForCurrentProcess();
  webkit::npapi::WebPluginInfo info;
  GURL url(original_params.url);
  std::string actual_mime_type;
  render_view->Send(new ViewHostMsg_GetPluginInfo(
      render_view->routing_id(), url, frame->top()->document().url(),
      original_params.mimeType.utf8(), &found, &info, &actual_mime_type));

  if (!found)
    return NULL;
  if (!webkit::npapi::IsPluginEnabled(info))
    return NULL;

  const webkit::npapi::PluginGroup* group =
      webkit::npapi::PluginList::Singleton()->GetPluginGroup(info);
  DCHECK(group != NULL);

  ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT;
  std::string resource;
  if (cmd->HasSwitch(switches::kEnableResourceContentSettings))
    resource = group->identifier();
  render_view->Send(new ViewHostMsg_GetPluginContentSetting(
      frame->top()->document().url(), resource, &plugin_setting));
  DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT);

  WebPluginParams params(original_params);
  for (size_t i = 0; i < info.mime_types.size(); ++i) {
    if (info.mime_types[i].mime_type == actual_mime_type) {
      AppendParams(info.mime_types[i].additional_param_names,
                   info.mime_types[i].additional_param_values,
                   &params.attributeNames,
                   &params.attributeValues);
      break;
    }
  }

  ContentSetting outdated_policy = CONTENT_SETTING_ASK;
  ContentSetting authorize_policy = CONTENT_SETTING_ASK;
  if (group->IsVulnerable() || group->RequiresAuthorization()) {
    render_view->Send(new ViewHostMsg_GetPluginPolicies(
        &outdated_policy, &authorize_policy));
  }

  if (group->IsVulnerable()) {
    if (outdated_policy == CONTENT_SETTING_ASK ||
        outdated_policy == CONTENT_SETTING_BLOCK) {
      if (outdated_policy == CONTENT_SETTING_ASK) {
        render_view->Send(new ViewHostMsg_BlockedOutdatedPlugin(
            render_view->routing_id(), group->GetGroupName(),
            GURL(group->GetUpdateURL())));
      }
      return CreatePluginPlaceholder(
          render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,
          IDS_PLUGIN_OUTDATED, false, outdated_policy == CONTENT_SETTING_ASK);
    } else {
      DCHECK(outdated_policy == CONTENT_SETTING_ALLOW);
    }
  }

  ContentSettingsObserver* observer = ContentSettingsObserver::Get(render_view);
  ContentSetting host_setting =
      observer->GetContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS);

  if (group->RequiresAuthorization() &&
      authorize_policy == CONTENT_SETTING_ASK &&
      (plugin_setting == CONTENT_SETTING_ALLOW ||
       plugin_setting == CONTENT_SETTING_ASK) &&
      host_setting == CONTENT_SETTING_DEFAULT) {
    render_view->Send(new ViewHostMsg_BlockedOutdatedPlugin(
        render_view->routing_id(), group->GetGroupName(), GURL()));
    return CreatePluginPlaceholder(
        render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,
        IDS_PLUGIN_NOT_AUTHORIZED, false, true);
  }

  if (info.path.value() == webkit::npapi::kDefaultPluginLibraryName ||
      plugin_setting == CONTENT_SETTING_ALLOW ||
      host_setting == CONTENT_SETTING_ALLOW) {
    if (prerender::PrerenderHelper::IsPrerendering(render_view)) {
      return CreatePluginPlaceholder(
          render_view, frame, params, *group, IDR_CLICK_TO_PLAY_PLUGIN_HTML,
          IDS_PLUGIN_LOAD, true, true);
    }

    bool pepper_plugin_was_registered = false;
    scoped_refptr<webkit::ppapi::PluginModule> pepper_module(
        render_view->pepper_delegate()->CreatePepperPlugin(
            info.path, &pepper_plugin_was_registered));
    if (pepper_plugin_was_registered) {
      if (pepper_module) {
        return render_view->CreatePepperPlugin(
            frame, params, info.path, pepper_module.get());
      }
      return NULL;
    }

    return render_view->CreateNPAPIPlugin(
        frame, params, info.path, actual_mime_type);
  }

  observer->DidBlockContentType(CONTENT_SETTINGS_TYPE_PLUGINS, resource);
  if (plugin_setting == CONTENT_SETTING_ASK) {
    return CreatePluginPlaceholder(
        render_view, frame, params, *group, IDR_CLICK_TO_PLAY_PLUGIN_HTML,
        IDS_PLUGIN_LOAD, false, true);
  } else {
    return CreatePluginPlaceholder(
        render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,
        IDS_PLUGIN_BLOCKED, false, true);
  }
}


static int get_max_p_order(int max_porder, int n, int order)

{

    int porder, max_parts;

    porder = max_porder;

    while(porder > 0) {

        max_parts = (1 << porder);

        if(!(n % max_parts) && (n > max_parts*order)) {

            break;

        }

        porder--;

    }

    return porder;

}


shell_initialize ()
{
  char hostname[256];
  int should_be_restricted;

  /* Line buffer output for stderr and stdout. */
  if (shell_initialized == 0)
    {
      sh_setlinebuf (stderr);
      sh_setlinebuf (stdout);
    }

  /* Sort the array of shell builtins so that the binary search in
     find_shell_builtin () works correctly. */
  initialize_shell_builtins ();

  /* Initialize the trap signal handlers before installing our own
     signal handlers.  traps.c:restore_original_signals () is responsible
     for restoring the original default signal handlers.  That function
     is called when we make a new child. */
  initialize_traps ();
  initialize_signals (0);

  /* It's highly unlikely that this will change. */
  if (current_host_name == 0)
    {
      /* Initialize current_host_name. */
      if (gethostname (hostname, 255) < 0)
	current_host_name = "??host??";
      else
	current_host_name = savestring (hostname);
    }

  /* Initialize the stuff in current_user that comes from the password
     file.  We don't need to do this right away if the shell is not
     interactive. */
  if (interactive_shell)
    get_current_user_info ();

  /* Initialize our interface to the tilde expander. */
  tilde_initialize ();

#if defined (RESTRICTED_SHELL)
  should_be_restricted = shell_is_restricted (shell_name);
#endif

  /* Initialize internal and environment variables.  Don't import shell
     functions from the environment if we are running in privileged or
     restricted mode or if the shell is running setuid. */
#if defined (RESTRICTED_SHELL)
  initialize_shell_variables (shell_environment, privileged_mode||restricted||should_be_restricted||running_setuid);
#else
  initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
#endif

  /* Initialize the data structures for storing and running jobs. */
  initialize_job_control (jobs_m_flag);

  /* Initialize input streams to null. */
  initialize_bash_input ();

  initialize_flags ();

  /* Initialize the shell options.  Don't import the shell options
     from the environment variables $SHELLOPTS or $BASHOPTS if we are
     running in privileged or restricted mode or if the shell is running
     setuid. */
#if defined (RESTRICTED_SHELL)
  initialize_shell_options (privileged_mode||restricted||should_be_restricted||running_setuid);
  initialize_bashopts (privileged_mode||restricted||should_be_restricted||running_setuid);
#else
  initialize_shell_options (privileged_mode||running_setuid);
  initialize_bashopts (privileged_mode||running_setuid);
#endif
}


void helper_lswx(CPUPPCState *env, target_ulong addr, uint32_t reg,

                 uint32_t ra, uint32_t rb)

{

    if (likely(xer_bc != 0)) {

        int num_used_regs = (xer_bc + 3) / 4;

        if (unlikely((ra != 0 && reg < ra && (reg + num_used_regs) > ra) ||

                     (reg < rb && (reg + num_used_regs) > rb))) {

            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,

                                       POWERPC_EXCP_INVAL |

                                       POWERPC_EXCP_INVAL_LSWX);

        } else {

            helper_lsw(env, addr, xer_bc, reg);

        }

    }

}


GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
	GF_HandlerBox *p = (GF_HandlerBox *)a;
	gf_isom_box_dump_start(a, "HandlerBox", trace);
	if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) {
		fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
	} else {
		fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
	}
	fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
	dump_data(trace, (char *) p->reserved2, 12);
	fprintf(trace, "\"");

	fprintf(trace, ">\n");
	gf_isom_box_dump_done("HandlerBox", a, trace);
	return GF_OK;
}


void PushMessagingServiceImpl::SetUnsubscribeCallbackForTesting(
    const base::Closure& callback) {
  unsubscribe_callback_for_testing_ = callback;
}


static void dec_pattern(DisasContext *dc)

{

    unsigned int mode;

    int l1;

    if ((dc->tb_flags & MSR_EE_FLAG)

          && !(dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)

          && !((dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR))) {

        tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

        t_gen_raise_exception(dc, EXCP_HW_EXCP);

    }

    mode = dc->opcode & 3;

    switch (mode) {

        case 0:

            /* pcmpbf.  */

            LOG_DIS("pcmpbf r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            if (dc->rd)

                gen_helper_pcmpbf(cpu_R[dc->rd], cpu_R[dc->ra], cpu_R[dc->rb]);

            break;

        case 2:

            LOG_DIS("pcmpeq r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            if (dc->rd) {

                TCGv t0 = tcg_temp_local_new();

                l1 = gen_new_label();

                tcg_gen_movi_tl(t0, 1);

                tcg_gen_brcond_tl(TCG_COND_EQ,

                                  cpu_R[dc->ra], cpu_R[dc->rb], l1);

                tcg_gen_movi_tl(t0, 0);

                gen_set_label(l1);

                tcg_gen_mov_tl(cpu_R[dc->rd], t0);

                tcg_temp_free(t0);

            }

            break;

        case 3:

            LOG_DIS("pcmpne r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            l1 = gen_new_label();

            if (dc->rd) {

                TCGv t0 = tcg_temp_local_new();

                tcg_gen_movi_tl(t0, 1);

                tcg_gen_brcond_tl(TCG_COND_NE,

                                  cpu_R[dc->ra], cpu_R[dc->rb], l1);

                tcg_gen_movi_tl(t0, 0);

                gen_set_label(l1);

                tcg_gen_mov_tl(cpu_R[dc->rd], t0);

                tcg_temp_free(t0);

            }

            break;

        default:

            cpu_abort(dc->env,

                      "unsupported pattern insn opcode=%x\n", dc->opcode);

            break;

    }

}


s32 gf_media_avc_read_pps(const char *pps_data, u32 pps_size, AVCState *avc)
{
	GF_BitStream *bs;
	char *pps_data_without_emulation_bytes = NULL;
	u32 pps_data_without_emulation_bytes_size = 0;
	s32 pps_id;
	AVC_PPS *pps;

	/*PPS still contains emulation bytes*/
	pps_data_without_emulation_bytes = gf_malloc(pps_size*sizeof(char));
	pps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(pps_data, pps_data_without_emulation_bytes, pps_size);
	bs = gf_bs_new(pps_data_without_emulation_bytes, pps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
	if (!bs) {
		pps_id = -1;
		goto exit;
	}
	/*nal hdr*/gf_bs_read_u8(bs);

	pps_id = bs_get_ue(bs);
	if (pps_id>=255) {
		pps_id = -1;
		goto exit;
	}
	pps = &avc->pps[pps_id];
	pps->id = pps_id;

	if (!pps->status) pps->status = 1;
	pps->sps_id = bs_get_ue(bs);
	if (pps->sps_id >= 32) {
		pps->sps_id = 0;
		pps_id = -1;
		goto exit;
	}
	/*sps_id may be refer to regular SPS or subseq sps, depending on the coded slice refering to the pps*/
	if (!avc->sps[pps->sps_id].state && !avc->sps[pps->sps_id + GF_SVC_SSPS_ID_SHIFT].state) {
		pps_id = -1;
		goto exit;
	}
	avc->sps_active_idx = pps->sps_id; /*set active sps*/
	pps->entropy_coding_mode_flag = gf_bs_read_int(bs, 1);
	pps->pic_order_present= gf_bs_read_int(bs, 1);
	pps->slice_group_count= bs_get_ue(bs) + 1;
	if (pps->slice_group_count > 1 ) /*pps->mb_slice_group_map_type = */bs_get_ue(bs);
	/*pps->ref_count[0]= */bs_get_ue(bs) /*+ 1*/;
	/*pps->ref_count[1]= */bs_get_ue(bs) /*+ 1*/;
	/*
	if ((pps->ref_count[0] > 32) || (pps->ref_count[1] > 32)) goto exit;
	*/

	/*pps->weighted_pred = */gf_bs_read_int(bs, 1);
	/*pps->weighted_bipred_idc = */gf_bs_read_int(bs, 2);
	/*pps->init_qp = */bs_get_se(bs) /*+ 26*/;
	/*pps->init_qs= */bs_get_se(bs) /*+ 26*/;
	/*pps->chroma_qp_index_offset = */bs_get_se(bs);
	/*pps->deblocking_filter_parameters_present = */gf_bs_read_int(bs, 1);
	/*pps->constrained_intra_pred = */gf_bs_read_int(bs, 1);
	pps->redundant_pic_cnt_present = gf_bs_read_int(bs, 1);

exit:
	gf_bs_del(bs);
	gf_free(pps_data_without_emulation_bytes);
	return pps_id;
}


UrlData::~UrlData() {
  UMA_HISTOGRAM_MEMORY_KB("Media.BytesReadFromCache",
                          BytesReadFromCache() >> 10);
  UMA_HISTOGRAM_MEMORY_KB("Media.BytesReadFromNetwork",
                          BytesReadFromNetwork() >> 10);
  DCHECK_EQ(0, playing_);
  DCHECK_EQ(0, preloading_);
}


int mgr_debug_toggle(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) {
	fm_mgr_config_errno_t	res;
	fm_msg_ret_code_t		ret_code;

	if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_DEBUG_TOGGLE, mgr, 0, NULL, &ret_code)) != FM_CONF_OK)
	{
		fprintf(stderr, "mgr_debug_toggle: Failed to retrieve data: \n"
			   "\tError:(%d) %s \n\tRet code:(%d) %s\n",
			   res, fm_mgr_get_error_str(res),ret_code,
			   fm_mgr_get_resp_error_str(ret_code));
	} else {
		printf("Successfully sent Debug output control to local Manager instance\n");
	}
	return 0;
}


poppler_page_get_property (GObject *object,
			   guint prop_id,
			   GValue *value,
			   GParamSpec *pspec)
{
  PopplerPage *page = POPPLER_PAGE (object);
  GooString label;

  switch (prop_id)
    {
    case PROP_LABEL:
      page->document->doc->getCatalog ()->indexToLabel (page->index, &label);
      g_value_take_string (value, _poppler_goo_string_to_utf8(&label));
      break;
    }
}


static void free_unused_bufs(struct virtnet_info *vi)
{
	void *buf;
	int i;

	for (i = 0; i < vi->max_queue_pairs; i++) {
		struct virtqueue *vq = vi->sq[i].vq;
		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
			dev_kfree_skb(buf);
	}

	for (i = 0; i < vi->max_queue_pairs; i++) {
		struct virtqueue *vq = vi->rq[i].vq;

		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
			if (vi->mergeable_rx_bufs) {
				unsigned long ctx = (unsigned long)buf;
				void *base = mergeable_ctx_to_buf_address(ctx);
				put_page(virt_to_head_page(base));
			} else if (vi->big_packets) {
				give_pages(&vi->rq[i], buf);
			} else {
				dev_kfree_skb(buf);
			}
		}
	}
}


static int vmci_transport_dgram_bind(struct vsock_sock *vsk,
				     struct sockaddr_vm *addr)
{
	u32 port;
	u32 flags;
	int err;

	/* VMCI will select a resource ID for us if we provide
	 * VMCI_INVALID_ID.
	 */
	port = addr->svm_port == VMADDR_PORT_ANY ?
			VMCI_INVALID_ID : addr->svm_port;

	if (port <= LAST_RESERVED_PORT && !capable(CAP_NET_BIND_SERVICE))
		return -EACCES;

	flags = addr->svm_cid == VMADDR_CID_ANY ?
				VMCI_FLAG_ANYCID_DG_HND : 0;

	err = vmci_transport_datagram_create_hnd(port, flags,
						 vmci_transport_recv_dgram_cb,
						 &vsk->sk,
						 &vmci_trans(vsk)->dg_handle);
	if (err < VMCI_SUCCESS)
		return vmci_transport_error_to_vsock_error(err);
	vsock_addr_init(&vsk->local_addr, addr->svm_cid,
			vmci_trans(vsk)->dg_handle.resource);

	return 0;
}


void GLES2Implementation::InvalidateCachedExtensions() {
  cached_extension_string_ = nullptr;
  cached_extensions_.clear();
}


static Datum ExecEvalBooleanTest ( GenericExprState * bstate , ExprContext * econtext , bool * isNull , ExprDoneCond * isDone ) {
 BooleanTest * btest = ( BooleanTest * ) bstate -> xprstate . expr ;
 Datum result ;
 result = ExecEvalExpr ( bstate -> arg , econtext , isNull , isDone ) ;
 if ( isDone && * isDone == ExprEndResult ) return result ;
 switch ( btest -> booltesttype ) {
 case IS_TRUE : if ( * isNull ) {
 * isNull = false ;
 return BoolGetDatum ( false ) ;
 }
 else if ( DatumGetBool ( result ) ) return BoolGetDatum ( true ) ;
 else return BoolGetDatum ( false ) ;
 case IS_NOT_TRUE : if ( * isNull ) {
 * isNull = false ;
 return BoolGetDatum ( true ) ;
 }
 else if ( DatumGetBool ( result ) ) return BoolGetDatum ( false ) ;
 else return BoolGetDatum ( true ) ;
 case IS_FALSE : if ( * isNull ) {
 * isNull = false ;
 return BoolGetDatum ( false ) ;
 }
 else if ( DatumGetBool ( result ) ) return BoolGetDatum ( false ) ;
 else return BoolGetDatum ( true ) ;
 case IS_NOT_FALSE : if ( * isNull ) {
 * isNull = false ;
 return BoolGetDatum ( true ) ;
 }
 else if ( DatumGetBool ( result ) ) return BoolGetDatum ( true ) ;
 else return BoolGetDatum ( false ) ;
 case IS_UNKNOWN : if ( * isNull ) {
 * isNull = false ;
 return BoolGetDatum ( true ) ;
 }
 else return BoolGetDatum ( false ) ;
 case IS_NOT_UNKNOWN : if ( * isNull ) {
 * isNull = false ;
 return BoolGetDatum ( false ) ;
 }
 else return BoolGetDatum ( true ) ;
 default : elog ( ERROR , "unrecognized booltesttype: %d" , ( int ) btest -> booltesttype ) ;
 return ( Datum ) 0 ;
 }
 }


static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
{
#define MinimumRunlength 4

  register size_t
    p,
    q;

  size_t
    runlength;

  ssize_t
    count,
    previous_count;

  unsigned char
    pixel[2];

  for (p=0; p < image->columns; )
  {
    q=p;
    runlength=0;
    previous_count=0;
    while ((runlength < MinimumRunlength) && (q < image->columns))
    {
      q+=runlength;
      previous_count=(ssize_t) runlength;
      runlength=1;
      while ((pixels[q] == pixels[q+runlength]) &&
             ((q+runlength) < image->columns) && (runlength < 127))
       runlength++;
    }
    if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
      {
        pixel[0]=(unsigned char) (128+previous_count);
        pixel[1]=pixels[p];
        if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
          break;
        p=q;
      }
    while (p < q)
    {
      count=(ssize_t) (q-p);
      if (count > 128)
        count=128;
      pixel[0]=(unsigned char) count;
      if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
        break;
      if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
        break;
      p+=count;
    }
    if (runlength >= MinimumRunlength)
      {
        pixel[0]=(unsigned char) (128+runlength);
        pixel[1]=pixels[q];
        if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
          break;
        p+=runlength;
      }
  }
  return(p);
}


static int qib_mmap_mem(struct vm_area_struct *vma, struct qib_ctxtdata *rcd,
			unsigned len, void *kvaddr, u32 write_ok, char *what)
{
	struct qib_devdata *dd = rcd->dd;
	unsigned long pfn;
	int ret;

	if ((vma->vm_end - vma->vm_start) > len) {
		qib_devinfo(dd->pcidev,
			 "FAIL on %s: len %lx > %x\n", what,
			 vma->vm_end - vma->vm_start, len);
		ret = -EFAULT;
		goto bail;
	}

	/*
	 * shared context user code requires rcvhdrq mapped r/w, others
	 * only allowed readonly mapping.
	 */
	if (!write_ok) {
		if (vma->vm_flags & VM_WRITE) {
			qib_devinfo(dd->pcidev,
				 "%s must be mapped readonly\n", what);
			ret = -EPERM;
			goto bail;
		}

		/* don't allow them to later change with mprotect */
		vma->vm_flags &= ~VM_MAYWRITE;
	}

	pfn = virt_to_phys(kvaddr) >> PAGE_SHIFT;
	ret = remap_pfn_range(vma, vma->vm_start, pfn,
			      len, vma->vm_page_prot);
	if (ret)
		qib_devinfo(dd->pcidev,
			"%s ctxt%u mmap of %lx, %x bytes failed: %d\n",
			what, rcd->ctxt, pfn, len, ret);
bail:
	return ret;
}


static int dissect_h245_IV8 ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_octet_string ( tvb , offset , actx , tree , hf_index , 8 , 8 , FALSE , NULL ) ;
 return offset ;
 }


static inline int spx_strategy(AC3DecodeContext *s, int blk)

{

    GetBitContext *bc = &s->gbc;

    int fbw_channels = s->fbw_channels;

    int dst_start_freq, dst_end_freq, src_start_freq,

        start_subband, end_subband, ch;

    /* determine which channels use spx */

    if (s->channel_mode == AC3_CHMODE_MONO) {

        s->channel_uses_spx[1] = 1;

    } else {

        for (ch = 1; ch <= fbw_channels; ch++)

            s->channel_uses_spx[ch] = get_bits1(bc);

    }

    /* get the frequency bins of the spx copy region and the spx start

       and end subbands */

    dst_start_freq = get_bits(bc, 2);

    start_subband  = get_bits(bc, 3) + 2;

    if (start_subband > 7)

        start_subband += start_subband - 7;

    end_subband    = get_bits(bc, 3) + 5;

#if USE_FIXED

    s->spx_dst_end_freq = end_freq_inv_tab[end_subband-5];

#endif

    if (end_subband   > 7)

        end_subband   += end_subband   - 7;

    dst_start_freq = dst_start_freq * 12 + 25;

    src_start_freq = start_subband  * 12 + 25;

    dst_end_freq   = end_subband    * 12 + 25;

    /* check validity of spx ranges */

    if (start_subband >= end_subband) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid spectral extension "

               "range (%d >= %d)\n", start_subband, end_subband);

        return AVERROR_INVALIDDATA;

    }

    if (dst_start_freq >= src_start_freq) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid spectral extension "

               "copy start bin (%d >= %d)\n", dst_start_freq, src_start_freq);

        return AVERROR_INVALIDDATA;

    }

    s->spx_dst_start_freq = dst_start_freq;

    s->spx_src_start_freq = src_start_freq;

    if (!USE_FIXED)

        s->spx_dst_end_freq   = dst_end_freq;

    decode_band_structure(bc, blk, s->eac3, 0,

                          start_subband, end_subband,

                          ff_eac3_default_spx_band_struct,

                          &s->num_spx_bands,

                          s->spx_band_sizes);

    return 0;

}


void
yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...)
{
  free(*param->value);
  *param->value = NULL;
  if (yylloc->first_line != -1) {
    if (*param->data_node && (*param->data_node) == (*param->actual_node)) {
      LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner));
    } else {
      LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner));
    }
  }


xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
	xmlParserCtxtPtr ctxt = NULL;
	xmlDocPtr ret;

/*
	xmlInitParser();
 */
        ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
        if (ctxt) {
               ctxt->options &= ~XML_PARSE_DTDLOAD;
                ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
                ctxt->sax->comment = soap_Comment;
                ctxt->sax->warning = NULL;
		ctxt->sax->error = NULL;
		/*ctxt->sax->fatalError = NULL;*/
#if LIBXML_VERSION >= 20703
		ctxt->options |= XML_PARSE_HUGE;
#endif
		xmlParseDocument(ctxt);
		if (ctxt->wellFormed) {
			ret = ctxt->myDoc;
			if (ret->URL == NULL && ctxt->directory != NULL) {
				ret->URL = xmlCharStrdup(ctxt->directory);
			}
		} else {
			ret = NULL;
			xmlFreeDoc(ctxt->myDoc);
			ctxt->myDoc = NULL;
		}
		xmlFreeParserCtxt(ctxt);
	} else {
		ret = NULL;
	}

/*
	xmlCleanupParser();
*/

/*
	if (ret) {
		cleanup_xml_node((xmlNodePtr)ret);
	}
*/
	return ret;
}


smp_fetch_url_param_val(struct proxy *px, struct session *l4, void *l7, unsigned int opt,
                     const struct arg *args, struct sample *smp, const char *kw)
{
	int ret = smp_fetch_url_param(px, l4, l7, opt, args, smp, kw);

	if (ret > 0) {
		smp->type = SMP_T_UINT;
		smp->data.uint = strl2ic(smp->data.str.str, smp->data.str.len);
	}

	return ret;
}


parse_DEBUG_RECIRC(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
{
    ofpact_put_DEBUG_RECIRC(ofpacts);
    return NULL;
}


int page_symlink(struct inode *inode, const char *symname, int len)
{
	return __page_symlink(inode, symname, len,
			!mapping_gfp_constraint(inode->i_mapping, __GFP_FS));
}


bool AppCacheDatabase::CreateSchema() {
  sql::Transaction transaction(db_.get());
  if (!transaction.Begin())
    return false;

  if (!meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion))
    return false;

  if (!meta_table_->SetValue(kExperimentFlagsKey,
                             GetActiveExperimentFlags())) {
    return false;
  }

  for (int i = 0; i < kTableCount; ++i) {
    if (!CreateTable(db_.get(), kTables[i]))
      return false;
  }

  for (int i = 0; i < kIndexCount; ++i) {
    if (!CreateIndex(db_.get(), kIndexes[i]))
      return false;
  }

  return transaction.Commit();
 }


static void virtio_net_rsc_purge(void *opq)
{
    VirtioNetRscSeg *seg, *rn;
    VirtioNetRscChain *chain = (VirtioNetRscChain *)opq;

    QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, rn) {
        if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
            chain->stat.purge_failed++;
            continue;
        }
    }

    chain->stat.timer++;
    if (!QTAILQ_EMPTY(&chain->buffers)) {
        timer_mod(chain->drain_timer,
              qemu_clock_get_ns(QEMU_CLOCK_HOST) + chain->n->rsc_timeout);
    }
}


bit_or(PG_FUNCTION_ARGS)
{
	VarBit	   *arg1 = PG_GETARG_VARBIT_P(0);
	VarBit	   *arg2 = PG_GETARG_VARBIT_P(1);
	VarBit	   *result;
	int			len,
				bitlen1,
				bitlen2,
				i;
	bits8	   *p1,
			   *p2,
			   *r;
	bits8		mask;

	bitlen1 = VARBITLEN(arg1);
	bitlen2 = VARBITLEN(arg2);
	if (bitlen1 != bitlen2)
		ereport(ERROR,
				(errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
				 errmsg("cannot OR bit strings of different sizes")));
	len = VARSIZE(arg1);
	result = (VarBit *) palloc(len);
	SET_VARSIZE(result, len);
	VARBITLEN(result) = bitlen1;

	p1 = VARBITS(arg1);
	p2 = VARBITS(arg2);
	r = VARBITS(result);
	for (i = 0; i < VARBITBYTES(arg1); i++)
		*r++ = *p1++ | *p2++;

	/* Pad the result */
	mask = BITMASK << VARBITPAD(result);
	if (mask)
	{
		r--;
		*r &= mask;
	}

	PG_RETURN_VARBIT_P(result);
}


static inline pte_t pte_mkspecial(pte_t pte)
{
	pte_val(pte) |= PTE_SPECIAL;
	return pte;
}


void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
                                           base::TerminationStatus status,
                                           int error_code) {
  if (rvh != GetRenderViewHost()) {
    return;
  }

  if (IsFullscreenForCurrentTab())
    ExitFullscreenMode(false);

  CancelActiveAndPendingDialogs();

  if (delegate_)
    delegate_->HideValidationMessage(this);

  audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());

  ResetLoadProgressState();
  NotifyDisconnected();
  SetIsCrashed(status, error_code);

  for (auto& observer : observers_)
    observer.RenderProcessGone(GetCrashedStatus());
}


bool ContextualSearchDelegate::CanSendPageURL(
    const GURL& current_page_url,
    Profile* profile,
    TemplateURLService* template_url_service) {
  if (field_trial_->IsSendBasePageURLDisabled())
    return false;

  TemplateURL* default_search_provider =
      template_url_service->GetDefaultSearchProvider();
  bool is_default_search_provider_google =
      default_search_provider &&
      default_search_provider->url_ref().HasGoogleBaseURLs(
          template_url_service->search_terms_data());
  if (!is_default_search_provider_google)
    return false;

  if (current_page_url.scheme() != url::kHttpScheme &&
      (current_page_url.scheme() != url::kHttpsScheme))
    return false;

  browser_sync::ProfileSyncService* service =
      ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
  sync_driver::SyncPrefs sync_prefs(profile->GetPrefs());
  if (service == NULL || !service->CanSyncStart() ||
      !sync_prefs.GetPreferredDataTypes(syncer::UserTypes())
           .Has(syncer::PROXY_TABS) ||
      !service->GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES)) {
    return false;
  }

  return true;
}


void LayerTreeHost::ApplyViewportDeltas(ScrollAndScaleSet* info) {
  gfx::Vector2dF inner_viewport_scroll_delta;
  if (info->inner_viewport_scroll.layer_id != Layer::INVALID_ID)
    inner_viewport_scroll_delta = info->inner_viewport_scroll.scroll_delta;

  if (inner_viewport_scroll_delta.IsZero() && info->page_scale_delta == 1.f &&
      info->elastic_overscroll_delta.IsZero() && !info->top_controls_delta)
    return;

  if (inner_viewport_scroll_layer_) {
    inner_viewport_scroll_layer_->SetScrollOffsetFromImplSide(
        gfx::ScrollOffsetWithDelta(
            inner_viewport_scroll_layer_->scroll_offset(),
            inner_viewport_scroll_delta));
  }

  ApplyPageScaleDeltaFromImplSide(info->page_scale_delta);
  SetElasticOverscrollFromImplSide(elastic_overscroll_ +
                                   info->elastic_overscroll_delta);
  client_->ApplyViewportDeltas(inner_viewport_scroll_delta, gfx::Vector2dF(),
                               info->elastic_overscroll_delta,
                               info->page_scale_delta,
                               info->top_controls_delta);
  SetNeedsUpdateLayers();
}


static bool reset_fw_if_needed(struct mlx5_core_dev *dev)
{
	bool supported = (ioread32be(&dev->iseg->initializing) >>
			  MLX5_FW_RESET_SUPPORTED_OFFSET) & 1;
	u32 fatal_error;

	if (!supported)
		return false;

	/* The reset only needs to be issued by one PF. The health buffer is
	 * shared between all functions, and will be cleared during a reset.
	 * Check again to avoid a redundant 2nd reset. If the fatal erros was
	 * PCI related a reset won't help.
	 */
	fatal_error = check_fatal_sensors(dev);
	if (fatal_error == MLX5_SENSOR_PCI_COMM_ERR ||
	    fatal_error == MLX5_SENSOR_NIC_DISABLED ||
	    fatal_error == MLX5_SENSOR_NIC_SW_RESET) {
		mlx5_core_warn(dev, "Not issuing FW reset. Either it's already done or won't help.");
		return false;
	}

	mlx5_core_warn(dev, "Issuing FW Reset\n");
	/* Write the NIC interface field to initiate the reset, the command
	 * interface address also resides here, don't overwrite it.
	 */
	mlx5_set_nic_state(dev, MLX5_NIC_IFC_SW_RESET);

	return true;
}


gfx::NativeViewId RenderWidgetHostViewGtk::GetNativeViewId() const {
  return GtkNativeViewManager::GetInstance()->GetIdForWidget(view_.get());
}


static ssize_t generic_perform_write_2copy(struct file *file,
				struct iov_iter *i, loff_t pos)
{
	struct address_space *mapping = file->f_mapping;
	const struct address_space_operations *a_ops = mapping->a_ops;
	struct inode *inode = mapping->host;
	long status = 0;
	ssize_t written = 0;

	do {
		struct page *src_page;
		struct page *page;
		pgoff_t index;		/* Pagecache index for current page */
		unsigned long offset;	/* Offset into pagecache page */
		unsigned long bytes;	/* Bytes to write to page */
		size_t copied;		/* Bytes copied from user */

		offset = (pos & (PAGE_CACHE_SIZE - 1));
		index = pos >> PAGE_CACHE_SHIFT;
		bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
						iov_iter_count(i));

		/*
		 * a non-NULL src_page indicates that we're doing the
		 * copy via get_user_pages and kmap.
		 */
		src_page = NULL;

		/*
		 * Bring in the user page that we will copy from _first_.
		 * Otherwise there's a nasty deadlock on copying from the
		 * same page as we're writing to, without it being marked
		 * up-to-date.
		 *
		 * Not only is this an optimisation, but it is also required
		 * to check that the address is actually valid, when atomic
		 * usercopies are used, below.
		 */
		if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
			status = -EFAULT;
			break;
		}

		page = __grab_cache_page(mapping, index);
		if (!page) {
			status = -ENOMEM;
			break;
		}

		/*
		 * non-uptodate pages cannot cope with short copies, and we
		 * cannot take a pagefault with the destination page locked.
		 * So pin the source page to copy it.
		 */
		if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) {
			unlock_page(page);

			src_page = alloc_page(GFP_KERNEL);
			if (!src_page) {
				page_cache_release(page);
				status = -ENOMEM;
				break;
			}

			/*
			 * Cannot get_user_pages with a page locked for the
			 * same reason as we can't take a page fault with a
			 * page locked (as explained below).
			 */
			copied = iov_iter_copy_from_user(src_page, i,
								offset, bytes);
			if (unlikely(copied == 0)) {
				status = -EFAULT;
				page_cache_release(page);
				page_cache_release(src_page);
				break;
			}
			bytes = copied;

			lock_page(page);
			/*
			 * Can't handle the page going uptodate here, because
			 * that means we would use non-atomic usercopies, which
			 * zero out the tail of the page, which can cause
			 * zeroes to become transiently visible. We could just
			 * use a non-zeroing copy, but the APIs aren't too
			 * consistent.
			 */
			if (unlikely(!page->mapping || PageUptodate(page))) {
				unlock_page(page);
				page_cache_release(page);
				page_cache_release(src_page);
				continue;
			}
		}

		status = a_ops->prepare_write(file, page, offset, offset+bytes);
		if (unlikely(status))
			goto fs_write_aop_error;

		if (!src_page) {
			/*
			 * Must not enter the pagefault handler here, because
			 * we hold the page lock, so we might recursively
			 * deadlock on the same lock, or get an ABBA deadlock
			 * against a different lock, or against the mmap_sem
			 * (which nests outside the page lock).  So increment
			 * preempt count, and use _atomic usercopies.
			 *
			 * The page is uptodate so we are OK to encounter a
			 * short copy: if unmodified parts of the page are
			 * marked dirty and written out to disk, it doesn't
			 * really matter.
			 */
			pagefault_disable();
			copied = iov_iter_copy_from_user_atomic(page, i,
								offset, bytes);
			pagefault_enable();
		} else {
			void *src, *dst;
			src = kmap_atomic(src_page, KM_USER0);
			dst = kmap_atomic(page, KM_USER1);
			memcpy(dst + offset, src + offset, bytes);
			kunmap_atomic(dst, KM_USER1);
			kunmap_atomic(src, KM_USER0);
			copied = bytes;
		}
		flush_dcache_page(page);

		status = a_ops->commit_write(file, page, offset, offset+bytes);
		if (unlikely(status < 0))
			goto fs_write_aop_error;
		if (unlikely(status > 0)) /* filesystem did partial write */
			copied = min_t(size_t, copied, status);

		unlock_page(page);
		mark_page_accessed(page);
		page_cache_release(page);
		if (src_page)
			page_cache_release(src_page);

		iov_iter_advance(i, copied);
		pos += copied;
		written += copied;

		balance_dirty_pages_ratelimited(mapping);
		cond_resched();
		continue;

fs_write_aop_error:
		unlock_page(page);
		page_cache_release(page);
		if (src_page)
			page_cache_release(src_page);

		/*
		 * prepare_write() may have instantiated a few blocks
		 * outside i_size.  Trim these off again. Don't need
		 * i_size_read because we hold i_mutex.
		 */
		if (pos + bytes > inode->i_size)
			vmtruncate(inode, inode->i_size);
		break;
	} while (iov_iter_count(i));

	return written ? written : status;
}


static int sqlite_callback(void *data, int argc,
			   char **argv, char **azColName) {
  struct ntopng_sqlite_state *s = (struct ntopng_sqlite_state*)data;

  lua_newtable(s->vm);

  for(int i=0; i<argc; i++)
    lua_push_str_table_entry(s->vm, (const char*)azColName[i],
			     (char*)(argv[i] ? argv[i] : "NULL"));

  lua_pushinteger(s->vm, ++s->num_rows);
  lua_insert(s->vm, -2);
  lua_settable(s->vm, -3);

  return(0);
}


static void write_delta_q ( struct vp9_write_bit_buffer * wb , int delta_q ) {
 if ( delta_q != 0 ) {
 vp9_wb_write_bit ( wb , 1 ) ;
 vp9_wb_write_literal ( wb , abs ( delta_q ) , 4 ) ;
 vp9_wb_write_bit ( wb , delta_q < 0 ) ;
 }
 else {
 vp9_wb_write_bit ( wb , 0 ) ;
 }
 }


bool WebGLRenderingContextBase::ValidateTexFuncData(
    const char* function_name,
    TexImageDimension tex_dimension,
    GLint level,
    GLsizei width,
    GLsizei height,
    GLsizei depth,
    GLenum format,
    GLenum type,
    DOMArrayBufferView* pixels,
    NullDisposition disposition,
    GLuint src_offset) {
  if (!pixels) {
    DCHECK_NE(disposition, kNullNotReachable);
    if (disposition == kNullAllowed)
      return true;
    SynthesizeGLError(GL_INVALID_VALUE, function_name, "no pixels");
    return false;
  }

  if (!ValidateSettableTexFormat(function_name, format))
    return false;

  switch (type) {
    case GL_BYTE:
      if (pixels->GetType() != DOMArrayBufferView::kTypeInt8) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "type BYTE but ArrayBufferView not Int8Array");
        return false;
      }
      break;
    case GL_UNSIGNED_BYTE:
      if (pixels->GetType() != DOMArrayBufferView::kTypeUint8) {
        SynthesizeGLError(
            GL_INVALID_OPERATION, function_name,
            "type UNSIGNED_BYTE but ArrayBufferView not Uint8Array");
        return false;
      }
      break;
    case GL_SHORT:
      if (pixels->GetType() != DOMArrayBufferView::kTypeInt16) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "type SHORT but ArrayBufferView not Int16Array");
        return false;
      }
      break;
    case GL_UNSIGNED_SHORT:
    case GL_UNSIGNED_SHORT_5_6_5:
    case GL_UNSIGNED_SHORT_4_4_4_4:
    case GL_UNSIGNED_SHORT_5_5_5_1:
      if (pixels->GetType() != DOMArrayBufferView::kTypeUint16) {
        SynthesizeGLError(
            GL_INVALID_OPERATION, function_name,
            "type UNSIGNED_SHORT but ArrayBufferView not Uint16Array");
        return false;
      }
      break;
    case GL_INT:
      if (pixels->GetType() != DOMArrayBufferView::kTypeInt32) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "type INT but ArrayBufferView not Int32Array");
        return false;
      }
      break;
    case GL_UNSIGNED_INT:
    case GL_UNSIGNED_INT_2_10_10_10_REV:
    case GL_UNSIGNED_INT_10F_11F_11F_REV:
    case GL_UNSIGNED_INT_5_9_9_9_REV:
    case GL_UNSIGNED_INT_24_8:
      if (pixels->GetType() != DOMArrayBufferView::kTypeUint32) {
        SynthesizeGLError(
            GL_INVALID_OPERATION, function_name,
            "type UNSIGNED_INT but ArrayBufferView not Uint32Array");
        return false;
      }
      break;
    case GL_FLOAT:  // OES_texture_float
      if (pixels->GetType() != DOMArrayBufferView::kTypeFloat32) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "type FLOAT but ArrayBufferView not Float32Array");
        return false;
      }
      break;
    case GL_HALF_FLOAT:
    case GL_HALF_FLOAT_OES:  // OES_texture_half_float
      if (pixels->GetType() != DOMArrayBufferView::kTypeUint16) {
        SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                          "type HALF_FLOAT_OES but ArrayBufferView is not NULL "
                          "and not Uint16Array");
        return false;
      }
      break;
    case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
      SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                        "type FLOAT_32_UNSIGNED_INT_24_8_REV but "
                        "ArrayBufferView is not NULL");
      return false;
    default:
      NOTREACHED();
  }

  unsigned total_bytes_required, skip_bytes;
  GLenum error = WebGLImageConversion::ComputeImageSizeInBytes(
      format, type, width, height, depth,
      GetUnpackPixelStoreParams(tex_dimension), &total_bytes_required, nullptr,
      &skip_bytes);
  if (error != GL_NO_ERROR) {
    SynthesizeGLError(error, function_name, "invalid texture dimensions");
    return false;
  }
  base::CheckedNumeric<uint32_t> total = src_offset;
  total *= pixels->TypeSize();
  total += total_bytes_required;
  total += skip_bytes;
  if (!total.IsValid() || pixels->byteLength() < total.ValueOrDie()) {
    SynthesizeGLError(GL_INVALID_OPERATION, function_name,
                      "ArrayBufferView not big enough for request");
    return false;
  }
  return true;
}


static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
{
	const struct usb_gadget_strings	*s;
	__le16				language;
	__le16				*tmp;

	while (*sp) {
		s = *sp;
		language = cpu_to_le16(s->language);
		for (tmp = buf; *tmp && tmp < &buf[USB_MAX_STRING_LEN]; tmp++) {
			if (*tmp == language)
				goto repeat;
		}
		*tmp++ = language;
repeat:
		sp++;
	}
}


ModuleExport void UnregisterMIFFImage(void)
{
  (void) UnregisterMagickInfo("MIFF");
}


bool RenderFrameHostImpl::UpdatePendingWebUI(const GURL& dest_url,
                                             int entry_bindings) {
  WebUI::TypeID new_web_ui_type =
      WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
          GetSiteInstance()->GetBrowserContext(), dest_url);

  if (new_web_ui_type == pending_web_ui_type_ ||
      (should_reuse_web_ui_ && new_web_ui_type == web_ui_type_)) {
    return false;
  }

  ClearPendingWebUI();

  if (GetSiteInstance()->GetSiteURL() == GURL(kUnreachableWebDataURL))
    return true;

  if (new_web_ui_type != WebUI::kNoWebUI) {
    if (new_web_ui_type == web_ui_type_) {
      DCHECK(web_ui_);
      should_reuse_web_ui_ = true;
    } else {
      pending_web_ui_ = delegate_->CreateWebUIForRenderFrameHost(dest_url);
      DCHECK(pending_web_ui_);
      pending_web_ui_type_ = new_web_ui_type;

      if (entry_bindings != NavigationEntryImpl::kInvalidBindings &&
          pending_web_ui_->GetBindings() != entry_bindings) {
        RecordAction(
            base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
        ClearPendingWebUI();
      }
    }
  }
  DCHECK_EQ(!pending_web_ui_, pending_web_ui_type_ == WebUI::kNoWebUI);

  if (pending_web_ui_ && !render_view_host_->GetProcess()->IsForGuestsOnly()) {
    int new_bindings = pending_web_ui_->GetBindings();
    if ((GetEnabledBindings() & new_bindings) != new_bindings) {
      AllowBindings(new_bindings);
    }
  } else if (render_view_host_->is_active()) {
    bool url_acceptable_for_webui =
        WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
            GetSiteInstance()->GetBrowserContext(), dest_url);
    if (!url_acceptable_for_webui) {
      CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
          GetProcess()->GetID()));
    }
  }
  return true;
}


static inline void bsg_set_block(struct bsg_device *bd, struct file *file)
{
	if (file->f_flags & O_NONBLOCK)
		clear_bit(BSG_F_BLOCK, &bd->flags);
	else
		set_bit(BSG_F_BLOCK, &bd->flags);
}


static void dca_exss_parse_header ( DCAContext * s ) {
 int ss_index ;
 int blownup ;
 int num_audiop = 1 ;
 int num_assets = 1 ;
 int active_ss_mask [ 8 ] ;
 int i , j ;
 if ( get_bits_left ( & s -> gb ) < 52 ) return ;
 skip_bits ( & s -> gb , 8 ) ;
 ss_index = get_bits ( & s -> gb , 2 ) ;
 blownup = get_bits1 ( & s -> gb ) ;
 skip_bits ( & s -> gb , 8 + 4 * blownup ) ;
 skip_bits ( & s -> gb , 16 + 4 * blownup ) ;
 s -> static_fields = get_bits1 ( & s -> gb ) ;
 if ( s -> static_fields ) {
 skip_bits ( & s -> gb , 2 ) ;
 skip_bits ( & s -> gb , 3 ) ;
 if ( get_bits1 ( & s -> gb ) ) skip_bits_long ( & s -> gb , 36 ) ;
 num_audiop = get_bits ( & s -> gb , 3 ) + 1 ;
 if ( num_audiop > 1 ) {
 av_log_ask_for_sample ( s -> avctx , "Multiple DTS-HD audio presentations." ) ;
 return ;
 }
 num_assets = get_bits ( & s -> gb , 3 ) + 1 ;
 if ( num_assets > 1 ) {
 av_log_ask_for_sample ( s -> avctx , "Multiple DTS-HD audio assets." ) ;
 return ;
 }
 for ( i = 0 ;
 i < num_audiop ;
 i ++ ) active_ss_mask [ i ] = get_bits ( & s -> gb , ss_index + 1 ) ;
 for ( i = 0 ;
 i < num_audiop ;
 i ++ ) for ( j = 0 ;
 j <= ss_index ;
 j ++ ) if ( active_ss_mask [ i ] & ( 1 << j ) ) skip_bits ( & s -> gb , 8 ) ;
 s -> mix_metadata = get_bits1 ( & s -> gb ) ;
 if ( s -> mix_metadata ) {
 int mix_out_mask_size ;
 skip_bits ( & s -> gb , 2 ) ;
 mix_out_mask_size = ( get_bits ( & s -> gb , 2 ) + 1 ) << 2 ;
 s -> num_mix_configs = get_bits ( & s -> gb , 2 ) + 1 ;
 for ( i = 0 ;
 i < s -> num_mix_configs ;
 i ++ ) {
 int mix_out_mask = get_bits ( & s -> gb , mix_out_mask_size ) ;
 s -> mix_config_num_ch [ i ] = dca_exss_mask2count ( mix_out_mask ) ;
 }
 }
 }
 for ( i = 0 ;
 i < num_assets ;
 i ++ ) skip_bits_long ( & s -> gb , 16 + 4 * blownup ) ;
 for ( i = 0 ;
 i < num_assets ;
 i ++ ) {
 if ( dca_exss_parse_asset_header ( s ) ) return ;
 }
 }


error::Error GLES2DecoderImpl::HandleWaitSync(
    uint32_t immediate_data_size, const void* cmd_data) {
  if (!unsafe_es3_apis_enabled())
    return error::kUnknownCommand;
  const gles2::cmds::WaitSync& c =
      *static_cast<const gles2::cmds::WaitSync*>(cmd_data);
  GLuint sync = static_cast<GLuint>(c.sync);
  GLbitfield flags = static_cast<GLbitfield>(c.flags);
  GLuint64 timeout = GLES2Util::MapTwoUint32ToUint64(c.timeout_0, c.timeout_1);
  GLsync service_sync = 0;
  if (!group_->GetSyncServiceId(sync, &service_sync)) {
    LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "WaitSync", "invalid sync");
    return error::kNoError;
  }
  glWaitSync(service_sync, flags, timeout);
  return error::kNoError;
}


bool Document::dispatchBeforeUnloadEvent(ChromeClient& chromeClient, bool isReload, bool& didAllowNavigation)
{
    if (!m_domWindow)
        return true;

    if (!body())
        return true;

    if (processingBeforeUnload())
        return false;

    BeforeUnloadEvent* beforeUnloadEvent = BeforeUnloadEvent::create();
    m_loadEventProgress = BeforeUnloadEventInProgress;
    m_domWindow->dispatchEvent(beforeUnloadEvent, this);
    m_loadEventProgress = BeforeUnloadEventCompleted;
    if (!beforeUnloadEvent->defaultPrevented())
        defaultEventHandler(beforeUnloadEvent);
    if (!frame() || beforeUnloadEvent->returnValue().isNull())
        return true;

    if (didAllowNavigation) {
        addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation."));
        return true;
    }

    String text = beforeUnloadEvent->returnValue();
    if (chromeClient.openBeforeUnloadConfirmPanel(text, m_frame, isReload)) {
        didAllowNavigation = true;
        return true;
    }
    return false;
}


  InspectorFileReaderLoaderClient(
      RefPtr<BlobDataHandle> blob,
      const String& mime_type,
      const String& text_encoding_name,
      std::unique_ptr<GetResponseBodyCallback> callback)
      : blob_(std::move(blob)),
        mime_type_(mime_type),
        text_encoding_name_(text_encoding_name),
        callback_(std::move(callback)) {
    loader_ = FileReaderLoader::Create(FileReaderLoader::kReadByClient, this);
  }