code,target " void UpdateNetworkManagerStatus() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &NetworkLibraryImpl::UpdateNetworkManagerStatus)); return; } SystemInfo* system = GetSystemInfo(); if (!system) return; std::string prev_cellular_service_path = cellular_ ? cellular_->service_path() : std::string(); ClearNetworks(); ParseSystem(system, ðernet_, &wifi_networks_, &cellular_networks_, &remembered_wifi_networks_); wifi_ = NULL; for (size_t i = 0; i < wifi_networks_.size(); i++) { if (wifi_networks_[i]->connecting_or_connected()) { wifi_ = wifi_networks_[i]; break; // There is only one connected or connecting wifi network. } } cellular_ = NULL; for (size_t i = 0; i < cellular_networks_.size(); i++) { if (cellular_networks_[i]->connecting_or_connected()) { cellular_ = cellular_networks_[i]; if (cellular_networks_[i]->service_path() != prev_cellular_service_path) { CellularDataPlanList* list = RetrieveCellularDataPlans( cellular_->service_path().c_str()); UpdateCellularDataPlan(list); FreeCellularDataPlanList(list); } break; // There is only one connected or connecting cellular network. } } available_devices_ = system->available_technologies; enabled_devices_ = system->enabled_technologies; connected_devices_ = system->connected_technologies; offline_mode_ = system->offline_mode; NotifyNetworkManagerChanged(); FreeSystemInfo(system); } ",1 "int64 ClientUsageTracker::GetCachedHostUsage(const std::string& host) { HostUsageMap::const_iterator found = cached_usage_.find(host); if (found == cached_usage_.end()) return 0; int64 usage = 0; const UsageMap& map = found->second; for (UsageMap::const_iterator iter = map.begin(); iter != map.end(); ++iter) { usage += iter->second; } return usage; } ",1 "void AddInstallerCopyTasks(const InstallerState& installer_state, const FilePath& setup_path, const FilePath& archive_path, const FilePath& temp_path, const Version& new_version, WorkItemList* install_list) { DCHECK(install_list); FilePath installer_dir(installer_state.GetInstallerDirectory(new_version)); install_list->AddCreateDirWorkItem(installer_dir); FilePath exe_dst(installer_dir.Append(setup_path.BaseName())); FilePath archive_dst(installer_dir.Append(archive_path.BaseName())); install_list->AddMoveTreeWorkItem(setup_path.value(), exe_dst.value(), temp_path.value(), WorkItem::ALWAYS_MOVE); install_list->AddMoveTreeWorkItem(archive_path.value(), archive_dst.value(), temp_path.value(), WorkItem::ALWAYS_MOVE); } ",1 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { RetainPtr baseURL; bool hasBaseURL; if (!decoder->decodeBool(hasBaseURL)) return false; if (hasBaseURL) { if (!decode(decoder, baseURL)) return false; } RetainPtr string; if (!decode(decoder, string)) return false; CFURLRef url = CFURLCreateWithString(0, string.get(), baseURL.get()); if (!url) return false; result.adoptCF(url); return true; } ",1 "void WebProcessProxy::addExistingWebPage(WebPageProxy* webPage, uint64_t pageID) { m_pageMap.set(pageID, webPage); globalPageMap().set(pageID, webPage); #if PLATFORM(MAC) if (pageIsProcessSuppressible(webPage)); m_processSuppressiblePages.add(pageID); updateProcessSuppressionState(); #endif } ",1 "v8::Handle V8ThrowException::createDOMException(v8::Isolate* isolate, int ec, const String& sanitizedMessage, const String& unsanitizedMessage, const v8::Handle& creationContext) { if (ec <= 0 || v8::V8::IsExecutionTerminating()) return v8Undefined(); ASSERT(ec == SecurityError || unsanitizedMessage.isEmpty()); if (ec == V8GeneralError) return V8ThrowException::createGeneralError(isolate, sanitizedMessage); if (ec == V8TypeError) return V8ThrowException::createTypeError(isolate, sanitizedMessage); if (ec == V8RangeError) return V8ThrowException::createRangeError(isolate, sanitizedMessage); if (ec == V8SyntaxError) return V8ThrowException::createSyntaxError(isolate, sanitizedMessage); if (ec == V8ReferenceError) return V8ThrowException::createReferenceError(isolate, sanitizedMessage); RefPtrWillBeRawPtr domException = DOMException::create(ec, sanitizedMessage, unsanitizedMessage); v8::Handle exception = toV8(domException.get(), creationContext, isolate); if (exception.IsEmpty()) return v8Undefined(); v8::Handle error = v8::Exception::Error(v8String(isolate, domException->message())); ASSERT(!error.IsEmpty()); ASSERT(exception->IsObject()); exception->ToObject(isolate)->SetAccessor(v8AtomicString(isolate, ""stack""), domExceptionStackGetter, domExceptionStackSetter, error); V8HiddenValue::setHiddenValue(isolate, exception->ToObject(isolate), V8HiddenValue::error(isolate), error); return exception; } ",1 "void OverlayWindowViews::OnGestureEvent(ui::GestureEvent* event) { if (event->type() != ui::ET_GESTURE_TAP) return; hide_controls_timer_.Reset(); if (!GetControlsScrimLayer()->visible()) { UpdateControlsVisibility(true); return; } if (GetCloseControlsBounds().Contains(event->location())) { controller_->Close(true /* should_pause_video */, true /* should_reset_pip_player */); event->SetHandled(); } else if (GetPlayPauseControlsBounds().Contains(event->location())) { TogglePlayPause(); event->SetHandled(); } views::Widget::OnGestureEvent(event); } ",1 "std::string CellularNetwork::ActivationStateToString( ActivationState activation_state) { switch (activation_state) { case ACTIVATION_STATE_ACTIVATED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED); break; case ACTIVATION_STATE_ACTIVATING: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING); break; case ACTIVATION_STATE_NOT_ACTIVATED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED); break; case ACTIVATION_STATE_PARTIALLY_ACTIVATED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED); break; default: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_UNKNOWN); break; } } ",0 " virtual void AddCellularDataPlanObserver(CellularDataPlanObserver* observer) { if (!data_plan_observers_.HasObserver(observer)) data_plan_observers_.AddObserver(observer); } ",0 " virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) { if (!network_manager_observers_.HasObserver(observer)) network_manager_observers_.AddObserver(observer); } ",0 " virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {} ",0 " virtual void AddNetworkObserver(const std::string& service_path, NetworkObserver* observer) { DCHECK(observer); if (!EnsureCrosLoaded()) return; NetworkObserverMap::iterator iter = network_observers_.find(service_path); NetworkObserverList* oblist; if (iter != network_observers_.end()) { oblist = iter->second; } else { std::pair inserted = network_observers_.insert( std::make_pair( service_path, new NetworkObserverList(this, service_path))); oblist = inserted.first->second; } if (!oblist->HasObserver(observer)) oblist->AddObserver(observer); } ",0 " virtual void AddNetworkObserver(const std::string& service_path, NetworkObserver* observer) {} ",0 "CellularNetwork::CellularNetwork() : WirelessNetwork(), activation_state_(ACTIVATION_STATE_UNKNOWN), network_technology_(NETWORK_TECHNOLOGY_UNKNOWN), roaming_state_(ROAMING_STATE_UNKNOWN), restricted_pool_(false), prl_version_(0) { type_ = TYPE_CELLULAR; } ",0 "CellularNetwork::CellularNetwork(const CellularNetwork& network) : WirelessNetwork(network) { activation_state_ = network.activation_state(); network_technology_ = network.network_technology(); roaming_state_ = network.roaming_state(); restricted_pool_ = network.restricted_pool(); service_name_ = network.service_name(); operator_name_ = network.operator_name(); operator_code_ = network.operator_code(); payment_url_ = network.payment_url(); meid_ = network.meid(); imei_ = network.imei(); imsi_ = network.imsi(); esn_ = network.esn(); mdn_ = network.mdn(); min_ = network.min(); model_id_ = network.model_id(); manufacturer_ = network.manufacturer(); firmware_revision_ = network.firmware_revision(); hardware_revision_ = network.hardware_revision(); last_update_ = network.last_update(); prl_version_ = network.prl_version(); type_ = TYPE_CELLULAR; } ",0 "CellularNetwork::CellularNetwork(const ServiceInfo* service) : WirelessNetwork(service) { service_name_ = SafeString(service->name); activation_state_ = service->activation_state; network_technology_ = service->network_technology; roaming_state_ = service->roaming_state; restricted_pool_ = service->restricted_pool; if (service->carrier_info) { operator_name_ = SafeString(service->carrier_info->operator_name); operator_code_ = SafeString(service->carrier_info->operator_code); payment_url_ = SafeString(service->carrier_info->payment_url); } if (service->device_info) { meid_ = SafeString(service->device_info->MEID); imei_ = SafeString(service->device_info->IMEI); imsi_ = SafeString(service->device_info->IMSI); esn_ = SafeString(service->device_info->ESN); mdn_ = SafeString(service->device_info->MDN); min_ = SafeString(service->device_info->MIN); model_id_ = SafeString(service->device_info->model_id); manufacturer_ = SafeString(service->device_info->manufacturer); firmware_revision_ = SafeString(service->device_info->firmware_revision); hardware_revision_ = SafeString(service->device_info->hardware_revision); last_update_ = SafeString(service->device_info->last_update); prl_version_ = service->device_info->PRL_version; } type_ = TYPE_CELLULAR; } ",0 "void Network::Clear() { state_ = STATE_UNKNOWN; error_ = ERROR_UNKNOWN; service_path_.clear(); device_path_.clear(); ip_address_.clear(); is_active_ = false; } ",0 "void WirelessNetwork::Clear() { Network::Clear(); name_.clear(); strength_ = 0; auto_connect_ = false; favorite_ = false; } ",0 "void CellularNetwork::Clear() { WirelessNetwork::Clear(); activation_state_ = ACTIVATION_STATE_UNKNOWN; roaming_state_ = ROAMING_STATE_UNKNOWN; network_technology_ = NETWORK_TECHNOLOGY_UNKNOWN; restricted_pool_ = false; service_name_.clear(); operator_name_.clear(); operator_code_.clear(); payment_url_.clear(); meid_.clear(); imei_.clear(); imsi_.clear(); esn_.clear(); mdn_.clear(); min_.clear(); model_id_.clear(); manufacturer_.clear(); firmware_revision_.clear(); hardware_revision_.clear(); last_update_.clear(); prl_version_ = 0; } ",0 "void WifiNetwork::Clear() { WirelessNetwork::Clear(); encryption_ = SECURITY_NONE; passphrase_.clear(); identity_.clear(); cert_path_.clear(); } ",0 " void ClearNetworks() { if (ethernet_) delete ethernet_; ethernet_ = NULL; wifi_ = NULL; cellular_ = NULL; STLDeleteElements(&wifi_networks_); wifi_networks_.clear(); STLDeleteElements(&cellular_networks_); cellular_networks_.clear(); STLDeleteElements(&remembered_wifi_networks_); remembered_wifi_networks_.clear(); } ",0 " virtual void ConnectToWifiNetwork(const WifiNetwork* network, const std::string& password, const std::string& identity, const std::string& certpath) { DCHECK(network); if (!EnsureCrosLoaded()) return; if (ConnectToNetworkWithCertInfo(network->service_path().c_str(), password.empty() ? NULL : password.c_str(), identity.empty() ? NULL : identity.c_str(), certpath.empty() ? NULL : certpath.c_str())) { WifiNetwork* wifi = GetWirelessNetworkByPath( wifi_networks_, network->service_path()); if (wifi) { wifi->set_passphrase(password); wifi->set_identity(identity); wifi->set_cert_path(certpath); wifi->set_connecting(true); wifi_ = wifi; } NotifyNetworkManagerChanged(); } } ",0 " virtual void ConnectToWifiNetwork(ConnectionSecurity security, const std::string& ssid, const std::string& password, const std::string& identity, const std::string& certpath, bool auto_connect) { if (!EnsureCrosLoaded()) return; ServiceInfo* service = GetWifiService(ssid.c_str(), security); if (service) { SetAutoConnect(service->service_path, auto_connect); ConnectToNetworkWithCertInfo(service->service_path, password.empty() ? NULL : password.c_str(), identity.empty() ? NULL : identity.c_str(), certpath.empty() ? NULL : certpath.c_str()); FreeServiceInfo(service); } else { LOG(WARNING) << ""Cannot find hidden network: "" << ssid; } } ",0 " virtual void ConnectToWifiNetwork(const WifiNetwork* network, const std::string& password, const std::string& identity, const std::string& certpath) {} ",0 " virtual void ConnectToWifiNetwork(ConnectionSecurity security, const std::string& ssid, const std::string& password, const std::string& identity, const std::string& certpath, bool auto_connect) {} ",0 " bool Connected() const { return ethernet_connected() || wifi_connected() || cellular_connected(); } ",0 " bool Connected() const { return true; } ",0 " bool Connecting() const { return ethernet_connecting() || wifi_connecting() || cellular_connecting(); } ",0 " bool Connecting() const { return false; } ",0 " virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) { DCHECK(network); if (!EnsureCrosLoaded() || !network) return; if (DisconnectFromNetwork(network->service_path().c_str())) { if (network->type() == TYPE_WIFI) { WifiNetwork* wifi = GetWirelessNetworkByPath( wifi_networks_, network->service_path()); if (wifi) { wifi->set_connected(false); wifi_ = NULL; } } else if (network->type() == TYPE_CELLULAR) { CellularNetwork* cellular = GetWirelessNetworkByPath( cellular_networks_, network->service_path()); if (cellular) { cellular->set_connected(false); cellular_ = NULL; } } NotifyNetworkManagerChanged(); } } ",0 " virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {} ",0 " virtual void EnableCellularNetworkDevice(bool enable) { EnableNetworkDeviceType(TYPE_CELLULAR, enable); } ",0 " virtual void EnableEthernetNetworkDevice(bool enable) { EnableNetworkDeviceType(TYPE_ETHERNET, enable); } ",0 " virtual void EnableEthernetNetworkDevice(bool enable) {} ",0 " void EnableNetworkDeviceType(ConnectionType device, bool enable) { if (!EnsureCrosLoaded()) return; if (enable && (enabled_devices_ & (1 << device))) { LOG(WARNING) << ""Trying to enable a device that's already enabled: "" << device; return; } if (!enable && !(enabled_devices_ & (1 << device))) { LOG(WARNING) << ""Trying to disable a device that's already disabled: "" << device; return; } EnableNetworkDevice(device, enable); } ",0 " virtual void EnableOfflineMode(bool enable) { if (!EnsureCrosLoaded()) return; if (enable && offline_mode_) { VLOG(1) << ""Trying to enable offline mode when it's already enabled.""; return; } if (!enable && !offline_mode_) { VLOG(1) << ""Trying to disable offline mode when it's already disabled.""; return; } if (SetOfflineMode(enable)) { offline_mode_ = enable; } } ",0 " virtual void EnableOfflineMode(bool enable) {} ",0 " virtual void EnableWifiNetworkDevice(bool enable) { EnableNetworkDeviceType(TYPE_WIFI, enable); } ",0 " virtual CellularNetwork* FindCellularNetworkByPath( const std::string& path) { return NULL; } ",0 " virtual WifiNetwork* FindWifiNetworkByPath( const std::string& path) { return GetWirelessNetworkByPath(wifi_networks_, path); } ",0 " virtual WifiNetwork* FindWifiNetworkByPath( const std::string& path) { return NULL; } ",0 " virtual void ForgetWifiNetwork(const std::string& service_path) { if (!EnsureCrosLoaded()) return; if (DeleteRememberedService(service_path.c_str())) { for (WifiNetworkVector::iterator iter = remembered_wifi_networks_.begin(); iter != remembered_wifi_networks_.end(); ++iter) { if ((*iter)->service_path() == service_path) { delete (*iter); remembered_wifi_networks_.erase(iter); break; } } NotifyNetworkManagerChanged(); } } ",0 "std::string CellularNetwork::GetActivationStateString() const { return ActivationStateToString(this->activation_state_); } ",0 "std::string WifiNetwork::GetEncryptionString() { switch (encryption_) { case SECURITY_UNKNOWN: break; case SECURITY_NONE: return """"; case SECURITY_WEP: return ""WEP""; case SECURITY_WPA: return ""WPA""; case SECURITY_RSN: return ""RSN""; case SECURITY_8021X: return ""8021X""; } return ""Unknown""; } ",0 "std::string Network::GetErrorString() const { switch (error_) { case ERROR_UNKNOWN: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN); case ERROR_OUT_OF_RANGE: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OUT_OF_RANGE); case ERROR_PIN_MISSING: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_PIN_MISSING); case ERROR_DHCP_FAILED: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_DHCP_FAILED); case ERROR_CONNECT_FAILED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ERROR_CONNECT_FAILED); case ERROR_BAD_PASSPHRASE: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ERROR_BAD_PASSPHRASE); case ERROR_BAD_WEPKEY: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_BAD_WEPKEY); case ERROR_ACTIVATION_FAILED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ERROR_ACTIVATION_FAILED); case ERROR_NEED_EVDO: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_NEED_EVDO); case ERROR_NEED_HOME_NETWORK: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ERROR_NEED_HOME_NETWORK); case ERROR_OTASP_FAILED: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OTASP_FAILED); case ERROR_AAA_FAILED: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_AAA_FAILED); default: break; } return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED); } ",0 " virtual std::string GetHtmlInfo(int refresh) { std::string output; output.append(""About Network""); if (refresh > 0) output.append(""""); output.append(""""); if (refresh > 0) { output.append(""(Auto-refreshing page every "" + base::IntToString(refresh) + ""s)""); } else { output.append(""(To auto-refresh this page: about:network/<secs>)""); } output.append(""

Ethernet:

""); if (ethernet_ && ethernet_enabled()) { output.append("""" + ToHtmlTableHeader(ethernet_) + """"); output.append("""" + ToHtmlTableRow(ethernet_) + """"); } output.append(""

Wifi:

""); for (size_t i = 0; i < wifi_networks_.size(); ++i) { if (i == 0) output.append("""" + ToHtmlTableHeader(wifi_networks_[i]) + """"); output.append("""" + ToHtmlTableRow(wifi_networks_[i]) + """"); } output.append(""

Cellular:

""); for (size_t i = 0; i < cellular_networks_.size(); ++i) { if (i == 0) output.append("""" + ToHtmlTableHeader(cellular_networks_[i]) + """"); output.append("""" + ToHtmlTableRow(cellular_networks_[i]) + """"); } output.append(""

Remembered Wifi:

""); for (size_t i = 0; i < remembered_wifi_networks_.size(); ++i) { if (i == 0) output.append( """" + ToHtmlTableHeader(remembered_wifi_networks_[i]) + """"); output.append("""" + ToHtmlTableRow(remembered_wifi_networks_[i]) + """"); } output.append(""
""); return output; } ",0 " virtual std::string GetHtmlInfo(int refresh) { return std::string(); } ",0 " virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path, std::string* hardware_address) { hardware_address->clear(); NetworkIPConfigVector ipconfig_vector; if (EnsureCrosLoaded() && !device_path.empty()) { IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str()); if (ipconfig_status) { for (int i = 0; i < ipconfig_status->size; i++) { IPConfig ipconfig = ipconfig_status->ips[i]; ipconfig_vector.push_back( NetworkIPConfig(device_path, ipconfig.type, ipconfig.address, ipconfig.netmask, ipconfig.gateway, ipconfig.name_servers)); } *hardware_address = ipconfig_status->hardware_address; FreeIPConfigStatus(ipconfig_status); std::sort(ipconfig_vector.begin(), ipconfig_vector.end()); } } return ipconfig_vector; } ",0 " virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path, std::string* hardware_address) { hardware_address->clear(); return NetworkIPConfigVector(); } ",0 "NetworkLibrary* NetworkLibrary::GetImpl(bool stub) { if (stub) return new NetworkLibraryStubImpl(); else return new NetworkLibraryImpl(); } ",0 "std::string CellularNetwork::GetRoamingStateString() const { switch (this->roaming_state_) { case ROAMING_STATE_HOME: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME); break; case ROAMING_STATE_ROAMING: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING); break; default: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ROAMING_STATE_UNKNOWN); break; }; } ",0 "std::string Network::GetStateString() const { switch (state_) { case STATE_UNKNOWN: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNKNOWN); case STATE_IDLE: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_IDLE); case STATE_CARRIER: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CARRIER); case STATE_ASSOCIATION: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_ASSOCIATION); case STATE_CONFIGURATION: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CONFIGURATION); case STATE_READY: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_READY); case STATE_DISCONNECT: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_DISCONNECT); case STATE_FAILURE: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_FAILURE); case STATE_ACTIVATION_FAILURE: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_STATE_ACTIVATION_FAILURE); default: break; } return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED); } ",0 " virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) { if (!EnsureCrosLoaded()) return false; DeviceNetworkList* network_list = GetDeviceNetworkList(); if (network_list == NULL) return false; result->clear(); result->reserve(network_list->network_size); const base::Time now = base::Time::Now(); for (size_t i = 0; i < network_list->network_size; ++i) { DCHECK(network_list->networks[i].address); DCHECK(network_list->networks[i].name); WifiAccessPoint ap; ap.mac_address = SafeString(network_list->networks[i].address); ap.name = SafeString(network_list->networks[i].name); ap.timestamp = now - base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds); ap.signal_strength = network_list->networks[i].strength; ap.channel = network_list->networks[i].channel; result->push_back(ap); } FreeDeviceNetworkList(network_list); return true; } ",0 " virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) { return false; } ",0 " WifiNetwork* GetWifiNetworkByName(const std::string& name) { for (size_t i = 0; i < wifi_networks_.size(); ++i) { if (wifi_networks_[i]->name().compare(name) == 0) { return wifi_networks_[i]; } } return NULL; } ",0 " template T GetWirelessNetworkByPath( std::vector& networks, const std::string& path) { typedef typename std::vector::iterator iter_t; iter_t iter = std::find_if(networks.begin(), networks.end(), WirelessNetwork::ServicePathEq(path)); return (iter != networks.end()) ? *iter : NULL; } ",0 " template const T GetWirelessNetworkByPath( const std::vector& networks, const std::string& path) const { typedef typename std::vector::const_iterator iter_t; iter_t iter = std::find_if(networks.begin(), networks.end(), WirelessNetwork::ServicePathEq(path)); return (iter != networks.end()) ? *iter : NULL; } ",0 " const std::string& IPAddress() const { const Network* active = active_network(); if (active != NULL) return active->ip_address(); if (ethernet_) return ethernet_->ip_address(); static std::string null_address(""0.0.0.0""); return null_address; } ",0 " const std::string& IPAddress() const { return ip_address_; } ",0 " void Init() { VLOG(1) << ""Getting initial CrOS network info.""; UpdateSystemInfo(); } ",0 " void InitTestData() { ethernet_ = new EthernetNetwork(); ethernet_->set_connected(true); ethernet_->set_service_path(""eth1""); STLDeleteElements(&wifi_networks_); wifi_networks_.clear(); WifiNetwork* wifi1 = new WifiNetwork(); wifi1->set_service_path(""fw1""); wifi1->set_name(""Fake Wifi 1""); wifi1->set_strength(90); wifi1->set_connected(false); wifi1->set_encryption(SECURITY_NONE); wifi_networks_.push_back(wifi1); WifiNetwork* wifi2 = new WifiNetwork(); wifi2->set_service_path(""fw2""); wifi2->set_name(""Fake Wifi 2""); wifi2->set_strength(70); wifi2->set_connected(true); wifi2->set_encryption(SECURITY_WEP); wifi_networks_.push_back(wifi2); WifiNetwork* wifi3 = new WifiNetwork(); wifi3->set_service_path(""fw3""); wifi3->set_name(""Fake Wifi 3""); wifi3->set_strength(50); wifi3->set_connected(false); wifi3->set_encryption(SECURITY_WEP); wifi_networks_.push_back(wifi3); wifi_ = wifi2; STLDeleteElements(&cellular_networks_); cellular_networks_.clear(); CellularNetwork* cellular1 = new CellularNetwork(); cellular1->set_service_path(""fc1""); cellular1->set_name(""Fake Cellular 1""); cellular1->set_strength(70); cellular1->set_connected(true); cellular1->set_activation_state(ACTIVATION_STATE_PARTIALLY_ACTIVATED); cellular1->set_payment_url(std::string(""http://www.google.com"")); cellular_networks_.push_back(cellular1); cellular_ = cellular1; remembered_wifi_networks_.clear(); remembered_wifi_networks_.push_back(new WifiNetwork(*wifi2)); int devices = (1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | (1 << TYPE_CELLULAR); available_devices_ = devices; enabled_devices_ = devices; connected_devices_ = devices; offline_mode_ = false; } ",0 "bool WifiNetwork::IsCertificateLoaded() const { static const std::string settings_string(""SETTINGS:""); static const std::string pkcs11_key(""key_id""); if (cert_path_.find(settings_string) == 0) { std::string::size_type idx = cert_path_.find(pkcs11_key); if (idx != std::string::npos) idx = cert_path_.find_first_not_of(kWhitespaceASCII, idx + pkcs11_key.length()); if (idx != std::string::npos && cert_path_[idx] == '=') return true; } return false; } ",0 "Network::Network(const Network& network) { service_path_ = network.service_path(); device_path_ = network.device_path(); ip_address_ = network.ip_address(); type_ = network.type(); state_ = network.state(); error_ = network.error(); } ",0 "Network::Network(const ServiceInfo* service) { type_ = service->type; state_ = service->state; error_ = service->error; service_path_ = SafeString(service->service_path); device_path_ = SafeString(service->device_path); is_active_ = service->is_active; ip_address_.clear(); if (EnsureCrosLoaded() && connected() && service->device_path) { IPConfigStatus* ipconfig_status = ListIPConfigs(service->device_path); if (ipconfig_status) { for (int i = 0; i < ipconfig_status->size; i++) { IPConfig ipconfig = ipconfig_status->ips[i]; if (strlen(ipconfig.address) > 0) ip_address_ = ipconfig.address; } FreeIPConfigStatus(ipconfig_status); } } } ",0 " NetworkLibraryImpl() : network_manager_monitor_(NULL), data_plan_monitor_(NULL), ethernet_(NULL), wifi_(NULL), cellular_(NULL), available_devices_(0), enabled_devices_(0), connected_devices_(0), offline_mode_(false) { if (EnsureCrosLoaded()) { Init(); network_manager_monitor_ = MonitorNetworkManager(&NetworkManagerStatusChangedHandler, this); data_plan_monitor_ = MonitorCellularDataPlan(&DataPlanUpdateHandler, this); } else { InitTestData(); } } ",0 " NetworkObserverList(NetworkLibraryImpl* library, const std::string& service_path) { network_monitor_ = MonitorNetworkService(&NetworkStatusChangedHandler, service_path.c_str(), library); } ",0 " static void NetworkStatusChangedHandler(void* object, const char* path, const char* key, const Value* value) { NetworkLibraryImpl* networklib = static_cast(object); DCHECK(networklib); networklib->UpdateNetworkStatus(path, key, value); } ",0 " void NotifyNetworkChanged(Network* network) { DCHECK(network); NetworkObserverMap::const_iterator iter = network_observers_.find( network->service_path()); if (iter != network_observers_.end()) { FOR_EACH_OBSERVER(NetworkObserver, *(iter->second), OnNetworkChanged(this, network)); } else { NOTREACHED() << ""There weren't supposed to be any property change observers of "" << network->service_path(); } } ",0 "static ActivationState ParseActivationState( const std::string& activation_state) { if (activation_state == kActivationStateActivated) return ACTIVATION_STATE_ACTIVATED; if (activation_state == kActivationStateActivating) return ACTIVATION_STATE_ACTIVATING; if (activation_state == kActivationStateNotActivated) return ACTIVATION_STATE_NOT_ACTIVATED; if (activation_state == kActivationStateUnknown) return ACTIVATION_STATE_UNKNOWN; if (activation_state == kActivationStatePartiallyActivated) return ACTIVATION_STATE_PARTIALLY_ACTIVATED; return ACTIVATION_STATE_UNKNOWN; } ",0 "static NetworkTechnology ParseNetworkTechnology( const std::string& technology) { if (technology == kNetworkTechnology1Xrtt) return NETWORK_TECHNOLOGY_1XRTT; if (technology == kNetworkTechnologyEvdo) return NETWORK_TECHNOLOGY_EVDO; if (technology == kNetworkTechnologyGprs) return NETWORK_TECHNOLOGY_GPRS; if (technology == kNetworkTechnologyEdge) return NETWORK_TECHNOLOGY_EDGE; if (technology == kNetworkTechnologyUmts) return NETWORK_TECHNOLOGY_UMTS; if (technology == kNetworkTechnologyHspa) return NETWORK_TECHNOLOGY_HSPA; if (technology == kNetworkTechnologyHspaPlus) return NETWORK_TECHNOLOGY_HSPA_PLUS; if (technology == kNetworkTechnologyLte) return NETWORK_TECHNOLOGY_LTE; if (technology == kNetworkTechnologyLteAdvanced) return NETWORK_TECHNOLOGY_LTE_ADVANCED; return NETWORK_TECHNOLOGY_UNKNOWN; } ",0 "static NetworkRoamingState ParseRoamingState( const std::string& roaming_state) { if (roaming_state == kRoamingStateHome) return ROAMING_STATE_HOME; if (roaming_state == kRoamingStateRoaming) return ROAMING_STATE_ROAMING; if (roaming_state == kRoamingStateUnknown) return ROAMING_STATE_UNKNOWN; return ROAMING_STATE_UNKNOWN; } ",0 "static ConnectionState ParseState(const std::string& state) { if (state == kStateIdle) return STATE_IDLE; if (state == kStateCarrier) return STATE_CARRIER; if (state == kStateAssociation) return STATE_ASSOCIATION; if (state == kStateConfiguration) return STATE_CONFIGURATION; if (state == kStateReady) return STATE_READY; if (state == kStateDisconnect) return STATE_DISCONNECT; if (state == kStateFailure) return STATE_FAILURE; if (state == kStateActivationFailure) return STATE_ACTIVATION_FAILURE; return STATE_UNKNOWN; } ",0 " static void ParseSystem(SystemInfo* system, EthernetNetwork** ethernet, WifiNetworkVector* wifi_networks, CellularNetworkVector* cellular_networks, WifiNetworkVector* remembered_wifi_networks) { DVLOG(1) << ""ParseSystem:""; DCHECK(!(*ethernet)); for (int i = 0; i < system->service_size; i++) { const ServiceInfo* service = system->GetServiceInfo(i); DVLOG(1) << "" ("" << service->type << "") "" << service->name << "" mode="" << service->mode << "" state="" << service->state << "" sec="" << service->security << "" req="" << service->passphrase_required << "" pass="" << service->passphrase << "" id="" << service->identity << "" certpath="" << service->cert_path << "" str="" << service->strength << "" fav="" << service->favorite << "" auto="" << service->auto_connect << "" is_active="" << service->is_active << "" error="" << service->error; if (service->type == TYPE_ETHERNET) (*ethernet) = new EthernetNetwork(service); else if (service->type == TYPE_WIFI) { wifi_networks->push_back(new WifiNetwork(service)); } else if (service->type == TYPE_CELLULAR) { cellular_networks->push_back(new CellularNetwork(service)); } } if (!(*ethernet)) (*ethernet) = new EthernetNetwork(); DVLOG(1) << ""Remembered networks:""; for (int i = 0; i < system->remembered_service_size; i++) { const ServiceInfo* service = system->GetRememberedServiceInfo(i); if (service->auto_connect) { DVLOG(1) << "" ("" << service->type << "") "" << service->name << "" mode="" << service->mode << "" sec="" << service->security << "" pass="" << service->passphrase << "" id="" << service->identity << "" certpath="" << service->cert_path << "" auto="" << service->auto_connect; if (service->type == TYPE_WIFI) { remembered_wifi_networks->push_back(new WifiNetwork(service)); } } } } ",0 " virtual void RefreshCellularDataPlans(const CellularNetwork* network) { DCHECK(network); if (!EnsureCrosLoaded() || !network) return; RequestCellularDataPlanUpdate(network->service_path().c_str()); } ",0 " virtual void RefreshCellularDataPlans(const CellularNetwork* network) {} ",0 " virtual void RemoveCellularDataPlanObserver( CellularDataPlanObserver* observer) { data_plan_observers_.RemoveObserver(observer); } ",0 " virtual void RemoveCellularDataPlanObserver( CellularDataPlanObserver* observer) {} ",0 " virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) { network_manager_observers_.RemoveObserver(observer); } ",0 " virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {} ",0 " virtual void RemoveNetworkObserver(const std::string& service_path, NetworkObserver* observer) { DCHECK(observer); DCHECK(service_path.size()); NetworkObserverMap::iterator map_iter = network_observers_.find(service_path); if (map_iter != network_observers_.end()) { map_iter->second->RemoveObserver(observer); if (!map_iter->second->size()) { delete map_iter->second; network_observers_.erase(map_iter++); } } } ",0 " virtual void RemoveNetworkObserver(const std::string& service_path, NetworkObserver* observer) {} ",0 " virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) { DCHECK(observer); NetworkObserverMap::iterator map_iter = network_observers_.begin(); while (map_iter != network_observers_.end()) { map_iter->second->RemoveObserver(observer); if (!map_iter->second->size()) { delete map_iter->second; network_observers_.erase(map_iter++); } else { ++map_iter; } } } ",0 " virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {} ",0 " virtual void RequestWifiScan() { if (EnsureCrosLoaded()) { RequestScan(TYPE_WIFI); } } ",0 " virtual void RequestWifiScan() {} ",0 "static std::string SafeString(const char* s) { return s ? std::string(s) : std::string(); } ",0 " virtual void SaveCellularNetwork(const CellularNetwork* network) { DCHECK(network); if (!EnsureCrosLoaded() || !network) return; SetAutoConnect(network->service_path().c_str(), network->auto_connect()); } ",0 " virtual void SaveCellularNetwork(const CellularNetwork* network) {} ",0 " virtual void SaveWifiNetwork(const WifiNetwork* network) { DCHECK(network); if (!EnsureCrosLoaded() || !network) return; SetPassphrase( network->service_path().c_str(), network->passphrase().c_str()); SetIdentity(network->service_path().c_str(), network->identity().c_str()); SetCertPath(network->service_path().c_str(), network->cert_path().c_str()); SetAutoConnect(network->service_path().c_str(), network->auto_connect()); } ",0 " virtual void SaveWifiNetwork(const WifiNetwork* network) {} ",0 "bool CellularNetwork::StartActivation() const { if (!EnsureCrosLoaded()) return false; return ActivateCellularModem(service_path_.c_str(), NULL); } ",0 "static std::string ToHtmlTableHeader(Network* network) { std::string str; if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) { str += WrapWithTH(""Name"") + WrapWithTH(""Auto-Connect"") + WrapWithTH(""Strength""); if (network->type() == TYPE_WIFI) str += WrapWithTH(""Encryption"") + WrapWithTH(""Passphrase"") + WrapWithTH(""Identity"") + WrapWithTH(""Certificate""); } str += WrapWithTH(""State"") + WrapWithTH(""Error"") + WrapWithTH(""IP Address""); return str; } ",0 "static std::string ToHtmlTableRow(Network* network) { std::string str; if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) { WirelessNetwork* wireless = static_cast(network); str += WrapWithTD(wireless->name()) + WrapWithTD(base::IntToString(wireless->auto_connect())) + WrapWithTD(base::IntToString(wireless->strength())); if (network->type() == TYPE_WIFI) { WifiNetwork* wifi = static_cast(network); str += WrapWithTD(wifi->GetEncryptionString()) + WrapWithTD(std::string(wifi->passphrase().length(), '*')) + WrapWithTD(wifi->identity()) + WrapWithTD(wifi->cert_path()); } } str += WrapWithTD(network->GetStateString()) + WrapWithTD(network->failed() ? network->GetErrorString() : """") + WrapWithTD(network->ip_address()); return str; } ",0 " void UpdateCellularDataPlan(const CellularDataPlanList* data_plans) { DCHECK(cellular_); cellular_->SetDataPlans(data_plans); NotifyCellularDataPlanChanged(); } ",0 " void UpdateNetworkStatus(const char* path, const char* key, const Value* value) { if (key == NULL || value == NULL) return; if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &NetworkLibraryImpl::UpdateNetworkStatus, path, key, value)); return; } bool boolval = false; int intval = 0; std::string stringval; Network* network; if (ethernet_->service_path() == path) { network = ethernet_; } else { CellularNetwork* cellular = GetWirelessNetworkByPath(cellular_networks_, path); WifiNetwork* wifi = GetWirelessNetworkByPath(wifi_networks_, path); if (cellular == NULL && wifi == NULL) return; WirelessNetwork* wireless; if (wifi != NULL) wireless = static_cast(wifi); else wireless = static_cast(cellular); if (strcmp(key, kSignalStrengthProperty) == 0) { if (value->GetAsInteger(&intval)) wireless->set_strength(intval); } else if (cellular != NULL) { if (strcmp(key, kRestrictedPoolProperty) == 0) { if (value->GetAsBoolean(&boolval)) cellular->set_restricted_pool(boolval); } else if (strcmp(key, kActivationStateProperty) == 0) { if (value->GetAsString(&stringval)) cellular->set_activation_state(ParseActivationState(stringval)); } else if (strcmp(key, kPaymentURLProperty) == 0) { if (value->GetAsString(&stringval)) cellular->set_payment_url(stringval); } else if (strcmp(key, kNetworkTechnologyProperty) == 0) { if (value->GetAsString(&stringval)) cellular->set_network_technology( ParseNetworkTechnology(stringval)); } else if (strcmp(key, kRoamingStateProperty) == 0) { if (value->GetAsString(&stringval)) cellular->set_roaming_state(ParseRoamingState(stringval)); } } network = wireless; } if (strcmp(key, kIsActiveProperty) == 0) { if (value->GetAsBoolean(&boolval)) network->set_active(boolval); } else if (strcmp(key, kStateProperty) == 0) { if (value->GetAsString(&stringval)) network->set_state(ParseState(stringval)); } NotifyNetworkChanged(network); } ",0 " void UpdateSystemInfo() { if (EnsureCrosLoaded()) { UpdateNetworkManagerStatus(); } } ",0 "WifiNetwork::WifiNetwork() : WirelessNetwork(), encryption_(SECURITY_NONE) { type_ = TYPE_WIFI; } ",0 "WifiNetwork::WifiNetwork(const WifiNetwork& network) : WirelessNetwork(network) { encryption_ = network.encryption(); passphrase_ = network.passphrase(); identity_ = network.identity(); cert_path_ = network.cert_path(); } ",0 "WirelessNetwork::WirelessNetwork(const WirelessNetwork& network) : Network(network) { name_ = network.name(); strength_ = network.strength(); auto_connect_ = network.auto_connect(); favorite_ = network.favorite(); } ",0 "WirelessNetwork::WirelessNetwork(const ServiceInfo* service) : Network(service) { name_ = SafeString(service->name); strength_ = service->strength; auto_connect_ = service->auto_connect; favorite_ = service->favorite; } ",0 "static std::string WrapWithTD(std::string text) { return """" + text + """"; } ",0 "static std::string WrapWithTH(std::string text) { return """" + text + """"; } ",0 " virtual const Network* active_network() const { if (ethernet_ && ethernet_->is_active()) return ethernet_; if (wifi_ && wifi_->is_active()) return wifi_; if (cellular_ && cellular_->is_active()) return cellular_; return NULL; } ",0 " virtual const Network* active_network() const { return NULL; } ",0 " virtual bool cellular_available() const { return available_devices_ & (1 << TYPE_CELLULAR); } ",0 " virtual bool cellular_available() const { return false; } ",0 " virtual bool cellular_connected() const { return cellular_ ? cellular_->connected() : false; } ",0 " virtual bool cellular_connected() const { return false; } ",0 " virtual bool cellular_connecting() const { return cellular_ ? cellular_->connecting() : false; } ",0 " virtual bool cellular_connecting() const { return false; } ",0 " virtual bool cellular_enabled() const { return enabled_devices_ & (1 << TYPE_CELLULAR); } ",0 " virtual CellularNetwork* cellular_network() { return cellular_; } ",0 " virtual const CellularNetworkVector& cellular_networks() const { return cellular_networks_; } ",0 "CellularNetwork::DataLeft CellularNetwork::data_left() const { if (data_plans_.empty()) return DATA_NORMAL; const CellularDataPlan& plan(data_plans_[0]); if (plan.plan_type == CELLULAR_DATA_PLAN_UNLIMITED) { base::TimeDelta remaining = plan.plan_end_time - plan.update_time; if (remaining <= base::TimeDelta::FromSeconds(0)) return DATA_NONE; else if (remaining <= base::TimeDelta::FromSeconds(kCellularDataVeryLowSecs)) return DATA_VERY_LOW; else if (remaining <= base::TimeDelta::FromSeconds(kCellularDataLowSecs)) return DATA_LOW; else return DATA_NORMAL; } else if (plan.plan_type == CELLULAR_DATA_PLAN_METERED_PAID || plan.plan_type == CELLULAR_DATA_PLAN_METERED_BASE) { int64 remaining = plan.plan_data_bytes - plan.data_bytes_used; if (remaining <= 0) return DATA_NONE; else if (remaining <= kCellularDataVeryLowBytes) return DATA_VERY_LOW; else if (remaining <= kCellularDataLowBytes) return DATA_LOW; else return DATA_NORMAL; } return DATA_NORMAL; } ",0 " virtual bool ethernet_available() const { return true; } ",0 " virtual bool ethernet_connected() const { return ethernet_ ? ethernet_->connected() : false; } ",0 " virtual bool ethernet_connected() const { return true; } ",0 " virtual bool ethernet_connecting() const { return false; } ",0 " virtual bool ethernet_enabled() const { return enabled_devices_ & (1 << TYPE_ETHERNET); } ",0 " virtual bool ethernet_enabled() const { return true; } ",0 " virtual EthernetNetwork* ethernet_network() { return ethernet_; } ",0 " virtual bool has_cellular_networks() const { return cellular_networks_.begin() != cellular_networks_.end(); } ",0 "bool CellularNetwork::is_gsm() const { return network_technology_ != NETWORK_TECHNOLOGY_EVDO && network_technology_ != NETWORK_TECHNOLOGY_1XRTT && network_technology_ != NETWORK_TECHNOLOGY_UNKNOWN; } ",0 " virtual bool offline_mode() const { return offline_mode_; } ",0 " virtual bool offline_mode() const { return false; } ",0 " virtual const WifiNetworkVector& remembered_wifi_networks() const { return remembered_wifi_networks_; } ",0 " virtual const WifiNetworkVector& remembered_wifi_networks() const { return wifi_networks_; } ",0 " virtual bool wifi_available() const { return available_devices_ & (1 << TYPE_WIFI); } ",0 " virtual bool wifi_available() const { return false; } ",0 " virtual bool wifi_connected() const { return false; } ",0 " virtual bool wifi_connecting() const { return wifi_ ? wifi_->connecting() : false; } ",0 " virtual bool wifi_connecting() const { return false; } ",0 " virtual bool wifi_enabled() const { return enabled_devices_ & (1 << TYPE_WIFI); } ",0 " virtual bool wifi_enabled() const { return false; } ",0 " virtual WifiNetwork* wifi_network() { return wifi_; } ",0 " virtual const WifiNetworkVector& wifi_networks() const { return wifi_networks_; } ",0 "CellularNetwork::~CellularNetwork() { } ",0 " ~NetworkLibraryImpl() { network_manager_observers_.Clear(); if (network_manager_monitor_) DisconnectPropertyChangeMonitor(network_manager_monitor_); data_plan_observers_.Clear(); if (data_plan_monitor_) DisconnectDataPlanUpdateMonitor(data_plan_monitor_); STLDeleteValues(&network_observers_); ClearNetworks(); } ",0 " ~NetworkLibraryStubImpl() { if (ethernet_) delete ethernet_; } ",0 " virtual ~NetworkObserverList() { if (network_monitor_) DisconnectPropertyChangeMonitor(network_monitor_); } ",0 " bool AddCallback(GetUsageAndQuotaCallback* callback, bool unlimited) { if (unlimited) unlimited_callbacks_.push_back(callback); else callbacks_.push_back(callback); return (callbacks_.size() + unlimited_callbacks_.size() == 1); } ",0 " bool AppendEntry(const TableEntry& entry) { entries_.push_back(entry); return true; } ",0 " void CallCallbacksAndClear( CallbackList* callbacks, QuotaStatusCode status, int64 usage, int64 quota) { for (CallbackList::iterator iter = callbacks->begin(); iter != callbacks->end(); ++iter) { (*iter)->Run(status, usage, quota); delete *iter; } callbacks->clear(); } ",0 " void CheckCompleted() { if (--waiting_callbacks_ <= 0) { DispatchCallbacks(); DCHECK(callbacks_.empty()); DCHECK(unlimited_callbacks_.empty()); UsageAndQuotaDispatcherTaskMap& dispatcher_map = manager()->usage_and_quota_dispatchers_; DCHECK(dispatcher_map.find(std::make_pair(host_, type_)) != dispatcher_map.end()); dispatcher_map.erase(std::make_pair(host_, type_)); CallCompleted(); } } ",0 "void CountOriginType(const std::set& origins, SpecialStoragePolicy* policy, size_t* protected_origins, size_t* unlimited_origins) { DCHECK(protected_origins); DCHECK(unlimited_origins); *protected_origins = 0; *unlimited_origins = 0; if (!policy) return; for (std::set::const_iterator itr = origins.begin(); itr != origins.end(); ++itr) { if (policy->IsStorageProtected(*itr)) ++*protected_origins; if (policy->IsStorageUnlimited(*itr)) ++*unlimited_origins; } } ",0 "QuotaManager::UsageAndQuotaDispatcherTask::Create( QuotaManager* manager, const std::string& host, StorageType type) { switch (type) { case kStorageTypeTemporary: return new UsageAndQuotaDispatcherTaskForTemporary( manager, host); case kStorageTypePersistent: return new UsageAndQuotaDispatcherTaskForPersistent( manager, host); default: NOTREACHED(); } return NULL; } ",0 "void QuotaManager::DeleteOnCorrectThread() const { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->DeleteSoon(FROM_HERE, this); return; } delete this; } ",0 "void QuotaManager::DeleteOriginData( const GURL& origin, StorageType type, StatusCallback* callback) { LazyInitialize(); if (origin.is_empty() || clients_.empty()) { callback->Run(kQuotaStatusOk); delete callback; return; } OriginDataDeleter* deleter = new OriginDataDeleter(this, origin, type, callback); deleter->Start(); } ",0 " DeleteOriginInfo( QuotaManager* manager, const GURL& origin, StorageType type) : DatabaseTaskBase(manager), origin_(origin), type_(type) {} ",0 " void DidDeleteOriginData(QuotaStatusCode status) { DCHECK_GT(remaining_clients_, 0); if (status != kQuotaStatusOk) ++error_count_; if (--remaining_clients_ == 0) CallCompleted(); } ",0 "void QuotaManager::DidGetAvailableSpaceForEviction( QuotaStatusCode status, int64 available_space) { eviction_context_.get_usage_and_quota_callback->Run(status, eviction_context_.usage, eviction_context_.unlimited_usage, eviction_context_.quota, available_space); eviction_context_.get_usage_and_quota_callback.reset(); } ",0 "void QuotaManager::DidGetDatabaseLRUOrigin(const GURL& origin) { if (origins_in_use_.find(origin) != origins_in_use_.end() || access_notified_origins_.find(origin) != access_notified_origins_.end()) lru_origin_callback_->Run(GURL()); else lru_origin_callback_->Run(origin); access_notified_origins_.clear(); lru_origin_callback_.reset(); } ",0 " void DidGetGlobalQuota(QuotaStatusCode status, StorageType type, int64 quota) { DCHECK_EQ(type_, type); quota_status_ = status; quota_ = quota; CheckCompleted(); } ",0 "void QuotaManager::DidGetGlobalQuotaForEviction( QuotaStatusCode status, StorageType type, int64 quota) { DCHECK_EQ(type, kStorageTypeTemporary); if (status != kQuotaStatusOk) { eviction_context_.get_usage_and_quota_callback->Run( status, 0, 0, 0, 0); eviction_context_.get_usage_and_quota_callback.reset(); return; } eviction_context_.quota = quota; GetAvailableSpace(callback_factory_. NewCallback(&QuotaManager::DidGetAvailableSpaceForEviction)); } ",0 " void DidGetGlobalUsage(StorageType type, int64 usage, int64 unlimited_usage) { DCHECK_EQ(type_, type); DCHECK_GE(usage, unlimited_usage); global_usage_ = usage; global_unlimited_usage_ = unlimited_usage; CheckCompleted(); } ",0 "void QuotaManager::DidGetGlobalUsageForEviction( StorageType type, int64 usage, int64 unlimited_usage) { DCHECK_EQ(type, kStorageTypeTemporary); DCHECK_GE(usage, unlimited_usage); eviction_context_.usage = usage; eviction_context_.unlimited_usage = unlimited_usage; GetTemporaryGlobalQuota(callback_factory_. NewCallback(&QuotaManager::DidGetGlobalQuotaForEviction)); } ",0 " void DidGetHostQuota(QuotaStatusCode status, const std::string& host, StorageType type, int64 quota) { DCHECK_EQ(host_, host); DCHECK_EQ(type_, type); quota_status_ = status; quota_ = quota; CheckCompleted(); } ",0 " void DidGetHostUsage(const std::string& host, StorageType type, int64 usage) { DCHECK_EQ(host_, host); DCHECK_EQ(type_, type); host_usage_ = usage; CheckCompleted(); } ",0 "void QuotaManager::DidGetPersistentGlobalUsageForHistogram( StorageType type, int64 usage, int64 unlimited_usage) { UMA_HISTOGRAM_MBYTES(""Quota.GlobalUsageOfPersistentStorage"", usage); std::set origins; GetCachedOrigins(type, &origins); size_t num_origins = origins.size(); size_t protected_origins = 0; size_t unlimited_origins = 0; CountOriginType(origins, special_storage_policy_, &protected_origins, &unlimited_origins); UMA_HISTOGRAM_COUNTS(""Quota.NumberOfPersistentStorageOrigins"", num_origins); UMA_HISTOGRAM_COUNTS(""Quota.NumberOfProtectedPersistentStorageOrigins"", protected_origins); UMA_HISTOGRAM_COUNTS(""Quota.NumberOfUnlimitedPersistentStorageOrigins"", unlimited_origins); } ",0 "void QuotaManager::DidInitializeTemporaryGlobalQuota(int64 quota) { temporary_global_quota_ = quota; temporary_global_quota_callbacks_.Run( db_disabled_ ? kQuotaErrorInvalidAccess : kQuotaStatusOk, kStorageTypeTemporary, quota); if (db_disabled_ || eviction_disabled_) return; if (!need_initialize_origins_) { StartEviction(); return; } temporary_usage_tracker_->GetGlobalUsage(callback_factory_.NewCallback( &QuotaManager::DidRunInitialGetTemporaryGlobalUsage)); } ",0 "void QuotaManager::DidRunInitialGetTemporaryGlobalUsage( StorageType type, int64 usage_unused, int64 unlimited_usage_unused) { DCHECK_EQ(type, kStorageTypeTemporary); scoped_refptr task( new InitializeTemporaryOriginsInfoTask( this, temporary_usage_tracker_.get())); task->Start(); } ",0 "void QuotaManager::DumpOriginInfoTable( DumpOriginInfoTableCallback* callback) { make_scoped_refptr(new DumpOriginInfoTableTask(this, callback))->Start(); } ",0 " DumpOriginInfoTableTask( QuotaManager* manager, Callback* callback) : DatabaseTaskBase(manager), callback_(callback) { } ",0 "void QuotaManager::DumpQuotaTable(DumpQuotaTableCallback* callback) { make_scoped_refptr(new DumpQuotaTableTask(this, callback))->Start(); } ",0 " DumpQuotaTableTask( QuotaManager* manager, Callback* callback) : DatabaseTaskBase(manager), callback_(callback) { } ",0 "void QuotaManager::EvictOriginData( const GURL& origin, StorageType type, EvictOriginDataCallback* callback) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK_EQ(type, kStorageTypeTemporary); eviction_context_.evicted_origin = origin; eviction_context_.evicted_type = type; eviction_context_.evict_origin_data_callback.reset(callback); DeleteOriginData(origin, type, callback_factory_.NewCallback( &QuotaManager::DidOriginDataEvicted)); } ",0 "void QuotaManager::GetAvailableSpace(AvailableSpaceCallback* callback) { scoped_refptr task( new AvailableSpaceQueryTask(this, db_thread_, profile_path_, callback)); task->Start(); } ",0 "void QuotaManager::GetCachedOrigins( StorageType type, std::set* origins) { DCHECK(origins); LazyInitialize(); switch (type) { case kStorageTypeTemporary: DCHECK(temporary_usage_tracker_.get()); temporary_usage_tracker_->GetCachedOrigins(origins); return; case kStorageTypePersistent: DCHECK(persistent_usage_tracker_.get()); persistent_usage_tracker_->GetCachedOrigins(origins); return; default: NOTREACHED(); } } ",0 "void QuotaManager::GetGlobalUsage( StorageType type, GlobalUsageCallback* callback) { LazyInitialize(); GetUsageTracker(type)->GetGlobalUsage(callback); } ",0 "void QuotaManager::GetHostUsage(const std::string& host, StorageType type, HostUsageCallback* callback) { LazyInitialize(); GetUsageTracker(type)->GetHostUsage(host, callback); } ",0 "int64 GetInitialTemporaryStorageQuotaSize(const FilePath& path, bool is_incognito) { int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(path); UMA_HISTOGRAM_MBYTES(""Quota.FreeDiskSpaceForProfile"", free_space); if (free_space < QuotaManager::kTemporaryStorageQuotaDefaultSize * 2) return 0; if (is_incognito) return QuotaManager::kIncognitoDefaultTemporaryQuota; if (free_space < QuotaManager::kTemporaryStorageQuotaDefaultSize * 20) return QuotaManager::kTemporaryStorageQuotaDefaultSize; if (free_space < QuotaManager::kTemporaryStorageQuotaMaxSize * 20) return free_space / 20; return QuotaManager::kTemporaryStorageQuotaMaxSize; } ",0 "void QuotaManager::GetLRUOrigin( StorageType type, GetLRUOriginCallback* callback) { LazyInitialize(); DCHECK(!lru_origin_callback_.get()); lru_origin_callback_.reset(callback); if (db_disabled_) { lru_origin_callback_->Run(GURL()); lru_origin_callback_.reset(); return; } scoped_refptr task(new GetLRUOriginTask( this, type, origins_in_use_, origins_in_error_, callback_factory_.NewCallback( &QuotaManager::DidGetDatabaseLRUOrigin))); task->Start(); } ",0 " GetLRUOriginTask( QuotaManager* manager, StorageType type, const std::map& origins_in_use, const std::map& origins_in_error, GetLRUOriginCallback *callback) : DatabaseTaskBase(manager), type_(type), callback_(callback), special_storage_policy_(manager->special_storage_policy_) { for (std::map::const_iterator p = origins_in_use.begin(); p != origins_in_use.end(); ++p) { if (p->second > 0) exceptions_.insert(p->first); } for (std::map::const_iterator p = origins_in_error.begin(); p != origins_in_error.end(); ++p) { if (p->second > QuotaManager::kThresholdOfErrorsToBeBlacklisted) exceptions_.insert(p->first); } } ",0 " GetModifiedSinceTask( QuotaManager* manager, StorageType type, base::Time modified_since, GetOriginsCallback* callback) : DatabaseTaskBase(manager), type_(type), modified_since_(modified_since), callback_(callback) {} ",0 "void QuotaManager::GetOriginsModifiedSince( StorageType type, base::Time modified_since, GetOriginsCallback* callback) { LazyInitialize(); make_scoped_refptr(new GetModifiedSinceTask( this, type, modified_since, callback))->Start(); } ",0 " GetPersistentHostQuotaTask( QuotaManager* manager, const std::string& host, HostQuotaCallback* callback) : DatabaseTaskBase(manager), host_(host), quota_(-1), callback_(callback) { } ",0 "void QuotaManager::GetStatistics( std::map* statistics) { DCHECK(statistics); if (temporary_storage_evictor_.get()) { std::map stats; temporary_storage_evictor_->GetStatistics(&stats); for (std::map::iterator p = stats.begin(); p != stats.end(); ++p) (*statistics)[p->first] = base::Int64ToString(p->second); } } ",0 "void QuotaManager::GetTemporaryGlobalQuota(QuotaCallback* callback) { LazyInitialize(); if (temporary_global_quota_ >= 0) { callback->Run(kQuotaStatusOk, kStorageTypeTemporary, temporary_global_quota_); delete callback; return; } temporary_global_quota_callbacks_.Add(callback); } ",0 " void QuotaManager::GetUsageAndQuota( const GURL& origin, StorageType type, GetUsageAndQuotaCallback* callback_ptr) { scoped_ptr callback(callback_ptr); LazyInitialize(); if (type == kStorageTypeUnknown) { callback->Run(kQuotaErrorNotSupported, 0, 0); return; } std::string host = net::GetHostOrSpecFromURL(origin); UsageAndQuotaDispatcherTaskMap::iterator found = usage_and_quota_dispatchers_.find(std::make_pair(host, type)); if (found == usage_and_quota_dispatchers_.end()) { UsageAndQuotaDispatcherTask* dispatcher = UsageAndQuotaDispatcherTask::Create(this, host, type); found = usage_and_quota_dispatchers_.insert( std::make_pair(std::make_pair(host, type), dispatcher)).first; } if (found->second->AddCallback( callback.release(), IsStorageUnlimited(origin))) { found->second->Start(); } } ",0 "void QuotaManager::GetUsageAndQuotaForEviction( GetUsageAndQuotaForEvictionCallback* callback) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK(!eviction_context_.get_usage_and_quota_callback.get()); eviction_context_.get_usage_and_quota_callback.reset(callback); GetGlobalUsage(kStorageTypeTemporary, callback_factory_. NewCallback(&QuotaManager::DidGetGlobalUsageForEviction)); } ",0 "UsageTracker* QuotaManager::GetUsageTracker(StorageType type) const { switch (type) { case kStorageTypeTemporary: return temporary_usage_tracker_.get(); case kStorageTypePersistent: return persistent_usage_tracker_.get(); default: NOTREACHED(); } return NULL; } ",0 " InitializeTask( QuotaManager* manager, const FilePath& profile_path, bool is_incognito) : DatabaseTaskBase(manager), profile_path_(profile_path), is_incognito_(is_incognito), need_initialize_origins_(false), temporary_storage_quota_(-1) { } ",0 " InitializeTemporaryOriginsInfoTask( QuotaManager* manager, UsageTracker* temporary_usage_tracker) : DatabaseTaskBase(manager), has_registered_origins_(false) { DCHECK(temporary_usage_tracker); temporary_usage_tracker->GetCachedOrigins(&origins_); } ",0 "void QuotaManager::LazyInitialize() { DCHECK(io_thread_->BelongsToCurrentThread()); if (database_.get()) { return; } database_.reset(new QuotaDatabase(is_incognito_ ? FilePath() : profile_path_.AppendASCII(kDatabaseName))); temporary_usage_tracker_.reset( new UsageTracker(clients_, kStorageTypeTemporary, special_storage_policy_)); persistent_usage_tracker_.reset( new UsageTracker(clients_, kStorageTypePersistent, special_storage_policy_)); scoped_refptr task( new InitializeTask(this, profile_path_, is_incognito_)); task->Start(); } ",0 " QuotaCallback* NewWaitableGlobalQuotaCallback() { ++waiting_callbacks_; return callback_factory_.NewCallback( &UsageAndQuotaDispatcherTask::DidGetGlobalQuota); } ",0 " GlobalUsageCallback* NewWaitableGlobalUsageCallback() { ++waiting_callbacks_; return callback_factory_.NewCallback( &UsageAndQuotaDispatcherTask::DidGetGlobalUsage); } ",0 " HostQuotaCallback* NewWaitableHostQuotaCallback() { ++waiting_callbacks_; return callback_factory_.NewCallback( &UsageAndQuotaDispatcherTask::DidGetHostQuota); } ",0 " HostUsageCallback* NewWaitableHostUsageCallback() { ++waiting_callbacks_; return callback_factory_.NewCallback( &UsageAndQuotaDispatcherTask::DidGetHostUsage); } ",0 "void QuotaManager::NotifyOriginInUse(const GURL& origin) { DCHECK(io_thread_->BelongsToCurrentThread()); origins_in_use_[origin]++; } ",0 "void QuotaManagerProxy::NotifyOriginInUse( const GURL& origin) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::NotifyOriginInUse, origin)); return; } if (manager_) manager_->NotifyOriginInUse(origin); } ",0 "void QuotaManager::NotifyOriginNoLongerInUse(const GURL& origin) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK(IsOriginInUse(origin)); int& count = origins_in_use_[origin]; if (--count == 0) origins_in_use_.erase(origin); } ",0 "void QuotaManagerProxy::NotifyOriginNoLongerInUse( const GURL& origin) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::NotifyOriginNoLongerInUse, origin)); return; } if (manager_) manager_->NotifyOriginNoLongerInUse(origin); } ",0 "void QuotaManager::NotifyStorageAccessed( QuotaClient::ID client_id, const GURL& origin, StorageType type) { NotifyStorageAccessedInternal(client_id, origin, type, base::Time::Now()); } ",0 "void QuotaManagerProxy::NotifyStorageAccessed( QuotaClient::ID client_id, const GURL& origin, StorageType type) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::NotifyStorageAccessed, client_id, origin, type)); return; } if (manager_) manager_->NotifyStorageAccessed(client_id, origin, type); } ",0 "void QuotaManager::NotifyStorageAccessedInternal( QuotaClient::ID client_id, const GURL& origin, StorageType type, base::Time accessed_time) { LazyInitialize(); if (type == kStorageTypeTemporary && lru_origin_callback_.get()) { access_notified_origins_.insert(origin); } if (db_disabled_) return; make_scoped_refptr(new UpdateAccessTimeTask( this, origin, type, accessed_time))->Start(); } ",0 "void QuotaManager::NotifyStorageModified( QuotaClient::ID client_id, const GURL& origin, StorageType type, int64 delta) { NotifyStorageModifiedInternal(client_id, origin, type, delta, base::Time::Now()); } ",0 "void QuotaManagerProxy::NotifyStorageModified( QuotaClient::ID client_id, const GURL& origin, StorageType type, int64 delta) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::NotifyStorageModified, client_id, origin, type, delta)); return; } if (manager_) manager_->NotifyStorageModified(client_id, origin, type, delta); } ",0 "void QuotaManager::NotifyStorageModifiedInternal( QuotaClient::ID client_id, const GURL& origin, StorageType type, int64 delta, base::Time modified_time) { LazyInitialize(); GetUsageTracker(type)->UpdateUsageCache(client_id, origin, delta); make_scoped_refptr(new UpdateModifiedTimeTask( this, origin, type, modified_time))->Start(); } ",0 " OriginDataDeleter(QuotaManager* manager, const GURL& origin, StorageType type, StatusCallback* callback) : QuotaTask(manager), origin_(origin), type_(type), error_count_(0), remaining_clients_(-1), callback_(callback), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {} ",0 "QuotaManager::QuotaManager(bool is_incognito, const FilePath& profile_path, base::MessageLoopProxy* io_thread, base::MessageLoopProxy* db_thread, SpecialStoragePolicy* special_storage_policy) : is_incognito_(is_incognito), profile_path_(profile_path), proxy_(new QuotaManagerProxy( ALLOW_THIS_IN_INITIALIZER_LIST(this), io_thread)), db_disabled_(false), eviction_disabled_(false), io_thread_(io_thread), db_thread_(db_thread), need_initialize_origins_(false), temporary_global_quota_(-1), special_storage_policy_(special_storage_policy), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } ",0 "QuotaManagerProxy::QuotaManagerProxy( QuotaManager* manager, base::MessageLoopProxy* io_thread) : manager_(manager), io_thread_(io_thread) { } ",0 "void QuotaManager::RegisterClient(QuotaClient* client) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK(!database_.get()); clients_.push_back(client); } ",0 "void QuotaManagerProxy::RegisterClient(QuotaClient* client) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::RegisterClient, client)); return; } if (manager_) manager_->RegisterClient(client); else client->OnQuotaManagerDestroyed(); } ",0 "void QuotaManager::SetPersistentHostQuota(const std::string& host, int64 new_quota, HostQuotaCallback* callback_ptr) { scoped_ptr callback(callback_ptr); LazyInitialize(); if (host.empty()) { callback->Run(kQuotaErrorNotSupported, host, kStorageTypePersistent, 0); return; } if (new_quota < 0) { callback->Run(kQuotaErrorInvalidModification, host, kStorageTypePersistent, -1); return; } if (!db_disabled_) { scoped_refptr task( new UpdatePersistentHostQuotaTask( this, host, new_quota, callback.release())); task->Start(); } else { callback->Run(kQuotaErrorInvalidAccess, host, kStorageTypePersistent, -1); } } ",0 "void QuotaManager::SetTemporaryGlobalQuota(int64 new_quota, QuotaCallback* callback) { LazyInitialize(); if (new_quota < 0) { callback->Run(kQuotaErrorInvalidModification, kStorageTypeTemporary, -1); delete callback; return; } if (!db_disabled_) { scoped_refptr task( new UpdateTemporaryGlobalQuotaTask(this, new_quota, callback)); task->Start(); } else { callback->Run(kQuotaErrorInvalidAccess, kStorageTypeTemporary, -1); delete callback; } } ",0 "void QuotaManager::StartEviction() { DCHECK(!temporary_storage_evictor_.get()); temporary_storage_evictor_.reset(new QuotaTemporaryStorageEvictor(this, kEvictionIntervalInMilliSeconds)); temporary_storage_evictor_->Start(); } ",0 " UpdateAccessTimeTask( QuotaManager* manager, const GURL& origin, StorageType type, base::Time accessed_time) : DatabaseTaskBase(manager), origin_(origin), type_(type), accessed_time_(accessed_time) {} ",0 " UpdateModifiedTimeTask( QuotaManager* manager, const GURL& origin, StorageType type, base::Time modified_time) : DatabaseTaskBase(manager), origin_(origin), type_(type), modified_time_(modified_time) {} ",0 " UpdatePersistentHostQuotaTask( QuotaManager* manager, const std::string& host, int new_quota, HostQuotaCallback* callback) : DatabaseTaskBase(manager), host_(host), new_quota_(new_quota), callback_(callback) { DCHECK_GE(new_quota_, 0); } ",0 " UsageAndQuotaDispatcherTask( QuotaManager* manager, const std::string& host, StorageType type) : QuotaTask(manager), host_(host), type_(type), quota_(-1), global_usage_(-1), global_unlimited_usage_(-1), host_usage_(-1), quota_status_(kQuotaStatusUnknown), waiting_callbacks_(1), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {} ",0 " UsageAndQuotaDispatcherTaskForPersistent( QuotaManager* manager, const std::string& host) : UsageAndQuotaDispatcherTask(manager, host, kStorageTypePersistent) {} ",0 " UsageAndQuotaDispatcherTaskForTemporary( QuotaManager* manager, const std::string& host) : UsageAndQuotaDispatcherTask(manager, host, kStorageTypeTemporary) {} ",0 " CallbackList& callbacks() { return callbacks_; } ",0 " QuotaDatabase* database() const { return database_; } ",0 " bool db_disabled() const { return db_disabled_; } ",0 " int64 global_unlimited_usage() const { return global_unlimited_usage_; } ",0 " int64 global_usage() const { return global_usage_; } ",0 " std::string host() const { return host_; } ",0 " int64 host_usage() const { return host_usage_; } ",0 " QuotaManager* manager() const { return static_cast(observer()); } ",0 " QuotaManager* manager() const { return manager_; } ",0 " int64 quota() const { return quota_; } ",0 "QuotaManager* QuotaManagerProxy::quota_manager() const { DCHECK(!io_thread_ || io_thread_->BelongsToCurrentThread()); return manager_; } ",0 " QuotaStatusCode quota_status() const { return quota_status_; } ",0 " void set_db_disabled(bool db_disabled) { db_disabled_ = db_disabled; } ",0 " StorageType type() const { return type_; } ",0 " virtual ~AvailableSpaceQueryTask() {} ",0 "QuotaManager::~QuotaManager() { DCHECK(io_thread_->BelongsToCurrentThread()); proxy_->manager_ = NULL; std::for_each(clients_.begin(), clients_.end(), std::mem_fun(&QuotaClient::OnQuotaManagerDestroyed)); if (database_.get()) db_thread_->DeleteSoon(FROM_HERE, database_.release()); } ",0 "QuotaManagerProxy::~QuotaManagerProxy() { } ",0 " virtual ~UsageAndQuotaDispatcherTask() { STLDeleteContainerPointers(callbacks_.begin(), callbacks_.end()); STLDeleteContainerPointers(unlimited_callbacks_.begin(), unlimited_callbacks_.end()); } ",0 " MockStorageClient* CreateClient( const MockOriginData* mock_data, size_t mock_data_size) { return new MockStorageClient(quota_manager_->proxy(), mock_data, mock_data_size); } ",0 " void DeleteClientOriginData(QuotaClient* client, const GURL& origin, StorageType type) { DCHECK(client); quota_status_ = kQuotaStatusUnknown; client->DeleteOriginData(origin, type, callback_factory_.NewCallback( &QuotaManagerTest::StatusCallback)); } ",0 " void DeleteOriginData(const GURL& origin, StorageType type) { quota_status_ = kQuotaStatusUnknown; quota_manager_->DeleteOriginData(origin, type, callback_factory_.NewCallback( &QuotaManagerTest::StatusCallback)); } ",0 " void DeleteOriginFromDatabase(const GURL& origin, StorageType type) { quota_manager_->DeleteOriginFromDatabase(origin, type); } ",0 " void DidDumpOriginInfoTable(const OriginInfoTableEntries& entries) { origin_info_entries_ = entries; } ",0 " void DidDumpQuotaTable(const QuotaTableEntries& entries) { quota_entries_ = entries; } ",0 " void DidGetAvailableSpace(QuotaStatusCode status, int64 available_space) { quota_status_ = status; available_space_ = available_space; } ",0 " void DidGetGlobalUsage(StorageType type, int64 usage, int64 unlimited_usage) { type_ = type; usage_ = usage; unlimited_usage_ = unlimited_usage; } ",0 " void DidGetHostQuota(QuotaStatusCode status, const std::string& host, StorageType type, int64 quota) { quota_status_ = status; host_ = host; type_ = type; quota_ = quota; } ",0 " void DidGetHostUsage(const std::string& host, StorageType type, int64 usage) { host_ = host; type_ = type; usage_ = usage; } ",0 " void DidGetLRUOrigin(const GURL& origin) { lru_origin_ = origin; } ",0 " void DidGetModifiedOrigins(const std::set& origins, StorageType type) { modified_origins_ = origins; modified_origins_type_ = type; } ",0 " void DidGetQuota(QuotaStatusCode status, StorageType type, int64 quota) { quota_status_ = status; type_ = type; quota_ = quota; } ",0 " void DidGetUsageAndQuota(QuotaStatusCode status, int64 usage, int64 quota) { quota_status_ = status; usage_ = usage; quota_ = quota; } ",0 " void DidGetUsageAndQuotaAdditional( QuotaStatusCode status, int64 usage, int64 quota) { ++additional_callback_count_; } ",0 " void DidGetUsageAndQuotaForEviction(QuotaStatusCode status, int64 usage, int64 unlimited_usage, int64 quota, int64 available_space) { quota_status_ = status; usage_ = usage; unlimited_usage_ = unlimited_usage; quota_ = quota; available_space_ = available_space; } ",0 " void DumpOriginInfoTable() { origin_info_entries_.clear(); quota_manager_->DumpOriginInfoTable( callback_factory_.NewCallback( &QuotaManagerTest::DidDumpOriginInfoTable)); } ",0 " void EvictOriginData(const GURL& origin, StorageType type) { quota_status_ = kQuotaStatusUnknown; quota_manager_->EvictOriginData(origin, type, callback_factory_.NewCallback( &QuotaManagerTest::StatusCallback)); } ",0 " void GetAvailableSpace() { quota_status_ = kQuotaStatusUnknown; available_space_ = -1; quota_manager_->GetAvailableSpace( callback_factory_.NewCallback( &QuotaManagerTest::DidGetAvailableSpace)); } ",0 " void GetCachedOrigins(StorageType type, std::set* origins) { ASSERT_TRUE(origins != NULL); origins->clear(); quota_manager_->GetCachedOrigins(type, origins); } ",0 " void GetGlobalUsage(StorageType type) { type_ = kStorageTypeUnknown; usage_ = -1; unlimited_usage_ = -1; quota_manager_->GetGlobalUsage(type, callback_factory_.NewCallback( &QuotaManagerTest::DidGetGlobalUsage)); } ",0 " void GetHostUsage(const std::string& host, StorageType type) { host_.clear(); type_ = kStorageTypeUnknown; usage_ = -1; quota_manager_->GetHostUsage(host, type, callback_factory_.NewCallback( &QuotaManagerTest::DidGetHostUsage)); } ",0 " void GetLRUOrigin(StorageType type) { lru_origin_ = GURL(); quota_manager_->GetLRUOrigin(type, callback_factory_.NewCallback(&QuotaManagerTest::DidGetLRUOrigin)); } ",0 " void GetOriginsModifiedSince(StorageType type, base::Time modified_since) { modified_origins_.clear(); modified_origins_type_ = kStorageTypeUnknown; quota_manager_->GetOriginsModifiedSince(type, modified_since, callback_factory_.NewCallback( &QuotaManagerTest::DidGetModifiedOrigins)); } ",0 " void GetTemporaryGlobalQuota() { quota_status_ = kQuotaStatusUnknown; quota_ = -1; quota_manager_->GetTemporaryGlobalQuota( callback_factory_.NewCallback( &QuotaManagerTest::DidGetQuota)); } ",0 " void GetUsageAndQuota(const GURL& origin, StorageType type) { quota_status_ = kQuotaStatusUnknown; usage_ = -1; quota_ = -1; quota_manager_->GetUsageAndQuota(origin, type, callback_factory_.NewCallback( &QuotaManagerTest::DidGetUsageAndQuota)); } ",0 " void GetUsageAndQuotaForEviction() { quota_status_ = kQuotaStatusUnknown; usage_ = -1; unlimited_usage_ = -1; quota_ = -1; available_space_ = -1; quota_manager_->GetUsageAndQuotaForEviction( callback_factory_.NewCallback( &QuotaManagerTest::DidGetUsageAndQuotaForEviction)); } ",0 "void QuotaManagerTest::GetUsage_WithModifyTestBody(const StorageType type) { const MockOriginData data[] = { { ""http://foo.com/"", type, 10 }, { ""http://foo.com:1/"", type, 20 }, }; MockStorageClient* client = CreateClient(data, ARRAYSIZE_UNSAFE(data)); RegisterClient(client); GetUsageAndQuota(GURL(""http://foo.com/""), type); MessageLoop::current()->RunAllPending(); EXPECT_EQ(kQuotaStatusOk, status()); EXPECT_EQ(10 + 20, usage()); client->ModifyOriginAndNotify(GURL(""http://foo.com/""), type, 30); client->ModifyOriginAndNotify(GURL(""http://foo.com:1/""), type, -5); client->AddOriginAndNotify(GURL(""https://foo.com/""), type, 1); GetUsageAndQuota(GURL(""http://foo.com/""), type); MessageLoop::current()->RunAllPending(); EXPECT_EQ(kQuotaStatusOk, status()); EXPECT_EQ(10 + 20 + 30 - 5 + 1, usage()); int foo_usage = usage(); client->AddOriginAndNotify(GURL(""http://bar.com/""), type, 40); GetUsageAndQuota(GURL(""http://bar.com/""), type); MessageLoop::current()->RunAllPending(); EXPECT_EQ(kQuotaStatusOk, status()); EXPECT_EQ(40, usage()); GetGlobalUsage(type); MessageLoop::current()->RunAllPending(); EXPECT_EQ(foo_usage + 40, usage()); EXPECT_EQ(0, unlimited_usage()); } ",0 " void NotifyOriginInUse(const GURL& origin) { quota_manager_->NotifyOriginInUse(origin); } ",0 " void NotifyOriginNoLongerInUse(const GURL& origin) { quota_manager_->NotifyOriginNoLongerInUse(origin); } ",0 " void NotifyStorageAccessed(QuotaClient* client, const GURL& origin, StorageType type) { DCHECK(client); quota_manager_->NotifyStorageAccessedInternal( client->id(), origin, type, IncrementMockTime()); } ",0 " QuotaManagerTest() : callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), mock_time_counter_(0) { } ",0 " void RegisterClient(MockStorageClient* client) { quota_manager_->proxy()->RegisterClient(client); } ",0 " void RunAdditionalUsageAndQuotaTask(const GURL& origin, StorageType type) { quota_manager_->GetUsageAndQuota(origin, type, callback_factory_.NewCallback( &QuotaManagerTest::DidGetUsageAndQuotaAdditional)); } ",0 " void SetPersistentHostQuota(const std::string& host, int64 new_quota) { quota_status_ = kQuotaStatusUnknown; host_.clear(); type_ = kStorageTypeUnknown; quota_ = -1; quota_manager_->SetPersistentHostQuota(host, new_quota, callback_factory_.NewCallback( &QuotaManagerTest::DidGetHostQuota)); } ",0 " void SetTemporaryGlobalQuota(int64 new_quota) { quota_status_ = kQuotaStatusUnknown; quota_ = -1; quota_manager_->SetTemporaryGlobalQuota(new_quota, callback_factory_.NewCallback( &QuotaManagerTest::DidGetQuota)); } ",0 " void SetUp() { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); mock_special_storage_policy_ = new MockSpecialStoragePolicy; quota_manager_ = new QuotaManager( false /* is_incognito */, data_dir_.path(), MessageLoopProxy::current(), MessageLoopProxy::current(), mock_special_storage_policy_); quota_manager_->eviction_disabled_ = true; additional_callback_count_ = 0; } ",0 " void StatusCallback(QuotaStatusCode status) { ++status_callback_count_; quota_status_ = status; } ",0 " int additional_callback_count() const { return additional_callback_count_; } ",0 " int64 available_space() const { return available_space_; } ",0 " const GURL& lru_origin() const { return lru_origin_; } ",0 " MockSpecialStoragePolicy* mock_special_storage_policy() const { return mock_special_storage_policy_.get(); } ",0 " const std::set& modified_origins() const { return modified_origins_; } ",0 " StorageType modified_origins_type() const { return modified_origins_type_; } ",0 " QuotaManager* quota_manager() const { return quota_manager_.get(); } ",0 " void reset_status_callback_count() { status_callback_count_ = 0; } ",0 " void set_additional_callback_count(int c) { additional_callback_count_ = c; } ",0 " int status_callback_count() const { return status_callback_count_; } ",0 " int64 unlimited_usage() const { return unlimited_usage_; } ",0 " int64 usage() const { return usage_; } ",0 "void ClientUsageTracker::AddCachedHost(const std::string& host) { cached_hosts_.insert(host); } ",0 "void ClientUsageTracker::AddCachedOrigin( const GURL& origin, int64 usage) { std::string host = net::GetHostOrSpecFromURL(origin); UsageMap::iterator iter = cached_usage_[host]. insert(UsageMap::value_type(origin, 0)).first; int64 old_usage = iter->second; iter->second = usage; int64 delta = usage - old_usage; if (delta) { global_usage_ += delta; if (global_unlimited_usage_is_valid_ && IsStorageUnlimited(origin)) global_unlimited_usage_ += delta; } DCHECK_GE(iter->second, 0); DCHECK_GE(global_usage_, 0); } ",0 "ClientUsageTracker::ClientUsageTracker( UsageTracker* tracker, QuotaClient* client, StorageType type, SpecialStoragePolicy* special_storage_policy) : tracker_(tracker), client_(client), type_(type), global_usage_(0), global_unlimited_usage_(0), global_usage_retrieved_(false), global_unlimited_usage_is_valid_(true), global_usage_task_(NULL), special_storage_policy_(special_storage_policy) { DCHECK(tracker_); DCHECK(client_); if (special_storage_policy_) special_storage_policy_->AddObserver(this); } ",0 "void UsageTracker::DidGetClientGlobalUsage(StorageType type, int64 usage, int64 unlimited_usage) { DCHECK_EQ(type, type_); global_usage_.usage += usage; global_usage_.unlimited_usage += unlimited_usage; if (--global_usage_.pending_clients == 0) { if (global_usage_.usage < 0) global_usage_.usage = 0; if (global_usage_.unlimited_usage > global_usage_.usage) global_usage_.unlimited_usage = global_usage_.usage; else if (global_usage_.unlimited_usage < 0) global_usage_.unlimited_usage = 0; global_usage_callbacks_.Run(type, global_usage_.usage, global_usage_.unlimited_usage); } } ",0 "void UsageTracker::DidGetClientHostUsage(const std::string& host, StorageType type, int64 usage) { DCHECK_EQ(type, type_); TrackingInfo& info = outstanding_host_usage_[host]; info.usage += usage; if (--info.pending_clients == 0) { if (info.usage < 0) info.usage = 0; host_usage_callbacks_.Run(host, host, type, info.usage); outstanding_host_usage_.erase(host); } } ",0 " void DidGetUsage(int64 usage) { DCHECK(original_message_loop()->BelongsToCurrentThread()); DCHECK(!pending_origins_.empty()); DCHECK(client_tracker_); DCHECK_GE(usage, 0); if (usage < 0) usage = 0; const GURL& origin = pending_origins_.front(); std::string host = net::GetHostOrSpecFromURL(origin); client_tracker_->AddCachedOrigin(origin, usage); pending_origins_.pop_front(); if (pending_origins_.empty() || host != net::GetHostOrSpecFromURL(pending_origins_.front())) { client_tracker_->AddCachedHost(host); } if (pending_origins_.empty()) { CallCompleted(); DeleteSoon(); } } ",0 "void ClientUsageTracker::GatherGlobalUsageComplete() { DCHECK(global_usage_task_ != NULL); global_usage_task_ = NULL; global_usage_retrieved_ = true; DCHECK(global_usage_callback_.HasCallbacks()); global_usage_callback_.Run(type_, global_usage_, GetCachedGlobalUnlimitedUsage()); for (HostUsageCallbackMap::iterator iter = host_usage_callbacks_.Begin(); iter != host_usage_callbacks_.End(); ++iter) { iter->second.Run(iter->first, type_, GetCachedHostUsage(iter->first)); } host_usage_callbacks_.Clear(); } ",0 "void ClientUsageTracker::GatherHostUsageComplete(const std::string& host) { DCHECK(host_usage_tasks_.find(host) != host_usage_tasks_.end()); host_usage_tasks_.erase(host); host_usage_callbacks_.Run(host, host, type_, GetCachedHostUsage(host)); } ",0 " GatherHostUsageTask( UsageTracker* tracker, QuotaClient* client, const std::string& host) : GatherUsageTaskBase(tracker, client), client_(client), host_(host), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { DCHECK(client_); } ",0 "int64 ClientUsageTracker::GetCachedGlobalUnlimitedUsage() { if (!global_unlimited_usage_is_valid_) { global_unlimited_usage_ = 0; for (HostUsageMap::const_iterator host_iter = cached_usage_.begin(); host_iter != cached_usage_.end(); host_iter++) { const UsageMap& origin_map = host_iter->second; for (UsageMap::const_iterator origin_iter = origin_map.begin(); origin_iter != origin_map.end(); origin_iter++) { if (IsStorageUnlimited(origin_iter->first)) global_unlimited_usage_ += origin_iter->second; } } global_unlimited_usage_is_valid_ = true; } return global_unlimited_usage_; } ",0 " void UsageTracker::GetCachedOrigins(std::set* origins) const { DCHECK(origins); origins->clear(); for (ClientTrackerMap::const_iterator iter = client_tracker_map_.begin(); iter != client_tracker_map_.end(); ++iter) { iter->second->GetCachedOrigins(origins); } } ",0 " void ClientUsageTracker::GetCachedOrigins(std::set* origins) const { DCHECK(origins); for (HostUsageMap::const_iterator host_iter = cached_usage_.begin(); host_iter != cached_usage_.end(); host_iter++) { const UsageMap& origin_map = host_iter->second; for (UsageMap::const_iterator origin_iter = origin_map.begin(); origin_iter != origin_map.end(); origin_iter++) { origins->insert(origin_iter->first); } } } ",0 "ClientUsageTracker* UsageTracker::GetClientTracker(QuotaClient::ID client_id) { ClientTrackerMap::iterator found = client_tracker_map_.find(client_id); if (found != client_tracker_map_.end()) return found->second; return NULL; } ",0 "void UsageTracker::GetGlobalUsage(GlobalUsageCallback* callback) { if (client_tracker_map_.size() == 0) { callback->Run(type_, 0, 0); delete callback; return; } if (global_usage_callbacks_.Add(callback)) { global_usage_.pending_clients = client_tracker_map_.size(); global_usage_.usage = 0; global_usage_.unlimited_usage = 0; for (ClientTrackerMap::iterator iter = client_tracker_map_.begin(); iter != client_tracker_map_.end(); ++iter) { iter->second->GetGlobalUsage(callback_factory_.NewCallback( &UsageTracker::DidGetClientGlobalUsage)); } } } ",0 "void ClientUsageTracker::GetGlobalUsage(GlobalUsageCallback* callback) { if (global_usage_retrieved_) { callback->Run(type_, global_usage_, GetCachedGlobalUnlimitedUsage()); delete callback; return; } DCHECK(!global_usage_callback_.HasCallbacks()); global_usage_callback_.Add(callback); global_usage_task_ = new GatherGlobalUsageTask(tracker_, client_); global_usage_task_->Start(); } ",0 "void UsageTracker::GetHostUsage( const std::string& host, HostUsageCallback* callback) { if (client_tracker_map_.size() == 0) { callback->Run(host, type_, 0); delete callback; return; } if (host_usage_callbacks_.Add(host, callback)) { DCHECK(outstanding_host_usage_.find(host) == outstanding_host_usage_.end()); outstanding_host_usage_[host].pending_clients = client_tracker_map_.size(); for (ClientTrackerMap::iterator iter = client_tracker_map_.begin(); iter != client_tracker_map_.end(); ++iter) { iter->second->GetHostUsage(host, callback_factory_.NewCallback( &UsageTracker::DidGetClientHostUsage)); } } } ",0 " void GetUsageForOrigins(const std::set& origins, StorageType type) { DCHECK(original_message_loop()->BelongsToCurrentThread()); std::vector origins_to_gather; std::set cached_origins; client_tracker()->GetCachedOrigins(&cached_origins); std::set already_added; for (std::set::const_iterator iter = origins.begin(); iter != origins.end(); ++iter) { if (cached_origins.find(*iter) == cached_origins.end() && already_added.insert(*iter).second) { origins_to_gather.push_back(*iter); } } if (origins_to_gather.empty()) { CallCompleted(); DeleteSoon(); return; } std::sort(origins_to_gather.begin(), origins_to_gather.end(), SortByHost); for (std::vector::const_iterator iter = origins_to_gather.begin(); iter != origins_to_gather.end(); iter++) pending_origins_.push_back(*iter); for (std::vector::const_iterator iter = origins_to_gather.begin(); iter != origins_to_gather.end(); iter++) client_->GetOriginUsage( *iter, tracker_->type(), callback_factory_.NewCallback(&GatherUsageTaskBase::DidGetUsage)); } ",0 "bool ClientUsageTracker::IsStorageUnlimited(const GURL& origin) const { return special_storage_policy_.get() && special_storage_policy_->IsStorageUnlimited(origin); } ",0 "void ClientUsageTracker::NoopHostUsageCallback( const std::string& host, StorageType type, int64 usage) { } ",0 "void ClientUsageTracker::OnSpecialStoragePolicyChanged() { DCHECK(CalledOnValidThread()); global_unlimited_usage_is_valid_ = false; } ",0 "bool SortByHost(const GURL& lhs, const GURL& rhs) { return net::GetHostOrSpecFromURL(lhs) > net::GetHostOrSpecFromURL(rhs); } ",0 "void UsageTracker::UpdateUsageCache( QuotaClient::ID client_id, const GURL& origin, int64 delta) { ClientUsageTracker* client_tracker = GetClientTracker(client_id); DCHECK(client_tracker); client_tracker->UpdateUsageCache(origin, delta); } ",0 "void ClientUsageTracker::UpdateUsageCache( const GURL& origin, int64 delta) { std::string host = net::GetHostOrSpecFromURL(origin); if (cached_hosts_.find(host) != cached_hosts_.end()) { cached_usage_[host][origin] += delta; global_usage_ += delta; if (global_unlimited_usage_is_valid_ && IsStorageUnlimited(origin)) global_unlimited_usage_ += delta; DCHECK_GE(cached_usage_[host][origin], 0); DCHECK_GE(global_usage_, 0); return; } GetHostUsage(host, NewCallback(this, &ClientUsageTracker::NoopHostUsageCallback)); } ",0 "UsageTracker::UsageTracker(const QuotaClientList& clients, StorageType type, SpecialStoragePolicy* special_storage_policy) : type_(type), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { for (QuotaClientList::const_iterator iter = clients.begin(); iter != clients.end(); ++iter) { client_tracker_map_.insert(std::make_pair( (*iter)->id(), new ClientUsageTracker(this, *iter, type, special_storage_policy))); } } ",0 " ClientUsageTracker* client_tracker() const { return client_tracker_; } ",0 " UsageTracker* tracker() const { return tracker_; } ",0 "ClientUsageTracker::~ClientUsageTracker() { if (special_storage_policy_) special_storage_policy_->RemoveObserver(this); } ",0 " virtual ~GatherGlobalUsageTask() {} ",0 " virtual ~GatherHostUsageTask() {} ",0 " virtual ~GatherUsageTaskBase() {} ",0 "UsageTracker::~UsageTracker() { STLDeleteValues(&client_tracker_map_); } ",0 "void AddChromeFrameWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, const Product& product, WorkItemList* list) { DCHECK(product.is_chrome_frame()); if (!installer_state.is_multi_install()) { VLOG(1) << ""Not adding GCF specific work items for single install.""; return; } std::wstring version_key(product.distribution()->GetVersionKey()); bool ready_mode = product.HasOption(kOptionReadyMode); HKEY root = installer_state.root_key(); const bool is_install = (installer_state.operation() != InstallerState::UNINSTALL); bool update_chrome_uninstall_command = false; BrowserDistribution* dist = installer_state.multi_package_binaries_distribution(); if (ready_mode) { list->AddCreateRegKeyWorkItem(root, dist->GetStateKey()); list->AddSetRegValueWorkItem(root, dist->GetStateKey(), kChromeFrameReadyModeField, static_cast(is_install ? 1 : 0), // The value we want to set. is_install ? false : true); // Overwrite existing value. if (is_install) { FilePath installer_path(installer_state .GetInstallerDirectory(new_version).Append(setup_path.BaseName())); CommandLine basic_cl(installer_path); basic_cl.AppendSwitch(switches::kChromeFrame); basic_cl.AppendSwitch(switches::kMultiInstall); if (installer_state.system_install()) basic_cl.AppendSwitch(switches::kSystemLevel); CommandLine temp_opt_out(basic_cl); temp_opt_out.AppendSwitch(switches::kChromeFrameReadyModeTempOptOut); CommandLine end_temp_opt_out(basic_cl); end_temp_opt_out.AppendSwitch( switches::kChromeFrameReadyModeEndTempOptOut); CommandLine opt_out(installer_path); AppendUninstallCommandLineFlags(installer_state, product, &opt_out); opt_out.AppendSwitch(switches::kForceUninstall); CommandLine opt_in(basic_cl); opt_in.AppendSwitch(switches::kChromeFrameReadyModeOptIn); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFTempOptOutCmdField, temp_opt_out.command_line_string(), true); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFEndTempOptOutCmdField, end_temp_opt_out.command_line_string(), true); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFOptOutCmdField, opt_out.command_line_string(), true); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFOptInCmdField, opt_in.command_line_string(), true); } else { update_chrome_uninstall_command = (installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER) == NULL); } } else { list->AddDeleteRegValueWorkItem(root, dist->GetStateKey(), kChromeFrameReadyModeField); const Product* chrome = installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER); if (chrome) { } else { const ProductState* chrome_state = original_state.GetProductState( installer_state.system_install(), BrowserDistribution::CHROME_BROWSER); update_chrome_uninstall_command = (chrome_state != NULL) && chrome_state->is_multi_install(); } } if (!ready_mode || !is_install) { list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFTempOptOutCmdField); list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFEndTempOptOutCmdField); list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFOptOutCmdField); list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFOptInCmdField); } if (update_chrome_uninstall_command) { const ProductState* chrome_state = original_state.GetProductState( installer_state.system_install(), BrowserDistribution::CHROME_BROWSER); if (chrome_state != NULL) { DCHECK(chrome_state->is_multi_install()); Product chrome(BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BROWSER)); chrome.InitializeFromUninstallCommand(chrome_state->uninstall_command()); AddUninstallShortcutWorkItems(installer_state, setup_path, chrome_state->version(), list, chrome); } else { NOTREACHED() << ""What happened to Chrome?""; } } } ",0 "void AddElevationPolicyWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const Version& new_version, WorkItemList* install_list) { if (!installer_state.is_multi_install()) { VLOG(1) << ""Not adding elevation policy for single installs""; return; } else { const ProductState* cf_state = original_state.GetProductState(installer_state.system_install(), BrowserDistribution::CHROME_FRAME); if (cf_state && !cf_state->is_multi_install()) { LOG(WARNING) << ""Not adding elevation policy since a single install "" ""of CF exists""; return; } } FilePath binary_dir( GetChromeInstallPath(installer_state.system_install(), BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES))); struct { const wchar_t* sub_key; const wchar_t* executable; const FilePath exe_dir; } low_rights_entries[] = { { L""ElevationPolicy\\"", kChromeLauncherExe, binary_dir.Append(ASCIIToWide(new_version.GetString())) }, { L""DragDrop\\"", chrome::kBrowserProcessExecutableName, binary_dir }, }; bool uninstall = (installer_state.operation() == InstallerState::UNINSTALL); HKEY root = installer_state.root_key(); const wchar_t kLowRightsKeyPath[] = L""SOFTWARE\\Microsoft\\Internet Explorer\\Low Rights\\""; std::wstring key_path(kLowRightsKeyPath); wchar_t cf_classid[64] = {0}; StringFromGUID2(__uuidof(ChromeFrame), cf_classid, arraysize(cf_classid)); for (size_t i = 0; i < arraysize(low_rights_entries); ++i) { key_path.append(low_rights_entries[i].sub_key).append(cf_classid); if (uninstall) { install_list->AddDeleteRegKeyWorkItem(root, key_path); } else { install_list->AddCreateRegKeyWorkItem(root, key_path); install_list->AddSetRegValueWorkItem(root, key_path, L""Policy"", static_cast(3), true); install_list->AddSetRegValueWorkItem(root, key_path, L""AppName"", low_rights_entries[i].executable, true); install_list->AddSetRegValueWorkItem(root, key_path, L""AppPath"", low_rights_entries[i].exe_dir.value(), true); } key_path.resize(arraysize(kLowRightsKeyPath) - 1); } } ",0 "void AddGoogleUpdateWorkItems(const InstallationState& original_state, const InstallerState& installer_state, WorkItemList* install_list) { if (installer_state.operation() != InstallerState::MULTI_INSTALL && installer_state.operation() != InstallerState::MULTI_UPDATE) { VLOG(1) << ""AddGoogleUpdateWorkItems noop: "" << installer_state.operation(); return; } if (installer_state.state_type() != BrowserDistribution::CHROME_BINARIES) { std::wstring multi_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); const ProductState* chrome_product_state = original_state.GetNonVersionedProductState( installer_state.system_install(), BrowserDistribution::CHROME_BROWSER); const std::wstring& brand(chrome_product_state->brand()); if (!brand.empty()) { install_list->AddCreateRegKeyWorkItem(installer_state.root_key(), multi_key); install_list->AddSetRegValueWorkItem(installer_state.root_key(), multi_key, google_update::kRegBrandField, brand, false); } } AddUsageStatsWorkItems(original_state, installer_state, install_list); } ",0 "void AddInstallWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const FilePath& setup_path, const FilePath& archive_path, const FilePath& src_path, const FilePath& temp_path, const Version& new_version, scoped_ptr* current_version, WorkItemList* install_list) { DCHECK(install_list); const FilePath& target_path = installer_state.target_path(); install_list->AddCreateDirWorkItem(temp_path); install_list->AddCreateDirWorkItem(target_path); if (current_version != NULL && current_version->get() != NULL) { FilePath old_installer_dir( installer_state.GetInstallerDirectory(**current_version)); FilePath old_archive(old_installer_dir.Append(archive_path.BaseName())); install_list->AddDeleteTreeWorkItem(old_archive, temp_path) ->set_ignore_failure(true); } FilePath new_chrome_exe(target_path.Append(installer::kChromeNewExe)); install_list->AddDeleteTreeWorkItem(new_chrome_exe, temp_path); install_list->AddCopyTreeWorkItem( src_path.Append(installer::kChromeExe).value(), target_path.Append(installer::kChromeExe).value(), temp_path.value(), WorkItem::NEW_NAME_IF_IN_USE, new_chrome_exe.value()); if (base::win::OSInfo::GetInstance()->wow64_status() != base::win::OSInfo::WOW64_DISABLED) { install_list->AddMoveTreeWorkItem( src_path.Append(installer::kWowHelperExe).value(), target_path.Append(installer::kWowHelperExe).value(), temp_path.value(), WorkItem::ALWAYS_MOVE); } bool check_for_duplicates = (current_version != NULL && current_version->get() != NULL && current_version->get()->Equals(new_version)); install_list->AddMoveTreeWorkItem( src_path.AppendASCII(new_version.GetString()).value(), target_path.AppendASCII(new_version.GetString()).value(), temp_path.value(), check_for_duplicates ? WorkItem::CHECK_DUPLICATES : WorkItem::ALWAYS_MOVE); install_list->AddCopyTreeWorkItem( src_path.Append(installer::kDictionaries).value(), target_path.Append(installer::kDictionaries).value(), temp_path.value(), WorkItem::IF_NOT_PRESENT); install_list->AddDeleteTreeWorkItem( target_path.Append(installer::kChromeOldExe), temp_path); AddInstallerCopyTasks(installer_state, setup_path, archive_path, temp_path, new_version, install_list); const HKEY root = installer_state.root_key(); const Products& products = installer_state.products(); for (size_t i = 0; i < products.size(); ++i) { const Product* product = products[i]; AddUninstallShortcutWorkItems(installer_state, setup_path, new_version, install_list, *product); AddVersionKeyWorkItems(root, product->distribution(), new_version, install_list); } if (installer_state.is_multi_install()) { AddVersionKeyWorkItems(root, installer_state.multi_package_binaries_distribution(), new_version, install_list); } AddProductSpecificWorkItems(original_state, installer_state, setup_path, new_version, install_list); AddGoogleUpdateWorkItems(original_state, installer_state, install_list); AddQuickEnableWorkItems(installer_state, original_state, &setup_path, &new_version, install_list); AppendPostInstallTasks(installer_state, setup_path, new_chrome_exe, current_version->get(), new_version, temp_path, install_list); } ",0 "void AddProductSpecificWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, WorkItemList* list) { const Products& products = installer_state.products(); for (size_t i = 0; i < products.size(); ++i) { const Product& p = *products[i]; if (p.is_chrome_frame()) { AddChromeFrameWorkItems(original_state, installer_state, setup_path, new_version, p, list); } } } ",0 "void AddRegisterComDllWorkItems(const FilePath& dll_folder, const std::vector& dll_list, bool system_level, bool do_register, bool ignore_failures, WorkItemList* work_item_list) { DCHECK(work_item_list); if (dll_list.empty()) { VLOG(1) << ""No COM DLLs to register""; } else { std::vector::const_iterator dll_iter(dll_list.begin()); for (; dll_iter != dll_list.end(); ++dll_iter) { FilePath dll_path = dll_folder.Append(*dll_iter); WorkItem* work_item = work_item_list->AddSelfRegWorkItem( dll_path.value(), do_register, !system_level); DCHECK(work_item); work_item->set_ignore_failure(ignore_failures); } } } ",0 "void AddRegisterComDllWorkItemsForPackage(const InstallerState& installer_state, const Version* old_version, const Version& new_version, WorkItemList* work_item_list) { std::vector com_dll_list; installer_state.AddComDllList(&com_dll_list); if (!com_dll_list.empty()) { if (old_version) { FilePath old_dll_path(installer_state.target_path().AppendASCII( old_version->GetString())); installer::AddRegisterComDllWorkItems(old_dll_path, com_dll_list, installer_state.system_install(), false, // Unregister true, // May fail work_item_list); } FilePath dll_path(installer_state.target_path().AppendASCII( new_version.GetString())); installer::AddRegisterComDllWorkItems(dll_path, com_dll_list, installer_state.system_install(), true, // Register false, // Must succeed. work_item_list); } } ",0 "void AddSetMsiMarkerWorkItem(const InstallerState& installer_state, BrowserDistribution* dist, bool set, WorkItemList* work_item_list) { DCHECK(work_item_list); DWORD msi_value = set ? 1 : 0; WorkItem* set_msi_work_item = work_item_list->AddSetRegValueWorkItem( installer_state.root_key(), dist->GetStateKey(), google_update::kRegMSIField, msi_value, true); DCHECK(set_msi_work_item); set_msi_work_item->set_ignore_failure(true); set_msi_work_item->set_log_message(""Could not write MSI marker!""); } ",0 "void AddUninstallShortcutWorkItems(const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, WorkItemList* install_list, const Product& product) { HKEY reg_root = installer_state.root_key(); BrowserDistribution* browser_dist = product.distribution(); DCHECK(browser_dist); FilePath install_path(installer_state.target_path()); FilePath installer_path(installer_state.GetInstallerDirectory(new_version)); installer_path = installer_path.Append(setup_path.BaseName()); CommandLine uninstall_arguments(CommandLine::NO_PROGRAM); AppendUninstallCommandLineFlags(installer_state, product, &uninstall_arguments); if (product.is_chrome() && installer_state.operation() != InstallerState::UNINSTALL) { const Products& products = installer_state.products(); for (size_t i = 0; i < products.size(); ++i) { const Product& p = *products[i]; if (!p.is_chrome() && !p.ShouldCreateUninstallEntry()) p.AppendUninstallFlags(&uninstall_arguments); } } std::wstring update_state_key(browser_dist->GetStateKey()); install_list->AddCreateRegKeyWorkItem(reg_root, update_state_key); install_list->AddSetRegValueWorkItem(reg_root, update_state_key, installer::kUninstallStringField, installer_path.value(), true); install_list->AddSetRegValueWorkItem(reg_root, update_state_key, installer::kUninstallArgumentsField, uninstall_arguments.command_line_string(), true); if (!installer_state.is_msi() && product.ShouldCreateUninstallEntry()) { CommandLine quoted_uninstall_cmd(installer_path); DCHECK_EQ(quoted_uninstall_cmd.command_line_string()[0], '""'); quoted_uninstall_cmd.AppendArguments(uninstall_arguments, false); std::wstring uninstall_reg = browser_dist->GetUninstallRegPath(); install_list->AddCreateRegKeyWorkItem(reg_root, uninstall_reg); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, installer::kUninstallDisplayNameField, browser_dist->GetAppShortCutName(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, installer::kUninstallStringField, quoted_uninstall_cmd.command_line_string(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""InstallLocation"", install_path.value(), true); FilePath chrome_icon(install_path.Append(installer::kChromeExe)); ShellUtil::GetChromeIcon(product.distribution(), chrome_icon.value()); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""DisplayIcon"", chrome_icon.value(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""NoModify"", static_cast(1), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""NoRepair"", static_cast(1), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""Publisher"", browser_dist->GetPublisherName(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""Version"", UTF8ToWide(new_version.GetString()), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""DisplayVersion"", UTF8ToWide(new_version.GetString()), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L""InstallDate"", InstallUtil::GetCurrentDate(), false); } } ",0 "void AddUsageStatsWorkItems(const InstallationState& original_state, const InstallerState& installer_state, WorkItemList* install_list) { DCHECK(installer_state.operation() == InstallerState::MULTI_INSTALL || installer_state.operation() == InstallerState::MULTI_UPDATE); HKEY root_key = installer_state.root_key(); bool value_found = false; DWORD usagestats = 0; const Products& products = installer_state.products(); for (Products::const_iterator scan = products.begin(), end = products.end(); !value_found && scan != end; ++scan) { BrowserDistribution* dist = (*scan)->distribution(); const ProductState* product_state = original_state.GetNonVersionedProductState( installer_state.system_install(), dist->GetType()); value_found = product_state->GetUsageStats(&usagestats); } if (value_found) { std::wstring state_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); install_list->AddCreateRegKeyWorkItem(root_key, state_key); install_list->AddSetRegValueWorkItem(root_key, state_key, google_update::kRegUsageStatsField, usagestats, false); for (Products::const_iterator scan = products.begin(), end = products.end(); scan != end; ++scan) { BrowserDistribution* dist = (*scan)->distribution(); if (installer_state.system_install()) { install_list->AddDeleteRegValueWorkItem( root_key, dist->GetStateMediumKey(), google_update::kRegUsageStatsField); install_list->AddDeleteRegValueWorkItem( HKEY_CURRENT_USER, dist->GetStateKey(), google_update::kRegUsageStatsField); } install_list->AddDeleteRegValueWorkItem(root_key, dist->GetStateKey(), google_update::kRegUsageStatsField); } } } ",0 "void AddVersionKeyWorkItems(HKEY root, BrowserDistribution* dist, const Version& new_version, WorkItemList* list) { std::wstring version_key(dist->GetVersionKey()); list->AddCreateRegKeyWorkItem(root, version_key); std::wstring product_name(dist->GetAppShortCutName()); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegNameField, product_name, true); // overwrite name also list->AddSetRegValueWorkItem(root, version_key, google_update::kRegOopcrashesField, static_cast(1), false); // set during first install list->AddSetRegValueWorkItem(root, version_key, google_update::kRegVersionField, UTF8ToWide(new_version.GetString()), true); // overwrite version } ",0 "bool AppendPostInstallTasks(const InstallerState& installer_state, const FilePath& setup_path, const FilePath& new_chrome_exe, const Version* current_version, const Version& new_version, const FilePath& temp_path, WorkItemList* post_install_task_list) { DCHECK(post_install_task_list); HKEY root = installer_state.root_key(); const Products& products = installer_state.products(); { scoped_ptr in_use_update_work_items( WorkItem::CreateConditionalWorkItemList( new ConditionRunIfFileExists(new_chrome_exe))); in_use_update_work_items->set_log_message(""InUseUpdateWorkItemList""); FilePath installer_path(installer_state.GetInstallerDirectory(new_version) .Append(setup_path.BaseName())); CommandLine rename(installer_path); rename.AppendSwitch(switches::kRenameChromeExe); if (installer_state.system_install()) rename.AppendSwitch(switches::kSystemLevel); if (installer_state.verbose_logging()) rename.AppendSwitch(switches::kVerboseLogging); std::wstring version_key; for (size_t i = 0; i < products.size(); ++i) { BrowserDistribution* dist = products[i]->distribution(); version_key = dist->GetVersionKey(); if (current_version != NULL) { in_use_update_work_items->AddSetRegValueWorkItem(root, version_key, google_update::kRegOldVersionField, UTF8ToWide(current_version->GetString()), true); } CommandLine product_rename_cmd(rename); products[i]->AppendRenameFlags(&product_rename_cmd); in_use_update_work_items->AddSetRegValueWorkItem( root, version_key, google_update::kRegRenameCmdField, product_rename_cmd.command_line_string(), true); } if (current_version != NULL && installer_state.is_multi_install()) { BrowserDistribution* dist = installer_state.multi_package_binaries_distribution(); in_use_update_work_items->AddSetRegValueWorkItem( root, dist->GetVersionKey(), google_update::kRegOldVersionField, UTF8ToWide(current_version->GetString()), true); } post_install_task_list->AddWorkItem(in_use_update_work_items.release()); } { scoped_ptr regular_update_work_items( WorkItem::CreateConditionalWorkItemList( new Not(new ConditionRunIfFileExists(new_chrome_exe)))); regular_update_work_items->set_log_message(""RegularUpdateWorkItemList""); for (size_t i = 0; i < products.size(); ++i) { BrowserDistribution* dist = products[i]->distribution(); std::wstring version_key(dist->GetVersionKey()); regular_update_work_items->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegOldVersionField); regular_update_work_items->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegRenameCmdField); } post_install_task_list->AddWorkItem(regular_update_work_items.release()); } AddRegisterComDllWorkItemsForPackage(installer_state, current_version, new_version, post_install_task_list); if (installer_state.is_msi()) { for (size_t i = 0; i < products.size(); ++i) { const Product* product = products[i]; AddSetMsiMarkerWorkItem(installer_state, product->distribution(), true, post_install_task_list); AddDeleteUninstallShortcutsForMSIWorkItems(installer_state, *product, temp_path, post_install_task_list); } if (installer_state.is_multi_install()) { AddSetMsiMarkerWorkItem(installer_state, installer_state.multi_package_binaries_distribution(), true, post_install_task_list); } } return true; } ",0 "void AppendUninstallCommandLineFlags(const InstallerState& installer_state, const Product& product, CommandLine* uninstall_cmd) { DCHECK(uninstall_cmd); uninstall_cmd->AppendSwitch(installer::switches::kUninstall); product.AppendUninstallFlags(uninstall_cmd); if (installer_state.is_msi()) { uninstall_cmd->AppendSwitch(installer::switches::kMsi); if (product.is_chrome_frame()) { uninstall_cmd->AppendSwitch(installer::switches::kDeleteProfile); } } if (installer_state.system_install()) uninstall_cmd->AppendSwitch(installer::switches::kSystemLevel); if (installer_state.verbose_logging()) uninstall_cmd->AppendSwitch(installer::switches::kVerboseLogging); } ",0 "void RefreshElevationPolicy() { const wchar_t kIEFrameDll[] = L""ieframe.dll""; const char kIERefreshPolicy[] = ""IERefreshElevationPolicy""; HMODULE ieframe = LoadLibrary(kIEFrameDll); if (ieframe) { typedef HRESULT (__stdcall *IERefreshPolicy)(); IERefreshPolicy ie_refresh_policy = reinterpret_cast( GetProcAddress(ieframe, kIERefreshPolicy)); if (ie_refresh_policy) { ie_refresh_policy(); } else { VLOG(1) << kIERefreshPolicy << "" not supported.""; } FreeLibrary(ieframe); } else { VLOG(1) << ""Cannot load "" << kIEFrameDll; } } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { CFType type; if (!decoder->decodeEnum(type)) return false; switch (type) { case CFArray: { RetainPtr array; if (!decode(decoder, array)) return false; result.adoptCF(array.leakRef()); return true; } case CFBoolean: { RetainPtr boolean; if (!decode(decoder, boolean)) return false; result.adoptCF(boolean.leakRef()); return true; } case CFData: { RetainPtr data; if (!decode(decoder, data)) return false; result.adoptCF(data.leakRef()); return true; } case CFDate: { RetainPtr date; if (!decode(decoder, date)) return false; result.adoptCF(date.leakRef()); return true; } case CFDictionary: { RetainPtr dictionary; if (!decode(decoder, dictionary)) return false; result.adoptCF(dictionary.leakRef()); return true; } case CFNull: result.adoptCF(kCFNull); return true; case CFNumber: { RetainPtr number; if (!decode(decoder, number)) return false; result.adoptCF(number.leakRef()); return true; } case CFString: { RetainPtr string; if (!decode(decoder, string)) return false; result.adoptCF(string.leakRef()); return true; } case CFURL: { RetainPtr url; if (!decode(decoder, url)) return false; result.adoptCF(url.leakRef()); return true; } #if PLATFORM(MAC) case SecCertificate: { RetainPtr certificate; if (!decode(decoder, certificate)) return false; result.adoptCF(certificate.leakRef()); return true; } case SecKeychainItem: { RetainPtr keychainItem; if (!decode(decoder, keychainItem)) return false; result.adoptCF(keychainItem.leakRef()); return true; } #endif case Null: result = tokenNullTypeRef(); return true; case Unknown: ASSERT_NOT_REACHED(); return false; } return false; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { uint64_t size; if (!decoder->decodeUInt64(size)) return false; RetainPtr array(AdoptCF, CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks)); for (size_t i = 0; i < size; ++i) { RetainPtr element; if (!decode(decoder, element)) return false; CFArrayAppendValue(array.get(), element.get()); } result.adoptCF(array.leakRef()); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { bool boolean; if (!decoder->decode(boolean)) return false; result.adoptCF(boolean ? kCFBooleanTrue : kCFBooleanFalse); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { CoreIPC::DataReference dataReference; if (!decoder->decode(dataReference)) return false; result.adoptCF(CFDataCreate(0, dataReference.data(), dataReference.size())); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { double absoluteTime; if (!decoder->decodeDouble(absoluteTime)) return false; result.adoptCF(CFDateCreate(0, absoluteTime)); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { CFNumberType numberType; if (!decoder->decodeEnum(numberType)) return false; CoreIPC::DataReference dataReference; if (!decoder->decode(dataReference)) return false; size_t neededBufferSize = sizeForNumberType(numberType); if (!neededBufferSize || dataReference.size() != neededBufferSize) return false; ASSERT(dataReference.data()); CFNumberRef number = CFNumberCreate(0, numberType, dataReference.data()); result.adoptCF(number); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { CFStringEncoding encoding; if (!decoder->decodeEnum(encoding)) return false; if (!CFStringIsEncodingAvailable(encoding)) return false; CoreIPC::DataReference dataReference; if (!decoder->decode(dataReference)) return false; CFStringRef string = CFStringCreateWithBytes(0, dataReference.data(), dataReference.size(), encoding, false); if (!string) return false; result.adoptCF(string); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { RetainPtr data; if (!decode(decoder, data)) return false; result.adoptCF(SecCertificateCreateWithData(0, data.get())); return true; } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { RetainPtr data; if (!CoreIPC::decode(decoder, data)) return false; SecKeychainItemRef item; if (SecKeychainItemCopyFromPersistentReference(data.get(), &item) != errSecSuccess || !item) return false; result.adoptCF(item); return true; } ",0 "void encode(ArgumentEncoder* encoder, CFTypeRef typeRef) { CFType type = typeFromCFTypeRef(typeRef); encoder->encodeEnum(type); switch (type) { case CFArray: encode(encoder, static_cast(typeRef)); return; case CFBoolean: encode(encoder, static_cast(typeRef)); return; case CFData: encode(encoder, static_cast(typeRef)); return; case CFDate: encode(encoder, static_cast(typeRef)); return; case CFDictionary: encode(encoder, static_cast(typeRef)); return; case CFNull: return; case CFNumber: encode(encoder, static_cast(typeRef)); return; case CFString: encode(encoder, static_cast(typeRef)); return; case CFURL: encode(encoder, static_cast(typeRef)); return; #if PLATFORM(MAC) case SecCertificate: encode(encoder, (SecCertificateRef)typeRef); return; case SecKeychainItem: encode(encoder, (SecKeychainItemRef)typeRef); return; #endif case Null: return; case Unknown: break; } ASSERT_NOT_REACHED(); } ",0 "void encode(ArgumentEncoder* encoder, CFArrayRef array) { CFIndex size = CFArrayGetCount(array); Vector values(size); CFArrayGetValues(array, CFRangeMake(0, size), values.data()); encoder->encodeUInt64(size); for (CFIndex i = 0; i < size; ++i) { ASSERT(values[i]); encode(encoder, values[i]); } } ",0 "void encode(ArgumentEncoder* encoder, CFBooleanRef boolean) { encoder->encodeBool(CFBooleanGetValue(boolean)); } ",0 "void encode(ArgumentEncoder* encoder, CFDataRef data) { CFIndex length = CFDataGetLength(data); const UInt8* bytePtr = CFDataGetBytePtr(data); encoder->encodeVariableLengthByteArray(CoreIPC::DataReference(bytePtr, length)); } ",0 "void encode(ArgumentEncoder* encoder, CFDateRef date) { encoder->encodeDouble(CFDateGetAbsoluteTime(date)); } ",0 "void encode(ArgumentEncoder* encoder, CFDictionaryRef dictionary) { CFIndex size = CFDictionaryGetCount(dictionary); Vector keys(size); Vector values(size); CFDictionaryGetKeysAndValues(dictionary, keys.data(), values.data()); encoder->encodeUInt64(size); for (CFIndex i = 0; i < size; ++i) { ASSERT(keys[i]); ASSERT(CFGetTypeID(keys[i]) == CFStringGetTypeID()); ASSERT(values[i]); if (typeFromCFTypeRef(values[i]) == Unknown) continue; encode(encoder, static_cast(keys[i])); encode(encoder, values[i]); } } ",0 "void encode(ArgumentEncoder* encoder, CFNumberRef number) { CFNumberType numberType = CFNumberGetType(number); Vector buffer(CFNumberGetByteSize(number)); bool result = CFNumberGetValue(number, numberType, buffer.data()); ASSERT_UNUSED(result, result); encoder->encodeEnum(numberType); encoder->encodeVariableLengthByteArray(buffer); } ",0 "void encode(ArgumentEncoder* encoder, CFURLRef url) { CFURLRef baseURL = CFURLGetBaseURL(url); encoder->encodeBool(baseURL); if (baseURL) encode(encoder, baseURL); encode(encoder, CFURLGetString(url)); } ",0 "void encode(ArgumentEncoder* encoder, SecCertificateRef certificate) { RetainPtr data(AdoptCF, SecCertificateCopyData(certificate)); encode(encoder, data.get()); } ",0 "void encode(ArgumentEncoder* encoder, SecKeychainItemRef keychainItem) { CFDataRef data; if (SecKeychainItemCreatePersistentReference(keychainItem, &data) == errSecSuccess) { encode(encoder, data); CFRelease(data); } } ",0 "static size_t sizeForNumberType(CFNumberType numberType) { switch (numberType) { case kCFNumberSInt8Type: return sizeof(SInt8); case kCFNumberSInt16Type: return sizeof(SInt16); case kCFNumberSInt32Type: return sizeof(SInt32); case kCFNumberSInt64Type: return sizeof(SInt64); case kCFNumberFloat32Type: return sizeof(Float32); case kCFNumberFloat64Type: return sizeof(Float64); case kCFNumberCharType: return sizeof(char); case kCFNumberShortType: return sizeof(short); case kCFNumberIntType: return sizeof(int); case kCFNumberLongType: return sizeof(long); case kCFNumberLongLongType: return sizeof(long long); case kCFNumberFloatType: return sizeof(float); case kCFNumberDoubleType: return sizeof(double); case kCFNumberCFIndexType: return sizeof(CFIndex); case kCFNumberNSIntegerType: #ifdef __LP64__ return sizeof(long); #else return sizeof(int); #endif case kCFNumberCGFloatType: #ifdef __LP64__ return sizeof(double); #else return sizeof(float); #endif } return 0; } ",0 " CFTypeRef tokenNullTypeRef() { static CFStringRef tokenNullType = CFSTR(""WKNull""); return tokenNullType; } ",0 "static CFType typeFromCFTypeRef(CFTypeRef type) { ASSERT(type); if (type == tokenNullTypeRef()) return Null; CFTypeID typeID = CFGetTypeID(type); if (typeID == CFArrayGetTypeID()) return CFArray; if (typeID == CFBooleanGetTypeID()) return CFBoolean; if (typeID == CFDataGetTypeID()) return CFData; if (typeID == CFDateGetTypeID()) return CFDate; if (typeID == CFDictionaryGetTypeID()) return CFDictionary; if (typeID == CFNullGetTypeID()) return CFNull; if (typeID == CFNumberGetTypeID()) return CFNumber; if (typeID == CFStringGetTypeID()) return CFString; if (typeID == CFURLGetTypeID()) return CFURL; #if PLATFORM(MAC) if (typeID == SecCertificateGetTypeID()) return SecCertificate; if (typeID == SecKeychainItemGetTypeID()) return SecKeychainItem; #endif ASSERT_NOT_REACHED(); return Unknown; } ",0 "WebProcessProxy::WebProcessProxy(PassRefPtr context) : ChildProcessProxy(this) , m_responsivenessTimer(this) , m_context(context) , m_mayHaveUniversalFileReadSandboxExtension(false) #if ENABLE(CUSTOM_PROTOCOLS) , m_customProtocolManagerProxy(this) #endif #if PLATFORM(MAC) , m_processSuppressionEnabled(false) #endif { connect(); } ",0 "void WebProcessProxy::addBackForwardItem(uint64_t itemID, const String& originalURL, const String& url, const String& title, const CoreIPC::DataReference& backForwardData) { MESSAGE_CHECK_URL(originalURL); MESSAGE_CHECK_URL(url); WebBackForwardListItemMap::AddResult result = m_backForwardListItemMap.add(itemID, 0); if (result.isNewEntry) { result.iterator->value = WebBackForwardListItem::create(originalURL, url, title, backForwardData.data(), backForwardData.size(), itemID); return; } result.iterator->value->setOriginalURL(originalURL); result.iterator->value->setURL(url); result.iterator->value->setTitle(title); result.iterator->value->setBackForwardData(backForwardData.data(), backForwardData.size()); } ",0 "void WebProcessProxy::addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver* messageReceiver) { m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver); } ",0 "void WebProcessProxy::addMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID, CoreIPC::MessageReceiver* messageReceiver) { m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver); } ",0 "void WebProcessProxy::assumeReadAccessToBaseURL(const String& urlString) { KURL url(KURL(), urlString); if (!url.isLocalFile()) return; KURL baseURL(KURL(), url.baseAsString()); m_localPathsWithAssumedReadAccess.add(baseURL.fileSystemPath()); } ",0 "bool WebProcessProxy::checkURLReceivedFromWebProcess(const String& urlString) { return checkURLReceivedFromWebProcess(KURL(KURL(), urlString)); } ",0 "bool WebProcessProxy::checkURLReceivedFromWebProcess(const KURL& url) { if (!url.isLocalFile()) return true; if (m_mayHaveUniversalFileReadSandboxExtension) return true; String path = url.fileSystemPath(); for (HashSet::const_iterator iter = m_localPathsWithAssumedReadAccess.begin(); iter != m_localPathsWithAssumedReadAccess.end(); ++iter) { if (path.startsWith(*iter)) return true; } for (WebBackForwardListItemMap::iterator iter = m_backForwardListItemMap.begin(), end = m_backForwardListItemMap.end(); iter != end; ++iter) { if (KURL(KURL(), iter->value->url()).fileSystemPath() == path) return true; if (KURL(KURL(), iter->value->originalURL()).fileSystemPath() == path) return true; } WTFLogAlways(""Received an unexpected URL from the web process: '%s'\n"", url.string().utf8().data()); return false; } ",0 "PassRefPtr WebProcessProxy::create(PassRefPtr context) { return adoptRef(new WebProcessProxy(context)); } ",0 "DownloadProxy* WebProcessProxy::createDownloadProxy() { #if ENABLE(NETWORK_PROCESS) ASSERT(!m_context->usesNetworkProcess()); #endif if (!m_downloadProxyMap) m_downloadProxyMap = adoptPtr(new DownloadProxyMap(m_messageReceiverMap)); return m_downloadProxyMap->createDownloadProxy(m_context.get()); } ",0 "PassRefPtr WebProcessProxy::createWebPage(PageClient* pageClient, WebContext*, WebPageGroup* pageGroup) { uint64_t pageID = generatePageID(); RefPtr webPage = WebPageProxy::create(pageClient, this, pageGroup, pageID); m_pageMap.set(pageID, webPage.get()); globalPageMap().set(pageID, webPage.get()); #if PLATFORM(MAC) if (pageIsProcessSuppressible(webPage.get())) m_processSuppressiblePages.add(pageID); updateProcessSuppressionState(); #endif return webPage.release(); } ",0 "void WebProcessProxy::didBecomeUnresponsive(ResponsivenessTimer*) { Vector > pages; copyValuesToVector(m_pageMap, pages); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->processDidBecomeUnresponsive(); } ",0 "void WebProcessProxy::didClearPluginSiteData(uint64_t callbackID) { m_context->pluginSiteDataManager()->didClearSiteData(callbackID); } ",0 "void WebProcessProxy::didClose(CoreIPC::Connection*) { RefPtr protect(this); webConnection()->didClose(); Vector > pages; copyValuesToVector(m_pageMap, pages); disconnect(); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->processDidCrash(); } ",0 "void WebProcessProxy::didDestroyFrame(uint64_t frameID) { ASSERT(isGoodKey(frameID)); m_frameMap.remove(frameID); } ",0 "void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC::Connection::Identifier connectionIdentifier) { ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier); #if USE(SECURITY_FRAMEWORK) connection()->addQueueClient(&SecItemShimProxy::shared()); #endif m_webConnection = WebConnectionToWebProcess::create(this); m_context->processDidFinishLaunching(this); #if PLATFORM(MAC) updateProcessSuppressionState(); #endif } ",0 "void WebProcessProxy::didGetSitesWithPluginData(const Vector& sites, uint64_t callbackID) { m_context->pluginSiteDataManager()->didGetSitesWithData(sites, callbackID); } ",0 "void WebProcessProxy::didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore& store, uint64_t frameID) { WebPageProxy* page = webPage(pageID); if (!page) return; WebFrameProxy* frame = webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK(frame->page() == page); m_context->historyClient().didNavigateWithNavigationData(m_context.get(), page, store, frame); } ",0 "void WebProcessProxy::didPerformServerRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID) { WebPageProxy* page = webPage(pageID); if (!page) return; if (sourceURLString.isEmpty() || destinationURLString.isEmpty()) return; WebFrameProxy* frame = webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK(frame->page() == page); MESSAGE_CHECK_URL(sourceURLString); MESSAGE_CHECK_URL(destinationURLString); m_context->historyClient().didPerformServerRedirect(m_context.get(), page, sourceURLString, destinationURLString, frame); } ",0 "void WebProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection* connection, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) { WTFLogAlways(""Received an invalid message \""%s.%s\"" from the web process.\n"", messageReceiverName.toString().data(), messageName.toString().data()); terminate(); didClose(connection); } ",0 "void WebProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) { if (m_messageReceiverMap.dispatchMessage(connection, messageID, decoder)) return; if (m_context->dispatchMessage(connection, messageID, decoder)) return; if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) { didReceiveWebProcessProxyMessage(connection, messageID, decoder); return; } #if ENABLE(CUSTOM_PROTOCOLS) if (decoder.messageReceiverName() == Messages::CustomProtocolManagerProxy::messageReceiverName()) { #if ENABLE(NETWORK_PROCESS) ASSERT(!context()->usesNetworkProcess()); #endif m_customProtocolManagerProxy.didReceiveMessage(connection, messageID, decoder); return; } #endif uint64_t pageID = decoder.destinationID(); if (!pageID) return; WebPageProxy* pageProxy = webPage(pageID); if (!pageProxy) return; pageProxy->didReceiveMessage(connection, messageID, decoder); } ",0 "void WebProcessProxy::didReceiveMessageOnConnectionWorkQueue(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, bool& didHandleMessage) { if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) didReceiveWebProcessProxyMessageOnConnectionWorkQueue(connection, messageID, decoder, didHandleMessage); } ",0 "void WebProcessProxy::didUpdateHistoryTitle(uint64_t pageID, const String& title, const String& url, uint64_t frameID) { WebPageProxy* page = webPage(pageID); if (!page) return; WebFrameProxy* frame = webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK(frame->page() == page); MESSAGE_CHECK_URL(url); m_context->historyClient().didUpdateHistoryTitle(m_context.get(), page, title, url, frame); } ",0 "void WebProcessProxy::disconnectFramesFromPage(WebPageProxy* page) { Vector > frames; copyValuesToVector(m_frameMap, frames); for (size_t i = 0, size = frames.size(); i < size; ++i) { if (frames[i]->page() == page) frames[i]->disconnect(); } } ",0 "size_t WebProcessProxy::frameCountInPage(WebPageProxy* page) const { size_t result = 0; for (HashMap >::const_iterator iter = m_frameMap.begin(); iter != m_frameMap.end(); ++iter) { if (iter->value->page() == page) ++result; } return result; } ",0 "void WebProcessProxy::frameCreated(uint64_t frameID, WebFrameProxy* frameProxy) { ASSERT(canCreateFrame(frameID)); m_frameMap.set(frameID, frameProxy); } ",0 "bool WebProcessProxy::fullKeyboardAccessEnabled() { return false; } ",0 "static uint64_t generatePageID() { static uint64_t uniquePageID = 1; return uniquePageID++; } ",0 "void WebProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) { launchOptions.processType = ProcessLauncher::WebProcess; platformGetLaunchOptions(launchOptions); } ",0 "void WebProcessProxy::getNetworkProcessConnection(PassRefPtr reply) { m_context->getNetworkProcessConnection(reply); } ",0 "void WebProcessProxy::getPluginPath(const String& mimeType, const String& urlString, String& pluginPath, uint32_t& pluginLoadPolicy) { MESSAGE_CHECK_URL(urlString); String newMimeType = mimeType.lower(); pluginLoadPolicy = PluginModuleLoadNormally; PluginModuleInfo plugin = m_context->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString)); if (!plugin.path) return; pluginLoadPolicy = PluginInfoStore::policyForPlugin(plugin); if (pluginLoadPolicy != PluginModuleLoadNormally) return; pluginPath = plugin.path; } ",0 "void WebProcessProxy::getPluginProcessConnection(const String& pluginPath, uint32_t processType, PassRefPtr reply) { PluginProcessManager::shared().getPluginProcessConnection(m_context->pluginInfoStore(), pluginPath, static_cast(processType), reply); } ",0 "void WebProcessProxy::getPlugins(CoreIPC::Connection*, uint64_t requestID, bool refresh) { pluginWorkQueue().dispatch(bind(&WebProcessProxy::handleGetPlugins, this, requestID, refresh)); } ",0 "void WebProcessProxy::getSharedWorkerProcessConnection(const String& /* url */, const String& /* name */, PassRefPtr) { } ",0 "static WebProcessProxy::WebPageProxyMap& globalPageMap() { ASSERT(isMainThread()); DEFINE_STATIC_LOCAL(WebProcessProxy::WebPageProxyMap, pageMap, ()); return pageMap; } ",0 "void WebProcessProxy::interactionOccurredWhileUnresponsive(ResponsivenessTimer*) { Vector > pages; copyValuesToVector(m_pageMap, pages); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->interactionOccurredWhileProcessUnresponsive(); } ",0 "static inline bool isGoodKey(const typename HashMap::KeyType& key) { return key != HashTraits::emptyValue() && !HashTraits::isDeletedValue(key); } ",0 "void WebProcessProxy::pagePreferencesChanged(WebKit::WebPageProxy *page) { #if PLATFORM(MAC) if (pageIsProcessSuppressible(page)) m_processSuppressiblePages.add(page->pageID()); else m_processSuppressiblePages.remove(page->pageID()); updateProcessSuppressionState(); #else UNUSED_PARAM(page); #endif } ",0 "void WebProcessProxy::pageVisibilityChanged(WebKit::WebPageProxy *page) { #if PLATFORM(MAC) if (pageIsProcessSuppressible(page)) m_processSuppressiblePages.add(page->pageID()); else m_processSuppressiblePages.remove(page->pageID()); updateProcessSuppressionState(); #else UNUSED_PARAM(page); #endif } ",0 "static WorkQueue& pluginWorkQueue() { DEFINE_STATIC_LOCAL(WorkQueue, queue, (""com.apple.CoreIPC.PluginQueue"")); return queue; } ",0 "void WebProcessProxy::registerNewWebBackForwardListItem(WebBackForwardListItem* item) { ASSERT(!m_backForwardListItemMap.contains(item->itemID())); m_backForwardListItemMap.set(item->itemID(), item); } ",0 "void WebProcessProxy::removeMessagePortChannel(uint64_t channelID) { if (!isValid()) return; send(Messages::WebProcess::RemoveMessagePortChannel(channelID), /* destinationID */ 0); } ",0 "void WebProcessProxy::removeMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID) { m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID); } ",0 "void WebProcessProxy::removeWebPage(uint64_t pageID) { m_pageMap.remove(pageID); globalPageMap().remove(pageID); #if PLATFORM(MAC) m_processSuppressiblePages.remove(pageID); updateProcessSuppressionState(); #endif } ",0 "void WebProcessProxy::sendDidGetPlugins(uint64_t requestID, PassOwnPtr > pluginInfos) { ASSERT(isMainThread()); OwnPtr > plugins(pluginInfos); #if PLATFORM(MAC) if (!m_context->omitPDFSupport()) { #if ENABLE(PDFKIT_PLUGIN) plugins->append(PDFPlugin::pluginInfo()); #endif plugins->append(SimplePDFPlugin::pluginInfo()); } #endif send(Messages::WebProcess::DidGetPlugins(requestID, *plugins), 0); } ",0 "void WebProcessProxy::shouldTerminate(bool& shouldTerminate) { if (!m_pageMap.isEmpty() || (m_downloadProxyMap && !m_downloadProxyMap->isEmpty()) || !m_context->shouldTerminate(this)) { shouldTerminate = false; return; } shouldTerminate = true; disconnect(); } ",0 "void WebProcessProxy::updateTextCheckerState() { if (canSendMessage()) send(Messages::WebProcess::SetTextCheckerState(TextChecker::state()), 0); } ",0 "WebPageProxy* WebProcessProxy::webPage(uint64_t pageID) { return globalPageMap().get(pageID); } ",0 "WebProcessProxy::~WebProcessProxy() { if (m_webConnection) m_webConnection->invalidate(); } ",0 "v8::Handle V8ThrowException::createRangeError(v8::Isolate* isolate, const String& message) { return v8::Exception::RangeError(v8String(isolate, message.isNull() ? ""Range error"" : message)); } ",0 "v8::Handle V8ThrowException::createSyntaxError(v8::Isolate* isolate, const String& message) { return v8::Exception::SyntaxError(v8String(isolate, message.isNull() ? ""Syntax error"" : message)); } ",0 "v8::Handle V8ThrowException::createTypeError(v8::Isolate* isolate, const String& message) { return v8::Exception::TypeError(v8String(isolate, message.isNull() ? ""Type error"" : message)); } ",0 "static void domExceptionStackGetter(v8::Local name, const v8::PropertyCallbackInfo& info) { ASSERT(info.Data()->IsObject()); v8SetReturnValue(info, info.Data()->ToObject(info.GetIsolate())->Get(v8AtomicString(info.GetIsolate(), ""stack""))); } ",0 "static void domExceptionStackSetter(v8::Local name, v8::Local value, const v8::PropertyCallbackInfo& info) { ASSERT(info.Data()->IsObject()); info.Data()->ToObject(info.GetIsolate())->Set(v8AtomicString(info.GetIsolate(), ""stack""), value); } ",0 "v8::Handle V8ThrowException::throwDOMException(int ec, const String& sanitizedMessage, const String& unsanitizedMessage, const v8::Handle& creationContext, v8::Isolate* isolate) { ASSERT(ec == SecurityError || unsanitizedMessage.isEmpty()); v8::Handle exception = createDOMException(isolate, ec, sanitizedMessage, unsanitizedMessage, creationContext); if (exception.IsEmpty()) return v8Undefined(); return V8ThrowException::throwException(exception, isolate); } ",0 "v8::Handle V8ThrowException::throwReferenceError(v8::Isolate* isolate, const String& message) { v8::Handle exception = V8ThrowException::createReferenceError(isolate, message); return V8ThrowException::throwException(exception, isolate); } ",0 "v8::Handle V8ThrowException::throwSyntaxError(v8::Isolate* isolate, const String& message) { v8::Handle exception = V8ThrowException::createSyntaxError(isolate, message); return V8ThrowException::throwException(exception, isolate); } ",0 "v8::Handle V8ThrowException::throwTypeError(v8::Isolate* isolate, const String& message) { v8::Handle exception = V8ThrowException::createTypeError(isolate, message); return V8ThrowException::throwException(exception, isolate); } ",0 "gfx::Rect OverlayWindowViews::CalculateAndUpdateWindowBounds() { gfx::Rect work_area = display::Screen::GetScreen() ->GetDisplayNearestWindow( controller_->GetInitiatorWebContents()->GetTopLevelNativeWindow()) .work_area(); max_size_ = gfx::Size(work_area.width() / 2, work_area.height() / 2); min_size_ = kMinWindowSize; gfx::Size window_size = window_bounds_.size(); if (!has_been_shown_) { window_size = gfx::Size(work_area.width() / 5, work_area.height() / 5); window_size.set_width(std::min( max_size_.width(), std::max(min_size_.width(), window_size.width()))); window_size.set_height( std::min(max_size_.height(), std::max(min_size_.height(), window_size.height()))); } if (!window_size.IsEmpty() && !natural_size_.IsEmpty()) { float aspect_ratio = (float)natural_size_.width() / natural_size_.height(); gfx::Rect window_rect(GetBounds().origin(), window_size); views::WindowResizeUtils::SizeRectToAspectRatio( views::HitTest::kBottomRight, aspect_ratio, min_size_, max_size_, &window_rect); window_size.SetSize(window_rect.width(), window_rect.height()); UpdateLayerBoundsWithLetterboxing(window_size); } gfx::Point origin = window_bounds_.origin(); int window_diff_width = work_area.right() - window_size.width(); int window_diff_height = work_area.bottom() - window_size.height(); int buffer = (window_diff_width + window_diff_height) / 2 * 0.02; gfx::Point default_origin = gfx::Point(window_diff_width - buffer, window_diff_height - buffer); if (has_been_shown_) { origin.SetToMin(default_origin); } else { origin = default_origin; } window_bounds_ = gfx::Rect(origin, window_size); return window_bounds_; } ",0 "gfx::Rect OverlayWindowViews::CalculateControlsBounds(int x, const gfx::Size& size) { return gfx::Rect( gfx::Point(x, (GetBounds().size().height() - size.height()) / 2), size); } ",0 "void OverlayWindowViews::Close() { views::Widget::Close(); } ",0 "std::unique_ptr content::OverlayWindow::Create( content::PictureInPictureWindowController* controller) { return base::WrapUnique(new OverlayWindowViews(controller)); } ",0 "void OverlayWindowViews::CreateCustomControl( std::unique_ptr& control_button, const blink::PictureInPictureControlInfo& info, ControlPosition position) { control_button = std::make_unique(this); controls_parent_view_->AddChildView(control_button.get()); control_button->set_id(info.id); control_button->set_owned_by_client(); control_button->SetImageAlignment(views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE); UpdateCustomControlsSize(control_button.get()); UpdateControlsBounds(); base::string16 custom_button_label = base::UTF8ToUTF16(info.label); control_button->SetAccessibleName(custom_button_label); control_button->SetTooltipText(custom_button_label); control_button->SetInstallFocusRingOnFocus(true); control_button->SetFocusForPlatform(); } ",0 "gfx::Rect OverlayWindowViews::GetBounds() const { return views::Widget::GetRestoredBounds(); } ",0 "gfx::Rect OverlayWindowViews::GetCloseControlsBounds() { return close_controls_view_->GetMirroredBounds(); } ",0 "ui::Layer* OverlayWindowViews::GetControlsParentLayer() { return controls_parent_view_->layer(); } ",0 "ui::Layer* OverlayWindowViews::GetControlsScrimLayer() { return controls_scrim_view_->layer(); } ",0 "OverlayWindowViews::WindowQuadrant GetCurrentWindowQuadrant( const gfx::Rect window_bounds, content::PictureInPictureWindowController* controller) { gfx::Rect work_area = display::Screen::GetScreen() ->GetDisplayNearestWindow( controller->GetInitiatorWebContents()->GetTopLevelNativeWindow()) .work_area(); gfx::Point window_center = window_bounds.CenterPoint(); if (window_center.x() < work_area.width() / 2) { return (window_center.y() < work_area.height() / 2) ? OverlayWindowViews::WindowQuadrant::kTopLeft : OverlayWindowViews::WindowQuadrant::kBottomLeft; } return (window_center.y() < work_area.height() / 2) ? OverlayWindowViews::WindowQuadrant::kTopRight : OverlayWindowViews::WindowQuadrant::kBottomRight; } ",0 "gfx::Rect OverlayWindowViews::GetFirstCustomControlsBounds() { if (!first_custom_controls_view_) return gfx::Rect(); return first_custom_controls_view_->GetMirroredBounds(); } ",0 "ui::Layer* OverlayWindowViews::GetLayer() { return views::Widget::GetLayer(); } ",0 "gfx::Size OverlayWindowViews::GetMaximumSize() const { return max_size_; } ",0 "gfx::Rect OverlayWindowViews::GetPlayPauseControlsBounds() { return play_pause_controls_view_->GetMirroredBounds(); } ",0 "ui::Layer* OverlayWindowViews::GetResizeHandleLayer() { return resize_handle_view_->layer(); } ",0 "gfx::Rect OverlayWindowViews::GetSecondCustomControlsBounds() { if (!second_custom_controls_view_) return gfx::Rect(); return second_custom_controls_view_->GetMirroredBounds(); } ",0 "gfx::Rect OverlayWindowViews::GetVideoBounds() { return video_bounds_; } ",0 "ui::Layer* OverlayWindowViews::GetVideoLayer() { return video_view_->layer(); } ",0 "ui::Layer* OverlayWindowViews::GetWindowBackgroundLayer() { return window_background_view_->layer(); } ",0 "bool OverlayWindowViews::HasOnlyOneCustomControl() { return first_custom_controls_view_ && !second_custom_controls_view_; } ",0 "void OverlayWindowViews::Hide() { views::Widget::Hide(); } ",0 "bool OverlayWindowViews::IsActive() const { return views::Widget::IsActive(); } ",0 "bool OverlayWindowViews::IsAlwaysOnTop() const { return true; } ",0 "bool OverlayWindowViews::IsVisible() const { return views::Widget::IsVisible(); } ",0 "void OverlayWindowViews::OnKeyEvent(ui::KeyEvent* event) { hide_controls_timer_.Reset(); if (event->type() == ui::ET_KEY_PRESSED || event->key_code() == ui::VKEY_TAB) { UpdateControlsVisibility(true); } #if defined(OS_MACOSX) if (event->type() == ui::ET_KEY_PRESSED && event->key_code() == ui::VKEY_SPACE) { TogglePlayPause(); event->SetHandled(); } #endif // OS_MACOSX #if defined(OS_WIN) if (event->type() == ui::ET_KEY_PRESSED && event->IsAltDown() && event->key_code() == ui::VKEY_F4) { controller_->Close(true /* should_pause_video */, true /* should_reset_pip_player */); event->SetHandled(); } #endif // OS_WIN views::Widget::OnKeyEvent(event); } ",0 "void OverlayWindowViews::OnNativeBlur() { if (is_initialized_) UpdateControlsVisibility(false); views::Widget::OnNativeBlur(); } ",0 "void OverlayWindowViews::OnNativeWidgetDestroyed() { controller_->OnWindowDestroyed(); } ",0 "void OverlayWindowViews::OnNativeWidgetMove() { if (is_initialized_) UpdateControlsVisibility(false); window_bounds_ = GetBounds(); #if defined(OS_CHROMEOS) WindowQuadrant quadrant = GetCurrentWindowQuadrant(GetBounds(), controller_); close_controls_view_->SetPosition(GetBounds().size(), quadrant); resize_handle_view_->SetPosition(GetBounds().size(), quadrant); #endif } ",0 "void OverlayWindowViews::OnNativeWidgetWorkspaceChanged() { } ",0 " explicit OverlayWindowFrameView(views::Widget* widget) : widget_(widget) {} ",0 " explicit OverlayWindowWidgetDelegate(views::Widget* widget) : widget_(widget) { DCHECK(widget_); } ",0 "void OverlayWindowViews::SetAlwaysHidePlayPauseButton(bool is_visible) { always_hide_play_pause_button_ = !is_visible; } ",0 "void OverlayWindowViews::SetPictureInPictureCustomControls( const std::vector& controls) { first_custom_controls_view_.reset(); second_custom_controls_view_.reset(); if (controls.size() > 0) CreateCustomControl(first_custom_controls_view_, controls[0], ControlPosition::kLeft); if (controls.size() > 1) CreateCustomControl(second_custom_controls_view_, controls[1], ControlPosition::kRight); } ",0 "void OverlayWindowViews::SetPlaybackState(PlaybackState playback_state) { bool controls_parent_layer_visible = GetControlsParentLayer()->visible(); playback_state_ = playback_state; switch (playback_state_) { case kPlaying: play_pause_controls_view_->SetToggled(true); controls_parent_view_->SetVisible(true); video_view_->SetVisible(true); GetControlsParentLayer()->SetVisible(controls_parent_layer_visible); break; case kPaused: play_pause_controls_view_->SetToggled(false); controls_parent_view_->SetVisible(true); video_view_->SetVisible(true); GetControlsParentLayer()->SetVisible(controls_parent_layer_visible); break; case kNoVideo: controls_scrim_view_->SetVisible(false); controls_parent_view_->SetVisible(false); video_view_->SetVisible(false); GetControlsParentLayer()->SetVisible(false); break; } } ",0 "void OverlayWindowViews::SetUpViews() { gfx::Rect larger_window_bounds = GetBounds(); larger_window_bounds.Inset(-1, -1); window_background_view_->SetSize(larger_window_bounds.size()); window_background_view_->SetPaintToLayer(ui::LAYER_SOLID_COLOR); GetWindowBackgroundLayer()->SetColor(SK_ColorBLACK); controls_scrim_view_->SetSize(GetBounds().size()); controls_scrim_view_->SetPaintToLayer(ui::LAYER_SOLID_COLOR); GetControlsScrimLayer()->SetColor(gfx::kGoogleGrey900); GetControlsScrimLayer()->SetOpacity(0.43f); controls_parent_view_->SetPaintToLayer(ui::LAYER_TEXTURED); controls_parent_view_->SetSize(GetBounds().size()); controls_parent_view_->layer()->SetFillsBoundsOpaquely(false); controls_parent_view_->set_owned_by_client(); close_controls_view_->SetPaintToLayer(ui::LAYER_TEXTURED); close_controls_view_->layer()->SetFillsBoundsOpaquely(false); close_controls_view_->set_owned_by_client(); video_view_->SetPaintToLayer(ui::LAYER_TEXTURED); play_pause_controls_view_->SetImageAlignment( views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE); play_pause_controls_view_->SetToggled(controller_->IsPlayerActive()); play_pause_controls_view_->set_owned_by_client(); #if defined(OS_CHROMEOS) resize_handle_view_->SetPaintToLayer(ui::LAYER_TEXTURED); resize_handle_view_->layer()->SetFillsBoundsOpaquely(false); resize_handle_view_->set_owned_by_client(); #endif play_pause_controls_view_->SetFocusForPlatform(); // Make button focusable. const base::string16 play_pause_accessible_button_label( l10n_util::GetStringUTF16( IDS_PICTURE_IN_PICTURE_PLAY_PAUSE_CONTROL_ACCESSIBLE_TEXT)); play_pause_controls_view_->SetAccessibleName( play_pause_accessible_button_label); const base::string16 play_button_label( l10n_util::GetStringUTF16(IDS_PICTURE_IN_PICTURE_PLAY_CONTROL_TEXT)); play_pause_controls_view_->SetTooltipText(play_button_label); const base::string16 pause_button_label( l10n_util::GetStringUTF16(IDS_PICTURE_IN_PICTURE_PAUSE_CONTROL_TEXT)); play_pause_controls_view_->SetToggledTooltipText(pause_button_label); play_pause_controls_view_->SetInstallFocusRingOnFocus(true); controls_parent_view_->AddChildView(play_pause_controls_view_.get()); GetContentsView()->AddChildView(controls_scrim_view_.get()); GetContentsView()->AddChildView(controls_parent_view_.get()); GetContentsView()->AddChildView(close_controls_view_.get()); #if defined(OS_CHROMEOS) GetContentsView()->AddChildView(resize_handle_view_.get()); #endif UpdatePlayPauseControlsSize(); UpdateControlsVisibility(false); } ",0 "void OverlayWindowViews::Show() { views::Widget::Show(); has_been_shown_ = true; } ",0 "void OverlayWindowViews::TogglePlayPause() { bool is_active = controller_->TogglePlayPause(); play_pause_controls_view_->SetToggled(is_active); } ",0 "void OverlayWindowViews::UpdateButtonSize() { const gfx::Size window_size = GetBounds().size(); int scaled_button_dimension = window_size.width() < window_size.height() ? window_size.width() * kControlRatioToWindow : window_size.height() * kControlRatioToWindow; int new_button_dimension = std::max(kMinControlButtonSize, scaled_button_dimension); button_size_.SetSize(new_button_dimension, new_button_dimension); } ",0 "void OverlayWindowViews::UpdateControlsBounds() { gfx::Rect larger_window_bounds = GetBounds(); larger_window_bounds.Inset(-1, -1); controls_scrim_view_->SetBoundsRect( gfx::Rect(gfx::Point(0, 0), larger_window_bounds.size())); WindowQuadrant quadrant = GetCurrentWindowQuadrant(GetBounds(), controller_); close_controls_view_->SetPosition(GetBounds().size(), quadrant); #if defined(OS_CHROMEOS) resize_handle_view_->SetPosition(GetBounds().size(), quadrant); #endif controls_parent_view_->SetBoundsRect( gfx::Rect(gfx::Point(0, 0), GetBounds().size())); UpdateControlsPositions(); } ",0 "void OverlayWindowViews::UpdateControlsPositions() { int mid_window_x = GetBounds().size().width() / 2; if (HasOnlyOneCustomControl()) { play_pause_controls_view_->SetBoundsRect( CalculateControlsBounds(mid_window_x, button_size_)); first_custom_controls_view_->SetBoundsRect(CalculateControlsBounds( mid_window_x - button_size_.width(), button_size_)); return; } play_pause_controls_view_->SetBoundsRect(CalculateControlsBounds( mid_window_x - button_size_.width() / 2, button_size_)); if (first_custom_controls_view_ && second_custom_controls_view_) { first_custom_controls_view_->SetBoundsRect(CalculateControlsBounds( mid_window_x - button_size_.width() / 2 - button_size_.width(), button_size_)); second_custom_controls_view_->SetBoundsRect(CalculateControlsBounds( mid_window_x + button_size_.width() / 2, button_size_)); } } ",0 "void OverlayWindowViews::UpdateControlsVisibility(bool is_visible) { if (always_hide_play_pause_button_ && is_visible) play_pause_controls_view_->SetVisible(false); GetCloseControlsLayer()->SetVisible(is_visible); #if defined(OS_CHROMEOS) GetResizeHandleLayer()->SetVisible(is_visible); #endif GetControlsScrimLayer()->SetVisible( (playback_state_ == kNoVideo) ? false : is_visible); GetControlsParentLayer()->SetVisible( (playback_state_ == kNoVideo) ? false : is_visible); } ",0 "void OverlayWindowViews::UpdateCustomControlsSize( views::ControlImageButton* control_button) { if (!control_button) return; UpdateButtonSize(); control_button->SetSize(button_size_); if (control_button == first_custom_controls_view_.get()) { first_custom_controls_view_->SetImage( views::Button::STATE_NORMAL, gfx::CreateVectorIcon(vector_icons::kPlayArrowIcon, button_size_.width() / 2, kControlIconColor)); } if (control_button == second_custom_controls_view_.get()) { second_custom_controls_view_->SetImage( views::Button::STATE_NORMAL, gfx::CreateVectorIcon(vector_icons::kPauseIcon, button_size_.width() / 2, kControlIconColor)); } const gfx::ImageSkia control_background = gfx::CreateVectorIcon( kPictureInPictureControlBackgroundIcon, button_size_.width(), kBgColor); control_button->SetBackgroundImage(kBgColor, &control_background, &control_background); } ",0 "void OverlayWindowViews::UpdateLayerBoundsWithLetterboxing( gfx::Size window_size) { if (window_bounds_.size().IsEmpty() || natural_size_.IsEmpty()) return; gfx::Rect letterbox_region = media::ComputeLetterboxRegion( gfx::Rect(gfx::Point(0, 0), window_size), natural_size_); if (letterbox_region.IsEmpty()) return; gfx::Size letterbox_size = letterbox_region.size(); gfx::Point origin = gfx::Point((window_size.width() - letterbox_size.width()) / 2, (window_size.height() - letterbox_size.height()) / 2); video_bounds_.set_origin(origin); video_bounds_.set_size(letterbox_region.size()); UpdateControlsBounds(); controller_->UpdateLayerBounds(); } ",0 "void OverlayWindowViews::UpdatePlayPauseControlsSize() { UpdateButtonSize(); play_pause_controls_view_->SetSize(button_size_); play_pause_controls_view_->SetImage( views::Button::STATE_NORMAL, gfx::CreateVectorIcon(vector_icons::kPlayArrowIcon, button_size_.width() / 2, kControlIconColor)); gfx::ImageSkia pause_icon = gfx::CreateVectorIcon( vector_icons::kPauseIcon, button_size_.width() / 2, kControlIconColor); play_pause_controls_view_->SetToggledImage(views::Button::STATE_NORMAL, &pause_icon); const gfx::ImageSkia play_pause_background = gfx::CreateVectorIcon( kPictureInPictureControlBackgroundIcon, button_size_.width(), kBgColor); play_pause_controls_view_->SetBackgroundImage( kBgColor, &play_pause_background, &play_pause_background); } ",0 "void OverlayWindowViews::UpdateVideoSize(const gfx::Size& natural_size) { DCHECK(!natural_size.IsEmpty()); natural_size_ = natural_size; SetAspectRatio(gfx::SizeF(natural_size_)); SetBounds(CalculateAndUpdateWindowBounds()); } ",0 "views::View* OverlayWindowViews::controls_parent_view_for_testing() const { return controls_parent_view_.get(); } ",0 "OverlayWindowViews::play_pause_controls_view_for_testing() const { return play_pause_controls_view_.get(); } ",0 "OverlayWindowViews::playback_state_for_testing() const { return playback_state_; } ",0 "gfx::Point OverlayWindowViews::resize_handle_position_for_testing() const { return resize_handle_view_->origin(); } ",0 " void UpdateNetworkManagerStatus() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &NetworkLibraryImpl::UpdateNetworkManagerStatus)); return; } SystemInfo* system = GetSystemInfo(); if (!system) return; std::string prev_cellular_service_path = cellular_ ? cellular_->service_path() : std::string(); ClearNetworks(); ParseSystem(system, ðernet_, &wifi_networks_, &cellular_networks_, &remembered_wifi_networks_); wifi_ = NULL; for (size_t i = 0; i < wifi_networks_.size(); i++) { if (wifi_networks_[i]->connecting_or_connected()) { wifi_ = wifi_networks_[i]; break; // There is only one connected or connecting wifi network. } } cellular_ = NULL; for (size_t i = 0; i < cellular_networks_.size(); i++) { if (cellular_networks_[i]->connecting_or_connected()) { cellular_ = cellular_networks_[i]; // If new cellular, then request update of the data plan list. if (cellular_networks_[i]->service_path() != prev_cellular_service_path) { RefreshCellularDataPlans(cellular_); } break; // There is only one connected or connecting cellular network. } } available_devices_ = system->available_technologies; enabled_devices_ = system->enabled_technologies; connected_devices_ = system->connected_technologies; offline_mode_ = system->offline_mode; NotifyNetworkManagerChanged(); FreeSystemInfo(system); } ",0 "int64 ClientUsageTracker::GetCachedHostUsage(const std::string& host) { int64 ClientUsageTracker::GetCachedHostUsage(const std::string& host) const { HostUsageMap::const_iterator found = cached_usage_.find(host); if (found == cached_usage_.end()) return 0; int64 usage = 0; const UsageMap& map = found->second; for (UsageMap::const_iterator iter = map.begin(); iter != map.end(); ++iter) { usage += iter->second; } return usage; } ",0 "void AddInstallerCopyTasks(const InstallerState& installer_state, const FilePath& setup_path, const FilePath& archive_path, const FilePath& temp_path, const Version& new_version, WorkItemList* install_list) { DCHECK(install_list); FilePath installer_dir(installer_state.GetInstallerDirectory(new_version)); install_list->AddCreateDirWorkItem(installer_dir); FilePath exe_dst(installer_dir.Append(setup_path.BaseName())); FilePath archive_dst(installer_dir.Append(archive_path.BaseName())); install_list->AddCopyTreeWorkItem(setup_path.value(), exe_dst.value(), temp_path.value(), WorkItem::ALWAYS); // otherwise), there is no need to do this for the archive. Setup.exe, on // the other hand, is created elsewhere so it must always be copied. install_list->AddMoveTreeWorkItem(archive_path.value(), archive_dst.value(), temp_path.value(), WorkItem::ALWAYS_MOVE); } ",0 "bool decode(ArgumentDecoder* decoder, RetainPtr& result) { RetainPtr baseURL; bool hasBaseURL; if (!decoder->decodeBool(hasBaseURL)) return false; if (hasBaseURL) { if (!decode(decoder, baseURL)) return false; } RetainPtr string; if (!decode(decoder, string)) return false; #if PLATFORM(MAC) // FIXME: Move this to ArgumentCodersCFMac.mm and change this file back to be C++ // instead of Objective-C++. if (!CFStringGetLength(string.get())) { // CFURL can't hold an empty URL, unlike NSURL. result = reinterpret_cast([NSURL URLWithString:@""""]); return true; } #endif CFURLRef url = CFURLCreateWithString(0, string.get(), baseURL.get()); if (!url) return false; result.adoptCF(url); return true; } ",0 "void WebProcessProxy::addExistingWebPage(WebPageProxy* webPage, uint64_t pageID) { m_pageMap.set(pageID, webPage); globalPageMap().set(pageID, webPage); #if PLATFORM(MAC) if (pageIsProcessSuppressible(webPage)) m_processSuppressiblePages.add(pageID); updateProcessSuppressionState(); #endif } ",0 "v8::Handle V8ThrowException::createDOMException(v8::Isolate* isolate, int ec, const String& sanitizedMessage, const String& unsanitizedMessage, const v8::Handle& creationContext) { if (ec <= 0 || v8::V8::IsExecutionTerminating()) return v8Undefined(); ASSERT(ec == SecurityError || unsanitizedMessage.isEmpty()); if (ec == V8GeneralError) return V8ThrowException::createGeneralError(isolate, sanitizedMessage); if (ec == V8TypeError) return V8ThrowException::createTypeError(isolate, sanitizedMessage); if (ec == V8RangeError) return V8ThrowException::createRangeError(isolate, sanitizedMessage); if (ec == V8SyntaxError) return V8ThrowException::createSyntaxError(isolate, sanitizedMessage); if (ec == V8ReferenceError) return V8ThrowException::createReferenceError(isolate, sanitizedMessage); v8::Handle sanitizedCreationContext = creationContext; // FIXME: Is the current context always the right choice? Frame* frame = toFrameIfNotDetached(creationContext->CreationContext()); if (!frame || !BindingSecurity::shouldAllowAccessToFrame(isolate, frame, DoNotReportSecurityError)) sanitizedCreationContext = isolate->GetCurrentContext()->Global(); RefPtrWillBeRawPtr domException = DOMException::create(ec, sanitizedMessage, unsanitizedMessage); v8::Handle exception = toV8(domException.get(), sanitizedCreationContext, isolate); if (exception.IsEmpty()) return v8Undefined(); v8::Handle error = v8::Exception::Error(v8String(isolate, domException->message())); ASSERT(!error.IsEmpty()); ASSERT(exception->IsObject()); exception->ToObject(isolate)->SetAccessor(v8AtomicString(isolate, ""stack""), domExceptionStackGetter, domExceptionStackSetter, error); V8HiddenValue::setHiddenValue(isolate, exception->ToObject(isolate), V8HiddenValue::error(isolate), error); return exception; } ",0 "void OverlayWindowViews::OnGestureEvent(ui::GestureEvent* event) { if (event->type() != ui::ET_GESTURE_TAP) return; hide_controls_timer_.Reset(); if (!GetControlsScrimLayer()->visible()) { UpdateControlsVisibility(true); return; } if (GetCloseControlsBounds().Contains(event->location())) { controller_->Close(true /* should_pause_video */, true /* should_reset_pip_player */); event->SetHandled(); } else if (GetPlayPauseControlsBounds().Contains(event->location())) { TogglePlayPause(); event->SetHandled(); } } ",0 " virtual void ConnectToCellularNetwork(const CellularNetwork* network) { DCHECK(network); if (!EnsureCrosLoaded()) return; if (network && ConnectToNetwork(network->service_path().c_str(), NULL)) { CellularNetwork* cellular = GetWirelessNetworkByPath( cellular_networks_, network->service_path()); if (cellular) { cellular->set_connecting(true); cellular_ = cellular; } NotifyNetworkManagerChanged(); } } ",0 " virtual void ConnectToCellularNetwork(const CellularNetwork* network) {} ",0 " static void DataPlanUpdateHandler(void* object, const char* modem_service_path, const CellularDataPlanList* dataplan) { NetworkLibraryImpl* networklib = static_cast(object); if (!networklib || !networklib->cellular_network()) { return; } if (networklib->cellular_network()->service_path() .compare(modem_service_path) == 0) { if (dataplan != NULL) { networklib->UpdateCellularDataPlan(dataplan); } } } ",0 " virtual void EnableCellularNetworkDevice(bool enable) {} ",0 " virtual void EnableWifiNetworkDevice(bool enable) {} ",0 "static bool EnsureCrosLoaded() { if (!CrosLibrary::Get()->EnsureLoaded()) { return false; } else { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << ""chromeos_library calls made from non UI thread!""; NOTREACHED(); } return true; } } ",0 " virtual CellularNetwork* FindCellularNetworkByPath( const std::string& path) { return GetWirelessNetworkByPath(cellular_networks_, path); } ",0 " virtual void ForgetWifiNetwork(const std::string& service_path) {} ",0 "std::string CellularNetwork::GetNetworkTechnologyString() const { switch (network_technology_) { case NETWORK_TECHNOLOGY_1XRTT: return ""1xRTT""; break; case NETWORK_TECHNOLOGY_EVDO: return ""EVDO""; break; case NETWORK_TECHNOLOGY_GPRS: return ""GPRS""; break; case NETWORK_TECHNOLOGY_EDGE: return ""EDGE""; break; case NETWORK_TECHNOLOGY_UMTS: return ""UMTS""; break; case NETWORK_TECHNOLOGY_HSPA: return ""HSPA""; break; case NETWORK_TECHNOLOGY_HSPA_PLUS: return ""HSPA Plus""; break; case NETWORK_TECHNOLOGY_LTE: return ""LTE""; break; case NETWORK_TECHNOLOGY_LTE_ADVANCED: return ""LTE Advanced""; break; default: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_CELLULAR_TECHNOLOGY_UNKNOWN); break; } } ",0 " NetworkLibraryStubImpl() : ip_address_(""1.1.1.1""), ethernet_(new EthernetNetwork()), wifi_(NULL), cellular_(NULL) { } ",0 " static void NetworkManagerStatusChangedHandler(void* object, const char* path, const char* key, const Value* value) { NetworkLibraryImpl* networklib = static_cast(object); DCHECK(networklib); networklib->UpdateNetworkManagerStatus(); } ",0 " void NotifyCellularDataPlanChanged() { FOR_EACH_OBSERVER(CellularDataPlanObserver, data_plan_observers_, OnCellularDataPlanChanged(this)); } ",0 " void NotifyNetworkManagerChanged() { FOR_EACH_OBSERVER(NetworkManagerObserver, network_manager_observers_, OnNetworkManagerChanged(this)); } ",0 " virtual void UpdateSystemInfo() {} ",0 "WifiNetwork::WifiNetwork(const ServiceInfo* service) : WirelessNetwork(service) { encryption_ = service->security; passphrase_ = SafeString(service->passphrase); identity_ = SafeString(service->identity); cert_path_ = SafeString(service->cert_path); type_ = TYPE_WIFI; } ",0 " virtual bool cellular_enabled() const { return false; } ",0 " virtual bool ethernet_available() const { return available_devices_ & (1 << TYPE_ETHERNET); } ",0 " virtual bool ethernet_connecting() const { return ethernet_ ? ethernet_->connecting() : false; } ",0 " AvailableSpaceQueryTask( QuotaManager* manager, scoped_refptr db_message_loop, const FilePath& profile_path, AvailableSpaceCallback* callback) : QuotaThreadTask(manager, db_message_loop), profile_path_(profile_path), space_(-1), callback_(callback) {} ",0 " explicit DatabaseTaskBase(QuotaManager* manager) : QuotaThreadTask(manager, manager->db_thread_), manager_(manager), database_(manager->database_.get()), db_disabled_(false) { DCHECK(manager_); DCHECK(database_); } ",0 "void QuotaManager::DeleteOriginFromDatabase( const GURL& origin, StorageType type) { LazyInitialize(); if (db_disabled_) return; scoped_refptr task = new DeleteOriginInfo(this, origin, type); task->Start(); } ",0 "void QuotaManager::DidOriginDataEvicted( QuotaStatusCode status) { DCHECK(io_thread_->BelongsToCurrentThread()); if (status != kQuotaStatusOk) origins_in_error_[eviction_context_.evicted_origin]++; eviction_context_.evict_origin_data_callback->Run(status); eviction_context_.evict_origin_data_callback.reset(); } ",0 "void QuotaManager::GetPersistentHostQuota(const std::string& host, HostQuotaCallback* callback_ptr) { scoped_ptr callback(callback_ptr); LazyInitialize(); if (host.empty()) { callback->Run(kQuotaStatusOk, host, kStorageTypePersistent, 0); return; } scoped_refptr task( new GetPersistentHostQuotaTask(this, host, callback.release())); task->Start(); } ",0 "bool QuotaManager::ResetUsageTracker(StorageType type) { switch (type) { case kStorageTypeTemporary: if (temporary_usage_tracker_->IsWorking()) return false; temporary_usage_tracker_.reset( new UsageTracker(clients_, kStorageTypeTemporary, special_storage_policy_)); return true; case kStorageTypePersistent: if (persistent_usage_tracker_->IsWorking()) return false; persistent_usage_tracker_.reset( new UsageTracker(clients_, kStorageTypePersistent, special_storage_policy_)); return true; default: NOTREACHED(); } return true; } ",0 " UpdateTemporaryGlobalQuotaTask( QuotaManager* manager, int64 new_quota, QuotaCallback* callback) : DatabaseTaskBase(manager), new_quota_(new_quota), callback_(callback) { DCHECK_GE(new_quota, 0); } ",0 " CallbackList& unlimited_callbacks() { return unlimited_callbacks_; } ",0 " void DumpQuotaTable() { quota_entries_.clear(); quota_manager_->DumpQuotaTable( callback_factory_.NewCallback( &QuotaManagerTest::DidDumpQuotaTable)); } ",0 " base::Time IncrementMockTime() { ++mock_time_counter_; return base::Time::FromDoubleT(mock_time_counter_ * 10.0); } ",0 " const std::string& host() const { return host_; } ",0 " const OriginInfoTableEntries& origin_info_entries() const { return origin_info_entries_; } ",0 " FilePath profile_path() const { return data_dir_.path(); } ",0 " const QuotaTableEntries& quota_entries() const { return quota_entries_; } ",0 " void set_quota_manager(QuotaManager* quota_manager) { quota_manager_ = quota_manager; } ",0 " QuotaStatusCode status() const { return quota_status_; } ",0 " GatherGlobalUsageTask( UsageTracker* tracker, QuotaClient* client) : GatherUsageTaskBase(tracker, client), client_(client), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { DCHECK(tracker); DCHECK(client); } ",0 " GatherUsageTaskBase( UsageTracker* tracker, QuotaClient* client) : QuotaTask(tracker), client_(client), tracker_(tracker), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { DCHECK(tracker_); DCHECK(client_); client_tracker_ = tracker_->GetClientTracker(client_->id()); DCHECK(client_tracker_); } ",0 "void ClientUsageTracker::GetHostUsage( const std::string& host, HostUsageCallback* callback) { HostSet::const_iterator found = cached_hosts_.find(host); if (found != cached_hosts_.end()) { callback->Run(host, type_, GetCachedHostUsage(host)); delete callback; return; } if (!host_usage_callbacks_.Add(host, callback) || global_usage_task_) return; GatherHostUsageTask* task = new GatherHostUsageTask(tracker_, client_, host); host_usage_tasks_[host] = task; task->Start(); } ",0 "void AddDeleteUninstallShortcutsForMSIWorkItems( const InstallerState& installer_state, const Product& product, const FilePath& temp_path, WorkItemList* work_item_list) { DCHECK(installer_state.is_msi()) << ""This must only be called for MSI installations!""; HKEY reg_root = installer_state.root_key(); std::wstring uninstall_reg(product.distribution()->GetUninstallRegPath()); WorkItem* delete_reg_key = work_item_list->AddDeleteRegKeyWorkItem( reg_root, uninstall_reg); delete_reg_key->set_ignore_failure(true); FilePath uninstall_link; if (installer_state.system_install()) { PathService::Get(base::DIR_COMMON_START_MENU, &uninstall_link); } else { PathService::Get(base::DIR_START_MENU, &uninstall_link); } if (uninstall_link.empty()) { LOG(ERROR) << ""Failed to get location for shortcut.""; } else { uninstall_link = uninstall_link.Append( product.distribution()->GetAppShortCutName()); uninstall_link = uninstall_link.Append( product.distribution()->GetUninstallLinkName() + L"".lnk""); VLOG(1) << ""Deleting old uninstall shortcut (if present): "" << uninstall_link.value(); WorkItem* delete_link = work_item_list->AddDeleteTreeWorkItem( uninstall_link, temp_path); delete_link->set_ignore_failure(true); delete_link->set_log_message( ""Failed to delete old uninstall shortcut.""); } } ",0 "void AddQuickEnableWorkItems(const InstallerState& installer_state, const InstallationState& machine_state, const FilePath* setup_path, const Version* new_version, WorkItemList* work_item_list) { DCHECK(setup_path || installer_state.operation() == InstallerState::UNINSTALL); DCHECK(new_version || installer_state.operation() == InstallerState::UNINSTALL); DCHECK(work_item_list); const bool system_install = installer_state.system_install(); bool have_multi_chrome = false; bool have_chrome_frame = false; const ProductState* product_state = NULL; product_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_BROWSER); if (product_state != NULL && product_state->is_multi_install()) have_multi_chrome = true; product_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_FRAME); if (product_state != NULL && !product_state->uninstall_command().HasSwitch( switches::kChromeFrameReadyMode)) have_chrome_frame = true; const Product* product = NULL; if (installer_state.operation() == InstallerState::UNINSTALL) { product = installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER); if (product != NULL && installer_state.is_multi_install()) have_multi_chrome = false; if (installer_state.FindProduct(BrowserDistribution::CHROME_FRAME) != NULL) have_chrome_frame = false; } else { product = installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER); if (product != NULL && installer_state.is_multi_install()) have_multi_chrome = true; product = installer_state.FindProduct(BrowserDistribution::CHROME_FRAME); if (product != NULL && !product->HasOption(kOptionReadyMode)) have_chrome_frame = true; } enum QuickEnableOperation { DO_NOTHING, ADD_COMMAND, REMOVE_COMMAND } operation = DO_NOTHING; FilePath binaries_setup_path; if (have_chrome_frame) { operation = REMOVE_COMMAND; } else if (have_multi_chrome) { operation = ADD_COMMAND; if (installer_state.operation() == InstallerState::UNINSTALL) { product_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_BROWSER); DCHECK(product_state); binaries_setup_path = product_state->uninstall_command().GetProgram(); } else { DCHECK(installer_state.is_multi_install()); binaries_setup_path = installer_state.GetInstallerDirectory(*new_version).Append( setup_path->BaseName()); } } if (operation != DO_NOTHING) { BrowserDistribution* binaries = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES); std::wstring cmd_key(binaries->GetVersionKey()); cmd_key.append(1, L'\\').append(google_update::kRegCommandsKey) .append(1, L'\\').append(kCmdQuickEnableCf); if (operation == ADD_COMMAND) { DCHECK(!binaries_setup_path.empty()); CommandLine cmd_line(binaries_setup_path); cmd_line.AppendSwitch(switches::kMultiInstall); if (installer_state.system_install()) cmd_line.AppendSwitch(switches::kSystemLevel); if (installer_state.verbose_logging()) cmd_line.AppendSwitch(switches::kVerboseLogging); cmd_line.AppendSwitch(switches::kChromeFrameQuickEnable); AppCommand cmd(cmd_line.command_line_string(), true, true); cmd.AddWorkItems(installer_state.root_key(), cmd_key, work_item_list); } else { DCHECK(operation == REMOVE_COMMAND); work_item_list->AddDeleteRegKeyWorkItem(installer_state.root_key(), cmd_key)->set_log_message( ""removing quick-enable-cf command""); } } } ",0 "bool WebProcessProxy::canCreateFrame(uint64_t frameID) const { return isGoodKey(frameID) && !m_frameMap.contains(frameID); } ",0 "void WebProcessProxy::didBecomeResponsive(ResponsivenessTimer*) { Vector > pages; copyValuesToVector(m_pageMap, pages); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->processDidBecomeResponsive(); } ",0 "void WebProcessProxy::didPerformClientRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID) { WebPageProxy* page = webPage(pageID); if (!page) return; if (sourceURLString.isEmpty() || destinationURLString.isEmpty()) return; WebFrameProxy* frame = webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK(frame->page() == page); MESSAGE_CHECK_URL(sourceURLString); MESSAGE_CHECK_URL(destinationURLString); m_context->historyClient().didPerformClientRedirect(m_context.get(), page, sourceURLString, destinationURLString, frame); } ",0 "void WebProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr& replyEncoder) { if (m_messageReceiverMap.dispatchSyncMessage(connection, messageID, decoder, replyEncoder)) return; if (m_context->dispatchSyncMessage(connection, messageID, decoder, replyEncoder)) return; if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) { didReceiveSyncWebProcessProxyMessage(connection, messageID, decoder, replyEncoder); return; } uint64_t pageID = decoder.destinationID(); if (!pageID) return; WebPageProxy* pageProxy = webPage(pageID); if (!pageProxy) return; pageProxy->didReceiveSyncMessage(connection, messageID, decoder, replyEncoder); } ",0 "void WebProcessProxy::disconnect() { clearConnection(); if (m_webConnection) { m_webConnection->invalidate(); m_webConnection = nullptr; } m_responsivenessTimer.stop(); Vector > frames; copyValuesToVector(m_frameMap, frames); for (size_t i = 0, size = frames.size(); i < size; ++i) frames[i]->disconnect(); m_frameMap.clear(); if (m_downloadProxyMap) m_downloadProxyMap->processDidClose(); m_context->disconnectProcess(this); } ",0 "Vector WebProcessProxy::pages() const { Vector result; copyValuesToVector(m_pageMap, result); return result; } ",0 "WebBackForwardListItem* WebProcessProxy::webBackForwardItem(uint64_t itemID) const { return m_backForwardListItemMap.get(itemID).get(); } ",0 "WebFrameProxy* WebProcessProxy::webFrame(uint64_t frameID) const { return isGoodKey(frameID) ? m_frameMap.get(frameID).get() : 0; } ",0 "v8::Handle V8ThrowException::createGeneralError(v8::Isolate* isolate, const String& message) { return v8::Exception::Error(v8String(isolate, message.isNull() ? ""Error"" : message)); } ",0 "v8::Handle V8ThrowException::createReferenceError(v8::Isolate* isolate, const String& message) { return v8::Exception::ReferenceError(v8String(isolate, message.isNull() ? ""Reference error"" : message)); } ",0 "v8::Handle V8ThrowException::throwException(v8::Handle exception, v8::Isolate* isolate) { if (!v8::V8::IsExecutionTerminating()) isolate->ThrowException(exception); return v8::Undefined(isolate); } ",0 "v8::Handle V8ThrowException::throwGeneralError(v8::Isolate* isolate, const String& message) { v8::Handle exception = V8ThrowException::createGeneralError(isolate, message); return V8ThrowException::throwException(exception, isolate); } ",0 "v8::Handle V8ThrowException::throwRangeError(v8::Isolate* isolate, const String& message) { v8::Handle exception = V8ThrowException::createRangeError(isolate, message); return V8ThrowException::throwException(exception, isolate); } ",0 " void OverlayWindowViews::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == close_controls_view_.get()) controller_->Close(true /* should_pause_video */, true /* should_reset_pip_player */); if (sender == play_pause_controls_view_.get()) TogglePlayPause(); if (sender == first_custom_controls_view_.get()) controller_->CustomControlPressed(first_custom_controls_view_->id()); if (sender == second_custom_controls_view_.get()) controller_->CustomControlPressed(second_custom_controls_view_->id()); } ",0 "ui::Layer* OverlayWindowViews::GetCloseControlsLayer() { return close_controls_view_->layer(); } ",0 "gfx::Size OverlayWindowViews::GetMinimumSize() const { return min_size_; } ",0 "OverlayWindowViews::OverlayWindowViews( content::PictureInPictureWindowController* controller) : controller_(controller), window_background_view_(new views::View()), video_view_(new views::View()), controls_scrim_view_(new views::View()), controls_parent_view_(new views::View()), close_controls_view_(new views::CloseImageButton(this)), #if defined(OS_CHROMEOS) resize_handle_view_(new views::ResizeHandleButton(this)), #endif play_pause_controls_view_(new views::ToggleImageButton(this)), hide_controls_timer_( FROM_HERE, base::TimeDelta::FromMilliseconds(2500 /* 2.5 seconds */), base::BindRepeating(&OverlayWindowViews::UpdateControlsVisibility, base::Unretained(this), false /* is_visible */)) { views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = CalculateAndUpdateWindowBounds(); params.keep_on_top = true; params.visible_on_all_workspaces = true; params.remove_standard_frame = true; params.name = ""PictureInPictureWindow""; params.delegate = new OverlayWindowWidgetDelegate(this); Init(params); SetUpViews(); #if defined(OS_CHROMEOS) GetNativeWindow()->SetProperty(ash::kWindowPipTypeKey, true); #endif // defined(OS_CHROMEOS) is_initialized_ = true; } ",0 "gfx::Point OverlayWindowViews::close_image_position_for_testing() const { return close_controls_view_->origin(); } ",0 "static MagickBooleanType GetEXIFProperty(const Image *image, const char *property) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER ""\n"" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MaxTextExtent-length, \ format"", "",arg); \ if (length >= (MaxTextExtent-1)) \ length=MaxTextExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MaxTextExtent-length, \ format"", "",(arg1),(arg2)); \ if (length >= (MaxTextExtent-1)) \ length=MaxTextExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char description[36]; } TagInfo; static const TagInfo EXIFTag[] = { { 0x001, ""exif:InteroperabilityIndex"" }, { 0x002, ""exif:InteroperabilityVersion"" }, { 0x100, ""exif:ImageWidth"" }, { 0x101, ""exif:ImageLength"" }, { 0x102, ""exif:BitsPerSample"" }, { 0x103, ""exif:Compression"" }, { 0x106, ""exif:PhotometricInterpretation"" }, { 0x10a, ""exif:FillOrder"" }, { 0x10d, ""exif:DocumentName"" }, { 0x10e, ""exif:ImageDescription"" }, { 0x10f, ""exif:Make"" }, { 0x110, ""exif:Model"" }, { 0x111, ""exif:StripOffsets"" }, { 0x112, ""exif:Orientation"" }, { 0x115, ""exif:SamplesPerPixel"" }, { 0x116, ""exif:RowsPerStrip"" }, { 0x117, ""exif:StripByteCounts"" }, { 0x11a, ""exif:XResolution"" }, { 0x11b, ""exif:YResolution"" }, { 0x11c, ""exif:PlanarConfiguration"" }, { 0x11d, ""exif:PageName"" }, { 0x11e, ""exif:XPosition"" }, { 0x11f, ""exif:YPosition"" }, { 0x118, ""exif:MinSampleValue"" }, { 0x119, ""exif:MaxSampleValue"" }, { 0x120, ""exif:FreeOffsets"" }, { 0x121, ""exif:FreeByteCounts"" }, { 0x122, ""exif:GrayResponseUnit"" }, { 0x123, ""exif:GrayResponseCurve"" }, { 0x124, ""exif:T4Options"" }, { 0x125, ""exif:T6Options"" }, { 0x128, ""exif:ResolutionUnit"" }, { 0x12d, ""exif:TransferFunction"" }, { 0x131, ""exif:Software"" }, { 0x132, ""exif:DateTime"" }, { 0x13b, ""exif:Artist"" }, { 0x13e, ""exif:WhitePoint"" }, { 0x13f, ""exif:PrimaryChromaticities"" }, { 0x140, ""exif:ColorMap"" }, { 0x141, ""exif:HalfToneHints"" }, { 0x142, ""exif:TileWidth"" }, { 0x143, ""exif:TileLength"" }, { 0x144, ""exif:TileOffsets"" }, { 0x145, ""exif:TileByteCounts"" }, { 0x14a, ""exif:SubIFD"" }, { 0x14c, ""exif:InkSet"" }, { 0x14d, ""exif:InkNames"" }, { 0x14e, ""exif:NumberOfInks"" }, { 0x150, ""exif:DotRange"" }, { 0x151, ""exif:TargetPrinter"" }, { 0x152, ""exif:ExtraSample"" }, { 0x153, ""exif:SampleFormat"" }, { 0x154, ""exif:SMinSampleValue"" }, { 0x155, ""exif:SMaxSampleValue"" }, { 0x156, ""exif:TransferRange"" }, { 0x157, ""exif:ClipPath"" }, { 0x158, ""exif:XClipPathUnits"" }, { 0x159, ""exif:YClipPathUnits"" }, { 0x15a, ""exif:Indexed"" }, { 0x15b, ""exif:JPEGTables"" }, { 0x15f, ""exif:OPIProxy"" }, { 0x200, ""exif:JPEGProc"" }, { 0x201, ""exif:JPEGInterchangeFormat"" }, { 0x202, ""exif:JPEGInterchangeFormatLength"" }, { 0x203, ""exif:JPEGRestartInterval"" }, { 0x205, ""exif:JPEGLosslessPredictors"" }, { 0x206, ""exif:JPEGPointTransforms"" }, { 0x207, ""exif:JPEGQTables"" }, { 0x208, ""exif:JPEGDCTables"" }, { 0x209, ""exif:JPEGACTables"" }, { 0x211, ""exif:YCbCrCoefficients"" }, { 0x212, ""exif:YCbCrSubSampling"" }, { 0x213, ""exif:YCbCrPositioning"" }, { 0x214, ""exif:ReferenceBlackWhite"" }, { 0x2bc, ""exif:ExtensibleMetadataPlatform"" }, { 0x301, ""exif:Gamma"" }, { 0x302, ""exif:ICCProfileDescriptor"" }, { 0x303, ""exif:SRGBRenderingIntent"" }, { 0x320, ""exif:ImageTitle"" }, { 0x5001, ""exif:ResolutionXUnit"" }, { 0x5002, ""exif:ResolutionYUnit"" }, { 0x5003, ""exif:ResolutionXLengthUnit"" }, { 0x5004, ""exif:ResolutionYLengthUnit"" }, { 0x5005, ""exif:PrintFlags"" }, { 0x5006, ""exif:PrintFlagsVersion"" }, { 0x5007, ""exif:PrintFlagsCrop"" }, { 0x5008, ""exif:PrintFlagsBleedWidth"" }, { 0x5009, ""exif:PrintFlagsBleedWidthScale"" }, { 0x500A, ""exif:HalftoneLPI"" }, { 0x500B, ""exif:HalftoneLPIUnit"" }, { 0x500C, ""exif:HalftoneDegree"" }, { 0x500D, ""exif:HalftoneShape"" }, { 0x500E, ""exif:HalftoneMisc"" }, { 0x500F, ""exif:HalftoneScreen"" }, { 0x5010, ""exif:JPEGQuality"" }, { 0x5011, ""exif:GridSize"" }, { 0x5012, ""exif:ThumbnailFormat"" }, { 0x5013, ""exif:ThumbnailWidth"" }, { 0x5014, ""exif:ThumbnailHeight"" }, { 0x5015, ""exif:ThumbnailColorDepth"" }, { 0x5016, ""exif:ThumbnailPlanes"" }, { 0x5017, ""exif:ThumbnailRawBytes"" }, { 0x5018, ""exif:ThumbnailSize"" }, { 0x5019, ""exif:ThumbnailCompressedSize"" }, { 0x501a, ""exif:ColorTransferFunction"" }, { 0x501b, ""exif:ThumbnailData"" }, { 0x5020, ""exif:ThumbnailImageWidth"" }, { 0x5021, ""exif:ThumbnailImageHeight"" }, { 0x5022, ""exif:ThumbnailBitsPerSample"" }, { 0x5023, ""exif:ThumbnailCompression"" }, { 0x5024, ""exif:ThumbnailPhotometricInterp"" }, { 0x5025, ""exif:ThumbnailImageDescription"" }, { 0x5026, ""exif:ThumbnailEquipMake"" }, { 0x5027, ""exif:ThumbnailEquipModel"" }, { 0x5028, ""exif:ThumbnailStripOffsets"" }, { 0x5029, ""exif:ThumbnailOrientation"" }, { 0x502a, ""exif:ThumbnailSamplesPerPixel"" }, { 0x502b, ""exif:ThumbnailRowsPerStrip"" }, { 0x502c, ""exif:ThumbnailStripBytesCount"" }, { 0x502d, ""exif:ThumbnailResolutionX"" }, { 0x502e, ""exif:ThumbnailResolutionY"" }, { 0x502f, ""exif:ThumbnailPlanarConfig"" }, { 0x5030, ""exif:ThumbnailResolutionUnit"" }, { 0x5031, ""exif:ThumbnailTransferFunction"" }, { 0x5032, ""exif:ThumbnailSoftwareUsed"" }, { 0x5033, ""exif:ThumbnailDateTime"" }, { 0x5034, ""exif:ThumbnailArtist"" }, { 0x5035, ""exif:ThumbnailWhitePoint"" }, { 0x5036, ""exif:ThumbnailPrimaryChromaticities"" }, { 0x5037, ""exif:ThumbnailYCbCrCoefficients"" }, { 0x5038, ""exif:ThumbnailYCbCrSubsampling"" }, { 0x5039, ""exif:ThumbnailYCbCrPositioning"" }, { 0x503A, ""exif:ThumbnailRefBlackWhite"" }, { 0x503B, ""exif:ThumbnailCopyRight"" }, { 0x5090, ""exif:LuminanceTable"" }, { 0x5091, ""exif:ChrominanceTable"" }, { 0x5100, ""exif:FrameDelay"" }, { 0x5101, ""exif:LoopCount"" }, { 0x5110, ""exif:PixelUnit"" }, { 0x5111, ""exif:PixelPerUnitX"" }, { 0x5112, ""exif:PixelPerUnitY"" }, { 0x5113, ""exif:PaletteHistogram"" }, { 0x1000, ""exif:RelatedImageFileFormat"" }, { 0x1001, ""exif:RelatedImageLength"" }, { 0x1002, ""exif:RelatedImageWidth"" }, { 0x800d, ""exif:ImageID"" }, { 0x80e3, ""exif:Matteing"" }, { 0x80e4, ""exif:DataType"" }, { 0x80e5, ""exif:ImageDepth"" }, { 0x80e6, ""exif:TileDepth"" }, { 0x828d, ""exif:CFARepeatPatternDim"" }, { 0x828e, ""exif:CFAPattern2"" }, { 0x828f, ""exif:BatteryLevel"" }, { 0x8298, ""exif:Copyright"" }, { 0x829a, ""exif:ExposureTime"" }, { 0x829d, ""exif:FNumber"" }, { 0x83bb, ""exif:IPTC/NAA"" }, { 0x84e3, ""exif:IT8RasterPadding"" }, { 0x84e5, ""exif:IT8ColorTable"" }, { 0x8649, ""exif:ImageResourceInformation"" }, { 0x8769, ""exif:ExifOffset"" }, /* specs as ""Exif IFD Pointer""? */ { 0x8773, ""exif:InterColorProfile"" }, { 0x8822, ""exif:ExposureProgram"" }, { 0x8824, ""exif:SpectralSensitivity"" }, { 0x8825, ""exif:GPSInfo"" }, /* specs as ""GPSInfo IFD Pointer""? */ { 0x8827, ""exif:PhotographicSensitivity"" }, { 0x8828, ""exif:OECF"" }, { 0x8829, ""exif:Interlace"" }, { 0x882a, ""exif:TimeZoneOffset"" }, { 0x882b, ""exif:SelfTimerMode"" }, { 0x8830, ""exif:SensitivityType"" }, { 0x8831, ""exif:StandardOutputSensitivity"" }, { 0x8832, ""exif:RecommendedExposureIndex"" }, { 0x8833, ""exif:ISOSpeed"" }, { 0x8834, ""exif:ISOSpeedLatitudeyyy"" }, { 0x8835, ""exif:ISOSpeedLatitudezzz"" }, { 0x9000, ""exif:ExifVersion"" }, { 0x9003, ""exif:DateTimeOriginal"" }, { 0x9004, ""exif:DateTimeDigitized"" }, { 0x9010, ""exif:OffsetTime"" }, { 0x9011, ""exif:OffsetTimeOriginal"" }, { 0x9012, ""exif:OffsetTimeDigitized"" }, { 0x9101, ""exif:ComponentsConfiguration"" }, { 0x9102, ""exif:CompressedBitsPerPixel"" }, { 0x9201, ""exif:ShutterSpeedValue"" }, { 0x9202, ""exif:ApertureValue"" }, { 0x9203, ""exif:BrightnessValue"" }, { 0x9204, ""exif:ExposureBiasValue"" }, { 0x9205, ""exif:MaxApertureValue"" }, { 0x9206, ""exif:SubjectDistance"" }, { 0x9207, ""exif:MeteringMode"" }, { 0x9208, ""exif:LightSource"" }, { 0x9209, ""exif:Flash"" }, { 0x920a, ""exif:FocalLength"" }, { 0x920b, ""exif:FlashEnergy"" }, { 0x920c, ""exif:SpatialFrequencyResponse"" }, { 0x920d, ""exif:Noise"" }, { 0x9214, ""exif:SubjectArea"" }, { 0x9290, ""exif:SubSecTime"" }, { 0x9291, ""exif:SubSecTimeOriginal"" }, { 0x9292, ""exif:SubSecTimeDigitized"" }, { 0x9211, ""exif:ImageNumber"" }, { 0x9212, ""exif:SecurityClassification"" }, { 0x9213, ""exif:ImageHistory"" }, { 0x9214, ""exif:SubjectArea"" }, { 0x9215, ""exif:ExposureIndex"" }, { 0x9216, ""exif:TIFF-EPStandardID"" }, { 0x927c, ""exif:MakerNote"" }, { 0x9286, ""exif:UserComment"" }, { 0x9290, ""exif:SubSecTime"" }, { 0x9291, ""exif:SubSecTimeOriginal"" }, { 0x9292, ""exif:SubSecTimeDigitized"" }, { 0x9400, ""exif:Temperature"" }, { 0x9401, ""exif:Humidity"" }, { 0x9402, ""exif:Pressure"" }, { 0x9403, ""exif:WaterDepth"" }, { 0x9404, ""exif:Acceleration"" }, { 0x9405, ""exif:CameraElevationAngle"" }, { 0x9C9b, ""exif:WinXP-Title"" }, { 0x9C9c, ""exif:WinXP-Comments"" }, { 0x9C9d, ""exif:WinXP-Author"" }, { 0x9C9e, ""exif:WinXP-Keywords"" }, { 0x9C9f, ""exif:WinXP-Subject"" }, { 0xa000, ""exif:FlashPixVersion"" }, { 0xa001, ""exif:ColorSpace"" }, { 0xa002, ""exif:PixelXDimension"" }, { 0xa003, ""exif:PixelYDimension"" }, { 0xa004, ""exif:RelatedSoundFile"" }, { 0xa005, ""exif:InteroperabilityOffset"" }, { 0xa20b, ""exif:FlashEnergy"" }, { 0xa20c, ""exif:SpatialFrequencyResponse"" }, { 0xa20d, ""exif:Noise"" }, { 0xa20e, ""exif:FocalPlaneXResolution"" }, { 0xa20f, ""exif:FocalPlaneYResolution"" }, { 0xa210, ""exif:FocalPlaneResolutionUnit"" }, { 0xa214, ""exif:SubjectLocation"" }, { 0xa215, ""exif:ExposureIndex"" }, { 0xa216, ""exif:TIFF/EPStandardID"" }, { 0xa217, ""exif:SensingMethod"" }, { 0xa300, ""exif:FileSource"" }, { 0xa301, ""exif:SceneType"" }, { 0xa302, ""exif:CFAPattern"" }, { 0xa401, ""exif:CustomRendered"" }, { 0xa402, ""exif:ExposureMode"" }, { 0xa403, ""exif:WhiteBalance"" }, { 0xa404, ""exif:DigitalZoomRatio"" }, { 0xa405, ""exif:FocalLengthIn35mmFilm"" }, { 0xa406, ""exif:SceneCaptureType"" }, { 0xa407, ""exif:GainControl"" }, { 0xa408, ""exif:Contrast"" }, { 0xa409, ""exif:Saturation"" }, { 0xa40a, ""exif:Sharpness"" }, { 0xa40b, ""exif:DeviceSettingDescription"" }, { 0xa40c, ""exif:SubjectDistanceRange"" }, { 0xa420, ""exif:ImageUniqueID"" }, { 0xa430, ""exif:CameraOwnerName"" }, { 0xa431, ""exif:BodySerialNumber"" }, { 0xa432, ""exif:LensSpecification"" }, { 0xa433, ""exif:LensMake"" }, { 0xa434, ""exif:LensModel"" }, { 0xa435, ""exif:LensSerialNumber"" }, { 0xc4a5, ""exif:PrintImageMatching"" }, { 0xa500, ""exif:Gamma"" }, { 0xc640, ""exif:CR2Slice"" }, { 0x10000, ""exif:GPSVersionID"" }, { 0x10001, ""exif:GPSLatitudeRef"" }, { 0x10002, ""exif:GPSLatitude"" }, { 0x10003, ""exif:GPSLongitudeRef"" }, { 0x10004, ""exif:GPSLongitude"" }, { 0x10005, ""exif:GPSAltitudeRef"" }, { 0x10006, ""exif:GPSAltitude"" }, { 0x10007, ""exif:GPSTimeStamp"" }, { 0x10008, ""exif:GPSSatellites"" }, { 0x10009, ""exif:GPSStatus"" }, { 0x1000a, ""exif:GPSMeasureMode"" }, { 0x1000b, ""exif:GPSDop"" }, { 0x1000c, ""exif:GPSSpeedRef"" }, { 0x1000d, ""exif:GPSSpeed"" }, { 0x1000e, ""exif:GPSTrackRef"" }, { 0x1000f, ""exif:GPSTrack"" }, { 0x10010, ""exif:GPSImgDirectionRef"" }, { 0x10011, ""exif:GPSImgDirection"" }, { 0x10012, ""exif:GPSMapDatum"" }, { 0x10013, ""exif:GPSDestLatitudeRef"" }, { 0x10014, ""exif:GPSDestLatitude"" }, { 0x10015, ""exif:GPSDestLongitudeRef"" }, { 0x10016, ""exif:GPSDestLongitude"" }, { 0x10017, ""exif:GPSDestBearingRef"" }, { 0x10018, ""exif:GPSDestBearing"" }, { 0x10019, ""exif:GPSDestDistanceRef"" }, { 0x1001a, ""exif:GPSDestDistance"" }, { 0x1001b, ""exif:GPSProcessingMethod"" }, { 0x1001c, ""exif:GPSAreaInformation"" }, { 0x1001d, ""exif:GPSDateStamp"" }, { 0x1001e, ""exif:GPSDifferential"" }, { 0x1001f, ""exif:GPSHPositioningError"" }, { 0x00000, """" } }; /* http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf */ const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,""exif""); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); if (length < 6) return(MagickFalse); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; if (format == 0) break; /* corrupt EXIF */ components=(ssize_t) ReadPropertySignedLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t dir_offset; /* The directory entry contains an offset. */ dir_offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((dir_offset < 0) || (size_t) dir_offset >= length) continue; if (((size_t) dir_offset+number_bytes) < (size_t) dir_offset) continue; /* prevent overflow */ if (((size_t) dir_offset+number_bytes) > length) continue; p=(unsigned char *) (exif+dir_offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MaxTextExtent], *value; if ((p < exif) || (p > (exif+length-tag_bytes[format]))) break; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if (isprint((int) p[i]) != 0) value[i]=(char) p[i]; } value[i]='\0'; } break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,""%.20g"",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,""%hd"",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,""%hu"",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,""%.20g"",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,""%.20g"",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,""%.20g/%.20g"",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,""%.20g/%.20g"",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,""%f"",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,""%f"",*(double *) p1); break; } case EXIF_FMT_STRING: default: { if ((p < exif) || (p > (exif+length-number_bytes))) break; value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; ssize_t i; description=""unknown""; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MaxTextExtent,""%s"", description); if (level == 2) (void) SubstituteString(&key,""exif:"",""exif:thumbnail:""); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MaxTextExtent,""#%04lx"", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MaxTextExtent,""@%04lx"", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MaxTextExtent,""unknown""); break; } default: { if (level == 2) (void) SubstituteString(&key,""exif:"",""exif:thumbnail:""); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; /* Check for duplicate tag. */ for (i=0; i < level; i++) if (directory_stack[i].directory == (exif+tag_offset1)) break; if (i < level) break; /* duplicate tag */ directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)+4) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); }",1 "static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; const unsigned char *p; IndexPacket *indexes; PixelPacket *q; ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType)QuantumRange*nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,indexes,x); q++; } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); }",1 "Status ImmutableExecutorState::Initialize(const Graph& graph) { TF_RETURN_IF_ERROR(gview_.Initialize(&graph)); // Build the information about frames in this subgraph. ControlFlowInfo cf_info; TF_RETURN_IF_ERROR(BuildControlFlowInfo(&graph, &cf_info)); for (auto& it : cf_info.unique_frame_names) { EnsureFrameInfo(it)->nodes = absl::make_unique>(); } root_frame_info_ = frame_info_[""""].get(); pending_ids_.resize(gview_.num_nodes()); // Preprocess every node in the graph to create an instance of op // kernel for each node. requires_control_flow_ = false; for (const Node* n : graph.nodes()) { if (IsSink(n)) continue; if (IsSwitch(n) || IsMerge(n) || IsEnter(n) || IsExit(n)) { requires_control_flow_ = true; } else if (IsRecv(n)) { // A Recv node from a different device may produce dead tensors from // non-local control-flow nodes. // // TODO(mrry): Track whether control flow was present in the // pre-partitioned graph, and enable the caller (e.g. // `DirectSession`) to relax this constraint. string send_device; string recv_device; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), ""send_device"", &send_device)); TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), ""recv_device"", &recv_device)); if (send_device != recv_device) { requires_control_flow_ = true; } } const int id = n->id(); const string& frame_name = cf_info.frame_names[id]; FrameInfo* frame_info = EnsureFrameInfo(frame_name); NodeItem* item = gview_.node(id); item->node_id = id; item->input_start = frame_info->total_inputs; frame_info->total_inputs += n->num_inputs(); Status s = params_.create_kernel(n->properties(), &item->kernel); if (!s.ok()) { item->kernel = nullptr; s = AttachDef(s, *n); return s; } CHECK(item->kernel); item->kernel_is_async = (item->kernel->AsAsync() != nullptr); item->is_merge = IsMerge(n); item->is_any_consumer_merge_or_control_trigger = false; for (const Node* consumer : n->out_nodes()) { if (IsMerge(consumer) || IsControlTrigger(consumer)) { item->is_any_consumer_merge_or_control_trigger = true; break; } } const Tensor* const_tensor = item->kernel->const_tensor(); if (const_tensor) { // Hold onto a shallow copy of the constant tensor in `*this` so that the // reference count does not drop to 1. This prevents the constant tensor // from being forwarded, and its buffer reused. const_tensors_.emplace_back(*const_tensor); } item->const_tensor = const_tensor; item->is_noop = (item->kernel->type_string_view() == ""NoOp""); item->is_enter = IsEnter(n); if (item->is_enter) { bool is_constant_enter; TF_RETURN_IF_ERROR( GetNodeAttr(n->attrs(), ""is_constant"", &is_constant_enter)); item->is_constant_enter = is_constant_enter; string frame_name; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), ""frame_name"", &frame_name)); FrameInfo* frame_info = frame_info_[frame_name].get(); int parallel_iterations; TF_RETURN_IF_ERROR( GetNodeAttr(n->attrs(), ""parallel_iterations"", ¶llel_iterations)); if (frame_info->parallel_iterations == -1) { frame_info->parallel_iterations = parallel_iterations; } else if (frame_info->parallel_iterations != parallel_iterations) { LOG(WARNING) << ""Loop frame \"""" << frame_name << ""\"" had two different values for parallel_iterations: "" << frame_info->parallel_iterations << "" vs. "" << parallel_iterations << "".""; } if (enter_frame_info_.size() <= id) { enter_frame_info_.resize(id + 1); } enter_frame_info_[id] = frame_info; } else { item->is_constant_enter = false; } item->is_exit = IsExit(n); item->is_control_trigger = IsControlTrigger(n); item->is_source = IsSource(n); item->is_enter_exit_or_next_iter = (IsEnter(n) || IsExit(n) || IsNextIteration(n)); item->is_transfer_node = IsTransferNode(n); item->is_initialization_op = IsInitializationOp(n); item->is_recv_or_switch = IsRecv(n) || IsSwitch(n); item->is_next_iteration = IsNextIteration(n); item->is_distributed_communication = IsDistributedCommunication(n); // Compute the maximum values we'll store for this node in the // pending counts data structure, and allocate a handle in // that frame's pending counts data structure that has enough // space to store these maximal count values. size_t max_pending, max_dead; GetMaxPendingCounts(n, &max_pending, &max_dead); pending_ids_[id] = frame_info->pending_counts_layout.CreateHandle(max_pending, max_dead); // See if this node is a root node, and if so, add item to root_nodes_. if (n->in_edges().empty()) { root_nodes_.push_back(item); } // Initialize static information about the frames in the graph. frame_info->nodes->push_back(item); if (item->is_enter) { string enter_name; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), ""frame_name"", &enter_name)); EnsureFrameInfo(enter_name)->input_count++; } // Record information about whether each output of the op is used. std::unique_ptr outputs_required(new bool[n->num_outputs()]); std::fill(&outputs_required[0], &outputs_required[n->num_outputs()], false); int32_t unused_outputs = n->num_outputs(); for (const Edge* e : n->out_edges()) { if (IsSink(e->dst())) continue; if (e->src_output() >= 0) { if (!outputs_required[e->src_output()]) { --unused_outputs; outputs_required[e->src_output()] = true; } } } if (unused_outputs > 0) { for (int i = 0; i < n->num_outputs(); ++i) { if (!outputs_required[i]) { metrics::RecordUnusedOutput(n->type_string()); } } item->outputs_required = std::move(outputs_required); } } // Rewrite each `EdgeInfo::input_slot` member to refer directly to the input // location. for (const Node* n : graph.nodes()) { if (IsSink(n)) continue; const int id = n->id(); NodeItem* item = gview_.node(id); for (EdgeInfo& e : item->mutable_output_edges()) { const int dst_id = e.dst_id; NodeItem* dst_item = gview_.node(dst_id); e.input_slot += dst_item->input_start; } } // Initialize PendingCounts only after pending_ids_[node.id] is initialized // for all nodes. InitializePending(&graph, cf_info); return gview_.SetAllocAttrs(&graph, params_.device); }",1 "Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def, string* init_op_name) { const auto& sig_def_map = meta_graph_def.signature_def(); const auto& init_op_sig_it = meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey); if (init_op_sig_it != sig_def_map.end()) { *init_op_name = init_op_sig_it->second.outputs() .find(kSavedModelInitOpSignatureKey) ->second.name(); return Status::OK(); } const auto& collection_def_map = meta_graph_def.collection_def(); string init_op_collection_key; if (collection_def_map.find(kSavedModelMainOpKey) != collection_def_map.end()) { init_op_collection_key = kSavedModelMainOpKey; } else { init_op_collection_key = kSavedModelLegacyInitOpKey; } const auto init_op_it = collection_def_map.find(init_op_collection_key); if (init_op_it != collection_def_map.end()) { if (init_op_it->second.node_list().value_size() != 1) { return errors::FailedPrecondition( strings::StrCat(""Expected exactly one main op in : "", export_dir)); } *init_op_name = init_op_it->second.node_list().value(0); } return Status::OK(); }",1 "Status ConstantFolding::IsSimplifiableReshape( const NodeDef& node, const GraphProperties& properties) const { if (!IsReshape(node)) { return errors::Internal(""Node "", node.name(), "" is not a Reshape node""); } if (2 > node.input_size()) { return errors::Internal(""Node "", node.name(), "" must have at most 2 inputs but has "", node.input_size()); } const NodeDef* new_shape = node_map_->GetNode(node.input(1)); if (!IsReallyConstant(*new_shape)) { return errors::Internal(""Node "", node.name(), "" has shape "", new_shape->DebugString(), "" which is not a constant""); } TensorVector outputs; auto outputs_cleanup = gtl::MakeCleanup([&outputs] { for (const auto& output : outputs) { delete output.tensor; } }); Status s = EvaluateNode(*new_shape, TensorVector(), &outputs); if (!s.ok()) { return errors::Internal(""Could not evaluate node "", node.name()); } if (outputs.size() != 1) { return errors::Internal(""Node "", node.name(), "" must have exactly 1 output but has "", outputs.size()); } const std::vector& props = properties.GetInputProperties(node.name()); if (props.empty()) { return errors::Internal(""Node "", node.name(), "" has no properties""); } const OpInfo::TensorProperties& prop = props[0]; if (prop.dtype() == DT_INVALID) { return errors::Internal(""Node "", node.name(), "" has property "", prop.DebugString(), "" with invalid dtype""); } const PartialTensorShape shape(prop.shape()); if (!shape.IsFullyDefined()) { return errors::Internal(""Node "", node.name(), "" has property "", prop.DebugString(), "" with shape "", shape.DebugString(), "" which is not fully defined""); } PartialTensorShape new_dims; if (outputs[0]->dtype() == DT_INT32) { std::vector shp; for (int i = 0; i < outputs[0]->NumElements(); ++i) { int32_t dim = outputs[0]->flat()(i); shp.push_back(dim); } TF_CHECK_OK(TensorShapeUtils::MakeShape(shp, &new_dims)); } else { std::vector shp; for (int i = 0; i < outputs[0]->NumElements(); ++i) { int64_t dim = outputs[0]->flat()(i); shp.push_back(dim); } TF_CHECK_OK(TensorShapeUtils::MakeShape(shp, &new_dims)); } if (!shape.IsCompatibleWith(new_dims)) { return errors::Internal(""Expected shape "", shape.DebugString(), ""to be compatible with "", new_dims.DebugString()); } return Status::OK(); }",1 "u32 GetHintFormat(GF_TrackBox *trak) { GF_HintMediaHeaderBox *hmhd = (GF_HintMediaHeaderBox *)trak->Media->information->InfoHeader; if (hmhd->type != GF_ISOM_BOX_TYPE_HMHD) return 0; if (!hmhd || !hmhd->subType) { GF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, 0); if (!hmhd) return a ? a->type : 0; if (a) hmhd->subType = a->type; return hmhd->subType; } return hmhd->subType; }",1 "Status ConstantFolding::EvaluateOneFoldable(const NodeDef& node, std::vector* outputs, bool* result_too_large) { TensorVector inputs; TensorVector output_tensors; auto inputs_cleanup = gtl::MakeCleanup([&inputs, &output_tensors] { for (const auto& input : inputs) { delete input.tensor; } for (const auto& output : output_tensors) { if (output.tensor) { delete output.tensor; } } }); size_t total_inputs_size = 0; for (const auto& input : node.input()) { const TensorId input_tensor = ParseTensorName(input); if (input_tensor.index() < 0) { // Control dependency break; } const NodeDef* input_node = node_map_->GetNode(input); if (!IsReallyConstant(*input_node)) { return Status(error::INVALID_ARGUMENT, strings::StrCat(""Can't fold "", node.name(), "", its "", input, "" isn't constant"")); } TF_RETURN_IF_ERROR(CheckAttrExists(*input_node, ""value"")); const TensorProto& raw_val = input_node->attr().at(""value"").tensor(); if (raw_val.dtype() == DT_INVALID) { return Status( error::INVALID_ARGUMENT, strings::StrCat(""A tensor in the input node, with TensorId of "", input_tensor.ToString(), "" has a dtype of DT_INVALID."")); } Tensor* value = new Tensor(raw_val.dtype(), raw_val.tensor_shape()); if (!value->FromProto(raw_val)) { delete (value); return errors::InvalidArgument(""Unable to make Tensor from proto for "", node.name(), "" with shape "", raw_val.tensor_shape().DebugString()); } inputs.emplace_back(value); total_inputs_size += value->TotalBytes(); } TF_RETURN_IF_ERROR(EvaluateNode(node, inputs, &output_tensors)); if (output_tensors.empty()) { return Status(error::INVALID_ARGUMENT, ""Expected at least one output.""); } outputs->resize(output_tensors.size()); for (size_t i = 0; i < output_tensors.size(); i++) { string node_name = OptimizedNodeName(node, ""-folded""); if (output_tensors.size() > 1) { node_name = strings::StrCat(node_name, ""-"", i); } if (output_tensors[i].tensor) { Status s = CreateNodeDef(node_name, output_tensors[i], &outputs->at(i), total_inputs_size); if (!s.ok()) { *result_too_large = true; return s; } } else { // Create an empty NodeDef to identify dead outputs (e.g. the output of a // switch that's not selected by the switch predicate). outputs->at(i) = NodeDef(); } } return Status::OK(); }",1 "int callback_glewlwyd_user_auth (const struct _u_request * request, struct _u_response * response, void * user_data) { struct config_elements * config = (struct config_elements *)user_data; json_t * j_param = ulfius_get_json_body_request(request, NULL), * j_result = NULL; const char * ip_source = get_ip_source(request); char * issued_for = get_client_hostname(request); char * session_uid, expires[129]; time_t now; struct tm ts; time(&now); now += GLEWLWYD_DEFAULT_SESSION_EXPIRATION_COOKIE; gmtime_r(&now, &ts); strftime(expires, 128, ""%a, %d %b %Y %T %Z"", &ts); if (j_param != NULL) { if (json_string_length(json_object_get(j_param, ""username""))) { if (json_object_get(j_param, ""scheme_type"") == NULL || 0 == o_strcmp(json_string_value(json_object_get(j_param, ""scheme_type"")), ""password"")) { if (json_string_length(json_object_get(j_param, ""password""))) { j_result = auth_check_user_credentials(config, json_string_value(json_object_get(j_param, ""username"")), json_string_value(json_object_get(j_param, ""password""))); if (check_result_value(j_result, G_OK)) { if ((session_uid = get_session_id(config, request)) == NULL) { session_uid = generate_session_id(); } if (user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), NULL, 1) != G_OK) { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (1)""); response->status = 500; } else { ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0); y_log_message(Y_LOG_LEVEL_INFO, ""Event - User '%s' authenticated with password"", json_string_value(json_object_get(j_param, ""username""))); } o_free(session_uid); glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL); glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, ""scheme_type"", ""password"", NULL); } else { if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) { y_log_message(Y_LOG_LEVEL_WARNING, ""Security - Authorization invalid for username %s at IP Address %s"", json_string_value(json_object_get(j_param, ""username"")), ip_source); } if ((session_uid = get_session_id(config, request)) != NULL && user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), NULL, 1) != G_OK) { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (2)""); } o_free(session_uid); response->status = 401; glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL); glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, ""scheme_type"", ""password"", NULL); } json_decref(j_result); } else if (json_object_get(j_param, ""password"") != NULL && !json_is_string(json_object_get(j_param, ""password""))) { ulfius_set_string_body_response(response, 400, ""password must be a string""); } else { session_uid = get_session_id(config, request); j_result = get_users_for_session(config, session_uid); if (check_result_value(j_result, G_OK)) { // Refresh username to set as default if (user_session_update(config, u_map_get(request->map_cookie, config->session_key), u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), NULL, 0) != G_OK) { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (3)""); response->status = 500; } else { ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0); } } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) { response->status = 401; } else { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error get_users_for_session""); response->status = 500; } o_free(session_uid); json_decref(j_result); } } else { if (json_string_length(json_object_get(j_param, ""scheme_type"")) && json_string_length(json_object_get(j_param, ""scheme_name"")) && json_is_object(json_object_get(j_param, ""value""))) { j_result = auth_check_user_scheme(config, json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name"")), json_string_value(json_object_get(j_param, ""username"")), json_object_get(j_param, ""value""), request); if (check_result_value(j_result, G_ERROR_PARAM)) { ulfius_set_string_body_response(response, 400, ""bad scheme response""); } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) { y_log_message(Y_LOG_LEVEL_WARNING, ""Security - Authorization invalid for username %s at IP Address %s"", json_string_value(json_object_get(j_param, ""username"")), ip_source); response->status = 401; glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL); glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, ""scheme_type"", json_string_value(json_object_get(j_param, ""scheme_type"")), ""scheme_name"", json_string_value(json_object_get(j_param, ""scheme_name"")), NULL); } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) { response->status = 404; } else if (check_result_value(j_result, G_OK)) { if ((session_uid = get_session_id(config, request)) == NULL) { session_uid = generate_session_id(); } if (user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), json_string_value(json_object_get(j_param, ""scheme_name"")), 1) != G_OK) { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (4)""); response->status = 500; } else { ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0); y_log_message(Y_LOG_LEVEL_INFO, ""Event - User '%s' authenticated with scheme '%s/%s'"", json_string_value(json_object_get(j_param, ""username"")), json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name""))); } o_free(session_uid); glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL); glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, ""scheme_type"", json_string_value(json_object_get(j_param, ""scheme_type"")), ""scheme_name"", json_string_value(json_object_get(j_param, ""scheme_name"")), NULL); } else { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error auth_check_user_scheme""); response->status = 500; } json_decref(j_result); } else { ulfius_set_string_body_response(response, 400, ""scheme_type, scheme_name and value are mandatory""); } } } else { if (json_string_length(json_object_get(j_param, ""scheme_type"")) && json_string_length(json_object_get(j_param, ""scheme_name"")) && json_is_object(json_object_get(j_param, ""value""))) { j_result = auth_check_identify_scheme(config, json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name"")), json_object_get(j_param, ""value""), request); if (check_result_value(j_result, G_ERROR_PARAM)) { ulfius_set_string_body_response(response, 400, ""bad scheme response""); } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) { y_log_message(Y_LOG_LEVEL_WARNING, ""Security - Authorization invalid for username at IP Address %s"", ip_source); response->status = 401; } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) { response->status = 404; } else if (check_result_value(j_result, G_OK)) { if ((session_uid = get_session_id(config, request)) == NULL) { session_uid = generate_session_id(); } if (user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_result, ""username"")), json_string_value(json_object_get(j_param, ""scheme_name"")), 1) != G_OK) { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (4)""); response->status = 500; } else { ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0); y_log_message(Y_LOG_LEVEL_INFO, ""Event - User '%s' authenticated with scheme '%s/%s'"", json_string_value(json_object_get(j_result, ""username"")), json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name""))); } o_free(session_uid); } else { y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error auth_check_user_scheme""); response->status = 500; } json_decref(j_result); } else { ulfius_set_string_body_response(response, 400, ""username is mandatory""); } } } else { ulfius_set_string_body_response(response, 400, ""Input parameters must be in JSON format""); } json_decref(j_param); o_free(issued_for); return U_CALLBACK_CONTINUE; }",1 " void Compute(OpKernelContext* context) override { const Tensor* input_indices; const Tensor* input_values; const Tensor* input_shape; SparseTensorsMap* map; OP_REQUIRES_OK(context, context->input(""sparse_indices"", &input_indices)); OP_REQUIRES_OK(context, context->input(""sparse_values"", &input_values)); OP_REQUIRES_OK(context, context->input(""sparse_shape"", &input_shape)); OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map)); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()), errors::InvalidArgument( ""Input indices should be a matrix but received shape "", input_indices->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()), errors::InvalidArgument( ""Input values should be a vector but received shape "", input_values->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()), errors::InvalidArgument( ""Input shape should be a vector but received shape "", input_shape->shape().DebugString())); OP_REQUIRES( context, input_values->shape().dim_size(0) == input_indices->shape().dim_size(0), errors::InvalidArgument( ""Number of values must match first dimension of indices. "", ""Got "", input_values->shape().dim_size(0), "" values, indices shape: "", input_indices->shape().DebugString())); OP_REQUIRES( context, input_shape->shape().dim_size(0) == input_indices->shape().dim_size(1), errors::InvalidArgument( ""Number of dimensions must match second dimension of indices. "", ""Got "", input_shape->shape().dim_size(0), "" dimensions, indices shape: "", input_indices->shape().DebugString())); int rank = input_shape->NumElements(); OP_REQUIRES( context, rank > 1, errors::InvalidArgument( ""Rank of input SparseTensor should be > 1, but saw rank: "", rank)); auto input_shape_vec = input_shape->vec(); int new_num_elements = 1; bool overflow_ocurred = false; for (int i = 0; i < input_shape_vec.size(); i++) { new_num_elements = MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i)); if (new_num_elements < 0) { overflow_ocurred = true; break; } } OP_REQUIRES( context, !overflow_ocurred, errors::Internal(""Encountered overflow from large input shape."")); TensorShape tensor_input_shape(input_shape_vec); gtl::InlinedVector std_order(rank); std::iota(std_order.begin(), std_order.end(), 0); SparseTensor input_st; OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values, tensor_input_shape, std_order, &input_st)); const int64_t N = input_shape_vec(0); Tensor sparse_handles(DT_INT64, TensorShape({N})); auto sparse_handles_t = sparse_handles.vec(); OP_REQUIRES_OK(context, input_st.IndicesValid()); // We can generate the output shape proto string now, for all // minibatch entries. TensorShape output_shape; OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape( input_shape_vec.data() + 1, input_shape->NumElements() - 1, &output_shape)); // Get groups by minibatch dimension std::unordered_set visited; sparse::GroupIterable minibatch = input_st.group({0}); for (const auto& subset : minibatch) { const int64_t b = subset.group()[0]; visited.insert(b); OP_REQUIRES( context, b > -1 && b < N, errors::InvalidArgument( ""Received unexpected column 0 value in input SparseTensor: "", b, "" < 0 or >= N (= "", N, "")"")); const auto indices = subset.indices(); const auto values = subset.values(); const int64_t num_entries = values.size(); Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1}); Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries}); auto output_indices_t = output_indices.matrix(); auto output_values_t = output_values.vec(); for (int i = 0; i < num_entries; ++i) { for (int d = 1; d < rank; ++d) { output_indices_t(i, d - 1) = indices(i, d); } output_values_t(i) = values(i); } SparseTensor st_i; OP_REQUIRES_OK(context, SparseTensor::Create(output_indices, output_values, output_shape, &st_i)); int64_t handle; OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle)); sparse_handles_t(b) = handle; } // Fill in any gaps; we must provide an empty ST for batch entries // the grouper didn't find. if (visited.size() < N) { Tensor empty_indices(DT_INT64, {0, rank - 1}); Tensor empty_values(DataTypeToEnum::value, {0}); SparseTensor empty_st; OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values, output_shape, &empty_st)); for (int64_t b = 0; b < N; ++b) { // We skipped this batch entry. if (visited.find(b) == visited.end()) { int64_t handle; OP_REQUIRES_OK(context, map->AddSparseTensor(context, empty_st, &handle)); sparse_handles_t(b) = handle; } } } context->set_output(0, sparse_handles); }",1 "nfs4_file_open(struct inode *inode, struct file *filp) { struct nfs_open_context *ctx; struct dentry *dentry = file_dentry(filp); struct dentry *parent = NULL; struct inode *dir; unsigned openflags = filp->f_flags; struct iattr attr; int err; /* * If no cached dentry exists or if it's negative, NFSv4 handled the * opens in ->lookup() or ->create(). * * We only get this far for a cached positive dentry. We skipped * revalidation, so handle it here by dropping the dentry and returning * -EOPENSTALE. The VFS will retry the lookup/create/open. */ dprintk(""NFS: open file(%pd2)\n"", dentry); err = nfs_check_flags(openflags); if (err) return err; if ((openflags & O_ACCMODE) == 3) return nfs_open(inode, filp); /* We can't create new files here */ openflags &= ~(O_CREAT|O_EXCL); parent = dget_parent(dentry); dir = d_inode(parent); ctx = alloc_nfs_open_context(file_dentry(filp), filp->f_mode, filp); err = PTR_ERR(ctx); if (IS_ERR(ctx)) goto out; attr.ia_valid = ATTR_OPEN; if (openflags & O_TRUNC) { attr.ia_valid |= ATTR_SIZE; attr.ia_size = 0; filemap_write_and_wait(inode->i_mapping); } inode = NFS_PROTO(dir)->open_context(dir, ctx, openflags, &attr, NULL); if (IS_ERR(inode)) { err = PTR_ERR(inode); switch (err) { default: goto out_put_ctx; case -ENOENT: case -ESTALE: case -EISDIR: case -ENOTDIR: case -ELOOP: goto out_drop; } } if (inode != d_inode(dentry)) goto out_drop; nfs_file_set_open_context(filp, ctx); nfs_fscache_open_file(inode, filp); err = 0; out_put_ctx: put_nfs_open_context(ctx); out: dput(parent); return err; out_drop: d_drop(dentry); err = -EOPENSTALE; goto out_put_ctx; }",1 " void DecodePngV2(OpKernelContext* context, StringPiece input) { int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16; png::DecodeContext decode; OP_REQUIRES( context, png::CommonInitDecode(input, channels_, channel_bits, &decode), errors::InvalidArgument(""Invalid PNG. Failed to initialize decoder."")); // Verify that width and height are not too large: // - verify width and height don't overflow int. // - width can later be multiplied by channels_ and sizeof(uint16), so // verify single dimension is not too large. // - verify when width and height are multiplied together, there are a few // bits to spare as well. const int width = static_cast(decode.width); const int height = static_cast(decode.height); const int64_t total_size = static_cast(width) * static_cast(height); if (width != static_cast(decode.width) || width <= 0 || width >= (1LL << 27) || height != static_cast(decode.height) || height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) { OP_REQUIRES(context, false, errors::InvalidArgument(""PNG size too large for int: "", decode.width, "" by "", decode.height)); } Tensor* output = nullptr; // By the existing API, we support decoding PNG with `DecodeGif` op. // We need to make sure to return 4-D shapes when using `DecodeGif`. if (op_type_ == ""DecodeGif"") { OP_REQUIRES_OK( context, context->allocate_output( 0, TensorShape({1, height, width, decode.channels}), &output)); } else { OP_REQUIRES_OK( context, context->allocate_output( 0, TensorShape({height, width, decode.channels}), &output)); } if (op_type_ == ""DecodeBmp"") { // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here // because currently `decode_(jpeg|png|gif)` ops can decode any one of // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode // anything but bmp formats. This behavior needs to be revisited. For more // details, please refer to the bug. OP_REQUIRES(context, false, errors::InvalidArgument( ""Trying to decode PNG format using DecodeBmp op. Use "" ""`decode_png` or `decode_image` instead."")); } else if (op_type_ == ""DecodeAndCropJpeg"") { OP_REQUIRES(context, false, errors::InvalidArgument( ""DecodeAndCropJpeg operation can run on JPEG only, but "" ""detected PNG."")); } if (data_type_ == DataType::DT_UINT8) { OP_REQUIRES( context, png::CommonFinishDecode( reinterpret_cast(output->flat().data()), decode.channels * width * sizeof(uint8), &decode), errors::InvalidArgument(""Invalid PNG data, size "", input.size())); } else if (data_type_ == DataType::DT_UINT16) { OP_REQUIRES( context, png::CommonFinishDecode( reinterpret_cast(output->flat().data()), decode.channels * width * sizeof(uint16), &decode), errors::InvalidArgument(""Invalid PNG data, size "", input.size())); } else if (data_type_ == DataType::DT_FLOAT) { // `png::CommonFinishDecode` does not support `float`. First allocate // uint16 buffer for the image and decode in uint16 (lossless). Wrap the // buffer in `unique_ptr` so that we don't forget to delete the buffer. std::unique_ptr buffer( new uint16[height * width * decode.channels]); OP_REQUIRES( context, png::CommonFinishDecode(reinterpret_cast(buffer.get()), decode.channels * width * sizeof(uint16), &decode), errors::InvalidArgument(""Invalid PNG data, size "", input.size())); // Convert uint16 image data to desired data type. // Use eigen threadpooling to speed up the copy operation. const auto& device = context->eigen_device(); TTypes::UnalignedConstTensor buf(buffer.get(), height, width, decode.channels); float scale = 1. / std::numeric_limits::max(); // Fill output tensor with desired dtype. output->tensor().device(device) = buf.cast() * scale; } }",1 "void Node::RunForwardTypeInference() { VLOG(4) << ""Forward type inference: "" << props_->node_def.DebugString(); if (props_->fwd_type_fn == nullptr) { return; } std::vector input_nodes(props_->input_types.size(), nullptr); std::vector input_idx(props_->input_types.size(), 0); for (const auto& edge : in_edges_) { if (edge->IsControlEdge()) { continue; } DCHECK(edge->dst_input() < input_nodes.size()) << DebugString(); int i = edge->dst_input(); input_nodes.at(i) = edge->src(); input_idx.at(i) = edge->src_output(); } // Note: technically, we could use a very generic type when some of the inputs // are unknown. But there is an expectation that a node will have complete // inputs soon, so updating intermediate types is largely unnecessary. for (const auto* node : input_nodes) { if (node == nullptr) { // Incomplete inputs, bail. ClearTypeInfo(); return; } } static FullTypeDef* no_type = new FullTypeDef(); std::vector> input_types; for (int i = 0; i < input_nodes.size(); i++) { const auto* node = input_nodes[i]; if (node->def().has_experimental_type()) { const auto& node_t = node->def().experimental_type(); if (node_t.type_id() != TFT_UNSET) { int ix = input_idx[i]; DCHECK(ix < node_t.args_size()) << ""input "" << i << "" should have an output "" << ix << "" but instead only has "" << node_t.args_size() << "" outputs: "" << node_t.DebugString(); input_types.emplace_back(node_t.args(ix)); } else { input_types.emplace_back(*no_type); } } else { // Incomplete inputs, bail. ClearTypeInfo(); return; } } const auto infer_type = props_->fwd_type_fn(input_types); const FullTypeDef infer_typedef = infer_type.ValueOrDie(); if (infer_typedef.type_id() != TFT_UNSET) { MaybeCopyOnWrite(); *(props_->node_def.mutable_experimental_type()) = infer_typedef; } }",1 " void Compute(OpKernelContext* context) override { const Tensor* input_indices; const Tensor* input_values; const Tensor* input_shape; SparseTensorsMap* map; OP_REQUIRES_OK(context, context->input(""sparse_indices"", &input_indices)); OP_REQUIRES_OK(context, context->input(""sparse_values"", &input_values)); OP_REQUIRES_OK(context, context->input(""sparse_shape"", &input_shape)); OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map)); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()), errors::InvalidArgument( ""Input indices should be a matrix but received shape "", input_indices->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()), errors::InvalidArgument( ""Input values should be a vector but received shape "", input_values->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()), errors::InvalidArgument( ""Input shape should be a vector but received shape "", input_shape->shape().DebugString())); int rank = input_shape->NumElements(); OP_REQUIRES( context, rank > 1, errors::InvalidArgument( ""Rank of input SparseTensor should be > 1, but saw rank: "", rank)); auto input_shape_vec = input_shape->vec(); int new_num_elements = 1; bool overflow_ocurred = false; for (int i = 0; i < input_shape_vec.size(); i++) { new_num_elements = MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i)); if (new_num_elements < 0) { overflow_ocurred = true; break; } } OP_REQUIRES( context, !overflow_ocurred, errors::Internal(""Encountered overflow from large input shape."")); TensorShape tensor_input_shape(input_shape_vec); gtl::InlinedVector std_order(rank); std::iota(std_order.begin(), std_order.end(), 0); SparseTensor input_st; OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values, tensor_input_shape, std_order, &input_st)); const int64_t N = input_shape_vec(0); Tensor sparse_handles(DT_INT64, TensorShape({N})); auto sparse_handles_t = sparse_handles.vec(); OP_REQUIRES_OK(context, input_st.IndicesValid()); // We can generate the output shape proto string now, for all // minibatch entries. TensorShape output_shape; OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape( input_shape_vec.data() + 1, input_shape->NumElements() - 1, &output_shape)); // Get groups by minibatch dimension std::unordered_set visited; sparse::GroupIterable minibatch = input_st.group({0}); for (const auto& subset : minibatch) { const int64_t b = subset.group()[0]; visited.insert(b); OP_REQUIRES( context, b > -1 && b < N, errors::InvalidArgument( ""Received unexpected column 0 value in input SparseTensor: "", b, "" < 0 or >= N (= "", N, "")"")); const auto indices = subset.indices(); const auto values = subset.values(); const int64_t num_entries = values.size(); Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1}); Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries}); auto output_indices_t = output_indices.matrix(); auto output_values_t = output_values.vec(); for (int i = 0; i < num_entries; ++i) { for (int d = 1; d < rank; ++d) { output_indices_t(i, d - 1) = indices(i, d); } output_values_t(i) = values(i); } SparseTensor st_i; OP_REQUIRES_OK(context, SparseTensor::Create(output_indices, output_values, output_shape, &st_i)); int64_t handle; OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle)); sparse_handles_t(b) = handle; } // Fill in any gaps; we must provide an empty ST for batch entries // the grouper didn't find. if (visited.size() < N) { Tensor empty_indices(DT_INT64, {0, rank - 1}); Tensor empty_values(DataTypeToEnum::value, {0}); SparseTensor empty_st; OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values, output_shape, &empty_st)); for (int64_t b = 0; b < N; ++b) { // We skipped this batch entry. if (visited.find(b) == visited.end()) { int64_t handle; OP_REQUIRES_OK(context, map->AddSparseTensor(context, empty_st, &handle)); sparse_handles_t(b) = handle; } } } context->set_output(0, sparse_handles); }",1 "mrb_ary_shift_m(mrb_state *mrb, mrb_value self) { struct RArray *a = mrb_ary_ptr(self); mrb_int len = ARY_LEN(a); mrb_int n; mrb_value val; if (mrb_get_args(mrb, ""|i"", &n) == 0) { return mrb_ary_shift(mrb, self); }; ary_modify_check(mrb, a); if (len == 0 || n == 0) return mrb_ary_new(mrb); if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, ""negative array shift""); if (n > len) n = len; val = mrb_ary_new_from_values(mrb, n, ARY_PTR(a)); if (ARY_SHARED_P(a)) { L_SHIFT: a->as.heap.ptr+=n; a->as.heap.len-=n; return val; } if (len > ARY_SHIFT_SHARED_MIN) { ary_make_shared(mrb, a); goto L_SHIFT; } else if (len == n) { ARY_SET_LEN(a, 0); } else { mrb_value *ptr = ARY_PTR(a); mrb_int size = len-n; while (size--) { *ptr = *(ptr+n); ++ptr; } ARY_SET_LEN(a, len-n); } return val; }",1 " void operator()(OpKernelContext* ctx, const Tensor& input, const Tensor& filter, int row_stride, int col_stride, int row_dilation, int col_dilation, const Padding& padding, const std::vector& explicit_paddings, Tensor* output, TensorFormat data_format) { DCHECK(data_format == FORMAT_NHWC) << ""Grouped conv implementation only "" ""supports NHWC tensor format for now.""; const int64_t in_depth = input.dim_size(3); const int64_t patch_depth = filter.dim_size(2); const int64_t num_groups = in_depth / patch_depth; // Shuffle input/filter tensors to have group as a leading dimension. std::array shuffle({3, 0, 1, 2, 4}); // Compute pre shuffle dimemnsions. auto pre_shuffle = [&](const Tensor& tensor) -> std::array { return {tensor.dim_size(0), tensor.dim_size(1), tensor.dim_size(2), num_groups, tensor.dim_size(3) / num_groups}; }; // Compute post shuffle dimemnsions. auto post_shuffle = [&](const Tensor& tensor) -> std::array { return {num_groups, tensor.dim_size(0), tensor.dim_size(1), tensor.dim_size(2), tensor.dim_size(3) / num_groups}; }; auto& device = ctx->eigen_device(); absl::BlockingCounter shuffles_completed(2); auto on_shuffled = [&]() { shuffles_completed.DecrementCount(); }; // Shuffle input into temporary tensor. Tensor input_shuffled(input.dtype(), TensorShape(post_shuffle(input))); input_shuffled.tensor().device(device, on_shuffled) = input.shaped(pre_shuffle(input)).shuffle(shuffle); // Shuffle filter into temporary tensor. Tensor filter_shuffled(filter.dtype(), TensorShape(post_shuffle(filter))); filter_shuffled.tensor().device(device, on_shuffled) = filter.shaped(pre_shuffle(filter)).shuffle(shuffle); // Wait for the completion of input/filter shuffles. shuffles_completed.Wait(); // Write group convolution results into temporary output tensor. Tensor output_shuffled(output->dtype(), TensorShape(post_shuffle(*output))); for (int64_t i = 0; i < num_groups; ++i) { // TODO(ezhulenev): Run this loop using `parallelFor` (regular parallelFor // will lead to deadlock, SpatialConvolution has to use async Eigen // assignment). This requires small changes to Eigen to support async // exeuction for tensor chipping operation. // TODO(ezhulenev): Grouped convolution should also support 1x1 filter // optimization. auto input_slice = input_shuffled.tensor().template chip<0>(i); auto filter_slice = filter_shuffled.tensor().template chip<0>(i); auto output_slice = output_shuffled.tensor().template chip<0>(i); if (padding == EXPLICIT) { functor::SpatialConvolution()( ctx->eigen_device(), output_slice, input_slice, filter_slice, row_stride, col_stride, row_dilation, col_dilation, static_cast(explicit_paddings[2]), static_cast(explicit_paddings[3]), static_cast(explicit_paddings[4]), static_cast(explicit_paddings[5])); } else { functor::SpatialConvolution()( ctx->eigen_device(), output_slice, input_slice, filter_slice, row_stride, col_stride, row_dilation, col_dilation, BrainPadding2EigenPadding(padding)); } } // Shuffle temporary output back into pre-shuffled shape. std::array rev_shuffle({1, 2, 3, 0, 4}); output->shaped(pre_shuffle(*output)).device(device) = output_shuffled.tensor().shuffle(rev_shuffle); }",1 "Status BuildXlaCompilationCache(DeviceBase* device, FunctionLibraryRuntime* flr, const XlaPlatformInfo& platform_info, XlaCompilationCache** cache) { if (platform_info.xla_device_metadata()) { *cache = new XlaCompilationCache( platform_info.xla_device_metadata()->client(), platform_info.xla_device_metadata()->jit_device_type()); return Status::OK(); } auto platform = se::MultiPlatformManager::PlatformWithId(platform_info.platform_id()); if (!platform.ok()) { return platform.status(); } StatusOr compiler_for_platform = xla::Compiler::GetForPlatform(platform.ValueOrDie()); if (!compiler_for_platform.ok()) { // In some rare cases (usually in unit tests with very small clusters) we // may end up transforming an XLA cluster with at least one GPU operation // (which would normally force the cluster to be compiled using XLA:GPU) // into an XLA cluster with no GPU operations (i.e. containing only CPU // operations). Such a cluster can fail compilation (in way that // MarkForCompilation could not have detected) if the CPU JIT is not linked // in. // // So bail out of _XlaCompile in this case, and let the executor handle the // situation for us. const Status& status = compiler_for_platform.status(); if (status.code() == error::NOT_FOUND) { return errors::Unimplemented(""Could not find compiler for platform "", platform.ValueOrDie()->Name(), "": "", status.ToString()); } } xla::LocalClientOptions client_options; client_options.set_platform(platform.ValueOrDie()); client_options.set_intra_op_parallelism_threads( device->tensorflow_cpu_worker_threads()->num_threads); string allowed_gpus = flr->config_proto()->gpu_options().visible_device_list(); TF_ASSIGN_OR_RETURN(absl::optional> gpu_ids, ParseVisibleDeviceList(allowed_gpus)); client_options.set_allowed_devices(gpu_ids); auto client = xla::ClientLibrary::GetOrCreateLocalClient(client_options); if (!client.ok()) { return client.status(); } const XlaOpRegistry::DeviceRegistration* registration; if (!XlaOpRegistry::GetCompilationDevice(platform_info.device_type().type(), ®istration)) { return errors::InvalidArgument(""No JIT device registered for "", platform_info.device_type().type()); } *cache = new XlaCompilationCache( client.ValueOrDie(), DeviceType(registration->compilation_device_name)); return Status::OK(); }",1 " void Compute(OpKernelContext* context) override { const Tensor& indices = context->input(0); const Tensor& values = context->input(1); const Tensor& shape = context->input(2); const Tensor& weights = context->input(3); bool use_weights = weights.NumElements() > 0; OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()), errors::InvalidArgument( ""Input indices must be a 2-dimensional tensor. Got: "", indices.shape().DebugString())); if (use_weights) { OP_REQUIRES( context, weights.shape() == values.shape(), errors::InvalidArgument( ""Weights and values must have the same shape. Weight shape: "", weights.shape().DebugString(), ""; values shape: "", values.shape().DebugString())); } OP_REQUIRES(context, shape.NumElements() != 0, errors::InvalidArgument( ""The shape argument requires at least one element."")); bool is_1d = shape.NumElements() == 1; auto shape_vector = shape.flat(); int num_batches = is_1d ? 1 : shape_vector(0); int num_values = values.NumElements(); for (int b = 0; b < shape_vector.size(); b++) { OP_REQUIRES(context, shape_vector(b) >= 0, errors::InvalidArgument( ""Elements in dense_shape must be >= 0. Instead got:"", shape.DebugString())); } OP_REQUIRES(context, num_values == indices.shape().dim_size(0), errors::InvalidArgument( ""Number of values must match first dimension of indices."", ""Got "", num_values, "" values, indices shape: "", indices.shape().DebugString())); const auto indices_values = indices.matrix(); const auto values_values = values.flat(); const auto weight_values = weights.flat(); auto per_batch_counts = BatchedMap(num_batches); T max_value = 0; OP_REQUIRES(context, num_values <= indices.shape().dim_size(0), errors::InvalidArgument( ""The first dimension of indices must be equal to or "" ""greather than number of values. ( "", indices.shape().dim_size(0), "" vs. "", num_values, "" )"")); OP_REQUIRES(context, indices.shape().dim_size(1) > 0, errors::InvalidArgument(""The second dimension of indices must "" ""be greater than 0. Received: "", indices.shape().dim_size(1))); for (int idx = 0; idx < num_values; ++idx) { int batch = is_1d ? 0 : indices_values(idx, 0); if (batch >= num_batches) { OP_REQUIRES(context, batch < num_batches, errors::InvalidArgument( ""Indices value along the first dimension must be "", ""lower than the first index of the shape."", ""Got "", batch, "" as batch and "", num_batches, "" as the first dimension of the shape."")); } const auto& value = values_values(idx); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[batch][value] = 1; } else if (use_weights) { per_batch_counts[batch][value] += weight_values(idx); } else { per_batch_counts[batch][value]++; } if (value > max_value) { max_value = value; } } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values, is_1d, context)); }",1 "inline void BiasAndClamp(float clamp_min, float clamp_max, int bias_size, const float* bias_data, int array_size, float* array_data) { // Note: see b/132215220: in May 2019 we thought it would be OK to replace // this with the Eigen one-liner: // return (array.colwise() + bias).cwiseMin(clamp_max).cwiseMin(clamp_max). // This turned out to severely regress performance: +4ms (i.e. 8%) on // MobileNet v2 / 1.0 / 224. So we keep custom NEON code for now. TFLITE_DCHECK_EQ((array_size % bias_size), 0); #ifdef USE_NEON float* array_ptr = array_data; float* array_end_ptr = array_ptr + array_size; const auto clamp_min_vec = vdupq_n_f32(clamp_min); const auto clamp_max_vec = vdupq_n_f32(clamp_max); for (; array_ptr != array_end_ptr; array_ptr += bias_size) { int i = 0; for (; i <= bias_size - 16; i += 16) { auto b0 = vld1q_f32(bias_data + i); auto b1 = vld1q_f32(bias_data + i + 4); auto b2 = vld1q_f32(bias_data + i + 8); auto b3 = vld1q_f32(bias_data + i + 12); auto a0 = vld1q_f32(array_ptr + i); auto a1 = vld1q_f32(array_ptr + i + 4); auto a2 = vld1q_f32(array_ptr + i + 8); auto a3 = vld1q_f32(array_ptr + i + 12); auto x0 = vaddq_f32(a0, b0); auto x1 = vaddq_f32(a1, b1); auto x2 = vaddq_f32(a2, b2); auto x3 = vaddq_f32(a3, b3); x0 = vmaxq_f32(clamp_min_vec, x0); x1 = vmaxq_f32(clamp_min_vec, x1); x2 = vmaxq_f32(clamp_min_vec, x2); x3 = vmaxq_f32(clamp_min_vec, x3); x0 = vminq_f32(clamp_max_vec, x0); x1 = vminq_f32(clamp_max_vec, x1); x2 = vminq_f32(clamp_max_vec, x2); x3 = vminq_f32(clamp_max_vec, x3); vst1q_f32(array_ptr + i, x0); vst1q_f32(array_ptr + i + 4, x1); vst1q_f32(array_ptr + i + 8, x2); vst1q_f32(array_ptr + i + 12, x3); } for (; i <= bias_size - 4; i += 4) { auto b = vld1q_f32(bias_data + i); auto a = vld1q_f32(array_ptr + i); auto x = vaddq_f32(a, b); x = vmaxq_f32(clamp_min_vec, x); x = vminq_f32(clamp_max_vec, x); vst1q_f32(array_ptr + i, x); } for (; i < bias_size; i++) { array_ptr[i] = ActivationFunctionWithMinMax(array_ptr[i] + bias_data[i], clamp_min, clamp_max); } } #else // not NEON for (int array_offset = 0; array_offset < array_size; array_offset += bias_size) { for (int i = 0; i < bias_size; i++) { array_data[array_offset + i] = ActivationFunctionWithMinMax( array_data[array_offset + i] + bias_data[i], clamp_min, clamp_max); } } #endif }",1 "bool DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const { if (!IsIdentity(node) && !IsIdentityN(node)) { return true; } if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) { return false; } if (!fetch_nodes_known_) { // The output values of this node may be needed. return false; } if (node.input_size() < 1) { // Node lacks input, is invalid return false; } const NodeDef* input = node_map_->GetNode(NodeName(node.input(0))); CHECK(input != nullptr) << ""node = "" << node.name() << "" input = "" << node.input(0); // Don't remove Identity nodes corresponding to Variable reads or following // Recv. if (IsVariable(*input) || IsRecv(*input)) { return false; } for (const auto& consumer : node_map_->GetOutputs(node.name())) { if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) { return false; } if (IsSwitch(*input)) { for (const string& consumer_input : consumer->input()) { if (consumer_input == AsControlDependency(node.name())) { return false; } } } } return true; }",1 "GF_Err mpgviddmx_process(GF_Filter *filter) { GF_MPGVidDmxCtx *ctx = gf_filter_get_udta(filter); GF_FilterPacket *pck, *dst_pck; u64 byte_offset; s64 vosh_start = -1; s64 vosh_end = -1; GF_Err e; char *data; u8 *start; u32 pck_size; s32 remain; //always reparse duration if (!ctx->duration.num) mpgviddmx_check_dur(filter, ctx); pck = gf_filter_pid_get_packet(ctx->ipid); if (!pck) { if (gf_filter_pid_is_eos(ctx->ipid)) { mpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_TRUE); if (ctx->opid) gf_filter_pid_set_eos(ctx->opid); if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = NULL; return GF_EOS; } return GF_OK; } data = (char *) gf_filter_pck_get_data(pck, &pck_size); byte_offset = gf_filter_pck_get_byte_offset(pck); start = data; remain = pck_size; //input pid sets some timescale - we flushed pending data , update cts if (!ctx->resume_from && ctx->timescale) { u64 ts = gf_filter_pck_get_cts(pck); if (ts != GF_FILTER_NO_TS) { if (!ctx->cts || !ctx->recompute_cts) ctx->cts = ts; } ts = gf_filter_pck_get_dts(pck); if (ts != GF_FILTER_NO_TS) { if (!ctx->dts || !ctx->recompute_cts) ctx->dts = ts; if (!ctx->prev_dts) ctx->prev_dts = ts; else if (ctx->prev_dts != ts) { u64 diff = ts; diff -= ctx->prev_dts; if (!ctx->cur_fps.den) ctx->cur_fps.den = (u32) diff; else if (ctx->cur_fps.den > diff) ctx->cur_fps.den = (u32) diff; } } gf_filter_pck_get_framing(pck, &ctx->input_is_au_start, &ctx->input_is_au_end); //this will force CTS recomput of each frame if (ctx->recompute_cts) ctx->input_is_au_start = GF_FALSE; if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = pck; gf_filter_pck_ref_props(&ctx->src_pck); } //we stored some data to find the complete vosh, aggregate this packet with current one if (!ctx->resume_from && ctx->hdr_store_size) { if (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size) { ctx->hdr_store_alloc = ctx->hdr_store_size + pck_size; ctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc); } memcpy(ctx->hdr_store + ctx->hdr_store_size, data, sizeof(char)*pck_size); if (byte_offset != GF_FILTER_NO_BO) { if (byte_offset >= ctx->hdr_store_size) byte_offset -= ctx->hdr_store_size; else byte_offset = GF_FILTER_NO_BO; } ctx->hdr_store_size += pck_size; start = data = ctx->hdr_store; remain = pck_size = ctx->hdr_store_size; } if (ctx->resume_from) { if (gf_filter_pid_would_block(ctx->opid)) return GF_OK; //resume from data copied internally if (ctx->hdr_store_size) { assert(ctx->resume_from <= ctx->hdr_store_size); start = data = ctx->hdr_store + ctx->resume_from; remain = pck_size = ctx->hdr_store_size - ctx->resume_from; } else { assert(remain >= (s32) ctx->resume_from); start += ctx->resume_from; remain -= ctx->resume_from; } ctx->resume_from = 0; } if (!ctx->bs) { ctx->bs = gf_bs_new(start, remain, GF_BITSTREAM_READ); } else { gf_bs_reassign_buffer(ctx->bs, start, remain); } if (!ctx->vparser) { ctx->vparser = gf_m4v_parser_bs_new(ctx->bs, ctx->is_mpg12); } while (remain) { Bool full_frame; u8 *pck_data; s32 current; u8 sc_type, forced_sc_type=0; Bool sc_type_forced = GF_FALSE; Bool skip_pck = GF_FALSE; u8 ftype; u32 tinc; u64 size=0; u64 fstart; Bool is_coded; u32 bytes_from_store = 0; u32 hdr_offset = 0; Bool copy_last_bytes = GF_FALSE; //not enough bytes to parse start code if (remain<5) { memcpy(ctx->hdr_store, start, remain); ctx->bytes_in_header = remain; break; } current = -1; //we have some potential bytes of a start code in the store, copy some more bytes and check if valid start code. //if not, dispatch these bytes as continuation of the data if (ctx->bytes_in_header) { memcpy(ctx->hdr_store + ctx->bytes_in_header, start, 8 - ctx->bytes_in_header); current = mpgviddmx_next_start_code(ctx->hdr_store, 8); //no start code in stored buffer if ((current<0) || (current >= (s32) ctx->bytes_in_header) ) { if (ctx->opid) { dst_pck = gf_filter_pck_new_alloc(ctx->opid, ctx->bytes_in_header, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); gf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS); memcpy(pck_data, ctx->hdr_store, ctx->bytes_in_header); gf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE); if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset - ctx->bytes_in_header); } mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); } if (current<0) current = -1; else current -= ctx->bytes_in_header; ctx->bytes_in_header = 0; } else { //we have a valid start code, check which byte in our store or in the packet payload is the start code type //and remember its location to reinit the parser from there hdr_offset = 4 - ctx->bytes_in_header + current; //bytes still to dispatch bytes_from_store = ctx->bytes_in_header; ctx->bytes_in_header = 0; if (!hdr_offset) { forced_sc_type = ctx->hdr_store[current+3]; } else { forced_sc_type = start[hdr_offset-1]; } sc_type_forced = GF_TRUE; } } //no starcode in store, look for startcode in packet if (current == -1) { //locate next start code current = mpgviddmx_next_start_code(start, remain); //no start code, dispatch the block if (current<0) { u8 b3, b2, b1; if (! ctx->frame_started) { GF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, (""[MPGVid] no start code in block and no frame started, discarding data\n"" )); break; } size = remain; b3 = start[remain-3]; b2 = start[remain-2]; b1 = start[remain-1]; //we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes ! if (!b1 || !b2 || !b3) { copy_last_bytes = GF_TRUE; assert(size >= 3); size -= 3; ctx->bytes_in_header = 3; } dst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); memcpy(pck_data, start, (size_t) size); gf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE); gf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS); if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset); } mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); if (copy_last_bytes) { memcpy(ctx->hdr_store, start+remain-3, 3); } break; } } assert(current>=0); //if we are in the middle of parsing the vosh, skip over bytes remaining from previous obj not parsed if ((vosh_start>=0) && current) { assert(remain>=current); start += current; remain -= current; current = 0; } //also skip if no output pid if (!ctx->opid && current) { assert(remain>=current); start += current; remain -= current; current = 0; } //dispatch remaining bytes if (current>0) { //flush remaining dst_pck = gf_filter_pck_new_alloc(ctx->opid, current, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); gf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_TRUE); //bytes were partly in store, partly in packet if (bytes_from_store) { if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store); } assert(bytes_from_store>=(u32) current); bytes_from_store -= current; memcpy(pck_data, ctx->hdr_store, current); } else { //bytes were only in packet if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset); } memcpy(pck_data, start, current); assert(remain>=current); start += current; remain -= current; current = 0; } gf_filter_pck_set_carousel_version(dst_pck, 1); mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); } //parse headers //we have a start code loaded, eg the data packet does not have a full start code at the beginning if (sc_type_forced) { gf_bs_reassign_buffer(ctx->bs, start + hdr_offset, remain - hdr_offset); sc_type = forced_sc_type; } else { gf_bs_reassign_buffer(ctx->bs, start, remain); gf_bs_read_int(ctx->bs, 24); sc_type = gf_bs_read_int(ctx->bs, 8); } if (ctx->is_mpg12) { switch (sc_type) { case M2V_SEQ_START_CODE: case M2V_EXT_START_CODE: gf_bs_reassign_buffer(ctx->bs, start, remain); e = gf_m4v_parse_config(ctx->vparser, &ctx->dsi); //not enough data, accumulate until we can parse the full header if (e==GF_EOS) { if (vosh_start<0) vosh_start = 0; if (data == ctx->hdr_store) { memmove(ctx->hdr_store, start, remain); ctx->hdr_store_size = remain; } else { if (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) { ctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - vosh_start); ctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc); } memcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) ); ctx->hdr_store_size += pck_size - (u32) vosh_start; } gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; } else if (e != GF_OK) { GF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (""[MPGVid] Failed to parse VOS header: %s\n"", gf_error_to_string(e) )); } else { mpgviddmx_check_pid(filter, ctx, 0, NULL); } break; case M2V_PIC_START_CODE: break; default: break; } } else { u8 PL; switch (sc_type) { case M4V_VOS_START_CODE: ctx->dsi.VideoPL = (u8) gf_bs_read_u8(ctx->bs); vosh_start = start - (u8 *)data; skip_pck = GF_TRUE; assert(remain>=5); start += 5; remain -= 5; break; case M4V_VOL_START_CODE: gf_bs_reassign_buffer(ctx->bs, start, remain); PL = ctx->dsi.VideoPL; e = gf_m4v_parse_config(ctx->vparser, &ctx->dsi); ctx->dsi.VideoPL = PL; //not enough data, accumulate until we can parse the full header if (e==GF_EOS) { if (vosh_start<0) vosh_start = 0; if (data == ctx->hdr_store) { memmove(ctx->hdr_store, start, remain); ctx->hdr_store_size = remain; } else { if (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) { ctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - (u32) vosh_start); ctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc); } memcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) ); ctx->hdr_store_size += pck_size - (u32) vosh_start; } gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; } else if (e != GF_OK) { GF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (""[MPGVid] Failed to parse VOS header: %s\n"", gf_error_to_string(e) )); } else { u32 obj_size = (u32) gf_m4v_get_object_start(ctx->vparser); if (vosh_start<0) vosh_start = 0; vosh_end = start - (u8 *)data + obj_size; vosh_end -= vosh_start; mpgviddmx_check_pid(filter, ctx,(u32) vosh_end, data+vosh_start); skip_pck = GF_TRUE; assert(remain>=(s32) obj_size); start += obj_size; remain -= obj_size; } break; case M4V_VOP_START_CODE: case M4V_GOV_START_CODE: break; case M4V_VO_START_CODE: case M4V_VISOBJ_START_CODE: default: if (vosh_start>=0) { skip_pck = GF_TRUE; assert(remain>=4); start += 4; remain -= 4; } break; } } if (skip_pck) { continue; } if (!ctx->opid) { assert(remain>=4); start += 4; remain -= 4; continue; } if (!ctx->is_playing) { ctx->resume_from = (u32) ((char *)start - (char *)data); return GF_OK; } //at this point, we no longer reaggregate packets ctx->hdr_store_size = 0; if (ctx->in_seek) { u64 nb_frames_at_seek = (u64) (ctx->start_range * ctx->cur_fps.num); if (ctx->cts + ctx->cur_fps.den >= nb_frames_at_seek) { //u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek; ctx->in_seek = GF_FALSE; } } //may happen that after all our checks, only 4 bytes are left, continue to store these 4 bytes if (remain<5) continue; //good to go gf_m4v_parser_reset(ctx->vparser, sc_type_forced ? forced_sc_type + 1 : 0); size = 0; e = gf_m4v_parse_frame(ctx->vparser, &ctx->dsi, &ftype, &tinc, &size, &fstart, &is_coded); //true if we strip VO and VISOBJ assert(!fstart); //we skipped bytes already in store + end of start code present in packet, so the size of the first object //needs adjustement if (bytes_from_store) { size += bytes_from_store + hdr_offset; } if ((e == GF_EOS) && !ctx->input_is_au_end) { u8 b3 = start[remain-3]; u8 b2 = start[remain-2]; u8 b1 = start[remain-1]; //we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes ! if (!b1 || !b2 || !b3) { copy_last_bytes = GF_TRUE; assert(size >= 3); size -= 3; ctx->bytes_in_header = 3; } full_frame = GF_FALSE; } else { full_frame = GF_TRUE; } if (!is_coded) { /*if prev is B and we're parsing a packed bitstream discard n-vop*/ if (ctx->forced_packed && ctx->b_frames) { ctx->is_packed = GF_TRUE; assert(remain>=size); start += size; remain -= (s32) size; continue; } /*policy is to import at variable frame rate, skip*/ if (ctx->vfr) { ctx->is_vfr = GF_TRUE; mpgviddmx_update_time(ctx); assert(remain>=size); start += size; remain -= (s32) size; continue; } /*policy is to keep non coded frame (constant frame rate), add*/ } if (ftype==2) { //count number of B-frames since last ref ctx->b_frames++; ctx->nb_b++; } else { //flush all pending packets mpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_FALSE); //remeber the CTS of the last ref ctx->last_ref_cts = ctx->cts; if (ctx->max_b < ctx->b_frames) ctx->max_b = ctx->b_frames; ctx->b_frames = 0; if (ftype) ctx->nb_p++; else ctx->nb_i++; } ctx->nb_frames++; dst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); //bytes come from both our store and the data packet if (bytes_from_store) { memcpy(pck_data, ctx->hdr_store+current, bytes_from_store); assert(size >= bytes_from_store); size -= bytes_from_store; if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store); } memcpy(pck_data + bytes_from_store, start, (size_t) size); } else { //bytes only come the data packet memcpy(pck_data, start, (size_t) size); if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset + start - (u8 *) data); } } assert(pck_data[0] == 0); assert(pck_data[1] == 0); assert(pck_data[2] == 0x01); gf_filter_pck_set_framing(dst_pck, GF_TRUE, (full_frame || ctx->input_is_au_end) ? GF_TRUE : GF_FALSE); gf_filter_pck_set_cts(dst_pck, ctx->cts); gf_filter_pck_set_dts(dst_pck, ctx->dts); if (ctx->input_is_au_start) { ctx->input_is_au_start = GF_FALSE; } else { //we use the carousel flag temporarly to indicate the cts must be recomputed gf_filter_pck_set_carousel_version(dst_pck, 1); } gf_filter_pck_set_sap(dst_pck, ftype ? GF_FILTER_SAP_NONE : GF_FILTER_SAP_1); gf_filter_pck_set_duration(dst_pck, ctx->cur_fps.den); if (ctx->in_seek) gf_filter_pck_set_seek_flag(dst_pck, GF_TRUE); ctx->frame_started = GF_TRUE; mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); mpgviddmx_update_time(ctx); if (!full_frame) { if (copy_last_bytes) { memcpy(ctx->hdr_store, start+remain-3, 3); } break; } assert(remain>=size); start += size; remain -= (s32) size; } gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; }",1 "StatusOr SpecializeType(const AttrSlice& attrs, const OpDef& op_def) { FullTypeDef ft; ft.set_type_id(TFT_PRODUCT); for (int i = 0; i < op_def.output_arg_size(); i++) { auto* t = ft.add_args(); *t = op_def.output_arg(i).experimental_full_type(); // Resolve dependent types. The convention for op registrations is to use // attributes as type variables. // See https://www.tensorflow.org/guide/create_op#type_polymorphism. // Once the op signature can be defined entirely in FullType, this // convention can be deprecated. // // Note: While this code performs some basic verifications, it generally // assumes consistent op defs and attributes. If more complete // verifications are needed, they should be done by separately, and in a // way that can be reused for type inference. for (int j = 0; j < t->args_size(); j++) { auto* arg = t->mutable_args(i); if (arg->type_id() == TFT_VAR) { const auto* attr = attrs.Find(arg->s()); DCHECK(attr != nullptr); if (attr->value_case() == AttrValue::kList) { const auto& attr_list = attr->list(); arg->set_type_id(TFT_PRODUCT); for (int i = 0; i < attr_list.type_size(); i++) { map_dtype_to_tensor(attr_list.type(i), arg->add_args()); } } else if (attr->value_case() == AttrValue::kType) { map_dtype_to_tensor(attr->type(), arg); } else { return Status(error::UNIMPLEMENTED, absl::StrCat(""unknown attribute type"", attrs.DebugString(), "" key="", arg->s())); } arg->clear_s(); } } } return ft; }",1 "static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si) { s32 pps_id; /*s->current_picture.reference= h->nal_ref_idc != 0;*/ gf_bs_read_ue_log(bs, ""first_mb_in_slice""); si->slice_type = gf_bs_read_ue_log(bs, ""slice_type""); if (si->slice_type > 9) return -1; pps_id = gf_bs_read_ue_log(bs, ""pps_id""); if (pps_id > 255) return -1; si->pps = &avc->pps[pps_id]; si->pps->id = pps_id; if (!si->pps->slice_group_count) return -2; si->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT]; if (!si->sps->log2_max_frame_num) return -2; si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, ""frame_num""); si->field_pic_flag = 0; if (si->sps->frame_mbs_only_flag) { /*s->picture_structure= PICT_FRAME;*/ } else { si->field_pic_flag = gf_bs_read_int_log(bs, 1, ""field_pic_flag""); if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, ""bottom_field_flag""); } if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag) si->idr_pic_id = gf_bs_read_ue_log(bs, ""idr_pic_id""); if (si->sps->poc_type == 0) { si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, ""poc_lsb""); if (si->pps->pic_order_present && !si->field_pic_flag) { si->delta_poc_bottom = gf_bs_read_se_log(bs, ""delta_poc_bottom""); } } else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) { si->delta_poc[0] = gf_bs_read_se_log(bs, ""delta_poc0""); if ((si->pps->pic_order_present == 1) && !si->field_pic_flag) si->delta_poc[1] = gf_bs_read_se_log(bs, ""delta_poc1""); } if (si->pps->redundant_pic_cnt_present) { si->redundant_pic_cnt = gf_bs_read_ue_log(bs, ""redundant_pic_cnt""); } return 0; }",1 " void DecodePngV2(OpKernelContext* context, StringPiece input) { int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16; png::DecodeContext decode; OP_REQUIRES( context, png::CommonInitDecode(input, channels_, channel_bits, &decode), errors::InvalidArgument(""Invalid PNG. Failed to initialize decoder."")); // Verify that width and height are not too large: // - verify width and height don't overflow int. // - width can later be multiplied by channels_ and sizeof(uint16), so // verify single dimension is not too large. // - verify when width and height are multiplied together, there are a few // bits to spare as well. const int width = static_cast(decode.width); const int height = static_cast(decode.height); const int64_t total_size = static_cast(width) * static_cast(height); if (width != static_cast(decode.width) || width <= 0 || width >= (1LL << 27) || height != static_cast(decode.height) || height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) { png::CommonFreeDecode(&decode); OP_REQUIRES(context, false, errors::InvalidArgument(""PNG size too large for int: "", decode.width, "" by "", decode.height)); } Tensor* output = nullptr; Status status; // By the existing API, we support decoding PNG with `DecodeGif` op. // We need to make sure to return 4-D shapes when using `DecodeGif`. if (op_type_ == ""DecodeGif"") { status = context->allocate_output( 0, TensorShape({1, height, width, decode.channels}), &output); } else { status = context->allocate_output( 0, TensorShape({height, width, decode.channels}), &output); } if (op_type_ == ""DecodeBmp"") { // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here // because currently `decode_(jpeg|png|gif)` ops can decode any one of // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode // anything but bmp formats. This behavior needs to be revisited. For more // details, please refer to the bug. OP_REQUIRES(context, false, errors::InvalidArgument( ""Trying to decode PNG format using DecodeBmp op. Use "" ""`decode_png` or `decode_image` instead."")); } else if (op_type_ == ""DecodeAndCropJpeg"") { OP_REQUIRES(context, false, errors::InvalidArgument( ""DecodeAndCropJpeg operation can run on JPEG only, but "" ""detected PNG."")); } if (!status.ok()) png::CommonFreeDecode(&decode); OP_REQUIRES_OK(context, status); if (data_type_ == DataType::DT_UINT8) { OP_REQUIRES( context, png::CommonFinishDecode( reinterpret_cast(output->flat().data()), decode.channels * width * sizeof(uint8), &decode), errors::InvalidArgument(""Invalid PNG data, size "", input.size())); } else if (data_type_ == DataType::DT_UINT16) { OP_REQUIRES( context, png::CommonFinishDecode( reinterpret_cast(output->flat().data()), decode.channels * width * sizeof(uint16), &decode), errors::InvalidArgument(""Invalid PNG data, size "", input.size())); } else if (data_type_ == DataType::DT_FLOAT) { // `png::CommonFinishDecode` does not support `float`. First allocate // uint16 buffer for the image and decode in uint16 (lossless). Wrap the // buffer in `unique_ptr` so that we don't forget to delete the buffer. std::unique_ptr buffer( new uint16[height * width * decode.channels]); OP_REQUIRES( context, png::CommonFinishDecode(reinterpret_cast(buffer.get()), decode.channels * width * sizeof(uint16), &decode), errors::InvalidArgument(""Invalid PNG data, size "", input.size())); // Convert uint16 image data to desired data type. // Use eigen threadpooling to speed up the copy operation. const auto& device = context->eigen_device(); TTypes::UnalignedConstTensor buf(buffer.get(), height, width, decode.channels); float scale = 1. / std::numeric_limits::max(); // Fill output tensor with desired dtype. output->tensor().device(device) = buf.cast() * scale; } }",1 "GF_AV1Config *gf_odf_av1_cfg_read_bs_size(GF_BitStream *bs, u32 size) { #ifndef GPAC_DISABLE_AV_PARSERS AV1State state; u8 reserved; GF_AV1Config *cfg; if (!size) size = (u32) gf_bs_available(bs); if (!size) return NULL; cfg = gf_odf_av1_cfg_new(); gf_av1_init_state(&state); state.config = cfg; cfg->marker = gf_bs_read_int(bs, 1); cfg->version = gf_bs_read_int(bs, 7); cfg->seq_profile = gf_bs_read_int(bs, 3); cfg->seq_level_idx_0 = gf_bs_read_int(bs, 5); cfg->seq_tier_0 = gf_bs_read_int(bs, 1); cfg->high_bitdepth = gf_bs_read_int(bs, 1); cfg->twelve_bit = gf_bs_read_int(bs, 1); cfg->monochrome = gf_bs_read_int(bs, 1); cfg->chroma_subsampling_x = gf_bs_read_int(bs, 1); cfg->chroma_subsampling_y = gf_bs_read_int(bs, 1); cfg->chroma_sample_position = gf_bs_read_int(bs, 2); reserved = gf_bs_read_int(bs, 3); if (reserved != 0 || cfg->marker != 1 || cfg->version != 1) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[AV1] wrong avcC reserved %d / marker %d / version %d expecting 0 1 1\n"", reserved, cfg->marker, cfg->version)); gf_odf_av1_cfg_del(cfg); return NULL; } cfg->initial_presentation_delay_present = gf_bs_read_int(bs, 1); if (cfg->initial_presentation_delay_present) { cfg->initial_presentation_delay_minus_one = gf_bs_read_int(bs, 4); } else { /*reserved = */gf_bs_read_int(bs, 4); cfg->initial_presentation_delay_minus_one = 0; } size -= 4; while (size) { u64 pos, obu_size; ObuType obu_type; GF_AV1_OBUArrayEntry *a; pos = gf_bs_get_position(bs); obu_size = 0; if (gf_av1_parse_obu(bs, &obu_type, &obu_size, NULL, &state) != GF_OK) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[AV1] could not parse AV1 OBU at position ""LLU"". Leaving parsing.\n"", pos)); break; } assert(obu_size == gf_bs_get_position(bs) - pos); GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[AV1] parsed AV1 OBU type=%u size=""LLU"" at position ""LLU"".\n"", obu_type, obu_size, pos)); if (!av1_is_obu_header(obu_type)) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[AV1] AV1 unexpected OBU type=%u size=""LLU"" found at position ""LLU"". Forwarding.\n"", pos)); } GF_SAFEALLOC(a, GF_AV1_OBUArrayEntry); if (!a) break; a->obu = gf_malloc((size_t)obu_size); if (!a->obu) { gf_free(a); break; } gf_bs_seek(bs, pos); gf_bs_read_data(bs, (char *) a->obu, (u32)obu_size); a->obu_length = obu_size; a->obu_type = obu_type; gf_list_add(cfg->obu_array, a); if (sizevmcb, VMCB_INTERCEPTS); if (!is_guest_mode(&svm->vcpu)) return; c = &svm->vmcb->control; h = &svm->vmcb01.ptr->control; g = &svm->nested.ctl; for (i = 0; i < MAX_INTERCEPT; i++) c->intercepts[i] = h->intercepts[i]; if (g->int_ctl & V_INTR_MASKING_MASK) { /* We only want the cr8 intercept bits of L1 */ vmcb_clr_intercept(c, INTERCEPT_CR8_READ); vmcb_clr_intercept(c, INTERCEPT_CR8_WRITE); /* * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not * affect any interrupt we may want to inject; therefore, * interrupt window vmexits are irrelevant to L0. */ vmcb_clr_intercept(c, INTERCEPT_VINTR); } /* We don't want to see VMMCALLs from a nested guest */ vmcb_clr_intercept(c, INTERCEPT_VMMCALL); for (i = 0; i < MAX_INTERCEPT; i++) c->intercepts[i] |= g->intercepts[i]; /* If SMI is not intercepted, ignore guest SMI intercept as well */ if (!intercept_smi) vmcb_clr_intercept(c, INTERCEPT_SMI); }",1 "bool Tensor::FromProto(Allocator* a, const TensorProto& proto) { CHECK_NOTNULL(a); TensorBuffer* p = nullptr; if (!TensorShape::IsValid(proto.tensor_shape())) return false; if (proto.dtype() == DT_INVALID) return false; TensorShape shape(proto.tensor_shape()); const int64_t N = shape.num_elements(); if (N > 0 && proto.dtype()) { bool dtype_error = false; if (!proto.tensor_content().empty()) { const auto& content = proto.tensor_content(); CASES_WITH_DEFAULT(proto.dtype(), p = Helper::Decode(a, content, N), dtype_error = true, dtype_error = true); } else { CASES_WITH_DEFAULT(proto.dtype(), p = FromProtoField(a, proto, N), dtype_error = true, dtype_error = true); } if (dtype_error || p == nullptr) return false; } shape_ = shape; set_dtype(proto.dtype()); UnrefIfNonNull(buf_); buf_ = p; // TODO(misard) add tracking of which kernels and steps are calling // FromProto. if (MemoryLoggingEnabled() && buf_ != nullptr && buf_->data() != nullptr) { LogMemory::RecordTensorAllocation(""Unknown (from Proto)"", LogMemory::UNKNOWN_STEP_ID, *this); } return true; }",1 "setup_seccomp (FlatpakBwrap *bwrap, const char *arch, gulong allowed_personality, FlatpakRunFlags run_flags, GError **error) { gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0; gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0; __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL; /**** BEGIN NOTE ON CODE SHARING * * There are today a number of different Linux container * implementations. That will likely continue for long into the * future. But we can still try to share code, and it's important * to do so because it affects what library and application writers * can do, and we should support code portability between different * container tools. * * This syscall blocklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blocklist. * * If you make any changes here, I suggest sending the changes along * to other sandbox maintainers. Using the libseccomp list is also * an appropriate venue: * https://groups.google.com/forum/#!forum/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blocklist: * * https://github.com/sandstorm-io/sandstorm * in src/sandstorm/supervisor.c++ * https://github.com/flatpak/flatpak.git * in common/flatpak-run.c * https://git.gnome.org/browse/linux-user-chroot * in src/setup-seccomp.c * **** END NOTE ON CODE SHARING */ struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_blocklist[] = { /* Block dmesg */ {SCMP_SYS (syslog), EPERM}, /* Useless old syscall */ {SCMP_SYS (uselib), EPERM}, /* Don't allow disabling accounting */ {SCMP_SYS (acct), EPERM}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt), EPERM}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl), EPERM}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key), EPERM}, {SCMP_SYS (keyctl), EPERM}, {SCMP_SYS (request_key), EPERM}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages), EPERM}, {SCMP_SYS (mbind), EPERM}, {SCMP_SYS (get_mempolicy), EPERM}, {SCMP_SYS (set_mempolicy), EPERM}, {SCMP_SYS (migrate_pages), EPERM}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare), EPERM}, {SCMP_SYS (mount), EPERM}, {SCMP_SYS (pivot_root), EPERM}, #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__) /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack * and flags arguments are reversed so the flags come second */ {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #else /* Normally the flags come first */ {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #endif /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)}, }; struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_nondevel_blocklist[] = { /* Profiling operations; we expect these to be done by tools from outside * the sandbox. In particular perf has been the source of many CVEs. */ {SCMP_SYS (perf_event_open), EPERM}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace), EPERM} }; /* Blocklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_allowlist[] = { /* NOTE: Keep in numerical order */ { AF_UNSPEC, 0 }, { AF_LOCAL, 0 }, { AF_INET, 0 }, { AF_INET6, 0 }, { AF_NETLINK, 0 }, { AF_CAN, FLATPAK_RUN_FLAG_CANBUS }, { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH }, }; int last_allowed_family; int i, r; g_auto(GLnxTmpfile) seccomp_tmpf = { 0, }; seccomp = seccomp_init (SCMP_ACT_ALLOW); if (!seccomp) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Initialize seccomp failed"")); if (arch != NULL) { uint32_t arch_id = 0; const uint32_t *extra_arches = NULL; if (strcmp (arch, ""i386"") == 0) { arch_id = SCMP_ARCH_X86; } else if (strcmp (arch, ""x86_64"") == 0) { arch_id = SCMP_ARCH_X86_64; extra_arches = seccomp_x86_64_extra_arches; } else if (strcmp (arch, ""arm"") == 0) { arch_id = SCMP_ARCH_ARM; } #ifdef SCMP_ARCH_AARCH64 else if (strcmp (arch, ""aarch64"") == 0) { arch_id = SCMP_ARCH_AARCH64; extra_arches = seccomp_aarch64_extra_arches; } #endif /* We only really need to handle arches on multiarch systems. * If only one arch is supported the default is fine */ if (arch_id != 0) { /* This *adds* the target arch, instead of replacing the native one. This is not ideal, because we'd like to only allow the target arch, but we can't really disallow the native arch at this point, because then bubblewrap couldn't continue running. */ r = seccomp_arch_add (seccomp, arch_id); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add architecture to seccomp filter"")); if (multiarch && extra_arches != NULL) { for (i = 0; extra_arches[i] != 0; i++) { r = seccomp_arch_add (seccomp, extra_arches[i]); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add multiarch architecture to seccomp filter"")); } } } } /* TODO: Should we filter the kernel keyring syscalls in some way? * We do want them to be used by desktop apps, but they could also perhaps * leak system stuff or secrets from other apps. */ for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++) { int scall = syscall_blocklist[i].scall; int errnum = syscall_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } if (!devel) { for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++) { int scall = syscall_nondevel_blocklist[i].scall; int errnum = syscall_nondevel_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_nondevel_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } } /* Socket filtering doesn't work on e.g. i386, so ignore failures here * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing * something else: https://github.com/seccomp/libseccomp/issues/8 */ last_allowed_family = -1; for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++) { int family = socket_family_allowlist[i].family; int disallowed; if (socket_family_allowlist[i].flags_mask != 0 && (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blocklist the in-between valid families */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed)); } last_allowed_family = family; } /* Blocklist the rest */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1)); if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, ""/tmp"", &seccomp_tmpf, error)) return FALSE; if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to export bpf"")); lseek (seccomp_tmpf.fd, 0, SEEK_SET); flatpak_bwrap_add_args_data_fd (bwrap, ""--seccomp"", glnx_steal_fd (&seccomp_tmpf.fd), NULL); return TRUE; }",1 "llvm::Optional simplifyBroadcast(ShapeComponentAnalysis& analysis, ValueRange shapes, Location loc, OpBuilder* builder) { // First find the input shape with the largest rank. SmallVector> shapes_found; size_t maxRank = 0; for (const auto &shape : llvm::enumerate(shapes)) { auto found_shape = analysis.GetValueInfo(shape.value()); if (!found_shape) return {}; shapes_found.push_back(*found_shape); maxRank = std::max(maxRank, found_shape->size()); } SmallVector joined_dimensions( maxRank); SmallVector> shape_and_rank_for_dim(maxRank); for (const auto &shape : llvm::enumerate(shapes_found)) { for (const auto &dim : llvm::enumerate(llvm::reverse(shape.value()))) { // 1 dimensions don't contribute to the final result. if (dim.value().isConstant(1)) continue; // If it's not a 1 dimension it will be present in the result. Remember // where it came from. auto index = maxRank - dim.index() - 1; if (!joined_dimensions[index]) { joined_dimensions[index] = &dim.value(); shape_and_rank_for_dim[index] = std::make_pair(shapes[shape.index()], shape.value().size()); continue; } // Bail if the dimensions are neither equal nor 1. if (*joined_dimensions[index] != dim.value()) return {}; } } // If the output is the same as one of the inputs just return that. if (llvm::is_splat(shape_and_rank_for_dim) && shape_and_rank_for_dim[0].first) { return shape_and_rank_for_dim[0].first; } // Otherwise rematerialize the shape from the pieces we have. SmallVector elements; for (int i = 0; i != maxRank; ++i) { // 1 dimensions are filtered above, recreate the constant. if (!shape_and_rank_for_dim[i].first) { auto one = builder->getIntegerAttr( shapes[0].getType().cast().getElementType(), 1); elements.push_back(builder->create(loc, one)); continue; } // Extract from one of the shapes, accounting for the reverse indexing // performed by broadcast. Value index = builder->create( loc, i - maxRank + shape_and_rank_for_dim[i].second); elements.push_back(builder->create( loc, shape_and_rank_for_dim[i].first, index)); } return Value(builder->create(loc, elements)); }",1 "Literal *hermes::evalUnaryOperator( UnaryOperatorInst::OpKind kind, IRBuilder &builder, Literal *operand) { switch (kind) { case UnaryOperatorInst::OpKind::MinusKind: // Negate constant integers. switch (operand->getKind()) { case ValueKind::LiteralNumberKind: if (auto *literalNum = llvh::dyn_cast(operand)) { auto V = -literalNum->getValue(); return builder.getLiteralNumber(V); } break; case ValueKind::LiteralUndefinedKind: return builder.getLiteralNaN(); case ValueKind::LiteralBoolKind: if (evalIsTrue(builder, operand)) { return builder.getLiteralNumber(-1); } else { // evalIsFalse(operand) return builder.getLiteralNegativeZero(); } case ValueKind::LiteralNullKind: return builder.getLiteralNegativeZero(); default: break; } break; case UnaryOperatorInst::OpKind::TypeofKind: switch (operand->getKind()) { case ValueKind::GlobalObjectKind: case ValueKind::LiteralNullKind: return builder.getLiteralString(""object""); case ValueKind::LiteralUndefinedKind: return builder.getLiteralString(""undefined""); case ValueKind::LiteralBoolKind: return builder.getLiteralString(""boolean""); case ValueKind::LiteralNumberKind: return builder.getLiteralString(""number""); case ValueKind::LiteralStringKind: return builder.getLiteralString(""string""); default: llvm_unreachable(""Invalid literal kind.""); } break; case UnaryOperatorInst::OpKind::BangKind: if (evalIsTrue(builder, operand)) { return builder.getLiteralBool(false); } if (evalIsFalse(builder, operand)) { return builder.getLiteralBool(true); } break; case UnaryOperatorInst::OpKind::VoidKind: return builder.getLiteralUndefined(); default: break; } return nullptr; }",1 "int Socket::startSslClient(const std::string &certificate_path, String hostname) { if (isssl) { stopSsl(); } ERR_clear_error(); #if OPENSSL_VERSION_NUMBER < 0x10100000L ctx = SSL_CTX_new(SSLv23_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) { #ifdef NETDEBUG std::cout << thread_id << ""Error ssl context is null (check that openssl has been inited)"" << std::endl; #endif log_ssl_errors(""Error ssl context is null for %s"", hostname.c_str()); return -1; } //set the timeout for the ssl session if (SSL_CTX_set_timeout(ctx, 130l) < 1) { SSL_CTX_free(ctx); ctx = NULL; return -1; } //load certs ERR_clear_error(); if (certificate_path.length()) { if (!SSL_CTX_load_verify_locations(ctx, NULL, certificate_path.c_str())) { #ifdef NETDEBUG std::cout << thread_id << ""couldnt load certificates"" << std::endl; #endif log_ssl_errors(""couldnt load certificates from %s"", certificate_path.c_str()); //tidy up SSL_CTX_free(ctx); ctx = NULL; return -2; } } else if (!SSL_CTX_set_default_verify_paths(ctx)) //use default if no certPpath given { #ifdef NETDEBUG std::cout << thread_id << ""couldnt load certificates"" << std::endl; #endif log_ssl_errors(""couldnt load default certificates for %s"", hostname.c_str()); //tidy up SSL_CTX_free(ctx); ctx = NULL; return -2; } // add validation params ERR_clear_error(); X509_VERIFY_PARAM *x509_param = X509_VERIFY_PARAM_new(); if (!x509_param) { log_ssl_errors(""couldnt add validation params for %s"", hostname.c_str()); //X509_VERIFY_PARAM_free(x509_param); SSL_CTX_free(ctx); ctx = NULL; return -2; } ERR_clear_error(); if (!X509_VERIFY_PARAM_set_flags(x509_param, X509_V_FLAG_TRUSTED_FIRST)) { log_ssl_errors(""couldnt add validation params for %s"", hostname.c_str()); X509_VERIFY_PARAM_free(x509_param); SSL_CTX_free(ctx); ctx = NULL; return -2; } ERR_clear_error(); if (!SSL_CTX_set1_param(ctx, x509_param)) { log_ssl_errors(""couldnt add validation params for %s"", hostname.c_str()); X509_VERIFY_PARAM_free(x509_param); SSL_CTX_free(ctx); ctx = NULL; return -2; } X509_VERIFY_PARAM_free(x509_param); // try not freeing this as SSL_CTX_free seems to be ring to free it //hand socket over to ssl lib ERR_clear_error(); ssl = SSL_new(ctx); SSL_set_options(ssl, SSL_OP_ALL); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); SSL_set_connect_state(ssl); //fcntl(this->getFD() ,F_SETFL, O_NONBLOCK); // blocking mode used currently SSL_set_fd(ssl, this->getFD()); SSL_set_tlsext_host_name(ssl, hostname.c_str()); //make io non blocking as select wont tell us if we can do a read without blocking //BIO_set_nbio(SSL_get_rbio(ssl),1l); // blocking mode used currently //BIO_set_nbio(SSL_get_wbio(ssl),1l); // blocking mode used currently ERR_clear_error(); int rc = SSL_connect(ssl); if (rc < 0) { log_ssl_errors(""ssl_connect failed to %s"", hostname.c_str()); #ifdef NETDEBUG std::cout << thread_id << ""ssl_connect failed with error "" << SSL_get_error(ssl, rc) << std::endl; #endif // tidy up SSL_free(ssl); ssl = NULL; SSL_CTX_free(ctx); ctx = NULL; return -3; } //should be safer to do this last as nothing will ever try to use a ssl socket that isnt fully setup isssl = true; issslserver = false; return 0; }",1 " Status BuildInputArgIndex(const OpDef::ArgDef& arg_def, AttrSlice attr_values, const FunctionDef::ArgAttrs* arg_attrs, bool ints_on_device, int64_t resource_arg_unique_id) { bool is_type_list; DataTypeVector dtypes; TF_RETURN_IF_ERROR( ArgNumType(attr_values, arg_def, &is_type_list, &dtypes)); CHECK_GE(dtypes.size(), size_t{1}); int arg_index = result_.nodes.size(); TF_RETURN_IF_ERROR( AddItem(arg_def.name(), {true, arg_index, 0, is_type_list, dtypes})); // Creates dtypes.size() nodes in the graph. for (size_t i = 0; i < dtypes.size(); ++i) { TF_RETURN_IF_ERROR(AddItem(strings::StrCat(arg_def.name(), "":"", i), {true, arg_index, 0, false, {dtypes[i]}})); DCHECK_EQ(arg_index, result_.nodes.size()); string name = arg_def.name(); if (dtypes.size() > 1) { strings::StrAppend(&name, ""_"", i); } NodeDef* gnode = AddNode(name); if (ints_on_device && dtypes[i] == DataType::DT_INT32) { gnode->set_op(FunctionLibraryDefinition::kDeviceArgOp); } else { gnode->set_op(FunctionLibraryDefinition::kArgOp); } DataType dtype = arg_def.is_ref() ? MakeRefType(dtypes[i]) : dtypes[i]; AddAttr(""T"", dtype, gnode); AddAttr(""index"", arg_index, gnode); if (resource_arg_unique_id >= 0) { AddAttr(""_resource_arg_unique_id"", resource_arg_unique_id, gnode); } if (arg_attrs) { for (const auto& arg_attr : arg_attrs->attr()) { AddAttr(arg_attr.first, arg_attr.second, gnode->mutable_attr()); } } result_.arg_types.push_back(dtypes[i]); ++arg_index; } return Status::OK(); }",1 "gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val) { int idx; int type = nint(tree->car); switch (type) { case NODE_GVAR: case NODE_ARG: case NODE_LVAR: case NODE_IVAR: case NODE_CVAR: case NODE_CONST: case NODE_NIL: case NODE_MASGN: if (rhs) { codegen(s, rhs, VAL); pop(); sp = cursp(); } break; case NODE_COLON2: case NODE_CALL: case NODE_SCALL: /* keep evaluation order */ break; case NODE_NVAR: codegen_error(s, ""Can't assign to numbered parameter""); break; default: codegen_error(s, ""unknown lhs""); break; } tree = tree->cdr; switch (type) { case NODE_GVAR: gen_setxv(s, OP_SETGV, sp, nsym(tree), val); break; case NODE_ARG: case NODE_LVAR: idx = lv_idx(s, nsym(tree)); if (idx > 0) { if (idx != sp) { gen_move(s, idx, sp, val); } break; } else { /* upvar */ gen_setupvar(s, sp, nsym(tree)); } break; case NODE_IVAR: gen_setxv(s, OP_SETIV, sp, nsym(tree), val); break; case NODE_CVAR: gen_setxv(s, OP_SETCV, sp, nsym(tree), val); break; case NODE_CONST: gen_setxv(s, OP_SETCONST, sp, nsym(tree), val); break; case NODE_COLON2: if (sp) { gen_move(s, cursp(), sp, 0); } sp = cursp(); push(); codegen(s, tree->car, VAL); if (rhs) { codegen(s, rhs, VAL); pop(); gen_move(s, sp, cursp(), 0); } pop_n(2); idx = new_sym(s, nsym(tree->cdr)); genop_2(s, OP_SETMCNST, sp, idx); break; case NODE_CALL: case NODE_SCALL: { int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0; mrb_sym mid = nsym(tree->cdr->car); top = cursp(); if (val || sp == cursp()) { push(); /* room for retval */ } call = cursp(); if (!tree->car) { noself = 1; push(); } else { codegen(s, tree->car, VAL); /* receiver */ } if (safe) { int recv = cursp()-1; gen_move(s, cursp(), recv, 1); skip = genjmp2_0(s, OP_JMPNIL, cursp(), val); } tree = tree->cdr->cdr->car; if (tree) { if (tree->car) { /* positional arguments */ n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14); if (n < 0) { /* variable length */ n = 15; push(); } } if (tree->cdr->car) { /* keyword arguments */ gen_hash(s, tree->cdr->car->cdr, VAL, 0); if (n < 14) { n++; push(); } else { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } } } if (rhs) { codegen(s, rhs, VAL); pop(); } else { gen_move(s, cursp(), sp, 0); } if (val) { gen_move(s, top, cursp(), 1); } if (n < 14) { n++; } else { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } s->sp = call; if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) { genop_1(s, OP_SETIDX, cursp()); } else { genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n); } if (safe) { dispatch(s, skip); } s->sp = top; } break; case NODE_MASGN: gen_vmassignment(s, tree->car, sp, val); break; /* splat without assignment */ case NODE_NIL: break; default: codegen_error(s, ""unknown lhs""); break; } if (val) push(); }",1 "int main(int argc, char **argv, char **envp) { int opt; while ((opt = getopt(argc, argv, ""b:h:k:p:q:w:z:xv"")) != -1) { switch (opt) { case 'b': tmate_settings->bind_addr = xstrdup(optarg); break; case 'h': tmate_settings->tmate_host = xstrdup(optarg); break; case 'k': tmate_settings->keys_dir = xstrdup(optarg); break; case 'p': tmate_settings->ssh_port = atoi(optarg); break; case 'q': tmate_settings->ssh_port_advertized = atoi(optarg); break; case 'w': tmate_settings->websocket_hostname = xstrdup(optarg); break; case 'z': tmate_settings->websocket_port = atoi(optarg); break; case 'x': tmate_settings->use_proxy_protocol = true; break; case 'v': tmate_settings->log_level++; break; default: usage(); return 1; } } init_logging(tmate_settings->log_level); setup_locale(); if (!tmate_settings->tmate_host) tmate_settings->tmate_host = get_full_hostname(); cmdline = *argv; cmdline_end = *envp; tmate_preload_trace_lib(); tmate_catch_sigsegv(); tmate_init_rand(); if ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) || (mkdir(TMATE_WORKDIR ""/sessions"", 0703) < 0 && errno != EEXIST) || (mkdir(TMATE_WORKDIR ""/jail"", 0700) < 0 && errno != EEXIST)) tmate_fatal(""Cannot prepare session in "" TMATE_WORKDIR); /* The websocket server needs to access the /session dir to rename sockets */ if ((chmod(TMATE_WORKDIR, 0701) < 0) || (chmod(TMATE_WORKDIR ""/sessions"", 0703) < 0) || (chmod(TMATE_WORKDIR ""/jail"", 0700) < 0)) tmate_fatal(""Cannot prepare session in "" TMATE_WORKDIR); tmate_ssh_server_main(tmate_session, tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port); return 0; }",1 "void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *sess, const void *pkt, pj_size_t size) { const pjmedia_rtcp_xr_pkt *rtcp_xr = (pjmedia_rtcp_xr_pkt*) pkt; const pjmedia_rtcp_xr_rb_rr_time *rb_rr_time = NULL; const pjmedia_rtcp_xr_rb_dlrr *rb_dlrr = NULL; const pjmedia_rtcp_xr_rb_stats *rb_stats = NULL; const pjmedia_rtcp_xr_rb_voip_mtc *rb_voip_mtc = NULL; const pjmedia_rtcp_xr_rb_header *rb_hdr = (pjmedia_rtcp_xr_rb_header*) rtcp_xr->buf; unsigned pkt_len, rb_len; if (rtcp_xr->common.pt != RTCP_XR) return; pkt_len = pj_ntohs((pj_uint16_t)rtcp_xr->common.length); if ((pkt_len + 1) > (size / 4)) return; /* Parse report rpt_types */ while ((pj_int32_t*)rb_hdr < (pj_int32_t*)pkt + pkt_len) { rb_len = pj_ntohs((pj_uint16_t)rb_hdr->length); /* Just skip any block with length == 0 (no report content) */ if (rb_len) { switch (rb_hdr->bt) { case BT_RR_TIME: rb_rr_time = (pjmedia_rtcp_xr_rb_rr_time*) rb_hdr; break; case BT_DLRR: rb_dlrr = (pjmedia_rtcp_xr_rb_dlrr*) rb_hdr; break; case BT_STATS: rb_stats = (pjmedia_rtcp_xr_rb_stats*) rb_hdr; break; case BT_VOIP_METRICS: rb_voip_mtc = (pjmedia_rtcp_xr_rb_voip_mtc*) rb_hdr; break; default: break; } } rb_hdr = (pjmedia_rtcp_xr_rb_header*) ((pj_int32_t*)rb_hdr + rb_len + 1); } /* Receiving RR Time */ if (rb_rr_time) { /* Save LRR from NTP timestamp of the RR time block report */ sess->rx_lrr = ((pj_ntohl(rb_rr_time->ntp_sec) & 0x0000FFFF) << 16) | ((pj_ntohl(rb_rr_time->ntp_frac) >> 16) & 0xFFFF); /* Calculate RR arrival time for DLRR */ pj_get_timestamp(&sess->rx_lrr_time); TRACE_((sess->name, ""Rx RTCP SR: ntp_ts=%p"", sess->rx_lrr, (pj_uint32_t)(sess->rx_lrr_time.u64*65536/ sess->rtcp_session->ts_freq.u64))); } /* Receiving DLRR */ if (rb_dlrr) { pj_uint32_t lrr, now, dlrr; pj_uint64_t eedelay; pjmedia_rtcp_ntp_rec ntp; /* LRR is the middle 32bit of NTP. It has 1/65536 second * resolution */ lrr = pj_ntohl(rb_dlrr->item.lrr); /* DLRR is delay since LRR, also in 1/65536 resolution */ dlrr = pj_ntohl(rb_dlrr->item.dlrr); /* Get current time, and convert to 1/65536 resolution */ pjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp); now = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16); /* End-to-end delay is (now-lrr-dlrr) */ eedelay = now - lrr - dlrr; /* Convert end to end delay to usec (keeping the calculation in * 64bit space):: * sess->ee_delay = (eedelay * 1000) / 65536; */ if (eedelay < 4294) { eedelay = (eedelay * 1000000) >> 16; } else { eedelay = (eedelay * 1000) >> 16; eedelay *= 1000; } TRACE_((sess->name, ""Rx RTCP XR DLRR: lrr=%p, dlrr=%p (%d:%03dms), "" ""now=%p, rtt=%p"", lrr, dlrr, dlrr/65536, (dlrr%65536)*1000/65536, now, (pj_uint32_t)eedelay)); /* Only save calculation if ""now"" is greater than lrr, or * otherwise rtt will be invalid */ if (now-dlrr >= lrr) { unsigned rtt = (pj_uint32_t)eedelay; /* Check that eedelay value really makes sense. * We allow up to 30 seconds RTT! */ if (eedelay <= 30 * 1000 * 1000UL) { /* ""Normalize"" rtt value that is exceptionally high. * For such values, ""normalize"" the rtt to be three times * the average value. */ if (rtt>((unsigned)sess->stat.rtt.mean*3) && sess->stat.rtt.n!=0) { unsigned orig_rtt = rtt; rtt = (unsigned)sess->stat.rtt.mean*3; PJ_LOG(5,(sess->name, ""RTT value %d usec is normalized to %d usec"", orig_rtt, rtt)); } TRACE_((sess->name, ""RTCP RTT is set to %d usec"", rtt)); pj_math_stat_update(&sess->stat.rtt, rtt); } } else { PJ_LOG(5, (sess->name, ""Internal RTCP NTP clock skew detected: "" ""lrr=%p, now=%p, dlrr=%p (%d:%03dms), "" ""diff=%d"", lrr, now, dlrr, dlrr/65536, (dlrr%65536)*1000/65536, dlrr-(now-lrr))); } } /* Receiving Statistics Summary */ if (rb_stats) { pj_uint8_t flags = rb_stats->header.specific; pj_bzero(&sess->stat.tx.stat_sum, sizeof(sess->stat.tx.stat_sum)); /* Range of packets sequence reported in this blocks */ sess->stat.tx.stat_sum.begin_seq = pj_ntohs(rb_stats->begin_seq); sess->stat.tx.stat_sum.end_seq = pj_ntohs(rb_stats->end_seq); /* Get flags of valid fields */ sess->stat.tx.stat_sum.l = (flags & (1 << 7)) != 0; sess->stat.tx.stat_sum.d = (flags & (1 << 6)) != 0; sess->stat.tx.stat_sum.j = (flags & (1 << 5)) != 0; sess->stat.tx.stat_sum.t = (flags & (3 << 3)) != 0; /* Fetch the reports info */ if (sess->stat.tx.stat_sum.l) { sess->stat.tx.stat_sum.lost = pj_ntohl(rb_stats->lost); } if (sess->stat.tx.stat_sum.d) { sess->stat.tx.stat_sum.dup = pj_ntohl(rb_stats->dup); } if (sess->stat.tx.stat_sum.j) { sess->stat.tx.stat_sum.jitter.min = pj_ntohl(rb_stats->jitter_min); sess->stat.tx.stat_sum.jitter.max = pj_ntohl(rb_stats->jitter_max); sess->stat.tx.stat_sum.jitter.mean= pj_ntohl(rb_stats->jitter_mean); pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.jitter, pj_ntohl(rb_stats->jitter_dev)); } if (sess->stat.tx.stat_sum.t) { sess->stat.tx.stat_sum.toh.min = rb_stats->toh_min; sess->stat.tx.stat_sum.toh.max = rb_stats->toh_max; sess->stat.tx.stat_sum.toh.mean= rb_stats->toh_mean; pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.toh, pj_ntohl(rb_stats->toh_dev)); } pj_gettimeofday(&sess->stat.tx.stat_sum.update); } /* Receiving VoIP Metrics */ if (rb_voip_mtc) { sess->stat.tx.voip_mtc.loss_rate = rb_voip_mtc->loss_rate; sess->stat.tx.voip_mtc.discard_rate = rb_voip_mtc->discard_rate; sess->stat.tx.voip_mtc.burst_den = rb_voip_mtc->burst_den; sess->stat.tx.voip_mtc.gap_den = rb_voip_mtc->gap_den; sess->stat.tx.voip_mtc.burst_dur = pj_ntohs(rb_voip_mtc->burst_dur); sess->stat.tx.voip_mtc.gap_dur = pj_ntohs(rb_voip_mtc->gap_dur); sess->stat.tx.voip_mtc.rnd_trip_delay = pj_ntohs(rb_voip_mtc->rnd_trip_delay); sess->stat.tx.voip_mtc.end_sys_delay = pj_ntohs(rb_voip_mtc->end_sys_delay); /* signal & noise level encoded in two's complement form */ sess->stat.tx.voip_mtc.signal_lvl = (pj_int8_t) ((rb_voip_mtc->signal_lvl > 127)? ((int)rb_voip_mtc->signal_lvl - 256) : rb_voip_mtc->signal_lvl); sess->stat.tx.voip_mtc.noise_lvl = (pj_int8_t) ((rb_voip_mtc->noise_lvl > 127)? ((int)rb_voip_mtc->noise_lvl - 256) : rb_voip_mtc->noise_lvl); sess->stat.tx.voip_mtc.rerl = rb_voip_mtc->rerl; sess->stat.tx.voip_mtc.gmin = rb_voip_mtc->gmin; sess->stat.tx.voip_mtc.r_factor = rb_voip_mtc->r_factor; sess->stat.tx.voip_mtc.ext_r_factor = rb_voip_mtc->ext_r_factor; sess->stat.tx.voip_mtc.mos_lq = rb_voip_mtc->mos_lq; sess->stat.tx.voip_mtc.mos_cq = rb_voip_mtc->mos_cq; sess->stat.tx.voip_mtc.rx_config = rb_voip_mtc->rx_config; sess->stat.tx.voip_mtc.jb_nom = pj_ntohs(rb_voip_mtc->jb_nom); sess->stat.tx.voip_mtc.jb_max = pj_ntohs(rb_voip_mtc->jb_max); sess->stat.tx.voip_mtc.jb_abs_max = pj_ntohs(rb_voip_mtc->jb_abs_max); pj_gettimeofday(&sess->stat.tx.voip_mtc.update); } }",1 "s32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc) { u8 idr_flag; s32 slice, ret; u32 nal_hdr; AVCSliceInfo n_state; gf_bs_enable_emulation_byte_removal(bs, GF_TRUE); nal_hdr = gf_bs_read_u8(bs); slice = 0; memcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo)); avc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F; n_state.nal_ref_idc = (nal_hdr >> 5) & 0x3; idr_flag = 0; switch (n_state.nal_unit_type) { case GF_AVC_NALU_ACCESS_UNIT: case GF_AVC_NALU_END_OF_SEQ: case GF_AVC_NALU_END_OF_STREAM: ret = 1; break; case GF_AVC_NALU_SVC_SLICE: SVC_ReadNal_header_extension(bs, &n_state.NalHeader); // slice buffer - read the info and compare. /*ret = */svc_parse_slice(bs, avc, &n_state); if (avc->s_info.nal_ref_idc) { n_state.poc_lsb_prev = avc->s_info.poc_lsb; n_state.poc_msb_prev = avc->s_info.poc_msb; } avc_compute_poc(&n_state); if (avc->s_info.poc != n_state.poc) { memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo)); return 1; } memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo)); return 0; case GF_AVC_NALU_SVC_PREFIX_NALU: SVC_ReadNal_header_extension(bs, &n_state.NalHeader); return 0; case GF_AVC_NALU_IDR_SLICE: case GF_AVC_NALU_NON_IDR_SLICE: case GF_AVC_NALU_DP_A_SLICE: case GF_AVC_NALU_DP_B_SLICE: case GF_AVC_NALU_DP_C_SLICE: slice = 1; /* slice buffer - read the info and compare.*/ ret = avc_parse_slice(bs, avc, idr_flag, &n_state); if (ret < 0) return ret; ret = 0; if ( ((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE)) && (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE) ) { break; } if (avc->s_info.frame_num != n_state.frame_num) { ret = 1; break; } if (avc->s_info.field_pic_flag != n_state.field_pic_flag) { ret = 1; break; } if ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) && (!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) { ret = 1; break; } assert(avc->s_info.sps); if (avc->s_info.sps->poc_type == n_state.sps->poc_type) { if (!avc->s_info.sps->poc_type) { if (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) { ret = 1; break; } if (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) { ret = 1; break; } } else if (avc->s_info.sps->poc_type == 1) { if (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) { ret = 1; break; } if (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) { ret = 1; break; } } } if (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) { if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/ ret = 1; break; } else if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/ ret = 1; break; } } break; case GF_AVC_NALU_SEQ_PARAM: avc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr); if (avc->last_ps_idx < 0) return -1; return 0; case GF_AVC_NALU_PIC_PARAM: avc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr); if (avc->last_ps_idx < 0) return -1; return 0; case GF_AVC_NALU_SVC_SUBSEQ_PARAM: avc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr); if (avc->last_ps_idx < 0) return -1; return 0; case GF_AVC_NALU_SEQ_PARAM_EXT: avc->last_ps_idx = (s32) gf_bs_read_ue(bs); if (avc->last_ps_idx < 0) return -1; return 0; case GF_AVC_NALU_SEI: case GF_AVC_NALU_FILLER_DATA: return 0; default: if (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1; //To detect change of AU when multiple sps and pps in stream else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE) ret = 1; else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE) ret = 1; else ret = 0; break; } /* save _prev values */ if (ret && avc->s_info.sps) { n_state.frame_num_offset_prev = avc->s_info.frame_num_offset; if ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0)) n_state.frame_num_prev = avc->s_info.frame_num; if (avc->s_info.nal_ref_idc) { n_state.poc_lsb_prev = avc->s_info.poc_lsb; n_state.poc_msb_prev = avc->s_info.poc_msb; } } if (slice) avc_compute_poc(&n_state); memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo)); return ret; }",1 " Status SetUnknownShape(const NodeDef* node, int output_port) { shape_inference::ShapeHandle shape = GetUnknownOutputShape(node, output_port); InferenceContext* ctx = GetContext(node); if (ctx == nullptr) { return errors::InvalidArgument(""Missing context""); } ctx->set_output(output_port, shape); return Status::OK(); }",1 " Status BuildInputArgIndex(const OpDef::ArgDef& arg_def, AttrSlice attr_values, const FunctionDef::ArgAttrs* arg_attrs, bool ints_on_device, int64_t resource_arg_unique_id) { bool is_type_list; DataTypeVector dtypes; TF_RETURN_IF_ERROR( ArgNumType(attr_values, arg_def, &is_type_list, &dtypes)); if (dtypes.size() < size_t{1}) { return errors::Internal(""Expected a list of at least one dtype""); } int arg_index = result_.nodes.size(); TF_RETURN_IF_ERROR( AddItem(arg_def.name(), {true, arg_index, 0, is_type_list, dtypes})); // Creates dtypes.size() nodes in the graph. for (size_t i = 0; i < dtypes.size(); ++i) { TF_RETURN_IF_ERROR(AddItem(strings::StrCat(arg_def.name(), "":"", i), {true, arg_index, 0, false, {dtypes[i]}})); DCHECK_EQ(arg_index, result_.nodes.size()); string name = arg_def.name(); if (dtypes.size() > 1) { strings::StrAppend(&name, ""_"", i); } NodeDef* gnode = AddNode(name); if (ints_on_device && dtypes[i] == DataType::DT_INT32) { gnode->set_op(FunctionLibraryDefinition::kDeviceArgOp); } else { gnode->set_op(FunctionLibraryDefinition::kArgOp); } DataType dtype = arg_def.is_ref() ? MakeRefType(dtypes[i]) : dtypes[i]; AddAttr(""T"", dtype, gnode); AddAttr(""index"", arg_index, gnode); if (resource_arg_unique_id >= 0) { AddAttr(""_resource_arg_unique_id"", resource_arg_unique_id, gnode); } if (arg_attrs) { for (const auto& arg_attr : arg_attrs->attr()) { AddAttr(arg_attr.first, arg_attr.second, gnode->mutable_attr()); } } result_.arg_types.push_back(dtypes[i]); ++arg_index; } return Status::OK(); }",1 "static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CropBox ""CropBox"" #define DeviceCMYK ""DeviceCMYK"" #define MediaBox ""MediaBox"" #define RenderPCLText "" Rendering PCL... "" char command[MagickPathExtent], *density, filename[MagickPathExtent], geometry[MagickPathExtent], *options, input_filename[MagickPathExtent]; const DelegateInfo *delegate_info; Image *image, *next_image; ImageInfo *read_info; MagickBooleanType cmyk, status; PointInfo delta; RectangleInfo bounding_box, page; char *p; ssize_t c; SegmentInfo bounds; size_t height, width; ssize_t count; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); /* Open image file. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,""UnableToCreateTemporaryFile"", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); if ((flags & RhoValue) != 0) image->resolution.x=geometry_info.rho; image->resolution.y=image->resolution.x; if ((flags & SigmaValue) != 0) image->resolution.y=geometry_info.sigma; } /* Determine page geometry from the PCL media box. */ cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; count=0; (void) memset(&bounding_box,0,sizeof(bounding_box)); (void) memset(&bounds,0,sizeof(bounds)); (void) memset(&page,0,sizeof(page)); (void) memset(command,0,sizeof(command)); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if (image_info->page != (char *) NULL) continue; /* Note PCL elements. */ *p++=(char) c; if ((c != (int) '/') && (c != '\n') && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Is this a CMYK document? */ if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,""CropBox [%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,""CropBox[%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,""MediaBox [%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,""MediaBox[%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; /* Set PCL render geometry. */ width=(size_t) floor(bounds.x2-bounds.x1+0.5); height=(size_t) floor(bounds.y2-bounds.y1+0.5); if (width > page.width) page.width=width; if (height > page.height) page.height=height; } (void) CloseBlob(image); /* Render PCL with the GhostPCL delegate. */ if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); (void) FormatLocaleString(geometry,MagickPathExtent,""%.20gx%.20g"",(double) page.width,(double) page.height); if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo(""pcl:mono"",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo(""pcl:cmyk"",(char *) NULL,exception); else delegate_info=GetDelegateInfo(""pcl:color"",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { image=DestroyImage(image); return((Image *) NULL); } if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); density=AcquireString(""""); options=AcquireString(""""); (void) FormatLocaleString(density,MagickPathExtent,""%gx%g"", image->resolution.x,image->resolution.y); if (image_info->ping != MagickFalse) (void) FormatLocaleString(density,MagickPathExtent,""2.0x2.0""); page.width=(size_t) floor(page.width*image->resolution.x/delta.x+0.5); page.height=(size_t) floor(page.height*image->resolution.y/delta.y+0.5); (void) FormatLocaleString(options,MagickPathExtent,""-g%.20gx%.20g "",(double) page.width,(double) page.height); image=DestroyImage(image); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { if (read_info->number_scenes != 1) (void) FormatLocaleString(options,MagickPathExtent,""-dLastPage=%.20g"", (double) (read_info->scene+read_info->number_scenes)); else (void) FormatLocaleString(options,MagickPathExtent, ""-dFirstPage=%.20g -dLastPage=%.20g"",(double) read_info->scene+1, (double) (read_info->scene+read_info->number_scenes)); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MagickPathExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options, read_info->filename,input_filename); options=DestroyString(options); density=DestroyString(density); status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command, (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse; image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); (void) RelinquishUniqueFileResource(input_filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) ThrowReaderException(DelegateError,""PCLDelegateFailed""); if (LocaleCompare(image->magick,""BMP"") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(image,exception); if (cmyk_image != (Image *) NULL) { image=DestroyImageList(image); image=cmyk_image; } } do { (void) CopyMagickString(image->filename,filename,MagickPathExtent); image->page=page; if (image_info->ping != MagickFalse) { image->magick_columns*=image->resolution.x/2.0; image->magick_rows*=image->resolution.y/2.0; image->columns*=image->resolution.x/2.0; image->rows*=image->resolution.y/2.0; } next_image=SyncNextImageInList(image); if (next_image != (Image *) NULL) image=next_image; } while (next_image != (Image *) NULL); return(GetFirstImageInList(image)); }",1 "setup_seccomp (FlatpakBwrap *bwrap, const char *arch, gulong allowed_personality, FlatpakRunFlags run_flags, GError **error) { gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0; gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0; __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL; /**** BEGIN NOTE ON CODE SHARING * * There are today a number of different Linux container * implementations. That will likely continue for long into the * future. But we can still try to share code, and it's important * to do so because it affects what library and application writers * can do, and we should support code portability between different * container tools. * * This syscall blocklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blocklist. * * If you make any changes here, I suggest sending the changes along * to other sandbox maintainers. Using the libseccomp list is also * an appropriate venue: * https://groups.google.com/forum/#!forum/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blocklist: * * https://github.com/sandstorm-io/sandstorm * in src/sandstorm/supervisor.c++ * https://github.com/flatpak/flatpak.git * in common/flatpak-run.c * https://git.gnome.org/browse/linux-user-chroot * in src/setup-seccomp.c * **** END NOTE ON CODE SHARING */ struct { int scall; struct scmp_arg_cmp *arg; } syscall_blocklist[] = { /* Block dmesg */ {SCMP_SYS (syslog)}, /* Useless old syscall */ {SCMP_SYS (uselib)}, /* Don't allow disabling accounting */ {SCMP_SYS (acct)}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt)}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl)}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key)}, {SCMP_SYS (keyctl)}, {SCMP_SYS (request_key)}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages)}, {SCMP_SYS (mbind)}, {SCMP_SYS (get_mempolicy)}, {SCMP_SYS (set_mempolicy)}, {SCMP_SYS (migrate_pages)}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare)}, {SCMP_SYS (mount)}, {SCMP_SYS (pivot_root)}, #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__) /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack * and flags arguments are reversed so the flags come second */ {SCMP_SYS (clone), &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #else /* Normally the flags come first */ {SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #endif /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)}, }; struct { int scall; struct scmp_arg_cmp *arg; } syscall_nondevel_blocklist[] = { /* Profiling operations; we expect these to be done by tools from outside * the sandbox. In particular perf has been the source of many CVEs. */ {SCMP_SYS (perf_event_open)}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace)} }; /* Blocklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_allowlist[] = { /* NOTE: Keep in numerical order */ { AF_UNSPEC, 0 }, { AF_LOCAL, 0 }, { AF_INET, 0 }, { AF_INET6, 0 }, { AF_NETLINK, 0 }, { AF_CAN, FLATPAK_RUN_FLAG_CANBUS }, { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH }, }; int last_allowed_family; int i, r; g_auto(GLnxTmpfile) seccomp_tmpf = { 0, }; seccomp = seccomp_init (SCMP_ACT_ALLOW); if (!seccomp) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Initialize seccomp failed"")); if (arch != NULL) { uint32_t arch_id = 0; const uint32_t *extra_arches = NULL; if (strcmp (arch, ""i386"") == 0) { arch_id = SCMP_ARCH_X86; } else if (strcmp (arch, ""x86_64"") == 0) { arch_id = SCMP_ARCH_X86_64; extra_arches = seccomp_x86_64_extra_arches; } else if (strcmp (arch, ""arm"") == 0) { arch_id = SCMP_ARCH_ARM; } #ifdef SCMP_ARCH_AARCH64 else if (strcmp (arch, ""aarch64"") == 0) { arch_id = SCMP_ARCH_AARCH64; extra_arches = seccomp_aarch64_extra_arches; } #endif /* We only really need to handle arches on multiarch systems. * If only one arch is supported the default is fine */ if (arch_id != 0) { /* This *adds* the target arch, instead of replacing the native one. This is not ideal, because we'd like to only allow the target arch, but we can't really disallow the native arch at this point, because then bubblewrap couldn't continue running. */ r = seccomp_arch_add (seccomp, arch_id); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add architecture to seccomp filter"")); if (multiarch && extra_arches != NULL) { for (i = 0; extra_arches[i] != 0; i++) { r = seccomp_arch_add (seccomp, extra_arches[i]); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add multiarch architecture to seccomp filter"")); } } } } /* TODO: Should we filter the kernel keyring syscalls in some way? * We do want them to be used by desktop apps, but they could also perhaps * leak system stuff or secrets from other apps. */ for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++) { int scall = syscall_blocklist[i].scall; if (syscall_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } if (!devel) { for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++) { int scall = syscall_nondevel_blocklist[i].scall; if (syscall_nondevel_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } } /* Socket filtering doesn't work on e.g. i386, so ignore failures here * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing * something else: https://github.com/seccomp/libseccomp/issues/8 */ last_allowed_family = -1; for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++) { int family = socket_family_allowlist[i].family; int disallowed; if (socket_family_allowlist[i].flags_mask != 0 && (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blocklist the in-between valid families */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed)); } last_allowed_family = family; } /* Blocklist the rest */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1)); if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, ""/tmp"", &seccomp_tmpf, error)) return FALSE; if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to export bpf"")); lseek (seccomp_tmpf.fd, 0, SEEK_SET); flatpak_bwrap_add_args_data_fd (bwrap, ""--seccomp"", glnx_steal_fd (&seccomp_tmpf.fd), NULL); return TRUE; }",1 " void Compute(OpKernelContext *ctx) override { const Tensor *indices_t, *values_t, *shape_t, *dense_t; OP_REQUIRES_OK(ctx, ctx->input(""sp_indices"", &indices_t)); OP_REQUIRES_OK(ctx, ctx->input(""sp_values"", &values_t)); OP_REQUIRES_OK(ctx, ctx->input(""sp_shape"", &shape_t)); OP_REQUIRES_OK(ctx, ctx->input(""dense"", &dense_t)); // Validations. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()), errors::InvalidArgument( ""Input sp_indices should be a matrix but received shape: "", indices_t->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values_t->shape()) && TensorShapeUtils::IsVector(shape_t->shape()), errors::InvalidArgument( ""Inputs sp_values and sp_shape should be vectors "" ""but received shapes: "", values_t->shape().DebugString(), "" and "", shape_t->shape().DebugString())); OP_REQUIRES( ctx, values_t->dim_size(0) == indices_t->dim_size(0), errors::InvalidArgument( ""The first dimension of values and indices should match. ("", values_t->dim_size(0), "" vs. "", indices_t->dim_size(0), "")"")); const auto indices_mat = indices_t->matrix(); const auto shape_vec = shape_t->vec(); const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec)); const auto rhs_dims = BCast::FromShape(dense_t->shape()); BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims. // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal // to dims in rhs (from right to left). auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) { if (lhs.size() < rhs.size()) return false; for (size_t i = 0; i < rhs.size(); ++i) { if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false; } return true; }; OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(), errors::InvalidArgument( ""SparseDenseBinaryOpShared broadcasts dense to sparse "" ""only; got incompatible shapes: ["", absl::StrJoin(lhs_dims, "",""), ""] vs. ["", absl::StrJoin(rhs_dims, "",""), ""]"")); Tensor *output_values = nullptr; Tensor dense_gathered; const int64_t nnz = indices_t->dim_size(0); OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({nnz}), &output_values)); OP_REQUIRES_OK( ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}), &dense_gathered)); bool op_is_div = false; if (absl::StrContains(ctx->op_kernel().type_string_view(), ""Div"")) { op_is_div = true; } // Pulls relevant entries from the dense side, with reshape and broadcasting // *of the dense side* taken into account. Use a TensorRef to avoid blowing // up memory. // // We can directly use the sparse indices to look up dense side, because // ""b.y_reshape()"" and ""b.y_bcast()"" are guaranteed to have rank ""ndims"". auto dense_gathered_flat = dense_gathered.flat(); const int ndims = lhs_dims.size(); switch (ndims) { #define CASE(NDIM) \ case NDIM: { \ TensorRef> rhs_ref = \ dense_t->shaped(b.y_reshape()) \ .broadcast(BCast::ToIndexArray(b.y_bcast())); \ Eigen::array idx; \ bool indices_valid = true; \ for (int i = 0; i < nnz; ++i) { \ for (int d = 0; d < NDIM; ++d) { \ idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \ if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \ indices_valid = false; \ } \ } \ OP_REQUIRES( \ ctx, indices_valid, \ errors::InvalidArgument(""Provided indices are out-of-bounds w.r.t. "" \ ""dense side with broadcasted shape"")); \ dense_gathered_flat(i) = rhs_ref.coeff(idx); \ if (op_is_div) { \ OP_REQUIRES(ctx, dense_gathered_flat(i) != 0, \ errors::InvalidArgument( \ ""SparseDenseCwiseDiv cannot divide by zero,"" \ ""but input dense tensor contains zero "")); \ } \ } \ break; \ } CASE(1); CASE(2); CASE(3); CASE(4); CASE(5); default: OP_REQUIRES( ctx, false, errors::InvalidArgument(""Only tensors with ranks between 1 and 5 "" ""are currently supported. Tensor rank: "", ndims)); #undef CASE } output_values->flat().device(ctx->eigen_device()) = values_t->flat().binaryExpr(dense_gathered_flat, typename Functor::func()); }",1 "static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si) { s32 pps_id, num_ref_idx_l0_active_minus1 = 0, num_ref_idx_l1_active_minus1 = 0; /*s->current_picture.reference= h->nal_ref_idc != 0;*/ gf_bs_read_ue_log(bs, ""first_mb_in_slice""); si->slice_type = gf_bs_read_ue_log(bs, ""slice_type""); if (si->slice_type > 9) return -1; pps_id = gf_bs_read_ue_log(bs, ""pps_id""); if (pps_id > 255) return -1; si->pps = &avc->pps[pps_id]; if (!si->pps->slice_group_count) return -2; si->sps = &avc->sps[si->pps->sps_id]; if (!si->sps->log2_max_frame_num) return -2; avc->sps_active_idx = si->pps->sps_id; avc->pps_active_idx = pps_id; si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, ""frame_num""); si->field_pic_flag = 0; si->bottom_field_flag = 0; if (!si->sps->frame_mbs_only_flag) { si->field_pic_flag = gf_bs_read_int_log(bs, 1, ""field_pic_flag""); if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, ""bottom_field_flag""); } if ((si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) || svc_idr_flag) si->idr_pic_id = gf_bs_read_ue_log(bs, ""idr_pic_id""); if (si->sps->poc_type == 0) { si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, ""poc_lsb""); if (si->pps->pic_order_present && !si->field_pic_flag) { si->delta_poc_bottom = gf_bs_read_se_log(bs, ""poc_lsb""); } } else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) { si->delta_poc[0] = gf_bs_read_se_log(bs, ""delta_poc0""); if ((si->pps->pic_order_present == 1) && !si->field_pic_flag) si->delta_poc[1] = gf_bs_read_se_log(bs, ""delta_poc1""); } if (si->pps->redundant_pic_cnt_present) { si->redundant_pic_cnt = gf_bs_read_ue_log(bs, ""redundant_pic_cnt""); } if (si->slice_type % 5 == GF_AVC_TYPE_B) { gf_bs_read_int_log(bs, 1, ""direct_spatial_mv_pred_flag""); } num_ref_idx_l0_active_minus1 = si->pps->num_ref_idx_l0_default_active_minus1; num_ref_idx_l1_active_minus1 = si->pps->num_ref_idx_l1_default_active_minus1; if (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_B) { Bool num_ref_idx_active_override_flag = gf_bs_read_int_log(bs, 1, ""num_ref_idx_active_override_flag""); if (num_ref_idx_active_override_flag) { num_ref_idx_l0_active_minus1 = gf_bs_read_ue_log(bs, ""num_ref_idx_l0_active_minus1""); if (si->slice_type % 5 == GF_AVC_TYPE_B) { num_ref_idx_l1_active_minus1 = gf_bs_read_ue_log(bs, ""num_ref_idx_l1_active_minus1""); } } } if (si->nal_unit_type == 20 || si->nal_unit_type == 21) { //ref_pic_list_mvc_modification(); /* specified in Annex H */ GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (""[avc-h264] unimplemented ref_pic_list_mvc_modification() in slide header\n"")); assert(0); return -1; } else { ref_pic_list_modification(bs, si->slice_type); } if ((si->pps->weighted_pred_flag && (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP)) || (si->pps->weighted_bipred_idc == 1 && si->slice_type % 5 == GF_AVC_TYPE_B)) { pred_weight_table(bs, si->slice_type, si->sps->ChromaArrayType, num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1); } if (si->nal_ref_idc != 0) { dec_ref_pic_marking(bs, (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE)); } if (si->pps->entropy_coding_mode_flag && si->slice_type % 5 != GF_AVC_TYPE_I && si->slice_type % 5 != GF_AVC_TYPE_SI) { gf_bs_read_ue_log(bs, ""cabac_init_idc""); } /*slice_qp_delta = */gf_bs_read_se(bs); if (si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_SI) { if (si->slice_type % 5 == GF_AVC_TYPE_SP) { gf_bs_read_int_log(bs, 1, ""sp_for_switch_flag""); } gf_bs_read_se_log(bs, ""slice_qs_delta""); } if (si->pps->deblocking_filter_control_present_flag) { if (gf_bs_read_ue_log(bs, ""disable_deblocking_filter_idc"") != 1) { gf_bs_read_se_log(bs, ""slice_alpha_c0_offset_div2""); gf_bs_read_se_log(bs, ""slice_beta_offset_div2""); } } if (si->pps->slice_group_count > 1 && si->pps->mb_slice_group_map_type >= 3 && si->pps->mb_slice_group_map_type <= 5) { gf_bs_read_int_log(bs, (u32)ceil(log1p((si->pps->pic_size_in_map_units_minus1 + 1) / (si->pps->slice_group_change_rate_minus1 + 1) ) / log(2)), ""slice_group_change_cycle""); } return 0; }",1 "Node* Graph::AddNode(NodeDef node_def, Status* status) { const OpRegistrationData* op_reg_data; status->Update(ops_.LookUp(node_def.op(), &op_reg_data)); if (!status->ok()) return nullptr; DataTypeVector inputs; DataTypeVector outputs; status->Update( InOutTypesForNode(node_def, op_reg_data->op_def, &inputs, &outputs)); if (!status->ok()) { *status = AttachDef(*status, node_def); return nullptr; } Node::NodeClass node_class = op_reg_data->is_function_op ? Node::NC_FUNCTION_OP : Node::GetNodeClassForOp(node_def.op()); if (op_reg_data->type_ctor != nullptr) { VLOG(3) << ""AddNode: found type constructor for "" << node_def.name(); const auto ctor_type = full_type::SpecializeType(AttrSlice(node_def), op_reg_data->op_def); const FullTypeDef ctor_typedef = ctor_type.ValueOrDie(); if (ctor_typedef.type_id() != TFT_UNSET) { *(node_def.mutable_experimental_type()) = ctor_typedef; } } else { VLOG(3) << ""AddNode: no type constructor for "" << node_def.name(); } Node* node = AllocateNode(std::make_shared( &op_reg_data->op_def, std::move(node_def), inputs, outputs, op_reg_data->fwd_type_fn), nullptr, node_class); return node; }",1 "static void compile_xclass_matchingpath(compiler_common *common, PCRE2_SPTR cc, jump_list **backtracks) { DEFINE_COMPILER; jump_list *found = NULL; jump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks; sljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX; struct sljit_jump *jump = NULL; PCRE2_SPTR ccbegin; int compares, invertcmp, numberofcmps; #if defined SUPPORT_UNICODE && (PCRE2_CODE_UNIT_WIDTH == 8 || PCRE2_CODE_UNIT_WIDTH == 16) BOOL utf = common->utf; #endif /* SUPPORT_UNICODE && PCRE2_CODE_UNIT_WIDTH == [8|16] */ #ifdef SUPPORT_UNICODE sljit_u32 unicode_status = 0; int typereg = TMP1; const sljit_u32 *other_cases; sljit_uw typeoffset; #endif /* SUPPORT_UNICODE */ /* Scanning the necessary info. */ cc++; ccbegin = cc; compares = 0; if (cc[-1] & XCL_MAP) { min = 0; cc += 32 / sizeof(PCRE2_UCHAR); } while (*cc != XCL_END) { compares++; if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); if (c > max) max = c; if (c < min) min = c; #ifdef SUPPORT_UNICODE unicode_status |= XCLASS_SAVE_CHAR; #endif /* SUPPORT_UNICODE */ } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); if (c < min) min = c; GETCHARINCTEST(c, cc); if (c > max) max = c; #ifdef SUPPORT_UNICODE unicode_status |= XCLASS_SAVE_CHAR; #endif /* SUPPORT_UNICODE */ } #ifdef SUPPORT_UNICODE else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; if (*cc == PT_CLIST && *cc == XCL_PROP) { other_cases = PRIV(ucd_caseless_sets) + cc[1]; while (*other_cases != NOTACHAR) { if (*other_cases > max) max = *other_cases; if (*other_cases < min) min = *other_cases; other_cases++; } } else { max = READ_CHAR_MAX; min = 0; } switch(*cc) { case PT_ANY: /* Any either accepts everything or ignored. */ if (cc[-1] == XCL_PROP) { compile_char1_matchingpath(common, OP_ALLANY, cc, backtracks, FALSE); if (list == backtracks) add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); return; } break; case PT_LAMP: case PT_GC: case PT_PC: case PT_ALNUM: unicode_status |= XCLASS_HAS_TYPE; break; case PT_SCX: unicode_status |= XCLASS_HAS_SCRIPT_EXTENSION; if (cc[-1] == XCL_NOTPROP) { unicode_status |= XCLASS_SCRIPT_EXTENSION_NOTPROP; break; } compares++; /* Fall through */ case PT_SC: unicode_status |= XCLASS_HAS_SCRIPT; break; case PT_SPACE: case PT_PXSPACE: case PT_WORD: case PT_PXGRAPH: case PT_PXPRINT: case PT_PXPUNCT: unicode_status |= XCLASS_SAVE_CHAR | XCLASS_HAS_TYPE; break; case PT_CLIST: case PT_UCNC: unicode_status |= XCLASS_SAVE_CHAR; break; case PT_BOOL: unicode_status |= XCLASS_HAS_BOOL; break; case PT_BIDICL: unicode_status |= XCLASS_HAS_BIDICL; break; default: SLJIT_UNREACHABLE(); break; } cc += 2; } #endif /* SUPPORT_UNICODE */ } SLJIT_ASSERT(compares > 0); /* We are not necessary in utf mode even in 8 bit mode. */ cc = ccbegin; if ((cc[-1] & XCL_NOT) != 0) read_char(common, min, max, backtracks, READ_CHAR_UPDATE_STR_PTR); else { #ifdef SUPPORT_UNICODE read_char(common, min, max, (unicode_status & XCLASS_NEEDS_UCD) ? backtracks : NULL, 0); #else /* !SUPPORT_UNICODE */ read_char(common, min, max, NULL, 0); #endif /* SUPPORT_UNICODE */ } if ((cc[-1] & XCL_HASPROP) == 0) { if ((cc[-1] & XCL_MAP) != 0) { jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); if (!optimize_class(common, (const sljit_u8 *)cc, (((const sljit_u8 *)cc)[31] & 0x80) != 0, TRUE, &found)) { OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0); add_jump(compiler, &found, JUMP(SLJIT_NOT_ZERO)); } add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(jump); cc += 32 / sizeof(PCRE2_UCHAR); } else { OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min); add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, max - min)); } } else if ((cc[-1] & XCL_MAP) != 0) { OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); #ifdef SUPPORT_UNICODE unicode_status |= XCLASS_CHAR_SAVED; #endif /* SUPPORT_UNICODE */ if (!optimize_class(common, (const sljit_u8 *)cc, FALSE, TRUE, list)) { #if PCRE2_CODE_UNIT_WIDTH == 8 jump = NULL; if (common->utf) #endif /* PCRE2_CODE_UNIT_WIDTH == 8 */ jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0); add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO)); #if PCRE2_CODE_UNIT_WIDTH == 8 if (common->utf) #endif /* PCRE2_CODE_UNIT_WIDTH == 8 */ JUMPHERE(jump); } OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0); cc += 32 / sizeof(PCRE2_UCHAR); } #ifdef SUPPORT_UNICODE if (unicode_status & XCLASS_NEEDS_UCD) { if ((unicode_status & (XCLASS_SAVE_CHAR | XCLASS_CHAR_SAVED)) == XCLASS_SAVE_CHAR) OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); #if PCRE2_CODE_UNIT_WIDTH == 32 if (!common->utf) { jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, MAX_UTF_CODE_POINT + 1); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, UNASSIGNED_UTF_CHAR); JUMPHERE(jump); } #endif /* PCRE2_CODE_UNIT_WIDTH == 32 */ OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2)); OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1); OP2(SLJIT_SHL, TMP1, 0, TMP2, 0, SLJIT_IMM, 3); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 2); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0); ccbegin = cc; if (unicode_status & XCLASS_HAS_BIDICL) { OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass)); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BIDICLASS_SHIFT); while (*cc != XCL_END) { if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); GETCHARINCTEST(c, cc); } else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; if (*cc == PT_BIDICL) { compares--; invertcmp = (compares == 0 && list != backtracks); if (cc[-1] == XCL_NOTPROP) invertcmp ^= 0x1; jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]); add_jump(compiler, compares > 0 ? list : backtracks, jump); } cc += 2; } } cc = ccbegin; } if (unicode_status & XCLASS_HAS_BOOL) { OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, bprops)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BPROPS_MASK); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2); while (*cc != XCL_END) { if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); GETCHARINCTEST(c, cc); } else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; if (*cc == PT_BOOL) { compares--; invertcmp = (compares == 0 && list != backtracks); if (cc[-1] == XCL_NOTPROP) invertcmp ^= 0x1; OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_boolprop_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f)); add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp)); } cc += 2; } } cc = ccbegin; } if (unicode_status & XCLASS_HAS_SCRIPT) { OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); while (*cc != XCL_END) { if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); GETCHARINCTEST(c, cc); } else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; switch (*cc) { case PT_SCX: if (cc[-1] == XCL_NOTPROP) break; /* Fall through */ case PT_SC: compares--; invertcmp = (compares == 0 && list != backtracks); if (cc[-1] == XCL_NOTPROP) invertcmp ^= 0x1; add_jump(compiler, compares > 0 ? list : backtracks, CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1])); } cc += 2; } } cc = ccbegin; } if (unicode_status & XCLASS_HAS_SCRIPT_EXTENSION) { OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_SCRIPTX_MASK); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2); if (unicode_status & XCLASS_SCRIPT_EXTENSION_NOTPROP) { if (unicode_status & XCLASS_HAS_TYPE) { if (unicode_status & XCLASS_SAVE_CHAR) { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP2, 0); unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0; } else { OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP2, 0); unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR; } } OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); } while (*cc != XCL_END) { if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); GETCHARINCTEST(c, cc); } else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; if (*cc == PT_SCX) { compares--; invertcmp = (compares == 0 && list != backtracks); jump = NULL; if (cc[-1] == XCL_NOTPROP) { jump = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, (int)cc[1]); if (invertcmp) { add_jump(compiler, backtracks, jump); jump = NULL; } invertcmp ^= 0x1; } OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_script_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f)); add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp)); if (jump != NULL) JUMPHERE(jump); } cc += 2; } } if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); else if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR) OP1(SLJIT_MOV, TMP2, 0, RETURN_ADDR, 0); cc = ccbegin; } if (unicode_status & XCLASS_SAVE_CHAR) OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0); if (unicode_status & XCLASS_HAS_TYPE) { if (unicode_status & XCLASS_SAVE_CHAR) typereg = RETURN_ADDR; OP1(SLJIT_MOV_U8, typereg, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype)); } } #endif /* SUPPORT_UNICODE */ /* Generating code. */ charoffset = 0; numberofcmps = 0; #ifdef SUPPORT_UNICODE typeoffset = 0; #endif /* SUPPORT_UNICODE */ while (*cc != XCL_END) { compares--; invertcmp = (compares == 0 && list != backtracks); jump = NULL; if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) { OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_EQUAL); numberofcmps++; } else if (numberofcmps > 0) { OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); numberofcmps = 0; } else { jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); numberofcmps = 0; } } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); SET_CHAR_OFFSET(c); GETCHARINCTEST(c, cc); if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) { OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); numberofcmps++; } else if (numberofcmps > 0) { OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); numberofcmps = 0; } else { jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); numberofcmps = 0; } } #ifdef SUPPORT_UNICODE else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); if (*cc == XCL_NOTPROP) invertcmp ^= 0x1; cc++; switch(*cc) { case PT_ANY: if (!invertcmp) jump = JUMP(SLJIT_JUMP); break; case PT_LAMP: OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_GC: c = PRIV(ucp_typerange)[(int)cc[1] * 2]; SET_TYPE_OFFSET(c); jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c); break; case PT_PC: jump = CMP(SLJIT_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset); break; case PT_SC: case PT_SCX: case PT_BOOL: case PT_BIDICL: compares++; /* Do nothing. */ break; case PT_SPACE: case PT_PXSPACE: SET_CHAR_OFFSET(9); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0xd - 0x9); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x85 - 0x9); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x9); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); SET_TYPE_OFFSET(ucp_Zl); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_WORD: OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset)); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); /* Fall through. */ case PT_ALNUM: SET_TYPE_OFFSET(ucp_Ll); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); SET_TYPE_OFFSET(ucp_Nd); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_CLIST: other_cases = PRIV(ucd_caseless_sets) + cc[1]; /* At least three characters are required. Otherwise this case would be handled by the normal code path. */ SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR); SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]); /* Optimizing character pairs, if their difference is power of 2. */ if (is_powerof2(other_cases[1] ^ other_cases[0])) { if (charoffset == 0) OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); else { OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); } OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[1]); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); other_cases += 2; } else if (is_powerof2(other_cases[2] ^ other_cases[1])) { if (charoffset == 0) OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]); else { OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); } OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[2]); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset)); OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL); other_cases += 3; } else { OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); } while (*other_cases != NOTACHAR) { OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL); } jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_UCNC: OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset)); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset)); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset)); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); SET_CHAR_OFFSET(0xa0); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset)); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); SET_CHAR_OFFSET(0); OP2U(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0xe000 - 0); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_GREATER_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_PXGRAPH: /* C and Z groups are the farthest two groups. */ SET_TYPE_OFFSET(ucp_Ll); OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER); jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); /* In case of ucp_Cf, we overwrite the result. */ SET_CHAR_OFFSET(0x2066); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); JUMPHERE(jump); jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); break; case PT_PXPRINT: /* C and Z groups are the farthest two groups. */ SET_TYPE_OFFSET(ucp_Ll); OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER); OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll); OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_NOT_EQUAL); jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); /* In case of ucp_Cf, we overwrite the result. */ SET_CHAR_OFFSET(0x2066); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); JUMPHERE(jump); jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); break; case PT_PXPUNCT: SET_TYPE_OFFSET(ucp_Sc); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); SET_CHAR_OFFSET(0); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x7f); OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_LESS_EQUAL); SET_TYPE_OFFSET(ucp_Pc); OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; default: SLJIT_UNREACHABLE(); break; } cc += 2; } #endif /* SUPPORT_UNICODE */ if (jump != NULL) add_jump(compiler, compares > 0 ? list : backtracks, jump); } if (found != NULL) set_jumps(found, LABEL()); }",1 "bool ConstantFolding::MulConvPushDown(GraphDef* optimized_graph, NodeDef* node, const GraphProperties& properties) { // Push down multiplication on ConvND. // * ConvND // / \ / \ // ConvND C2 -- > X * // / \ / \ // X C1 C1 C2 // // where C1 and C2 are constants and X is non-constant. // // TODO(rmlarsen): Use PrepareConstantPushDown() to simplify this code. if (!IsAnyMul(*node) || NumNonControlInputs(*node) != 2) return false; NodeDef* mul_left_child = node_map_->GetNode(node->input(0)); NodeDef* mul_right_child = node_map_->GetNode(node->input(1)); // One child must be constant, and the second must be Conv op. const bool left_child_is_constant = IsReallyConstant(*mul_left_child); const bool right_child_is_constant = IsReallyConstant(*mul_right_child); if (!left_child_is_constant && !right_child_is_constant) { return false; } NodeDef* conv_node = left_child_is_constant ? mul_right_child : mul_left_child; if (!IsConv2D(*conv_node) && !IsConv3D(*conv_node)) { return false; } if (node->device() != mul_left_child->device() || node->device() != mul_right_child->device()) { return false; } // Make sure that it is safe to change the value of the convolution // output. if (conv_node->input_size() < 2 || NumNonControlOutputs(*conv_node, *node_map_) > 1 || nodes_to_preserve_.find(conv_node->name()) != nodes_to_preserve_.end()) { return false; } // Identify the nodes to swap. NodeDef* conv_left_child = node_map_->GetNode(conv_node->input(0)); NodeDef* conv_right_child = node_map_->GetNode(conv_node->input(1)); const bool conv_left_is_constant = IsReallyConstant(*conv_left_child); const bool conv_right_is_constant = IsReallyConstant(*conv_right_child); if (!conv_left_is_constant && !conv_right_is_constant) { // At least one of the convolution inputs should be constant. return false; } if (conv_left_is_constant && conv_right_is_constant) { // Leverage regular constant folding to handle this. return false; } const auto& mul_props = properties.GetOutputProperties(node->name()); const auto& conv_props = properties.GetOutputProperties(conv_node->name()); if (mul_props.empty() || conv_props.empty()) { return false; } const auto& mul_shape = mul_props[0].shape(); const auto& conv_shape = conv_props[0].shape(); if (!ShapesSymbolicallyEqual(mul_shape, conv_shape)) { return false; } const auto& input_props = properties.GetInputProperties(conv_node->name()); if (input_props.size() < 2) { return false; } const auto& filter_shape = input_props[1].shape(); NodeDef* const_node = left_child_is_constant ? mul_left_child : mul_right_child; const auto& const_props = properties.GetOutputProperties(const_node->name()); if (const_props.empty()) { return false; } const auto& const_shape = const_props[0].shape(); if (!IsValidConstShapeForMulConvPushDown( conv_node->attr().at(""data_format"").s(), filter_shape, const_shape)) { return false; } string mul_new_name = AddPrefixToNodeName(""merged_input"", conv_node->name()); if (node_map_->NodeExists(mul_new_name)) { return false; } // Make sure we don't introduce loops in the graph by removing control // dependencies from the conv2d node to c2. string conv_const_input = conv_left_is_constant ? conv_node->input(0) : conv_node->input(1); if (MaybeRemoveControlInput(conv_node->name(), const_node, optimized_graph, node_map_.get())) { // Add a control dep from c1 to c2 to ensure c2 is in the right frame MaybeAddControlInput(conv_const_input, const_node, optimized_graph, node_map_.get()); } conv_node->set_name(node->name()); node->set_name(mul_new_name); if (conv_left_is_constant) { node_map_->UpdateInput(conv_node->name(), node->input(0), mul_new_name); conv_node->set_input(0, mul_new_name); } else { node_map_->UpdateInput(conv_node->name(), node->input(1), mul_new_name); conv_node->set_input(1, mul_new_name); } NodeDef* conv_const_node = conv_left_is_constant ? conv_left_child : conv_right_child; if (left_child_is_constant) { node->set_input(1, conv_const_node->name()); } else { node->set_input(0, conv_const_node->name()); } node_map_->AddNode(mul_new_name, node); return true; }",1 " void Compute(OpKernelContext* context) override { const Tensor& indices = context->input(0); const Tensor& values = context->input(1); const Tensor& shape = context->input(2); const Tensor& weights = context->input(3); bool use_weights = weights.NumElements() > 0; OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()), errors::InvalidArgument( ""Input indices must be a 2-dimensional tensor. Got: "", indices.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(values.shape()), errors::InvalidArgument(""Input values must be a vector. Got: "", values.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(shape.shape()), errors::InvalidArgument(""Input shape must be a vector. Got: "", shape.shape().DebugString())); OP_REQUIRES(context, values.shape().dim_size(0) == indices.shape().dim_size(0), errors::InvalidArgument( ""Number of values must match first dimension of indices."", ""Got "", values.shape().dim_size(0), "" values, indices shape: "", indices.shape().DebugString())); OP_REQUIRES( context, shape.shape().dim_size(0) == indices.shape().dim_size(1), errors::InvalidArgument( ""Number of dimensions must match second dimension of indices."", ""Got "", shape.shape().dim_size(0), "" dimensions, indices shape: "", indices.shape().DebugString())); OP_REQUIRES(context, shape.NumElements() > 0, errors::InvalidArgument( ""The shape argument requires at least one element."")); if (use_weights) { OP_REQUIRES( context, weights.shape() == values.shape(), errors::InvalidArgument( ""Weights and values must have the same shape. Weight shape: "", weights.shape().DebugString(), ""; values shape: "", values.shape().DebugString())); } bool is_1d = shape.NumElements() == 1; auto shape_vector = shape.flat(); int num_batches = is_1d ? 1 : shape_vector(0); int num_values = values.NumElements(); const auto indices_values = indices.matrix(); const auto values_values = values.flat(); const auto weight_values = weights.flat(); auto per_batch_counts = BatchedMap(num_batches); T max_value = 0; for (int idx = 0; idx < num_values; ++idx) { int batch = is_1d ? 0 : indices_values(idx, 0); if (batch >= num_batches) { OP_REQUIRES(context, batch < num_batches, errors::InvalidArgument( ""Indices value along the first dimension must be "", ""lower than the first index of the shape."", ""Got "", batch, "" as batch and "", num_batches, "" as the first dimension of the shape."")); } const auto& value = values_values(idx); if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) { if (binary_output_) { per_batch_counts[batch][value] = 1; } else if (use_weights) { per_batch_counts[batch][value] += weight_values(idx); } else { per_batch_counts[batch][value]++; } if (value > max_value) { max_value = value; } } } int num_output_values = GetOutputSize(max_value, maxlength_, minlength_); OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values, is_1d, context)); }",1 " void Compute(OpKernelContext* context) override { const Tensor& rhs = context->input(1); // We always return the input ref. context->forward_ref_input_to_ref_output(0, 0); // We can't always know how this value will be used downstream, so make // conservative assumptions in specifying constraints on the memory // allocation attributes, unless the Grappler graph analysis determined that // it was safe not to. AllocatorAttributes attr; if (!relax_constraints_) { attr.set_gpu_compatible(true); attr.set_nic_compatible(true); } { mutex_lock l(*context->input_ref_mutex(0)); const Tensor& old_lhs = context->mutable_input(0, /* lock_held */ true); const bool same_shape = old_lhs.shape().IsSameSize(rhs.shape()); if (validate_shape_) { OP_REQUIRES(context, same_shape, errors::InvalidArgument( ""Assign requires shapes of both tensors to match. "" ""lhs shape= "", old_lhs.shape().DebugString(), "" rhs shape= "", rhs.shape().DebugString())); } // In the code below we try to minimize the amount of memory allocation // and copying by trying the following two shortcuts: // 1. If the lhs is initialized and has the same number of elements as // the rhs we can avoid a memory allocation. // 2. If we can reuse the rhs buffer we avoid both a memory allocation // and copying. // 1. Try to copy into an existing buffer. if (old_lhs.IsInitialized() && old_lhs.shape().num_elements() == rhs.shape().num_elements()) { // The existing lhs tensor has already been initialized and the right // hand side can fit in the underlying buffer. Tensor reshaped_old_lhs; if (same_shape) { reshaped_old_lhs = old_lhs; } else { CHECK(reshaped_old_lhs.CopyFrom(old_lhs, rhs.shape())); context->replace_ref_input(0, reshaped_old_lhs, /* lock_held */ true); } if (use_exclusive_lock_) { Copy(context, &reshaped_old_lhs, rhs); return; } } else { // 2. Try to reuse the rhs. std::unique_ptr input_alias = context->forward_input( 1, OpKernelContext::Params::kNoReservation /*output_index*/, rhs.dtype(), rhs.shape(), DEVICE_MEMORY, attr); if (input_alias != nullptr) { // Update the ref to point to the new buffer. context->replace_ref_input(0, *input_alias, /* lock_held */ true); return; } // Otherwise, create a new tensor whose shape matches the // right hand side, hand off to lhs and copy the rhs into it. Tensor copy_tensor; OP_REQUIRES_OK(context, context->allocate_temp(old_lhs.dtype(), rhs.shape(), ©_tensor, attr)); // We track memory of variables in variable ops instead of in this // assign op. context->clear_recorded_memory(); context->replace_ref_input(0, copy_tensor, /* lock_held */ true); if (use_exclusive_lock_) { Copy(context, ©_tensor, rhs); return; } } } // The tensor has already been initialized and the right hand side // matches the left hand side's shape. We have been told to do the // copy outside the lock. Tensor old_unlocked_lhs = context->mutable_input(0, /* lock_held */ false); Copy(context, &old_unlocked_lhs, rhs); }",1 "gen_hash(codegen_scope *s, node *tree, int val, int limit) { int slimit = GEN_VAL_STACK_MAX; if (cursp() >= GEN_LIT_ARY_MAX) slimit = INT16_MAX; int len = 0; mrb_bool update = FALSE; while (tree) { if (nint(tree->car->car->car) == NODE_KW_REST_ARGS) { if (len > 0) { pop_n(len*2); if (!update) { genop_2(s, OP_HASH, cursp(), len); } else { pop(); genop_2(s, OP_HASHADD, cursp(), len); } push(); } codegen(s, tree->car->cdr, val); if (len > 0 || update) { pop(); pop(); genop_1(s, OP_HASHCAT, cursp()); push(); } update = TRUE; len = 0; } else { codegen(s, tree->car->car, val); codegen(s, tree->car->cdr, val); len++; } tree = tree->cdr; if (val && cursp() >= slimit) { pop_n(len*2); if (!update) { genop_2(s, OP_HASH, cursp(), len); } else { pop(); genop_2(s, OP_HASHADD, cursp(), len); } push(); update = TRUE; len = 0; } } if (update) { if (val && len > 0) { pop_n(len*2+1); genop_2(s, OP_HASHADD, cursp(), len); push(); } return -1; /* variable length */ } return len; }",1 " void Compute(OpKernelContext* ctx) override { StagingMap* map = nullptr; OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map)); core::ScopedUnref scope(map); typename StagingMap::OptionalTuple tuple; const Tensor* key_tensor; const Tensor* indices_tensor; OpInputList values_tensor; OP_REQUIRES_OK(ctx, ctx->input(""key"", &key_tensor)); OP_REQUIRES_OK(ctx, ctx->input(""indices"", &indices_tensor)); OP_REQUIRES_OK(ctx, ctx->input_list(""values"", &values_tensor)); OP_REQUIRES(ctx, key_tensor->NumElements() > 0, errors::InvalidArgument(""key must not be empty"")); // Create copy for insertion into Staging Area Tensor key(*key_tensor); // Create the tuple to store for (std::size_t i = 0; i < values_tensor.size(); ++i) { tuple.push_back(values_tensor[i]); } // Store the tuple in the map OP_REQUIRES_OK(ctx, map->put(&key, indices_tensor, &tuple)); }",1 "gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val) { int idx; int type = nint(tree->car); switch (type) { case NODE_GVAR: case NODE_ARG: case NODE_LVAR: case NODE_IVAR: case NODE_CVAR: case NODE_CONST: case NODE_NIL: case NODE_MASGN: if (rhs) { codegen(s, rhs, VAL); pop(); sp = cursp(); } break; case NODE_COLON2: case NODE_CALL: case NODE_SCALL: /* keep evaluation order */ break; case NODE_NVAR: codegen_error(s, ""Can't assign to numbered parameter""); break; default: codegen_error(s, ""unknown lhs""); break; } tree = tree->cdr; switch (type) { case NODE_GVAR: gen_setxv(s, OP_SETGV, sp, nsym(tree), val); break; case NODE_ARG: case NODE_LVAR: idx = lv_idx(s, nsym(tree)); if (idx > 0) { if (idx != sp) { gen_move(s, idx, sp, val); } break; } else { /* upvar */ gen_setupvar(s, sp, nsym(tree)); } break; case NODE_IVAR: gen_setxv(s, OP_SETIV, sp, nsym(tree), val); break; case NODE_CVAR: gen_setxv(s, OP_SETCV, sp, nsym(tree), val); break; case NODE_CONST: gen_setxv(s, OP_SETCONST, sp, nsym(tree), val); break; case NODE_COLON2: if (sp) { gen_move(s, cursp(), sp, 0); } sp = cursp(); push(); codegen(s, tree->car, VAL); if (rhs) { codegen(s, rhs, VAL); pop(); gen_move(s, sp, cursp(), 0); } pop_n(2); idx = new_sym(s, nsym(tree->cdr)); genop_2(s, OP_SETMCNST, sp, idx); break; case NODE_CALL: case NODE_SCALL: { int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0; mrb_sym mid = nsym(tree->cdr->car); top = cursp(); if (val || sp == cursp()) { push(); /* room for retval */ } call = cursp(); if (!tree->car) { noself = 1; push(); } else { codegen(s, tree->car, VAL); /* receiver */ } if (safe) { int recv = cursp()-1; gen_move(s, cursp(), recv, 1); skip = genjmp2_0(s, OP_JMPNIL, cursp(), val); } tree = tree->cdr->cdr->car; if (tree) { if (tree->car) { /* positional arguments */ n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14); if (n < 0) { /* variable length */ n = 15; push(); } } if (tree->cdr->car) { /* keyword arguments */ if (n == 14) { pop_n(n); genop_2(s, OP_ARRAY, cursp(), n); push(); n = 15; } gen_hash(s, tree->cdr->car->cdr, VAL, 0); if (n < 14) { n++; } else { pop_n(2); genop_2(s, OP_ARYPUSH, cursp(), 1); } push(); } } if (rhs) { codegen(s, rhs, VAL); pop(); } else { gen_move(s, cursp(), sp, 0); } if (val) { gen_move(s, top, cursp(), 1); } if (n < 15) { n++; if (n == 15) { pop_n(14); genop_2(s, OP_ARRAY, cursp(), 15); } } else { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } s->sp = call; if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) { genop_1(s, OP_SETIDX, cursp()); } else { genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n); } if (safe) { dispatch(s, skip); } s->sp = top; } break; case NODE_MASGN: gen_massignment(s, tree->car, sp, val); break; /* splat without assignment */ case NODE_NIL: break; default: codegen_error(s, ""unknown lhs""); break; } if (val) push(); }",1 " void publish(Topic *iterator, size_t start, size_t stop, std::string_view topic, std::pair message) { /* If we already have 64 triggered topics make sure to drain it here */ if (numTriggeredTopics == 64) { drain(); } /* Iterate over all segments in given topic */ for (; stop != std::string::npos; start = stop + 1) { stop = topic.find('/', start); std::string_view segment = topic.substr(start, stop - start); /* It is very important to disallow wildcards when publishing. * We will not catch EVERY misuse this lazy way, but enough to hinder * explosive recursion. * Terminating wildcards MAY still get triggered along the way, if for * instace the error is found late while iterating the topic segments. */ if (segment.length() == 1) { if (segment[0] == '+' || segment[0] == '#') { return; } } /* Do we have a terminating wildcard child? */ if (iterator->terminatingWildcardChild) { iterator->terminatingWildcardChild->messages[messageId] = message; /* Add this topic to triggered */ if (!iterator->terminatingWildcardChild->triggered) { triggeredTopics[numTriggeredTopics++] = iterator->terminatingWildcardChild; iterator->terminatingWildcardChild->triggered = true; } } /* Do we have a wildcard child? */ if (iterator->wildcardChild) { publish(iterator->wildcardChild, stop + 1, stop, topic, message); } std::map::iterator it = iterator->children.find(segment); if (it == iterator->children.end()) { /* Stop trying to match by exact string */ return; } iterator = it->second; } /* If we went all the way we matched exactly */ iterator->messages[messageId] = message; /* Add this topic to triggered */ if (!iterator->triggered) { triggeredTopics[numTriggeredTopics++] = iterator; iterator->triggered = true; } }",1 "R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) { RIOBank *bank = r_io_bank_get (io, bankid); RIOMap *map = r_io_map_get (io, mapid); r_return_val_if_fail (io && bank && map, false); RIOMapRef *mapref = _mapref_from_map (map); if (!mapref) { return false; } RIOSubMap *sm = r_io_submap_new (io, mapref); if (!sm) { free (mapref); return false; } RRBNode *entry = _find_entry_submap_node (bank, sm); if (!entry) { // no intersection with any submap, so just insert if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } bank->last_used = NULL; RIOSubMap *bd = (RIOSubMap *)entry->data; if (r_io_submap_to (bd) == r_io_submap_to (sm) && r_io_submap_from (bd) >= r_io_submap_from (sm)) { // _find_entry_submap_node guarantees, that there is no submap // prior to bd in the range of sm, so instead of deleting and inserting // we can just memcpy memcpy (bd, sm, sizeof (RIOSubMap)); free (sm); r_list_append (bank->maprefs, mapref); return true; } if (r_io_submap_from (bd) < r_io_submap_from (sm) && r_io_submap_to (sm) < r_io_submap_to (bd)) { // split bd into 2 maps => bd and bdsm RIOSubMap *bdsm = R_NEWCOPY (RIOSubMap, bd); if (!bdsm) { free (sm); free (mapref); return false; } r_io_submap_set_from (bdsm, r_io_submap_to (sm) + 1); r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); // TODO: insert and check return value, before adjusting sm size if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (bdsm); free (mapref); return false; } if (!r_crbtree_insert (bank->submaps, bdsm, _find_sm_by_from_vaddr_cb, NULL)) { r_crbtree_delete (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL); free (sm); free (bdsm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } // guaranteed intersection if (r_io_submap_from (bd) < r_io_submap_from (sm)) { r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); entry = r_rbnode_next (entry); } while (entry && r_io_submap_to (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { //delete all submaps that are completly included in sm RRBNode *next = r_rbnode_next (entry); // this can be optimized, there is no need to do search here r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL); entry = next; } if (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { bd = (RIOSubMap *)entry->data; r_io_submap_set_from (bd, r_io_submap_to (sm) + 1); } if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; }",1 "setup_seccomp (FlatpakBwrap *bwrap, const char *arch, gulong allowed_personality, FlatpakRunFlags run_flags, GError **error) { gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0; gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0; __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL; /**** BEGIN NOTE ON CODE SHARING * * There are today a number of different Linux container * implementations. That will likely continue for long into the * future. But we can still try to share code, and it's important * to do so because it affects what library and application writers * can do, and we should support code portability between different * container tools. * * This syscall blocklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blocklist. * * If you make any changes here, I suggest sending the changes along * to other sandbox maintainers. Using the libseccomp list is also * an appropriate venue: * https://groups.google.com/forum/#!forum/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blocklist: * * https://github.com/sandstorm-io/sandstorm * in src/sandstorm/supervisor.c++ * https://github.com/flatpak/flatpak.git * in common/flatpak-run.c * https://git.gnome.org/browse/linux-user-chroot * in src/setup-seccomp.c * * Other useful resources: * https://github.com/systemd/systemd/blob/HEAD/src/shared/seccomp-util.c * https://github.com/moby/moby/blob/HEAD/profiles/seccomp/default.json * **** END NOTE ON CODE SHARING */ struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_blocklist[] = { /* Block dmesg */ {SCMP_SYS (syslog), EPERM}, /* Useless old syscall */ {SCMP_SYS (uselib), EPERM}, /* Don't allow disabling accounting */ {SCMP_SYS (acct), EPERM}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt), EPERM}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl), EPERM}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key), EPERM}, {SCMP_SYS (keyctl), EPERM}, {SCMP_SYS (request_key), EPERM}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages), EPERM}, {SCMP_SYS (mbind), EPERM}, {SCMP_SYS (get_mempolicy), EPERM}, {SCMP_SYS (set_mempolicy), EPERM}, {SCMP_SYS (migrate_pages), EPERM}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare), EPERM}, {SCMP_SYS (setns), EPERM}, {SCMP_SYS (mount), EPERM}, {SCMP_SYS (umount), EPERM}, {SCMP_SYS (umount2), EPERM}, {SCMP_SYS (pivot_root), EPERM}, #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__) /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack * and flags arguments are reversed so the flags come second */ {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #else /* Normally the flags come first */ {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #endif /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)}, /* seccomp can't look into clone3()'s struct clone_args to check whether * the flags are OK, so we have no choice but to block clone3(). * Return ENOSYS so user-space will fall back to clone(). * (GHSA-67h7-w3jq-vh4q; see also https://github.com/moby/moby/commit/9f6b562d) */ {SCMP_SYS (clone3), ENOSYS}, /* New mount manipulation APIs can also change our VFS. There's no * legitimate reason to do these in the sandbox, so block all of them * rather than thinking about which ones might be dangerous. * (GHSA-67h7-w3jq-vh4q) */ {SCMP_SYS (open_tree), ENOSYS}, {SCMP_SYS (move_mount), ENOSYS}, {SCMP_SYS (fsopen), ENOSYS}, {SCMP_SYS (fsconfig), ENOSYS}, {SCMP_SYS (fsmount), ENOSYS}, {SCMP_SYS (fspick), ENOSYS}, {SCMP_SYS (mount_setattr), ENOSYS}, }; struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_nondevel_blocklist[] = { /* Profiling operations; we expect these to be done by tools from outside * the sandbox. In particular perf has been the source of many CVEs. */ {SCMP_SYS (perf_event_open), EPERM}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace), EPERM} }; /* Blocklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_allowlist[] = { /* NOTE: Keep in numerical order */ { AF_UNSPEC, 0 }, { AF_LOCAL, 0 }, { AF_INET, 0 }, { AF_INET6, 0 }, { AF_NETLINK, 0 }, { AF_CAN, FLATPAK_RUN_FLAG_CANBUS }, { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH }, }; int last_allowed_family; int i, r; g_auto(GLnxTmpfile) seccomp_tmpf = { 0, }; seccomp = seccomp_init (SCMP_ACT_ALLOW); if (!seccomp) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Initialize seccomp failed"")); if (arch != NULL) { uint32_t arch_id = 0; const uint32_t *extra_arches = NULL; if (strcmp (arch, ""i386"") == 0) { arch_id = SCMP_ARCH_X86; } else if (strcmp (arch, ""x86_64"") == 0) { arch_id = SCMP_ARCH_X86_64; extra_arches = seccomp_x86_64_extra_arches; } else if (strcmp (arch, ""arm"") == 0) { arch_id = SCMP_ARCH_ARM; } #ifdef SCMP_ARCH_AARCH64 else if (strcmp (arch, ""aarch64"") == 0) { arch_id = SCMP_ARCH_AARCH64; extra_arches = seccomp_aarch64_extra_arches; } #endif /* We only really need to handle arches on multiarch systems. * If only one arch is supported the default is fine */ if (arch_id != 0) { /* This *adds* the target arch, instead of replacing the native one. This is not ideal, because we'd like to only allow the target arch, but we can't really disallow the native arch at this point, because then bubblewrap couldn't continue running. */ r = seccomp_arch_add (seccomp, arch_id); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add architecture to seccomp filter"")); if (multiarch && extra_arches != NULL) { for (i = 0; extra_arches[i] != 0; i++) { r = seccomp_arch_add (seccomp, extra_arches[i]); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add multiarch architecture to seccomp filter"")); } } } } /* TODO: Should we filter the kernel keyring syscalls in some way? * We do want them to be used by desktop apps, but they could also perhaps * leak system stuff or secrets from other apps. */ for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++) { int scall = syscall_blocklist[i].scall; int errnum = syscall_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } if (!devel) { for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++) { int scall = syscall_nondevel_blocklist[i].scall; int errnum = syscall_nondevel_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_nondevel_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } } /* Socket filtering doesn't work on e.g. i386, so ignore failures here * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing * something else: https://github.com/seccomp/libseccomp/issues/8 */ last_allowed_family = -1; for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++) { int family = socket_family_allowlist[i].family; int disallowed; if (socket_family_allowlist[i].flags_mask != 0 && (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blocklist the in-between valid families */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed)); } last_allowed_family = family; } /* Blocklist the rest */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1)); if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, ""/tmp"", &seccomp_tmpf, error)) return FALSE; if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to export bpf"")); lseek (seccomp_tmpf.fd, 0, SEEK_SET); flatpak_bwrap_add_args_data_fd (bwrap, ""--seccomp"", glnx_steal_fd (&seccomp_tmpf.fd), NULL); return TRUE; }",1 "gopherToHTML(GopherStateData * gopherState, char *inbuf, int len) { char *pos = inbuf; char *lpos = NULL; char *tline = NULL; LOCAL_ARRAY(char, line, TEMP_BUF_SIZE); LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE); char *name = NULL; char *selector = NULL; char *host = NULL; char *port = NULL; char *escaped_selector = NULL; const char *icon_url = NULL; char gtype; StoreEntry *entry = NULL; memset(tmpbuf, '\0', TEMP_BUF_SIZE); memset(line, '\0', TEMP_BUF_SIZE); entry = gopherState->entry; if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, ""Gopher Index %s"", html_url); storeAppendPrintf(entry, ""

This is a searchable Gopher index. Use the search\n"" ""function of your browser to enter search terms.\n"" ""\n""); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, ""CSO Search of %s"", html_url); storeAppendPrintf(entry, ""

A CSO database usually contains a phonebook or\n"" ""directory. Use the search function of your browser to enter\n"" ""search terms.

\n""); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } String outbuf; if (!gopherState->HTML_header_added) { if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT) gopherHTMLHeader(entry, ""CSO Search Result"", NULL); else gopherHTMLHeader(entry, ""Gopher Menu"", NULL); outbuf.append (""
"");

        gopherState->HTML_header_added = 1;

        gopherState->HTML_pre = 1;
    }

    while (pos < inbuf + len) {
        int llen;
        int left = len - (pos - inbuf);
        lpos = (char *)memchr(pos, '\n', left);
        if (lpos) {
            ++lpos;             /* Next line is after \n */
            llen = lpos - pos;
        } else {
            llen = left;
        }
        if (gopherState->len + llen >= TEMP_BUF_SIZE) {
            debugs(10, DBG_IMPORTANT, ""GopherHTML: Buffer overflow. Lost some data on URL: "" << entry->url()  );
            llen = TEMP_BUF_SIZE - gopherState->len - 1;
            gopherState->overflowed = true; // may already be true
        }
        if (!lpos) {
            /* there is no complete line in inbuf */
            /* copy it to temp buffer */
            /* note: llen is adjusted above */
            memcpy(gopherState->buf + gopherState->len, pos, llen);
            gopherState->len += llen;
            break;
        }
        if (gopherState->len != 0) {
            /* there is something left from last tx. */
            memcpy(line, gopherState->buf, gopherState->len);
            memcpy(line + gopherState->len, pos, llen);
            llen += gopherState->len;
            gopherState->len = 0;
        } else {
            memcpy(line, pos, llen);
        }
        line[llen + 1] = '\0';
        /* move input to next line */
        pos = lpos;

        /* at this point. We should have one line in buffer to process */

        if (*line == '.') {
            /* skip it */
            memset(line, '\0', TEMP_BUF_SIZE);
            continue;
        }

        switch (gopherState->conversion) {

        case GopherStateData::HTML_INDEX_RESULT:

        case GopherStateData::HTML_DIR: {
            tline = line;
            gtype = *tline;
            ++tline;
            name = tline;
            selector = strchr(tline, TAB);

            if (selector) {
                *selector = '\0';
                ++selector;
                host = strchr(selector, TAB);

                if (host) {
                    *host = '\0';
                    ++host;
                    port = strchr(host, TAB);

                    if (port) {
                        char *junk;
                        port[0] = ':';
                        junk = strchr(host, TAB);

                        if (junk)
                            *junk++ = 0;    /* Chop port */
                        else {
                            junk = strchr(host, '\r');

                            if (junk)
                                *junk++ = 0;    /* Chop port */
                            else {
                                junk = strchr(host, '\n');

                                if (junk)
                                    *junk++ = 0;    /* Chop port */
                            }
                        }

                        if ((port[1] == '0') && (!port[2]))
                            port[0] = 0;    /* 0 means none */
                    }

                    /* escape a selector here */
                    escaped_selector = xstrdup(rfc1738_escape_part(selector));

                    switch (gtype) {

                    case GOPHER_DIRECTORY:
                        icon_url = mimeGetIconURL(""internal-menu"");
                        break;

                    case GOPHER_HTML:

                    case GOPHER_FILE:
                        icon_url = mimeGetIconURL(""internal-text"");
                        break;

                    case GOPHER_INDEX:

                    case GOPHER_CSO:
                        icon_url = mimeGetIconURL(""internal-index"");
                        break;

                    case GOPHER_IMAGE:

                    case GOPHER_GIF:

                    case GOPHER_PLUS_IMAGE:
                        icon_url = mimeGetIconURL(""internal-image"");
                        break;

                    case GOPHER_SOUND:

                    case GOPHER_PLUS_SOUND:
                        icon_url = mimeGetIconURL(""internal-sound"");
                        break;

                    case GOPHER_PLUS_MOVIE:
                        icon_url = mimeGetIconURL(""internal-movie"");
                        break;

                    case GOPHER_TELNET:

                    case GOPHER_3270:
                        icon_url = mimeGetIconURL(""internal-telnet"");
                        break;

                    case GOPHER_BIN:

                    case GOPHER_MACBINHEX:

                    case GOPHER_DOSBIN:

                    case GOPHER_UUENCODED:
                        icon_url = mimeGetIconURL(""internal-binary"");
                        break;

                    case GOPHER_INFO:
                        icon_url = NULL;
                        break;

                    case GOPHER_WWW:
                        icon_url = mimeGetIconURL(""internal-link"");
                        break;

                    default:
                        icon_url = mimeGetIconURL(""internal-unknown"");
                        break;
                    }

                    memset(tmpbuf, '\0', TEMP_BUF_SIZE);

                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {
                        if (strlen(escaped_selector) != 0)
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, escaped_selector, rfc1738_escape_part(host),
                                     *port ? "":"" : """", port, html_quote(name));
                        else
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, rfc1738_escape_part(host), *port ? "":"" : """",
                                     port, html_quote(name));

                    } else if (gtype == GOPHER_INFO) {
                        snprintf(tmpbuf, TEMP_BUF_SIZE, ""\t%s\n"", html_quote(name));
                    } else {
                        if (strncmp(selector, ""GET /"", 5) == 0) {
                            /* WWW link */
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));
                        } else if (gtype == GOPHER_WWW) {
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, rfc1738_escape_unescaped(selector), html_quote(name));
                        } else {
                            /* Standard link */
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, host, gtype, escaped_selector, html_quote(name));
                        }
                    }

                    safe_free(escaped_selector);
                    outbuf.append(tmpbuf);
                } else {
                    memset(line, '\0', TEMP_BUF_SIZE);
                    continue;
                }
            } else {
                memset(line, '\0', TEMP_BUF_SIZE);
                continue;
            }

            break;
            }           /* HTML_DIR, HTML_INDEX_RESULT */

        case GopherStateData::HTML_CSO_RESULT: {
            if (line[0] == '-') {
                int code, recno;
                char *s_code, *s_recno, *result;

                s_code = strtok(line + 1, "":\n"");
                s_recno = strtok(NULL, "":\n"");
                result = strtok(NULL, ""\n"");

                if (!result)
                    break;

                code = atoi(s_code);

                recno = atoi(s_recno);

                if (code != 200)
                    break;

                if (gopherState->cso_recno != recno) {
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""

Record# %d
%s

\n
"", recno, html_quote(result));
                    gopherState->cso_recno = recno;
                } else {
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""%s\n"", html_quote(result));
                }

                outbuf.append(tmpbuf);
                break;
            } else {
                int code;
                char *s_code, *result;

                s_code = strtok(line, "":"");
                result = strtok(NULL, ""\n"");

                if (!result)
                    break;

                code = atoi(s_code);

                switch (code) {

                case 200: {
                    /* OK */
                    /* Do nothing here */
                    break;
                }

                case 102:   /* Number of matches */

                case 501:   /* No Match */

                case 502: { /* Too Many Matches */
                    /* Print the message the server returns */
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""

%s

\n
"", html_quote(result));
                    outbuf.append(tmpbuf);
                    break;
                }

                }
            }

            break;
            }           /* HTML_CSO_RESULT */
        default:
            break;      /* do nothing */

        }           /* switch */

    }               /* while loop */

    if (outbuf.size() > 0) {
        entry->append(outbuf.rawBuf(), outbuf.size());
        /* now let start sending stuff to client */
        entry->flush();
    }

    outbuf.clean();
    return;
}",1
"char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type)
{
	u32 i, j, len;
	char *sOK;
	char szLineConv[1024];
	unsigned short *sptr;

	memset(szLine, 0, sizeof(char)*lineSize);
	sOK = gf_fgets(szLine, lineSize, txt_in);
	if (!sOK) return NULL;
	if (unicode_type<=1) {
		j=0;
		len = (u32) strlen(szLine);
		for (i=0; i> 6) & 0x3 );
					j++;
					szLine[i] &= 0xbf;
				}
				/*UTF8 2 bytes char*/
				else if ( (szLine[i] & 0xe0) == 0xc0) {
					szLineConv[j] = szLine[i];
					i++;
					j++;
				}
				/*UTF8 3 bytes char*/
				else if ( (szLine[i] & 0xf0) == 0xe0) {
					szLineConv[j] = szLine[i];
					i++;
					j++;
					szLineConv[j] = szLine[i];
					i++;
					j++;
				}
				/*UTF8 4 bytes char*/
				else if ( (szLine[i] & 0xf8) == 0xf0) {
					szLineConv[j] = szLine[i];
					i++;
					j++;
					szLineConv[j] = szLine[i];
					i++;
					j++;
					szLineConv[j] = szLine[i];
					i++;
					j++;
				} else {
					i+=1;
					continue;
				}
			}
			szLineConv[j] = szLine[i];
			j++;
		}
		szLineConv[j] = 0;
		strcpy(szLine, szLineConv);
		return sOK;
	}

#ifdef GPAC_BIG_ENDIAN
	if (unicode_type==3)
#else
	if (unicode_type==2)
#endif
	{
		i=0;
		while (1) {
			char c;
			if (!szLine[i] && !szLine[i+1]) break;
			c = szLine[i+1];
			szLine[i+1] = szLine[i];
			szLine[i] = c;
			i+=2;
		}
	}
	sptr = (u16 *)szLine;
	i = (u32) gf_utf8_wcstombs(szLineConv, 1024, (const unsigned short **) &sptr);
	szLineConv[i] = 0;
	strcpy(szLine, szLineConv);
	/*this is ugly indeed: since input is UTF16-LE, there are many chances the gf_fgets never reads the \0 after a \n*/
	if (unicode_type==3) gf_fgetc(txt_in);
	return sOK;
}",1
"Status ConcatShapeHelper(InferenceContext* c, int start_value_index,
                         int end_value_index, int dim_index) {
  ShapeHandle unused;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(dim_index), 0, &unused));
  const Tensor* concat_dim_t = c->input_tensor(dim_index);
  if (concat_dim_t == nullptr) {
    // Return an unknown shape with same rank as inputs, or an unknown rank
    // if no input's rank is known.

    // Find rank.
    int32_t rank = InferenceContext::kUnknownRank;
    for (int i = start_value_index; i < end_value_index; ++i) {
      if (rank == InferenceContext::kUnknownRank) rank = c->Rank(c->input(i));
      if (rank != InferenceContext::kUnknownRank) {
        break;
      }
    }
    if (rank == InferenceContext::kUnknownRank) {
      c->set_output(0, c->UnknownShape());
      return Status::OK();
    } else if (rank == 0) {
      return errors::InvalidArgument(
          ""Can't concatenate scalars (use tf.stack instead)"");
    } else {
      for (int i = start_value_index; i < end_value_index; ++i) {
        // Check that all the inputs are of the correct rank.
        TF_RETURN_IF_ERROR(c->WithRank(c->input(i), rank, &unused));
      }
    }
    // Build result of  different unknown dims.
    std::vector dims;
    dims.reserve(rank);
    for (int i = 0; i < rank; ++i) dims.push_back(c->UnknownDim());
    c->set_output(0, c->MakeShape(dims));
    return Status::OK();
  }

  // Merge all the non-concat dims, and sum the concat dim to make an output
  // shape.
  int64_t concat_dim;
  if (concat_dim_t->dtype() == DT_INT32) {
    concat_dim = static_cast(concat_dim_t->flat()(0));
  } else {
    concat_dim = concat_dim_t->flat()(0);
  }

  // Minimum required number of dimensions.
  const int min_rank = concat_dim < 0 ? -concat_dim : concat_dim + 1;

  ShapeHandle output_before;
  ShapeHandle output_after;

  ShapeHandle input = c->input(end_value_index - 1);
  TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, min_rank, &input));
  TF_RETURN_IF_ERROR(c->Subshape(input, 0, concat_dim, &output_before));
  DimensionHandle output_middle = c->Dim(input, concat_dim);
  if (concat_dim == -1) {
    output_after = c->Scalar();  // no dimensions.
  } else {
    TF_RETURN_IF_ERROR(c->Subshape(input, concat_dim + 1, &output_after));
  }

  for (int i = end_value_index - 2; i >= start_value_index; --i) {
    ShapeHandle before;
    ShapeHandle after;
    input = c->input(i);
    TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, min_rank, &input));
    TF_RETURN_IF_ERROR(c->Subshape(input, 0, concat_dim, &before));
    DimensionHandle middle = c->Dim(input, concat_dim);
    if (concat_dim == -1) {
      after = c->Scalar();
    } else {
      TF_RETURN_IF_ERROR(c->Subshape(input, concat_dim + 1, &after));
    }

    TF_RETURN_IF_ERROR(c->Merge(before, output_before, &output_before));
    TF_RETURN_IF_ERROR(c->Add(output_middle, middle, &output_middle));
    TF_RETURN_IF_ERROR(c->Merge(after, output_after, &output_after));
  }

  ShapeHandle s;
  TF_RETURN_IF_ERROR(
      c->Concatenate(output_before, c->Vector(output_middle), &s));
  TF_RETURN_IF_ERROR(c->Concatenate(s, output_after, &s));
  c->set_output(0, s);
  return Status::OK();
}",1
"GF_Err iloc_box_read(GF_Box *s, GF_BitStream *bs)
{
	u32 item_count, extent_count, i, j;
	GF_ItemLocationBox *ptr = (GF_ItemLocationBox *)s;

	ISOM_DECREASE_SIZE(ptr, 2)
	ptr->offset_size = gf_bs_read_int(bs, 4);
	ptr->length_size = gf_bs_read_int(bs, 4);
	ptr->base_offset_size = gf_bs_read_int(bs, 4);
	if (ptr->version == 1 || ptr->version == 2) {
		ptr->index_size = gf_bs_read_int(bs, 4);
	} else {
		gf_bs_read_int(bs, 4);
	}
	if (ptr->version < 2) {
		ISOM_DECREASE_SIZE(ptr, 2)
		item_count = gf_bs_read_u16(bs);
	} else {
		ISOM_DECREASE_SIZE(ptr, 4)
		item_count = gf_bs_read_u32(bs);
	}

	for (i = 0; i < item_count; i++) {
		GF_ItemLocationEntry *location_entry = (GF_ItemLocationEntry *)gf_malloc(sizeof(GF_ItemLocationEntry));
		if (!location_entry) return GF_OUT_OF_MEM;

		gf_list_add(ptr->location_entries, location_entry);
		if (ptr->version < 2) {
			ISOM_DECREASE_SIZE(ptr, 2)
			location_entry->item_ID = gf_bs_read_u16(bs);
		} else {
			ISOM_DECREASE_SIZE(ptr, 4)
			location_entry->item_ID = gf_bs_read_u32(bs);
		}
		if (ptr->version == 1 || ptr->version == 2) {
			ISOM_DECREASE_SIZE(ptr, 2)
			location_entry->construction_method = gf_bs_read_u16(bs);
		}
		else {
			location_entry->construction_method = 0;
		}
		ISOM_DECREASE_SIZE(ptr, (2 + ptr->base_offset_size) )
		location_entry->data_reference_index = gf_bs_read_u16(bs);
		location_entry->base_offset = gf_bs_read_int(bs, 8*ptr->base_offset_size);
#ifndef GPAC_DISABLE_ISOM_WRITE
		location_entry->original_base_offset = location_entry->base_offset;
#endif

		ISOM_DECREASE_SIZE(ptr, 2)
		extent_count = gf_bs_read_u16(bs);
		location_entry->extent_entries = gf_list_new();
		for (j = 0; j < extent_count; j++) {
			GF_ItemExtentEntry *extent_entry = (GF_ItemExtentEntry *)gf_malloc(sizeof(GF_ItemExtentEntry));
			if (!extent_entry) return GF_OUT_OF_MEM;
			
			gf_list_add(location_entry->extent_entries, extent_entry);
			if ((ptr->version == 1 || ptr->version == 2) && ptr->index_size > 0) {
				ISOM_DECREASE_SIZE(ptr, ptr->index_size)
				extent_entry->extent_index = gf_bs_read_int(bs, 8 * ptr->index_size);
			}
			else {
				extent_entry->extent_index = 0;
			}
			ISOM_DECREASE_SIZE(ptr, (ptr->offset_size+ptr->length_size) )

			extent_entry->extent_offset = gf_bs_read_int(bs, 8*ptr->offset_size);
			extent_entry->extent_length = gf_bs_read_int(bs, 8*ptr->length_size);
#ifndef GPAC_DISABLE_ISOM_WRITE
			extent_entry->original_extent_offset = extent_entry->extent_offset;
#endif
		}
	}
	return GF_OK;
}",1
"static void naludmx_queue_param_set(GF_NALUDmxCtx *ctx, char *data, u32 size, u32 ps_type, s32 ps_id)
{
	GF_List *list = NULL, *alt_list = NULL;
	GF_NALUFFParam *sl;
	u32 i, count;
	u32 crc = gf_crc_32(data, size);

	if (ctx->codecid==GF_CODECID_HEVC) {
		switch (ps_type) {
		case GF_HEVC_NALU_VID_PARAM:
			if (!ctx->vps) ctx->vps = gf_list_new();
			list = ctx->vps;
			break;
		case GF_HEVC_NALU_SEQ_PARAM:
			list = ctx->sps;
			break;
		case GF_HEVC_NALU_PIC_PARAM:
			list = ctx->pps;
			break;
		default:
			assert(0);
			return;
		}
	} else if (ctx->codecid==GF_CODECID_VVC) {
		switch (ps_type) {
		case GF_VVC_NALU_VID_PARAM:
			if (!ctx->vps) ctx->vps = gf_list_new();
			list = ctx->vps;
			break;
		case GF_VVC_NALU_SEQ_PARAM:
			list = ctx->sps;
			break;
		case GF_VVC_NALU_PIC_PARAM:
			list = ctx->pps;
			break;
		case GF_VVC_NALU_DEC_PARAM:
			if (!ctx->vvc_dci) ctx->vvc_dci = gf_list_new();
			list = ctx->vvc_dci;
			break;
		case GF_VVC_NALU_APS_PREFIX:
			if (!ctx->vvc_aps_pre) ctx->vvc_aps_pre = gf_list_new();
			list = ctx->vvc_aps_pre;
			break;
		default:
			assert(0);
			return;
		}
	} else {
		switch (ps_type) {
		case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
		case GF_AVC_NALU_SEQ_PARAM:
			list = ctx->sps;
			break;
		case GF_AVC_NALU_PIC_PARAM:
			list = ctx->pps;
			alt_list = ctx->pps_svc;
			break;
		case GF_AVC_NALU_SEQ_PARAM_EXT:
			if (!ctx->sps_ext) ctx->sps_ext = gf_list_new();
			list = ctx->sps_ext;
			break;
		default:
			assert(0);
			return;
		}
	}
	sl = NULL;
	count = gf_list_count(list);
	for (i=0; iid != ps_id) {
			sl = NULL;
			continue;
		}
		//same ID, same CRC, we don't change our state
		if (sl->crc == crc) return;
		break;
	}
	//handle alt PPS list for SVC
	if (!sl && alt_list) {
		count = gf_list_count(alt_list);
		for (i=0; iid != ps_id) {
				sl = NULL;
				continue;
			}
			//same ID, same CRC, we don't change our state
			if (sl->crc == crc) return;
			break;
		}
	}

	if (sl) {
		//otherwise we keep this new param set
		sl->data = gf_realloc(sl->data, size);
		memcpy(sl->data, data, size);
		sl->size = size;
		sl->crc = crc;
		ctx->ps_modified = GF_TRUE;
		return;
	}
	//TODO we might want to purge the list after a while !!

	GF_SAFEALLOC(sl, GF_NALUFFParam);
	if (!sl) return;
	sl->data = gf_malloc(sizeof(char) * size);
	if (!sl->data) {
		gf_free(sl);
		return;
	}
	memcpy(sl->data, data, size);
	sl->size = size;
	sl->id = ps_id;
	sl->crc = crc;

	ctx->ps_modified = GF_TRUE;
	gf_list_add(list, sl);
}",1
"  void Compute(OpKernelContext *ctx) override {
    const Tensor *indices_t, *values_t, *shape_t, *dense_t;
    OP_REQUIRES_OK(ctx, ctx->input(""sp_indices"", &indices_t));
    OP_REQUIRES_OK(ctx, ctx->input(""sp_values"", &values_t));
    OP_REQUIRES_OK(ctx, ctx->input(""sp_shape"", &shape_t));
    OP_REQUIRES_OK(ctx, ctx->input(""dense"", &dense_t));

    // Validations.
    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),
                errors::InvalidArgument(
                    ""Input sp_indices should be a matrix but received shape: "",
                    indices_t->shape().DebugString()));
    OP_REQUIRES(ctx,
                TensorShapeUtils::IsVector(values_t->shape()) &&
                    TensorShapeUtils::IsVector(shape_t->shape()),
                errors::InvalidArgument(
                    ""Inputs sp_values and sp_shape should be vectors ""
                    ""but received shapes: "",
                    values_t->shape().DebugString(), "" and "",
                    shape_t->shape().DebugString()));
    OP_REQUIRES(
        ctx, TensorShapeUtils::IsVector(shape_t->shape()),
        errors::InvalidArgument(""Input sp_shape must be a vector. Got: "",
                                shape_t->shape().DebugString()));
    OP_REQUIRES(
        ctx, values_t->dim_size(0) == indices_t->dim_size(0),
        errors::InvalidArgument(
            ""The first dimension of values and indices should match. ("",
            values_t->dim_size(0), "" vs. "", indices_t->dim_size(0), "")""));
    OP_REQUIRES(
        ctx, shape_t->shape().dim_size(0) == indices_t->shape().dim_size(1),
        errors::InvalidArgument(
            ""Number of dimensions must match second dimension of indices. "",
            ""Got "", shape_t->shape().dim_size(0),
            "" dimensions, indices shape: "", indices_t->shape().DebugString()));
    OP_REQUIRES(ctx, shape_t->NumElements() > 0,
                errors::InvalidArgument(
                    ""The shape argument requires at least one element.""));

    const auto indices_mat = indices_t->matrix();
    const auto shape_vec = shape_t->vec();
    const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));
    const auto rhs_dims = BCast::FromShape(dense_t->shape());
    BCast b(lhs_dims, rhs_dims, false);  // false for keeping the same num dims.

    // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal
    // to dims in rhs (from right to left).
    auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {
      if (lhs.size() < rhs.size()) return false;
      for (size_t i = 0; i < rhs.size(); ++i) {
        if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;
      }
      return true;
    };
    OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),
                errors::InvalidArgument(
                    ""SparseDenseBinaryOpShared broadcasts dense to sparse ""
                    ""only; got incompatible shapes: ["",
                    absl::StrJoin(lhs_dims, "",""), ""] vs. ["",
                    absl::StrJoin(rhs_dims, "",""), ""]""));

    Tensor *output_values = nullptr;
    Tensor dense_gathered;
    const int64_t nnz = indices_t->dim_size(0);
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_output(0, TensorShape({nnz}), &output_values));
    OP_REQUIRES_OK(
        ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),
                                &dense_gathered));
    bool op_is_div = false;
    if (absl::StrContains(ctx->op_kernel().type_string_view(), ""Div"")) {
      op_is_div = true;
    }
    // Pulls relevant entries from the dense side, with reshape and broadcasting
    // *of the dense side* taken into account.  Use a TensorRef to avoid blowing
    // up memory.
    //
    // We can directly use the sparse indices to look up dense side, because
    // ""b.y_reshape()"" and ""b.y_bcast()"" are guaranteed to have rank ""ndims"".
    auto dense_gathered_flat = dense_gathered.flat();
    const int ndims = lhs_dims.size();
    switch (ndims) {
#define CASE(NDIM)                                                             \
  case NDIM: {                                                                 \
    TensorRef> rhs_ref =         \
        dense_t->shaped(b.y_reshape())                                \
            .broadcast(BCast::ToIndexArray(b.y_bcast()));                \
    Eigen::array idx;                                 \
    bool indices_valid = true;                                                 \
    for (int i = 0; i < nnz; ++i) {                                            \
      for (int d = 0; d < NDIM; ++d) {                                         \
        idx[d] = internal::SubtleMustCopy(indices_mat(i, d));                  \
        if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) {                  \
          indices_valid = false;                                               \
        }                                                                      \
      }                                                                        \
      OP_REQUIRES(                                                             \
          ctx, indices_valid,                                                  \
          errors::InvalidArgument(""Provided indices are out-of-bounds w.r.t. "" \
                                  ""dense side with broadcasted shape""));       \
      dense_gathered_flat(i) = rhs_ref.coeff(idx);                             \
      if (op_is_div) {                                                         \
        OP_REQUIRES(ctx, dense_gathered_flat(i) != 0,                          \
                    errors::InvalidArgument(                                   \
                        ""SparseDenseCwiseDiv cannot divide by zero,""           \
                        ""but input dense tensor contains zero ""));             \
      }                                                                        \
    }                                                                          \
    break;                                                                     \
  }

      CASE(1);
      CASE(2);
      CASE(3);
      CASE(4);
      CASE(5);
      default:
        OP_REQUIRES(
            ctx, false,
            errors::InvalidArgument(""Only tensors with ranks between 1 and 5 ""
                                    ""are currently supported.  Tensor rank: "",
                                    ndims));
#undef CASE
    }

    output_values->flat().device(ctx->eigen_device()) =
        values_t->flat().binaryExpr(dense_gathered_flat,
                                       typename Functor::func());
  }",1
"int64_t OpLevelCostEstimator::CalculateOutputSize(const OpInfo& op_info,
                                                  bool* found_unknown_shapes) {
  int64_t total_output_size = 0;
  // Use float as default for calculations.
  for (const auto& output : op_info.outputs()) {
    DataType dt = output.dtype();
    const auto& original_output_shape = output.shape();
    int64_t output_size = DataTypeSize(BaseType(dt));
    int num_dims = std::max(1, original_output_shape.dim_size());
    auto output_shape = MaybeGetMinimumShape(original_output_shape, num_dims,
                                             found_unknown_shapes);
    for (const auto& dim : output_shape.dim()) {
      output_size *= dim.size();
    }
    total_output_size += output_size;
    VLOG(1) << ""Output Size: "" << output_size
            << "" Total Output Size:"" << total_output_size;
  }
  return total_output_size;
}",1
"  void Compute(OpKernelContext* context) override {
    // Here's the basic idea:
    // Batch and depth dimension are independent from row and col dimension. And
    // because FractionalAvgPool currently only support pooling along row and
    // col, we can basically think of this 4D tensor backpropagation as
    // operation of a series of 2D planes.
    //
    // For each element of a 'slice' (2D plane) of output_backprop, we need to
    // figure out its contributors when doing FractionalAvgPool operation. This
    // can be done based on row_pooling_sequence, col_pooling_seq and
    // overlapping.
    // Once we figure out the original contributors, we just need to evenly
    // divide the value of this element among these contributors.
    //
    // Internally, we divide the out_backprop tensor and store it in a temporary
    // tensor of double type. And cast it to the corresponding type.
    typedef Eigen::Map>
        ConstEigenMatrixMap;
    typedef Eigen::Map>
        EigenDoubleMatrixMap;

    // Grab the inputs.
    const Tensor& orig_input_tensor_shape = context->input(0);
    OP_REQUIRES(context,
                orig_input_tensor_shape.dims() == 1 &&
                    orig_input_tensor_shape.NumElements() == 4,
                errors::InvalidArgument(""original input tensor shape must be""
                                        ""1-dimensional and 4 elements""));
    const Tensor& out_backprop = context->input(1);
    const Tensor& row_seq_tensor = context->input(2);
    const Tensor& col_seq_tensor = context->input(3);

    const int64_t out_batch = out_backprop.dim_size(0);
    const int64_t out_rows = out_backprop.dim_size(1);
    const int64_t out_cols = out_backprop.dim_size(2);
    const int64_t out_depth = out_backprop.dim_size(3);

    OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,
                errors::InvalidArgument(""Given out_backprop shape "",
                                        out_backprop.shape().DebugString(),
                                        "", row_seq_tensor must have at least "",
                                        out_rows + 1, "" elements, but got "",
                                        row_seq_tensor.NumElements()));
    OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,
                errors::InvalidArgument(""Given out_backprop shape "",
                                        out_backprop.shape().DebugString(),
                                        "", col_seq_tensor must have at least "",
                                        out_cols + 1, "" elements, but got "",
                                        col_seq_tensor.NumElements()));

    auto row_seq_tensor_flat = row_seq_tensor.flat();
    auto col_seq_tensor_flat = col_seq_tensor.flat();
    auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();

    const int64_t in_batch = orig_input_tensor_shape_flat(0);
    const int64_t in_rows = orig_input_tensor_shape_flat(1);
    const int64_t in_cols = orig_input_tensor_shape_flat(2);
    const int64_t in_depth = orig_input_tensor_shape_flat(3);
    OP_REQUIRES(
        context, in_batch != 0,
        errors::InvalidArgument(""Batch dimension of input must not be 0""));
    OP_REQUIRES(
        context, in_rows != 0,
        errors::InvalidArgument(""Rows dimension of input must not be 0""));
    OP_REQUIRES(
        context, in_cols != 0,
        errors::InvalidArgument(""Columns dimension of input must not be 0""));
    OP_REQUIRES(
        context, in_depth != 0,
        errors::InvalidArgument(""Depth dimension of input must not be 0""));

    constexpr int tensor_in_and_out_dims = 4;
    // Transform orig_input_tensor_shape into TensorShape
    TensorShape in_shape;
    for (auto i = 0; i < tensor_in_and_out_dims; ++i) {
      in_shape.AddDim(orig_input_tensor_shape_flat(i));
    }

    // Create intermediate in_backprop.
    Tensor in_backprop_tensor_temp;
    OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(
                                {0}, DataTypeToEnum::v(), in_shape,
                                &in_backprop_tensor_temp));
    in_backprop_tensor_temp.flat().setZero();
    // Transform 4D tensor to 2D matrix.
    EigenDoubleMatrixMap in_backprop_tensor_temp_mat(
        in_backprop_tensor_temp.flat().data(), in_depth,
        in_cols * in_rows * in_batch);
    ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),
                                         out_depth,
                                         out_cols * out_rows * out_batch);
    // Loop through each element of out_backprop and evenly distribute the
    // element to the corresponding pooling cell.
    const int64_t in_max_row_index = in_rows - 1;
    const int64_t in_max_col_index = in_cols - 1;
    for (int64_t b = 0; b < out_batch; ++b) {
      for (int64_t r = 0; r < out_rows; ++r) {
        const int64_t in_row_start = row_seq_tensor_flat(r);
        int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)
                                          : row_seq_tensor_flat(r + 1) - 1;
        in_row_end = std::min(in_row_end, in_max_row_index);
        for (int64_t c = 0; c < out_cols; ++c) {
          const int64_t in_col_start = col_seq_tensor_flat(c);
          int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)
                                            : col_seq_tensor_flat(c + 1) - 1;
          in_col_end = std::min(in_col_end, in_max_col_index);

          const int64_t num_elements_in_pooling_cell =
              (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);
          const int64_t out_index = (b * out_rows + r) * out_cols + c;
          // Now we can evenly distribute out_backprop(b, h, w, *) to
          // in_backprop(b, hs:he, ws:we, *).
          for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) {
            for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) {
              const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c;
              // Walk through each channel (depth).
              for (int64_t d = 0; d < out_depth; ++d) {
                const double out_backprop_element = static_cast(
                    out_backprop_mat.coeffRef(d, out_index));
                double& in_backprop_ref =
                    in_backprop_tensor_temp_mat.coeffRef(d, in_index);
                in_backprop_ref +=
                    out_backprop_element / num_elements_in_pooling_cell;
              }
            }
          }
        }
      }
    }

    // Depending on the type, cast double to type T.
    Tensor* in_backprop_tensor = nullptr;
    OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
                                {0}, 0, in_shape, &in_backprop_tensor));
    auto in_backprop_tensor_flat = in_backprop_tensor->flat();
    auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();
    for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) {
      in_backprop_tensor_flat(i) =
          static_cast(in_backprop_tensor_temp_flat(i));
    }
  }",1
"flatpak_dir_ensure_bundle_remote (FlatpakDir         *self,
                                  GFile              *file,
                                  GBytes             *extra_gpg_data,
                                  FlatpakDecomposed **out_ref,
                                  char              **out_checksum,
                                  char              **out_metadata,
                                  gboolean           *out_created_remote,
                                  GCancellable       *cancellable,
                                  GError            **error)
{
  g_autoptr(FlatpakDecomposed) ref = NULL;
  gboolean created_remote = FALSE;
  g_autoptr(GBytes) deploy_data = NULL;
  g_autoptr(GVariant) metadata = NULL;
  g_autofree char *origin = NULL;
  g_autofree char *fp_metadata = NULL;
  g_autofree char *basename = NULL;
  g_autoptr(GBytes) included_gpg_data = NULL;
  GBytes *gpg_data = NULL;
  g_autofree char *to_checksum = NULL;
  g_autofree char *remote = NULL;
  g_autofree char *collection_id = NULL;

  if (!flatpak_dir_ensure_repo (self, cancellable, error))
    return NULL;

  metadata = flatpak_bundle_load (file, &to_checksum,
                                  &ref,
                                  &origin,
                                  NULL, &fp_metadata, NULL,
                                  &included_gpg_data,
                                  &collection_id,
                                  error);
  if (metadata == NULL)
    return NULL;

  gpg_data = extra_gpg_data ? extra_gpg_data : included_gpg_data;

  deploy_data = flatpak_dir_get_deploy_data (self, ref, FLATPAK_DEPLOY_VERSION_ANY, cancellable, NULL);
  if (deploy_data != NULL)
    {
      remote = g_strdup (flatpak_deploy_data_get_origin (deploy_data));

      /* We need to import any gpg keys because otherwise the pull will fail */
      if (gpg_data != NULL)
        {
          g_autoptr(GKeyFile) new_config = NULL;

          new_config = ostree_repo_copy_config (flatpak_dir_get_repo (self));

          if (!flatpak_dir_modify_remote (self, remote, new_config,
                                          gpg_data, cancellable, error))
            return NULL;
        }
    }
  else
    {
      g_autofree char *id = flatpak_decomposed_dup_id (ref);
      /* Add a remote for later updates */
      basename = g_file_get_basename (file);
      remote = flatpak_dir_create_origin_remote (self,
                                                 origin,
                                                 id,
                                                 basename,
                                                 flatpak_decomposed_get_ref (ref),
                                                 gpg_data,
                                                 collection_id,
                                                 &created_remote,
                                                 cancellable,
                                                 error);
      if (remote == NULL)
        return NULL;
    }

  if (out_created_remote)
    *out_created_remote = created_remote;

  if (out_ref)
    *out_ref = g_steal_pointer (&ref);

  if (out_checksum)
    *out_checksum = g_steal_pointer (&to_checksum);

  if (out_metadata)
    *out_metadata = g_steal_pointer (&fp_metadata);


  return g_steal_pointer (&remote);
}",1
"PQconnectPoll(PGconn *conn)
{
	bool		reset_connection_state_machine = false;
	bool		need_new_connection = false;
	PGresult   *res;
	char		sebuf[PG_STRERROR_R_BUFLEN];
	int			optval;

	if (conn == NULL)
		return PGRES_POLLING_FAILED;

	/* Get the new data */
	switch (conn->status)
	{
			/*
			 * We really shouldn't have been polled in these two cases, but we
			 * can handle it.
			 */
		case CONNECTION_BAD:
			return PGRES_POLLING_FAILED;
		case CONNECTION_OK:
			return PGRES_POLLING_OK;

			/* These are reading states */
		case CONNECTION_AWAITING_RESPONSE:
		case CONNECTION_AUTH_OK:
		case CONNECTION_CHECK_WRITABLE:
		case CONNECTION_CONSUME:
		case CONNECTION_CHECK_STANDBY:
			{
				/* Load waiting data */
				int			n = pqReadData(conn);

				if (n < 0)
					goto error_return;
				if (n == 0)
					return PGRES_POLLING_READING;

				break;
			}

			/* These are writing states, so we just proceed. */
		case CONNECTION_STARTED:
		case CONNECTION_MADE:
			break;

			/* Special cases: proceed without waiting. */
		case CONNECTION_SSL_STARTUP:
		case CONNECTION_NEEDED:
		case CONNECTION_GSS_STARTUP:
		case CONNECTION_CHECK_TARGET:
			break;

		default:
			appendPQExpBufferStr(&conn->errorMessage,
								 libpq_gettext(""invalid connection state, probably indicative of memory corruption\n""));
			goto error_return;
	}


keep_going:						/* We will come back to here until there is
								 * nothing left to do. */

	/* Time to advance to next address, or next host if no more addresses? */
	if (conn->try_next_addr)
	{
		if (conn->addr_cur && conn->addr_cur->ai_next)
		{
			conn->addr_cur = conn->addr_cur->ai_next;
			reset_connection_state_machine = true;
		}
		else
			conn->try_next_host = true;
		conn->try_next_addr = false;
	}

	/* Time to advance to next connhost[] entry? */
	if (conn->try_next_host)
	{
		pg_conn_host *ch;
		struct addrinfo hint;
		int			thisport;
		int			ret;
		char		portstr[MAXPGPATH];

		if (conn->whichhost + 1 < conn->nconnhost)
			conn->whichhost++;
		else
		{
			/*
			 * Oops, no more hosts.
			 *
			 * If we are trying to connect in ""prefer-standby"" mode, then drop
			 * the standby requirement and start over.
			 *
			 * Otherwise, an appropriate error message is already set up, so
			 * we just need to set the right status.
			 */
			if (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY &&
				conn->nconnhost > 0)
			{
				conn->target_server_type = SERVER_TYPE_PREFER_STANDBY_PASS2;
				conn->whichhost = 0;
			}
			else
				goto error_return;
		}

		/* Drop any address info for previous host */
		release_conn_addrinfo(conn);

		/*
		 * Look up info for the new host.  On failure, log the problem in
		 * conn->errorMessage, then loop around to try the next host.  (Note
		 * we don't clear try_next_host until we've succeeded.)
		 */
		ch = &conn->connhost[conn->whichhost];

		/* Initialize hint structure */
		MemSet(&hint, 0, sizeof(hint));
		hint.ai_socktype = SOCK_STREAM;
		conn->addrlist_family = hint.ai_family = AF_UNSPEC;

		/* Figure out the port number we're going to use. */
		if (ch->port == NULL || ch->port[0] == '\0')
			thisport = DEF_PGPORT;
		else
		{
			if (!parse_int_param(ch->port, &thisport, conn, ""port""))
				goto error_return;

			if (thisport < 1 || thisport > 65535)
			{
				appendPQExpBuffer(&conn->errorMessage,
								  libpq_gettext(""invalid port number: \""%s\""\n""),
								  ch->port);
				goto keep_going;
			}
		}
		snprintf(portstr, sizeof(portstr), ""%d"", thisport);

		/* Use pg_getaddrinfo_all() to resolve the address */
		switch (ch->type)
		{
			case CHT_HOST_NAME:
				ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
										 &conn->addrlist);
				if (ret || !conn->addrlist)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""could not translate host name \""%s\"" to address: %s\n""),
									  ch->host, gai_strerror(ret));
					goto keep_going;
				}
				break;

			case CHT_HOST_ADDRESS:
				hint.ai_flags = AI_NUMERICHOST;
				ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
										 &conn->addrlist);
				if (ret || !conn->addrlist)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""could not parse network address \""%s\"": %s\n""),
									  ch->hostaddr, gai_strerror(ret));
					goto keep_going;
				}
				break;

			case CHT_UNIX_SOCKET:
#ifdef HAVE_UNIX_SOCKETS
				conn->addrlist_family = hint.ai_family = AF_UNIX;
				UNIXSOCK_PATH(portstr, thisport, ch->host);
				if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""Unix-domain socket path \""%s\"" is too long (maximum %d bytes)\n""),
									  portstr,
									  (int) (UNIXSOCK_PATH_BUFLEN - 1));
					goto keep_going;
				}

				/*
				 * NULL hostname tells pg_getaddrinfo_all to parse the service
				 * name as a Unix-domain socket path.
				 */
				ret = pg_getaddrinfo_all(NULL, portstr, &hint,
										 &conn->addrlist);
				if (ret || !conn->addrlist)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""could not translate Unix-domain socket path \""%s\"" to address: %s\n""),
									  portstr, gai_strerror(ret));
					goto keep_going;
				}
#else
				Assert(false);
#endif
				break;
		}

		/* OK, scan this addrlist for a working server address */
		conn->addr_cur = conn->addrlist;
		reset_connection_state_machine = true;
		conn->try_next_host = false;
	}

	/* Reset connection state machine? */
	if (reset_connection_state_machine)
	{
		/*
		 * (Re) initialize our connection control variables for a set of
		 * connection attempts to a single server address.  These variables
		 * must persist across individual connection attempts, but we must
		 * reset them when we start to consider a new server.
		 */
		conn->pversion = PG_PROTOCOL(3, 0);
		conn->send_appname = true;
#ifdef USE_SSL
		/* initialize these values based on SSL mode */
		conn->allow_ssl_try = (conn->sslmode[0] != 'd');	/* ""disable"" */
		conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* ""allow"" */
#endif
#ifdef ENABLE_GSS
		conn->try_gss = (conn->gssencmode[0] != 'd');	/* ""disable"" */
#endif

		reset_connection_state_machine = false;
		need_new_connection = true;
	}

	/* Force a new connection (perhaps to the same server as before)? */
	if (need_new_connection)
	{
		/* Drop any existing connection */
		pqDropConnection(conn, true);

		/* Reset all state obtained from old server */
		pqDropServerData(conn);

		/* Drop any PGresult we might have, too */
		conn->asyncStatus = PGASYNC_IDLE;
		conn->xactStatus = PQTRANS_IDLE;
		conn->pipelineStatus = PQ_PIPELINE_OFF;
		pqClearAsyncResult(conn);

		/* Reset conn->status to put the state machine in the right state */
		conn->status = CONNECTION_NEEDED;

		need_new_connection = false;
	}

	/* Now try to advance the state machine for this connection */
	switch (conn->status)
	{
		case CONNECTION_NEEDED:
			{
				/*
				 * Try to initiate a connection to one of the addresses
				 * returned by pg_getaddrinfo_all().  conn->addr_cur is the
				 * next one to try.
				 *
				 * The extra level of braces here is historical.  It's not
				 * worth reindenting this whole switch case to remove 'em.
				 */
				{
					struct addrinfo *addr_cur = conn->addr_cur;
					char		host_addr[NI_MAXHOST];

					/*
					 * Advance to next possible host, if we've tried all of
					 * the addresses for the current host.
					 */
					if (addr_cur == NULL)
					{
						conn->try_next_host = true;
						goto keep_going;
					}

					/* Remember current address for possible use later */
					memcpy(&conn->raddr.addr, addr_cur->ai_addr,
						   addr_cur->ai_addrlen);
					conn->raddr.salen = addr_cur->ai_addrlen;

					/*
					 * Set connip, too.  Note we purposely ignore strdup
					 * failure; not a big problem if it fails.
					 */
					if (conn->connip != NULL)
					{
						free(conn->connip);
						conn->connip = NULL;
					}
					getHostaddr(conn, host_addr, NI_MAXHOST);
					if (host_addr[0])
						conn->connip = strdup(host_addr);

					/* Try to create the socket */
					conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
					if (conn->sock == PGINVALID_SOCKET)
					{
						int			errorno = SOCK_ERRNO;

						/*
						 * Silently ignore socket() failure if we have more
						 * addresses to try; this reduces useless chatter in
						 * cases where the address list includes both IPv4 and
						 * IPv6 but kernel only accepts one family.
						 */
						if (addr_cur->ai_next != NULL ||
							conn->whichhost + 1 < conn->nconnhost)
						{
							conn->try_next_addr = true;
							goto keep_going;
						}
						emitHostIdentityInfo(conn, host_addr);
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""could not create socket: %s\n""),
										  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
						goto error_return;
					}

					/*
					 * Once we've identified a target address, all errors
					 * except the preceding socket()-failure case should be
					 * prefixed with host-identity information.  (If the
					 * connection succeeds, the contents of conn->errorMessage
					 * won't matter, so this is harmless.)
					 */
					emitHostIdentityInfo(conn, host_addr);

					/*
					 * Select socket options: no delay of outgoing data for
					 * TCP sockets, nonblock mode, close-on-exec.  Try the
					 * next address if any of this fails.
					 */
					if (!IS_AF_UNIX(addr_cur->ai_family))
					{
						if (!connectNoDelay(conn))
						{
							/* error message already created */
							conn->try_next_addr = true;
							goto keep_going;
						}
					}
					if (!pg_set_noblock(conn->sock))
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""could not set socket to nonblocking mode: %s\n""),
										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
						conn->try_next_addr = true;
						goto keep_going;
					}

#ifdef F_SETFD
					if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""could not set socket to close-on-exec mode: %s\n""),
										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
						conn->try_next_addr = true;
						goto keep_going;
					}
#endif							/* F_SETFD */

					if (!IS_AF_UNIX(addr_cur->ai_family))
					{
#ifndef WIN32
						int			on = 1;
#endif
						int			usekeepalives = useKeepalives(conn);
						int			err = 0;

						if (usekeepalives < 0)
						{
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""keepalives parameter must be an integer\n""));
							err = 1;
						}
						else if (usekeepalives == 0)
						{
							/* Do nothing */
						}
#ifndef WIN32
						else if (setsockopt(conn->sock,
											SOL_SOCKET, SO_KEEPALIVE,
											(char *) &on, sizeof(on)) < 0)
						{
							appendPQExpBuffer(&conn->errorMessage,
											  libpq_gettext(""%s(%s) failed: %s\n""),
											  ""setsockopt"",
											  ""SO_KEEPALIVE"",
											  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
							err = 1;
						}
						else if (!setKeepalivesIdle(conn)
								 || !setKeepalivesInterval(conn)
								 || !setKeepalivesCount(conn))
							err = 1;
#else							/* WIN32 */
#ifdef SIO_KEEPALIVE_VALS
						else if (!setKeepalivesWin32(conn))
							err = 1;
#endif							/* SIO_KEEPALIVE_VALS */
#endif							/* WIN32 */
						else if (!setTCPUserTimeout(conn))
							err = 1;

						if (err)
						{
							conn->try_next_addr = true;
							goto keep_going;
						}
					}

					/*----------
					 * We have three methods of blocking SIGPIPE during
					 * send() calls to this socket:
					 *
					 *	- setsockopt(sock, SO_NOSIGPIPE)
					 *	- send(sock, ..., MSG_NOSIGNAL)
					 *	- setting the signal mask to SIG_IGN during send()
					 *
					 * The third method requires three syscalls per send,
					 * so we prefer either of the first two, but they are
					 * less portable.  The state is tracked in the following
					 * members of PGconn:
					 *
					 * conn->sigpipe_so		- we have set up SO_NOSIGPIPE
					 * conn->sigpipe_flag	- we're specifying MSG_NOSIGNAL
					 *
					 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
					 * and we're done.  Otherwise, set sigpipe_flag so that
					 * we will try MSG_NOSIGNAL on sends.  If we get an error
					 * with MSG_NOSIGNAL, we'll clear that flag and revert to
					 * signal masking.
					 *----------
					 */
					conn->sigpipe_so = false;
#ifdef MSG_NOSIGNAL
					conn->sigpipe_flag = true;
#else
					conn->sigpipe_flag = false;
#endif							/* MSG_NOSIGNAL */

#ifdef SO_NOSIGPIPE
					optval = 1;
					if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
								   (char *) &optval, sizeof(optval)) == 0)
					{
						conn->sigpipe_so = true;
						conn->sigpipe_flag = false;
					}
#endif							/* SO_NOSIGPIPE */

					/*
					 * Start/make connection.  This should not block, since we
					 * are in nonblock mode.  If it does, well, too bad.
					 */
					if (connect(conn->sock, addr_cur->ai_addr,
								addr_cur->ai_addrlen) < 0)
					{
						if (SOCK_ERRNO == EINPROGRESS ||
#ifdef WIN32
							SOCK_ERRNO == EWOULDBLOCK ||
#endif
							SOCK_ERRNO == EINTR)
						{
							/*
							 * This is fine - we're in non-blocking mode, and
							 * the connection is in progress.  Tell caller to
							 * wait for write-ready on socket.
							 */
							conn->status = CONNECTION_STARTED;
							return PGRES_POLLING_WRITING;
						}
						/* otherwise, trouble */
					}
					else
					{
						/*
						 * Hm, we're connected already --- seems the ""nonblock
						 * connection"" wasn't.  Advance the state machine and
						 * go do the next stuff.
						 */
						conn->status = CONNECTION_STARTED;
						goto keep_going;
					}

					/*
					 * This connection failed.  Add the error report to
					 * conn->errorMessage, then try the next address if any.
					 */
					connectFailureMessage(conn, SOCK_ERRNO);
					conn->try_next_addr = true;
					goto keep_going;
				}
			}

		case CONNECTION_STARTED:
			{
				ACCEPT_TYPE_ARG3 optlen = sizeof(optval);

				/*
				 * Write ready, since we've made it here, so the connection
				 * has been made ... or has failed.
				 */

				/*
				 * Now check (using getsockopt) that there is not an error
				 * state waiting for us on the socket.
				 */

				if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
							   (char *) &optval, &optlen) == -1)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""could not get socket error status: %s\n""),
									  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
					goto error_return;
				}
				else if (optval != 0)
				{
					/*
					 * When using a nonblocking connect, we will typically see
					 * connect failures at this point, so provide a friendly
					 * error message.
					 */
					connectFailureMessage(conn, optval);

					/*
					 * Try the next address if any, just as in the case where
					 * connect() returned failure immediately.
					 */
					conn->try_next_addr = true;
					goto keep_going;
				}

				/* Fill in the client address */
				conn->laddr.salen = sizeof(conn->laddr.addr);
				if (getsockname(conn->sock,
								(struct sockaddr *) &conn->laddr.addr,
								&conn->laddr.salen) < 0)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""could not get client address from socket: %s\n""),
									  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
					goto error_return;
				}

				/*
				 * Make sure we can write before advancing to next step.
				 */
				conn->status = CONNECTION_MADE;
				return PGRES_POLLING_WRITING;
			}

		case CONNECTION_MADE:
			{
				char	   *startpacket;
				int			packetlen;

				/*
				 * Implement requirepeer check, if requested and it's a
				 * Unix-domain socket.
				 */
				if (conn->requirepeer && conn->requirepeer[0] &&
					IS_AF_UNIX(conn->raddr.addr.ss_family))
				{
#ifndef WIN32
					char		pwdbuf[BUFSIZ];
					struct passwd pass_buf;
					struct passwd *pass;
					int			passerr;
#endif
					uid_t		uid;
					gid_t		gid;

					errno = 0;
					if (getpeereid(conn->sock, &uid, &gid) != 0)
					{
						/*
						 * Provide special error message if getpeereid is a
						 * stub
						 */
						if (errno == ENOSYS)
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""requirepeer parameter is not supported on this platform\n""));
						else
							appendPQExpBuffer(&conn->errorMessage,
											  libpq_gettext(""could not get peer credentials: %s\n""),
											  strerror_r(errno, sebuf, sizeof(sebuf)));
						goto error_return;
					}

#ifndef WIN32
					passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
					if (pass == NULL)
					{
						if (passerr != 0)
							appendPQExpBuffer(&conn->errorMessage,
											  libpq_gettext(""could not look up local user ID %d: %s\n""),
											  (int) uid,
											  strerror_r(passerr, sebuf, sizeof(sebuf)));
						else
							appendPQExpBuffer(&conn->errorMessage,
											  libpq_gettext(""local user with ID %d does not exist\n""),
											  (int) uid);
						goto error_return;
					}

					if (strcmp(pass->pw_name, conn->requirepeer) != 0)
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""requirepeer specifies \""%s\"", but actual peer user name is \""%s\""\n""),
										  conn->requirepeer, pass->pw_name);
						goto error_return;
					}
#else							/* WIN32 */
					/* should have failed with ENOSYS above */
					Assert(false);
#endif							/* WIN32 */
				}

				if (IS_AF_UNIX(conn->raddr.addr.ss_family))
				{
					/* Don't request SSL or GSSAPI over Unix sockets */
#ifdef USE_SSL
					conn->allow_ssl_try = false;
#endif
#ifdef ENABLE_GSS
					conn->try_gss = false;
#endif
				}

#ifdef ENABLE_GSS

				/*
				 * If GSSAPI encryption is enabled, then call
				 * pg_GSS_have_cred_cache() which will return true if we can
				 * acquire credentials (and give us a handle to use in
				 * conn->gcred), and then send a packet to the server asking
				 * for GSSAPI Encryption (and skip past SSL negotiation and
				 * regular startup below).
				 */
				if (conn->try_gss && !conn->gctx)
					conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
				if (conn->try_gss && !conn->gctx)
				{
					ProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);

					if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""could not send GSSAPI negotiation packet: %s\n""),
										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
						goto error_return;
					}

					/* Ok, wait for response */
					conn->status = CONNECTION_GSS_STARTUP;
					return PGRES_POLLING_READING;
				}
				else if (!conn->gctx && conn->gssencmode[0] == 'r')
				{
					appendPQExpBufferStr(&conn->errorMessage,
										 libpq_gettext(""GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\n""));
					goto error_return;
				}
#endif

#ifdef USE_SSL

				/*
				 * Enable the libcrypto callbacks before checking if SSL needs
				 * to be done.  This is done before sending the startup packet
				 * as depending on the type of authentication done, like MD5
				 * or SCRAM that use cryptohashes, the callbacks would be
				 * required even without a SSL connection
				 */
				if (pqsecure_initialize(conn, false, true) < 0)
					goto error_return;

				/*
				 * If SSL is enabled and we haven't already got encryption of
				 * some sort running, request SSL instead of sending the
				 * startup message.
				 */
				if (conn->allow_ssl_try && !conn->wait_ssl_try &&
					!conn->ssl_in_use
#ifdef ENABLE_GSS
					&& !conn->gssenc
#endif
					)
				{
					ProtocolVersion pv;

					/*
					 * Send the SSL request packet.
					 *
					 * Theoretically, this could block, but it really
					 * shouldn't since we only got here if the socket is
					 * write-ready.
					 */
					pv = pg_hton32(NEGOTIATE_SSL_CODE);
					if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""could not send SSL negotiation packet: %s\n""),
										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
						goto error_return;
					}
					/* Ok, wait for response */
					conn->status = CONNECTION_SSL_STARTUP;
					return PGRES_POLLING_READING;
				}
#endif							/* USE_SSL */

				/*
				 * Build the startup packet.
				 */
				startpacket = pqBuildStartupPacket3(conn, &packetlen,
													EnvironmentOptions);
				if (!startpacket)
				{
					appendPQExpBufferStr(&conn->errorMessage,
										 libpq_gettext(""out of memory\n""));
					goto error_return;
				}

				/*
				 * Send the startup packet.
				 *
				 * Theoretically, this could block, but it really shouldn't
				 * since we only got here if the socket is write-ready.
				 */
				if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""could not send startup packet: %s\n""),
									  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
					free(startpacket);
					goto error_return;
				}

				free(startpacket);

				conn->status = CONNECTION_AWAITING_RESPONSE;
				return PGRES_POLLING_READING;
			}

			/*
			 * Handle SSL negotiation: wait for postmaster messages and
			 * respond as necessary.
			 */
		case CONNECTION_SSL_STARTUP:
			{
#ifdef USE_SSL
				PostgresPollingStatusType pollres;

				/*
				 * On first time through, get the postmaster's response to our
				 * SSL negotiation packet.
				 */
				if (!conn->ssl_in_use)
				{
					/*
					 * We use pqReadData here since it has the logic to
					 * distinguish no-data-yet from connection closure. Since
					 * conn->ssl isn't set, a plain recv() will occur.
					 */
					char		SSLok;
					int			rdresult;

					rdresult = pqReadData(conn);
					if (rdresult < 0)
					{
						/* errorMessage is already filled in */
						goto error_return;
					}
					if (rdresult == 0)
					{
						/* caller failed to wait for data */
						return PGRES_POLLING_READING;
					}
					if (pqGetc(&SSLok, conn) < 0)
					{
						/* should not happen really */
						return PGRES_POLLING_READING;
					}
					if (SSLok == 'S')
					{
						/* mark byte consumed */
						conn->inStart = conn->inCursor;

						/*
						 * Set up global SSL state if required.  The crypto
						 * state has already been set if libpq took care of
						 * doing that, so there is no need to make that happen
						 * again.
						 */
						if (pqsecure_initialize(conn, true, false) != 0)
							goto error_return;
					}
					else if (SSLok == 'N')
					{
						/* mark byte consumed */
						conn->inStart = conn->inCursor;
						/* OK to do without SSL? */
						if (conn->sslmode[0] == 'r' ||	/* ""require"" */
							conn->sslmode[0] == 'v')	/* ""verify-ca"" or
														 * ""verify-full"" */
						{
							/* Require SSL, but server does not want it */
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""server does not support SSL, but SSL was required\n""));
							goto error_return;
						}
						/* Otherwise, proceed with normal startup */
						conn->allow_ssl_try = false;
						/* We can proceed using this connection */
						conn->status = CONNECTION_MADE;
						return PGRES_POLLING_WRITING;
					}
					else if (SSLok == 'E')
					{
						/*
						 * Server failure of some sort, such as failure to
						 * fork a backend process.  We need to process and
						 * report the error message, which might be formatted
						 * according to either protocol 2 or protocol 3.
						 * Rather than duplicate the code for that, we flip
						 * into AWAITING_RESPONSE state and let the code there
						 * deal with it.  Note we have *not* consumed the ""E""
						 * byte here.
						 */
						conn->status = CONNECTION_AWAITING_RESPONSE;
						goto keep_going;
					}
					else
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""received invalid response to SSL negotiation: %c\n""),
										  SSLok);
						goto error_return;
					}
				}

				/*
				 * Begin or continue the SSL negotiation process.
				 */
				pollres = pqsecure_open_client(conn);
				if (pollres == PGRES_POLLING_OK)
				{
					/* SSL handshake done, ready to send startup packet */
					conn->status = CONNECTION_MADE;
					return PGRES_POLLING_WRITING;
				}
				if (pollres == PGRES_POLLING_FAILED)
				{
					/*
					 * Failed ... if sslmode is ""prefer"" then do a non-SSL
					 * retry
					 */
					if (conn->sslmode[0] == 'p' /* ""prefer"" */
						&& conn->allow_ssl_try	/* redundant? */
						&& !conn->wait_ssl_try) /* redundant? */
					{
						/* only retry once */
						conn->allow_ssl_try = false;
						need_new_connection = true;
						goto keep_going;
					}
					/* Else it's a hard failure */
					goto error_return;
				}
				/* Else, return POLLING_READING or POLLING_WRITING status */
				return pollres;
#else							/* !USE_SSL */
				/* can't get here */
				goto error_return;
#endif							/* USE_SSL */
			}

		case CONNECTION_GSS_STARTUP:
			{
#ifdef ENABLE_GSS
				PostgresPollingStatusType pollres;

				/*
				 * If we haven't yet, get the postmaster's response to our
				 * negotiation packet
				 */
				if (conn->try_gss && !conn->gctx)
				{
					char		gss_ok;
					int			rdresult = pqReadData(conn);

					if (rdresult < 0)
						/* pqReadData fills in error message */
						goto error_return;
					else if (rdresult == 0)
						/* caller failed to wait for data */
						return PGRES_POLLING_READING;
					if (pqGetc(&gss_ok, conn) < 0)
						/* shouldn't happen... */
						return PGRES_POLLING_READING;

					if (gss_ok == 'E')
					{
						/*
						 * Server failure of some sort.  Assume it's a
						 * protocol version support failure, and let's see if
						 * we can't recover (if it's not, we'll get a better
						 * error message on retry).  Server gets fussy if we
						 * don't hang up the socket, though.
						 */
						conn->try_gss = false;
						need_new_connection = true;
						goto keep_going;
					}

					/* mark byte consumed */
					conn->inStart = conn->inCursor;

					if (gss_ok == 'N')
					{
						/* Server doesn't want GSSAPI; fall back if we can */
						if (conn->gssencmode[0] == 'r')
						{
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""server doesn't support GSSAPI encryption, but it was required\n""));
							goto error_return;
						}

						conn->try_gss = false;
						/* We can proceed using this connection */
						conn->status = CONNECTION_MADE;
						return PGRES_POLLING_WRITING;
					}
					else if (gss_ok != 'G')
					{
						appendPQExpBuffer(&conn->errorMessage,
										  libpq_gettext(""received invalid response to GSSAPI negotiation: %c\n""),
										  gss_ok);
						goto error_return;
					}
				}

				/* Begin or continue GSSAPI negotiation */
				pollres = pqsecure_open_gss(conn);
				if (pollres == PGRES_POLLING_OK)
				{
					/* All set for startup packet */
					conn->status = CONNECTION_MADE;
					return PGRES_POLLING_WRITING;
				}
				else if (pollres == PGRES_POLLING_FAILED &&
						 conn->gssencmode[0] == 'p')
				{
					/*
					 * We failed, but we can retry on ""prefer"".  Have to drop
					 * the current connection to do so, though.
					 */
					conn->try_gss = false;
					need_new_connection = true;
					goto keep_going;
				}
				return pollres;
#else							/* !ENABLE_GSS */
				/* unreachable */
				goto error_return;
#endif							/* ENABLE_GSS */
			}

			/*
			 * Handle authentication exchange: wait for postmaster messages
			 * and respond as necessary.
			 */
		case CONNECTION_AWAITING_RESPONSE:
			{
				char		beresp;
				int			msgLength;
				int			avail;
				AuthRequest areq;
				int			res;

				/*
				 * Scan the message from current point (note that if we find
				 * the message is incomplete, we will return without advancing
				 * inStart, and resume here next time).
				 */
				conn->inCursor = conn->inStart;

				/* Read type byte */
				if (pqGetc(&beresp, conn))
				{
					/* We'll come back when there is more data */
					return PGRES_POLLING_READING;
				}

				/*
				 * Validate message type: we expect only an authentication
				 * request or an error here.  Anything else probably means
				 * it's not Postgres on the other end at all.
				 */
				if (!(beresp == 'R' || beresp == 'E'))
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""expected authentication request from server, but received %c\n""),
									  beresp);
					goto error_return;
				}

				/* Read message length word */
				if (pqGetInt(&msgLength, 4, conn))
				{
					/* We'll come back when there is more data */
					return PGRES_POLLING_READING;
				}

				/*
				 * Try to validate message length before using it.
				 * Authentication requests can't be very large, although GSS
				 * auth requests may not be that small.  Errors can be a
				 * little larger, but not huge.  If we see a large apparent
				 * length in an error, it means we're really talking to a
				 * pre-3.0-protocol server; cope.  (Before version 14, the
				 * server also used the old protocol for errors that happened
				 * before processing the startup packet.)
				 */
				if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
				{
					appendPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(""expected authentication request from server, but received %c\n""),
									  beresp);
					goto error_return;
				}

				if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
				{
					/* Handle error from a pre-3.0 server */
					conn->inCursor = conn->inStart + 1; /* reread data */
					if (pqGets_append(&conn->errorMessage, conn))
					{
						/* We'll come back when there is more data */
						return PGRES_POLLING_READING;
					}
					/* OK, we read the message; mark data consumed */
					conn->inStart = conn->inCursor;

					/*
					 * Before 7.2, the postmaster didn't always end its
					 * messages with a newline, so add one if needed to
					 * conform to libpq conventions.
					 */
					if (conn->errorMessage.len == 0 ||
						conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
					{
						appendPQExpBufferChar(&conn->errorMessage, '\n');
					}

					goto error_return;
				}

				/*
				 * Can't process if message body isn't all here yet.
				 */
				msgLength -= 4;
				avail = conn->inEnd - conn->inCursor;
				if (avail < msgLength)
				{
					/*
					 * Before returning, try to enlarge the input buffer if
					 * needed to hold the whole message; see notes in
					 * pqParseInput3.
					 */
					if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
											 conn))
						goto error_return;
					/* We'll come back when there is more data */
					return PGRES_POLLING_READING;
				}

				/* Handle errors. */
				if (beresp == 'E')
				{
					if (pqGetErrorNotice3(conn, true))
					{
						/* We'll come back when there is more data */
						return PGRES_POLLING_READING;
					}
					/* OK, we read the message; mark data consumed */
					conn->inStart = conn->inCursor;

					/*
					 * If error is ""cannot connect now"", try the next host if
					 * any (but we don't want to consider additional addresses
					 * for this host, nor is there much point in changing SSL
					 * or GSS mode).  This is helpful when dealing with
					 * standby servers that might not be in hot-standby state.
					 */
					if (strcmp(conn->last_sqlstate,
							   ERRCODE_CANNOT_CONNECT_NOW) == 0)
					{
						conn->try_next_host = true;
						goto keep_going;
					}

					/* Check to see if we should mention pgpassfile */
					pgpassfileWarning(conn);

#ifdef ENABLE_GSS

					/*
					 * If gssencmode is ""prefer"" and we're using GSSAPI, retry
					 * without it.
					 */
					if (conn->gssenc && conn->gssencmode[0] == 'p')
					{
						/* only retry once */
						conn->try_gss = false;
						need_new_connection = true;
						goto keep_going;
					}
#endif

#ifdef USE_SSL

					/*
					 * if sslmode is ""allow"" and we haven't tried an SSL
					 * connection already, then retry with an SSL connection
					 */
					if (conn->sslmode[0] == 'a' /* ""allow"" */
						&& !conn->ssl_in_use
						&& conn->allow_ssl_try
						&& conn->wait_ssl_try)
					{
						/* only retry once */
						conn->wait_ssl_try = false;
						need_new_connection = true;
						goto keep_going;
					}

					/*
					 * if sslmode is ""prefer"" and we're in an SSL connection,
					 * then do a non-SSL retry
					 */
					if (conn->sslmode[0] == 'p' /* ""prefer"" */
						&& conn->ssl_in_use
						&& conn->allow_ssl_try	/* redundant? */
						&& !conn->wait_ssl_try) /* redundant? */
					{
						/* only retry once */
						conn->allow_ssl_try = false;
						need_new_connection = true;
						goto keep_going;
					}
#endif

					goto error_return;
				}

				/* It is an authentication request. */
				conn->auth_req_received = true;

				/* Get the type of request. */
				if (pqGetInt((int *) &areq, 4, conn))
				{
					/* We'll come back when there are more data */
					return PGRES_POLLING_READING;
				}
				msgLength -= 4;

				/*
				 * Process the rest of the authentication request message, and
				 * respond to it if necessary.
				 *
				 * Note that conn->pghost must be non-NULL if we are going to
				 * avoid the Kerberos code doing a hostname look-up.
				 */
				res = pg_fe_sendauth(areq, msgLength, conn);

				/* OK, we have processed the message; mark data consumed */
				conn->inStart = conn->inCursor;

				if (res != STATUS_OK)
					goto error_return;

				/*
				 * Just make sure that any data sent by pg_fe_sendauth is
				 * flushed out.  Although this theoretically could block, it
				 * really shouldn't since we don't send large auth responses.
				 */
				if (pqFlush(conn))
					goto error_return;

				if (areq == AUTH_REQ_OK)
				{
					/* We are done with authentication exchange */
					conn->status = CONNECTION_AUTH_OK;

					/*
					 * Set asyncStatus so that PQgetResult will think that
					 * what comes back next is the result of a query.  See
					 * below.
					 */
					conn->asyncStatus = PGASYNC_BUSY;
				}

				/* Look to see if we have more data yet. */
				goto keep_going;
			}

		case CONNECTION_AUTH_OK:
			{
				/*
				 * Now we expect to hear from the backend. A ReadyForQuery
				 * message indicates that startup is successful, but we might
				 * also get an Error message indicating failure. (Notice
				 * messages indicating nonfatal warnings are also allowed by
				 * the protocol, as are ParameterStatus and BackendKeyData
				 * messages.) Easiest way to handle this is to let
				 * PQgetResult() read the messages. We just have to fake it
				 * out about the state of the connection, by setting
				 * asyncStatus = PGASYNC_BUSY (done above).
				 */

				if (PQisBusy(conn))
					return PGRES_POLLING_READING;

				res = PQgetResult(conn);

				/*
				 * NULL return indicating we have gone to IDLE state is
				 * expected
				 */
				if (res)
				{
					if (res->resultStatus != PGRES_FATAL_ERROR)
						appendPQExpBufferStr(&conn->errorMessage,
											 libpq_gettext(""unexpected message from server during startup\n""));
					else if (conn->send_appname &&
							 (conn->appname || conn->fbappname))
					{
						/*
						 * If we tried to send application_name, check to see
						 * if the error is about that --- pre-9.0 servers will
						 * reject it at this stage of the process.  If so,
						 * close the connection and retry without sending
						 * application_name.  We could possibly get a false
						 * SQLSTATE match here and retry uselessly, but there
						 * seems no great harm in that; we'll just get the
						 * same error again if it's unrelated.
						 */
						const char *sqlstate;

						sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
						if (sqlstate &&
							strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
						{
							PQclear(res);
							conn->send_appname = false;
							need_new_connection = true;
							goto keep_going;
						}
					}

					/*
					 * if the resultStatus is FATAL, then conn->errorMessage
					 * already has a copy of the error; needn't copy it back.
					 * But add a newline if it's not there already, since
					 * postmaster error messages may not have one.
					 */
					if (conn->errorMessage.len <= 0 ||
						conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
						appendPQExpBufferChar(&conn->errorMessage, '\n');
					PQclear(res);
					goto error_return;
				}

				/* Almost there now ... */
				conn->status = CONNECTION_CHECK_TARGET;
				goto keep_going;
			}

		case CONNECTION_CHECK_TARGET:
			{
				/*
				 * If a read-write, read-only, primary, or standby connection
				 * is required, see if we have one.
				 */
				if (conn->target_server_type == SERVER_TYPE_READ_WRITE ||
					conn->target_server_type == SERVER_TYPE_READ_ONLY)
				{
					bool		read_only_server;

					/*
					 * If the server didn't report
					 * ""default_transaction_read_only"" or ""in_hot_standby"" at
					 * startup, we must determine its state by sending the
					 * query ""SHOW transaction_read_only"".  This GUC exists in
					 * all server versions that support 3.0 protocol.
					 */
					if (conn->default_transaction_read_only == PG_BOOL_UNKNOWN ||
						conn->in_hot_standby == PG_BOOL_UNKNOWN)
					{
						/*
						 * We use PQsendQueryContinue so that
						 * conn->errorMessage does not get cleared.  We need
						 * to preserve any error messages related to previous
						 * hosts we have tried and failed to connect to.
						 */
						conn->status = CONNECTION_OK;
						if (!PQsendQueryContinue(conn,
												 ""SHOW transaction_read_only""))
							goto error_return;
						/* We'll return to this state when we have the answer */
						conn->status = CONNECTION_CHECK_WRITABLE;
						return PGRES_POLLING_READING;
					}

					/* OK, we can make the test */
					read_only_server =
						(conn->default_transaction_read_only == PG_BOOL_YES ||
						 conn->in_hot_standby == PG_BOOL_YES);

					if ((conn->target_server_type == SERVER_TYPE_READ_WRITE) ?
						read_only_server : !read_only_server)
					{
						/* Wrong server state, reject and try the next host */
						if (conn->target_server_type == SERVER_TYPE_READ_WRITE)
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""session is read-only\n""));
						else
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""session is not read-only\n""));

						/* Close connection politely. */
						conn->status = CONNECTION_OK;
						sendTerminateConn(conn);

						/*
						 * Try next host if any, but we don't want to consider
						 * additional addresses for this host.
						 */
						conn->try_next_host = true;
						goto keep_going;
					}
				}
				else if (conn->target_server_type == SERVER_TYPE_PRIMARY ||
						 conn->target_server_type == SERVER_TYPE_STANDBY ||
						 conn->target_server_type == SERVER_TYPE_PREFER_STANDBY)
				{
					/*
					 * If the server didn't report ""in_hot_standby"" at
					 * startup, we must determine its state by sending the
					 * query ""SELECT pg_catalog.pg_is_in_recovery()"".  Servers
					 * before 9.0 don't have that function, but by the same
					 * token they don't have any standby mode, so we may just
					 * assume the result.
					 */
					if (conn->sversion < 90000)
						conn->in_hot_standby = PG_BOOL_NO;

					if (conn->in_hot_standby == PG_BOOL_UNKNOWN)
					{
						/*
						 * We use PQsendQueryContinue so that
						 * conn->errorMessage does not get cleared.  We need
						 * to preserve any error messages related to previous
						 * hosts we have tried and failed to connect to.
						 */
						conn->status = CONNECTION_OK;
						if (!PQsendQueryContinue(conn,
												 ""SELECT pg_catalog.pg_is_in_recovery()""))
							goto error_return;
						/* We'll return to this state when we have the answer */
						conn->status = CONNECTION_CHECK_STANDBY;
						return PGRES_POLLING_READING;
					}

					/* OK, we can make the test */
					if ((conn->target_server_type == SERVER_TYPE_PRIMARY) ?
						(conn->in_hot_standby == PG_BOOL_YES) :
						(conn->in_hot_standby == PG_BOOL_NO))
					{
						/* Wrong server state, reject and try the next host */
						if (conn->target_server_type == SERVER_TYPE_PRIMARY)
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""server is in hot standby mode\n""));
						else
							appendPQExpBufferStr(&conn->errorMessage,
												 libpq_gettext(""server is not in hot standby mode\n""));

						/* Close connection politely. */
						conn->status = CONNECTION_OK;
						sendTerminateConn(conn);

						/*
						 * Try next host if any, but we don't want to consider
						 * additional addresses for this host.
						 */
						conn->try_next_host = true;
						goto keep_going;
					}
				}

				/* We can release the address list now. */
				release_conn_addrinfo(conn);

				/*
				 * Contents of conn->errorMessage are no longer interesting
				 * (and it seems some clients expect it to be empty after a
				 * successful connection).
				 */
				resetPQExpBuffer(&conn->errorMessage);

				/* We are open for business! */
				conn->status = CONNECTION_OK;
				return PGRES_POLLING_OK;
			}

		case CONNECTION_CONSUME:
			{
				/*
				 * This state just makes sure the connection is idle after
				 * we've obtained the result of a SHOW or SELECT query.  Once
				 * we're clear, return to CONNECTION_CHECK_TARGET state to
				 * decide what to do next.  We must transiently set status =
				 * CONNECTION_OK in order to use the result-consuming
				 * subroutines.
				 */
				conn->status = CONNECTION_OK;
				if (!PQconsumeInput(conn))
					goto error_return;

				if (PQisBusy(conn))
				{
					conn->status = CONNECTION_CONSUME;
					return PGRES_POLLING_READING;
				}

				/* Call PQgetResult() again until we get a NULL result */
				res = PQgetResult(conn);
				if (res != NULL)
				{
					PQclear(res);
					conn->status = CONNECTION_CONSUME;
					return PGRES_POLLING_READING;
				}

				conn->status = CONNECTION_CHECK_TARGET;
				goto keep_going;
			}

		case CONNECTION_CHECK_WRITABLE:
			{
				/*
				 * Waiting for result of ""SHOW transaction_read_only"".  We
				 * must transiently set status = CONNECTION_OK in order to use
				 * the result-consuming subroutines.
				 */
				conn->status = CONNECTION_OK;
				if (!PQconsumeInput(conn))
					goto error_return;

				if (PQisBusy(conn))
				{
					conn->status = CONNECTION_CHECK_WRITABLE;
					return PGRES_POLLING_READING;
				}

				res = PQgetResult(conn);
				if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
					PQntuples(res) == 1)
				{
					char	   *val = PQgetvalue(res, 0, 0);

					/*
					 * ""transaction_read_only = on"" proves that at least one
					 * of default_transaction_read_only and in_hot_standby is
					 * on, but we don't actually know which.  We don't care
					 * though for the purpose of identifying a read-only
					 * session, so satisfy the CONNECTION_CHECK_TARGET code by
					 * claiming they are both on.  On the other hand, if it's
					 * a read-write session, they are certainly both off.
					 */
					if (strncmp(val, ""on"", 2) == 0)
					{
						conn->default_transaction_read_only = PG_BOOL_YES;
						conn->in_hot_standby = PG_BOOL_YES;
					}
					else
					{
						conn->default_transaction_read_only = PG_BOOL_NO;
						conn->in_hot_standby = PG_BOOL_NO;
					}
					PQclear(res);

					/* Finish reading messages before continuing */
					conn->status = CONNECTION_CONSUME;
					goto keep_going;
				}

				/* Something went wrong with ""SHOW transaction_read_only"". */
				if (res)
					PQclear(res);

				/* Append error report to conn->errorMessage. */
				appendPQExpBuffer(&conn->errorMessage,
								  libpq_gettext(""\""%s\"" failed\n""),
								  ""SHOW transaction_read_only"");

				/* Close connection politely. */
				conn->status = CONNECTION_OK;
				sendTerminateConn(conn);

				/* Try next host. */
				conn->try_next_host = true;
				goto keep_going;
			}

		case CONNECTION_CHECK_STANDBY:
			{
				/*
				 * Waiting for result of ""SELECT pg_is_in_recovery()"".  We
				 * must transiently set status = CONNECTION_OK in order to use
				 * the result-consuming subroutines.
				 */
				conn->status = CONNECTION_OK;
				if (!PQconsumeInput(conn))
					goto error_return;

				if (PQisBusy(conn))
				{
					conn->status = CONNECTION_CHECK_STANDBY;
					return PGRES_POLLING_READING;
				}

				res = PQgetResult(conn);
				if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
					PQntuples(res) == 1)
				{
					char	   *val = PQgetvalue(res, 0, 0);

					if (strncmp(val, ""t"", 1) == 0)
						conn->in_hot_standby = PG_BOOL_YES;
					else
						conn->in_hot_standby = PG_BOOL_NO;
					PQclear(res);

					/* Finish reading messages before continuing */
					conn->status = CONNECTION_CONSUME;
					goto keep_going;
				}

				/* Something went wrong with ""SELECT pg_is_in_recovery()"". */
				if (res)
					PQclear(res);

				/* Append error report to conn->errorMessage. */
				appendPQExpBuffer(&conn->errorMessage,
								  libpq_gettext(""\""%s\"" failed\n""),
								  ""SELECT pg_is_in_recovery()"");

				/* Close connection politely. */
				conn->status = CONNECTION_OK;
				sendTerminateConn(conn);

				/* Try next host. */
				conn->try_next_host = true;
				goto keep_going;
			}

		default:
			appendPQExpBuffer(&conn->errorMessage,
							  libpq_gettext(""invalid connection state %d, ""
											""probably indicative of memory corruption\n""),
							  conn->status);
			goto error_return;
	}

	/* Unreachable */

error_return:

	/*
	 * We used to close the socket at this point, but that makes it awkward
	 * for those above us if they wish to remove this socket from their own
	 * records (an fd_set for example).  We'll just have this socket closed
	 * when PQfinish is called (which is compulsory even after an error, since
	 * the connection structure must be freed).
	 */
	conn->status = CONNECTION_BAD;
	return PGRES_POLLING_FAILED;
}",1
"bool RepeatedAttrDefEqual(
    const protobuf::RepeatedPtrField& a1,
    const protobuf::RepeatedPtrField& a2) {
  std::unordered_map a1_set;
  for (const OpDef::AttrDef& def : a1) {
    DCHECK(a1_set.find(def.name()) == a1_set.end())
        << ""AttrDef names must be unique, but '"" << def.name()
        << ""' appears more than once"";
    a1_set[def.name()] = &def;
  }
  for (const OpDef::AttrDef& def : a2) {
    auto iter = a1_set.find(def.name());
    if (iter == a1_set.end()) return false;
    if (!AttrDefEqual(*iter->second, def)) return false;
    a1_set.erase(iter);
  }
  if (!a1_set.empty()) return false;
  return true;
}",1
"  void Compute(tensorflow::OpKernelContext* context) override {
    for (int ngram_width : ngram_widths_) {
      OP_REQUIRES(
          context, ngram_width > 0,
          errors::InvalidArgument(""ngram_widths must contain positive values""));
    }

    const tensorflow::Tensor* data;
    OP_REQUIRES_OK(context, context->input(""data"", &data));
    const auto& input_data = data->flat().data();

    const tensorflow::Tensor* splits;
    OP_REQUIRES_OK(context, context->input(""data_splits"", &splits));
    const auto& splits_vec = splits->flat();

    // Validate that the splits are valid indices into data, only if there are
    // splits specified.
    const int input_data_size = data->flat().size();
    const int splits_vec_size = splits_vec.size();
    if (splits_vec_size > 0) {
      int prev_split = splits_vec(0);
      OP_REQUIRES(context, prev_split == 0,
                  errors::InvalidArgument(""First split value must be 0, got "",
                                          prev_split));
      for (int i = 1; i < splits_vec_size; ++i) {
        bool valid_splits = splits_vec(i) >= prev_split;
        valid_splits = valid_splits && (splits_vec(i) <= input_data_size);
        OP_REQUIRES(context, valid_splits,
                    errors::InvalidArgument(
                        ""Invalid split value "", splits_vec(i), "", must be in ["",
                        prev_split, "", "", input_data_size, ""]""));
        prev_split = splits_vec(i);
      }
      OP_REQUIRES(context, prev_split == input_data_size,
                  errors::InvalidArgument(
                      ""Last split value must be data size. Expected "",
                      input_data_size, "", got "", prev_split));
    }

    int num_batch_items = splits_vec.size() - 1;
    tensorflow::Tensor* ngrams_splits;
    OP_REQUIRES_OK(
        context, context->allocate_output(1, splits->shape(), &ngrams_splits));
    auto ngrams_splits_data = ngrams_splits->flat().data();

    // If there is no data or size, return an empty RT.
    if (data->flat().size() == 0 || splits_vec.size() == 0) {
      tensorflow::Tensor* empty;
      OP_REQUIRES_OK(context,
                     context->allocate_output(0, data->shape(), &empty));
      for (int i = 0; i <= num_batch_items; ++i) {
        ngrams_splits_data[i] = 0;
      }
      return;
    }

    ngrams_splits_data[0] = 0;
    for (int i = 1; i <= num_batch_items; ++i) {
      int length = splits_vec(i) - splits_vec(i - 1);
      int num_ngrams = 0;
      for (int ngram_width : ngram_widths_)
        num_ngrams += get_num_ngrams(length, ngram_width);
      if (preserve_short_ && length > 0 && num_ngrams == 0) {
        num_ngrams = 1;
      }
      ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams;
    }

    tensorflow::Tensor* ngrams;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams));
    auto ngrams_data = ngrams->flat().data();

    for (int i = 0; i < num_batch_items; ++i) {
      auto data_start = &input_data[splits_vec(i)];
      int output_start_idx = ngrams_splits_data[i];
      for (int ngram_width : ngram_widths_) {
        auto output_start = &ngrams_data[output_start_idx];
        int length = splits_vec(i + 1) - splits_vec(i);
        int num_ngrams = get_num_ngrams(length, ngram_width);
        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
        output_start_idx += num_ngrams;
      }
      // If we're preserving short sequences, check to see if no sequence was
      // generated by comparing the current output start idx to the original
      // one (ngram_splits_data). If no ngrams were generated, then they will
      // be equal (since we increment output_start_idx by num_ngrams every
      // time we create a set of ngrams.)
      if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) {
        int data_length = splits_vec(i + 1) - splits_vec(i);
        // One legitimate reason to not have any ngrams when preserve_short_
        // is true is if the sequence itself is empty. In that case, move on.
        if (data_length == 0) {
          continue;
        }
        // We don't have to worry about dynamic padding sizes here: if padding
        // was dynamic, every sequence would have had sufficient padding to
        // generate at least one ngram.
        int ngram_width = data_length + 2 * pad_width_;
        auto output_start = &ngrams_data[output_start_idx];
        int num_ngrams = 1;
        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
      }
    }
  }",1
"static int vidioc_querycap(struct file *file, void *priv,
			   struct v4l2_capability *cap)
{
	struct v4l2_loopback_device *dev = v4l2loopback_getdevice(file);
	int labellen = (sizeof(cap->card) < sizeof(dev->card_label)) ?
			       sizeof(cap->card) :
				     sizeof(dev->card_label);
	int device_nr =
		((struct v4l2loopback_private *)video_get_drvdata(dev->vdev))
			->device_nr;
	__u32 capabilities = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;

	strlcpy(cap->driver, ""v4l2 loopback"", sizeof(cap->driver));
	snprintf(cap->card, labellen, dev->card_label);
	snprintf(cap->bus_info, sizeof(cap->bus_info),
		 ""platform:v4l2loopback-%03d"", device_nr);

#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 1, 0)
	/* since 3.1.0, the v4l2-core system is supposed to set the version */
	cap->version = V4L2LOOPBACK_VERSION_CODE;
#endif

#ifdef V4L2_CAP_VIDEO_M2M
	capabilities |= V4L2_CAP_VIDEO_M2M;
#endif /* V4L2_CAP_VIDEO_M2M */

	if (dev->announce_all_caps) {
		capabilities |= V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT;
	} else {
		if (dev->ready_for_capture) {
			capabilities |= V4L2_CAP_VIDEO_CAPTURE;
		}
		if (dev->ready_for_output) {
			capabilities |= V4L2_CAP_VIDEO_OUTPUT;
		}
	}

#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 7, 0)
	dev->vdev->device_caps =
#endif /* >=linux-4.7.0 */
		cap->device_caps = cap->capabilities = capabilities;

#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 3, 0)
	cap->capabilities |= V4L2_CAP_DEVICE_CAPS;
#endif

	memset(cap->reserved, 0, sizeof(cap->reserved));
	return 0;
}",1
"bool IsIdentityConsumingSwitch(const MutableGraphView& graph,
                               const NodeDef& node) {
  if ((IsIdentity(node) || IsIdentityNSingleInput(node)) &&
      node.input_size() > 0) {
    TensorId tensor_id = ParseTensorName(node.input(0));
    if (IsTensorIdControlling(tensor_id)) {
      return false;
    }

    NodeDef* input_node = graph.GetNode(tensor_id.node());
    return IsSwitch(*input_node);
  }
  return false;
}",1
"int TfLiteIntArrayGetSizeInBytes(int size) {
  static TfLiteIntArray dummy;

  int computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size;
#if defined(_MSC_VER)
  // Context for why this is needed is in http://b/189926408#comment21
  computed_size -= sizeof(dummy.data[0]);
#endif
  return computed_size;
}",1
"TfLiteIntArray* TfLiteIntArrayCreate(int size) {
  int alloc_size = TfLiteIntArrayGetSizeInBytes(size);
  if (alloc_size <= 0) return NULL;
  TfLiteIntArray* ret = (TfLiteIntArray*)malloc(alloc_size);
  if (!ret) return ret;
  ret->size = size;
  return ret;
}",1
"  void Compute(OpKernelContext* context) override {
    typedef Eigen::Map>
        ConstEigenMatrixMap;
    typedef Eigen::Map>
        EigenMatrixMap;

    constexpr int tensor_in_and_out_dims = 4;

    const Tensor& tensor_in = context->input(0);
    OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,
                errors::InvalidArgument(""tensor_in must be 4-dimensional""));

    std::vector input_size(tensor_in_and_out_dims);
    std::vector output_size(tensor_in_and_out_dims);
    for (int i = 0; i < tensor_in_and_out_dims; ++i) {
      input_size[i] = tensor_in.dim_size(i);
    }
    // Output size.
    for (int i = 0; i < tensor_in_and_out_dims; ++i) {
      // This must match the same logic in the shape function in
      // core/ops/nn_ops.cc.
      output_size[i] =
          static_cast(std::floor(input_size[i] / pooling_ratio_[i]));
      DCHECK_GT(output_size[i], 0);
    }

    // Generate pooling sequence.
    std::vector height_cum_seq;
    std::vector width_cum_seq;
    GuardedPhiloxRandom generator;
    generator.Init(seed_, seed2_);
    height_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],
                                             &generator, pseudo_random_);
    width_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],
                                            &generator, pseudo_random_);

    // Prepare output.
    Tensor* output_tensor = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                0,
                                TensorShape({output_size[0], output_size[1],
                                             output_size[2], output_size[3]}),
                                &output_tensor));
    Tensor* output_height_seq_tensor = nullptr;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            1, TensorShape({static_cast(height_cum_seq.size())}),
            &output_height_seq_tensor));
    Tensor* output_width_seq_tensor = nullptr;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            2, TensorShape({static_cast(width_cum_seq.size())}),
            &output_width_seq_tensor));

    ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],
                               input_size[2] * input_size[1] * input_size[0]);

    EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],
                           output_size[2] * output_size[1] * output_size[0]);

    // Initializes the output tensor with MIN.
    output_tensor->flat().setConstant(Eigen::NumTraits::lowest());

    auto output_height_seq_flat = output_height_seq_tensor->flat();
    auto output_width_seq_flat = output_width_seq_tensor->flat();

    // Set output tensors.
    for (int i = 0; i < height_cum_seq.size(); ++i) {
      output_height_seq_flat(i) = height_cum_seq[i];
    }

    for (int i = 0; i < width_cum_seq.size(); ++i) {
      output_width_seq_flat(i) = width_cum_seq[i];
    }

    // For both input and output,
    // 0: batch
    // 1: height / row
    // 2: width / col
    // 3: depth / channel
    const int64_t height_max = input_size[1] - 1;
    const int64_t width_max = input_size[2] - 1;
    for (int64_t b = 0; b < input_size[0]; ++b) {
      // height sequence.
      for (int64_t hs = 0; hs < height_cum_seq.size() - 1; ++hs) {
        // height start and end.
        const int64_t height_start = height_cum_seq[hs];
        int64_t height_end =
            overlapping_ ? height_cum_seq[hs + 1] : height_cum_seq[hs + 1] - 1;
        height_end = std::min(height_end, height_max);

        // width sequence.
        for (int64_t ws = 0; ws < width_cum_seq.size() - 1; ++ws) {
          const int64_t out_offset =
              (b * output_size[1] + hs) * output_size[2] + ws;
          // width start and end.
          const int64_t width_start = width_cum_seq[ws];
          int64_t width_end =
              overlapping_ ? width_cum_seq[ws + 1] : width_cum_seq[ws + 1] - 1;
          width_end = std::min(width_end, width_max);
          for (int64_t h = height_start; h <= height_end; ++h) {
            for (int64_t w = width_start; w <= width_end; ++w) {
              const int64_t in_offset =
                  (b * input_size[1] + h) * input_size[2] + w;
              out_mat.col(out_offset) =
                  out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));
            }
          }
        }
      }
    }
  }",1
"static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CropBox  ""CropBox""
#define DeviceCMYK  ""DeviceCMYK""
#define MediaBox  ""MediaBox""
#define RenderPCLText  ""  Rendering PCL...  ""

  char
    command[MaxTextExtent],
    *density,
    filename[MaxTextExtent],
    geometry[MaxTextExtent],
    *options,
    input_filename[MaxTextExtent];

  const DelegateInfo
    *delegate_info;

  Image
    *image,
    *next_image;

  ImageInfo
    *read_info;

  int
    c;

  MagickBooleanType
    cmyk,
    status;

  PointInfo
    delta;

  RectangleInfo
    bounding_box,
    page;

  char
    *p;

  SegmentInfo
    bounds;

  size_t
    height,
    width;

  ssize_t
    count;

  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  /*
    Open image file.
  */
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
  if (status == MagickFalse)
    {
      ThrowFileException(exception,FileOpenError,""UnableToCreateTemporaryFile"",
        image_info->filename);
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Set the page density.
  */
  delta.x=DefaultResolution;
  delta.y=DefaultResolution;
  if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
    {
      GeometryInfo
        geometry_info;

      MagickStatusType
        flags;

      flags=ParseGeometry(PSDensityGeometry,&geometry_info);
      if ((flags & RhoValue) != 0)
        image->x_resolution=geometry_info.rho;
      image->y_resolution=image->x_resolution;
      if ((flags & SigmaValue) != 0)
        image->y_resolution=geometry_info.sigma;
    }
  /*
    Determine page geometry from the PCL media box.
  */
  cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
  count=0;
  (void) memset(&bounding_box,0,sizeof(bounding_box));
  (void) memset(&bounds,0,sizeof(bounds));
  (void) memset(&page,0,sizeof(page));
  (void) memset(command,0,sizeof(command));
  p=command;
  for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
  {
    if (image_info->page != (char *) NULL)
      continue;
    /*
      Note PCL elements.
    */
    *p++=(char) c;
    if ((c != (int) '/') && (c != '\n') &&
        ((size_t) (p-command) < (MaxTextExtent-1)))
      continue;
    *p='\0';
    p=command;
    /*
      Is this a CMYK document?
    */
    if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)
      cmyk=MagickTrue;
    if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)
      {
        /*
          Note region defined by crop box.
        */
        count=(ssize_t) sscanf(command,""CropBox [%lf %lf %lf %lf"",
          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
        if (count != 4)
          count=(ssize_t) sscanf(command,""CropBox[%lf %lf %lf %lf"",
            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
      }
    if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)
      {
        /*
          Note region defined by media box.
        */
        count=(ssize_t) sscanf(command,""MediaBox [%lf %lf %lf %lf"",
          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
        if (count != 4)
          count=(ssize_t) sscanf(command,""MediaBox[%lf %lf %lf %lf"",
            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
      }
    if (count != 4)
      continue;
    /*
      Set PCL render geometry.
    */
    width=(size_t) floor(bounds.x2-bounds.x1+0.5);
    height=(size_t) floor(bounds.y2-bounds.y1+0.5);
    if (width > page.width)
      page.width=width;
    if (height > page.height)
      page.height=height;
  }
  (void) CloseBlob(image);
  /*
    Render PCL with the GhostPCL delegate.
  */
  if ((page.width == 0) || (page.height == 0))
    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  (void) FormatLocaleString(geometry,MaxTextExtent,""%.20gx%.20g"",(double)
    page.width,(double) page.height);
  if (image_info->monochrome != MagickFalse)
    delegate_info=GetDelegateInfo(""pcl:mono"",(char *) NULL,exception);
  else
     if (cmyk != MagickFalse)
       delegate_info=GetDelegateInfo(""pcl:cmyk"",(char *) NULL,exception);
     else
       delegate_info=GetDelegateInfo(""pcl:color"",(char *) NULL,exception);
  if (delegate_info == (const DelegateInfo *) NULL)
    {
      image=DestroyImage(image);
      return((Image *) NULL);
    }
  if ((page.width == 0) || (page.height == 0))
    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  density=AcquireString("""");
  options=AcquireString("""");
  (void) FormatLocaleString(density,MaxTextExtent,""%gx%g"",
    image->x_resolution,image->y_resolution);
  if (image_info->ping != MagickFalse)
    (void) FormatLocaleString(density,MagickPathExtent,""2.0x2.0"");
  page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+
    0.5);
  page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+
    0.5);
  (void) FormatLocaleString(options,MaxTextExtent,""-g%.20gx%.20g "",(double)
     page.width,(double) page.height);
  image=DestroyImage(image);
  read_info=CloneImageInfo(image_info);
  *read_info->magick='\0';
  if (read_info->number_scenes != 0)
    {
      if (read_info->number_scenes != 1)
        (void) FormatLocaleString(options,MaxTextExtent,""-dLastPage=%.20g"",
          (double) (read_info->scene+read_info->number_scenes));
      else
        (void) FormatLocaleString(options,MaxTextExtent,
          ""-dFirstPage=%.20g -dLastPage=%.20g"",(double) read_info->scene+1,
          (double) (read_info->scene+read_info->number_scenes));
      read_info->number_scenes=0;
      if (read_info->scenes != (char *) NULL)
        *read_info->scenes='\0';
    }
  (void) CopyMagickString(filename,read_info->filename,MaxTextExtent);
  (void) AcquireUniqueFilename(read_info->filename);
  (void) FormatLocaleString(command,MaxTextExtent,
    GetDelegateCommands(delegate_info),
    read_info->antialias != MagickFalse ? 4 : 1,
    read_info->antialias != MagickFalse ? 4 : 1,density,options,
    read_info->filename,input_filename);
  options=DestroyString(options);
  density=DestroyString(density);
  status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,
    (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;
  image=ReadImage(read_info,exception);
  (void) RelinquishUniqueFileResource(read_info->filename);
  (void) RelinquishUniqueFileResource(input_filename);
  read_info=DestroyImageInfo(read_info);
  if (image == (Image *) NULL)
    ThrowReaderException(DelegateError,""PCLDelegateFailed"");
  if (LocaleCompare(image->magick,""BMP"") == 0)
    {
      Image
        *cmyk_image;

      cmyk_image=ConsolidateCMYKImages(image,&image->exception);
      if (cmyk_image != (Image *) NULL)
        {
          image=DestroyImageList(image);
          image=cmyk_image;
        }
    }
  do
  {
    (void) CopyMagickString(image->filename,filename,MaxTextExtent);
    image->page=page;
    if (image_info->ping != MagickFalse)
      {
        image->magick_columns*=image->x_resolution/2.0;
        image->magick_rows*=image->y_resolution/2.0;
        image->columns*=image->x_resolution/2.0;
        image->rows*=image->y_resolution/2.0;
      }
    next_image=SyncNextImageInList(image);
    if (next_image != (Image *) NULL)
      image=next_image;
  } while (next_image != (Image *) NULL);
  return(GetFirstImageInList(image));
}",1
"
void gitn_box_del(GF_Box *s)
{
	u32 i;
	GroupIdToNameBox *ptr = (GroupIdToNameBox *)s;
	if (ptr == NULL) return;
	for (i=0; inb_entries; i++) {
		if (ptr->entries[i].name) gf_free(ptr->entries[i].name);
	}
	if (ptr->entries) gf_free(ptr->entries);
	gf_free(ptr);",1
"  void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
    // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in
    // the step container, and return it as the output.
    const Tensor* indices;
    OP_REQUIRES_OK(ctx, ctx->input(""indices"", &indices));
    const Tensor* values;
    OP_REQUIRES_OK(ctx, ctx->input(""values"", &values));
    const Tensor* dense_shape;
    OP_REQUIRES_OK(ctx, ctx->input(""dense_shape"", &dense_shape));

    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()),
                errors::InvalidArgument(
                    ""Input indices should be a matrix but received shape "",
                    indices->shape().DebugString()));

    const auto num_indices = indices->NumElements();
    const auto num_values = values->NumElements();
    if (num_indices == 0 || num_values == 0) {
      OP_REQUIRES(ctx, num_indices == num_values,
                  errors::InvalidArgument(
                      ""If indices or values are empty, the other one must also ""
                      ""be. Got indices of shape "",
                      indices->shape().DebugString(), "" and values of shape "",
                      values->shape().DebugString()));
    }
    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()),
                errors::InvalidArgument(
                    ""Input values should be a vector but received shape "",
                    indices->shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()),
                errors::InvalidArgument(
                    ""Input shape should be a vector but received shape "",
                    dense_shape->shape().DebugString()));

    // We currently ensure that `sparse_tensor` is ordered in the
    // batch dimension.
    // TODO(mrry): Investigate ways to avoid this unconditional check
    // if we can be sure that the sparse tensor was produced in an
    // appropriate order (e.g. by `tf.parse_example()` or a Dataset
    // that batches elements into rows of a SparseTensor).
    int64_t previous_batch_index = -1;
    for (int64_t i = 0; i < indices->dim_size(0); ++i) {
      int64_t next_batch_index = indices->matrix()(i, 0);
      OP_REQUIRES(
          ctx, next_batch_index >= previous_batch_index,
          errors::Unimplemented(""The SparseTensor must be ordered in the batch ""
                                ""dimension; handling arbitrarily ordered input ""
                                ""is not currently supported.""));
      previous_batch_index = next_batch_index;
    }
    gtl::InlinedVector std_order(dense_shape->NumElements(), 0);
    sparse::SparseTensor tensor;
    OP_REQUIRES_OK(
        ctx, sparse::SparseTensor::Create(
                 *indices, *values, TensorShape(dense_shape->vec()),
                 std_order, &tensor));
    *output = new Dataset(ctx, std::move(tensor));
  }",1
"IRC_PROTOCOL_CALLBACK(352)
{
    char *pos_attr, *pos_hopcount, *pos_realname, *str_host;
    int arg_start, length;
    struct t_irc_channel *ptr_channel;
    struct t_irc_nick *ptr_nick;

    IRC_PROTOCOL_MIN_ARGS(5);

    /* silently ignore malformed 352 message (missing infos) */
    if (argc < 8)
        return WEECHAT_RC_OK;

    pos_attr = NULL;
    pos_hopcount = NULL;
    pos_realname = NULL;

    if (argc > 8)
    {
        arg_start = (strcmp (argv[8], ""*"") == 0) ? 9 : 8;
        if (argv[arg_start][0] == ':')
        {
            pos_attr = NULL;
            pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;
            pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;
        }
        else
        {
            pos_attr = argv[arg_start];
            pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;
            pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;
        }
    }

    ptr_channel = irc_channel_search (server, argv[3]);
    ptr_nick = (ptr_channel) ?
        irc_nick_search (server, ptr_channel, argv[7]) : NULL;

    /* update host in nick */
    if (ptr_nick)
    {
        length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;
        str_host = malloc (length);
        if (str_host)
        {
            snprintf (str_host, length, ""%s@%s"", argv[4], argv[5]);
            irc_nick_set_host (ptr_nick, str_host);
            free (str_host);
        }
    }

    /* update away flag in nick */
    if (ptr_channel && ptr_nick && pos_attr)
    {
        irc_nick_set_away (server, ptr_channel, ptr_nick,
                           (pos_attr[0] == 'G') ? 1 : 0);
    }

    /* update realname in nick */
    if (ptr_channel && ptr_nick && pos_realname)
    {
        if (ptr_nick->realname)
            free (ptr_nick->realname);
        if (pos_realname &&
            weechat_hashtable_has_key (server->cap_list, ""extended-join""))
        {
            ptr_nick->realname = strdup (pos_realname);
        }
        else
        {
            ptr_nick->realname = NULL;
        }
    }

    /* display output of who (manual who from user) */
    if (!ptr_channel || (ptr_channel->checking_whox <= 0))
    {
        weechat_printf_date_tags (
            irc_msgbuffer_get_target_buffer (
                server, NULL, command, ""who"", NULL),
            date,
            irc_protocol_tags (command, ""irc_numeric"", NULL, NULL),
            ""%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)"",
            weechat_prefix (""network""),
            IRC_COLOR_CHAT_DELIMITERS,
            IRC_COLOR_CHAT_CHANNEL,
            argv[3],
            IRC_COLOR_CHAT_DELIMITERS,
            irc_nick_color_for_msg (server, 1, NULL, argv[7]),
            argv[7],
            IRC_COLOR_CHAT_DELIMITERS,
            IRC_COLOR_CHAT_HOST,
            argv[4],
            argv[5],
            IRC_COLOR_CHAT_DELIMITERS,
            IRC_COLOR_RESET,
            (pos_attr) ? pos_attr : """",
            (pos_attr) ? "" "" : """",
            (pos_hopcount) ? pos_hopcount : """",
            (pos_hopcount) ? "" "" : """",
            (pos_realname) ? pos_realname : """");
    }

    return WEECHAT_RC_OK;
}",1
"bool JSON_parser(Variant &z, const char *p, int length, bool const assoc,
                 int depth, int64_t options) {
  // No GC safepoints during JSON parsing, please. Code is not re-entrant.
  NoHandleSurpriseScope no_surprise(SafepointFlags);

  json_parser *json = s_json_parser.get(); /* the parser state */
  // Clear and reuse the thread-local string buffers. They are only freed if
  // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread
  // is explicitly flushed (e.g., due to being idle).
  json->initSb(length);
  SCOPE_EXIT {
    constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024;
    if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb();
  };
  // SimpleParser only handles the most common set of options. Also, only use it
  // if its array nesting depth check is *more* restrictive than what the user
  // asks for, to ensure that the precise semantics of the general case is
  // applied for all nesting overflows.
  if (assoc &&
      options == (options & (k_JSON_FB_LOOSE |
                             k_JSON_FB_DARRAYS |
                             k_JSON_FB_DARRAYS_AND_VARRAYS |
                             k_JSON_FB_HACK_ARRAYS |
                             k_JSON_FB_THRIFT_SIMPLE_JSON |
                             k_JSON_FB_LEGACY_HACK_ARRAYS)) &&
      depth >= SimpleParser::kMaxArrayDepth &&
      length <= RuntimeOption::EvalSimpleJsonMaxLength &&
      SimpleParser::TryParse(p, length, json->tl_buffer.tv, z,
                             get_container_type_from_options(options),
                             options & k_JSON_FB_THRIFT_SIMPLE_JSON)) {
    return true;
  }

  int b;  /* the next character */
  int c;  /* the next character class */
  int s;  /* the next state */
  int state = 0;

  /**/
  bool const loose = options & k_JSON_FB_LOOSE;
  JSONContainerType const container_type =
    get_container_type_from_options(options);
  int qchr = 0;
  int8_t const *byte_class;
  int8_t const (*next_state_table)[32];
  if (loose) {
    byte_class = loose_ascii_class;
    next_state_table = loose_state_transition_table;
  } else {
    byte_class = ascii_class;
    next_state_table = state_transition_table;
  }
  /**/

  UncheckedBuffer *buf = &json->sb_buf;
  UncheckedBuffer *key = &json->sb_key;

  DataType type = kInvalidDataType;
  unsigned short escaped_bytes = 0;

  auto reset_type = [&] { type = kInvalidDataType; };

  json->depth = depth;
  // Since the stack is maintainined on a per request basis, for performance
  // reasons, it only makes sense to expand if necessary and cycles are wasted
  // contracting. Calls with a depth other than default should be rare.
  if (depth > json->stack.size()) {
    json->stack.resize(depth);
  }
  SCOPE_EXIT {
    if (json->stack.empty()) return;
    for (int i = 0; i <= json->mark; i++) {
      json->stack[i].key.reset();
      json->stack[i].val.unset();
    }
    json->mark = -1;
  };

  json->mark = json->top = -1;
  push(json, Mode::DONE);

  UTF8To16Decoder decoder(p, length, loose);
  for (;;) {
    b = decoder.decode();
    // Fast-case most common transition: append a simple string character.
    if (state == 3 && type == KindOfString) {
      while (b != '\""' &&  b != '\\' && b != '\'' && b <= 127 && b >= ' ') {
        buf->append((char)b);
        b = decoder.decode();
      }
    }
    if (b == UTF8_END) break; // UTF-8 decoding finishes successfully.
    if (b == UTF8_ERROR) {
      s_json_parser->error_code = JSON_ERROR_UTF8;
      return false;
    }
    assertx(b >= 0);

    if ((b & 127) == b) {
      /**/
      c = byte_class[b];
      /**/
      if (c <= S_ERR) {
        s_json_parser->error_code = JSON_ERROR_CTRL_CHAR;
        return false;
      }
    } else {
      c = S_ETC;
    }
    /*
      Get the next state from the transition table.
    */

    /**/
    s = next_state_table[state][c];

    if (s == -4) {
      if (b != qchr) {
        s = 3;
      } else {
        qchr = 0;
      }
    }
    /**/

    if (s < 0) {
      /*
        Perform one of the predefined actions.
      */
      switch (s) {
        /*
          empty }
        */
      case -9:
        /**/
        if (json->top == 1) z = json->stack[json->top].val;
        else {
        /**/
          attach_zval(json, json->stack[json->top].key, assoc, container_type);
        /**/
        }
        /**/
        if (!pop(json, Mode::KEY)) {
          return false;
        }
        state = 9;
        break;
        /*
          {
        */
      case -8:
        if (!push(json, Mode::KEY)) {
          s_json_parser->error_code = JSON_ERROR_DEPTH;
          return false;
        }

        state = 1;
        if (json->top > 0) {
          Variant &top = json->stack[json->top].val;
          /**/
          if (container_type == JSONContainerType::COLLECTIONS) {
            // stable_maps is meaningless
            top = req::make();
          } else {
          /**/
            if (!assoc) {
              top = SystemLib::AllocStdClassObject();
            /*  */
            } else if (container_type == JSONContainerType::HACK_ARRAYS) {
              top = Array::CreateDict();
            } else if (container_type == JSONContainerType::DARRAYS ||
                       container_type == JSONContainerType::DARRAYS_AND_VARRAYS)
            {
              top = Array::CreateDArray();
            /*  */
            } else if (
              container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
              auto arr = staticEmptyDictArray()->copy();
              arr->setLegacyArray(true);
              top = arr;
            } else {
              top = Array::CreateDArray();
            }
          /**/
          }
          /**/
          json->stack[json->top].key = copy_and_clear(*key);
          reset_type();
        }
        break;
        /*
          }
        */
      case -7:
        /*** BEGIN Facebook: json_utf8_loose ***/
        /*
          If this is a trailing comma in an object definition,
          we're in Mode::KEY. In that case, throw that off the
          stack and restore Mode::OBJECT so that we pretend the
          trailing comma just didn't happen.
        */
        if (loose) {
          if (pop(json, Mode::KEY)) {
            push(json, Mode::OBJECT);
          }
        }
        /*** END Facebook: json_utf8_loose ***/

        if (type != kInvalidDataType &&
            json->stack[json->top].mode == Mode::OBJECT) {
          Variant mval;
          json_create_zval(mval, *buf, type, options);
          Variant &top = json->stack[json->top].val;
          object_set(json, top, copy_and_clear(*key),
                     mval, assoc, container_type);
          buf->clear();
          reset_type();
        }

        /**/
        if (json->top == 1) z = json->stack[json->top].val;
        else {
        /**/
          attach_zval(json, json->stack[json->top].key,
            assoc, container_type);
        /**/
        }
        /**/
        if (!pop(json, Mode::OBJECT)) {
          s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
          return false;
        }
        state = 9;
        break;
        /*
          [
        */
      case -6:
        if (!push(json, Mode::ARRAY)) {
          s_json_parser->error_code = JSON_ERROR_DEPTH;
          return false;
        }
        state = 2;

        if (json->top > 0) {
          Variant &top = json->stack[json->top].val;
          /**/
          if (container_type == JSONContainerType::COLLECTIONS) {
            top = req::make();
          } else if (container_type == JSONContainerType::HACK_ARRAYS) {
            top = Array::CreateVec();
          } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) {
            top = Array::CreateVArray();
          } else if (container_type == JSONContainerType::DARRAYS) {
            top = Array::CreateDArray();
          } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
            auto arr = staticEmptyVecArray()->copy();
            arr->setLegacyArray(true);
            top = arr;
          } else {
            top = Array::CreateDArray();
          }
          /**/
          json->stack[json->top].key = copy_and_clear(*key);
          reset_type();
        }
        break;
        /*
          ]
        */
      case -5:
        {
          if (type != kInvalidDataType &&
               json->stack[json->top].mode == Mode::ARRAY) {
            Variant mval;
            json_create_zval(mval, *buf, type, options);
            auto& top = json->stack[json->top].val;
            if (container_type == JSONContainerType::COLLECTIONS) {
              collections::append(top.getObjectData(), mval.asTypedValue());
            } else {
              top.asArrRef().append(mval);
            }
            buf->clear();
            reset_type();
          }

          /**/
          if (json->top == 1) z = json->stack[json->top].val;
          else {
          /**/
            attach_zval(json, json->stack[json->top].key, assoc,
              container_type);
          /**/
          }
          /**/
          if (!pop(json, Mode::ARRAY)) {
            s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
            return false;
          }
          state = 9;
        }
        break;
        /*
          ""
        */
      case -4:
        switch (json->stack[json->top].mode) {
        case Mode::KEY:
          state = 27;
          std::swap(buf, key);
          reset_type();
          break;
        case Mode::ARRAY:
        case Mode::OBJECT:
          state = 9;
          break;
        case Mode::DONE:
          if (type == KindOfString) {
            z = copy_and_clear(*buf);
            state = 9;
            break;
          }
          /* fall through if not KindOfString */
        default:
          s_json_parser->error_code = JSON_ERROR_SYNTAX;
          return false;
        }
        break;
        /*
          ,
        */
      case -3:
        {
          Variant mval;
          if (type != kInvalidDataType &&
              (json->stack[json->top].mode == Mode::OBJECT ||
               json->stack[json->top].mode == Mode::ARRAY)) {
            json_create_zval(mval, *buf, type, options);
          }

          switch (json->stack[json->top].mode) {
          case Mode::OBJECT:
            if (pop(json, Mode::OBJECT) &&
                push(json, Mode::KEY)) {
              if (type != kInvalidDataType) {
                Variant &top = json->stack[json->top].val;
                object_set(
                  json,
                  top,
                  copy_and_clear(*key),
                  mval,
                  assoc,
                  container_type
                );
              }
              state = 29;
            }
            break;
          case Mode::ARRAY:
            if (type != kInvalidDataType) {
              auto& top = json->stack[json->top].val;
              if (container_type == JSONContainerType::COLLECTIONS) {
                collections::append(top.getObjectData(), mval.asTypedValue());
              } else {
                top.asArrRef().append(mval);
              }
            }
            state = 28;
            break;
          default:
            s_json_parser->error_code = JSON_ERROR_SYNTAX;
            return false;
          }
          buf->clear();
          reset_type();
          check_non_safepoint_surprise();
        }
        break;

        /**/
        /*
          : (after unquoted string)
        */
      case -10:
        if (json->stack[json->top].mode == Mode::KEY) {
          state = 27;
          std::swap(buf, key);
          reset_type();
          s = -2;
        } else {
          s = 3;
          break;
        }
        /**/

        /*
          :
        */
      case -2:
        if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) {
          state = 28;
          break;
        }
        /*
          syntax error
        */
      case -1:
        s_json_parser->error_code = JSON_ERROR_SYNTAX;
        return false;
      }
    } else {
      /*
        Change the state and iterate.
      */
      bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON;
      if (type == KindOfString) {
        if (/**/(/**/s == 3/**/ || s == 30)/**/ &&
            state != 8) {
          if (state != 4) {
            utf16_to_utf8(*buf, b);
          } else {
            switch (b) {
            case 'b': buf->append('\b'); break;
            case 't': buf->append('\t'); break;
            case 'n': buf->append('\n'); break;
            case 'f': buf->append('\f'); break;
            case 'r': buf->append('\r'); break;
            default:
              utf16_to_utf8(*buf, b);
              break;
            }
          }
        } else if (s == 6) {
          if (UNLIKELY(is_tsimplejson)) {
            if (UNLIKELY(b != '0'))  {
              s_json_parser->error_code = JSON_ERROR_SYNTAX;
              return false;
            }
            escaped_bytes = 0;
          } else {
            escaped_bytes = dehexchar(b) << 12;
          }
        } else if (s == 7) {
          if (UNLIKELY(is_tsimplejson)) {
            if (UNLIKELY(b != '0'))  {
              s_json_parser->error_code = JSON_ERROR_SYNTAX;
              return false;
            }
          } else {
            escaped_bytes += dehexchar(b) << 8;
          }
        } else if (s == 8) {
          escaped_bytes += dehexchar(b) << 4;
        } else if (s == 3 && state == 8) {
          escaped_bytes += dehexchar(b);
          if (UNLIKELY(is_tsimplejson)) {
            buf->append((char)escaped_bytes);
          } else {
            utf16_to_utf8(*buf, escaped_bytes);
          }
        }
      } else if ((type == kInvalidDataType || type == KindOfNull) &&
                 (c == S_DIG || c == S_ZER)) {
        type = KindOfInt64;
        buf->append((char)b);
      } else if (type == KindOfInt64 && s == 24) {
        type = KindOfDouble;
        buf->append((char)b);
      } else if ((type == kInvalidDataType || type == KindOfNull ||
                  type == KindOfInt64) &&
                 c == S_DOT) {
        type = KindOfDouble;
        buf->append((char)b);
      } else if (type != KindOfString && c == S_QUO) {
        type = KindOfString;
        /**/qchr = b;/**/
      } else if ((type == kInvalidDataType || type == KindOfNull ||
                  type == KindOfInt64 || type == KindOfDouble) &&
                 ((state == 12 && s == 9) ||
                  (state == 16 && s == 9))) {
        type = KindOfBoolean;
      } else if (type == kInvalidDataType && state == 19 && s == 9) {
        type = KindOfNull;
      } else if (type != KindOfString && c > S_WSP) {
        utf16_to_utf8(*buf, b);
      }

      state = s;
    }
  }

  if (state == 9 && pop(json, Mode::DONE)) {
    s_json_parser->error_code = JSON_ERROR_NONE;
    return true;
  }

  s_json_parser->error_code = JSON_ERROR_SYNTAX;
  return false;
}",1
"bool WddxPacket::recursiveAddVar(const String& varName,
                                 const Variant& varVariant,
                                 bool hasVarTag) {

  bool isArray = varVariant.isArray();
  bool isObject = varVariant.isObject();

  if (isArray || isObject) {
    if (hasVarTag) {
      m_packetString.append("""");
    }

    Array varAsArray;
    Object varAsObject = varVariant.toObject();
    if (isArray) varAsArray = varVariant.toArray();
    if (isObject) varAsArray = varAsObject.toArray();

    int length = varAsArray.length();
    if (length > 0) {
      ArrayIter it = ArrayIter(varAsArray);
      if (it.first().isString()) isObject = true;
      if (isObject) {
        m_packetString.append("""");
        if (!isArray) {
          m_packetString.append("""");
          m_packetString.append(varAsObject->getClassName());
          m_packetString.append("""");
        }
      } else {
        m_packetString.append("""");
      }
      for (ArrayIter it(varAsArray); it; ++it) {
        Variant key = it.first();
        Variant value = it.second();
        recursiveAddVar(key.toString(), value, isObject);
      }
      if (isObject) {
        m_packetString.append("""");
      }
      else {
        m_packetString.append("""");
      }
    }
    else {
      //empty object
      if (isObject) {
        m_packetString.append("""");
        if (!isArray) {
          m_packetString.append("""");
          m_packetString.append(varAsObject->getClassName());
          m_packetString.append("""");
        }
        m_packetString.append("""");
      }
    }
    if (hasVarTag) {
      m_packetString.append("""");
    }
    return true;
  }

  String varType = getDataTypeString(varVariant.getType());
  if (!getWddxEncoded(varType, """", varName, false).empty()) {
    String varValue;
    if (varType.compare(""boolean"") == 0) {
      varValue = varVariant.toBoolean() ? ""true"" : ""false"";
    } else {
      varValue = StringUtil::HtmlEncode(varVariant.toString(),
                                        StringUtil::QuoteStyle::Double,
                                        ""UTF-8"", false, false).toCppString();
    }
    m_packetString.append(
      getWddxEncoded(varType, varValue, varName, hasVarTag));
    return true;
  }

  return false;
}",1
"String string_number_format(double d, int dec,
                            const String& dec_point,
                            const String& thousand_sep) {
  char *tmpbuf = nullptr, *resbuf;
  char *s, *t;  /* source, target */
  char *dp;
  int integral;
  int tmplen, reslen=0;
  int count=0;
  int is_negative=0;

  if (d < 0) {
    is_negative = 1;
    d = -d;
  }

  if (dec < 0) dec = 0;
  d = php_math_round(d, dec);

  // departure from PHP: we got rid of dependencies on spprintf() here.
  String tmpstr(63, ReserveString);
  tmpbuf = tmpstr.mutableData();
  tmplen = snprintf(tmpbuf, 64, ""%.*F"", dec, d);
  if (tmplen < 0) return empty_string();
  if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {
    tmpstr.setSize(tmplen);
    return tmpstr;
  }
  if (tmplen >= 64) {
    // Uncommon, asked for more than 64 chars worth of precision
    tmpstr = String(tmplen, ReserveString);
    tmpbuf = tmpstr.mutableData();
    tmplen = snprintf(tmpbuf, tmplen + 1, ""%.*F"", dec, d);
    if (tmplen < 0) return empty_string();
    if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {
      tmpstr.setSize(tmplen);
      return tmpstr;
    }
  }

  /* find decimal point, if expected */
  if (dec) {
    dp = strpbrk(tmpbuf, "".,"");
  } else {
    dp = nullptr;
  }

  /* calculate the length of the return buffer */
  if (dp) {
    integral = dp - tmpbuf;
  } else {
    /* no decimal point was found */
    integral = tmplen;
  }

  /* allow for thousand separators */
  if (!thousand_sep.empty()) {
    if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) {
      /* overflow */
      raise_error(""String overflow"");
    }

    integral += ((integral-1) / 3) * thousand_sep.size();
  }

  reslen = integral;

  if (dec) {
    reslen += dec;

    if (!dec_point.empty()) {
      if (reslen + dec_point.size() < dec_point.size()) {
        /* overflow */
        raise_error(""String overflow"");
      }
      reslen += dec_point.size();
    }
  }

  /* add a byte for minus sign */
  if (is_negative) {
    reslen++;
  }
  String resstr(reslen, ReserveString);
  resbuf = resstr.mutableData();

  s = tmpbuf+tmplen-1;
  t = resbuf+reslen-1;

  /* copy the decimal places.
   * Take care, as the sprintf implementation may return less places than
   * we requested due to internal buffer limitations */
  if (dec) {
    int declen = dp ? s - dp : 0;
    int topad = dec > declen ? dec - declen : 0;

    /* pad with '0's */
    while (topad--) {
      *t-- = '0';
    }

    if (dp) {
      s -= declen + 1; /* +1 to skip the point */
      t -= declen;

      /* now copy the chars after the point */
      memcpy(t + 1, dp + 1, declen);
    }

    /* add decimal point */
    if (!dec_point.empty()) {
      memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size());
      t -= dec_point.size();
    }
  }

  /* copy the numbers before the decimal point, adding thousand
   * separator every three digits */
  while(s >= tmpbuf) {
    *t-- = *s--;
    if (thousand_sep && (++count%3)==0 && s>=tmpbuf) {
      memcpy(t + (1 - thousand_sep.size()),
             thousand_sep.data(),
             thousand_sep.size());
      t -= thousand_sep.size();
    }
  }

  /* and a minus sign, if needed */
  if (is_negative) {
    *t-- = '-';
  }

  resstr.setSize(reslen);
  return resstr;
}",1
"static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)
{
    VirtQueueElement elem;
    VirtQueue *vq;

    vq = vser->c_ivq;
    if (!virtio_queue_ready(vq)) {
        return 0;
    }
    if (!virtqueue_pop(vq, &elem)) {
        return 0;
    }

    memcpy(elem.in_sg[0].iov_base, buf, len);

    virtqueue_push(vq, &elem, len);
    virtio_notify(VIRTIO_DEVICE(vser), vq);
    return len;
}",1
"future cql_server::connection::read_and_decompress_frame(size_t length, uint8_t flags)
{
    using namespace compression_buffers;
    if (flags & cql_frame_flags::compression) {
        if (_compression == cql_compression::lz4) {
            if (length < 4) {
                throw std::runtime_error(fmt::format(""CQL frame truncated: expected to have at least 4 bytes, got {}"", length));
            }
            return _buffer_reader.read_exactly(_read_buf, length).then([this] (fragmented_temporary_buffer buf) {
                auto linearization_buffer = bytes_ostream();
                int32_t uncomp_len = request_reader(buf.get_istream(), linearization_buffer).read_int();
                if (uncomp_len < 0) {
                    throw std::runtime_error(""CQL frame uncompressed length is negative: "" + std::to_string(uncomp_len));
                }
                buf.remove_prefix(4);
                auto in = input_buffer.get_linearized_view(fragmented_temporary_buffer::view(buf));
                auto uncomp = output_buffer.make_fragmented_temporary_buffer(uncomp_len, fragmented_temporary_buffer::default_fragment_size, [&] (bytes_mutable_view out) {
                    auto ret = LZ4_decompress_safe(reinterpret_cast(in.data()), reinterpret_cast(out.data()),
                                                   in.size(), out.size());
                    if (ret < 0) {
                        throw std::runtime_error(""CQL frame LZ4 uncompression failure"");
                    }
                    return out.size();
                });
                on_compression_buffer_use();
                return uncomp;
            });
        } else if (_compression == cql_compression::snappy) {
            return _buffer_reader.read_exactly(_read_buf, length).then([this] (fragmented_temporary_buffer buf) {
                auto in = input_buffer.get_linearized_view(fragmented_temporary_buffer::view(buf));
                size_t uncomp_len;
                if (snappy_uncompressed_length(reinterpret_cast(in.data()), in.size(), &uncomp_len) != SNAPPY_OK) {
                    throw std::runtime_error(""CQL frame Snappy uncompressed size is unknown"");
                }
                auto uncomp = output_buffer.make_fragmented_temporary_buffer(uncomp_len, fragmented_temporary_buffer::default_fragment_size, [&] (bytes_mutable_view out) {
                    size_t output_len = out.size();
                    if (snappy_uncompress(reinterpret_cast(in.data()), in.size(), reinterpret_cast(out.data()), &output_len) != SNAPPY_OK) {
                        throw std::runtime_error(""CQL frame Snappy uncompression failure"");
                    }
                    return output_len;
                });
                on_compression_buffer_use();
                return uncomp;
            });
        } else {
            throw exceptions::protocol_exception(format(""Unknown compression algorithm""));
        }
    }
    return _buffer_reader.read_exactly(_read_buf, length);
}",1
"Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,
                         TensorHandle* tensor_handle, Device** result) {
  Device* cpu_device = ctx.HostCPU();
  string device_name;
  if (tensor_handle->Type() != TensorHandle::LOCAL) {
    Device* device = tensor_handle->device();
    device_name = device != nullptr ? device->name() : cpu_device->name();
    *result = (device == nullptr ? cpu_device : device);
  } else if (tensor_handle->dtype == DT_RESOURCE) {
    // Use the resource's actual device because it is the device that will
    // influence partitioning the multi-device function.
    const Tensor* tensor;
    // TODO(fishx): Avoid blocking here.
    TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));
    const ResourceHandle& handle = tensor->flat()(0);
    device_name = handle.device();

    Device* input_device;
    TF_RETURN_IF_ERROR(
        ctx.FindDeviceFromName(device_name.c_str(), &input_device));
    *result = input_device;
  } else {
    Device* device = tensor_handle->device();
    const bool is_tpu = device != nullptr && device->device_type() == ""TPU"";
    // int32 return values can be placed on TPUs.
    const bool use_host_memory =
        is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)
               : MTypeFromDType(tensor_handle->dtype);
    if (use_host_memory) {
      *result = cpu_device;
    } else {
      // Eager ops executing as functions should have their preferred inputs set
      // to the op's device. This allows us to avoid expensive D2H copies if a
      // mirror of the tensor already exists on the op's device.
      if (!op.is_function() && device != nullptr && device != cpu_device) {
        device = absl::get(op.Device());
      }
      *result = (device == nullptr ? cpu_device : device);
    }
  }
  return Status::OK();
}",1
"static int check_assertion(struct config_module * config, json_t * j_params, const char * username, json_t * j_scheme_data, json_t * j_assertion) {
  int ret, res;
  unsigned char * client_data = NULL, * challenge_b64 = NULL, * auth_data = NULL, rpid_hash[32] = {0}, * flags, cdata_hash[32] = {0},
                  data_signed[128] = {0}, sig[128] = {0}, * counter;
  char * challenge_hash = NULL;
  const char * rpid = NULL;
  size_t client_data_len, challenge_b64_len, auth_data_len, rpid_hash_len = 32, cdata_hash_len = 32, sig_len = 128, counter_value = 0, rpid_len = 0;
  json_t * j_client_data = NULL, * j_credential = NULL, * j_query;
  gnutls_pubkey_t pubkey = NULL;
  gnutls_datum_t pubkey_dat, data, signature;

  if (j_scheme_data != NULL && j_assertion != NULL) {
    do {
      ret = G_OK;

      if (!json_is_string(json_object_get(json_object_get(j_scheme_data, ""credential""), ""rawId"")) || !json_string_length(json_object_get(json_object_get(j_scheme_data, ""credential""), ""rawId""))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - rawId missing"");
        ret = G_ERROR_PARAM;
        break;
      }
      j_credential = get_credential(config, j_params, username, json_string_value(json_object_get(json_object_get(j_scheme_data, ""credential""), ""rawId"")));
      if (check_result_value(j_credential, G_ERROR_NOT_FOUND)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - credential ID not found"");
        ret = G_ERROR_UNAUTHORIZED;
        break;
      }
      if (!json_is_string(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""clientDataJSON"")) || !json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""clientDataJSON""))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON mandatory"");
        ret = G_ERROR_PARAM;
        break;
      }
      if ((client_data = o_malloc(json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""clientDataJSON""))+1)) == NULL) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error allocating resources for client_data"");
        ret = G_ERROR_MEMORY;
        break;
      }
      if (!o_base64_decode((const unsigned char *)json_string_value(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""clientDataJSON"")), json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""clientDataJSON"")), client_data, &client_data_len)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error o_base64_decode client_data"");
        ret = G_ERROR_PARAM;
        break;
      }
      client_data[client_data_len] = '\0';
      j_client_data = json_loads((const char *)client_data, JSON_DECODE_ANY, NULL);
      if (j_client_data == NULL) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error parsing JSON client data %s"", client_data);
        ret = G_ERROR_PARAM;
        break;
      }
      // Step 7
      if (0 != o_strcmp(""webauthn.get"", json_string_value(json_object_get(j_client_data, ""type"")))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON.type invalid"");
        ret = G_ERROR_PARAM;
        break;
      }
      // Step 8
      if (!json_string_length(json_object_get(j_client_data, ""challenge""))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON.challenge mandatory"");
        ret = G_ERROR_PARAM;
        break;
      }
      if ((challenge_b64 = o_malloc(json_string_length(json_object_get(j_client_data, ""challenge""))+3)) == NULL) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""register_new_attestation - Error allocating resources for challenge_b64"");
        ret = G_ERROR_MEMORY;
        break;
      }
      if (!o_base64url_2_base64((unsigned char *)json_string_value(json_object_get(j_client_data, ""challenge"")), json_string_length(json_object_get(j_client_data, ""challenge"")), challenge_b64, &challenge_b64_len)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON.challenge invalid base64"");
        ret = G_ERROR_PARAM;
        break;
      }
      challenge_b64[challenge_b64_len] = '\0';
      if ((challenge_hash = generate_hash(config->hash_algorithm, (const char *)challenge_b64)) == NULL) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""register_new_attestation - Error generate_hash for challenge_b64"");
        ret = G_ERROR;
        break;
      }
      if (0 != o_strcmp(challenge_hash, json_string_value(json_object_get(j_assertion, ""challenge_hash"")))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON.challenge invalid"");
        ret = G_ERROR_PARAM;
        break;
      }
      // Step 9
      if (!json_string_length(json_object_get(j_client_data, ""origin""))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON.origin mandatory"");
        ret = G_ERROR_PARAM;
        break;
      }
      if (0 != o_strcmp(json_string_value(json_object_get(j_params, ""rp-origin"")), json_string_value(json_object_get(j_client_data, ""origin"")))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - clientDataJSON.origin invalid - Client send %s, required %s"", json_string_value(json_object_get(j_client_data, ""origin"")), json_string_value(json_object_get(j_params, ""rp-origin"")));
        ret = G_ERROR_PARAM;
        break;
      }
      // Step 10 ??

      // Step 11
      if (!json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""authenticatorData""))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - authenticatorData mandatory"");
        ret = G_ERROR_PARAM;
        break;
      }
      if ((auth_data = o_malloc(json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""authenticatorData""))+1)) == NULL) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error allocating resources for auth_data"");
        ret = G_ERROR_PARAM;
        break;
      }
      if (!o_base64_decode((const unsigned char *)json_string_value(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""authenticatorData"")), json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""authenticatorData"")), auth_data, &auth_data_len)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error o_base64_decode auth_data"");
        ret = G_ERROR_PARAM;
        break;
      }
      if (auth_data_len < 37) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error authenticatorData invalid"");
        ret = G_ERROR_PARAM;
        break;
      }

      if (o_strstr(json_string_value(json_object_get(j_params, ""rp-origin"")), ""://"") != NULL) {
        rpid = o_strstr(json_string_value(json_object_get(j_params, ""rp-origin"")), ""://"")+3;
      } else {
        rpid = json_string_value(json_object_get(j_params, ""rp-origin""));
      }
      if (o_strchr(rpid, ':') != NULL) {
        rpid_len = o_strchr(rpid, ':') - rpid;
      } else {
        rpid_len = o_strlen(rpid);
      }

      if (!generate_digest_raw(digest_SHA256, (unsigned char *)rpid, rpid_len, rpid_hash, &rpid_hash_len)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error generate_digest_raw for rpid_hash"");
        ret = G_ERROR_PARAM;
        break;
      }

      if (0 != memcmp(auth_data, rpid_hash, rpid_hash_len)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - authData.rpIdHash invalid"");
        ret = G_ERROR_PARAM;
        break;
      }
      flags = auth_data + FLAGS_OFFSET;

      // Step 12
      if (!(*flags & FLAG_USER_PRESENT)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - authData.userPresent not set"");
        ret = G_ERROR_PARAM;
        break;
      }

      // Step 13 ignored for now
      //y_log_message(Y_LOG_LEVEL_DEBUG, ""authData.userVerified: %d"", !!(*flags & FLAG_USER_VERIFY));

      // Step 14 ignored for now (no extension)
      //y_log_message(Y_LOG_LEVEL_DEBUG, ""authData.Extension: %d"", !!(*flags & FLAG_ED));

      // Step 15
      if (!generate_digest_raw(digest_SHA256, client_data, client_data_len, cdata_hash, &cdata_hash_len)) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error generate_digest_raw for cdata_hash"");
        ret = G_ERROR_PARAM;
        break;
      }
      counter = auth_data + COUNTER_OFFSET;
      counter_value = counter[3] | (counter[2] << 8) | (counter[1] << 16) | (counter[0] << 24);

      if (gnutls_pubkey_init(&pubkey) < 0) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error gnutls_pubkey_init"");
        ret = G_ERROR;
        break;
      }
      pubkey_dat.data = (unsigned char *)json_string_value(json_object_get(json_object_get(j_credential, ""credential""), ""public_key""));
      pubkey_dat.size = json_string_length(json_object_get(json_object_get(j_credential, ""credential""), ""public_key""));
      if ((ret = gnutls_pubkey_import(pubkey, &pubkey_dat, GNUTLS_X509_FMT_PEM)) < 0) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error gnutls_pubkey_import: %d"", ret);
        ret = G_ERROR;
        break;
      }

      if (!o_base64url_decode((const unsigned char *)json_string_value(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""signature"")), json_string_length(json_object_get(json_object_get(json_object_get(j_scheme_data, ""credential""), ""response""), ""signature"")), sig, &sig_len)) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Error o_base64url_decode signature"");
        ret = G_ERROR_PARAM;
        break;
      }

      memcpy(data_signed, auth_data, auth_data_len);
      memcpy(data_signed+auth_data_len, cdata_hash, cdata_hash_len);

      // Let's verify sig over data_signed
      data.data = data_signed;
      data.size = (auth_data_len+cdata_hash_len);

      signature.data = sig;
      signature.size = sig_len;

      if ((res = gnutls_pubkey_verify_data2(pubkey, GNUTLS_SIGN_ECDSA_SHA256, 0, &data, &signature)) < 0) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - Invalid signature: %d"", res);
        ret = G_ERROR_UNAUTHORIZED;
        break;
      }

      if ((json_integer_value(json_object_get(json_object_get(j_credential, ""credential""), ""counter"")) || counter_value) && counter_value <= (size_t)json_integer_value(json_object_get(json_object_get(j_credential, ""credential""), ""counter""))) {
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_assertion - counter invalid"");
        ret = G_ERROR_UNAUTHORIZED;
        break;
      }
    } while (0); // This is not a loop, but a structure where you can easily cancel the rest of the process with breaks

    if (ret == G_OK) {
      // Update assertion
      j_query = json_pack(""{sss{sisi}s{sO}}"",
                          ""table"",
                          G_TABLE_WEBAUTHN_ASSERTION,
                          ""set"",
                            ""gswa_counter"",
                            counter_value,
                            ""gswa_status"",
                            1,
                          ""where"",
                            ""gswa_id"",
                            json_object_get(j_assertion, ""gswa_id""));
      res = h_update(config->conn, j_query, NULL);
      json_decref(j_query);
      if (res != H_OK) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error executing j_query (1)"");
        config->glewlwyd_module_callback_metrics_increment_counter(config, GLWD_METRICS_DATABSE_ERROR, 1, NULL);
        ret = G_ERROR_DB;
      } else {
        // Update counter in credential if necessary
        if (counter) {
          j_query = json_pack(""{sss{si}s{sO}}"",
                              ""table"",
                              G_TABLE_WEBAUTHN_CREDENTIAL,
                              ""set"",
                                ""gswc_counter"",
                                counter_value,
                              ""where"",
                                ""gswc_id"",
                                json_object_get(json_object_get(j_credential, ""credential""), ""gswc_id""));
          res = h_update(config->conn, j_query, NULL);
          json_decref(j_query);
          if (res != H_OK) {
            y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error executing j_query (2)"");
            config->glewlwyd_module_callback_metrics_increment_counter(config, GLWD_METRICS_DATABSE_ERROR, 1, NULL);
            ret = G_ERROR_DB;
          }
        }
      }
    } else if (ret == G_ERROR_PARAM) {
      j_query = json_pack(""{sss{sisi}s{sO}}"",
                          ""table"",
                          G_TABLE_WEBAUTHN_ASSERTION,
                          ""set"",
                            ""gswa_counter"",
                            counter_value,
                            ""gswa_status"",
                            2,
                          ""where"",
                            ""gswa_id"",
                            json_object_get(j_assertion, ""gswa_id""));
      res = h_update(config->conn, j_query, NULL);
      json_decref(j_query);
      if (res != H_OK) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error executing j_query (3)"");
        config->glewlwyd_module_callback_metrics_increment_counter(config, GLWD_METRICS_DATABSE_ERROR, 1, NULL);
        ret = G_ERROR_DB;
      }
    } else {
      j_query = json_pack(""{sss{sisi}s{sO}}"",
                          ""table"",
                          G_TABLE_WEBAUTHN_ASSERTION,
                          ""set"",
                            ""gswa_counter"",
                            counter_value,
                            ""gswa_status"",
                            3,
                          ""where"",
                            ""gswa_id"",
                            json_object_get(j_assertion, ""gswa_id""));
      res = h_update(config->conn, j_query, NULL);
      json_decref(j_query);
      if (res != H_OK) {
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_assertion - Error executing j_query (4)"");
        config->glewlwyd_module_callback_metrics_increment_counter(config, GLWD_METRICS_DATABSE_ERROR, 1, NULL);
        ret = G_ERROR_DB;
      }
    }
    o_free(client_data);
    o_free(challenge_b64);
    o_free(challenge_hash);
    o_free(auth_data);
    json_decref(j_client_data);
    json_decref(j_credential);
    gnutls_pubkey_deinit(pubkey);
  } else {
    ret = G_ERROR_PARAM;
  }
  return ret;
}",1
"njs_array_prototype_splice(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
    njs_index_t unused)
{
    int64_t      i, n, start, length, items, delta, delete;
    njs_int_t    ret;
    njs_value_t  *this, value, del_object;
    njs_array_t  *array, *deleted;

    this = njs_argument(args, 0);

    ret = njs_value_to_object(vm, this);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    ret = njs_object_length(vm, this, &length);
    if (njs_slow_path(ret == NJS_ERROR)) {
        return ret;
    }

    ret = njs_value_to_integer(vm, njs_arg(args, nargs, 1), &start);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    start = (start < 0) ? njs_max(length + start, 0) : njs_min(start, length);

    items = 0;
    delete = 0;

    if (nargs == 2) {
        delete = length - start;

    } else if (nargs > 2) {
        items = nargs - 3;

        ret = njs_value_to_integer(vm, njs_arg(args, nargs, 2), &delete);
        if (njs_slow_path(ret != NJS_OK)) {
            return ret;
        }

        delete = njs_min(njs_max(delete, 0), length - start);
    }

    delta = items - delete;

    if (njs_slow_path((length + delta) > NJS_MAX_LENGTH)) {
        njs_type_error(vm, ""Invalid length"");
        return NJS_ERROR;
    }

    /* TODO: ArraySpeciesCreate(). */

    deleted = njs_array_alloc(vm, 0, delete, 0);
    if (njs_slow_path(deleted == NULL)) {
        return NJS_ERROR;
    }

    if (njs_fast_path(njs_is_fast_array(this) && deleted->object.fast_array)) {
        array = njs_array(this);
        for (i = 0, n = start; i < delete; i++, n++) {
            deleted->start[i] = array->start[n];
        }

    } else {
        njs_set_array(&del_object, deleted);

        for (i = 0, n = start; i < delete; i++, n++) {
            ret = njs_value_property_i64(vm, this, n, &value);
            if (njs_slow_path(ret == NJS_ERROR)) {
                return NJS_ERROR;
            }

            if (ret == NJS_OK) {
                /* TODO:  CreateDataPropertyOrThrow(). */
                ret = njs_value_property_i64_set(vm, &del_object, i, &value);
                if (njs_slow_path(ret == NJS_ERROR)) {
                    return ret;
                }
            }
        }

        ret = njs_object_length_set(vm, &del_object, delete);
        if (njs_slow_path(ret != NJS_OK)) {
            return NJS_ERROR;
        }
    }

    if (njs_fast_path(njs_is_fast_array(this))) {
        array = njs_array(this);

        if (delta != 0) {
            /*
             * Relocate the rest of items.
             * Index of the first item is in ""n"".
             */
            if (delta > 0) {
                ret = njs_array_expand(vm, array, 0, delta);
                if (njs_slow_path(ret != NJS_OK)) {
                    return ret;
                }
            }

            ret = njs_array_copy_within(vm, this, start + items, start + delete,
                                        array->length - (start + delete), 0);
            if (njs_slow_path(ret != NJS_OK)) {
                return ret;
            }

            array->length += delta;
        }

        /* Copy new items. */

        if (items > 0) {
            memcpy(&array->start[start], &args[3],
                   items * sizeof(njs_value_t));
        }

    } else {

       if (delta != 0) {
           ret = njs_array_copy_within(vm, this, start + items, start + delete,
                                       length - (start + delete), delta < 0);
            if (njs_slow_path(ret != NJS_OK)) {
                return ret;
            }

            for (i = length - 1; i >= length + delta; i--) {
                ret = njs_value_property_i64_delete(vm, this, i, NULL);
                if (njs_slow_path(ret == NJS_ERROR)) {
                    return NJS_ERROR;
                }
            }
       }

        /* Copy new items. */

        for (i = 3, n = start; items-- > 0; i++, n++) {
            ret = njs_value_property_i64_set(vm, this, n, &args[i]);
            if (njs_slow_path(ret == NJS_ERROR)) {
                return NJS_ERROR;
            }
        }

        ret = njs_object_length_set(vm, this, length + delta);
        if (njs_slow_path(ret != NJS_OK)) {
            return NJS_ERROR;
        }
    }

    njs_set_array(&vm->retval, deleted);

    return NJS_OK;
}",1
"gen_values(codegen_scope *s, node *t, int val, int limit)
{
  int n = 0;
  int first = 1;
  int slimit = GEN_VAL_STACK_MAX;

  if (limit == 0) limit = GEN_LIT_ARY_MAX;
  if (cursp() >= slimit) slimit = INT16_MAX;

  if (!val) {
    while (t) {
      codegen(s, t->car, NOVAL);
      n++;
      t = t->cdr;
    }
    return n;
  }

  while (t) {
    int is_splat = nint(t->car->car) == NODE_SPLAT;

    if (is_splat || n > limit || cursp() >= slimit) { /* flush stack */
      pop_n(n);
      if (first) {
        if (n == 0) {
          genop_1(s, OP_LOADNIL, cursp());
        }
        else {
          genop_2(s, OP_ARRAY, cursp(), n);
        }
        push();
        first = 0;
        limit = GEN_LIT_ARY_MAX;
      }
      else if (n > 0) {
        pop();
        genop_2(s, OP_ARYPUSH, cursp(), n);
        push();
      }
      n = 0;
    }
    codegen(s, t->car, val);
    if (is_splat) {
      pop(); pop();
      genop_1(s, OP_ARYCAT, cursp());
      push();
    }
    else {
      n++;
    }
    t = t->cdr;
  }
  if (!first) {
    pop();
    if (n > 0) {
      pop_n(n);
      genop_2(s, OP_ARYPUSH, cursp(), n);
    }
    return -1;                  /* variable length */
  }
  return n;
}",1
"static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner)
{
    pj_xml_node *node;
    pj_str_t end_name;

    PJ_CHECK_STACK();

    if (*scanner->curptr != '<')
	on_syntax_error(scanner);

    /* Handle Processing Instructino (PI) construct (i.e. ""curptr == '<' && *(scanner->curptr+1) == '?') {
	pj_scan_advance_n(scanner, 2, PJ_FALSE);
	for (;;) {
	    pj_str_t dummy;
	    pj_scan_get_until_ch(scanner, '?', &dummy);
	    if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') {
		pj_scan_advance_n(scanner, 2, PJ_TRUE);
		break;
	    } else {
		pj_scan_advance_n(scanner, 1, PJ_FALSE);
	    }
	}
	return xml_parse_node(pool, scanner);
    }

    /* Handle comments construct (i.e. ""', &dummy);
	    if (pj_scan_strcmp(scanner, "">"", 1) == 0) {
		pj_scan_advance_n(scanner, 1, PJ_TRUE);
		break;
	    } else {
		pj_scan_advance_n(scanner, 1, PJ_FALSE);
	    }
	}
	return xml_parse_node(pool, scanner);
    }

    /* Alloc node. */
    node = alloc_node(pool);

    /* Get '<' */
    pj_scan_get_char(scanner);

    /* Get node name. */
    pj_scan_get_until_chr( scanner, "" />\t\r\n"", &node->name);

    /* Get attributes. */
    while (*scanner->curptr != '>' && *scanner->curptr != '/') {
	pj_xml_attr *attr = alloc_attr(pool);
	
	pj_scan_get_until_chr( scanner, ""=> \t\r\n"", &attr->name);
	if (*scanner->curptr == '=') {
	    pj_scan_get_char( scanner );
            pj_scan_get_quotes(scanner, ""\""'"", ""\""'"", 2, &attr->value);
	    /* remove quote characters */
	    ++attr->value.ptr;
	    attr->value.slen -= 2;
	}
	
	pj_list_push_back( &node->attr_head, attr );
    }

    if (*scanner->curptr == '/') {
	pj_scan_get_char(scanner);
	if (pj_scan_get_char(scanner) != '>')
	    on_syntax_error(scanner);
	return node;
    }

    /* Enclosing bracket. */
    if (pj_scan_get_char(scanner) != '>')
	on_syntax_error(scanner);

    /* Sub nodes. */
    while (*scanner->curptr == '<' && *(scanner->curptr+1) != '/'
				   && *(scanner->curptr+1) != '!')
    {
	pj_xml_node *sub_node = xml_parse_node(pool, scanner);
	pj_list_push_back( &node->node_head, sub_node );
    }

    /* Content. */
    if (!pj_scan_is_eof(scanner) && *scanner->curptr != '<') {
	pj_scan_get_until_ch(scanner, '<', &node->content);
    }

    /* CDATA content. */
    if (*scanner->curptr == '<' && *(scanner->curptr+1) == '!' &&
	pj_scan_strcmp(scanner, ""content);
	while (pj_scan_strcmp(scanner, ""]]>"", 3)) {
	    pj_str_t dummy;
	    pj_scan_get_until_ch(scanner, ']', &dummy);
	}
	node->content.slen = scanner->curptr - node->content.ptr;
	pj_scan_advance_n(scanner, 3, PJ_TRUE);
    }

    /* Enclosing node. */
    if (pj_scan_get_char(scanner) != '<' || pj_scan_get_char(scanner) != '/')
	on_syntax_error(scanner);

    pj_scan_get_until_chr(scanner, "" \t>"", &end_name);

    /* Compare name. */
    if (pj_stricmp(&node->name, &end_name) != 0)
	on_syntax_error(scanner);

    /* Enclosing '>' */
    if (pj_scan_get_char(scanner) != '>')
	on_syntax_error(scanner);

    return node;
}",1
"ns_input(void)
{
  uint8_t flags = 0;

  LOG_INFO(""Received NS from "");
  LOG_INFO_6ADDR(&UIP_IP_BUF->srcipaddr);
  LOG_INFO_("" to "");
  LOG_INFO_6ADDR(&UIP_IP_BUF->destipaddr);
  LOG_INFO_("" with target address "");
  LOG_INFO_6ADDR((uip_ipaddr_t *) (&UIP_ND6_NS_BUF->tgtipaddr));
  LOG_INFO_(""\n"");
  UIP_STAT(++uip_stat.nd6.recv);

#if UIP_CONF_IPV6_CHECKS
  if((UIP_IP_BUF->ttl != UIP_ND6_HOP_LIMIT) ||
     (uip_is_addr_mcast(&UIP_ND6_NS_BUF->tgtipaddr)) ||
     (UIP_ICMP_BUF->icode != 0)) {
    LOG_ERR(""NS received is bad\n"");
    goto discard;
  }
#endif /* UIP_CONF_IPV6_CHECKS */

  /* Options processing */
  nd6_opt_llao = NULL;
  nd6_opt_offset = UIP_ND6_NS_LEN;
  while(uip_l3_icmp_hdr_len + nd6_opt_offset < uip_len) {
#if UIP_CONF_IPV6_CHECKS
    if(ND6_OPT_HDR_BUF(nd6_opt_offset)->len == 0) {
      LOG_ERR(""NS received is bad\n"");
      goto discard;
    }
#endif /* UIP_CONF_IPV6_CHECKS */
    switch (ND6_OPT_HDR_BUF(nd6_opt_offset)->type) {
    case UIP_ND6_OPT_SLLAO:
      nd6_opt_llao = &uip_buf[uip_l3_icmp_hdr_len + nd6_opt_offset];
#if UIP_CONF_IPV6_CHECKS
      /* There must be NO option in a DAD NS */
      if(uip_is_addr_unspecified(&UIP_IP_BUF->srcipaddr)) {
        LOG_ERR(""NS received is bad\n"");
        goto discard;
      } else {
#endif /*UIP_CONF_IPV6_CHECKS */
        uip_lladdr_t lladdr_aligned;
        extract_lladdr_from_llao_aligned(&lladdr_aligned);
        nbr = uip_ds6_nbr_lookup(&UIP_IP_BUF->srcipaddr);
        if(nbr == NULL) {
          uip_ds6_nbr_add(&UIP_IP_BUF->srcipaddr, &lladdr_aligned,
			  0, NBR_STALE, NBR_TABLE_REASON_IPV6_ND, NULL);
        } else {
          const uip_lladdr_t *lladdr = uip_ds6_nbr_get_ll(nbr);
          if(lladdr == NULL) {
            goto discard;
          }
          if(memcmp(&nd6_opt_llao[UIP_ND6_OPT_DATA_OFFSET],
              lladdr, UIP_LLADDR_LEN) != 0) {
            if(uip_ds6_nbr_update_ll(&nbr,
                                     (const uip_lladdr_t *)&lladdr_aligned)
               < 0) {
              /* failed to update the lladdr */
              goto discard;
            }
            nbr->state = NBR_STALE;
          } else {
            if(nbr->state == NBR_INCOMPLETE) {
              nbr->state = NBR_STALE;
            }
          }
        }
#if UIP_CONF_IPV6_CHECKS
      }
#endif /*UIP_CONF_IPV6_CHECKS */
      break;
    default:
      LOG_WARN(""ND option not supported in NS"");
      break;
    }
    nd6_opt_offset += (ND6_OPT_HDR_BUF(nd6_opt_offset)->len << 3);
  }

  addr = uip_ds6_addr_lookup(&UIP_ND6_NS_BUF->tgtipaddr);
  if(addr != NULL) {
    if(uip_is_addr_unspecified(&UIP_IP_BUF->srcipaddr)) {
      /* DAD CASE */
#if UIP_ND6_DEF_MAXDADNS > 0
#if UIP_CONF_IPV6_CHECKS
      if(!uip_is_addr_solicited_node(&UIP_IP_BUF->destipaddr)) {
        LOG_ERR(""NS received is bad\n"");
        goto discard;
      }
#endif /* UIP_CONF_IPV6_CHECKS */
      if(addr->state != ADDR_TENTATIVE) {
        uip_create_linklocal_allnodes_mcast(&UIP_IP_BUF->destipaddr);
        uip_ds6_select_src(&UIP_IP_BUF->srcipaddr, &UIP_IP_BUF->destipaddr);
        flags = UIP_ND6_NA_FLAG_OVERRIDE;
        goto create_na;
      } else {
          /** \todo if I sent a NS before him, I win */
        uip_ds6_dad_failed(addr);
        goto discard;
      }
#else /* UIP_ND6_DEF_MAXDADNS > 0 */
      goto discard;  /* DAD CASE */
#endif /* UIP_ND6_DEF_MAXDADNS > 0 */
    }
#if UIP_CONF_IPV6_CHECKS
    if(uip_ds6_is_my_addr(&UIP_IP_BUF->srcipaddr)) {
        /**
         * \NOTE do we do something here? we both are using the same address.
         * If we are doing dad, we could cancel it, though we should receive a
         * NA in response of DAD NS we sent, hence DAD will fail anyway. If we
         * were not doing DAD, it means there is a duplicate in the network!
         */
      LOG_ERR(""NS received is bad\n"");
      goto discard;
    }
#endif /*UIP_CONF_IPV6_CHECKS */

    /* Address resolution case */
    if(uip_is_addr_solicited_node(&UIP_IP_BUF->destipaddr)) {
      uip_ipaddr_copy(&UIP_IP_BUF->destipaddr, &UIP_IP_BUF->srcipaddr);
      uip_ipaddr_copy(&UIP_IP_BUF->srcipaddr, &UIP_ND6_NS_BUF->tgtipaddr);
      flags = UIP_ND6_NA_FLAG_SOLICITED | UIP_ND6_NA_FLAG_OVERRIDE;
      goto create_na;
    }

    /* NUD CASE */
    if(uip_ds6_addr_lookup(&UIP_IP_BUF->destipaddr) == addr) {
      uip_ipaddr_copy(&UIP_IP_BUF->destipaddr, &UIP_IP_BUF->srcipaddr);
      uip_ipaddr_copy(&UIP_IP_BUF->srcipaddr, &UIP_ND6_NS_BUF->tgtipaddr);
      flags = UIP_ND6_NA_FLAG_SOLICITED | UIP_ND6_NA_FLAG_OVERRIDE;
      goto create_na;
    } else {
#if UIP_CONF_IPV6_CHECKS
      LOG_ERR(""NS received is bad\n"");
      goto discard;
#endif /* UIP_CONF_IPV6_CHECKS */
    }
  } else {
    goto discard;
  }


create_na:
    /* If the node is a router it should set R flag in NAs */
#if UIP_CONF_ROUTER
    flags = flags | UIP_ND6_NA_FLAG_ROUTER;
#endif
  uipbuf_clear();
  UIP_IP_BUF->vtc = 0x60;
  UIP_IP_BUF->tcflow = 0;
  UIP_IP_BUF->flow = 0;
  uipbuf_set_len_field(UIP_IP_BUF, UIP_ICMPH_LEN + UIP_ND6_NA_LEN + UIP_ND6_OPT_LLAO_LEN);
  UIP_IP_BUF->proto = UIP_PROTO_ICMP6;
  UIP_IP_BUF->ttl = UIP_ND6_HOP_LIMIT;

  UIP_ICMP_BUF->type = ICMP6_NA;
  UIP_ICMP_BUF->icode = 0;

  UIP_ND6_NA_BUF->flagsreserved = flags;
  memcpy(&UIP_ND6_NA_BUF->tgtipaddr, &addr->ipaddr, sizeof(uip_ipaddr_t));

  create_llao(&uip_buf[uip_l3_icmp_hdr_len + UIP_ND6_NA_LEN],
              UIP_ND6_OPT_TLLAO);

  UIP_ICMP_BUF->icmpchksum = 0;
  UIP_ICMP_BUF->icmpchksum = ~uip_icmp6chksum();

  uipbuf_set_len(UIP_IPH_LEN + UIP_ICMPH_LEN + UIP_ND6_NA_LEN + UIP_ND6_OPT_LLAO_LEN);

  UIP_STAT(++uip_stat.nd6.sent);
  LOG_INFO(""Sending NA to "");
  LOG_INFO_6ADDR(&UIP_IP_BUF->destipaddr);
  LOG_INFO_("" from "");
  LOG_INFO_6ADDR(&UIP_IP_BUF->srcipaddr);
  LOG_INFO_("" with target address "");
  LOG_INFO_6ADDR(&UIP_ND6_NA_BUF->tgtipaddr);
  LOG_INFO_(""\n"");
  return;

discard:
  uipbuf_clear();
  return;
}",1
"void generate_inter_prediction_samples(base_context* ctx,
                                       const slice_segment_header* shdr,
                                       de265_image* img,
                                       int xC,int yC,
                                       int xB,int yB,
                                       int nCS, int nPbW,int nPbH,
                                       const PBMotion* vi)
{
  int xP = xC+xB;
  int yP = yC+yB;

  void*  pixels[3];
  int    stride[3];

  const pic_parameter_set* pps = shdr->pps.get();
  const seq_parameter_set* sps = pps->sps.get();

  const int SubWidthC  = sps->SubWidthC;
  const int SubHeightC = sps->SubHeightC;

  pixels[0] = img->get_image_plane_at_pos_any_depth(0,xP,yP);
  stride[0] = img->get_image_stride(0);

  pixels[1] = img->get_image_plane_at_pos_any_depth(1,xP/SubWidthC,yP/SubHeightC);
  stride[1] = img->get_image_stride(1);

  pixels[2] = img->get_image_plane_at_pos_any_depth(2,xP/SubWidthC,yP/SubHeightC);
  stride[2] = img->get_image_stride(2);


  ALIGNED_16(int16_t) predSamplesL                 [2 /* LX */][MAX_CU_SIZE* MAX_CU_SIZE];
  ALIGNED_16(int16_t) predSamplesC[2 /* chroma */ ][2 /* LX */][MAX_CU_SIZE* MAX_CU_SIZE];

  //int xP = xC+xB;
  //int yP = yC+yB;

  int predFlag[2];
  predFlag[0] = vi->predFlag[0];
  predFlag[1] = vi->predFlag[1];

  const int bit_depth_L = sps->BitDepth_Y;
  const int bit_depth_C = sps->BitDepth_C;

  // Some encoders use bi-prediction with two similar MVs.
  // Identify this case and use only one MV.

  // do this only without weighted prediction, because the weights/offsets may be different
  if (pps->weighted_pred_flag==0) {
    if (predFlag[0] && predFlag[1]) {
      if (vi->mv[0].x == vi->mv[1].x &&
          vi->mv[0].y == vi->mv[1].y &&
          shdr->RefPicList[0][vi->refIdx[0]] ==
          shdr->RefPicList[1][vi->refIdx[1]]) {
        predFlag[1] = 0;
      }
    }
  }


  for (int l=0;l<2;l++) {
    if (predFlag[l]) {
      // 8.5.3.2.1

      if (vi->refIdx[l] >= MAX_NUM_REF_PICS) {
        img->integrity = INTEGRITY_DECODING_ERRORS;
        ctx->add_warning(DE265_WARNING_NONEXISTING_REFERENCE_PICTURE_ACCESSED, false);
        return;
      }

      const de265_image* refPic = ctx->get_image(shdr->RefPicList[l][vi->refIdx[l]]);

      logtrace(LogMotion, ""refIdx: %d -> dpb[%d]\n"", vi->refIdx[l], shdr->RefPicList[l][vi->refIdx[l]]);

      if (!refPic || refPic->PicState == UnusedForReference) {
        img->integrity = INTEGRITY_DECODING_ERRORS;
        ctx->add_warning(DE265_WARNING_NONEXISTING_REFERENCE_PICTURE_ACCESSED, false);

        // TODO: fill predSamplesC with black or grey
      }
      else {
        // 8.5.3.2.2

        logtrace(LogMotion,""do MC: L%d,MV=%d;%d RefPOC=%d\n"",
                 l,vi->mv[l].x,vi->mv[l].y,refPic->PicOrderCntVal);


        // TODO: must predSamples stride really be nCS or can it be somthing smaller like nPbW?

        if (img->high_bit_depth(0)) {
          mc_luma(ctx, sps, vi->mv[l].x, vi->mv[l].y, xP,yP,
                  predSamplesL[l],nCS,
                  (const uint16_t*)refPic->get_image_plane(0),
                  refPic->get_luma_stride(), nPbW,nPbH, bit_depth_L);
        }
        else {
          mc_luma(ctx, sps, vi->mv[l].x, vi->mv[l].y, xP,yP,
                  predSamplesL[l],nCS,
                  (const uint8_t*)refPic->get_image_plane(0),
                  refPic->get_luma_stride(), nPbW,nPbH, bit_depth_L);
        }

        if (img->high_bit_depth(0)) {
          mc_chroma(ctx, sps, vi->mv[l].x, vi->mv[l].y, xP,yP,
                    predSamplesC[0][l],nCS, (const uint16_t*)refPic->get_image_plane(1),
                    refPic->get_chroma_stride(), nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
          mc_chroma(ctx, sps, vi->mv[l].x, vi->mv[l].y, xP,yP,
                    predSamplesC[1][l],nCS, (const uint16_t*)refPic->get_image_plane(2),
                    refPic->get_chroma_stride(), nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
        }
        else {
          mc_chroma(ctx, sps, vi->mv[l].x, vi->mv[l].y, xP,yP,
                    predSamplesC[0][l],nCS, (const uint8_t*)refPic->get_image_plane(1),
                    refPic->get_chroma_stride(), nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
          mc_chroma(ctx, sps, vi->mv[l].x, vi->mv[l].y, xP,yP,
                    predSamplesC[1][l],nCS, (const uint8_t*)refPic->get_image_plane(2),
                    refPic->get_chroma_stride(), nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
        }
      }
    }
  }


  // weighted sample prediction  (8.5.3.2.3)

  const int shift1_L = libde265_max(2,14-sps->BitDepth_Y);
  const int offset_shift1_L = img->get_sps().WpOffsetBdShiftY;
  const int shift1_C = libde265_max(2,14-sps->BitDepth_C);
  const int offset_shift1_C = img->get_sps().WpOffsetBdShiftC;

  /*
  const int shift1_L = 14-img->sps.BitDepth_Y;
  const int offset_shift1_L = img->sps.BitDepth_Y-8;
  const int shift1_C = 14-img->sps.BitDepth_C;
  const int offset_shift1_C = img->sps.BitDepth_C-8;
  */

  /*
  if (0)
  printf(""%d/%d %d/%d %d/%d %d/%d\n"",
         shift1_L,
         Nshift1_L,
         offset_shift1_L,
         Noffset_shift1_L,
         shift1_C,
         Nshift1_C,
         offset_shift1_C,
         Noffset_shift1_C);

  assert(shift1_L==
         Nshift1_L);
  assert(offset_shift1_L==
         Noffset_shift1_L);
  assert(shift1_C==
         Nshift1_C);
  assert(offset_shift1_C==
         Noffset_shift1_C);
  */


  logtrace(LogMotion,""predFlags (modified): %d %d\n"", predFlag[0], predFlag[1]);

  if (shdr->slice_type == SLICE_TYPE_P) {
    if (pps->weighted_pred_flag==0) {
      if (predFlag[0]==1 && predFlag[1]==0) {
        ctx->acceleration.put_unweighted_pred(pixels[0], stride[0],
                                              predSamplesL[0],nCS, nPbW,nPbH, bit_depth_L);
        ctx->acceleration.put_unweighted_pred(pixels[1], stride[1],
                                              predSamplesC[0][0],nCS,
                                              nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
        ctx->acceleration.put_unweighted_pred(pixels[2], stride[2],
                                              predSamplesC[1][0],nCS,
                                              nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
      }
      else {
        ctx->add_warning(DE265_WARNING_BOTH_PREDFLAGS_ZERO, false);
        img->integrity = INTEGRITY_DECODING_ERRORS;
      }
    }
    else {
      // weighted prediction

      if (predFlag[0]==1 && predFlag[1]==0) {

        int refIdx0 = vi->refIdx[0];

        int luma_log2WD   = shdr->luma_log2_weight_denom + shift1_L;
        int chroma_log2WD = shdr->ChromaLog2WeightDenom  + shift1_C;

        int luma_w0 = shdr->LumaWeight[0][refIdx0];
        int luma_o0 = shdr->luma_offset[0][refIdx0] * (1<<(offset_shift1_L));

        int chroma0_w0 = shdr->ChromaWeight[0][refIdx0][0];
        int chroma0_o0 = shdr->ChromaOffset[0][refIdx0][0] * (1<<(offset_shift1_C));
        int chroma1_w0 = shdr->ChromaWeight[0][refIdx0][1];
        int chroma1_o0 = shdr->ChromaOffset[0][refIdx0][1] * (1<<(offset_shift1_C));

        logtrace(LogMotion,""weighted-0 [%d] %d %d %d  %dx%d\n"", refIdx0, luma_log2WD-6,luma_w0,luma_o0,nPbW,nPbH);

        ctx->acceleration.put_weighted_pred(pixels[0], stride[0],
                                            predSamplesL[0],nCS, nPbW,nPbH,
                                            luma_w0, luma_o0, luma_log2WD, bit_depth_L);
        ctx->acceleration.put_weighted_pred(pixels[1], stride[1],
                                            predSamplesC[0][0],nCS, nPbW/SubWidthC,nPbH/SubHeightC,
                                            chroma0_w0, chroma0_o0, chroma_log2WD, bit_depth_C);
        ctx->acceleration.put_weighted_pred(pixels[2], stride[2],
                                            predSamplesC[1][0],nCS, nPbW/SubWidthC,nPbH/SubHeightC,
                                            chroma1_w0, chroma1_o0, chroma_log2WD, bit_depth_C);
      }
      else {
        ctx->add_warning(DE265_WARNING_BOTH_PREDFLAGS_ZERO, false);
        img->integrity = INTEGRITY_DECODING_ERRORS;
      }
    }
  }
  else {
    assert(shdr->slice_type == SLICE_TYPE_B);

    if (predFlag[0]==1 && predFlag[1]==1) {
      if (pps->weighted_bipred_flag==0) {
        //const int shift2  = 15-8; // TODO: real bit depth
        //const int offset2 = 1<<(shift2-1);

        int16_t* in0 = predSamplesL[0];
        int16_t* in1 = predSamplesL[1];

        ctx->acceleration.put_weighted_pred_avg(pixels[0], stride[0],
                                                in0,in1, nCS, nPbW, nPbH, bit_depth_L);

        int16_t* in00 = predSamplesC[0][0];
        int16_t* in01 = predSamplesC[0][1];
        int16_t* in10 = predSamplesC[1][0];
        int16_t* in11 = predSamplesC[1][1];

        ctx->acceleration.put_weighted_pred_avg(pixels[1], stride[1],
                                                in00,in01, nCS,
                                                nPbW/SubWidthC, nPbH/SubHeightC, bit_depth_C);
        ctx->acceleration.put_weighted_pred_avg(pixels[2], stride[2],
                                                in10,in11, nCS,
                                                nPbW/SubWidthC, nPbH/SubHeightC, bit_depth_C);
      }
      else {
        // weighted prediction

        int refIdx0 = vi->refIdx[0];
        int refIdx1 = vi->refIdx[1];

        int luma_log2WD   = shdr->luma_log2_weight_denom + shift1_L;
        int chroma_log2WD = shdr->ChromaLog2WeightDenom + shift1_C;

        int luma_w0 = shdr->LumaWeight[0][refIdx0];
        int luma_o0 = shdr->luma_offset[0][refIdx0] * (1<<(offset_shift1_L));
        int luma_w1 = shdr->LumaWeight[1][refIdx1];
        int luma_o1 = shdr->luma_offset[1][refIdx1] * (1<<(offset_shift1_L));

        int chroma0_w0 = shdr->ChromaWeight[0][refIdx0][0];
        int chroma0_o0 = shdr->ChromaOffset[0][refIdx0][0] * (1<<(offset_shift1_C));
        int chroma1_w0 = shdr->ChromaWeight[0][refIdx0][1];
        int chroma1_o0 = shdr->ChromaOffset[0][refIdx0][1] * (1<<(offset_shift1_C));
        int chroma0_w1 = shdr->ChromaWeight[1][refIdx1][0];
        int chroma0_o1 = shdr->ChromaOffset[1][refIdx1][0] * (1<<(offset_shift1_C));
        int chroma1_w1 = shdr->ChromaWeight[1][refIdx1][1];
        int chroma1_o1 = shdr->ChromaOffset[1][refIdx1][1] * (1<<(offset_shift1_C));

        logtrace(LogMotion,""weighted-BI-0 [%d] %d %d %d  %dx%d\n"", refIdx0, luma_log2WD-6,luma_w0,luma_o0,nPbW,nPbH);
        logtrace(LogMotion,""weighted-BI-1 [%d] %d %d %d  %dx%d\n"", refIdx1, luma_log2WD-6,luma_w1,luma_o1,nPbW,nPbH);

        int16_t* in0 = predSamplesL[0];
        int16_t* in1 = predSamplesL[1];

        ctx->acceleration.put_weighted_bipred(pixels[0], stride[0],
                                              in0,in1, nCS, nPbW, nPbH,
                                              luma_w0,luma_o0,
                                              luma_w1,luma_o1,
                                              luma_log2WD, bit_depth_L);

        int16_t* in00 = predSamplesC[0][0];
        int16_t* in01 = predSamplesC[0][1];
        int16_t* in10 = predSamplesC[1][0];
        int16_t* in11 = predSamplesC[1][1];

        ctx->acceleration.put_weighted_bipred(pixels[1], stride[1],
                                              in00,in01, nCS, nPbW/SubWidthC, nPbH/SubHeightC,
                                              chroma0_w0,chroma0_o0,
                                              chroma0_w1,chroma0_o1,
                                              chroma_log2WD, bit_depth_C);
        ctx->acceleration.put_weighted_bipred(pixels[2], stride[2],
                                              in10,in11, nCS, nPbW/SubWidthC, nPbH/SubHeightC,
                                              chroma1_w0,chroma1_o0,
                                              chroma1_w1,chroma1_o1,
                                              chroma_log2WD, bit_depth_C);
      }
    }
    else if (predFlag[0]==1 || predFlag[1]==1) {
      int l = predFlag[0] ? 0 : 1;

      if (pps->weighted_bipred_flag==0) {
        ctx->acceleration.put_unweighted_pred(pixels[0], stride[0],
                                              predSamplesL[l],nCS, nPbW,nPbH, bit_depth_L);
        ctx->acceleration.put_unweighted_pred(pixels[1], stride[1],
                                              predSamplesC[0][l],nCS,
                                              nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
        ctx->acceleration.put_unweighted_pred(pixels[2], stride[2],
                                              predSamplesC[1][l],nCS,
                                              nPbW/SubWidthC,nPbH/SubHeightC, bit_depth_C);
      }
      else {
        int refIdx = vi->refIdx[l];

        int luma_log2WD   = shdr->luma_log2_weight_denom + shift1_L;
        int chroma_log2WD = shdr->ChromaLog2WeightDenom  + shift1_C;

        int luma_w = shdr->LumaWeight[l][refIdx];
        int luma_o = shdr->luma_offset[l][refIdx] * (1<<(offset_shift1_L));

        int chroma0_w = shdr->ChromaWeight[l][refIdx][0];
        int chroma0_o = shdr->ChromaOffset[l][refIdx][0] * (1<<(offset_shift1_C));
        int chroma1_w = shdr->ChromaWeight[l][refIdx][1];
        int chroma1_o = shdr->ChromaOffset[l][refIdx][1] * (1<<(offset_shift1_C));

        logtrace(LogMotion,""weighted-B-L%d [%d] %d %d %d  %dx%d\n"", l, refIdx, luma_log2WD-6,luma_w,luma_o,nPbW,nPbH);

        ctx->acceleration.put_weighted_pred(pixels[0], stride[0],
                                            predSamplesL[l],nCS, nPbW,nPbH,
                                            luma_w, luma_o, luma_log2WD, bit_depth_L);
        ctx->acceleration.put_weighted_pred(pixels[1], stride[1],
                                            predSamplesC[0][l],nCS,
                                            nPbW/SubWidthC,nPbH/SubHeightC,
                                            chroma0_w, chroma0_o, chroma_log2WD, bit_depth_C);
        ctx->acceleration.put_weighted_pred(pixels[2], stride[2],
                                            predSamplesC[1][l],nCS,
                                            nPbW/SubWidthC,nPbH/SubHeightC,
                                            chroma1_w, chroma1_o, chroma_log2WD, bit_depth_C);
      }
    }
    else {
      // TODO: check why it can actually happen that both predFlags[] are false.
      // For now, we ignore this and continue decoding.

      ctx->add_warning(DE265_WARNING_BOTH_PREDFLAGS_ZERO, false);
      img->integrity = INTEGRITY_DECODING_ERRORS;
    }
  }

#if defined(DE265_LOG_TRACE) && 0
  logtrace(LogTransform,""MC pixels (luma), position %d %d:\n"", xP,yP);

  for (int y=0;ybody.irep;
  const mrb_pool_value *pool = irep->pool;
  const mrb_sym *syms = irep->syms;
  mrb_code insn;
  int ai = mrb_gc_arena_save(mrb);
  struct mrb_jmpbuf *prev_jmp = mrb->jmp;
  struct mrb_jmpbuf c_jmp;
  uint32_t a;
  uint16_t b;
  uint16_t c;
  mrb_sym mid;
  const struct mrb_irep_catch_handler *ch;

#ifdef DIRECT_THREADED
  static const void * const optable[] = {
#define OPCODE(x,_) &&L_OP_ ## x,
#include ""mruby/ops.h""
#undef OPCODE
  };
#endif

  mrb_bool exc_catched = FALSE;
RETRY_TRY_BLOCK:

  MRB_TRY(&c_jmp) {

  if (exc_catched) {
    exc_catched = FALSE;
    mrb_gc_arena_restore(mrb, ai);
    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)
      goto L_BREAK;
    goto L_RAISE;
  }
  mrb->jmp = &c_jmp;
  mrb_vm_ci_proc_set(mrb->c->ci, proc);

#define regs (mrb->c->ci->stack)
  INIT_DISPATCH {
    CASE(OP_NOP, Z) {
      /* do nothing */
      NEXT;
    }

    CASE(OP_MOVE, BB) {
      regs[a] = regs[b];
      NEXT;
    }

    CASE(OP_LOADL, BB) {
      switch (pool[b].tt) {   /* number */
      case IREP_TT_INT32:
        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);
        break;
      case IREP_TT_INT64:
#if defined(MRB_INT64)
        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);
        break;
#else
#if defined(MRB_64BIT)
        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {
          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);
          break;
        }
#endif
        goto L_INT_OVERFLOW;
#endif
      case IREP_TT_BIGINT:
#ifdef MRB_USE_BIGINT
        {
          const char *s = pool[b].u.str;
          regs[a] = mrb_bint_new_str(mrb, s+2, (mrb_int)s[0], (mrb_int)s[1]);
        }
        break;
#else
        goto L_INT_OVERFLOW;
#endif
#ifndef MRB_NO_FLOAT
      case IREP_TT_FLOAT:
        regs[a] = mrb_float_value(mrb, pool[b].u.f);
        break;
#endif
      default:
        /* should not happen (tt:string) */
        regs[a] = mrb_nil_value();
        break;
      }
      NEXT;
    }

    CASE(OP_LOADI, BB) {
      SET_FIXNUM_VALUE(regs[a], b);
      NEXT;
    }

    CASE(OP_LOADINEG, BB) {
      SET_FIXNUM_VALUE(regs[a], -b);
      NEXT;
    }

    CASE(OP_LOADI__1,B) goto L_LOADI;
    CASE(OP_LOADI_0,B) goto L_LOADI;
    CASE(OP_LOADI_1,B) goto L_LOADI;
    CASE(OP_LOADI_2,B) goto L_LOADI;
    CASE(OP_LOADI_3,B) goto L_LOADI;
    CASE(OP_LOADI_4,B) goto L_LOADI;
    CASE(OP_LOADI_5,B) goto L_LOADI;
    CASE(OP_LOADI_6,B) goto L_LOADI;
    CASE(OP_LOADI_7, B) {
    L_LOADI:
      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);
      NEXT;
    }

    CASE(OP_LOADI16, BS) {
      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);
      NEXT;
    }

    CASE(OP_LOADI32, BSS) {
      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));
      NEXT;
    }

    CASE(OP_LOADSYM, BB) {
      SET_SYM_VALUE(regs[a], syms[b]);
      NEXT;
    }

    CASE(OP_LOADNIL, B) {
      SET_NIL_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_LOADSELF, B) {
      regs[a] = regs[0];
      NEXT;
    }

    CASE(OP_LOADT, B) {
      SET_TRUE_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_LOADF, B) {
      SET_FALSE_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_GETGV, BB) {
      mrb_value val = mrb_gv_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETGV, BB) {
      mrb_gv_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETSV, BB) {
      mrb_value val = mrb_vm_special_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETSV, BB) {
      mrb_vm_special_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETIV, BB) {
      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);
      NEXT;
    }

    CASE(OP_SETIV, BB) {
      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETCV, BB) {
      mrb_value val;
      val = mrb_vm_cv_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETCV, BB) {
      mrb_vm_cv_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETIDX, B) {
      mrb_value va = regs[a], vb = regs[a+1];
      switch (mrb_type(va)) {
      case MRB_TT_ARRAY:
        if (!mrb_integer_p(vb)) goto getidx_fallback;
        regs[a] = mrb_ary_entry(va, mrb_integer(vb));
        break;
      case MRB_TT_HASH:
        va = mrb_hash_get(mrb, va, vb);
        regs[a] = va;
        break;
      case MRB_TT_STRING:
        switch (mrb_type(vb)) {
        case MRB_TT_INTEGER:
        case MRB_TT_STRING:
        case MRB_TT_RANGE:
          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());
          regs[a] = va;
          break;
        default:
          goto getidx_fallback;
        }
        break;
      default:
      getidx_fallback:
        mid = MRB_OPSYM(aref);
        goto L_SEND_SYM;
      }
      NEXT;
    }

    CASE(OP_SETIDX, B) {
      c = 2;
      mid = MRB_OPSYM(aset);
      SET_NIL_VALUE(regs[a+3]);
      goto L_SENDB_SYM;
    }

    CASE(OP_GETCONST, BB) {
      mrb_value v = mrb_vm_const_get(mrb, syms[b]);
      regs[a] = v;
      NEXT;
    }

    CASE(OP_SETCONST, BB) {
      mrb_vm_const_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETMCNST, BB) {
      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);
      regs[a] = v;
      NEXT;
    }

    CASE(OP_SETMCNST, BB) {
      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETUPVAR, BBB) {
      mrb_value *regs_a = regs + a;
      struct REnv *e = uvenv(mrb, c);

      if (e && b < MRB_ENV_LEN(e)) {
        *regs_a = e->stack[b];
      }
      else {
        *regs_a = mrb_nil_value();
      }
      NEXT;
    }

    CASE(OP_SETUPVAR, BBB) {
      struct REnv *e = uvenv(mrb, c);

      if (e) {
        mrb_value *regs_a = regs + a;

        if (b < MRB_ENV_LEN(e)) {
          e->stack[b] = *regs_a;
          mrb_write_barrier(mrb, (struct RBasic*)e);
        }
      }
      NEXT;
    }

    CASE(OP_JMP, S) {
      pc += (int16_t)a;
      JUMP;
    }
    CASE(OP_JMPIF, BS) {
      if (mrb_test(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }
    CASE(OP_JMPNOT, BS) {
      if (!mrb_test(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }
    CASE(OP_JMPNIL, BS) {
      if (mrb_nil_p(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }

    CASE(OP_JMPUW, S) {
      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);
      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {
        struct RBreak *brk = (struct RBreak*)mrb->exc;
        mrb_value target = mrb_break_value_get(brk);
        mrb_assert(mrb_integer_p(target));
        a = (uint32_t)mrb_integer(target);
        mrb_assert(a >= 0 && a < irep->ilen);
      }
      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {
        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);
        if (ch) {
          /* avoiding a jump from a catch handler into the same handler */
          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {
            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));
          }
        }
      }
      CHECKPOINT_END(RBREAK_TAG_JUMP);

      mrb->exc = NULL; /* clear break object */
      pc = irep->iseq + a;
      JUMP;
    }

    CASE(OP_EXCEPT, B) {
      mrb_value exc;

      if (mrb->exc == NULL) {
        exc = mrb_nil_value();
      }
      else {
        switch (mrb->exc->tt) {
        case MRB_TT_BREAK:
        case MRB_TT_EXCEPTION:
          exc = mrb_obj_value(mrb->exc);
          break;
        default:
          mrb_assert(!""bad mrb_type"");
          exc = mrb_nil_value();
          break;
        }
        mrb->exc = NULL;
      }
      regs[a] = exc;
      NEXT;
    }
    CASE(OP_RESCUE, BB) {
      mrb_value exc = regs[a];  /* exc on stack */
      mrb_value e = regs[b];
      struct RClass *ec;

      switch (mrb_type(e)) {
      case MRB_TT_CLASS:
      case MRB_TT_MODULE:
        break;
      default:
        {
          mrb_value exc;

          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,
                                    ""class or module required for rescue clause"");
          mrb_exc_set(mrb, exc);
          goto L_RAISE;
        }
      }
      ec = mrb_class_ptr(e);
      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));
      NEXT;
    }

    CASE(OP_RAISEIF, B) {
      mrb_value exc = regs[a];
      if (mrb_break_p(exc)) {
        mrb->exc = mrb_obj_ptr(exc);
        goto L_BREAK;
      }
      mrb_exc_set(mrb, exc);
      if (mrb->exc) {
        goto L_RAISE;
      }
      NEXT;
    }

    CASE(OP_SSEND, BBB) {
      regs[a] = regs[0];
      insn = OP_SEND;
    }
    goto L_SENDB;

    CASE(OP_SSENDB, BBB) {
      regs[a] = regs[0];
    }
    goto L_SENDB;

    CASE(OP_SEND, BBB)
    goto L_SENDB;

    L_SEND_SYM:
    c = 1;
    /* push nil after arguments */
    SET_NIL_VALUE(regs[a+2]);
    goto L_SENDB_SYM;

    CASE(OP_SENDB, BBB)
    L_SENDB:
    mid = syms[b];
    L_SENDB_SYM:
    {
      mrb_callinfo *ci = mrb->c->ci;
      mrb_method_t m;
      struct RClass *cls;
      mrb_value recv, blk;

      ARGUMENT_NORMALIZE(a, &c, insn);

      recv = regs[a];
      cls = mrb_class(mrb, recv);
      m = mrb_method_search_vm(mrb, &cls, mid);
      if (MRB_METHOD_UNDEF_P(m)) {
        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);
        mid = MRB_SYM(method_missing);
      }

      /* push callinfo */
      ci = cipush(mrb, a, 0, cls, NULL, mid, c);

      if (MRB_METHOD_CFUNC_P(m)) {
        if (MRB_METHOD_PROC_P(m)) {
          struct RProc *p = MRB_METHOD_PROC(m);

          mrb_vm_ci_proc_set(ci, p);
          recv = p->body.func(mrb, recv);
        }
        else {
          if (MRB_METHOD_NOARG_P(m)) {
            check_method_noarg(mrb, ci);
          }
          recv = MRB_METHOD_FUNC(m)(mrb, recv);
        }
        mrb_gc_arena_shrink(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        ci = mrb->c->ci;
        if (mrb_proc_p(blk)) {
          struct RProc *p = mrb_proc_ptr(blk);
          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {
            p->flags |= MRB_PROC_ORPHAN;
          }
        }
        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */
          if (ci->cci == CINFO_RESUMED) {
            mrb->jmp = prev_jmp;
            return recv;
          }
          else {
            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
            proc = ci[-1].proc;
            irep = proc->body.irep;
            pool = irep->pool;
            syms = irep->syms;
          }
        }
        ci->stack[0] = recv;
        /* pop stackpos */
        ci = cipop(mrb);
        pc = ci->pc;
      }
      else {
        /* setup environment for calling method */
        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);
        pc = irep->iseq;
      }
    }
    JUMP;

    CASE(OP_CALL, Z) {
      mrb_callinfo *ci = mrb->c->ci;
      mrb_value recv = ci->stack[0];
      struct RProc *m = mrb_proc_ptr(recv);

      /* replace callinfo */
      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);
      mrb_vm_ci_proc_set(ci, m);
      if (MRB_PROC_ENV_P(m)) {
        ci->mid = MRB_PROC_ENV(m)->mid;
      }

      /* prepare stack */
      if (MRB_PROC_CFUNC_P(m)) {
        recv = MRB_PROC_CFUNC(m)(mrb, recv);
        mrb_gc_arena_shrink(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        /* pop stackpos */
        ci = cipop(mrb);
        pc = ci->pc;
        ci[1].stack[0] = recv;
        irep = mrb->c->ci->proc->body.irep;
      }
      else {
        /* setup environment for calling method */
        proc = m;
        irep = m->body.irep;
        if (!irep) {
          mrb->c->ci->stack[0] = mrb_nil_value();
          a = 0;
          c = OP_R_NORMAL;
          goto L_OP_RETURN_BODY;
        }
        mrb_int nargs = mrb_ci_bidx(ci)+1;
        if (nargs < irep->nregs) {
          mrb_stack_extend(mrb, irep->nregs);
          stack_clear(regs+nargs, irep->nregs-nargs);
        }
        if (MRB_PROC_ENV_P(m)) {
          regs[0] = MRB_PROC_ENV(m)->stack[0];
        }
        pc = irep->iseq;
      }
      pool = irep->pool;
      syms = irep->syms;
      JUMP;
    }

    CASE(OP_SUPER, BB) {
      mrb_method_t m;
      struct RClass *cls;
      mrb_callinfo *ci = mrb->c->ci;
      mrb_value recv, blk;
      const struct RProc *p = ci->proc;
      mrb_sym mid = ci->mid;
      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);

      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */
        mid = p->e.env->mid;    /* restore old mid */
      }

      if (mid == 0 || !target_class) {
        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }
      if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {
        target_class = mrb_vm_ci_target_class(ci);
      }
      else if (target_class->tt == MRB_TT_MODULE) {
        target_class = mrb_vm_ci_target_class(ci);
        if (!target_class || target_class->tt != MRB_TT_ICLASS) {
          goto super_typeerror;
        }
      }
      recv = regs[0];
      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {
      super_typeerror: ;
        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,
                                            ""self has wrong type to call super in this context"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }

      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);

      cls = target_class->super;
      m = mrb_method_search_vm(mrb, &cls, mid);
      if (MRB_METHOD_UNDEF_P(m)) {
        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);
        mid = MRB_SYM(method_missing);
      }

      /* push callinfo */
      ci = cipush(mrb, a, 0, cls, NULL, mid, b);

      /* prepare stack */
      ci->stack[0] = recv;

      if (MRB_METHOD_CFUNC_P(m)) {
        mrb_value v;

        if (MRB_METHOD_PROC_P(m)) {
          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));
        }
        v = MRB_METHOD_CFUNC(m)(mrb, recv);
        mrb_gc_arena_restore(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        ci = mrb->c->ci;
        mrb_assert(!mrb_break_p(v));
        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */
          if (ci->cci == CINFO_RESUMED) {
            mrb->jmp = prev_jmp;
            return v;
          }
          else {
            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
            proc = ci[-1].proc;
            irep = proc->body.irep;
            pool = irep->pool;
            syms = irep->syms;
          }
        }
        mrb->c->ci->stack[0] = v;
        ci = cipop(mrb);
        pc = ci->pc;
      }
      else {
        /* setup environment for calling method */
        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);
        pc = irep->iseq;
      }
      JUMP;
    }

    CASE(OP_ARGARY, BS) {
      mrb_int m1 = (b>>11)&0x3f;
      mrb_int r  = (b>>10)&0x1;
      mrb_int m2 = (b>>5)&0x1f;
      mrb_int kd = (b>>4)&0x1;
      mrb_int lv = (b>>0)&0xf;
      mrb_value *stack;

      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {
        mrb_value exc;

      L_NOSUPER:
        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }
      if (lv == 0) stack = regs + 1;
      else {
        struct REnv *e = uvenv(mrb, lv-1);
        if (!e) goto L_NOSUPER;
        if (MRB_ENV_LEN(e) <= m1+r+m2+1)
          goto L_NOSUPER;
        stack = e->stack + 1;
      }
      if (r == 0) {
        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);
      }
      else {
        mrb_value *pp = NULL;
        struct RArray *rest;
        mrb_int len = 0;

        if (mrb_array_p(stack[m1])) {
          struct RArray *ary = mrb_ary_ptr(stack[m1]);

          pp = ARY_PTR(ary);
          len = ARY_LEN(ary);
        }
        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);
        rest = mrb_ary_ptr(regs[a]);
        if (m1 > 0) {
          stack_copy(ARY_PTR(rest), stack, m1);
        }
        if (len > 0) {
          stack_copy(ARY_PTR(rest)+m1, pp, len);
        }
        if (m2 > 0) {
          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);
        }
        ARY_SET_LEN(rest, m1+len+m2);
      }
      if (kd) {
        regs[a+1] = stack[m1+r+m2];
        regs[a+2] = stack[m1+r+m2+1];
      }
      else {
        regs[a+1] = stack[m1+r+m2];
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ENTER, W) {
      mrb_int m1 = MRB_ASPEC_REQ(a);
      mrb_int o  = MRB_ASPEC_OPT(a);
      mrb_int r  = MRB_ASPEC_REST(a);
      mrb_int m2 = MRB_ASPEC_POST(a);
      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;
      /* unused
      int b  = MRB_ASPEC_BLOCK(a);
      */
      mrb_int const len = m1 + o + r + m2;

      mrb_callinfo *ci = mrb->c->ci;
      mrb_int argc = ci->n;
      mrb_value *argv = regs+1;
      mrb_value * const argv0 = argv;
      mrb_int const kw_pos = len + kd;    /* where kwhash should be */
      mrb_int const blk_pos = kw_pos + 1; /* where block should be */
      mrb_value blk = regs[mrb_ci_bidx(ci)];
      mrb_value kdict = mrb_nil_value();

      /* keyword arguments */
      if (ci->nk > 0) {
        mrb_int kidx = mrb_ci_kidx(ci);
        kdict = regs[kidx];
        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {
          kdict = mrb_nil_value();
          ci->nk = 0;
        }
      }
      if (!kd && !mrb_nil_p(kdict)) {
        if (argc < 14) {
          ci->n++;
          argc++;    /* include kdict in normal arguments */
        }
        else if (argc == 14) {
          /* pack arguments and kdict */
          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);
          argc = ci->n = 15;
        }
        else {/* argc == 15 */
          /* push kdict to packed arguments */
          mrb_ary_push(mrb, regs[1], regs[2]);
        }
        ci->nk = 0;
      }
      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {
        kdict = mrb_hash_dup(mrb, kdict);
      }

      /* arguments is passed with Array */
      if (argc == 15) {
        struct RArray *ary = mrb_ary_ptr(regs[1]);
        argv = ARY_PTR(ary);
        argc = (int)ARY_LEN(ary);
        mrb_gc_protect(mrb, regs[1]);
      }

      /* strict argument check */
      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {
        if (argc < m1 + m2 || (r == 0 && argc > len)) {
          argnum_error(mrb, m1+m2);
          goto L_RAISE;
        }
      }
      /* extract first argument array to arguments */
      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {
        mrb_gc_protect(mrb, argv[0]);
        argc = (int)RARRAY_LEN(argv[0]);
        argv = RARRAY_PTR(argv[0]);
      }

      /* rest arguments */
      mrb_value rest = mrb_nil_value();
      if (argc < len) {
        mrb_int mlen = m2;
        if (argc < m1+m2) {
          mlen = m1 < argc ? argc - m1 : 0;
        }

        /* copy mandatory and optional arguments */
        if (argv0 != argv && argv) {
          value_move(®s[1], argv, argc-mlen); /* m1 + o */
        }
        if (argc < m1) {
          stack_clear(®s[argc+1], m1-argc);
        }
        /* copy post mandatory arguments */
        if (mlen) {
          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
        }
        if (mlen < m2) {
          stack_clear(®s[len-m2+mlen+1], m2-mlen);
        }
        /* initialize rest arguments with empty Array */
        if (r) {
          rest = mrb_ary_new_capa(mrb, 0);
          regs[m1+o+1] = rest;
        }
        /* skip initializer of passed arguments */
        if (o > 0 && argc > m1+m2)
          pc += (argc - m1 - m2)*3;
      }
      else {
        mrb_int rnum = 0;
        if (argv0 != argv) {
          value_move(®s[1], argv, m1+o);
        }
        if (r) {
          rnum = argc-m1-o-m2;
          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);
          regs[m1+o+1] = rest;
        }
        if (m2 > 0 && argc-m2 > m1) {
          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);
        }
        pc += o*3;
      }

      /* need to be update blk first to protect blk from GC */
      regs[blk_pos] = blk;              /* move block */
      if (kd) {
        if (mrb_nil_p(kdict))
          kdict = mrb_hash_new_capa(mrb, 0);
        regs[kw_pos] = kdict;           /* set kwhash */
      }

      /* format arguments for generated code */
      mrb->c->ci->n = (uint8_t)len;

      /* clear local (but non-argument) variables */
      if (irep->nlocals-blk_pos-1 > 0) {
        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);
      }
      JUMP;
    }

    CASE(OP_KARG, BB) {
      mrb_value k = mrb_symbol_value(syms[b]);
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict, v;

      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {
        mrb_value str = mrb_format(mrb, ""missing keyword: %v"", k);
        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));
        goto L_RAISE;
      }
      v = mrb_hash_get(mrb, kdict, k);
      regs[a] = v;
      mrb_hash_delete_key(mrb, kdict, k);
      NEXT;
    }

    CASE(OP_KEY_P, BB) {
      mrb_value k = mrb_symbol_value(syms[b]);
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;
      mrb_bool key_p = FALSE;

      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {
        key_p = mrb_hash_key_p(mrb, kdict, k);
      }
      regs[a] = mrb_bool_value(key_p);
      NEXT;
    }

    CASE(OP_KEYEND, Z) {
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;

      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {
        mrb_value keys = mrb_hash_keys(mrb, kdict);
        mrb_value key1 = RARRAY_PTR(keys)[0];
        mrb_value str = mrb_format(mrb, ""unknown keyword: %v"", key1);
        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));
        goto L_RAISE;
      }
      NEXT;
    }

    CASE(OP_BREAK, B) {
      c = OP_R_BREAK;
      goto L_RETURN;
    }
    CASE(OP_RETURN_BLK, B) {
      c = OP_R_RETURN;
      goto L_RETURN;
    }
    CASE(OP_RETURN, B)
    c = OP_R_NORMAL;
    L_RETURN:
    {
      mrb_callinfo *ci;

      ci = mrb->c->ci;
      if (ci->mid) {
        mrb_value blk = regs[mrb_ci_bidx(ci)];

        if (mrb_proc_p(blk)) {
          struct RProc *p = mrb_proc_ptr(blk);

          if (!MRB_PROC_STRICT_P(p) &&
              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {
            p->flags |= MRB_PROC_ORPHAN;
          }
        }
      }

      if (mrb->exc) {
      L_RAISE:
        ci = mrb->c->ci;
        if (ci == mrb->c->cibase) {
          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);
          if (ch == NULL) goto L_FTOP;
          goto L_CATCH;
        }
        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {
          ci = cipop(mrb);
          if (ci[1].cci == CINFO_SKIP && prev_jmp) {
            mrb->jmp = prev_jmp;
            MRB_THROW(prev_jmp);
          }
          pc = ci[0].pc;
          if (ci == mrb->c->cibase) {
            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);
            if (ch == NULL) {
            L_FTOP:             /* fiber top */
              if (mrb->c == mrb->root_c) {
                mrb->c->ci->stack = mrb->c->stbase;
                goto L_STOP;
              }
              else {
                struct mrb_context *c = mrb->c;

                c->status = MRB_FIBER_TERMINATED;
                mrb->c = c->prev;
                c->prev = NULL;
                goto L_RAISE;
              }
            }
            break;
          }
        }
      L_CATCH:
        if (ch == NULL) goto L_STOP;
        if (FALSE) {
        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */
          ci = mrb->c->ci;
        }
        proc = ci->proc;
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, irep->nregs);
        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);
      }
      else {
        mrb_int acc;
        mrb_value v;

        ci = mrb->c->ci;
        v = regs[a];
        mrb_gc_protect(mrb, v);
        switch (c) {
        case OP_R_RETURN:
          /* Fall through to OP_R_NORMAL otherwise */
          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {
            const struct RProc *dst;
            mrb_callinfo *cibase;
            cibase = mrb->c->cibase;
            dst = top_proc(mrb, proc);

            if (MRB_PROC_ENV_P(dst)) {
              struct REnv *e = MRB_PROC_ENV(dst);

              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {
                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
                goto L_RAISE;
              }
            }
            /* check jump destination */
            while (cibase <= ci && ci->proc != dst) {
              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */
                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
                goto L_RAISE;
              }
              ci--;
            }
            if (ci <= cibase) { /* no jump destination */
              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
              goto L_RAISE;
            }
            ci = mrb->c->ci;
            while (cibase <= ci && ci->proc != dst) {
              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {
                cibase = mrb->c->cibase;
                dst = top_proc(mrb, proc);
              }
              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {
                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);
              }
              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);
              ci = cipop(mrb);
              pc = ci->pc;
            }
            proc = ci->proc;
            mrb->exc = NULL; /* clear break object */
            break;
          }
          /* fallthrough */
        case OP_R_NORMAL:
        NORMAL_RETURN:
          if (ci == mrb->c->cibase) {
            struct mrb_context *c;
            c = mrb->c;

            if (!c->prev) { /* toplevel return */
              regs[irep->nlocals] = v;
              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);
            }
            if (!c->vmexec && c->prev->ci == c->prev->cibase) {
              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, ""double resume"");
              mrb_exc_set(mrb, exc);
              goto L_RAISE;
            }
            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {
              c = mrb->c;
            }
            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {
              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);
            }
            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);
            /* automatic yield at the end */
            c->status = MRB_FIBER_TERMINATED;
            mrb->c = c->prev;
            mrb->c->status = MRB_FIBER_RUNNING;
            c->prev = NULL;
            if (c->vmexec) {
              mrb_gc_arena_restore(mrb, ai);
              c->vmexec = FALSE;
              mrb->jmp = prev_jmp;
              return v;
            }
            ci = mrb->c->ci;
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_RETURN);
          mrb->exc = NULL; /* clear break object */
          break;
        case OP_R_BREAK:
          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;
          if (MRB_PROC_ORPHAN_P(proc)) {
            mrb_value exc;

          L_BREAK_ERROR:
            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,
                                      ""break from proc-closure"");
            mrb_exc_set(mrb, exc);
            goto L_RAISE;
          }
          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {
            goto L_BREAK_ERROR;
          }
          else {
            struct REnv *e = MRB_PROC_ENV(proc);

            if (e->cxt != mrb->c) {
              goto L_BREAK_ERROR;
            }
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_BREAK);
          /* break from fiber block */
          if (ci == mrb->c->cibase && ci->pc) {
            struct mrb_context *c = mrb->c;

            mrb->c = c->prev;
            c->prev = NULL;
            ci = mrb->c->ci;
          }
          if (ci->cci > CINFO_NONE) {
            ci = cipop(mrb);
            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);
            mrb_gc_arena_restore(mrb, ai);
            mrb->c->vmexec = FALSE;
            mrb->jmp = prev_jmp;
            MRB_THROW(prev_jmp);
          }
          if (FALSE) {
            struct RBreak *brk;

          L_BREAK:
            brk = (struct RBreak*)mrb->exc;
            proc = mrb_break_proc_get(brk);
            v = mrb_break_value_get(brk);
            ci = mrb->c->ci;

            switch (mrb_break_tag_get(brk)) {
#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);
              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)
#undef DISPATCH_CHECKPOINTS
              default:
                mrb_assert(!""wrong break tag"");
            }
          }
          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {
            if (ci[-1].cci == CINFO_SKIP) {
              goto L_BREAK_ERROR;
            }
            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {
              /* do nothing */
            }
            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {
              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);
            }
            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);
            ci = cipop(mrb);
            pc = ci->pc;
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);
          if (ci == mrb->c->cibase) {
            goto L_BREAK_ERROR;
          }
          mrb->exc = NULL; /* clear break object */
          break;
        default:
          /* cannot happen */
          break;
        }
        mrb_assert(ci == mrb->c->ci);
        mrb_assert(mrb->exc == NULL);

        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {
          mrb_gc_arena_restore(mrb, ai);
          mrb->c->vmexec = FALSE;
          mrb->jmp = prev_jmp;
          return v;
        }
        acc = ci->cci;
        ci = cipop(mrb);
        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {
          mrb_gc_arena_restore(mrb, ai);
          mrb->jmp = prev_jmp;
          return v;
        }
        pc = ci->pc;
        DEBUG(fprintf(stderr, ""from :%s\n"", mrb_sym_name(mrb, ci->mid)));
        proc = ci->proc;
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;

        ci[1].stack[0] = v;
        mrb_gc_arena_restore(mrb, ai);
      }
      JUMP;
    }

    CASE(OP_BLKPUSH, BS) {
      int m1 = (b>>11)&0x3f;
      int r  = (b>>10)&0x1;
      int m2 = (b>>5)&0x1f;
      int kd = (b>>4)&0x1;
      int lv = (b>>0)&0xf;
      mrb_value *stack;

      if (lv == 0) stack = regs + 1;
      else {
        struct REnv *e = uvenv(mrb, lv-1);
        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||
            MRB_ENV_LEN(e) <= m1+r+m2+1) {
          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
          goto L_RAISE;
        }
        stack = e->stack + 1;
      }
      if (mrb_nil_p(stack[m1+r+m2+kd])) {
        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
        goto L_RAISE;
      }
      regs[a] = stack[m1+r+m2+kd];
      NEXT;
    }

#if !defined(MRB_USE_BIGINT) || defined(MRB_INT32)
  L_INT_OVERFLOW:
    {
      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, ""integer overflow"");
      mrb_exc_set(mrb, exc);
    }
    goto L_RAISE;
#endif

#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))
#define OP_MATH(op_name)                                                    \
  /* need to check if op is overridden */                                   \
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \
    OP_MATH_CASE_INTEGER(op_name);                                          \
    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \
    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \
    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \
    OP_MATH_CASE_STRING_##op_name();                                        \
    default:                                                                \
      mid = MRB_OPSYM(op_name);                                             \
      goto L_SEND_SYM;                                                      \
  }                                                                         \
  NEXT;
#define OP_MATH_CASE_INTEGER(op_name)                                       \
  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \
    {                                                                       \
      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \
      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \
        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \
      }                                                                     \
      else                                                                  \
        SET_INT_VALUE(mrb,regs[a], z);                                      \
    }                                                                       \
    break
#ifdef MRB_NO_FLOAT
#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0
#else
#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \
  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \
    {                                                                           \
      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \
      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \
    }                                                                           \
    break
#endif
#ifdef MRB_USE_BIGINT
#define OP_MATH_OVERFLOW_INT(op,x,y) regs[a] = mrb_bint_##op##_ii(mrb,x,y)
#else
#define OP_MATH_OVERFLOW_INT(op,x,y) goto L_INT_OVERFLOW
#endif
#define OP_MATH_CASE_STRING_add()                                           \
  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \
    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \
    mrb_gc_arena_restore(mrb, ai);                                          \
    break
#define OP_MATH_CASE_STRING_sub() (void)0
#define OP_MATH_CASE_STRING_mul() (void)0
#define OP_MATH_OP_add +
#define OP_MATH_OP_sub -
#define OP_MATH_OP_mul *
#define OP_MATH_TT_integer MRB_TT_INTEGER
#define OP_MATH_TT_float   MRB_TT_FLOAT

    CASE(OP_ADD, B) {
      OP_MATH(add);
    }

    CASE(OP_SUB, B) {
      OP_MATH(sub);
    }

    CASE(OP_MUL, B) {
      OP_MATH(mul);
    }

    CASE(OP_DIV, B) {
#ifndef MRB_NO_FLOAT
      mrb_float x, y, f;
#endif

      /* need to check if op is overridden */
      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):
        {
          mrb_int x = mrb_integer(regs[a]);
          mrb_int y = mrb_integer(regs[a+1]);
          mrb_int div = mrb_div_int(mrb, x, y);
          SET_INT_VALUE(mrb, regs[a], div);
        }
        NEXT;
#ifndef MRB_NO_FLOAT
      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):
        x = (mrb_float)mrb_integer(regs[a]);
        y = mrb_float(regs[a+1]);
        break;
      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):
        x = mrb_float(regs[a]);
        y = (mrb_float)mrb_integer(regs[a+1]);
        break;
      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
        x = mrb_float(regs[a]);
        y = mrb_float(regs[a+1]);
        break;
#endif
      default:
        mid = MRB_OPSYM(div);
        goto L_SEND_SYM;
      }

#ifndef MRB_NO_FLOAT
      f = mrb_div_float(x, y);
      SET_FLOAT_VALUE(mrb, regs[a], f);
#endif
      NEXT;
    }

#define OP_MATHI(op_name)                                                   \
  /* need to check if op is overridden */                                   \
  switch (mrb_type(regs[a])) {                                              \
    OP_MATHI_CASE_INTEGER(op_name);                                         \
    OP_MATHI_CASE_FLOAT(op_name);                                           \
    default:                                                                \
      SET_INT_VALUE(mrb,regs[a+1], b);                                      \
      mid = MRB_OPSYM(op_name);                                             \
      goto L_SEND_SYM;                                                      \
  }                                                                         \
  NEXT;
#define OP_MATHI_CASE_INTEGER(op_name)                                      \
  case MRB_TT_INTEGER:                                                      \
    {                                                                       \
      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \
      if (mrb_int_##op_name##_overflow(x, y, &z)) {                         \
        OP_MATH_OVERFLOW_INT(op_name,x,y);                                  \
      }                                                                     \
      else                                                                  \
        SET_INT_VALUE(mrb,regs[a], z);                                      \
    }                                                                       \
    break
#ifdef MRB_NO_FLOAT
#define OP_MATHI_CASE_FLOAT(op_name) (void)0
#else
#define OP_MATHI_CASE_FLOAT(op_name)                                        \
  case MRB_TT_FLOAT:                                                        \
    {                                                                       \
      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \
      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \
    }                                                                       \
    break
#endif

    CASE(OP_ADDI, BB) {
      OP_MATHI(add);
    }

    CASE(OP_SUBI, BB) {
      OP_MATHI(sub);
    }

#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))

#ifdef MRB_NO_FLOAT
#define OP_CMP(op,sym) do {\
  int result;\
  /* need to check if - is overridden */\
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
    break;\
  default:\
    mid = MRB_OPSYM(sym);\
    goto L_SEND_SYM;\
  }\
  if (result) {\
    SET_TRUE_VALUE(regs[a]);\
  }\
  else {\
    SET_FALSE_VALUE(regs[a]);\
  }\
} while(0)
#else
#define OP_CMP(op, sym) do {\
  int result;\
  /* need to check if - is overridden */\
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
    break;\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\
    break;\
  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\
    break;\
  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\
    result = OP_CMP_BODY(op,mrb_float,mrb_float);\
    break;\
  default:\
    mid = MRB_OPSYM(sym);\
    goto L_SEND_SYM;\
  }\
  if (result) {\
    SET_TRUE_VALUE(regs[a]);\
  }\
  else {\
    SET_FALSE_VALUE(regs[a]);\
  }\
} while(0)
#endif

    CASE(OP_EQ, B) {
      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {
        SET_TRUE_VALUE(regs[a]);
      }
      else {
        OP_CMP(==,eq);
      }
      NEXT;
    }

    CASE(OP_LT, B) {
      OP_CMP(<,lt);
      NEXT;
    }

    CASE(OP_LE, B) {
      OP_CMP(<=,le);
      NEXT;
    }

    CASE(OP_GT, B) {
      OP_CMP(>,gt);
      NEXT;
    }

    CASE(OP_GE, B) {
      OP_CMP(>=,ge);
      NEXT;
    }

    CASE(OP_ARRAY, BB) {
      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }
    CASE(OP_ARRAY2, BBB) {
      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ARYCAT, B) {
      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);
      if (mrb_nil_p(regs[a])) {
        regs[a] = splat;
      }
      else {
        mrb_assert(mrb_array_p(regs[a]));
        mrb_ary_concat(mrb, regs[a], splat);
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ARYPUSH, BB) {
      mrb_assert(mrb_array_p(regs[a]));
      for (mrb_int i=0; i pre + post) {
        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);
        regs[a++] = v;
        while (post--) {
          regs[a++] = ARY_PTR(ary)[len-post-1];
        }
      }
      else {
        v = mrb_ary_new_capa(mrb, 0);
        regs[a++] = v;
        for (idx=0; idx+pre> 2;
      if (pool[b].tt & IREP_TT_SFLAG) {
        sym = mrb_intern_static(mrb, pool[b].u.str, len);
      }
      else {
        sym  = mrb_intern(mrb, pool[b].u.str, len);
      }
      regs[a] = mrb_symbol_value(sym);
      NEXT;
    }

    CASE(OP_STRING, BB) {
      mrb_int len;

      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);
      len = pool[b].tt >> 2;
      if (pool[b].tt & IREP_TT_SFLAG) {
        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);
      }
      else {
        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_STRCAT, B) {
      mrb_assert(mrb_string_p(regs[a]));
      mrb_str_concat(mrb, regs[a], regs[a+1]);
      NEXT;
    }

    CASE(OP_HASH, BB) {
      mrb_value hash = mrb_hash_new_capa(mrb, b);
      int i;
      int lim = a+b*2;

      for (i=a; ireps[b];

      if (c & OP_L_CAPTURE) {
        p = mrb_closure_new(mrb, nirep);
      }
      else {
        p = mrb_proc_new(mrb, nirep);
        p->flags |= MRB_PROC_SCOPE;
      }
      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;
      regs[a] = mrb_obj_value(p);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }
    CASE(OP_BLOCK, BB) {
      c = OP_L_BLOCK;
      goto L_MAKE_LAMBDA;
    }
    CASE(OP_METHOD, BB) {
      c = OP_L_METHOD;
      goto L_MAKE_LAMBDA;
    }

    CASE(OP_RANGE_INC, B) {
      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);
      regs[a] = v;
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_RANGE_EXC, B) {
      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);
      regs[a] = v;
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_OCLASS, B) {
      regs[a] = mrb_obj_value(mrb->object_class);
      NEXT;
    }

    CASE(OP_CLASS, BB) {
      struct RClass *c = 0, *baseclass;
      mrb_value base, super;
      mrb_sym id = syms[b];

      base = regs[a];
      super = regs[a+1];
      if (mrb_nil_p(base)) {
        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
        if (!baseclass) baseclass = mrb->object_class;
        base = mrb_obj_value(baseclass);
      }
      c = mrb_vm_define_class(mrb, base, super, id);
      regs[a] = mrb_obj_value(c);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_MODULE, BB) {
      struct RClass *cls = 0, *baseclass;
      mrb_value base;
      mrb_sym id = syms[b];

      base = regs[a];
      if (mrb_nil_p(base)) {
        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
        if (!baseclass) baseclass = mrb->object_class;
        base = mrb_obj_value(baseclass);
      }
      cls = mrb_vm_define_module(mrb, base, id);
      regs[a] = mrb_obj_value(cls);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_EXEC, BB)
    {
      mrb_value recv = regs[a];
      struct RProc *p;
      const mrb_irep *nirep = irep->reps[b];

      /* prepare closure */
      p = mrb_proc_new(mrb, nirep);
      p->c = NULL;
      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);
      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));
      p->flags |= MRB_PROC_SCOPE;

      /* prepare call stack */
      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);

      irep = p->body.irep;
      pool = irep->pool;
      syms = irep->syms;
      mrb_stack_extend(mrb, irep->nregs);
      stack_clear(regs+1, irep->nregs-1);
      pc = irep->iseq;
      JUMP;
    }

    CASE(OP_DEF, BB) {
      struct RClass *target = mrb_class_ptr(regs[a]);
      struct RProc *p = mrb_proc_ptr(regs[a+1]);
      mrb_method_t m;
      mrb_sym mid = syms[b];

      MRB_METHOD_FROM_PROC(m, p);
      mrb_define_method_raw(mrb, target, mid, m);
      mrb_method_added(mrb, target, mid);
      mrb_gc_arena_restore(mrb, ai);
      regs[a] = mrb_symbol_value(mid);
      NEXT;
    }

    CASE(OP_SCLASS, B) {
      regs[a] = mrb_singleton_class(mrb, regs[a]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_TCLASS, B) {
      struct RClass *target = check_target_class(mrb);
      if (!target) goto L_RAISE;
      regs[a] = mrb_obj_value(target);
      NEXT;
    }

    CASE(OP_ALIAS, BB) {
      struct RClass *target = check_target_class(mrb);

      if (!target) goto L_RAISE;
      mrb_alias_method(mrb, target, syms[a], syms[b]);
      mrb_method_added(mrb, target, syms[a]);
      NEXT;
    }
    CASE(OP_UNDEF, B) {
      struct RClass *target = check_target_class(mrb);

      if (!target) goto L_RAISE;
      mrb_undef_method_id(mrb, target, syms[a]);
      NEXT;
    }

    CASE(OP_DEBUG, Z) {
      FETCH_BBB();
#ifdef MRB_USE_DEBUG_HOOK
      mrb->debug_op_hook(mrb, irep, pc, regs);
#else
#ifndef MRB_NO_STDIO
      printf(""OP_DEBUG %d %d %d\n"", a, b, c);
#else
      abort();
#endif
#endif
      NEXT;
    }

    CASE(OP_ERR, B) {
      size_t len = pool[a].tt >> 2;
      mrb_value exc;

      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);
      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);
      mrb_exc_set(mrb, exc);
      goto L_RAISE;
    }

    CASE(OP_EXT1, Z) {
      insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }
    CASE(OP_EXT2, Z) {
      insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }
    CASE(OP_EXT3, Z) {
      uint8_t insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }

    CASE(OP_STOP, Z) {
      /*        stop VM */
      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {
        /* do nothing */
      }
      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {
        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());
      }
      CHECKPOINT_END(RBREAK_TAG_STOP);
    L_STOP:
      mrb->jmp = prev_jmp;
      if (mrb->exc) {
        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);
        return mrb_obj_value(mrb->exc);
      }
      return regs[irep->nlocals];
    }
  }
  END_DISPATCH;
#undef regs
  }
  MRB_CATCH(&c_jmp) {
    mrb_callinfo *ci = mrb->c->ci;
    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {
      ci = cipop(mrb);
    }
    exc_catched = TRUE;
    pc = ci->pc;
    goto RETRY_TRY_BLOCK;
  }
  MRB_END_EXC(&c_jmp);
}",1
"    QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength,
                                       const UBaseType_t uxItemSize,
                                       const uint8_t ucQueueType )
    {
        Queue_t * pxNewQueue;
        size_t xQueueSizeInBytes;
        uint8_t * pucQueueStorage;

        configASSERT( uxQueueLength > ( UBaseType_t ) 0 );

        /* Allocate enough space to hold the maximum number of items that
         * can be in the queue at any time.  It is valid for uxItemSize to be
         * zero in the case the queue is used as a semaphore. */
        xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */

        /* Check for multiplication overflow. */
        configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) );

        /* Allocate the queue and storage area.  Justification for MISRA
         * deviation as follows:  pvPortMalloc() always ensures returned memory
         * blocks are aligned per the requirements of the MCU stack.  In this case
         * pvPortMalloc() must return a pointer that is guaranteed to meet the
         * alignment requirements of the Queue_t structure - which in this case
         * is an int8_t *.  Therefore, whenever the stack alignment requirements
         * are greater than or equal to the pointer to char requirements the cast
         * is safe.  In other cases alignment requirements are not strict (one or
         * two bytes). */
        pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */

        if( pxNewQueue != NULL )
        {
            /* Jump past the queue structure to find the location of the queue
             * storage area. */
            pucQueueStorage = ( uint8_t * ) pxNewQueue;
            pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */

            #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
                {
                    /* Queues can be created either statically or dynamically, so
                     * note this task was created dynamically in case it is later
                     * deleted. */
                    pxNewQueue->ucStaticallyAllocated = pdFALSE;
                }
            #endif /* configSUPPORT_STATIC_ALLOCATION */

            prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );
        }
        else
        {
            traceQUEUE_CREATE_FAILED( ucQueueType );
            mtCOVERAGE_TEST_MARKER();
        }

        return pxNewQueue;
    }
",1
"__getcwd_generic (char *buf, size_t size)
{
  /* Lengths of big file name components and entire file names, and a
     deep level of file name nesting.  These numbers are not upper
     bounds; they are merely large values suitable for initial
     allocations, designed to be large enough for most real-world
     uses.  */
  enum
    {
      BIG_FILE_NAME_COMPONENT_LENGTH = 255,
      BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),
      DEEP_NESTING = 100
    };

#if HAVE_OPENAT_SUPPORT
  int fd = AT_FDCWD;
  bool fd_needs_closing = false;
#else
  char dots[DEEP_NESTING * sizeof "".."" + BIG_FILE_NAME_COMPONENT_LENGTH + 1];
  char *dotlist = dots;
  size_t dotsize = sizeof dots;
  size_t dotlen = 0;
#endif
  DIR *dirstream = NULL;
  dev_t rootdev, thisdev;
  ino_t rootino, thisino;
  char *dir;
  register char *dirp;
  struct __stat64_t64 st;
  size_t allocated = size;
  size_t used;

#if HAVE_MINIMALLY_WORKING_GETCWD
  /* If AT_FDCWD is not defined, the algorithm below is O(N**2) and
     this is much slower than the system getcwd (at least on
     GNU/Linux).  So trust the system getcwd's results unless they
     look suspicious.

     Use the system getcwd even if we have openat support, since the
     system getcwd works even when a parent is unreadable, while the
     openat-based approach does not.

     But on AIX 5.1..7.1, the system getcwd is not even minimally
     working: If the current directory name is slightly longer than
     PATH_MAX, it omits the first directory component and returns
     this wrong result with errno = 0.  */

# undef getcwd
  dir = getcwd_system (buf, size);
  if (dir || (size && errno == ERANGE))
    return dir;

  /* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has
     internal magic that lets it work even if an ancestor directory is
     inaccessible, which is better in many cases.  So in this case try
     again with a buffer that's almost always big enough.  */
  if (errno == EINVAL && buf == NULL && size == 0)
    {
      char big_buffer[BIG_FILE_NAME_LENGTH + 1];
      dir = getcwd_system (big_buffer, sizeof big_buffer);
      if (dir)
        return strdup (dir);
    }

# if HAVE_PARTLY_WORKING_GETCWD
  /* The system getcwd works, except it sometimes fails when it
     shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT.    */
  if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT)
    return NULL;
# endif
#endif
  if (size == 0)
    {
      if (buf != NULL)
        {
          __set_errno (EINVAL);
          return NULL;
        }

      allocated = BIG_FILE_NAME_LENGTH + 1;
    }

  if (buf == NULL)
    {
      dir = malloc (allocated);
      if (dir == NULL)
        return NULL;
    }
  else
    dir = buf;

  dirp = dir + allocated;
  *--dirp = '\0';

  if (__lstat64_time64 (""."", &st) < 0)
    goto lose;
  thisdev = st.st_dev;
  thisino = st.st_ino;

  if (__lstat64_time64 (""/"", &st) < 0)
    goto lose;
  rootdev = st.st_dev;
  rootino = st.st_ino;

  while (!(thisdev == rootdev && thisino == rootino))
    {
      struct dirent64 *d;
      dev_t dotdev;
      ino_t dotino;
      bool mount_point;
      int parent_status;
      size_t dirroom;
      size_t namlen;
      bool use_d_ino = true;

      /* Look at the parent directory.  */
#if HAVE_OPENAT_SUPPORT
      fd = __openat64 (fd, "".."", O_RDONLY);
      if (fd < 0)
        goto lose;
      fd_needs_closing = true;
      parent_status = __fstat64_time64 (fd, &st);
#else
      dotlist[dotlen++] = '.';
      dotlist[dotlen++] = '.';
      dotlist[dotlen] = '\0';
      parent_status = __lstat64_time64 (dotlist, &st);
#endif
      if (parent_status != 0)
        goto lose;

      if (dirstream && __closedir (dirstream) != 0)
        {
          dirstream = NULL;
          goto lose;
        }

      /* Figure out if this directory is a mount point.  */
      dotdev = st.st_dev;
      dotino = st.st_ino;
      mount_point = dotdev != thisdev;

      /* Search for the last directory.  */
#if HAVE_OPENAT_SUPPORT
      dirstream = __fdopendir (fd);
      if (dirstream == NULL)
        goto lose;
      fd_needs_closing = false;
#else
      dirstream = __opendir (dotlist);
      if (dirstream == NULL)
        goto lose;
      dotlist[dotlen++] = '/';
#endif
      for (;;)
        {
          /* Clear errno to distinguish EOF from error if readdir returns
             NULL.  */
          __set_errno (0);
          d = __readdir64 (dirstream);

          /* When we've iterated through all directory entries without finding
             one with a matching d_ino, rewind the stream and consider each
             name again, but this time, using lstat.  This is necessary in a
             chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
             .., ../.., ../../.., etc. all had the same device number, yet the
             d_ino values for entries in / did not match those obtained
             via lstat.  */
          if (d == NULL && errno == 0 && use_d_ino)
            {
              use_d_ino = false;
              __rewinddir (dirstream);
              d = __readdir64 (dirstream);
            }

          if (d == NULL)
            {
              if (errno == 0)
                /* EOF on dirstream, which can mean e.g., that the current
                   directory has been removed.  */
                __set_errno (ENOENT);
              goto lose;
            }
          if (d->d_name[0] == '.' &&
              (d->d_name[1] == '\0' ||
               (d->d_name[1] == '.' && d->d_name[2] == '\0')))
            continue;

          if (use_d_ino)
            {
              bool match = (MATCHING_INO (d, thisino) || mount_point);
              if (! match)
                continue;
            }

          {
            int entry_status;
#if HAVE_OPENAT_SUPPORT
            entry_status = __fstatat64_time64 (fd, d->d_name, &st,
					       AT_SYMLINK_NOFOLLOW);
#else
            /* Compute size needed for this file name, or for the file
               name "".."" in the same directory, whichever is larger.
               Room for "".."" might be needed the next time through
               the outer loop.  */
            size_t name_alloc = _D_ALLOC_NAMLEN (d);
            size_t filesize = dotlen + MAX (sizeof "".."", name_alloc);

            if (filesize < dotlen)
              goto memory_exhausted;

            if (dotsize < filesize)
              {
                /* My, what a deep directory tree you have, Grandma.  */
                size_t newsize = MAX (filesize, dotsize * 2);
                size_t i;
                if (newsize < dotsize)
                  goto memory_exhausted;
                if (dotlist != dots)
                  free (dotlist);
                dotlist = malloc (newsize);
                if (dotlist == NULL)
                  goto lose;
                dotsize = newsize;

                i = 0;
                do
                  {
                    dotlist[i++] = '.';
                    dotlist[i++] = '.';
                    dotlist[i++] = '/';
                  }
                while (i < dotlen);
              }

            memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
            entry_status = __lstat64_time64 (dotlist, &st);
#endif
            /* We don't fail here if we cannot stat() a directory entry.
               This can happen when (network) file systems fail.  If this
               entry is in fact the one we are looking for we will find
               out soon as we reach the end of the directory without
               having found anything.  */
            if (entry_status == 0 && S_ISDIR (st.st_mode)
                && st.st_dev == thisdev && st.st_ino == thisino)
              break;
          }
        }

      dirroom = dirp - dir;
      namlen = _D_EXACT_NAMLEN (d);

      if (dirroom <= namlen)
        {
          if (size != 0)
            {
              __set_errno (ERANGE);
              goto lose;
            }
          else
            {
              char *tmp;
              size_t oldsize = allocated;

              allocated += MAX (allocated, namlen);
              if (allocated < oldsize
                  || ! (tmp = realloc (dir, allocated)))
                goto memory_exhausted;

              /* Move current contents up to the end of the buffer.
                 This is guaranteed to be non-overlapping.  */
              dirp = memcpy (tmp + allocated - (oldsize - dirroom),
                             tmp + dirroom,
                             oldsize - dirroom);
              dir = tmp;
            }
        }
      dirp -= namlen;
      memcpy (dirp, d->d_name, namlen);
      *--dirp = '/';

      thisdev = dotdev;
      thisino = dotino;
    }

  if (dirstream && __closedir (dirstream) != 0)
    {
      dirstream = NULL;
      goto lose;
    }

  if (dirp == &dir[allocated - 1])
    *--dirp = '/';

#if ! HAVE_OPENAT_SUPPORT
  if (dotlist != dots)
    free (dotlist);
#endif

  used = dir + allocated - dirp;
  memmove (dir, dirp, used);

  if (size == 0)
    /* Ensure that the buffer is only as large as necessary.  */
    buf = (used < allocated ? realloc (dir, used) : dir);

  if (buf == NULL)
    /* Either buf was NULL all along, or 'realloc' failed but
       we still have the original string.  */
    buf = dir;

  return buf;

 memory_exhausted:
  __set_errno (ENOMEM);
 lose:
  {
    int save = errno;
    if (dirstream)
      __closedir (dirstream);
#if HAVE_OPENAT_SUPPORT
    if (fd_needs_closing)
       __close_nocancel_nostatus (fd);
#else
    if (dotlist != dots)
      free (dotlist);
#endif
    if (buf == NULL)
      free (dir);
    __set_errno (save);
  }
  return NULL;
}",1
"void updateHandshakeState(QuicServerConnectionState& conn) {
  // Zero RTT read cipher is available after chlo is processed with the
  // condition that early data attempt is accepted.
  auto handshakeLayer = conn.serverHandshakeLayer;
  auto zeroRttReadCipher = handshakeLayer->getZeroRttReadCipher();
  auto zeroRttHeaderCipher = handshakeLayer->getZeroRttReadHeaderCipher();
  // One RTT write cipher is available at Fizz layer after chlo is processed.
  // However, the cipher is only exported to QUIC if early data attempt is
  // accepted. Otherwise, the cipher will be available after cfin is
  // processed.
  auto oneRttWriteCipher = handshakeLayer->getOneRttWriteCipher();
  // One RTT read cipher is available after cfin is processed.
  auto oneRttReadCipher = handshakeLayer->getOneRttReadCipher();

  auto oneRttWriteHeaderCipher = handshakeLayer->getOneRttWriteHeaderCipher();
  auto oneRttReadHeaderCipher = handshakeLayer->getOneRttReadHeaderCipher();

  if (zeroRttReadCipher) {
    if (conn.qLogger) {
      conn.qLogger->addTransportStateUpdate(kDerivedZeroRttReadCipher);
    }
    QUIC_TRACE(fst_trace, conn, ""derived 0-rtt read cipher"");
    conn.readCodec->setZeroRttReadCipher(std::move(zeroRttReadCipher));
  }
  if (zeroRttHeaderCipher) {
    conn.readCodec->setZeroRttHeaderCipher(std::move(zeroRttHeaderCipher));
  }
  if (oneRttWriteHeaderCipher) {
    conn.oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher);
  }
  if (oneRttReadHeaderCipher) {
    conn.readCodec->setOneRttHeaderCipher(std::move(oneRttReadHeaderCipher));
  }

  if (oneRttWriteCipher) {
    if (conn.qLogger) {
      conn.qLogger->addTransportStateUpdate(kDerivedOneRttWriteCipher);
    }
    QUIC_TRACE(fst_trace, conn, ""derived 1-rtt write cipher"");
    CHECK(!conn.oneRttWriteCipher.get());
    conn.oneRttWriteCipher = std::move(oneRttWriteCipher);

    updatePacingOnKeyEstablished(conn);

    // We negotiate the transport parameters whenever we have the 1-RTT write
    // keys available.
    auto clientParams = handshakeLayer->getClientTransportParams();
    if (!clientParams) {
      throw QuicTransportException(
          ""No client transport params"",
          TransportErrorCode::TRANSPORT_PARAMETER_ERROR);
    }
    processClientInitialParams(conn, std::move(*clientParams));
  }
  if (oneRttReadCipher) {
    if (conn.qLogger) {
      conn.qLogger->addTransportStateUpdate(kDerivedOneRttReadCipher);
    }
    QUIC_TRACE(fst_trace, conn, ""derived 1-rtt read cipher"");
    // Clear limit because CFIN is received at this point
    conn.writableBytesLimit = folly::none;
    conn.readCodec->setOneRttReadCipher(std::move(oneRttReadCipher));
  }
  auto handshakeReadCipher = handshakeLayer->getHandshakeReadCipher();
  auto handshakeReadHeaderCipher =
      handshakeLayer->getHandshakeReadHeaderCipher();
  if (handshakeReadCipher) {
    CHECK(handshakeReadHeaderCipher);
    conn.readCodec->setHandshakeReadCipher(std::move(handshakeReadCipher));
    conn.readCodec->setHandshakeHeaderCipher(
        std::move(handshakeReadHeaderCipher));
  }
  if (handshakeLayer->isHandshakeDone()) {
    CHECK(conn.oneRttWriteCipher);
    if (conn.version != QuicVersion::MVFST_D24 && !conn.sentHandshakeDone) {
      sendSimpleFrame(conn, HandshakeDoneFrame());
      conn.sentHandshakeDone = true;
    }
  }
}",1
"bool SampleInterleavedLSScan::ParseMCU(void)
{
#if ACCUSOFT_CODE
  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.
  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();
  struct Line *line[4];
  UBYTE cx;

  //
  // If a DNL marker is present, the number of remaining lines is zero. Fix it.
  if (m_pFrame->HeightOf() == 0) {
    assert(lines == 0);
    lines = 8;
  }
  //
  // A ""MCU"" in respect to the code organization is eight lines.
  if (lines > 8) {
    lines = 8;
  }
  if (m_pFrame->HeightOf() > 0)
    m_ulRemaining[0] -= lines;
  assert(lines > 0);
  assert(m_ucCount < 4);

  //
  // Fill the line pointers.
  for(cx = 0;cx < m_ucCount;cx++) {
    line[cx] = CurrentLine(cx);
  }

  // Loop over lines and columns
  do {
    LONG length = m_ulWidth[0];
    LONG *lp[4];

    // Get the line pointers and initialize the internal backup lines.
    for(cx = 0;cx < m_ucCount;cx++) {
      lp[cx] = line[cx]->m_pData;
      StartLine(cx);
    }

    if (BeginReadMCU(m_Stream.ByteStreamOf())) { 
      // No error handling strategy. No RST in scans. Bummer!
      do {
        LONG a[4],b[4],c[4],d[4]; // neighbouring values.
        LONG d1[4],d2[4],d3[4];   // local gradients.
        bool isrun = true;
      
        for(cx = 0;cx < m_ucCount;cx++) {
          GetContext(cx,a[cx],b[cx],c[cx],d[cx]);

          d1[cx]  = d[cx] - b[cx];    // compute local gradients
          d2[cx]  = b[cx] - c[cx];
          d3[cx]  = c[cx] - a[cx];

          //
          // Run mode only if the run condition is met for all components
          if (isrun && !isRunMode(d1[cx],d2[cx],d3[cx]))
            isrun = false;
        }
        
        if (isrun) {
          LONG run = DecodeRun(length,m_lRunIndex[0]);
          //
          // Now fill the data.
          while(run) {
            // Update so that the next process gets the correct value.
            // There is one sample per component.
            for(cx = 0;cx < m_ucCount;cx++) {
              UpdateContext(cx,a[cx]);
              // And insert the value into the target line as well.
              *lp[cx]++ = a[cx] << preshift;
            }
            run--,length--;
            // As long as there are pixels on the line.
          }
          //
          // More data on the line? I.e. the run did not cover the full m_lJ samples?
          // Now decode the run interruption sample. The rtype is here always zero.
          if (length) {
            bool negative; // the sign variable
            LONG errval;   // the prediction error
            LONG merr;     // the mapped error (symbol)
            LONG rx;       // the reconstructed value
            UBYTE k;       // golomb parameter
            //
            // Decode the interrupting pixels.
            for(cx = 0;cx < m_ucCount;cx++) {
              // Get the neighbourhood.
              GetContext(cx,a[cx],b[cx],c[cx],d[cx]);
              // The prediction mode is always false, but the sign information
              // is required.
              negative = a[cx] > b[cx];
              // Get the golomb parameter for run interruption coding.
              k       = GolombParameter(false);
              // Golomb-decode the error symbol. It is always using the common
              // run index.
              merr    = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);
              // Inverse the error mapping procedure.
              errval  = InverseErrorMapping(merr,ErrorMappingOffset(false,merr != 0,k));
              // Compute the reconstructed value.
              rx      = Reconstruct(negative,b[cx],errval);
              // Update so that the next process gets the correct value.
              UpdateContext(cx,rx);
              // Fill in the value into the line
              *lp[cx]++ = rx << preshift;
              // Update the variables of the run mode.
              UpdateState(false,errval);
            }
            // Update the run index now. This is not part of
            // EncodeRun because the non-reduced run-index is
            // required for the golomb coder length limit. 
            if (m_lRunIndex[0] > 0)
              m_lRunIndex[0]--;
          } else break; // end of line.
        } else {
          UWORD ctxt;
          bool  negative; // the sign variable.
          LONG  px;       // the predicted variable.
          LONG  rx;       // the reconstructed value.
          LONG  errval;   // the error value.
          LONG  merr;     // the mapped error value.
          UBYTE k;        // the Golomb parameter.
          //
          for(cx = 0;cx < m_ucCount;cx++) {
            // Quantize the gradients.
            d1[cx]  = QuantizedGradient(d1[cx]);
            d2[cx]  = QuantizedGradient(d2[cx]);
            d3[cx]  = QuantizedGradient(d3[cx]);
            // Compute the context.
            ctxt    = Context(negative,d1[cx],d2[cx],d3[cx]); 
            // Compute the predicted value.
            px      = Predict(a[cx],b[cx],c[cx]);
            // Correct the prediction.
            px      = CorrectPrediction(ctxt,negative,px);
            // Compute the golomb parameter k from the context.
            k       = GolombParameter(ctxt);
            // Decode the error symbol.
            merr    = GolombDecode(k,m_lLimit);
            // Inverse the error symbol into an error value.
            errval  = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));
            // Update the variables.
            UpdateState(ctxt,errval);
            // Compute the reconstructed value.
            rx      = Reconstruct(negative,px,errval);
            // Update so that the next process gets the correct value.
            UpdateContext(cx,rx);
            // And insert the value into the target line as well.
            *lp[cx]++ = rx << preshift;
          }
        }
      } while(--length);
    } // No error handling here.
    //
    // Advance the line pointers.
    for(cx = 0;cx < m_ucCount;cx++) {
      EndLine(cx);
      line[cx] = line[cx]->m_pNext;
    }
    //
  } while(--lines);
  //
  // If this is the last line, gobble up all the
  // bits from bitstuffing the last byte may have left.
  // As SkipStuffing is idempotent, we can also do that
  // all the time.
  m_Stream.SkipStuffing();
#endif  
  return false;
}",1
"bool SingleComponentLSScan::ParseMCU(void)
{ 
#if ACCUSOFT_CODE
  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.
  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();
  struct Line *line     = CurrentLine(0);
  
  //
  // If a DNL marker is present, the number of remaining lines is zero. Fix it.
  if (m_pFrame->HeightOf() == 0) {
    assert(lines == 0);
    lines = 8;
  }

  assert(m_ucCount == 1);

  //
  // A ""MCU"" in respect to the code organization is eight lines.
  if (lines > 8) {
    lines = 8;
  }
  if (m_pFrame->HeightOf() > 0)
    m_ulRemaining[0] -= lines;
  
  assert(lines > 0);

  // Loop over lines and columns
  do {
    LONG length = m_ulWidth[0];
    LONG *lp    = line->m_pData;

#ifdef DEBUG_LS
    int xpos    = 0;
    static int linenumber = 0;
    printf(""\n%4d : "",++linenumber);
#endif
     
    StartLine(0);
    if (BeginReadMCU(m_Stream.ByteStreamOf())) { // No error handling strategy. No RST in scans. Bummer!
      do {
        LONG a,b,c,d;   // neighbouring values.
        LONG d1,d2,d3;  // local gradients.
      
        GetContext(0,a,b,c,d);
        d1  = d - b;    // compute local gradients
        d2  = b - c;
        d3  = c - a;
        
        if (isRunMode(d1,d2,d3)) {
          LONG run = DecodeRun(length,m_lRunIndex[0]);
          //
          // Now fill the data.
          while(run) {
            // Update so that the next process gets the correct value.
            UpdateContext(0,a);
            // And insert the value into the target line as well.
            *lp++ = a << preshift;
#ifdef DEBUG_LS
            printf(""%4d:<%2x> "",xpos++,a);
#endif
            run--,length--;
            // As long as there are pixels on the line.
          }
          //
          // More data on the line? I.e. the run did not cover the full m_lJ samples?
          // Now decode the run interruption sample.
          if (length) {
            bool negative; // the sign variable
            bool rtype;    // run interruption type
            LONG errval;   // the prediction error
            LONG merr;     // the mapped error (symbol)
            LONG rx;       // the reconstructed value
            UBYTE k;       // golomb parameter
            // Get the neighbourhood.
            GetContext(0,a,b,c,d);
            // Get the prediction mode.
            rtype  = InterruptedPredictionMode(negative,a,b);
            // Get the golomb parameter for run interruption coding.
            k      = GolombParameter(rtype);
            // Golomb-decode the error symbol.
            merr   = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);
            // Inverse the error mapping procedure.
            errval = InverseErrorMapping(merr + rtype,ErrorMappingOffset(rtype,rtype || merr,k));
            // Compute the reconstructed value.
            rx     = Reconstruct(negative,rtype?a:b,errval);
            // Update so that the next process gets the correct value.
            UpdateContext(0,rx);
            // Fill in the value into the line
            *lp    = rx << preshift;
#ifdef DEBUG_LS
            printf(""%4d:<%2x> "",xpos++,*lp);
#endif
            // Update the variables of the run mode.
            UpdateState(rtype,errval);
            // Update the run index now. This is not part of
            // EncodeRun because the non-reduced run-index is
            // required for the golomb coder length limit. 
            if (m_lRunIndex[0] > 0)
              m_lRunIndex[0]--;
          } else break; // end of line.
        } else {
          UWORD ctxt;
          bool  negative; // the sign variable.
          LONG  px;       // the predicted variable.
          LONG  rx;       // the reconstructed value.
          LONG  errval;   // the error value.
          LONG  merr;     // the mapped error value.
          UBYTE k;        // the Golomb parameter.
          // Quantize the gradients.
          d1     = QuantizedGradient(d1);
          d2     = QuantizedGradient(d2);
          d3     = QuantizedGradient(d3);
          // Compute the context.
          ctxt   = Context(negative,d1,d2,d3); 
          // Compute the predicted value.
          px     = Predict(a,b,c);
          // Correct the prediction.
          px     = CorrectPrediction(ctxt,negative,px);
          // Compute the golomb parameter k from the context.
          k      = GolombParameter(ctxt);
          // Decode the error symbol.
          merr   = GolombDecode(k,m_lLimit);
          // Inverse the error symbol into an error value.
          errval = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));
          // Update the variables.
          UpdateState(ctxt,errval);
          // Compute the reconstructed value.
          rx     = Reconstruct(negative,px,errval);
          // Update so that the next process gets the correct value.
          UpdateContext(0,rx);
          // And insert the value into the target line as well.
          *lp    = rx << preshift;
#ifdef DEBUG_LS
          printf(""%4d:<%2x> "",xpos++,*lp);
#endif
        }
      } while(++lp,--length);
    } // No error handling here.
    EndLine(0);
    line = line->m_pNext;
  } while(--lines); 
  //
  // If this is the last line, gobble up all the
  // bits from bitstuffing the last byte may have left.
  // As SkipStuffing is idempotent, we can also do that
  // all the time.
  m_Stream.SkipStuffing();
#endif  
  return false;
}",1
"static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)
{
	GF_Box *a;
	u64 totSize, mdat_end=0;
	GF_Err e = GF_OK;

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
	if (mov->single_moof_mode && mov->single_moof_state == 2) {
		return e;
	}

	/*restart from where we stopped last*/
	totSize = mov->current_top_box_start;
	if (mov->bytes_removed) {
		assert(totSize >= mov->bytes_removed);
		totSize -= mov->bytes_removed;
	}
	gf_bs_seek(mov->movieFileMap->bs, totSize);
#endif


	/*while we have some data, parse our boxes*/
	while (gf_bs_available(mov->movieFileMap->bs)) {
		*bytesMissing = 0;
#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		mov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[iso file] Parsing a top-level box at position %d\n"", mov->current_top_box_start));
#endif

		e = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);

		if (e >= 0) {

		} else if (e == GF_ISOM_INCOMPLETE_FILE) {
			/*our mdat is uncomplete, only valid for READ ONLY files...*/
			if (mov->openMode != GF_ISOM_OPEN_READ) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Incomplete MDAT while file is not read-only\n""));
				return GF_ISOM_INVALID_FILE;
			}
			if ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Incomplete file while reading for dump - aborting parsing\n""));
				break;
			}
			return e;
		} else {
			return e;
		}

		switch (a->type) {
		/*MOOV box*/
		case GF_ISOM_BOX_TYPE_MOOV:
			if (mov->moov) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate MOOV detected!\n""));
				gf_isom_box_del(a);
				return GF_ISOM_INVALID_FILE;
			}
			mov->moov = (GF_MovieBox *)a;
			mov->original_moov_offset = mov->current_top_box_start;
			/*set our pointer to the movie*/
			mov->moov->mov = mov;
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
			if (mov->moov->mvex) mov->moov->mvex->mov = mov;

#ifdef GF_ENABLE_CTRN
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				gf_isom_setup_traf_inheritance(mov);
			}
#endif

#endif
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;

			totSize += a->size;

            if (!mov->moov->mvhd) {
                GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing MovieHeaderBox\n""));
                return GF_ISOM_INVALID_FILE;
            }

            if (mov->meta) {
				gf_isom_meta_restore_items_ref(mov, mov->meta);
			}

			//dump senc info in dump mode
			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				u32 k;
				for (k=0; kmoov->trackList); k++) {
					GF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);

					if (trak->sample_encryption) {
						e = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);
						if (e) return e;
					}
				}
			} else {
				u32 k;
				for (k=0; kmoov->trackList); k++) {
					GF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);
					if (trak->Media->information->sampleTable->sampleGroups) {
						convert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);
					}
				}
			}

            if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {
                gf_isom_push_mdat_end(mov, mdat_end);
                mdat_end=0;
            }
			break;

		/*META box*/
		case GF_ISOM_BOX_TYPE_META:
			if (mov->meta) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate META detected!\n""));
				gf_isom_box_del(a);
				return GF_ISOM_INVALID_FILE;
			}
			mov->meta = (GF_MetaBox *)a;
			mov->original_meta_offset = mov->current_top_box_start;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) {
				return e;
			}
			totSize += a->size;
			gf_isom_meta_restore_items_ref(mov, mov->meta);
			break;

		/*we only keep the MDAT in READ for dump purposes*/
		case GF_ISOM_BOX_TYPE_MDAT:
			if (!mov->first_data_toplevel_offset) {
				mov->first_data_toplevel_offset = mov->current_top_box_start;
				mov->first_data_toplevel_size = a->size;
			}
			totSize += a->size;

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
			if (mov->emsgs) {
				gf_isom_box_array_del(mov->emsgs);
				mov->emsgs = NULL;
			}
#endif

			if (mov->openMode == GF_ISOM_OPEN_READ) {
				if (!mov->mdat) {
					mov->mdat = (GF_MediaDataBox *) a;
					e = gf_list_add(mov->TopBoxes, mov->mdat);
					if (e) {
						return e;
					}
				}
#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
				else if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);
#endif
				else gf_isom_box_del(a); //in other modes we don't care


				if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {
                    mdat_end = gf_bs_get_position(mov->movieFileMap->bs);
                    if (mov->moov) {
                        gf_isom_push_mdat_end(mov, mdat_end);
                        mdat_end=0;
                    }
				}
			}
			/*if we don't have any MDAT yet, create one (edit-write mode)
			We only work with one mdat, but we're puting it at the place
			of the first mdat found when opening a file for editing*/
			else if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {
				gf_isom_box_del(a);
				mov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);
				if (!mov->mdat) return GF_OUT_OF_MEM;
				e = gf_list_add(mov->TopBoxes, mov->mdat);
				if (e) {
					return e;
				}
			} else {
				gf_isom_box_del(a);
			}
			break;
		case GF_ISOM_BOX_TYPE_FTYP:
			/*ONE AND ONLY ONE FTYP*/
			if (mov->brand) {
				gf_isom_box_del(a);
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate 'ftyp' detected!\n""));
				return GF_ISOM_INVALID_FILE;
			}
			mov->brand = (GF_FileTypeBox *)a;
			totSize += a->size;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;
			break;

		case GF_ISOM_BOX_TYPE_OTYP:
			/*ONE AND ONLY ONE FTYP*/
			if (mov->otyp) {
				gf_isom_box_del(a);
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate 'otyp' detected!\n""));
				return GF_ISOM_INVALID_FILE;
			}

			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				mov->otyp = (GF_Box *)a;
				totSize += a->size;
				e = gf_list_add(mov->TopBoxes, a);
				if (e) return e;
			} else {
				GF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);
				if (brand) {
					s32 pos;
					gf_list_del_item(a->child_boxes, brand);
					pos = gf_list_del_item(mov->TopBoxes, mov->brand);
					gf_isom_box_del((GF_Box *) mov->brand);
					mov->brand = brand;
					if (pos<0) pos=0;
					gf_list_insert(mov->TopBoxes, brand, pos);
				}
				gf_isom_box_del(a);
			}
			break;

		case GF_ISOM_BOX_TYPE_PDIN:
			/*ONE AND ONLY ONE PDIN*/
			if (mov->pdin) {
				gf_isom_box_del(a);
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate 'pdin'' detected!\n""));
				return GF_ISOM_INVALID_FILE;
			}
			mov->pdin = (GF_ProgressiveDownloadBox *) a;
			totSize += a->size;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;
			break;


#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		case GF_ISOM_BOX_TYPE_STYP:
		{
			u32 brand = ((GF_FileTypeBox *)a)->majorBrand;
			switch (brand) {
			case GF_ISOM_BRAND_SISX:
			case GF_ISOM_BRAND_RISX:
			case GF_ISOM_BRAND_SSSS:
				mov->is_index_segment = GF_TRUE;
				break;
			default:
				break;
			}
		}
		/*fall-through*/

		case GF_ISOM_BOX_TYPE_SIDX:
		case GF_ISOM_BOX_TYPE_SSIX:
			if (mov->moov && !mov->first_data_toplevel_offset) {
				mov->first_data_toplevel_offset = mov->current_top_box_start;
				mov->first_data_toplevel_size = a->size;
			}
			totSize += a->size;
			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				e = gf_list_add(mov->TopBoxes, a);
				if (e) return e;
			} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)  && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)
			) {
				if (a->type==GF_ISOM_BOX_TYPE_SIDX) {
					if (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);
					mov->root_sidx = (GF_SegmentIndexBox *) a;
					mov->sidx_start_offset = mov->current_top_box_start;
					mov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);

				}
				else if (a->type==GF_ISOM_BOX_TYPE_STYP) {
					mov->styp_start_offset = mov->current_top_box_start;

					if (mov->seg_styp) gf_isom_box_del(mov->seg_styp);
					mov->seg_styp = a;
				} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {
					if (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);
					mov->seg_ssix = a;
				} else {
					gf_isom_box_del(a);
				}
				gf_isom_push_mdat_end(mov, mov->current_top_box_start);
			} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {
				if (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);
				mov->main_sidx = (GF_SegmentIndexBox *) a;
				mov->main_sidx_end_pos = mov->current_top_box_start + a->size;
			} else {
				gf_isom_box_del(a);
			}
			break;

		case GF_ISOM_BOX_TYPE_MOOF:
			//no support for inplace rewrite for fragmented files
			gf_isom_disable_inplace_rewrite(mov);
			if (!mov->moov) {
				GF_LOG(mov->moof ? GF_LOG_DEBUG : GF_LOG_WARNING, GF_LOG_CONTAINER, (""[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\n""));
			}
			if (mov->single_moof_mode) {
				mov->single_moof_state++;
				if (mov->single_moof_state > 1) {
					gf_isom_box_del(a);
					return GF_OK;
				}
			}
			((GF_MovieFragmentBox *)a)->mov = mov;

			totSize += a->size;
			mov->moof = (GF_MovieFragmentBox *) a;

			/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/
			FixTrackID(mov);
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				FixSDTPInTRAF(mov->moof);
			} else {
				u32 k;
				for (k=0; kmoof->TrackList); k++) {
					GF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);
					if (traf->sampleGroups) {
						convert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);
					}
				}
			}

			/*read & debug: store at root level*/
			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				u32 k;
				gf_list_add(mov->TopBoxes, a);
				/*also update pointers to trex for debug*/
				if (mov->moov) {
					for (k=0; kmoof->TrackList); k++) {
						GF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);
						if (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {
							GF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);
							u32 j=0;
							while ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {
								if (traf->trex->trackID == traf->tfhd->trackID) {
									if (!traf->trex->track) traf->trex->track = trak;
									break;
								}
								traf->trex = NULL;
							}
						}
						//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly
						if (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {
							GF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);
							if (trak) {
								trak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;
								e = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);
								if (e) return e;
								trak->current_traf_stsd_idx = 0;
							}
						}
					}
				} else {
					for (k=0; kmoof->TrackList); k++) {
						GF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);
						if (traf->sample_encryption) {
							e = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);
							if (e) return e;
						}
					}

				}
			} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {
				mov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;
				mov->moof = NULL;
				gf_isom_box_del(a);
			} else {
				/*merge all info*/
				e = MergeFragment((GF_MovieFragmentBox *)a, mov);
				gf_isom_box_del(a);
				if (e) return e;
			}

			//done with moov
			if (mov->root_sidx) {
				gf_isom_box_del((GF_Box *) mov->root_sidx);
				mov->root_sidx = NULL;
			}
			if (mov->root_ssix) {
				gf_isom_box_del(mov->seg_ssix);
				mov->root_ssix = NULL;
			}
			if (mov->seg_styp) {
				gf_isom_box_del(mov->seg_styp);
				mov->seg_styp = NULL;
			}
			mov->sidx_start_offset = 0;
			mov->sidx_end_offset = 0;
			mov->styp_start_offset = 0;
			break;
#endif
		case GF_ISOM_BOX_TYPE_UNKNOWN:
		{
			GF_UnknownBox *box = (GF_UnknownBox*)a;
			if (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {
				u8 *c = (u8 *) box->data;
				if ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))
					mov->is_jp2 = 1;
				gf_isom_box_del(a);
			} else {
				e = gf_list_add(mov->TopBoxes, a);
				if (e) return e;
			}
		}
		break;

		case GF_ISOM_BOX_TYPE_PRFT:
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
			if (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				//keep the last one read
				if (mov->last_producer_ref_time)
					gf_isom_box_del(a);
				else
					mov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;
				break;
			}
#endif
		//fallthrough
		case GF_ISOM_BOX_TYPE_EMSG:
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				if (!mov->emsgs) mov->emsgs = gf_list_new();
				gf_list_add(mov->emsgs, a);
				break;
			}
#endif
		case GF_ISOM_BOX_TYPE_MFRA:
		case GF_ISOM_BOX_TYPE_MFRO:
			//only keep for dump mode, otherwise we ignore these boxes and we don't want to carry them over in non-fragmented file
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				totSize += a->size;
				gf_isom_box_del(a);
				break;
			}
		default:
			totSize += a->size;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;
			break;
		}

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		/*remember where we left, in case we append an entire number of movie fragments*/
		mov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;
#endif
	}

	/*we need at least moov or meta*/
	if (!mov->moov && !mov->meta
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
	        && !mov->moof && !mov->is_index_segment
#endif
	   ) {
		return GF_ISOM_INCOMPLETE_FILE;
	}
	/*we MUST have movie header*/
	if (!gf_opts_get_bool(""core"", ""no-check"")) {
		if (mov->moov && !mov->moov->mvhd) {
			GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing MVHD in MOOV!\n""));
			return GF_ISOM_INVALID_FILE;
		}

		/*we MUST have meta handler*/
		if (mov->meta && !mov->meta->handler) {
			GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing handler in META!\n""));
			return GF_ISOM_INVALID_FILE;
		}
	}

#ifndef GPAC_DISABLE_ISOM_WRITE

	if (mov->moov) {
		/*set the default interleaving time*/
		mov->interleavingTime = mov->moov->mvhd->timeScale;

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		/*in edit mode with successfully loaded fragments, delete all fragment signaling since
		file is no longer fragmented*/
		if ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {
			gf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);
			mov->moov->mvex = NULL;
		}
#endif

	}

	//create a default mdat if none was found
	if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {
		mov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);
		if (!mov->mdat) return GF_OUT_OF_MEM;
		e = gf_list_add(mov->TopBoxes, mov->mdat);
		if (e) return e;
	}
#endif /*GPAC_DISABLE_ISOM_WRITE*/

	return GF_OK;
}",1
"  void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
    // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in
    // the step container, and return it as the output.
    const Tensor* indices;
    OP_REQUIRES_OK(ctx, ctx->input(""indices"", &indices));
    const Tensor* values;
    OP_REQUIRES_OK(ctx, ctx->input(""values"", &values));
    const Tensor* dense_shape;
    OP_REQUIRES_OK(ctx, ctx->input(""dense_shape"", &dense_shape));

    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()),
                errors::InvalidArgument(
                    ""Input indices should be a matrix but received shape "",
                    indices->shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()),
                errors::InvalidArgument(
                    ""Input values should be a vector but received shape "",
                    indices->shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()),
                errors::InvalidArgument(
                    ""Input shape should be a vector but received shape "",
                    dense_shape->shape().DebugString()));

    // We currently ensure that `sparse_tensor` is ordered in the
    // batch dimension.
    // TODO(mrry): Investigate ways to avoid this unconditional check
    // if we can be sure that the sparse tensor was produced in an
    // appropriate order (e.g. by `tf.parse_example()` or a Dataset
    // that batches elements into rows of a SparseTensor).
    int64_t previous_batch_index = -1;
    for (int64_t i = 0; i < indices->dim_size(0); ++i) {
      int64_t next_batch_index = indices->matrix()(i, 0);
      OP_REQUIRES(
          ctx, next_batch_index >= previous_batch_index,
          errors::Unimplemented(""The SparseTensor must be ordered in the batch ""
                                ""dimension; handling arbitrarily ordered input ""
                                ""is not currently supported.""));
      previous_batch_index = next_batch_index;
    }
    gtl::InlinedVector std_order(dense_shape->NumElements(), 0);
    sparse::SparseTensor tensor;
    OP_REQUIRES_OK(
        ctx, sparse::SparseTensor::Create(
                 *indices, *values, TensorShape(dense_shape->vec()),
                 std_order, &tensor));
    *output = new Dataset(ctx, std::move(tensor));
  }",1
"  void Compute(OpKernelContext* context) override {
    // Only create one, if one does not exist already. Report status for all
    // other exceptions. If one already exists, it unrefs the new one.
    // An epsilon value of zero could cause performance issues and is therefore,
    // disallowed.
    const Tensor* epsilon_t;
    OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t));
    float epsilon = epsilon_t->scalar()();
    OP_REQUIRES(
        context, epsilon > 0,
        errors::InvalidArgument(""An epsilon value of zero is not allowed.""));

    const Tensor* num_streams_t;
    OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t));
    int64_t num_streams = num_streams_t->scalar()();

    auto result =
        new QuantileStreamResource(epsilon, max_elements_, num_streams);
    auto status = CreateResource(context, HandleFromInput(context, 0), result);
    if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {
      OP_REQUIRES(context, false, status);
    }
  }",1
"CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
                                     const char *enclist, int maybechunked)
{
  struct SingleRequest *k = &data->req;

  do {
    const char *name;
    size_t namelen;

    /* Parse a single encoding name. */
    while(ISSPACE(*enclist) || *enclist == ',')
      enclist++;

    name = enclist;

    for(namelen = 0; *enclist && *enclist != ','; enclist++)
      if(!ISSPACE(*enclist))
        namelen = enclist - name + 1;

    /* Special case: chunked encoding is handled at the reader level. */
    if(maybechunked && namelen == 7 && strncasecompare(name, ""chunked"", 7)) {
      k->chunk = TRUE;             /* chunks coming our way. */
      Curl_httpchunk_init(data);   /* init our chunky engine. */
    }
    else if(namelen) {
      const struct content_encoding *encoding = find_encoding(name, namelen);
      struct contenc_writer *writer;

      if(!k->writer_stack) {
        k->writer_stack = new_unencoding_writer(data, &client_encoding, NULL);

        if(!k->writer_stack)
          return CURLE_OUT_OF_MEMORY;
      }

      if(!encoding)
        encoding = &error_encoding;  /* Defer error at stack use. */

      /* Stack the unencoding stage. */
      writer = new_unencoding_writer(data, encoding, k->writer_stack);
      if(!writer)
        return CURLE_OUT_OF_MEMORY;
      k->writer_stack = writer;
    }
  } while(*enclist);

  return CURLE_OK;
}",1
"void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,
	i64 pos)
{
	i64 pixmap_version;
	i64 pack_size;
	i64 plane_bytes;
	i64 n;

	de_dbg(c, ""additional PixMap header fields, at %d"", (int)pos);
	de_dbg_indent(c, 1);

	pixmap_version = dbuf_getu16be(f, pos+0);
	de_dbg(c, ""pixmap version: %d"", (int)pixmap_version);

	bi->packing_type = dbuf_getu16be(f, pos+2);
	de_dbg(c, ""packing type: %d"", (int)bi->packing_type);

	pack_size = dbuf_getu32be(f, pos+4);
	de_dbg(c, ""pixel data length: %d"", (int)pack_size);

	bi->hdpi = pict_read_fixed(f, pos+8);
	bi->vdpi = pict_read_fixed(f, pos+12);
	de_dbg(c, ""dpi: %.2f""DE_CHAR_TIMES""%.2f"", bi->hdpi, bi->vdpi);

	bi->pixeltype = dbuf_getu16be(f, pos+16);
	bi->pixelsize = dbuf_getu16be(f, pos+18);
	bi->cmpcount = dbuf_getu16be(f, pos+20);
	bi->cmpsize = dbuf_getu16be(f, pos+22);
	de_dbg(c, ""pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d"",
		(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);

	bi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;
	if(bi->pdwidth < bi->npwidth) {
		bi->pdwidth = bi->npwidth;
	}

	plane_bytes = dbuf_getu32be(f, pos+24);
	de_dbg(c, ""plane bytes: %d"", (int)plane_bytes);

	bi->pmTable = (u32)dbuf_getu32be(f, pos+28);
	de_dbg(c, ""pmTable: 0x%08x"", (unsigned int)bi->pmTable);

	n = dbuf_getu32be(f, pos+32);
	de_dbg(c, ""pmReserved: 0x%08x"", (unsigned int)n);

	de_dbg_indent(c, -1);
}",1
" */
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
	st_entry 			*ent1, *ent2;
	wddx_stack 			*stack = (wddx_stack *)user_data;
	HashTable 			*target_hash;
	zend_class_entry 	*pce;
	zval				obj;

/* OBJECTS_FIXME */
	if (stack->top == 0) {
		return;
	}

	if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||
		!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||
	  	!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||
		!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||
		!strcmp((char *)name, EL_DATETIME)) {
		wddx_stack_top(stack, (void**)&ent1);

		if (Z_TYPE(ent1->data) == IS_UNDEF) {
			if (stack->top > 1) {
				stack->top--;
			} else {
				stack->done = 1;
			}
			efree(ent1);
			return;
		}

		if (!strcmp((char *)name, EL_BINARY)) {
			zend_string *new_str = php_base64_decode(
				(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
			zval_ptr_dtor(&ent1->data);
			ZVAL_STR(&ent1->data, new_str);
		}

		/* Call __wakeup() method on the object. */
		if (Z_TYPE(ent1->data) == IS_OBJECT) {
			zval fname, retval;

			ZVAL_STRING(&fname, ""__wakeup"");

			call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);

			zval_ptr_dtor(&fname);
			zval_ptr_dtor(&retval);
		}

		if (stack->top > 1) {
			stack->top--;
			wddx_stack_top(stack, (void**)&ent2);

			/* if non-existent field */
			if (ent2->type == ST_FIELD && Z_ISUNDEF(ent2->data)) {
				zval_ptr_dtor(&ent1->data);
				efree(ent1);
				return;
			}

			if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {
				target_hash = HASH_OF(&ent2->data);

				if (ent1->varname) {
					if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
						Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&
						ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {
						zend_bool incomplete_class = 0;

						zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
						zend_string_forget_hash_val(Z_STR(ent1->data));
						if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {
							incomplete_class = 1;
							pce = PHP_IC_ENTRY;
						}

						/* Initialize target object */
						object_init_ex(&obj, pce);

						/* Merge current hashtable with object's default properties */
						zend_hash_merge(Z_OBJPROP(obj),
										Z_ARRVAL(ent2->data),
										zval_add_ref, 0);

						if (incomplete_class) {
							php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
						}

						/* Clean up old array entry */
						zval_ptr_dtor(&ent2->data);

						/* Set stack entry to point to the newly created object */
						ZVAL_COPY_VALUE(&ent2->data, &obj);

						/* Clean up class name var entry */
						zval_ptr_dtor(&ent1->data);
					} else if (Z_TYPE(ent2->data) == IS_OBJECT) {
						zend_class_entry *old_scope = EG(scope);

						EG(scope) = Z_OBJCE(ent2->data);
						add_property_zval(&ent2->data, ent1->varname, &ent1->data);
						if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);
						EG(scope) = old_scope;
					} else {
						zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);
					}
					efree(ent1->varname);
				} else	{
					zend_hash_next_index_insert(target_hash, &ent1->data);
				}
			}
			efree(ent1);
		} else {
			stack->done = 1;
		}
	} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {
		efree(stack->varname);
		stack->varname = NULL;
	} else if (!strcmp((char *)name, EL_FIELD)) {
		st_entry *ent;
		wddx_stack_top(stack, (void **)&ent);
		efree(ent);
		stack->top--;
	}",1
"DocumentSource::GetNextResult DocumentSourceUnionWith::doGetNext() {
    if (!_pipeline) {
        // We must have already been disposed, so we're finished.
        return GetNextResult::makeEOF();
    }

    if (_executionState == ExecutionProgress::kIteratingSource) {
        auto nextInput = pSource->getNext();
        if (!nextInput.isEOF()) {
            return nextInput;
        }
        _executionState = ExecutionProgress::kStartingSubPipeline;
        // All documents from the base collection have been returned, switch to iterating the sub-
        // pipeline by falling through below.
    }

    if (_executionState == ExecutionProgress::kStartingSubPipeline) {
        auto serializedPipe = _pipeline->serializeToBson();
        LOGV2_DEBUG(23869,
                    1,
                    ""$unionWith attaching cursor to pipeline {pipeline}"",
                    ""pipeline""_attr = serializedPipe);
        // $$SEARCH_META can be set during runtime earlier in the pipeline, and therefore must be
        // copied to the subpipeline manually.
        if (pExpCtx->variables.hasConstantValue(Variables::kSearchMetaId)) {
            _pipeline->getContext()->variables.setReservedValue(
                Variables::kSearchMetaId,
                pExpCtx->variables.getValue(Variables::kSearchMetaId, Document()),
                true);
        }
        try {
            _pipeline =
                pExpCtx->mongoProcessInterface->attachCursorSourceToPipeline(_pipeline.release());
            _executionState = ExecutionProgress::kIteratingSubPipeline;
        } catch (const ExceptionFor& e) {
            _pipeline = buildPipelineFromViewDefinition(
                pExpCtx,
                ExpressionContext::ResolvedNamespace{e->getNamespace(), e->getPipeline()},
                serializedPipe);
            LOGV2_DEBUG(4556300,
                        3,
                        ""$unionWith found view definition. ns: {ns}, pipeline: {pipeline}. New ""
                        ""$unionWith sub-pipeline: {new_pipe}"",
                        ""ns""_attr = e->getNamespace(),
                        ""pipeline""_attr = Value(e->getPipeline()),
                        ""new_pipe""_attr = _pipeline->serializeToBson());
            return doGetNext();
        }
    }

    auto res = _pipeline->getNext();
    if (res)
        return std::move(*res);

    // Record the plan summary stats after $unionWith operation is done.
    recordPlanSummaryStats(*_pipeline);

    _executionState = ExecutionProgress::kFinished;
    return GetNextResult::makeEOF();
}",1
"display_debug_names (struct dwarf_section *section, void *file)
{
  unsigned char *hdrptr = section->start;
  dwarf_vma unit_length;
  unsigned char *unit_start;
  const unsigned char *const section_end = section->start + section->size;
  unsigned char *unit_end;

  introduce (section, false);

  load_debug_section_with_follow (str, file);

  for (; hdrptr < section_end; hdrptr = unit_end)
    {
      unsigned int offset_size;
      uint16_t dwarf_version, padding;
      uint32_t comp_unit_count, local_type_unit_count, foreign_type_unit_count;
      uint64_t bucket_count, name_count, abbrev_table_size;
      uint32_t augmentation_string_size;
      unsigned int i;
      bool augmentation_printable;
      const char *augmentation_string;
      size_t total;

      unit_start = hdrptr;

      /* Get and check the length of the block.  */
      SAFE_BYTE_GET_AND_INC (unit_length, hdrptr, 4, section_end);

      if (unit_length == 0xffffffff)
	{
	  /* This section is 64-bit DWARF.  */
	  SAFE_BYTE_GET_AND_INC (unit_length, hdrptr, 8, section_end);
	  offset_size = 8;
	}
      else
	offset_size = 4;

      if (unit_length > (size_t) (section_end - hdrptr)
	  || unit_length < 2 + 2 + 4 * 7)
	{
	too_short:
	  warn (_(""Debug info is corrupted, %s header at %#lx has length %s\n""),
		section->name,
		(unsigned long) (unit_start - section->start),
		dwarf_vmatoa (""x"", unit_length));
	  return 0;
	}
      unit_end = hdrptr + unit_length;

      /* Get and check the version number.  */
      SAFE_BYTE_GET_AND_INC (dwarf_version, hdrptr, 2, unit_end);
      printf (_(""Version %ld\n""), (long) dwarf_version);

      /* Prior versions did not exist, and future versions may not be
	 backwards compatible.  */
      if (dwarf_version != 5)
	{
	  warn (_(""Only DWARF version 5 .debug_names ""
		  ""is currently supported.\n""));
	  return 0;
	}

      SAFE_BYTE_GET_AND_INC (padding, hdrptr, 2, unit_end);
      if (padding != 0)
	warn (_(""Padding field of .debug_names must be 0 (found 0x%x)\n""),
	      padding);

      SAFE_BYTE_GET_AND_INC (comp_unit_count, hdrptr, 4, unit_end);
      if (comp_unit_count == 0)
	warn (_(""Compilation unit count must be >= 1 in .debug_names\n""));

      SAFE_BYTE_GET_AND_INC (local_type_unit_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (foreign_type_unit_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (bucket_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (name_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (abbrev_table_size, hdrptr, 4, unit_end);

      SAFE_BYTE_GET_AND_INC (augmentation_string_size, hdrptr, 4, unit_end);
      if (augmentation_string_size % 4 != 0)
	{
	  warn (_(""Augmentation string length %u must be rounded up ""
		  ""to a multiple of 4 in .debug_names.\n""),
		augmentation_string_size);
	  augmentation_string_size += (-augmentation_string_size) & 3;
	}
      if (augmentation_string_size > (size_t) (unit_end - hdrptr))
	goto too_short;

      printf (_(""Augmentation string:""));

      augmentation_printable = true;
      augmentation_string = (const char *) hdrptr;

      for (i = 0; i < augmentation_string_size; i++)
	{
	  unsigned char uc;

	  SAFE_BYTE_GET_AND_INC (uc, hdrptr, 1, unit_end);
	  printf ("" %02x"", uc);

	  if (uc != 0 && !ISPRINT (uc))
	    augmentation_printable = false;
	}

      if (augmentation_printable)
	{
	  printf (""  (\"""");
	  for (i = 0;
	       i < augmentation_string_size && augmentation_string[i];
	       ++i)
	    putchar (augmentation_string[i]);
	  printf (""\"")"");
	}
      putchar ('\n');

      printf (_(""CU table:\n""));
      if (_mul_overflow (comp_unit_count, offset_size, &total)
	  || total > (size_t) (unit_end - hdrptr))
	goto too_short;
      for (i = 0; i < comp_unit_count; i++)
	{
	  uint64_t cu_offset;

	  SAFE_BYTE_GET_AND_INC (cu_offset, hdrptr, offset_size, unit_end);
	  printf (_(""[%3u] 0x%lx\n""), i, (unsigned long) cu_offset);
	}
      putchar ('\n');

      printf (_(""TU table:\n""));
      if (_mul_overflow (local_type_unit_count, offset_size, &total)
	  || total > (size_t) (unit_end - hdrptr))
	goto too_short;
      for (i = 0; i < local_type_unit_count; i++)
	{
	  uint64_t tu_offset;

	  SAFE_BYTE_GET_AND_INC (tu_offset, hdrptr, offset_size, unit_end);
	  printf (_(""[%3u] 0x%lx\n""), i, (unsigned long) tu_offset);
	}
      putchar ('\n');

      printf (_(""Foreign TU table:\n""));
      if (_mul_overflow (foreign_type_unit_count, 8, &total)
	  || total > (size_t) (unit_end - hdrptr))
	goto too_short;
      for (i = 0; i < foreign_type_unit_count; i++)
	{
	  uint64_t signature;

	  SAFE_BYTE_GET_AND_INC (signature, hdrptr, 8, unit_end);
	  printf (_(""[%3u] ""), i);
	  print_dwarf_vma (signature, 8);
	  putchar ('\n');
	}
      putchar ('\n');

      uint64_t xtra = (bucket_count * sizeof (uint32_t)
		       + name_count * (sizeof (uint32_t) + 2 * offset_size)
		       + abbrev_table_size);
      if (xtra > (size_t) (unit_end - hdrptr))
	{
	  warn (_(""Entry pool offset (0x%lx) exceeds unit size 0x%lx ""
		  ""for unit 0x%lx in the debug_names\n""),
		(long) xtra,
		(long) (unit_end - unit_start),
		(long) (unit_start - section->start));
	  return 0;
	}
      const uint32_t *const hash_table_buckets = (uint32_t *) hdrptr;
      hdrptr += bucket_count * sizeof (uint32_t);
      const uint32_t *const hash_table_hashes = (uint32_t *) hdrptr;
      hdrptr += name_count * sizeof (uint32_t);
      unsigned char *const name_table_string_offsets = hdrptr;
      hdrptr += name_count * offset_size;
      unsigned char *const name_table_entry_offsets = hdrptr;
      hdrptr += name_count * offset_size;
      unsigned char *const abbrev_table = hdrptr;
      hdrptr += abbrev_table_size;
      const unsigned char *const abbrev_table_end = hdrptr;
      unsigned char *const entry_pool = hdrptr;

      size_t buckets_filled = 0;
      size_t bucketi;
      for (bucketi = 0; bucketi < bucket_count; bucketi++)
	{
	  const uint32_t bucket = hash_table_buckets[bucketi];

	  if (bucket != 0)
	    ++buckets_filled;
	}
      printf (ngettext (""Used %zu of %lu bucket.\n"",
			""Used %zu of %lu buckets.\n"",
			bucket_count),
	      buckets_filled, (unsigned long) bucket_count);

      if (bucket_count != 0)
	{
	  uint32_t hash_prev = 0;
	  size_t hash_clash_count = 0;
	  size_t longest_clash = 0;
	  size_t this_length = 0;
	  size_t hashi;
	  for (hashi = 0; hashi < name_count; hashi++)
	    {
	      const uint32_t hash_this = hash_table_hashes[hashi];

	      if (hashi > 0)
		{
		  if (hash_prev % bucket_count == hash_this % bucket_count)
		    {
		      ++hash_clash_count;
		      ++this_length;
		      longest_clash = MAX (longest_clash, this_length);
		    }
		  else
		    this_length = 0;
		}
	      hash_prev = hash_this;
	    }
	  printf (_(""Out of %lu items there are %zu bucket clashes""
		    "" (longest of %zu entries).\n""),
		  (unsigned long) name_count, hash_clash_count, longest_clash);
	  assert (name_count == buckets_filled + hash_clash_count);
	}

      struct abbrev_lookup_entry
      {
	dwarf_vma abbrev_tag;
	unsigned char *abbrev_lookup_ptr;
      };
      struct abbrev_lookup_entry *abbrev_lookup = NULL;
      size_t abbrev_lookup_used = 0;
      size_t abbrev_lookup_allocated = 0;

      unsigned char *abbrevptr = abbrev_table;
      for (;;)
	{
	  dwarf_vma abbrev_tag;

	  READ_ULEB (abbrev_tag, abbrevptr, abbrev_table_end);
	  if (abbrev_tag == 0)
	    break;
	  if (abbrev_lookup_used == abbrev_lookup_allocated)
	    {
	      abbrev_lookup_allocated = MAX (0x100,
					     abbrev_lookup_allocated * 2);
	      abbrev_lookup = xrealloc (abbrev_lookup,
					(abbrev_lookup_allocated
					 * sizeof (*abbrev_lookup)));
	    }
	  assert (abbrev_lookup_used < abbrev_lookup_allocated);
	  struct abbrev_lookup_entry *entry;
	  for (entry = abbrev_lookup;
	       entry < abbrev_lookup + abbrev_lookup_used;
	       entry++)
	    if (entry->abbrev_tag == abbrev_tag)
	      {
		warn (_(""Duplicate abbreviation tag %lu ""
			""in unit 0x%lx in the debug_names\n""),
		      (long) abbrev_tag, (long) (unit_start - section->start));
		break;
	      }
	  entry = &abbrev_lookup[abbrev_lookup_used++];
	  entry->abbrev_tag = abbrev_tag;
	  entry->abbrev_lookup_ptr = abbrevptr;

	  /* Skip DWARF tag.  */
	  SKIP_ULEB (abbrevptr, abbrev_table_end);
	  for (;;)
	    {
	      dwarf_vma xindex, form;

	      READ_ULEB (xindex, abbrevptr, abbrev_table_end);
	      READ_ULEB (form, abbrevptr, abbrev_table_end);
	      if (xindex == 0 && form == 0)
		break;
	    }
	}

      printf (_(""\nSymbol table:\n""));
      uint32_t namei;
      for (namei = 0; namei < name_count; ++namei)
	{
	  uint64_t string_offset, entry_offset;
	  unsigned char *p;

	  p = name_table_string_offsets + namei * offset_size;
	  SAFE_BYTE_GET (string_offset, p, offset_size, unit_end);
	  p = name_table_entry_offsets + namei * offset_size;
	  SAFE_BYTE_GET (entry_offset, p, offset_size, unit_end);

	  printf (""[%3u] #%08x %s:"", namei, hash_table_hashes[namei],
		  fetch_indirect_string (string_offset));

	  unsigned char *entryptr = entry_pool + entry_offset;

	  /* We need to scan first whether there is a single or multiple
	     entries.  TAGNO is -2 for the first entry, it is -1 for the
	     initial tag read of the second entry, then it becomes 0 for the
	     first entry for real printing etc.  */
	  int tagno = -2;
	  /* Initialize it due to a false compiler warning.  */
	  dwarf_vma second_abbrev_tag = -1;
	  for (;;)
	    {
	      dwarf_vma abbrev_tag;
	      dwarf_vma dwarf_tag;
	      const struct abbrev_lookup_entry *entry;

	      READ_ULEB (abbrev_tag, entryptr, unit_end);
	      if (tagno == -1)
		{
		  second_abbrev_tag = abbrev_tag;
		  tagno = 0;
		  entryptr = entry_pool + entry_offset;
		  continue;
		}
	      if (abbrev_tag == 0)
		break;
	      if (tagno >= 0)
		printf (""%s<%lu>"",
		        (tagno == 0 && second_abbrev_tag == 0 ? "" "" : ""\n\t""),
			(unsigned long) abbrev_tag);

	      for (entry = abbrev_lookup;
		   entry < abbrev_lookup + abbrev_lookup_used;
		   entry++)
		if (entry->abbrev_tag == abbrev_tag)
		  break;
	      if (entry >= abbrev_lookup + abbrev_lookup_used)
		{
		  warn (_(""Undefined abbreviation tag %lu ""
			  ""in unit 0x%lx in the debug_names\n""),
			(long) abbrev_tag,
			(long) (unit_start - section->start));
		  break;
		}
	      abbrevptr = entry->abbrev_lookup_ptr;
	      READ_ULEB (dwarf_tag, abbrevptr, abbrev_table_end);
	      if (tagno >= 0)
		printf ("" %s"", get_TAG_name (dwarf_tag));
	      for (;;)
		{
		  dwarf_vma xindex, form;

		  READ_ULEB (xindex, abbrevptr, abbrev_table_end);
		  READ_ULEB (form, abbrevptr, abbrev_table_end);
		  if (xindex == 0 && form == 0)
		    break;

		  if (tagno >= 0)
		    printf ("" %s"", get_IDX_name (xindex));
		  entryptr = read_and_display_attr_value (0, form, 0,
							  unit_start, entryptr, unit_end,
							  0, 0, offset_size,
							  dwarf_version, NULL,
							  (tagno < 0), section,
							  NULL, '=', -1);
		}
	      ++tagno;
	    }
	  if (tagno <= 0)
	    printf (_("" ""));
	  putchar ('\n');
	}

      free (abbrev_lookup);
    }

  return 1;
}",1
"int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
		    u64 devid)
{
	struct btrfs_device *device;
	struct btrfs_fs_devices *cur_devices;
	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
	u64 num_devices;
	int ret = 0;

	mutex_lock(&uuid_mutex);

	num_devices = btrfs_num_devices(fs_info);

	ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
	if (ret)
		goto out;

	device = btrfs_find_device_by_devspec(fs_info, devid, device_path);

	if (IS_ERR(device)) {
		if (PTR_ERR(device) == -ENOENT &&
		    strcmp(device_path, ""missing"") == 0)
			ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
		else
			ret = PTR_ERR(device);
		goto out;
	}

	if (btrfs_pinned_by_swapfile(fs_info, device)) {
		btrfs_warn_in_rcu(fs_info,
		  ""cannot remove device %s (devid %llu) due to active swapfile"",
				  rcu_str_deref(device->name), device->devid);
		ret = -ETXTBSY;
		goto out;
	}

	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
		ret = BTRFS_ERROR_DEV_TGT_REPLACE;
		goto out;
	}

	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
	    fs_info->fs_devices->rw_devices == 1) {
		ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
		goto out;
	}

	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
		mutex_lock(&fs_info->chunk_mutex);
		list_del_init(&device->dev_alloc_list);
		device->fs_devices->rw_devices--;
		mutex_unlock(&fs_info->chunk_mutex);
	}

	mutex_unlock(&uuid_mutex);
	ret = btrfs_shrink_device(device, 0);
	if (!ret)
		btrfs_reada_remove_dev(device);
	mutex_lock(&uuid_mutex);
	if (ret)
		goto error_undo;

	/*
	 * TODO: the superblock still includes this device in its num_devices
	 * counter although write_all_supers() is not locked out. This
	 * could give a filesystem state which requires a degraded mount.
	 */
	ret = btrfs_rm_dev_item(device);
	if (ret)
		goto error_undo;

	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
	btrfs_scrub_cancel_dev(device);

	/*
	 * the device list mutex makes sure that we don't change
	 * the device list while someone else is writing out all
	 * the device supers. Whoever is writing all supers, should
	 * lock the device list mutex before getting the number of
	 * devices in the super block (super_copy). Conversely,
	 * whoever updates the number of devices in the super block
	 * (super_copy) should hold the device list mutex.
	 */

	/*
	 * In normal cases the cur_devices == fs_devices. But in case
	 * of deleting a seed device, the cur_devices should point to
	 * its own fs_devices listed under the fs_devices->seed.
	 */
	cur_devices = device->fs_devices;
	mutex_lock(&fs_devices->device_list_mutex);
	list_del_rcu(&device->dev_list);

	cur_devices->num_devices--;
	cur_devices->total_devices--;
	/* Update total_devices of the parent fs_devices if it's seed */
	if (cur_devices != fs_devices)
		fs_devices->total_devices--;

	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
		cur_devices->missing_devices--;

	btrfs_assign_next_active_device(device, NULL);

	if (device->bdev) {
		cur_devices->open_devices--;
		/* remove sysfs entry */
		btrfs_sysfs_remove_device(device);
	}

	num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
	btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
	mutex_unlock(&fs_devices->device_list_mutex);

	/*
	 * at this point, the device is zero sized and detached from
	 * the devices list.  All that's left is to zero out the old
	 * supers and free the device.
	 */
	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
		btrfs_scratch_superblocks(fs_info, device->bdev,
					  device->name->str);

	btrfs_close_bdev(device);
	synchronize_rcu();
	btrfs_free_device(device);

	if (cur_devices->open_devices == 0) {
		list_del_init(&cur_devices->seed_list);
		close_fs_devices(cur_devices);
		free_fs_devices(cur_devices);
	}

out:
	mutex_unlock(&uuid_mutex);
	return ret;

error_undo:
	btrfs_reada_undo_remove_dev(device);
	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
		mutex_lock(&fs_info->chunk_mutex);
		list_add(&device->dev_alloc_list,
			 &fs_devices->alloc_list);
		device->fs_devices->rw_devices++;
		mutex_unlock(&fs_info->chunk_mutex);
	}
	goto out;
}",1
"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
     ExceptionInfo *exception)
{
  char
    page_geometry[MagickPathExtent];

  Image
    *image;

  MagickBooleanType
    logging;

  volatile int
    first_mng_object,
    object_id,
    term_chunk_found,
    skip_to_iend;

  volatile ssize_t
    image_count=0;

  MagickBooleanType
    status;

  MagickOffsetType
    offset;

  MngBox
    default_fb,
    fb,
    previous_fb;

#if defined(MNG_INSERT_LAYERS)
  PixelInfo
    mng_background_color;
#endif

  register unsigned char
    *p;

  register ssize_t
    i;

  size_t
    count;

  ssize_t
    loop_level;

  volatile short
    skipping_loop;

#if defined(MNG_INSERT_LAYERS)
  unsigned int
    mandatory_back=0;
#endif

  volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
    mng_background_object=0,
#endif
    mng_type=0;   /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */

  size_t
    default_frame_timeout,
    frame_timeout,
#if defined(MNG_INSERT_LAYERS)
    image_height,
    image_width,
#endif
    length;

  /* These delays are all measured in image ticks_per_second,
   * not in MNG ticks_per_second
   */
  volatile size_t
    default_frame_delay,
    final_delay,
    final_image_delay,
    frame_delay,
#if defined(MNG_INSERT_LAYERS)
    insert_layers,
#endif
    mng_iterations=1,
    simplicity=0,
    subframe_height=0,
    subframe_width=0;

  previous_fb.top=0;
  previous_fb.bottom=0;
  previous_fb.left=0;
  previous_fb.right=0;
  default_fb.top=0;
  default_fb.bottom=0;
  default_fb.left=0;
  default_fb.right=0;

  logging=LogMagickEvent(CoderEvent,GetMagickModule(),
    ""  Enter ReadOneMNGImage()"");

  image=mng_info->image;

  if (LocaleCompare(image_info->magick,""MNG"") == 0)
    {
      char
        magic_number[MagickPathExtent];

      /* Verify MNG signature.  */
      count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
      if (memcmp(magic_number,""\212MNG\r\n\032\n"",8) != 0)
        ThrowReaderException(CorruptImageError,""ImproperImageHeader"");

      /* Initialize some nonzero members of the MngInfo structure.  */
      for (i=0; i < MNG_MAX_OBJECTS; i++)
      {
        mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
        mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
      }
      mng_info->exists[0]=MagickTrue;
    }

  skipping_loop=(-1);
  first_mng_object=MagickTrue;
  mng_type=0;
#if defined(MNG_INSERT_LAYERS)
  insert_layers=MagickFalse; /* should be False during convert or mogrify */
#endif
  default_frame_delay=0;
  default_frame_timeout=0;
  frame_delay=0;
  final_delay=1;
  mng_info->ticks_per_second=1UL*image->ticks_per_second;
  object_id=0;
  skip_to_iend=MagickFalse;
  term_chunk_found=MagickFalse;
  mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
  mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
  mng_background_color=image->background_color;
#endif
  default_fb=mng_info->frame;
  previous_fb=mng_info->frame;
  do
  {
    char
      type[MagickPathExtent];

    if (LocaleCompare(image_info->magick,""MNG"") == 0)
      {
        unsigned char
          *chunk;

        /*
          Read a new chunk.
        */
        type[0]='\0';
        (void) ConcatenateMagickString(type,""errr"",MagickPathExtent);
        length=ReadBlobMSBLong(image);
        count=(size_t) ReadBlob(image,4,(unsigned char *) type);

        if (logging != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
           ""  Reading MNG chunk type %c%c%c%c, length: %.20g"",
           type[0],type[1],type[2],type[3],(double) length);

        if (length > PNG_UINT_31_MAX)
          {
            status=MagickFalse;
            break;
          }

        if (count == 0)
          ThrowReaderException(CorruptImageError,""CorruptImage"");

        p=NULL;
        chunk=(unsigned char *) NULL;

        if (length != 0)
          {
            if (length > GetBlobSize(image))
              ThrowReaderException(CorruptImageError,
                ""InsufficientImageDataInFile"");
            chunk=(unsigned char *) AcquireQuantumMemory(length+
             MagickPathExtent,sizeof(*chunk));

            if (chunk == (unsigned char *) NULL)
              ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");

            for (i=0; i < (ssize_t) length; i++)
            {
              int
                c;

              c=ReadBlobByte(image);
              if (c == EOF)
                break;
              chunk[i]=(unsigned char) c;
            }

            p=chunk;
          }

        (void) ReadBlobMSBLong(image);  /* read crc word */

#if !defined(JNG_SUPPORTED)
        if (memcmp(type,mng_JHDR,4) == 0)
          {
            skip_to_iend=MagickTrue;

            if (mng_info->jhdr_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""JNGCompressNotSupported"",""`%s'"",image->filename);

            mng_info->jhdr_warning++;
          }
#endif
        if (memcmp(type,mng_DHDR,4) == 0)
          {
            skip_to_iend=MagickTrue;

            if (mng_info->dhdr_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""DeltaPNGNotSupported"",""`%s'"",image->filename);

            mng_info->dhdr_warning++;
          }
        if (memcmp(type,mng_MEND,4) == 0)
          break;

        if (skip_to_iend)
          {
            if (memcmp(type,mng_IEND,4) == 0)
              skip_to_iend=MagickFalse;

            if (length != 0)
              chunk=(unsigned char *) RelinquishMagickMemory(chunk);

            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""  Skip to IEND."");

            continue;
          }

        if (memcmp(type,mng_MHDR,4) == 0)
          {
            if (length != 28)
              {
                chunk=(unsigned char *) RelinquishMagickMemory(chunk);
                ThrowReaderException(CorruptImageError,""CorruptImage"");
              }

            mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
                (p[2] << 8) | p[3]);

            mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
                (p[6] << 8) | p[7]);

            if (logging != MagickFalse)
              {
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  ""  MNG width: %.20g"",(double) mng_info->mng_width);
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  ""  MNG height: %.20g"",(double) mng_info->mng_height);
              }

            p+=8;
            mng_info->ticks_per_second=(size_t) mng_get_long(p);

            if (mng_info->ticks_per_second == 0)
              default_frame_delay=0;

            else
              default_frame_delay=1UL*image->ticks_per_second/
                mng_info->ticks_per_second;

            frame_delay=default_frame_delay;
            simplicity=0;

            p+=16;
            simplicity=(size_t) mng_get_long(p);

            mng_type=1;    /* Full MNG */

            if ((simplicity != 0) && ((simplicity | 11) == 11))
              mng_type=2; /* LC */

            if ((simplicity != 0) && ((simplicity | 9) == 9))
              mng_type=3; /* VLC */

#if defined(MNG_INSERT_LAYERS)
            if (mng_type != 3)
              insert_layers=MagickTrue;
#endif
            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
              {
                /* Allocate next image structure.  */
                AcquireNextImage(image_info,image,exception);

                if (GetNextImageInList(image) == (Image *) NULL)
                  return((Image *) NULL);

                image=SyncNextImageInList(image);
                mng_info->image=image;
              }

            if ((mng_info->mng_width > 65535L) ||
                (mng_info->mng_height > 65535L))
              {
                chunk=(unsigned char *) RelinquishMagickMemory(chunk);
                ThrowReaderException(ImageError,""WidthOrHeightExceedsLimit"");
              }

            (void) FormatLocaleString(page_geometry,MagickPathExtent,
              ""%.20gx%.20g+0+0"",(double) mng_info->mng_width,(double)
              mng_info->mng_height);

            mng_info->frame.left=0;
            mng_info->frame.right=(ssize_t) mng_info->mng_width;
            mng_info->frame.top=0;
            mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
            mng_info->clip=default_fb=previous_fb=mng_info->frame;

            for (i=0; i < MNG_MAX_OBJECTS; i++)
              mng_info->object_clip[i]=mng_info->frame;

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_TERM,4) == 0)
          {
            int
              repeat=0;

            if (length != 0)
              repeat=p[0];

            if (repeat == 3)
              {
                final_delay=(png_uint_32) mng_get_long(&p[2]);
                mng_iterations=(png_uint_32) mng_get_long(&p[6]);

                if (mng_iterations == PNG_UINT_31_MAX)
                  mng_iterations=0;

                image->iterations=mng_iterations;
                term_chunk_found=MagickTrue;
              }

            if (logging != MagickFalse)
              {
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  ""    repeat=%d,  final_delay=%.20g,  iterations=%.20g"",
                  repeat,(double) final_delay, (double) image->iterations);
              }

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }
        if (memcmp(type,mng_DEFI,4) == 0)
          {
            if (mng_type == 3)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""DEFI chunk found in MNG-VLC datastream"",""`%s'"",
                image->filename);

            if (length < 2)
              {
                if (chunk)
                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);
                ThrowReaderException(CorruptImageError,""CorruptImage"");
              }

            object_id=(p[0] << 8) | p[1];

            if (mng_type == 2 && object_id != 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""Nonzero object_id in MNG-LC datastream"",""`%s'"",
                image->filename);

            if (object_id > MNG_MAX_OBJECTS)
              {
                /*
                  Instead of using a warning we should allocate a larger
                  MngInfo structure and continue.
                */
                (void) ThrowMagickException(exception,GetMagickModule(),
                  CoderError,""object id too large"",""`%s'"",image->filename);
                object_id=MNG_MAX_OBJECTS;
              }

            if (mng_info->exists[object_id])
              if (mng_info->frozen[object_id])
                {
                  chunk=(unsigned char *) RelinquishMagickMemory(chunk);
                  (void) ThrowMagickException(exception,
                    GetMagickModule(),CoderError,
                    ""DEFI cannot redefine a frozen MNG object"",""`%s'"",
                    image->filename);
                  continue;
                }

            mng_info->exists[object_id]=MagickTrue;

            if (length > 2)
              mng_info->invisible[object_id]=p[2];

            /*
              Extract object offset info.
            */
            if (length > 11)
              {
                mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
                    (p[5] << 16) | (p[6] << 8) | p[7]);

                mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
                    (p[9] << 16) | (p[10] << 8) | p[11]);

                if (logging != MagickFalse)
                  {
                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                      ""  x_off[%d]: %.20g,  y_off[%d]: %.20g"",
                      object_id,(double) mng_info->x_off[object_id],
                      object_id,(double) mng_info->y_off[object_id]);
                  }
              }

            /*
              Extract object clipping info.
            */
            if (length > 27)
              mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0,
                &p[12]);

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }
        if (memcmp(type,mng_bKGD,4) == 0)
          {
            mng_info->have_global_bkgd=MagickFalse;

            if (length > 5)
              {
                mng_info->mng_global_bkgd.red=
                  ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));

                mng_info->mng_global_bkgd.green=
                  ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));

                mng_info->mng_global_bkgd.blue=
                  ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));

                mng_info->have_global_bkgd=MagickTrue;
              }

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }
        if (memcmp(type,mng_BACK,4) == 0)
          {
#if defined(MNG_INSERT_LAYERS)
            if (length > 6)
              mandatory_back=p[6];

            else
              mandatory_back=0;

            if (mandatory_back && length > 5)
              {
                mng_background_color.red=
                    ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));

                mng_background_color.green=
                    ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));

                mng_background_color.blue=
                    ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));

                mng_background_color.alpha=OpaqueAlpha;
              }

#ifdef MNG_OBJECT_BUFFERS
            if (length > 8)
              mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_PLTE,4) == 0)
          {
            /* Read global PLTE.  */

            if (length && (length < 769))
              {
                if (mng_info->global_plte == (png_colorp) NULL)
                  mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
                    sizeof(*mng_info->global_plte));

                for (i=0; i < (ssize_t) (length/3); i++)
                {
                  mng_info->global_plte[i].red=p[3*i];
                  mng_info->global_plte[i].green=p[3*i+1];
                  mng_info->global_plte[i].blue=p[3*i+2];
                }

                mng_info->global_plte_length=(unsigned int) (length/3);
              }
#ifdef MNG_LOOSE
            for ( ; i < 256; i++)
            {
              mng_info->global_plte[i].red=i;
              mng_info->global_plte[i].green=i;
              mng_info->global_plte[i].blue=i;
            }

            if (length != 0)
              mng_info->global_plte_length=256;
#endif
            else
              mng_info->global_plte_length=0;

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_tRNS,4) == 0)
          {
            /* read global tRNS */

            if (length > 0 && length < 257)
              for (i=0; i < (ssize_t) length; i++)
                mng_info->global_trns[i]=p[i];

#ifdef MNG_LOOSE
            for ( ; i < 256; i++)
              mng_info->global_trns[i]=255;
#endif
            mng_info->global_trns_length=(unsigned int) length;
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }
        if (memcmp(type,mng_gAMA,4) == 0)
          {
            if (length == 4)
              {
                ssize_t
                  igamma;

                igamma=mng_get_long(p);
                mng_info->global_gamma=((float) igamma)*0.00001;
                mng_info->have_global_gama=MagickTrue;
              }

            else
              mng_info->have_global_gama=MagickFalse;

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_cHRM,4) == 0)
          {
            /* Read global cHRM */

            if (length == 32)
              {
                mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
                mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
                mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
                mng_info->global_chrm.red_primary.y=0.00001*
                  mng_get_long(&p[12]);
                mng_info->global_chrm.green_primary.x=0.00001*
                  mng_get_long(&p[16]);
                mng_info->global_chrm.green_primary.y=0.00001*
                  mng_get_long(&p[20]);
                mng_info->global_chrm.blue_primary.x=0.00001*
                  mng_get_long(&p[24]);
                mng_info->global_chrm.blue_primary.y=0.00001*
                  mng_get_long(&p[28]);
                mng_info->have_global_chrm=MagickTrue;
              }
            else
              mng_info->have_global_chrm=MagickFalse;

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_sRGB,4) == 0)
          {
            /*
              Read global sRGB.
            */
            if (length != 0)
              {
                mng_info->global_srgb_intent=
                  Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
                mng_info->have_global_srgb=MagickTrue;
              }
            else
              mng_info->have_global_srgb=MagickFalse;

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_iCCP,4) == 0)
          {
            /* To do: */

            /*
              Read global iCCP.
            */
            if (length != 0)
              chunk=(unsigned char *) RelinquishMagickMemory(chunk);

            continue;
          }

        if (memcmp(type,mng_FRAM,4) == 0)
          {
            if (mng_type == 3)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""FRAM chunk found in MNG-VLC datastream"",""`%s'"",
                image->filename);

            if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
              image->delay=frame_delay;

            frame_delay=default_frame_delay;
            frame_timeout=default_frame_timeout;
            fb=default_fb;

            if (length != 0)
              if (p[0])
                mng_info->framing_mode=p[0];

            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""    Framing_mode=%d"",mng_info->framing_mode);

            if (length > 6)
              {
                /* Note the delay and frame clipping boundaries.  */

                p++; /* framing mode */

                while (*p && ((p-chunk) < (ssize_t) length))
                  p++;  /* frame name */

                p++;  /* frame name terminator */

                if ((p-chunk) < (ssize_t) (length-4))
                  {
                    int
                      change_delay,
                      change_timeout,
                      change_clipping;

                    change_delay=(*p++);
                    change_timeout=(*p++);
                    change_clipping=(*p++);
                    p++; /* change_sync */

                    if (change_delay)
                      {
                        frame_delay=1UL*image->ticks_per_second*
                          mng_get_long(p);

                        if (mng_info->ticks_per_second != 0)
                          frame_delay/=mng_info->ticks_per_second;

                        else
                          frame_delay=PNG_UINT_31_MAX;

                        if (change_delay == 2)
                          default_frame_delay=frame_delay;

                        p+=4;

                        if (logging != MagickFalse)
                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            ""    Framing_delay=%.20g"",(double) frame_delay);
                      }

                    if (change_timeout)
                      {
                        frame_timeout=1UL*image->ticks_per_second*
                          mng_get_long(p);

                        if (mng_info->ticks_per_second != 0)
                          frame_timeout/=mng_info->ticks_per_second;

                        else
                          frame_timeout=PNG_UINT_31_MAX;

                        if (change_timeout == 2)
                          default_frame_timeout=frame_timeout;

                        p+=4;

                        if (logging != MagickFalse)
                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            ""    Framing_timeout=%.20g"",(double) frame_timeout);
                      }

                    if (change_clipping)
                      {
                        fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
                        p+=17;
                        previous_fb=fb;

                        if (logging != MagickFalse)
                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            ""    Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g"",
                            (double) fb.left,(double) fb.right,(double) fb.top,
                            (double) fb.bottom);

                        if (change_clipping == 2)
                          default_fb=fb;
                      }
                  }
              }
            mng_info->clip=fb;
            mng_info->clip=mng_minimum_box(fb,mng_info->frame);

            subframe_width=(size_t) (mng_info->clip.right
               -mng_info->clip.left);

            subframe_height=(size_t) (mng_info->clip.bottom
               -mng_info->clip.top);
            /*
              Insert a background layer behind the frame if framing_mode is 4.
            */
#if defined(MNG_INSERT_LAYERS)
            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""   subframe_width=%.20g, subframe_height=%.20g"",(double)
                subframe_width,(double) subframe_height);

            if (insert_layers && (mng_info->framing_mode == 4) &&
                (subframe_width) && (subframe_height))
              {
                /* Allocate next image structure.  */
                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
                  {
                    AcquireNextImage(image_info,image,exception);

                    if (GetNextImageInList(image) == (Image *) NULL)
                      return(DestroyImageList(image));

                    image=SyncNextImageInList(image);
                  }

                mng_info->image=image;

                if (term_chunk_found)
                  {
                    image->start_loop=MagickTrue;
                    image->iterations=mng_iterations;
                    term_chunk_found=MagickFalse;
                  }

                else
                    image->start_loop=MagickFalse;

                image->columns=subframe_width;
                image->rows=subframe_height;
                image->page.width=subframe_width;
                image->page.height=subframe_height;
                image->page.x=mng_info->clip.left;
                image->page.y=mng_info->clip.top;
                image->background_color=mng_background_color;
                image->alpha_trait=UndefinedPixelTrait;
                image->delay=0;
                (void) SetImageBackgroundColor(image,exception);

                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""  Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"",
                    (double) mng_info->clip.left,
                    (double) mng_info->clip.right,
                    (double) mng_info->clip.top,
                    (double) mng_info->clip.bottom);
              }
#endif
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_CLIP,4) == 0)
          {
            unsigned int
              first_object,
              last_object;

            /*
              Read CLIP.
            */
            if (length > 3)
              {
                first_object=(p[0] << 8) | p[1];
                last_object=(p[2] << 8) | p[3];
                p+=4;

                for (i=(int) first_object; i <= (int) last_object; i++)
                {
                  if (mng_info->exists[i] && !mng_info->frozen[i])
                    {
                      MngBox
                        box;

                      box=mng_info->object_clip[i];
                      if ((p-chunk) < (ssize_t) (length-17))
                        mng_info->object_clip[i]=
                           mng_read_box(box,(char) p[0],&p[1]);
                    }
                }

              }
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_SAVE,4) == 0)
          {
            for (i=1; i < MNG_MAX_OBJECTS; i++)
              if (mng_info->exists[i])
                {
                 mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
                 if (mng_info->ob[i] != (MngBuffer *) NULL)
                    mng_info->ob[i]->frozen=MagickTrue;
#endif
                }

            if (length != 0)
              chunk=(unsigned char *) RelinquishMagickMemory(chunk);

            continue;
          }

        if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
          {
            /* Read DISC or SEEK.  */

            if ((length == 0) || !memcmp(type,mng_SEEK,4))
              {
                for (i=1; i < MNG_MAX_OBJECTS; i++)
                  MngInfoDiscardObject(mng_info,i);
              }

            else
              {
                register ssize_t
                  j;

                for (j=1; j < (ssize_t) length; j+=2)
                {
                  i=p[j-1] << 8 | p[j];
                  MngInfoDiscardObject(mng_info,i);
                }
              }

            if (length != 0)
              chunk=(unsigned char *) RelinquishMagickMemory(chunk);

            continue;
          }

        if (memcmp(type,mng_MOVE,4) == 0)
          {
            size_t
              first_object,
              last_object;

            /* read MOVE */

            if (length > 3)
            {
              first_object=(p[0] << 8) | p[1];
              last_object=(p[2] << 8) | p[3];
              p+=4;

              for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
              {
                if ((i < 0) || (i >= MNG_MAX_OBJECTS))
                  continue;

                if (mng_info->exists[i] && !mng_info->frozen[i] &&
                    (p-chunk) < (ssize_t) (length-8))
                  {
                    MngPair
                      new_pair;

                    MngPair
                      old_pair;

                    old_pair.a=mng_info->x_off[i];
                    old_pair.b=mng_info->y_off[i];
                    new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
                    mng_info->x_off[i]=new_pair.a;
                    mng_info->y_off[i]=new_pair.b;
                  }
              }
            }

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_LOOP,4) == 0)
          {
            ssize_t loop_iters=1;
            if (length > 4)
              {
                loop_level=chunk[0];
                mng_info->loop_active[loop_level]=1;  /* mark loop active */

                /* Record starting point.  */
                loop_iters=mng_get_long(&chunk[1]);

                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""  LOOP level %.20g has %.20g iterations "",
                    (double) loop_level, (double) loop_iters);

                if (loop_iters == 0)
                  skipping_loop=loop_level;

                else
                  {
                    mng_info->loop_jump[loop_level]=TellBlob(image);
                    mng_info->loop_count[loop_level]=loop_iters;
                  }

                mng_info->loop_iteration[loop_level]=0;
              }
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_ENDL,4) == 0)
          {
            if (length > 0)
              {
                loop_level=chunk[0];

                if (skipping_loop > 0)
                  {
                    if (skipping_loop == loop_level)
                      {
                        /*
                          Found end of zero-iteration loop.
                        */
                        skipping_loop=(-1);
                        mng_info->loop_active[loop_level]=0;
                      }
                  }

                else
                  {
                    if (mng_info->loop_active[loop_level] == 1)
                      {
                        mng_info->loop_count[loop_level]--;
                        mng_info->loop_iteration[loop_level]++;

                        if (logging != MagickFalse)
                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                          ""  ENDL: LOOP level %.20g has %.20g remaining iters"",
                            (double) loop_level,(double)
                            mng_info->loop_count[loop_level]);

                        if (mng_info->loop_count[loop_level] != 0)
                          {
                            offset=
                              SeekBlob(image,mng_info->loop_jump[loop_level],
                              SEEK_SET);

                            if (offset < 0)
                              {
                                chunk=(unsigned char *) RelinquishMagickMemory(
                                  chunk);
                                ThrowReaderException(CorruptImageError,
                                  ""ImproperImageHeader"");
                              }
                          }

                        else
                          {
                            short
                              last_level;

                            /*
                              Finished loop.
                            */
                            mng_info->loop_active[loop_level]=0;
                            last_level=(-1);
                            for (i=0; i < loop_level; i++)
                              if (mng_info->loop_active[i] == 1)
                                last_level=(short) i;
                            loop_level=last_level;
                          }
                      }
                  }
              }

            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_CLON,4) == 0)
          {
            if (mng_info->clon_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""CLON is not implemented yet"",""`%s'"",
                image->filename);

            mng_info->clon_warning++;
          }

        if (memcmp(type,mng_MAGN,4) == 0)
          {
            png_uint_16
              magn_first,
              magn_last,
              magn_mb,
              magn_ml,
              magn_mr,
              magn_mt,
              magn_mx,
              magn_my,
              magn_methx,
              magn_methy;

            if (length > 1)
              magn_first=(p[0] << 8) | p[1];

            else
              magn_first=0;

            if (length > 3)
              magn_last=(p[2] << 8) | p[3];

            else
              magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
            if (magn_first || magn_last)
              if (mng_info->magn_warning == 0)
                {
                  (void) ThrowMagickException(exception,
                     GetMagickModule(),CoderError,
                     ""MAGN is not implemented yet for nonzero objects"",
                     ""`%s'"",image->filename);

                   mng_info->magn_warning++;
                }
#endif
            if (length > 4)
              magn_methx=p[4];

            else
              magn_methx=0;

            if (length > 6)
              magn_mx=(p[5] << 8) | p[6];

            else
              magn_mx=1;

            if (magn_mx == 0)
              magn_mx=1;

            if (length > 8)
              magn_my=(p[7] << 8) | p[8];

            else
              magn_my=magn_mx;

            if (magn_my == 0)
              magn_my=1;

            if (length > 10)
              magn_ml=(p[9] << 8) | p[10];

            else
              magn_ml=magn_mx;

            if (magn_ml == 0)
              magn_ml=1;

            if (length > 12)
              magn_mr=(p[11] << 8) | p[12];

            else
              magn_mr=magn_mx;

            if (magn_mr == 0)
              magn_mr=1;

            if (length > 14)
              magn_mt=(p[13] << 8) | p[14];

            else
              magn_mt=magn_my;

            if (magn_mt == 0)
              magn_mt=1;

            if (length > 16)
              magn_mb=(p[15] << 8) | p[16];

            else
              magn_mb=magn_my;

            if (magn_mb == 0)
              magn_mb=1;

            if (length > 17)
              magn_methy=p[17];

            else
              magn_methy=magn_methx;


            if (magn_methx > 5 || magn_methy > 5)
              if (mng_info->magn_warning == 0)
                {
                  (void) ThrowMagickException(exception,
                     GetMagickModule(),CoderError,
                     ""Unknown MAGN method in MNG datastream"",""`%s'"",
                     image->filename);

                   mng_info->magn_warning++;
                }
#ifdef MNG_OBJECT_BUFFERS
          /* Magnify existing objects in the range magn_first to magn_last */
#endif
            if (magn_first == 0 || magn_last == 0)
              {
                /* Save the magnification factors for object 0 */
                mng_info->magn_mb=magn_mb;
                mng_info->magn_ml=magn_ml;
                mng_info->magn_mr=magn_mr;
                mng_info->magn_mt=magn_mt;
                mng_info->magn_mx=magn_mx;
                mng_info->magn_my=magn_my;
                mng_info->magn_methx=magn_methx;
                mng_info->magn_methy=magn_methy;
              }
          }

        if (memcmp(type,mng_PAST,4) == 0)
          {
            if (mng_info->past_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""PAST is not implemented yet"",""`%s'"",
                image->filename);

            mng_info->past_warning++;
          }

        if (memcmp(type,mng_SHOW,4) == 0)
          {
            if (mng_info->show_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""SHOW is not implemented yet"",""`%s'"",
                image->filename);

            mng_info->show_warning++;
          }

        if (memcmp(type,mng_sBIT,4) == 0)
          {
            if (length < 4)
              mng_info->have_global_sbit=MagickFalse;

            else
              {
                mng_info->global_sbit.gray=p[0];
                mng_info->global_sbit.red=p[0];
                mng_info->global_sbit.green=p[1];
                mng_info->global_sbit.blue=p[2];
                mng_info->global_sbit.alpha=p[3];
                mng_info->have_global_sbit=MagickTrue;
             }
          }
        if (memcmp(type,mng_pHYs,4) == 0)
          {
            if (length > 8)
              {
                mng_info->global_x_pixels_per_unit=
                    (size_t) mng_get_long(p);
                mng_info->global_y_pixels_per_unit=
                    (size_t) mng_get_long(&p[4]);
                mng_info->global_phys_unit_type=p[8];
                mng_info->have_global_phys=MagickTrue;
              }

            else
              mng_info->have_global_phys=MagickFalse;
          }
        if (memcmp(type,mng_pHYg,4) == 0)
          {
            if (mng_info->phyg_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""pHYg is not implemented."",""`%s'"",image->filename);

            mng_info->phyg_warning++;
          }
        if (memcmp(type,mng_BASI,4) == 0)
          {
            skip_to_iend=MagickTrue;

            if (mng_info->basi_warning == 0)
              (void) ThrowMagickException(exception,GetMagickModule(),
                CoderError,""BASI is not implemented yet"",""`%s'"",
                image->filename);

            mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
            basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
               (p[2] << 8) | p[3]);
            basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
               (p[6] << 8) | p[7]);
            basi_color_type=p[8];
            basi_compression_method=p[9];
            basi_filter_type=p[10];
            basi_interlace_method=p[11];
            if (length > 11)
              basi_red=(p[12] << 8) & p[13];

            else
              basi_red=0;

            if (length > 13)
              basi_green=(p[14] << 8) & p[15];

            else
              basi_green=0;

            if (length > 15)
              basi_blue=(p[16] << 8) & p[17];

            else
              basi_blue=0;

            if (length > 17)
              basi_alpha=(p[18] << 8) & p[19];

            else
              {
                if (basi_sample_depth == 16)
                  basi_alpha=65535L;
                else
                  basi_alpha=255;
              }

            if (length > 19)
              basi_viewable=p[20];

            else
              basi_viewable=0;

#endif
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }

        if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
            && memcmp(type,mng_JHDR,4)
#endif
            )
          {
            /* Not an IHDR or JHDR chunk */
            if (length != 0)
              chunk=(unsigned char *) RelinquishMagickMemory(chunk);

            continue;
          }
/* Process IHDR */
        if (logging != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            ""  Processing %c%c%c%c chunk"",type[0],type[1],type[2],type[3]);

        mng_info->exists[object_id]=MagickTrue;
        mng_info->viewable[object_id]=MagickTrue;

        if (mng_info->invisible[object_id])
          {
            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""  Skipping invisible object"");

            skip_to_iend=MagickTrue;
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            continue;
          }
#if defined(MNG_INSERT_LAYERS)
        if (length < 8)
          {
            chunk=(unsigned char *) RelinquishMagickMemory(chunk);
            ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
          }

        image_width=(size_t) mng_get_long(p);
        image_height=(size_t) mng_get_long(&p[4]);
#endif
        chunk=(unsigned char *) RelinquishMagickMemory(chunk);

        /*
          Insert a transparent background layer behind the entire animation
          if it is not full screen.
        */
#if defined(MNG_INSERT_LAYERS)
        if (insert_layers && mng_type && first_mng_object)
          {
            if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
                (image_width < mng_info->mng_width) ||
                (mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
                (image_height < mng_info->mng_height) ||
                (mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
              {
                if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
                  {
                    /*
                      Allocate next image structure.
                    */
                    AcquireNextImage(image_info,image,exception);

                    if (GetNextImageInList(image) == (Image *) NULL)
                      return(DestroyImageList(image));

                    image=SyncNextImageInList(image);
                  }
                mng_info->image=image;

                if (term_chunk_found)
                  {
                    image->start_loop=MagickTrue;
                    image->iterations=mng_iterations;
                    term_chunk_found=MagickFalse;
                  }

                else
                    image->start_loop=MagickFalse;

                /* Make a background rectangle.  */

                image->delay=0;
                image->columns=mng_info->mng_width;
                image->rows=mng_info->mng_height;
                image->page.width=mng_info->mng_width;
                image->page.height=mng_info->mng_height;
                image->page.x=0;
                image->page.y=0;
                image->background_color=mng_background_color;
                (void) SetImageBackgroundColor(image,exception);
                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""  Inserted transparent background layer, W=%.20g, H=%.20g"",
                    (double) mng_info->mng_width,(double) mng_info->mng_height);
              }
          }
        /*
          Insert a background layer behind the upcoming image if
          framing_mode is 3, and we haven't already inserted one.
        */
        if (insert_layers && (mng_info->framing_mode == 3) &&
                (subframe_width) && (subframe_height) && (simplicity == 0 ||
                (simplicity & 0x08)))
          {
            if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
            {
              /*
                Allocate next image structure.
              */
              AcquireNextImage(image_info,image,exception);

              if (GetNextImageInList(image) == (Image *) NULL)
                return(DestroyImageList(image));

              image=SyncNextImageInList(image);
            }

            mng_info->image=image;

            if (term_chunk_found)
              {
                image->start_loop=MagickTrue;
                image->iterations=mng_iterations;
                term_chunk_found=MagickFalse;
              }

            else
                image->start_loop=MagickFalse;

            image->delay=0;
            image->columns=subframe_width;
            image->rows=subframe_height;
            image->page.width=subframe_width;
            image->page.height=subframe_height;
            image->page.x=mng_info->clip.left;
            image->page.y=mng_info->clip.top;
            image->background_color=mng_background_color;
            image->alpha_trait=UndefinedPixelTrait;
            (void) SetImageBackgroundColor(image,exception);

            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""  Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"",
                (double) mng_info->clip.left,(double) mng_info->clip.right,
                (double) mng_info->clip.top,(double) mng_info->clip.bottom);
          }
#endif /* MNG_INSERT_LAYERS */
        first_mng_object=MagickFalse;

        if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
          {
            /*
              Allocate next image structure.
            */
            AcquireNextImage(image_info,image,exception);

            if (GetNextImageInList(image) == (Image *) NULL)
              return(DestroyImageList(image));

            image=SyncNextImageInList(image);
          }
        mng_info->image=image;
        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
          GetBlobSize(image));

        if (status == MagickFalse)
          break;

        if (term_chunk_found)
          {
            image->start_loop=MagickTrue;
            term_chunk_found=MagickFalse;
          }

        else
            image->start_loop=MagickFalse;

        if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
          {
            image->delay=frame_delay;
            frame_delay=default_frame_delay;
          }

        else
          image->delay=0;

        image->page.width=mng_info->mng_width;
        image->page.height=mng_info->mng_height;
        image->page.x=mng_info->x_off[object_id];
        image->page.y=mng_info->y_off[object_id];
        image->iterations=mng_iterations;

        /*
          Seek back to the beginning of the IHDR or JHDR chunk's length field.
        */

        if (logging != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            ""  Seeking back to beginning of %c%c%c%c chunk"",type[0],type[1],
            type[2],type[3]);

        offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);

        if (offset < 0)
          ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
      }

    mng_info->image=image;
    mng_info->mng_type=mng_type;
    mng_info->object_id=object_id;

    if (memcmp(type,mng_IHDR,4) == 0)
      image=ReadOnePNGImage(mng_info,image_info,exception);

#if defined(JNG_SUPPORTED)
    else
      image=ReadOneJNGImage(mng_info,image_info,exception);
#endif

    if (image == (Image *) NULL)
      {
        if (logging != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            ""exit ReadJNGImage() with error"");

        return((Image *) NULL);
      }

    if (image->columns == 0 || image->rows == 0)
      {
        (void) CloseBlob(image);
        return(DestroyImageList(image));
      }

    mng_info->image=image;

    if (mng_type)
      {
        MngBox
          crop_box;

        if (mng_info->magn_methx || mng_info->magn_methy)
          {
            png_uint_32
               magnified_height,
               magnified_width;

            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""  Processing MNG MAGN chunk"");

            if (mng_info->magn_methx == 1)
              {
                magnified_width=mng_info->magn_ml;

                if (image->columns > 1)
                   magnified_width += mng_info->magn_mr;

                if (image->columns > 2)
                   magnified_width += (png_uint_32)
                      ((image->columns-2)*(mng_info->magn_mx));
              }

            else
              {
                magnified_width=(png_uint_32) image->columns;

                if (image->columns > 1)
                   magnified_width += mng_info->magn_ml-1;

                if (image->columns > 2)
                   magnified_width += mng_info->magn_mr-1;

                if (image->columns > 3)
                   magnified_width += (png_uint_32)
                      ((image->columns-3)*(mng_info->magn_mx-1));
              }

            if (mng_info->magn_methy == 1)
              {
                magnified_height=mng_info->magn_mt;

                if (image->rows > 1)
                   magnified_height += mng_info->magn_mb;

                if (image->rows > 2)
                   magnified_height += (png_uint_32)
                      ((image->rows-2)*(mng_info->magn_my));
              }

            else
              {
                magnified_height=(png_uint_32) image->rows;

                if (image->rows > 1)
                   magnified_height += mng_info->magn_mt-1;

                if (image->rows > 2)
                   magnified_height += mng_info->magn_mb-1;

                if (image->rows > 3)
                   magnified_height += (png_uint_32)
                      ((image->rows-3)*(mng_info->magn_my-1));
              }

            if (magnified_height > image->rows ||
                magnified_width > image->columns)
              {
                Image
                  *large_image;

                int
                  yy;

                Quantum
                  *next,
                  *prev;

                png_uint_16
                  magn_methx,
                  magn_methy;

                ssize_t
                  m,
                  y;

                register Quantum
                  *n,
                  *q;

                register ssize_t
                  x;

                /* Allocate next image structure.  */

                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""    Allocate magnified image"");

                AcquireNextImage(image_info,image,exception);

                if (GetNextImageInList(image) == (Image *) NULL)
                  return(DestroyImageList(image));

                large_image=SyncNextImageInList(image);

                large_image->columns=magnified_width;
                large_image->rows=magnified_height;

                magn_methx=mng_info->magn_methx;
                magn_methy=mng_info->magn_methy;

#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
                if (magn_methx != 1 || magn_methy != 1)
                  {
                  /*
                     Scale pixels to unsigned shorts to prevent
                     overflow of intermediate values of interpolations
                  */
                     for (y=0; y < (ssize_t) image->rows; y++)
                     {
                       q=GetAuthenticPixels(image,0,y,image->columns,1,
                          exception);

                       for (x=(ssize_t) image->columns-1; x >= 0; x--)
                       {
                          SetPixelRed(image,ScaleQuantumToShort(
                            GetPixelRed(image,q)),q);
                          SetPixelGreen(image,ScaleQuantumToShort(
                            GetPixelGreen(image,q)),q);
                          SetPixelBlue(image,ScaleQuantumToShort(
                            GetPixelBlue(image,q)),q);
                          SetPixelAlpha(image,ScaleQuantumToShort(
                            GetPixelAlpha(image,q)),q);
                          q+=GetPixelChannels(image);
                       }

                       if (SyncAuthenticPixels(image,exception) == MagickFalse)
                         break;
                     }
                  }
#else
#define QM Quantum
#endif

                if (image->alpha_trait != UndefinedPixelTrait)
                   (void) SetImageBackgroundColor(large_image,exception);

                else
                  {
                    large_image->background_color.alpha=OpaqueAlpha;
                    (void) SetImageBackgroundColor(large_image,exception);

                    if (magn_methx == 4)
                      magn_methx=2;

                    if (magn_methx == 5)
                      magn_methx=3;

                    if (magn_methy == 4)
                      magn_methy=2;

                    if (magn_methy == 5)
                      magn_methy=3;
                  }

                /* magnify the rows into the right side of the large image */

                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""    Magnify the rows to %.20g"",
                    (double) large_image->rows);
                m=(ssize_t) mng_info->magn_mt;
                yy=0;
                length=(size_t) GetPixelChannels(image)*image->columns;
                next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next));
                prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev));

                if ((prev == (Quantum *) NULL) ||
                    (next == (Quantum *) NULL))
                  {
                     image=DestroyImageList(image);
                     ThrowReaderException(ResourceLimitError,
                       ""MemoryAllocationFailed"");
                  }

                n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
                (void) CopyMagickMemory(next,n,length);

                for (y=0; y < (ssize_t) image->rows; y++)
                {
                  if (y == 0)
                    m=(ssize_t) mng_info->magn_mt;

                  else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
                    m=(ssize_t) mng_info->magn_mb;

                  else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
                    m=(ssize_t) mng_info->magn_mb;

                  else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
                    m=1;

                  else
                    m=(ssize_t) mng_info->magn_my;

                  n=prev;
                  prev=next;
                  next=n;

                  if (y < (ssize_t) image->rows-1)
                    {
                      n=GetAuthenticPixels(image,0,y+1,image->columns,1,
                          exception);
                      (void) CopyMagickMemory(next,n,length);
                    }

                  for (i=0; i < m; i++, yy++)
                  {
                    register Quantum
                      *pixels;

                    assert(yy < (ssize_t) large_image->rows);
                    pixels=prev;
                    n=next;
                    q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
                      1,exception);
                    q+=(large_image->columns-image->columns)*
                      GetPixelChannels(large_image);

                    for (x=(ssize_t) image->columns-1; x >= 0; x--)
                    {
                      /* To do: get color as function of indexes[x] */
                      /*
                      if (image->storage_class == PseudoClass)
                        {
                        }
                      */

                      if (magn_methy <= 1)
                        {
                          /* replicate previous */
                          SetPixelRed(large_image,GetPixelRed(image,pixels),q);
                          SetPixelGreen(large_image,GetPixelGreen(image,
                             pixels),q);
                          SetPixelBlue(large_image,GetPixelBlue(image,
                             pixels),q);
                          SetPixelAlpha(large_image,GetPixelAlpha(image,
                             pixels),q);
                        }

                      else if (magn_methy == 2 || magn_methy == 4)
                        {
                          if (i == 0)
                            {
                              SetPixelRed(large_image,GetPixelRed(image,
                                 pixels),q);
                              SetPixelGreen(large_image,GetPixelGreen(image,
                                 pixels),q);
                              SetPixelBlue(large_image,GetPixelBlue(image,
                                 pixels),q);
                              SetPixelAlpha(large_image,GetPixelAlpha(image,
                                 pixels),q);
                            }

                          else
                            {
                              /* Interpolate */
                              SetPixelRed(large_image,((QM) (((ssize_t)
                                 (2*i*(GetPixelRed(image,n)
                                 -GetPixelRed(image,pixels)+m))/
                                 ((ssize_t) (m*2))
                                 +GetPixelRed(image,pixels)))),q);
                              SetPixelGreen(large_image,((QM) (((ssize_t)
                                 (2*i*(GetPixelGreen(image,n)
                                 -GetPixelGreen(image,pixels)+m))/
                                 ((ssize_t) (m*2))
                                 +GetPixelGreen(image,pixels)))),q);
                              SetPixelBlue(large_image,((QM) (((ssize_t)
                                 (2*i*(GetPixelBlue(image,n)
                                 -GetPixelBlue(image,pixels)+m))/
                                 ((ssize_t) (m*2))
                                 +GetPixelBlue(image,pixels)))),q);

                              if (image->alpha_trait != UndefinedPixelTrait)
                                 SetPixelAlpha(large_image, ((QM) (((ssize_t)
                                    (2*i*(GetPixelAlpha(image,n)
                                    -GetPixelAlpha(image,pixels)+m))
                                    /((ssize_t) (m*2))+
                                   GetPixelAlpha(image,pixels)))),q);
                            }

                          if (magn_methy == 4)
                            {
                              /* Replicate nearest */
                              if (i <= ((m+1) << 1))
                                 SetPixelAlpha(large_image,GetPixelAlpha(image,
                                    pixels),q);
                              else
                                 SetPixelAlpha(large_image,GetPixelAlpha(image,
                                    n),q);
                            }
                        }

                      else /* if (magn_methy == 3 || magn_methy == 5) */
                        {
                          /* Replicate nearest */
                          if (i <= ((m+1) << 1))
                          {
                             SetPixelRed(large_image,GetPixelRed(image,
                                    pixels),q);
                             SetPixelGreen(large_image,GetPixelGreen(image,
                                    pixels),q);
                             SetPixelBlue(large_image,GetPixelBlue(image,
                                    pixels),q);
                             SetPixelAlpha(large_image,GetPixelAlpha(image,
                                    pixels),q);
                          }

                          else
                          {
                             SetPixelRed(large_image,GetPixelRed(image,n),q);
                             SetPixelGreen(large_image,GetPixelGreen(image,n),
                                    q);
                             SetPixelBlue(large_image,GetPixelBlue(image,n),
                                    q);
                             SetPixelAlpha(large_image,GetPixelAlpha(image,n),
                                    q);
                          }

                          if (magn_methy == 5)
                            {
                              SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i*
                                 (GetPixelAlpha(image,n)
                                 -GetPixelAlpha(image,pixels))
                                 +m))/((ssize_t) (m*2))
                                 +GetPixelAlpha(image,pixels)),q);
                            }
                        }
                      n+=GetPixelChannels(image);
                      q+=GetPixelChannels(large_image);
                      pixels+=GetPixelChannels(image);
                    } /* x */

                    if (SyncAuthenticPixels(large_image,exception) == 0)
                      break;

                  } /* i */
                } /* y */

                prev=(Quantum *) RelinquishMagickMemory(prev);
                next=(Quantum *) RelinquishMagickMemory(next);

                length=image->columns;

                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""    Delete original image"");

                DeleteImageFromList(&image);

                image=large_image;

                mng_info->image=image;

                /* magnify the columns */
                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""    Magnify the columns to %.20g"",
                    (double) image->columns);

                for (y=0; y < (ssize_t) image->rows; y++)
                {
                  register Quantum
                    *pixels;

                  q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
                  pixels=q+(image->columns-length)*GetPixelChannels(image);
                  n=pixels+GetPixelChannels(image);

                  for (x=(ssize_t) (image->columns-length);
                    x < (ssize_t) image->columns; x++)
                  {
                    /* To do: Rewrite using Get/Set***PixelChannel() */

                    if (x == (ssize_t) (image->columns-length))
                      m=(ssize_t) mng_info->magn_ml;

                    else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
                      m=(ssize_t) mng_info->magn_mr;

                    else if (magn_methx <= 1 &&
                        x == (ssize_t) image->columns-1)
                      m=(ssize_t) mng_info->magn_mr;

                    else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
                      m=1;

                    else
                      m=(ssize_t) mng_info->magn_mx;

                    for (i=0; i < m; i++)
                    {
                      if (magn_methx <= 1)
                        {
                          /* replicate previous */
                          SetPixelRed(image,GetPixelRed(image,pixels),q);
                          SetPixelGreen(image,GetPixelGreen(image,pixels),q);
                          SetPixelBlue(image,GetPixelBlue(image,pixels),q);
                          SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);
                        }

                      else if (magn_methx == 2 || magn_methx == 4)
                        {
                          if (i == 0)
                          {
                            SetPixelRed(image,GetPixelRed(image,pixels),q);
                            SetPixelGreen(image,GetPixelGreen(image,pixels),q);
                            SetPixelBlue(image,GetPixelBlue(image,pixels),q);
                            SetPixelAlpha(image,GetPixelAlpha(image,pixels),q);
                          }

                          /* To do: Rewrite using Get/Set***PixelChannel() */
                          else
                            {
                              /* Interpolate */
                              SetPixelRed(image,(QM) ((2*i*(
                                 GetPixelRed(image,n)
                                 -GetPixelRed(image,pixels))+m)
                                 /((ssize_t) (m*2))+
                                 GetPixelRed(image,pixels)),q);

                              SetPixelGreen(image,(QM) ((2*i*(
                                 GetPixelGreen(image,n)
                                 -GetPixelGreen(image,pixels))+m)
                                 /((ssize_t) (m*2))+
                                 GetPixelGreen(image,pixels)),q);

                              SetPixelBlue(image,(QM) ((2*i*(
                                 GetPixelBlue(image,n)
                                 -GetPixelBlue(image,pixels))+m)
                                 /((ssize_t) (m*2))+
                                 GetPixelBlue(image,pixels)),q);
                              if (image->alpha_trait != UndefinedPixelTrait)
                                 SetPixelAlpha(image,(QM) ((2*i*(
                                   GetPixelAlpha(image,n)
                                   -GetPixelAlpha(image,pixels))+m)
                                   /((ssize_t) (m*2))+
                                   GetPixelAlpha(image,pixels)),q);
                            }

                          if (magn_methx == 4)
                            {
                              /* Replicate nearest */
                              if (i <= ((m+1) << 1))
                              {
                                 SetPixelAlpha(image,
                                   GetPixelAlpha(image,pixels)+0,q);
                              }
                              else
                              {
                                 SetPixelAlpha(image,
                                   GetPixelAlpha(image,n)+0,q);
                              }
                            }
                        }

                      else /* if (magn_methx == 3 || magn_methx == 5) */
                        {
                          /* Replicate nearest */
                          if (i <= ((m+1) << 1))
                          {
                             SetPixelRed(image,GetPixelRed(image,pixels),q);
                             SetPixelGreen(image,GetPixelGreen(image,
                                 pixels),q);
                             SetPixelBlue(image,GetPixelBlue(image,pixels),q);
                             SetPixelAlpha(image,GetPixelAlpha(image,
                                 pixels),q);
                          }

                          else
                          {
                             SetPixelRed(image,GetPixelRed(image,n),q);
                             SetPixelGreen(image,GetPixelGreen(image,n),q);
                             SetPixelBlue(image,GetPixelBlue(image,n),q);
                             SetPixelAlpha(image,GetPixelAlpha(image,n),q);
                          }

                          if (magn_methx == 5)
                            {
                              /* Interpolate */
                              SetPixelAlpha(image,
                                 (QM) ((2*i*( GetPixelAlpha(image,n)
                                 -GetPixelAlpha(image,pixels))+m)/
                                 ((ssize_t) (m*2))
                                 +GetPixelAlpha(image,pixels)),q);
                            }
                        }
                      q+=GetPixelChannels(image);
                    }
                    n+=GetPixelChannels(image);
                  }

                  if (SyncAuthenticPixels(image,exception) == MagickFalse)
                    break;
                }
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
              if (magn_methx != 1 || magn_methy != 1)
                {
                /*
                   Rescale pixels to Quantum
                */
                   for (y=0; y < (ssize_t) image->rows; y++)
                   {
                     q=GetAuthenticPixels(image,0,y,image->columns,1,
                       exception);

                     for (x=(ssize_t) image->columns-1; x >= 0; x--)
                     {
                        SetPixelRed(image,ScaleShortToQuantum(
                          GetPixelRed(image,q)),q);
                        SetPixelGreen(image,ScaleShortToQuantum(
                          GetPixelGreen(image,q)),q);
                        SetPixelBlue(image,ScaleShortToQuantum(
                          GetPixelBlue(image,q)),q);
                        SetPixelAlpha(image,ScaleShortToQuantum(
                          GetPixelAlpha(image,q)),q);
                        q+=GetPixelChannels(image);
                     }

                     if (SyncAuthenticPixels(image,exception) == MagickFalse)
                       break;
                   }
                }
#endif
                if (logging != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    ""  Finished MAGN processing"");
              }
          }

        /*
          Crop_box is with respect to the upper left corner of the MNG.
        */
        crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
        crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
        crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
        crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
        crop_box=mng_minimum_box(crop_box,mng_info->clip);
        crop_box=mng_minimum_box(crop_box,mng_info->frame);
        crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
        if ((crop_box.left != (mng_info->image_box.left
            +mng_info->x_off[object_id])) ||
            (crop_box.right != (mng_info->image_box.right
            +mng_info->x_off[object_id])) ||
            (crop_box.top != (mng_info->image_box.top
            +mng_info->y_off[object_id])) ||
            (crop_box.bottom != (mng_info->image_box.bottom
            +mng_info->y_off[object_id])))
          {
            if (logging != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                ""  Crop the PNG image"");

            if ((crop_box.left < crop_box.right) &&
                (crop_box.top < crop_box.bottom))
              {
                Image
                  *im;

                RectangleInfo
                  crop_info;

                /*
                  Crop_info is with respect to the upper left corner of
                  the image.
                */
                crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
                crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
                crop_info.width=(size_t) (crop_box.right-crop_box.left);
                crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
                image->page.width=image->columns;
                image->page.height=image->rows;
                image->page.x=0;
                image->page.y=0;
                im=CropImage(image,&crop_info,exception);

                if (im != (Image *) NULL)
                  {
                    image->columns=im->columns;
                    image->rows=im->rows;
                    im=DestroyImage(im);
                    image->page.width=image->columns;
                    image->page.height=image->rows;
                    image->page.x=crop_box.left;
                    image->page.y=crop_box.top;
                  }
              }

            else
              {
                /*
                  No pixels in crop area.  The MNG spec still requires
                  a layer, though, so make a single transparent pixel in
                  the top left corner.
                */
                image->columns=1;
                image->rows=1;
                image->colors=2;
                (void) SetImageBackgroundColor(image,exception);
                image->page.width=1;
                image->page.height=1;
                image->page.x=0;
                image->page.y=0;
              }
          }
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
        image=mng_info->image;
#endif
      }

#if (MAGICKCORE_QUANTUM_DEPTH > 16)
      /* PNG does not handle depths greater than 16 so reduce it even
       * if lossy.
       */
      if (image->depth > 16)
         image->depth=16;
#endif

#if (MAGICKCORE_QUANTUM_DEPTH > 8)
      if (image->depth > 8)
        {
          /* To do: fill low byte properly */
          image->depth=16;
        }

      if (LosslessReduceDepthOK(image,exception) != MagickFalse)
         image->depth = 8;
#endif

      if (image_info->number_scenes != 0)
        {
          if (mng_info->scenes_found >
             (ssize_t) (image_info->first_scene+image_info->number_scenes))
            break;
        }

      if (logging != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          ""  Finished reading image datastream."");

  } while (LocaleCompare(image_info->magick,""MNG"") == 0);

  (void) CloseBlob(image);

  if (logging != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      ""  Finished reading all image datastreams."");

#if defined(MNG_INSERT_LAYERS)
  if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
       (mng_info->mng_height))
    {
      /*
        Insert a background layer if nothing else was found.
      */
      if (logging != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          ""  No images found.  Inserting a background layer."");

      if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
        {
          /*
            Allocate next image structure.
          */
          AcquireNextImage(image_info,image,exception);
          if (GetNextImageInList(image) == (Image *) NULL)
            {
              if (logging != MagickFalse)
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  ""  Allocation failed, returning NULL."");

              return(DestroyImageList(image));;
            }
          image=SyncNextImageInList(image);
        }
      image->columns=mng_info->mng_width;
      image->rows=mng_info->mng_height;
      image->page.width=mng_info->mng_width;
      image->page.height=mng_info->mng_height;
      image->page.x=0;
      image->page.y=0;
      image->background_color=mng_background_color;
      image->alpha_trait=UndefinedPixelTrait;

      if (image_info->ping == MagickFalse)
        (void) SetImageBackgroundColor(image,exception);

      mng_info->image_found++;
    }
#endif
  image->iterations=mng_iterations;

  if (mng_iterations == 1)
    image->start_loop=MagickTrue;

  while (GetPreviousImageInList(image) != (Image *) NULL)
  {
    image_count++;
    if (image_count > 10*mng_info->image_found)
      {
        if (logging != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),""  No beginning"");

        (void) ThrowMagickException(exception,GetMagickModule(),
          CoderError,""Linked list is corrupted, beginning of list not found"",
          ""`%s'"",image_info->filename);

        return(DestroyImageList(image));
      }

    image=GetPreviousImageInList(image);

    if (GetNextImageInList(image) == (Image *) NULL)
      {
        if (logging != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),""  Corrupt list"");

        (void) ThrowMagickException(exception,GetMagickModule(),
          CoderError,""Linked list is corrupted; next_image is NULL"",""`%s'"",
          image_info->filename);
      }
  }

  if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
             GetNextImageInList(image) ==
     (Image *) NULL)
    {
      if (logging != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            ""  First image null"");

      (void) ThrowMagickException(exception,GetMagickModule(),
        CoderError,""image->next for first image is NULL but shouldn't be."",
        ""`%s'"",image_info->filename);
    }

  if (mng_info->image_found == 0)
    {
      if (logging != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          ""  No visible images found."");

      (void) ThrowMagickException(exception,GetMagickModule(),
        CoderError,""No visible images in file"",""`%s'"",image_info->filename);

      return(DestroyImageList(image));
    }

  if (mng_info->ticks_per_second)
    final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
            final_delay/mng_info->ticks_per_second;

  else
    image->start_loop=MagickTrue;

  /* Find final nonzero image delay */
  final_image_delay=0;

  while (GetNextImageInList(image) != (Image *) NULL)
    {
      if (image->delay)
        final_image_delay=image->delay;

      image=GetNextImageInList(image);
    }

  if (final_delay < final_image_delay)
    final_delay=final_image_delay;

  image->delay=final_delay;

  if (logging != MagickFalse)
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        ""  image->delay=%.20g, final_delay=%.20g"",(double) image->delay,
        (double) final_delay);

  if (logging != MagickFalse)
    {
      int
        scene;

      scene=0;
      image=GetFirstImageInList(image);

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        ""  Before coalesce:"");

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        ""    scene 0 delay=%.20g"",(double) image->delay);

      while (GetNextImageInList(image) != (Image *) NULL)
      {
        image=GetNextImageInList(image);
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          ""    scene %.20g delay=%.20g"",(double) scene++,
          (double) image->delay);
      }
    }

  image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
  if (insert_layers)
    {
      Image
        *next_image,
        *next;

      size_t
        scene;

      if (logging != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          ""  Coalesce Images"");

      scene=image->scene;
      next_image=CoalesceImages(image,exception);

      if (next_image == (Image *) NULL)
        ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");

      image=DestroyImageList(image);
      image=next_image;

      for (next=image; next != (Image *) NULL; next=next_image)
      {
         next->page.width=mng_info->mng_width;
         next->page.height=mng_info->mng_height;
         next->page.x=0;
         next->page.y=0;
         next->scene=scene++;
         next_image=GetNextImageInList(next);

         if (next_image == (Image *) NULL)
           break;

         if (next->delay == 0)
           {
             scene--;
             next_image->previous=GetPreviousImageInList(next);
             if (GetPreviousImageInList(next) == (Image *) NULL)
               image=next_image;
             else
               next->previous->next=next_image;
             next=DestroyImage(next);
           }
      }
    }
#endif

  while (GetNextImageInList(image) != (Image *) NULL)
      image=GetNextImageInList(image);

  image->dispose=BackgroundDispose;

  if (logging != MagickFalse)
    {
      int
        scene;

      scene=0;
      image=GetFirstImageInList(image);

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        ""  After coalesce:"");

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        ""    scene 0 delay=%.20g dispose=%.20g"",(double) image->delay,
        (double) image->dispose);

      while (GetNextImageInList(image) != (Image *) NULL)
      {
        image=GetNextImageInList(image);

        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          ""    scene %.20g delay=%.20g dispose=%.20g"",(double) scene++,
          (double) image->delay,(double) image->dispose);
      }
   }

  if (logging != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      ""  exit ReadOneMNGImage();"");

  return(image);
}",1
"struct torture_suite *torture_raw_write(TALLOC_CTX *mem_ctx)
{
	struct torture_suite *suite = torture_suite_create(mem_ctx, ""write"");

	torture_suite_add_1smb_test(suite, ""write"", test_write);
	torture_suite_add_1smb_test(suite, ""write unlock"", test_writeunlock);
	torture_suite_add_1smb_test(suite, ""write close"", test_writeclose);
	torture_suite_add_1smb_test(suite, ""writex"", test_writex);

	return suite;
}",1
"static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool,
			       const pj_uint8_t *pkt, const pj_uint8_t *start,
			       const pj_uint8_t *max, int *parsed_len)
{
    const pj_uint8_t *p = start;
    int name_len, name_part_len;
    pj_status_t status;

    /* Get the length of the name */
    status = get_name_len(0, pkt, start, max, &name_part_len, &name_len);
    if (status != PJ_SUCCESS)
	return status;

    /* Allocate memory for the name */
    q->name.ptr = (char*) pj_pool_alloc(pool, name_len+4);
    q->name.slen = 0;

    /* Get the name */
    status = get_name(0, pkt, start, max, &q->name);
    if (status != PJ_SUCCESS)
	return status;

    p = (start + name_part_len);

    /* Get the type */
    pj_memcpy(&q->type, p, 2);
    q->type = pj_ntohs(q->type);
    p += 2;

    /* Get the class */
    pj_memcpy(&q->dnsclass, p, 2);
    q->dnsclass = pj_ntohs(q->dnsclass);
    p += 2;

    *parsed_len = (int)(p - start);

    return PJ_SUCCESS;
}",1
"  void Compute(OpKernelContext* ctx) override {
    const Tensor* hypothesis_indices;
    const Tensor* hypothesis_values;
    const Tensor* hypothesis_shape;
    const Tensor* truth_indices;
    const Tensor* truth_values;
    const Tensor* truth_shape;
    OP_REQUIRES_OK(ctx, ctx->input(""hypothesis_indices"", &hypothesis_indices));
    OP_REQUIRES_OK(ctx, ctx->input(""hypothesis_values"", &hypothesis_values));
    OP_REQUIRES_OK(ctx, ctx->input(""hypothesis_shape"", &hypothesis_shape));
    OP_REQUIRES_OK(ctx, ctx->input(""truth_indices"", &truth_indices));
    OP_REQUIRES_OK(ctx, ctx->input(""truth_values"", &truth_values));
    OP_REQUIRES_OK(ctx, ctx->input(""truth_shape"", &truth_shape));

    OP_REQUIRES_OK(
        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,
                            *hypothesis_shape, *truth_indices, *truth_values,
                            *truth_shape));

    TensorShape hypothesis_st_shape;
    OP_REQUIRES_OK(ctx,
                   TensorShapeUtils::MakeShape(
                       hypothesis_shape->vec().data(),
                       hypothesis_shape->NumElements(), &hypothesis_st_shape));
    TensorShape truth_st_shape;
    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(
                            truth_shape->vec().data(),
                            truth_shape->NumElements(), &truth_st_shape));

    // Assume indices are sorted in row-major order.
    std::vector sorted_order(truth_st_shape.dims());
    std::iota(sorted_order.begin(), sorted_order.end(), 0);

    sparse::SparseTensor hypothesis;
    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(
                            *hypothesis_indices, *hypothesis_values,
                            hypothesis_st_shape, sorted_order, &hypothesis));

    sparse::SparseTensor truth;
    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(
                            *truth_indices, *truth_values, truth_st_shape,
                            sorted_order, &truth));

    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed
    // to store the variable length sequences.
    std::vector group_dims(truth_st_shape.dims() - 1);
    std::iota(group_dims.begin(), group_dims.end(), 0);

    TensorShape output_shape;
    for (int d = 0; d < static_cast(group_dims.size()); ++d) {
      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),
                                   truth_st_shape.dim_size(d)));
    }
    const auto output_elements = output_shape.num_elements();
    OP_REQUIRES(
        ctx, output_elements > 0,
        errors::InvalidArgument(""Got output shape "", output_shape.DebugString(),
                                "" which has 0 elements""));

    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(""output"", output_shape, &output));
    auto output_t = output->flat();
    output_t.setZero();

    std::vector output_strides(output_shape.dims());
    output_strides[output_shape.dims() - 1] = 1;
    for (int d = output_shape.dims() - 2; d >= 0; --d) {
      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);
    }

    auto hypothesis_grouper = hypothesis.group(group_dims);
    auto truth_grouper = truth.group(group_dims);

    auto hypothesis_iter = hypothesis_grouper.begin();
    auto truth_iter = truth_grouper.begin();

    auto cmp = std::equal_to();

    while (hypothesis_iter != hypothesis_grouper.end() &&
           truth_iter != truth_grouper.end()) {
      sparse::Group truth_i = *truth_iter;
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector g_truth = truth_i.group();
      std::vector g_hypothesis = hypothesis_j.group();
      auto truth_seq = truth_i.values();
      auto hypothesis_seq = hypothesis_j.values();

      if (g_truth == g_hypothesis) {
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), int64_t{0});
        OP_REQUIRES(
            ctx, loc < output_elements,
            errors::Internal(""Got an inner product "", loc,
                             "" which would require in writing to outside of ""
                             ""the buffer for the output tensor (max elements "",
                             output_elements, "")""));
        output_t(loc) =
            gtl::LevenshteinDistance(truth_seq, hypothesis_seq, cmp);
        if (normalize_) output_t(loc) /= truth_seq.size();

        ++hypothesis_iter;
        ++truth_iter;
      } else if (g_truth > g_hypothesis) {  // zero-length truth
        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                      output_strides.begin(), int64_t{0});
        OP_REQUIRES(
            ctx, loc < output_elements,
            errors::Internal(""Got an inner product "", loc,
                             "" which would require in writing to outside of ""
                             ""the buffer for the output tensor (max elements "",
                             output_elements, "")""));
        output_t(loc) = hypothesis_seq.size();
        if (normalize_ && output_t(loc) != 0.0f) {
          output_t(loc) = std::numeric_limits::infinity();
        }
        ++hypothesis_iter;
      } else {  // zero-length hypothesis
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), int64_t{0});
        OP_REQUIRES(
            ctx, loc < output_elements,
            errors::Internal(""Got an inner product "", loc,
                             "" which would require in writing to outside of ""
                             ""the buffer for the output tensor (max elements "",
                             output_elements, "")""));
        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
        ++truth_iter;
      }
    }
    while (hypothesis_iter != hypothesis_grouper.end()) {  // zero-length truths
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector g_hypothesis = hypothesis_j.group();
      auto hypothesis_seq = hypothesis_j.values();
      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                    output_strides.begin(), int64_t{0});
      OP_REQUIRES(
          ctx, loc < output_elements,
          errors::Internal(""Got an inner product "", loc,
                           "" which would require in writing to outside of the ""
                           ""buffer for the output tensor (max elements "",
                           output_elements, "")""));
      output_t(loc) = hypothesis_seq.size();
      if (normalize_ && output_t(loc) != 0.0f) {
        output_t(loc) = std::numeric_limits::infinity();
      }
      ++hypothesis_iter;
    }
    while (truth_iter != truth_grouper.end()) {  // missing hypotheses
      sparse::Group truth_i = *truth_iter;
      std::vector g_truth = truth_i.group();
      auto truth_seq = truth_i.values();
      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                    output_strides.begin(), int64_t{0});
      OP_REQUIRES(
          ctx, loc < output_elements,
          errors::Internal(""Got an inner product "", loc,
                           "" which would require in writing to outside of the ""
                           ""buffer for the output tensor (max elements "",
                           output_elements, "")""));
      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
      ++truth_iter;
    }
  }",1
"GF_Err diST_box_read(GF_Box *s, GF_BitStream *bs)
{
	u32 i;
	char str[1024];
	GF_DIMSScriptTypesBox *p = (GF_DIMSScriptTypesBox *)s;

	i=0;
	str[0]=0;
	while (1) {
		str[i] = gf_bs_read_u8(bs);
		if (!str[i]) break;
		i++;
	}
	ISOM_DECREASE_SIZE(p, i);

	p->content_script_types = gf_strdup(str);
	return GF_OK;
}",1
"void TensorSliceReader::LoadShard(int shard) const {
  CHECK_LT(shard, sss_.size());
  if (sss_[shard] || !status_.ok()) {
    return;  // Already loaded, or invalid.
  }
  string value;
  SavedTensorSlices sts;
  const string fname = fnames_[shard];
  VLOG(1) << ""Reading meta data from file "" << fname << ""..."";
  Table* table;
  Status s = open_function_(fname, &table);
  if (!s.ok()) {
    status_ = errors::DataLoss(""Unable to open table file "", fname, "": "",
                               s.ToString());
    return;
  }
  sss_[shard].reset(table);
  if (!(table->Get(kSavedTensorSlicesKey, &value) &&
        ParseProtoUnlimited(&sts, value))) {
    status_ = errors::Internal(
        ""Failed to find the saved tensor slices at the beginning of the ""
        ""checkpoint file: "",
        fname);
    return;
  }
  status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,
                          TF_CHECKPOINT_VERSION_MIN_PRODUCER, ""Checkpoint"",
                          ""checkpoint"");
  if (!status_.ok()) return;
  for (const SavedSliceMeta& ssm : sts.meta().tensor()) {
    TensorShape ssm_shape(ssm.shape());
    for (const TensorSliceProto& tsp : ssm.slice()) {
      TensorSlice ss_slice(tsp);
      status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,
                                    ss_slice, &tensors_);
      if (!status_.ok()) return;
    }
  }
}",1
"static int acurite_00275rm_decode(r_device *decoder, bitbuffer_t *bitbuffer)
{
    int result = 0;
    bitbuffer_invert(bitbuffer);

    // This sensor repeats a signal three times. Combine as fallback.
    uint8_t *b_rows[3] = {0};
    int n_rows         = 0;
    for (int row = 0; row < bitbuffer->num_rows; ++row) {
        if (n_rows < 3 && bitbuffer->bits_per_row[row] == 88) {
            b_rows[n_rows] = bitbuffer->bb[row];
            n_rows++;
        }
    }

    // Combine signal if exactly three repeats were found
    if (n_rows == 3) {
        uint8_t *b = bitbuffer->bb[bitbuffer->num_rows];
        for (int i = 0; i < 11; ++i) {
            // The majority bit count wins
            b[i] = (b_rows[0][i] & b_rows[1][i]) |
                    (b_rows[1][i] & b_rows[2][i]) |
                    (b_rows[2][i] & b_rows[0][i]);
        }
        bitbuffer->bits_per_row[bitbuffer->num_rows] = 88;
        bitbuffer->num_rows += 1;
    }

    // Output the first valid row
    for (int row = 0; row < bitbuffer->num_rows; ++row) {
        if (bitbuffer->bits_per_row[row] != 88) {
            result = DECODE_ABORT_LENGTH;
            continue; // return DECODE_ABORT_LENGTH;
        }
        uint8_t *b = bitbuffer->bb[row];

        // Check CRC
        if (crc16lsb(b, 11, 0x00b2, 0x00d0) != 0) {
            decoder_log_bitrow(decoder, 1, __func__, b, 11 * 8, ""sensor bad CRC"");
            result = DECODE_FAIL_MIC;
            continue; // return DECODE_FAIL_MIC;
        }

        //  Decode common fields
        int id          = (b[0] << 16) | (b[1] << 8) | b[3];
        int battery_low = (b[2] & 0x40) == 0;
        int model_flag  = (b[2] & 1);
        float tempc     = ((b[4] << 4) | (b[5] >> 4)) * 0.1 - 100;
        int probe       = b[5] & 3;
        int humidity    = ((b[6] & 0x1f) << 2) | (b[7] >> 6);

        //  Water probe (detects water leak)
        int water = (b[7] & 0x0f) == 15; // valid only if (probe == 1)
        //  Soil probe (detects temperature)
        float ptempc = (((b[7] & 0x0f) << 8) | b[8]) * 0.1 - 100; // valid only if (probe == 2 || probe == 3)
        //  Spot probe (detects temperature and humidity)
        int phumidity = b[9] & 0x7f; // valid only if (probe == 3)

        /* clang-format off */
        data_t *data = data_make(
                ""model"",            """",             DATA_STRING,    model_flag ? ""Acurite-00275rm"" : ""Acurite-00276rm"",
                ""subtype"",          ""Probe"",        DATA_INT,       probe,
                ""id"",               """",             DATA_INT,       id,
                ""battery_ok"",       ""Battery"",      DATA_INT,       !battery_low,
                ""temperature_C"",    ""Celsius"",      DATA_FORMAT,    ""%.1f C"",  DATA_DOUBLE, tempc,
                ""humidity"",         ""Humidity"",     DATA_FORMAT,    ""%u %%"", DATA_INT,      humidity,
                ""water"",            """",             DATA_COND, probe == 1, DATA_INT,        water,
                ""temperature_1_C"",  ""Celsius"",      DATA_COND, probe == 2, DATA_FORMAT, ""%.1f C"",   DATA_DOUBLE, ptempc,
                ""temperature_1_C"",  ""Celsius"",      DATA_COND, probe == 3, DATA_FORMAT, ""%.1f C"",   DATA_DOUBLE, ptempc,
                ""humidity_1"",       ""Humidity"",     DATA_COND, probe == 3, DATA_FORMAT, ""%u %%"",    DATA_INT,    phumidity,
                ""mic"",              ""Integrity"",    DATA_STRING,    ""CRC"",
                NULL);
        /* clang-format on */

        decoder_output_data(decoder, data);

        return 1;
    }
    // Only returns the latest result, but better than nothing.
    return result;
}",1
"lsquic_qeh_settings (struct qpack_enc_hdl *qeh, unsigned max_table_size,
             unsigned dyn_table_size, unsigned max_risked_streams, int server)
{
    enum lsqpack_enc_opts enc_opts;

    assert(qeh->qeh_flags & QEH_INITIALIZED);

    if (qeh->qeh_flags & QEH_HAVE_SETTINGS)
    {
        LSQ_WARN(""settings already set"");
        return -1;
    }

    enc_opts = LSQPACK_ENC_OPT_STAGE_2
             | (server ? LSQPACK_ENC_OPT_SERVER : 0);
    qeh->qeh_tsu_sz = sizeof(qeh->qeh_tsu_buf);
    if (0 != lsqpack_enc_init(&qeh->qeh_encoder, (void *) qeh->qeh_conn,
                max_table_size, dyn_table_size, max_risked_streams, enc_opts,
                qeh->qeh_tsu_buf, &qeh->qeh_tsu_sz))
    {
        LSQ_INFO(""could not initialize QPACK encoder"");
        return -1;
    }
    LSQ_DEBUG(""%zu-byte post-init TSU"", qeh->qeh_tsu_sz);
    qeh->qeh_flags |= QEH_HAVE_SETTINGS;
    qeh->qeh_max_prefix_size =
                        lsqpack_enc_header_block_prefix_size(&qeh->qeh_encoder);
    LSQ_DEBUG(""have settings: max table size=%u; dyn table size=%u; max risked ""
        ""streams=%u"", max_table_size, dyn_table_size, max_risked_streams);
    if (qeh->qeh_enc_sm_out)
        qeh_begin_out(qeh);
    return 0;
}",1
"int digest_generic_verify(struct digest *d, const unsigned char *md)
{
	int ret;
	int len = digest_length(d);
	unsigned char *tmp;

	tmp = xmalloc(len);

	ret = digest_final(d, tmp);
	if (ret)
		goto end;

	ret = memcmp(md, tmp, len);
	ret = ret ? -EINVAL : 0;
end:
	free(tmp);
	return ret;
}",1
"njs_function_prototype_apply(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
    njs_index_t unused)
{
    int64_t         i, length;
    njs_int_t       ret;
    njs_frame_t     *frame;
    njs_value_t     *this, *arr_like;
    njs_array_t     *arr;
    njs_function_t  *func;

    if (!njs_is_function(njs_argument(args, 0))) {
        njs_type_error(vm, ""\""this\"" argument is not a function"");
        return NJS_ERROR;
    }

    func = njs_function(njs_argument(args, 0));
    this = njs_arg(args, nargs, 1);
    arr_like = njs_arg(args, nargs, 2);

    if (njs_is_null_or_undefined(arr_like)) {
        length = 0;

        goto activate;

    } else if (njs_is_array(arr_like)) {
        arr = arr_like->data.u.array;

        args = arr->start;
        length = arr->length;

        goto activate;

    } else if (njs_slow_path(!njs_is_object(arr_like))) {
        njs_type_error(vm, ""second argument is not an array-like object"");
        return NJS_ERROR;
    }

    ret = njs_object_length(vm, arr_like, &length);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    arr = njs_array_alloc(vm, 1, length, NJS_ARRAY_SPARE);
    if (njs_slow_path(arr == NULL)) {
        return NJS_ERROR;
    }

    args = arr->start;

    for (i = 0; i < length; i++) {
        ret = njs_value_property_i64(vm, arr_like, i, &args[i]);
        if (njs_slow_path(ret == NJS_ERROR)) {
            return ret;
        }
    }

activate:

    /* Skip the ""apply"" method frame. */
    vm->top_frame->skip = 1;

    frame = (njs_frame_t *) vm->top_frame;

    ret = njs_function_frame(vm, func, this, args, length, 0);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    ret = njs_function_frame_invoke(vm, frame->native.retval);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    return NJS_DECLINED;
}",1
"static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
			  struct bpf_call_arg_meta *meta,
			  const struct bpf_func_proto *fn)
{
	u32 regno = BPF_REG_1 + arg;
	struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
	enum bpf_arg_type arg_type = fn->arg_type[arg];
	enum bpf_reg_type type = reg->type;
	int err = 0;

	if (arg_type == ARG_DONTCARE)
		return 0;

	err = check_reg_arg(env, regno, SRC_OP);
	if (err)
		return err;

	if (arg_type == ARG_ANYTHING) {
		if (is_pointer_value(env, regno)) {
			verbose(env, ""R%d leaks addr into helper function\n"",
				regno);
			return -EACCES;
		}
		return 0;
	}

	if (type_is_pkt_pointer(type) &&
	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
		verbose(env, ""helper access to the packet is not allowed\n"");
		return -EACCES;
	}

	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
		err = resolve_map_arg_type(env, meta, &arg_type);
		if (err)
			return err;
	}

	if (register_is_null(reg) && type_may_be_null(arg_type))
		/* A NULL register has a SCALAR_VALUE type, so skip
		 * type checking.
		 */
		goto skip_type_check;

	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
	if (err)
		return err;

	switch ((u32)type) {
	case SCALAR_VALUE:
	/* Pointer types where reg offset is explicitly allowed: */
	case PTR_TO_PACKET:
	case PTR_TO_PACKET_META:
	case PTR_TO_MAP_KEY:
	case PTR_TO_MAP_VALUE:
	case PTR_TO_MEM:
	case PTR_TO_MEM | MEM_RDONLY:
	case PTR_TO_BUF:
	case PTR_TO_BUF | MEM_RDONLY:
	case PTR_TO_STACK:
		break;
	/* All the rest must be rejected: */
	default:
		err = __check_ptr_off_reg(env, reg, regno,
					  type == PTR_TO_BTF_ID);
		if (err < 0)
			return err;
		break;
	}

skip_type_check:
	if (reg->ref_obj_id) {
		if (meta->ref_obj_id) {
			verbose(env, ""verifier internal error: more than one arg with ref_obj_id R%d %u %u\n"",
				regno, reg->ref_obj_id,
				meta->ref_obj_id);
			return -EFAULT;
		}
		meta->ref_obj_id = reg->ref_obj_id;
	}

	if (arg_type == ARG_CONST_MAP_PTR) {
		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
		if (meta->map_ptr) {
			/* Use map_uid (which is unique id of inner map) to reject:
			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
			 * if (inner_map1 && inner_map2) {
			 *     timer = bpf_map_lookup_elem(inner_map1);
			 *     if (timer)
			 *         // mismatch would have been allowed
			 *         bpf_timer_init(timer, inner_map2);
			 * }
			 *
			 * Comparing map_ptr is enough to distinguish normal and outer maps.
			 */
			if (meta->map_ptr != reg->map_ptr ||
			    meta->map_uid != reg->map_uid) {
				verbose(env,
					""timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n"",
					meta->map_uid, reg->map_uid);
				return -EINVAL;
			}
		}
		meta->map_ptr = reg->map_ptr;
		meta->map_uid = reg->map_uid;
	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
		/* bpf_map_xxx(..., map_ptr, ..., key) call:
		 * check that [key, key + map->key_size) are within
		 * stack limits and initialized
		 */
		if (!meta->map_ptr) {
			/* in function declaration map_ptr must come before
			 * map_key, so that it's verified and known before
			 * we have to check map_key here. Otherwise it means
			 * that kernel subsystem misconfigured verifier
			 */
			verbose(env, ""invalid map_ptr to access map->key\n"");
			return -EACCES;
		}
		err = check_helper_mem_access(env, regno,
					      meta->map_ptr->key_size, false,
					      NULL);
	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
		if (type_may_be_null(arg_type) && register_is_null(reg))
			return 0;

		/* bpf_map_xxx(..., map_ptr, ..., value) call:
		 * check [value, value + map->value_size) validity
		 */
		if (!meta->map_ptr) {
			/* kernel subsystem misconfigured verifier */
			verbose(env, ""invalid map_ptr to access map->value\n"");
			return -EACCES;
		}
		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
		err = check_helper_mem_access(env, regno,
					      meta->map_ptr->value_size, false,
					      meta);
	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
		if (!reg->btf_id) {
			verbose(env, ""Helper has invalid btf_id in R%d\n"", regno);
			return -EACCES;
		}
		meta->ret_btf = reg->btf;
		meta->ret_btf_id = reg->btf_id;
	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
		if (meta->func_id == BPF_FUNC_spin_lock) {
			if (process_spin_lock(env, regno, true))
				return -EACCES;
		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
			if (process_spin_lock(env, regno, false))
				return -EACCES;
		} else {
			verbose(env, ""verifier internal error\n"");
			return -EFAULT;
		}
	} else if (arg_type == ARG_PTR_TO_TIMER) {
		if (process_timer_func(env, regno, meta))
			return -EACCES;
	} else if (arg_type == ARG_PTR_TO_FUNC) {
		meta->subprogno = reg->subprogno;
	} else if (arg_type_is_mem_ptr(arg_type)) {
		/* The access to this pointer is only checked when we hit the
		 * next is_mem_size argument below.
		 */
		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
	} else if (arg_type_is_mem_size(arg_type)) {
		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);

		/* This is used to refine r0 return value bounds for helpers
		 * that enforce this value as an upper bound on return values.
		 * See do_refine_retval_range() for helpers that can refine
		 * the return value. C type of helper is u32 so we pull register
		 * bound from umax_value however, if negative verifier errors
		 * out. Only upper bounds can be learned because retval is an
		 * int type and negative retvals are allowed.
		 */
		meta->msize_max_value = reg->umax_value;

		/* The register is SCALAR_VALUE; the access check
		 * happens using its boundaries.
		 */
		if (!tnum_is_const(reg->var_off))
			/* For unprivileged variable accesses, disable raw
			 * mode so that the program is required to
			 * initialize all the memory that the helper could
			 * just partially fill up.
			 */
			meta = NULL;

		if (reg->smin_value < 0) {
			verbose(env, ""R%d min value is negative, either use unsigned or 'var &= const'\n"",
				regno);
			return -EACCES;
		}

		if (reg->umin_value == 0) {
			err = check_helper_mem_access(env, regno - 1, 0,
						      zero_size_allowed,
						      meta);
			if (err)
				return err;
		}

		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
			verbose(env, ""R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n"",
				regno);
			return -EACCES;
		}
		err = check_helper_mem_access(env, regno - 1,
					      reg->umax_value,
					      zero_size_allowed, meta);
		if (!err)
			err = mark_chain_precision(env, regno);
	} else if (arg_type_is_alloc_size(arg_type)) {
		if (!tnum_is_const(reg->var_off)) {
			verbose(env, ""R%d is not a known constant'\n"",
				regno);
			return -EACCES;
		}
		meta->mem_size = reg->var_off.value;
	} else if (arg_type_is_int_ptr(arg_type)) {
		int size = int_ptr_type_to_size(arg_type);

		err = check_helper_mem_access(env, regno, size, false, meta);
		if (err)
			return err;
		err = check_ptr_alignment(env, reg, 0, size, true);
	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
		struct bpf_map *map = reg->map_ptr;
		int map_off;
		u64 map_addr;
		char *str_ptr;

		if (!bpf_map_is_rdonly(map)) {
			verbose(env, ""R%d does not point to a readonly map'\n"", regno);
			return -EACCES;
		}

		if (!tnum_is_const(reg->var_off)) {
			verbose(env, ""R%d is not a constant address'\n"", regno);
			return -EACCES;
		}

		if (!map->ops->map_direct_value_addr) {
			verbose(env, ""no direct value access support for this map type\n"");
			return -EACCES;
		}

		err = check_map_access(env, regno, reg->off,
				       map->value_size - reg->off, false);
		if (err)
			return err;

		map_off = reg->off + reg->var_off.value;
		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
		if (err) {
			verbose(env, ""direct value access on string failed\n"");
			return err;
		}

		str_ptr = (char *)(long)(map_addr);
		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
			verbose(env, ""string is not zero-terminated\n"");
			return -EINVAL;
		}
	}

	return err;
}",1
"find_pattern_in_path(
    char_u	*ptr,		// pointer to search pattern
    int		dir UNUSED,	// direction of expansion
    int		len,		// length of search pattern
    int		whole,		// match whole words only
    int		skip_comments,	// don't match inside comments
    int		type,		// Type of search; are we looking for a type?
				// a macro?
    long	count,
    int		action,		// What to do when we find it
    linenr_T	start_lnum,	// first line to start searching
    linenr_T	end_lnum)	// last line for searching
{
    SearchedFile *files;		// Stack of included files
    SearchedFile *bigger;		// When we need more space
    int		max_path_depth = 50;
    long	match_count = 1;

    char_u	*pat;
    char_u	*new_fname;
    char_u	*curr_fname = curbuf->b_fname;
    char_u	*prev_fname = NULL;
    linenr_T	lnum;
    int		depth;
    int		depth_displayed;	// For type==CHECK_PATH
    int		old_files;
    int		already_searched;
    char_u	*file_line;
    char_u	*line;
    char_u	*p;
    char_u	save_char;
    int		define_matched;
    regmatch_T	regmatch;
    regmatch_T	incl_regmatch;
    regmatch_T	def_regmatch;
    int		matched = FALSE;
    int		did_show = FALSE;
    int		found = FALSE;
    int		i;
    char_u	*already = NULL;
    char_u	*startp = NULL;
    char_u	*inc_opt = NULL;
#if defined(FEAT_QUICKFIX)
    win_T	*curwin_save = NULL;
#endif

    regmatch.regprog = NULL;
    incl_regmatch.regprog = NULL;
    def_regmatch.regprog = NULL;

    file_line = alloc(LSIZE);
    if (file_line == NULL)
	return;

    if (type != CHECK_PATH && type != FIND_DEFINE
	    // when CONT_SOL is set compare ""ptr"" with the beginning of the
	    // line is faster than quote_meta/regcomp/regexec ""ptr"" -- Acevedo
	    && !compl_status_sol())
    {
	pat = alloc(len + 5);
	if (pat == NULL)
	    goto fpip_end;
	sprintf((char *)pat, whole ? ""\\<%.*s\\>"" : ""%.*s"", len, ptr);
	// ignore case according to p_ic, p_scs and pat
	regmatch.rm_ic = ignorecase(pat);
	regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
	vim_free(pat);
	if (regmatch.regprog == NULL)
	    goto fpip_end;
    }
    inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc;
    if (*inc_opt != NUL)
    {
	incl_regmatch.regprog = vim_regcomp(inc_opt,
						 magic_isset() ? RE_MAGIC : 0);
	if (incl_regmatch.regprog == NULL)
	    goto fpip_end;
	incl_regmatch.rm_ic = FALSE;	// don't ignore case in incl. pat.
    }
    if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL))
    {
	def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL
			   ? p_def : curbuf->b_p_def,
						 magic_isset() ? RE_MAGIC : 0);
	if (def_regmatch.regprog == NULL)
	    goto fpip_end;
	def_regmatch.rm_ic = FALSE;	// don't ignore case in define pat.
    }
    files = lalloc_clear(max_path_depth * sizeof(SearchedFile), TRUE);
    if (files == NULL)
	goto fpip_end;
    old_files = max_path_depth;
    depth = depth_displayed = -1;

    lnum = start_lnum;
    if (end_lnum > curbuf->b_ml.ml_line_count)
	end_lnum = curbuf->b_ml.ml_line_count;
    if (lnum > end_lnum)		// do at least one line
	lnum = end_lnum;
    line = ml_get(lnum);

    for (;;)
    {
	if (incl_regmatch.regprog != NULL
		&& vim_regexec(&incl_regmatch, line, (colnr_T)0))
	{
	    char_u *p_fname = (curr_fname == curbuf->b_fname)
					      ? curbuf->b_ffname : curr_fname;

	    if (inc_opt != NULL && strstr((char *)inc_opt, ""\\zs"") != NULL)
		// Use text from '\zs' to '\ze' (or end) of 'include'.
		new_fname = find_file_name_in_path(incl_regmatch.startp[0],
		       (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]),
				 FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname);
	    else
		// Use text after match with 'include'.
		new_fname = file_name_in_line(incl_regmatch.endp[0], 0,
			     FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL);
	    already_searched = FALSE;
	    if (new_fname != NULL)
	    {
		// Check whether we have already searched in this file
		for (i = 0;; i++)
		{
		    if (i == depth + 1)
			i = old_files;
		    if (i == max_path_depth)
			break;
		    if (fullpathcmp(new_fname, files[i].name, TRUE, TRUE)
								    & FPC_SAME)
		    {
			if (type != CHECK_PATH
				&& action == ACTION_SHOW_ALL
				&& files[i].matched)
			{
			    msg_putchar('\n');	    // cursor below last one
			    if (!got_int)	    // don't display if 'q'
						    // typed at ""--more--""
						    // message
			    {
				msg_home_replace_hl(new_fname);
				msg_puts(_("" (includes previously listed match)""));
				prev_fname = NULL;
			    }
			}
			VIM_CLEAR(new_fname);
			already_searched = TRUE;
			break;
		    }
		}
	    }

	    if (type == CHECK_PATH && (action == ACTION_SHOW_ALL
				 || (new_fname == NULL && !already_searched)))
	    {
		if (did_show)
		    msg_putchar('\n');	    // cursor below last one
		else
		{
		    gotocmdline(TRUE);	    // cursor at status line
		    msg_puts_title(_(""--- Included files ""));
		    if (action != ACTION_SHOW_ALL)
			msg_puts_title(_(""not found ""));
		    msg_puts_title(_(""in path ---\n""));
		}
		did_show = TRUE;
		while (depth_displayed < depth && !got_int)
		{
		    ++depth_displayed;
		    for (i = 0; i < depth_displayed; i++)
			msg_puts(""  "");
		    msg_home_replace(files[depth_displayed].name);
		    msg_puts("" -->\n"");
		}
		if (!got_int)		    // don't display if 'q' typed
					    // for ""--more--"" message
		{
		    for (i = 0; i <= depth_displayed; i++)
			msg_puts(""  "");
		    if (new_fname != NULL)
		    {
			// using ""new_fname"" is more reliable, e.g., when
			// 'includeexpr' is set.
			msg_outtrans_attr(new_fname, HL_ATTR(HLF_D));
		    }
		    else
		    {
			/*
			 * Isolate the file name.
			 * Include the surrounding """" or <> if present.
			 */
			if (inc_opt != NULL
				   && strstr((char *)inc_opt, ""\\zs"") != NULL)
			{
			    // pattern contains \zs, use the match
			    p = incl_regmatch.startp[0];
			    i = (int)(incl_regmatch.endp[0]
						   - incl_regmatch.startp[0]);
			}
			else
			{
			    // find the file name after the end of the match
			    for (p = incl_regmatch.endp[0];
						  *p && !vim_isfilec(*p); p++)
				;
			    for (i = 0; vim_isfilec(p[i]); i++)
				;
			}

			if (i == 0)
			{
			    // Nothing found, use the rest of the line.
			    p = incl_regmatch.endp[0];
			    i = (int)STRLEN(p);
			}
			// Avoid checking before the start of the line, can
			// happen if \zs appears in the regexp.
			else if (p > line)
			{
			    if (p[-1] == '""' || p[-1] == '<')
			    {
				--p;
				++i;
			    }
			    if (p[i] == '""' || p[i] == '>')
				++i;
			}
			save_char = p[i];
			p[i] = NUL;
			msg_outtrans_attr(p, HL_ATTR(HLF_D));
			p[i] = save_char;
		    }

		    if (new_fname == NULL && action == ACTION_SHOW_ALL)
		    {
			if (already_searched)
			    msg_puts(_(""  (Already listed)""));
			else
			    msg_puts(_(""  NOT FOUND""));
		    }
		}
		out_flush();	    // output each line directly
	    }

	    if (new_fname != NULL)
	    {
		// Push the new file onto the file stack
		if (depth + 1 == old_files)
		{
		    bigger = ALLOC_MULT(SearchedFile, max_path_depth * 2);
		    if (bigger != NULL)
		    {
			for (i = 0; i <= depth; i++)
			    bigger[i] = files[i];
			for (i = depth + 1; i < old_files + max_path_depth; i++)
			{
			    bigger[i].fp = NULL;
			    bigger[i].name = NULL;
			    bigger[i].lnum = 0;
			    bigger[i].matched = FALSE;
			}
			for (i = old_files; i < max_path_depth; i++)
			    bigger[i + max_path_depth] = files[i];
			old_files += max_path_depth;
			max_path_depth *= 2;
			vim_free(files);
			files = bigger;
		    }
		}
		if ((files[depth + 1].fp = mch_fopen((char *)new_fname, ""r""))
								    == NULL)
		    vim_free(new_fname);
		else
		{
		    if (++depth == old_files)
		    {
			/*
			 * lalloc() for 'bigger' must have failed above.  We
			 * will forget one of our already visited files now.
			 */
			vim_free(files[old_files].name);
			++old_files;
		    }
		    files[depth].name = curr_fname = new_fname;
		    files[depth].lnum = 0;
		    files[depth].matched = FALSE;
		    if (action == ACTION_EXPAND)
		    {
			msg_hist_off = TRUE;	// reset in msg_trunc_attr()
			vim_snprintf((char*)IObuff, IOSIZE,
				_(""Scanning included file: %s""),
				(char *)new_fname);
			msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
		    }
		    else if (p_verbose >= 5)
		    {
			verbose_enter();
			smsg(_(""Searching included file %s""),
							   (char *)new_fname);
			verbose_leave();
		    }

		}
	    }
	}
	else
	{
	    /*
	     * Check if the line is a define (type == FIND_DEFINE)
	     */
	    p = line;
search_line:
	    define_matched = FALSE;
	    if (def_regmatch.regprog != NULL
			      && vim_regexec(&def_regmatch, line, (colnr_T)0))
	    {
		/*
		 * Pattern must be first identifier after 'define', so skip
		 * to that position before checking for match of pattern.  Also
		 * don't let it match beyond the end of this identifier.
		 */
		p = def_regmatch.endp[0];
		while (*p && !vim_iswordc(*p))
		    p++;
		define_matched = TRUE;
	    }

	    /*
	     * Look for a match.  Don't do this if we are looking for a
	     * define and this line didn't match define_prog above.
	     */
	    if (def_regmatch.regprog == NULL || define_matched)
	    {
		if (define_matched || compl_status_sol())
		{
		    // compare the first ""len"" chars from ""ptr""
		    startp = skipwhite(p);
		    if (p_ic)
			matched = !MB_STRNICMP(startp, ptr, len);
		    else
			matched = !STRNCMP(startp, ptr, len);
		    if (matched && define_matched && whole
						  && vim_iswordc(startp[len]))
			matched = FALSE;
		}
		else if (regmatch.regprog != NULL
			 && vim_regexec(®match, line, (colnr_T)(p - line)))
		{
		    matched = TRUE;
		    startp = regmatch.startp[0];
		    /*
		     * Check if the line is not a comment line (unless we are
		     * looking for a define).  A line starting with ""# define""
		     * is not considered to be a comment line.
		     */
		    if (!define_matched && skip_comments)
		    {
			if ((*line != '#' ||
				STRNCMP(skipwhite(line + 1), ""define"", 6) != 0)
				&& get_leader_len(line, NULL, FALSE, TRUE))
			    matched = FALSE;

			/*
			 * Also check for a ""/ *"" or ""/ /"" before the match.
			 * Skips lines like ""int backwards;  / * normal index
			 * * /"" when looking for ""normal"".
			 * Note: Doesn't skip ""/ *"" in comments.
			 */
			p = skipwhite(line);
			if (matched
				|| (p[0] == '/' && p[1] == '*') || p[0] == '*')
			    for (p = line; *p && p < startp; ++p)
			    {
				if (matched
					&& p[0] == '/'
					&& (p[1] == '*' || p[1] == '/'))
				{
				    matched = FALSE;
				    // After ""//"" all text is comment
				    if (p[1] == '/')
					break;
				    ++p;
				}
				else if (!matched && p[0] == '*' && p[1] == '/')
				{
				    // Can find match after ""* /"".
				    matched = TRUE;
				    ++p;
				}
			    }
		    }
		}
	    }
	}
	if (matched)
	{
	    if (action == ACTION_EXPAND)
	    {
		int	cont_s_ipos = FALSE;
		int	add_r;
		char_u	*aux;

		if (depth == -1 && lnum == curwin->w_cursor.lnum)
		    break;
		found = TRUE;
		aux = p = startp;
		if (compl_status_adding())
		{
		    p += ins_compl_len();
		    if (vim_iswordp(p))
			goto exit_matched;
		    p = find_word_start(p);
		}
		p = find_word_end(p);
		i = (int)(p - aux);

		if (compl_status_adding() && i == ins_compl_len())
		{
		    // IOSIZE > compl_length, so the STRNCPY works
		    STRNCPY(IObuff, aux, i);

		    // Get the next line: when ""depth"" < 0  from the current
		    // buffer, otherwise from the included file.  Jump to
		    // exit_matched when past the last line.
		    if (depth < 0)
		    {
			if (lnum >= end_lnum)
			    goto exit_matched;
			line = ml_get(++lnum);
		    }
		    else if (vim_fgets(line = file_line,
						      LSIZE, files[depth].fp))
			goto exit_matched;

		    // we read a line, set ""already"" to check this ""line"" later
		    // if depth >= 0 we'll increase files[depth].lnum far
		    // below  -- Acevedo
		    already = aux = p = skipwhite(line);
		    p = find_word_start(p);
		    p = find_word_end(p);
		    if (p > aux)
		    {
			if (*aux != ')' && IObuff[i-1] != TAB)
			{
			    if (IObuff[i-1] != ' ')
				IObuff[i++] = ' ';
			    // IObuf =~ ""\(\k\|\i\).* "", thus i >= 2
			    if (p_js
				&& (IObuff[i-2] == '.'
				    || (vim_strchr(p_cpo, CPO_JOINSP) == NULL
					&& (IObuff[i-2] == '?'
					    || IObuff[i-2] == '!'))))
				IObuff[i++] = ' ';
			}
			// copy as much as possible of the new word
			if (p - aux >= IOSIZE - i)
			    p = aux + IOSIZE - i - 1;
			STRNCPY(IObuff + i, aux, p - aux);
			i += (int)(p - aux);
			cont_s_ipos = TRUE;
		    }
		    IObuff[i] = NUL;
		    aux = IObuff;

		    if (i == ins_compl_len())
			goto exit_matched;
		}

		add_r = ins_compl_add_infercase(aux, i, p_ic,
			curr_fname == curbuf->b_fname ? NULL : curr_fname,
			dir, cont_s_ipos);
		if (add_r == OK)
		    // if dir was BACKWARD then honor it just once
		    dir = FORWARD;
		else if (add_r == FAIL)
		    break;
	    }
	    else if (action == ACTION_SHOW_ALL)
	    {
		found = TRUE;
		if (!did_show)
		    gotocmdline(TRUE);		// cursor at status line
		if (curr_fname != prev_fname)
		{
		    if (did_show)
			msg_putchar('\n');	// cursor below last one
		    if (!got_int)		// don't display if 'q' typed
						// at ""--more--"" message
			msg_home_replace_hl(curr_fname);
		    prev_fname = curr_fname;
		}
		did_show = TRUE;
		if (!got_int)
		    show_pat_in_path(line, type, TRUE, action,
			    (depth == -1) ? NULL : files[depth].fp,
			    (depth == -1) ? &lnum : &files[depth].lnum,
			    match_count++);

		// Set matched flag for this file and all the ones that
		// include it
		for (i = 0; i <= depth; ++i)
		    files[i].matched = TRUE;
	    }
	    else if (--count <= 0)
	    {
		found = TRUE;
		if (depth == -1 && lnum == curwin->w_cursor.lnum
#if defined(FEAT_QUICKFIX)
						      && g_do_tagpreview == 0
#endif
						      )
		    emsg(_(e_match_is_on_current_line));
		else if (action == ACTION_SHOW)
		{
		    show_pat_in_path(line, type, did_show, action,
			(depth == -1) ? NULL : files[depth].fp,
			(depth == -1) ? &lnum : &files[depth].lnum, 1L);
		    did_show = TRUE;
		}
		else
		{
#ifdef FEAT_GUI
		    need_mouse_correct = TRUE;
#endif
#if defined(FEAT_QUICKFIX)
		    // "":psearch"" uses the preview window
		    if (g_do_tagpreview != 0)
		    {
			curwin_save = curwin;
			prepare_tagpreview(TRUE, TRUE, FALSE);
		    }
#endif
		    if (action == ACTION_SPLIT)
		    {
			if (win_split(0, 0) == FAIL)
			    break;
			RESET_BINDING(curwin);
		    }
		    if (depth == -1)
		    {
			// match in current file
#if defined(FEAT_QUICKFIX)
			if (g_do_tagpreview != 0)
			{
			    if (!win_valid(curwin_save))
				break;
			    if (!GETFILE_SUCCESS(getfile(
					   curwin_save->w_buffer->b_fnum, NULL,
						     NULL, TRUE, lnum, FALSE)))
				break;	// failed to jump to file
			}
			else
#endif
			    setpcmark();
			curwin->w_cursor.lnum = lnum;
			check_cursor();
		    }
		    else
		    {
			if (!GETFILE_SUCCESS(getfile(
					0, files[depth].name, NULL, TRUE,
						    files[depth].lnum, FALSE)))
			    break;	// failed to jump to file
			// autocommands may have changed the lnum, we don't
			// want that here
			curwin->w_cursor.lnum = files[depth].lnum;
		    }
		}
		if (action != ACTION_SHOW)
		{
		    curwin->w_cursor.col = (colnr_T)(startp - line);
		    curwin->w_set_curswant = TRUE;
		}

#if defined(FEAT_QUICKFIX)
		if (g_do_tagpreview != 0
			   && curwin != curwin_save && win_valid(curwin_save))
		{
		    // Return cursor to where we were
		    validate_cursor();
		    redraw_later(VALID);
		    win_enter(curwin_save, TRUE);
		}
# ifdef FEAT_PROP_POPUP
		else if (WIN_IS_POPUP(curwin))
		    // can't keep focus in popup window
		    win_enter(firstwin, TRUE);
# endif
#endif
		break;
	    }
exit_matched:
	    matched = FALSE;
	    // look for other matches in the rest of the line if we
	    // are not at the end of it already
	    if (def_regmatch.regprog == NULL
		    && action == ACTION_EXPAND
		    && !compl_status_sol()
		    && *startp != NUL
		    && *(p = startp + mb_ptr2len(startp)) != NUL)
		goto search_line;
	}
	line_breakcheck();
	if (action == ACTION_EXPAND)
	    ins_compl_check_keys(30, FALSE);
	if (got_int || ins_compl_interrupted())
	    break;

	/*
	 * Read the next line.  When reading an included file and encountering
	 * end-of-file, close the file and continue in the file that included
	 * it.
	 */
	while (depth >= 0 && !already
		&& vim_fgets(line = file_line, LSIZE, files[depth].fp))
	{
	    fclose(files[depth].fp);
	    --old_files;
	    files[old_files].name = files[depth].name;
	    files[old_files].matched = files[depth].matched;
	    --depth;
	    curr_fname = (depth == -1) ? curbuf->b_fname
				       : files[depth].name;
	    if (depth < depth_displayed)
		depth_displayed = depth;
	}
	if (depth >= 0)		// we could read the line
	{
	    files[depth].lnum++;
	    // Remove any CR and LF from the line.
	    i = (int)STRLEN(line);
	    if (i > 0 && line[i - 1] == '\n')
		line[--i] = NUL;
	    if (i > 0 && line[i - 1] == '\r')
		line[--i] = NUL;
	}
	else if (!already)
	{
	    if (++lnum > end_lnum)
		break;
	    line = ml_get(lnum);
	}
	already = NULL;
    }
    // End of big for (;;) loop.

    // Close any files that are still open.
    for (i = 0; i <= depth; i++)
    {
	fclose(files[i].fp);
	vim_free(files[i].name);
    }
    for (i = old_files; i < max_path_depth; i++)
	vim_free(files[i].name);
    vim_free(files);

    if (type == CHECK_PATH)
    {
	if (!did_show)
	{
	    if (action != ACTION_SHOW_ALL)
		msg(_(""All included files were found""));
	    else
		msg(_(""No included files""));
	}
    }
    else if (!found && action != ACTION_EXPAND)
    {
	if (got_int || ins_compl_interrupted())
	    emsg(_(e_interrupted));
	else if (type == FIND_DEFINE)
	    emsg(_(e_couldnt_find_definition));
	else
	    emsg(_(e_couldnt_find_pattern));
    }
    if (action == ACTION_SHOW || action == ACTION_SHOW_ALL)
	msg_end();

fpip_end:
    vim_free(file_line);
    vim_regfree(regmatch.regprog);
    vim_regfree(incl_regmatch.regprog);
    vim_regfree(def_regmatch.regprog);
}",1
"yank_copy_line(struct block_def *bd, long y_idx, int exclude_trailing_space)
{
    char_u	*pnew;

    if (exclude_trailing_space)
	bd->endspaces = 0;
    if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1))
								      == NULL)
	return FAIL;
    y_current->y_array[y_idx] = pnew;
    vim_memset(pnew, ' ', (size_t)bd->startspaces);
    pnew += bd->startspaces;
    mch_memmove(pnew, bd->textstart, (size_t)bd->textlen);
    pnew += bd->textlen;
    vim_memset(pnew, ' ', (size_t)bd->endspaces);
    pnew += bd->endspaces;
    if (exclude_trailing_space)
    {
	int s = bd->textlen + bd->endspaces;

	while (VIM_ISWHITE(*(bd->textstart + s - 1)) && s > 0)
	{
	    s = s - (*mb_head_off)(bd->textstart, bd->textstart + s - 1) - 1;
	    pnew--;
	}
    }
    *pnew = NUL;
    return OK;
}",1
"  void DoCompute(OpKernelContext* c) {
    core::RefCountPtr v;
    OP_REQUIRES_OK(c, LookupResource(c, HandleFromInput(c, 0), &v));
    Tensor* params = v->tensor();
    const Tensor& indices = c->input(1);
    const Tensor& updates = c->input(2);

    // Check that rank(updates.shape) = rank(indices.shape + params.shape[1:])
    OP_REQUIRES(c,
                updates.dims() == 0 ||
                    updates.dims() == indices.dims() + params->dims() - 1,
                errors::InvalidArgument(
                    ""Must have updates.shape = indices.shape + ""
                    ""params.shape[1:] or updates.shape = [], got "",
                    ""updates.shape "", updates.shape().DebugString(),
                    "", indices.shape "", indices.shape().DebugString(),
                    "", params.shape "", params->shape().DebugString()));

    // Check that we have enough index space
    const int64_t N_big = indices.NumElements();
    OP_REQUIRES(
        c, N_big <= std::numeric_limits::max(),
        errors::InvalidArgument(""indices has too many elements for "",
                                DataTypeString(DataTypeToEnum::v()),
                                "" indexing: "", N_big, "" > "",
                                std::numeric_limits::max()));
    const Index N = static_cast(N_big);
    OP_REQUIRES(
        c, params->dim_size(0) <= std::numeric_limits::max(),
        errors::InvalidArgument(""params.shape[0] too large for "",
                                DataTypeString(DataTypeToEnum::v()),
                                "" indexing: "", params->dim_size(0), "" > "",
                                std::numeric_limits::max()));

    if (N > 0) {
      auto indices_flat = indices.flat();
      auto params_flat = params->flat_outer_dims();
      if (TensorShapeUtils::IsScalar(updates.shape())) {
        const auto update = updates.scalar();

        functor::ScatterScalarFunctor functor;
        const Index bad_i = functor(c, c->template eigen_device(),
                                    params_flat, update, indices_flat);
        OP_REQUIRES(c, bad_i < 0,
                    errors::InvalidArgument(
                        ""indices"", SliceDebugString(indices.shape(), bad_i),
                        "" = "", indices_flat(bad_i), "" is not in [0, "",
                        params->dim_size(0), "")""));
      } else {
        int64_t num_updates = updates.NumElements();
        OP_REQUIRES(
            c, TensorShapeUtils::StartsWith(updates.shape(), indices.shape()),
            errors::InvalidArgument(
                ""The shape of indices ("", indices.shape().DebugString(),
                "") must be a prefix of the shape of updates ("",
                updates.shape().DebugString(), "")""));
        auto updates_flat = updates.shaped({N, num_updates / N});

        functor::ScatterFunctor functor;
        const Index bad_i = functor(c, c->template eigen_device(),
                                    params_flat, updates_flat, indices_flat);
        OP_REQUIRES(c, bad_i < 0,
                    errors::InvalidArgument(
                        ""indices"", SliceDebugString(indices.shape(), bad_i),
                        "" = "", indices_flat(bad_i), "" is not in [0, "",
                        params->dim_size(0), "")""));
      }
    }
  }",1
"int main(int argc, char *argv[])
{
    void *jfif = NULL;
    BMP   bmp  = {0};

    if (argc < 3) {
        printf(
            ""jfif test program\n""
            ""usage: ffjpeg -d filename decode jpg file to decode.bmp\n""
            ""       ffjpeg -e filename encode bmp file to encode.jpg\n""
        );
        return 0;
    }

    if (strcmp(argv[1], ""-d"") == 0) {
        jfif = jfif_load(argv[2]);
        jfif_decode(jfif, &bmp);
        jfif_free  (jfif);
        bmp_save(&bmp, ""decode.bmp"");
        bmp_free(&bmp);
    } else if (strcmp(argv[1], ""-e"") == 0) {
        bmp_load(&bmp, argv[2]);
        jfif = jfif_encode(&bmp);
        bmp_free(&bmp);
        jfif_save(jfif, ""encode.jpg"");
        jfif_free(jfif);
    }

    return 0;
}
",1
"static int setup_config(int type)
{
	int rv;

	rv = read_config(cl.configfile, type);
	if (rv < 0)
		goto out;

	if (is_auth_req()) {
		rv = read_authkey();
		if (rv < 0)
			goto out;
#if HAVE_LIBGCRYPT
		if (!gcry_check_version(NULL)) {
			log_error(""gcry_check_version"");
			rv = -ENOENT;
			goto out;
		}
		gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
		gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
	}

	/* Set ""local"" pointer, ignoring errors. */
	if (cl.type == DAEMON && cl.site[0]) {
		if (!find_site_by_name(cl.site, &local, 1)) {
			log_error(""Cannot find \""%s\"" in the configuration."",
					cl.site);
			return -EINVAL;
		}
		local->local = 1;
	} else
		find_myself(NULL, type == CLIENT || type == GEOSTORE);


	rv = check_config(type);
	if (rv < 0)
		goto out;


	/* Per default the PID file name is derived from the
	 * configuration name. */
	if (!cl.lockfile[0]) {
		snprintf(cl.lockfile, sizeof(cl.lockfile)-1,
				""%s/%s.pid"", BOOTH_RUN_DIR, booth_conf->name);
	}

out:
	return rv;
}",1
"  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    const TensorShape& input_shape = input.shape();
    const int32_t input_dims = input_shape.dims();

    const Tensor& segment_id = context->input(1);
    const TensorShape& segment_id_shape = segment_id.shape();
    const int32_t segment_dims = segment_id_shape.dims();

    const Tensor& num_segments_tensor = context->input(2);
    OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,
                errors::InvalidArgument(""Number of segments cannot be empty.""));
    auto num_segments = num_segments_tensor.scalar()();

    OP_REQUIRES(context, num_segments > 0,
                errors::InvalidArgument(""Number of segments must be positive""));
    OP_REQUIRES(context, segment_dims != 0,
                errors::InvalidArgument(""Segment_id cannot have rank 0""));

    OP_REQUIRES(
        context, segment_dims <= input_dims,
        errors::OutOfRange(""Invalid segment_id rank "", segment_dims,
                           "" for input with "", input_dims, "" dimension(s)""));
    for (auto i = 0; i < segment_dims; i++) {
      OP_REQUIRES(
          context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),
          errors::InvalidArgument(
              ""Segment dimension is "", segment_id_shape.dim_size(i),
              "" while input dimension is "", input_dims, "" in rank "", i));
    }

    // Making output tensor.
    Tensor* output_tensor = nullptr;
    TensorShape output_shape =
        GetOutputShape(input_shape, segment_id_shape, num_segments);
    OP_REQUIRES_OK(context, context->allocate_output(""output"", output_shape,
                                                     &output_tensor));

    // Preparating flat tensors.
    auto output_flat = output_tensor->flat();
    auto flat_segment_id = segment_id.flat();
    auto flat_input = input.flat();

    for (int i = 0; i < flat_segment_id.size(); i++) {
      OP_REQUIRES(
          context,
          ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),
          errors::InvalidArgument(
              ""segment_ids are not allowed to exceed num_segments or""
              "" to have negative values.""));
    }

    int64_t big_stride;
    int64_t small_stride;
    std::tie(big_stride, small_stride) =
        GetStrides(input_shape, segment_id_shape);
    auto relative_offset_set =
        GetFlattenedRelativeOffsets(small_stride, big_stride);
    for (auto start_offset = 0; start_offset < big_stride; start_offset++) {
      for (auto i = 0; i < relative_offset_set.size(); i++) {
        auto output_index = start_offset + flat_segment_id(i) * big_stride;
        auto offset = start_offset + relative_offset_set[i];
        if (output_flat(output_index).length() != 0)
          output_flat(output_index).append(separator_.c_str());
        output_flat(output_index).append(flat_input(offset));
      }
    }
  }",1
"mrb_remove_method(mrb_state *mrb, struct RClass *c, mrb_sym mid)
{
  mt_tbl *h;

  MRB_CLASS_ORIGIN(c);
  h = c->mt;

  if (h && mt_del(mrb, h, mid)) return;
  mrb_name_error(mrb, mid, ""method '%n' not defined in %C"", mid, c);
}",1
"int main(int argc, char *argv[]) {
	(void)argc;

	const char *usage = ""Usage: seatd-launch [options] [--] command\n""
			    ""\n""
			    ""  -h		Show this help message\n""
			    ""  -s 	Where to create the seatd socket\n""
			    ""  -v		Show the version number\n""
			    ""\n"";

	int c;
	char *sockpath = NULL;
	while ((c = getopt(argc, argv, ""vhs:"")) != -1) {
		switch (c) {
		case 's':
			sockpath = optarg;
			break;
		case 'v':
			printf(""seatd-launch version %s\n"", SEATD_VERSION);
			return 0;
		case 'h':
			printf(""%s"", usage);
			return 0;
		case '?':
			fprintf(stderr, ""Try '%s -h' for more information.\n"", argv[0]);
			return 1;
		default:
			abort();
		}
	}

	if (optind >= argc) {
		fprintf(stderr, ""A command must be specified\n\n%s"", usage);
		return 1;
	}
	char **command = &argv[optind];

	char sockbuf[256];
	if (sockpath == NULL) {
		sprintf(sockbuf, ""/tmp/seatd.%d.sock"", getpid());
		sockpath = sockbuf;
	}

	unlink(sockpath);

	int fds[2];
	if (pipe(fds) == -1) {
		perror(""Could not create pipe"");
		goto error;
	}

	pid_t seatd_child = fork();
	if (seatd_child == -1) {
		perror(""Could not fork seatd process"");
		goto error;
	} else if (seatd_child == 0) {
		close(fds[0]);

		char pipebuf[16] = {0};
		snprintf(pipebuf, sizeof pipebuf, ""%d"", fds[1]);

		char *env[2] = {NULL, NULL};
		char loglevelbuf[32] = {0};
		char *cur_loglevel = getenv(""SEATD_LOGLEVEL"");
		if (cur_loglevel != NULL) {
			snprintf(loglevelbuf, sizeof loglevelbuf, ""SEATD_LOGLEVEL=%s"", cur_loglevel);
			env[0] = loglevelbuf;
		}

		char *command[] = {""seatd"", ""-n"", pipebuf, ""-s"", sockpath, NULL};
		execve(SEATD_INSTALLPATH, command, env);
		perror(""Could not start seatd"");
		_exit(1);
	}
	close(fds[1]);

	// Wait for seatd to be ready
	char buf[1] = {0};
	while (true) {
		pid_t p = waitpid(seatd_child, NULL, WNOHANG);
		if (p == seatd_child) {
			fprintf(stderr, ""seatd exited prematurely\n"");
			goto error_seatd;
		} else if (p == -1 && (errno != EINTR && errno != ECHILD)) {
			perror(""Could not wait for seatd process"");
			goto error_seatd;
		}

		struct pollfd fd = {
			.fd = fds[0],
			.events = POLLIN,
		};

		// We poll with timeout to avoid a racing on a blocking read
		if (poll(&fd, 1, 1000) == -1) {
			if (errno == EAGAIN || errno == EINTR) {
				continue;
			} else {
				perror(""Could not poll notification fd"");
				goto error_seatd;
			}
		}

		if (fd.revents & POLLIN) {
			ssize_t n = read(fds[0], buf, 1);
			if (n == -1 && errno != EINTR) {
				perror(""Could not read from pipe"");
				goto error_seatd;
			} else if (n > 0) {
				break;
			}
		}
	}
	close(fds[0]);

	uid_t uid = getuid();
	gid_t gid = getgid();

	// Restrict access to the socket to just us
	if (chown(sockpath, uid, gid) == -1) {
		perror(""Could not chown seatd socket"");
		goto error_seatd;
	}
	if (chmod(sockpath, 0700) == -1) {
		perror(""Could not chmod socket"");
		goto error_seatd;
	}

	// Drop privileges
	if (setgid(gid) == -1) {
		perror(""Could not set gid to drop privileges"");
		goto error_seatd;
	}
	if (setuid(uid) == -1) {
		perror(""Could not set uid to drop privileges"");
		goto error_seatd;
	}

	pid_t child = fork();
	if (child == -1) {
		perror(""Could not fork target process"");
		goto error_seatd;
	} else if (child == 0) {
		setenv(""SEATD_SOCK"", sockpath, 1);
		execvp(command[0], command);
		perror(""Could not start target"");
		_exit(1);
	}

	int status = 0;
	while (true) {
		pid_t p = waitpid(child, &status, 0);
		if (p == child) {
			break;
		} else if (p == -1 && errno != EINTR) {
			perror(""Could not wait for target process"");
			goto error_seatd;
		}
	}

	if (unlink(sockpath) != 0) {
		perror(""Could not unlink socket"");
	}
	if (kill(seatd_child, SIGTERM) != 0) {
		perror(""Could not kill seatd"");
	}

	if (WIFEXITED(status)) {
		return WEXITSTATUS(status);
	} else if (WIFSIGNALED(status)) {
		return 128 + WTERMSIG(status);
	} else {
		abort(); // unreachable
	}

error_seatd:
	unlink(sockpath);
	kill(seatd_child, SIGTERM);
error:
	return 1;
}",1
"  void ComputeAsync(OpKernelContext* context, DoneCallback done) final {
    const Tensor& input = context->input(0);
    const Tensor& rhs = context->input(1);
    const int ndims = input.dims();
    const int64 n = input.dim_size(ndims - 1);
    const int64 nrhs = rhs.dim_size(ndims - 1);
    // Validate inputs.
    OP_REQUIRES_ASYNC(
        context, ndims >= 2,
        errors::InvalidArgument(""Input must have rank >= 2, got "", ndims),
        done);
    OP_REQUIRES_ASYNC(context, rhs.dims() == ndims,
                      errors::InvalidArgument(
                          ""Input and right-hand side must have same rank, got "",
                          ndims, "" != "", rhs.dims()),
                      done);
    OP_REQUIRES_ASYNC(
        context, input.dim_size(ndims - 2) == n,
        errors::InvalidArgument(""Input matrices must be squares, got"",
                                input.dim_size(ndims - 2), "" != "", n),
        done);
    OP_REQUIRES_ASYNC(context, rhs.dim_size(ndims - 2) == n,
                      errors::InvalidArgument(
                          ""Input matrix and right-hand side must have the ""
                          ""same number of rows, got"",
                          n, "" != "", rhs.dim_size(ndims - 2)),
                      done);

    // Allocate output.
    Tensor* output;
    OP_REQUIRES_OK_ASYNC(
        context,
        context->forward_input_or_allocate_output({1}, 0, rhs.shape(), &output),
        done);

    // To be consistent with the MatrixInverse op, we define the solution for
    // an empty set of equations as the empty matrix.
    if (input.NumElements() == 0 || rhs.NumElements() == 0) {
      done();
      return;
    }

    // TODO(rmlarsen): Convert to std::make_unique when available.
    std::unique_ptr solver(new CudaSolver(context));

    // Make a copy of the input for the factorization step, or, if adjoint_ is
    // false, try to reuse the input buffer if this op owns it exclusively.
    Tensor input_copy;
    const GPUDevice& device = context->eigen_device();
    if (adjoint_) {
      // For the adjoint case, it is simpler to always make a transposed copy up
      // front.
      OP_REQUIRES_OK_ASYNC(
          context,
          solver->allocate_scoped_tensor(DataTypeToEnum::value,
                                         input.shape(), &input_copy),
          done);
      OP_REQUIRES_OK_ASYNC(context,
                           DoMatrixTranspose(device, input, &input_copy), done);
    } else {
      OP_REQUIRES_OK_ASYNC(
          context,
          solver->forward_input_or_allocate_scoped_tensor(
              {0}, DataTypeToEnum::value, input.shape(), &input_copy),
          done);
      if (!input.SharesBufferWith(input_copy)) {
        device.memcpy(input_copy.flat().data(),
                      input.flat().data(),
                      input.NumElements() * sizeof(Scalar));
      }
    }
    auto input_copy_reshaped = input_copy.template flat_inner_dims();
    const int64 batch_size = input_copy_reshaped.dimension(0);

    // Allocate pivots on the device.
    Tensor pivots;
    OP_REQUIRES_OK_ASYNC(
        context,
        solver->allocate_scoped_tensor(DataTypeToEnum::value,
                                       TensorShape{batch_size, n}, &pivots),
        done);
    auto pivots_mat = pivots.template matrix();

    // 1. Compute the partially pivoted LU factorization(s) of the
    // matrix/matrices.
    std::vector dev_info;
    auto input_copy_ptrs = solver->GetScratchSpace(
        sizeof(Scalar*) * batch_size, ""input_copt_ptrs"",
        /* on_host */ true);
    const int kMaxMatrixSizeToBatchSizeRatio = 128;
    const bool use_batched_solver =
        n <= kMaxMatrixSizeToBatchSizeRatio * batch_size;
    if (use_batched_solver) {
      // For small matrices or large batch sizes, we use the batched interface
      // from cuBlas.
      const Scalar** input_copy_ptrs_base =
          reinterpret_cast(input_copy_ptrs.mutable_data());
      for (int batch = 0; batch < batch_size; ++batch) {
        input_copy_ptrs_base[batch] = &input_copy_reshaped(batch, 0, 0);
      }
      dev_info.push_back(
          solver->GetDeviceLapackInfo(batch_size, ""getrfBatched""));
      OP_REQUIRES_OK_ASYNC(
          context,
          solver->GetrfBatched(n, input_copy_ptrs_base, n, pivots_mat.data(),
                               &dev_info.back(), batch_size),
          done);
    } else {
      // For small batch sizes or large matrices, we use the non-batched
      // interface from cuSolver, which is much faster for large matrices.
      dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, ""getrf""));
      for (int batch = 0; batch < batch_size; ++batch) {
        OP_REQUIRES_OK_ASYNC(
            context,
            solver->Getrf(n, n, &input_copy_reshaped(batch, 0, 0), n,
                          &pivots_mat(batch, 0), &dev_info.back()(batch)),
            done);
      }
    }

    // 2. Make a transposed copy of the right-hand sides. This is necessary
    // because cuBLAS assumes column-major storage while TensorFlow TF uses
    // row-major.
    TensorShape transposed_rhs_shape(rhs.shape());
    transposed_rhs_shape.RemoveLastDims(2);
    transposed_rhs_shape.AddDim(nrhs);
    transposed_rhs_shape.AddDim(n);
    Tensor transposed_rhs;
    OP_REQUIRES_OK_ASYNC(
        context,
        solver->allocate_scoped_tensor(DataTypeToEnum::value,
                                       transposed_rhs_shape, &transposed_rhs),
        done);
    if (nrhs > 1) {
      OP_REQUIRES_OK_ASYNC(
          context, DoMatrixTranspose(device, rhs, &transposed_rhs), done);
    } else {
      device.memcpy(transposed_rhs.flat().data(),
                    rhs.flat().data(),
                    rhs.NumElements() * sizeof(Scalar));
    }

    // 3. Solve op(A) X = B (in column major form).
    // We use a trick here: If adjoint_ is true, we converted A to column major
    // form above. If adjoint is false then I leave A in row-major form and use
    // trans_a = CUBLAS_OP_T to effectively transform it to column-major on the
    // fly. (This means that we actually use the LU-factorization of A^T in that
    // case, but that is equally good for solving AX=B). This way we save an
    // explicit transpose in the more common case of adjoint_ == false.
    auto input_copy_ptr_array = solver->GetScratchSpace(
        sizeof(Scalar*) * batch_size, ""input_copy_ptr_array"",
        /* on_host */ true);
    auto transposed_rhs_ptr_array = solver->GetScratchSpace(
        sizeof(Scalar*) * batch_size, ""transposed_rhs_ptr_array"",
        /* on_host */ true);
    auto transposed_rhs_reshaped =
        transposed_rhs.template flat_inner_dims();
    if (use_batched_solver) {
      const Scalar** input_copy_ptrs_base =
          reinterpret_cast(input_copy_ptr_array.mutable_data());
      const Scalar** transposed_rhs_ptrs_base =
          reinterpret_cast(
              transposed_rhs_ptr_array.mutable_data());
      for (int batch = 0; batch < batch_size; ++batch) {
        input_copy_ptrs_base[batch] = &input_copy_reshaped(batch, 0, 0);
        transposed_rhs_ptrs_base[batch] = &transposed_rhs_reshaped(batch, 0, 0);
      }
      int host_info = 0;
      OP_REQUIRES_OK_ASYNC(
          context,
          solver->GetrsBatched(adjoint_ ? CUBLAS_OP_C : CUBLAS_OP_T, n, nrhs,
                               input_copy_ptrs_base, n, pivots_mat.data(),
                               transposed_rhs_ptrs_base, n, &host_info,
                               batch_size),
          done);
      OP_REQUIRES_ASYNC(
          context, host_info == 0,
          errors::InvalidArgument(""The "", -host_info,
                                  ""'th argument to cublas*getrsBatched had ""
                                  ""an illegal value.""),
          done);
    } else {
      dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, ""getrs""));
      for (int batch = 0; batch < batch_size; ++batch) {
        OP_REQUIRES_OK_ASYNC(
            context,
            solver->Getrs(adjoint_ ? CUBLAS_OP_C : CUBLAS_OP_T, n, nrhs,
                          &input_copy_reshaped(batch, 0, 0), n,
                          &pivots_mat(batch, 0),
                          &transposed_rhs_reshaped(batch, 0, 0), n,
                          &dev_info.back()(batch)),
            done);
      }
    }

    // 4. Transpose X to get the final result in row-major form.
    if (nrhs > 1) {
      OP_REQUIRES_OK_ASYNC(
          context, DoMatrixTranspose(device, transposed_rhs, output), done);
    } else {
      device.memcpy(output->flat().data(),
                    transposed_rhs.flat().data(),
                    transposed_rhs.NumElements() * sizeof(Scalar));
    }

    // Callback for checking info after kernels finish. Also capture the
    // temporary Tensors/ScratchSpace so they don't get deallocated before the
    // kernels run. TODO(rmlarsen): Use move capture once C++14 becomes
    // available.
    auto info_checker = [context, done, dev_info](
                            const Status& status,
                            const std::vector& host_infos) {
      if (!status.ok() && errors::IsInvalidArgument(status) &&
          !host_infos.empty()) {
        for (int i = 0; i < host_infos[0].size(); ++i) {
          // Match the CPU error message for singular matrices. Otherwise
          // just print the original error message from the status below.
          OP_REQUIRES_ASYNC(context, host_infos[0].data()[i] <= 0,
                            errors::InvalidArgument(kErrMsg), done);
        }
      }
      OP_REQUIRES_OK_ASYNC(context, status, done);
      done();
    };
    CudaSolver::CheckLapackInfoAndDeleteSolverAsync(std::move(solver), dev_info,
                                                    std::move(info_checker));
  }",1
"static inline int checkSettingSecurity(lua_State* L, const std::string &name)
{
	if (ScriptApiSecurity::isSecure(L) && name.compare(0, 7, ""secure."") == 0)
		throw LuaError(""Attempt to set secure setting."");

	bool is_mainmenu = false;
#ifndef SERVER
	is_mainmenu = ModApiBase::getGuiEngine(L) != nullptr;
#endif
	if (!is_mainmenu && (name == ""mg_name"" || name == ""mg_flags"")) {
		errorstream << ""Tried to set global setting "" << name << "", ignoring. ""
			""minetest.set_mapgen_setting() should be used instead."" << std::endl;
		infostream << script_get_backtrace(L) << std::endl;
		return -1;
	}

	return 0;
}",1
"static int DoPamAuth(struct pam_handle* pamh,
                     const char* username,
                     std::string& authenticated_username)
{
  int err = pam_set_item(pamh, PAM_RUSER, username);
  if (err != PAM_SUCCESS) {
    Dmsg1(debuglevel, ""PAM set_item failed: %s\n"", pam_strerror(pamh, err));
    return err;
  }

  err = pam_authenticate(pamh, 0);
  if (err != PAM_SUCCESS) {
    Dmsg1(debuglevel, ""PAM authentication failed: %s\n"",
          pam_strerror(pamh, err));
    return err;
  }

#if defined(__sun)
  void* data;
#else
  const void* data;
#endif
  err = pam_get_item(pamh, PAM_USER, &data);
  if (err != PAM_SUCCESS) {
    Dmsg1(debuglevel, ""PAM get_item failed: %s\n"", pam_strerror(pamh, err));
    return err;
  } else {
    if (data) { authenticated_username = static_cast(data); }
  }
  return err;
}",1
"EFI_STATUS verify_image(void *data, unsigned int datasize,
			EFI_LOADED_IMAGE *li,
			PE_COFF_LOADER_IMAGE_CONTEXT *context)
{
	EFI_STATUS efi_status;
	UINT8 sha1hash[SHA1_DIGEST_SIZE];
	UINT8 sha256hash[SHA256_DIGEST_SIZE];

	/*
	 * The binary header contains relevant context and section pointers
	 */
	efi_status = read_header(data, datasize, context);
	if (EFI_ERROR(efi_status)) {
		perror(L""Failed to read header: %r\n"", efi_status);
		return efi_status;
	}

	/*
	 * We only need to verify the binary if we're in secure mode
	 */
	efi_status = generate_hash(data, datasize, context, sha256hash,
				   sha1hash);
	if (EFI_ERROR(efi_status))
		return efi_status;

	/* Measure the binary into the TPM */
#ifdef REQUIRE_TPM
	efi_status =
#endif
	tpm_log_pe((EFI_PHYSICAL_ADDRESS)(UINTN)data, datasize,
		   (EFI_PHYSICAL_ADDRESS)(UINTN)context->ImageAddress,
		   li->FilePath, sha1hash, 4);
#ifdef REQUIRE_TPM
	if (efi_status != EFI_SUCCESS) {
		return efi_status;
	}
#endif

	if (secure_mode()) {
		efi_status = verify_buffer(data, datasize,
					   context, sha256hash, sha1hash);
		if (EFI_ERROR(efi_status)) {
			if (verbose)
				console_print(L""Verification failed: %r\n"", efi_status);
			else
				console_error(L""Verification failed"", efi_status);
			return efi_status;
		} else if (verbose)
			console_print(L""Verification succeeded\n"");
	}

	return EFI_SUCCESS;
}",1
"  void Compute(OpKernelContext* ctx) override {
    Buffer* buf = nullptr;
    OP_REQUIRES_OK(ctx, GetBuffer(ctx, def(), &buf));
    core::ScopedUnref scope(buf);
    Buffer::Tuple tuple;

    std::size_t index = ctx->input(0).scalar()();

    OP_REQUIRES_OK(ctx, buf->Peek(index, &tuple));

    OP_REQUIRES(
        ctx, tuple.size() == (size_t)ctx->num_outputs(),
        errors::InvalidArgument(""Mismatch stage/unstage: "", tuple.size(),
                                "" vs. "", ctx->num_outputs()));

    for (size_t i = 0; i < tuple.size(); ++i) {
      ctx->set_output(i, tuple[i]);
    }
  }",1
"static GF_Err isoffin_process(GF_Filter *filter)
{
	ISOMReader *read = gf_filter_get_udta(filter);
	u32 i, count = gf_list_count(read->channels);
	Bool is_active = GF_FALSE;
	Bool in_is_eos = GF_FALSE;
	Bool check_forced_end = GF_FALSE;
	Bool has_new_data = GF_FALSE;
	u64 min_offset_plus_one = 0;
	u32 nb_forced_end=0;
	if (read->in_error)
		return read->in_error;

	if (read->pid) {
		Bool fetch_input = GF_TRUE;

		//we failed at loading the init segment during a dash switch, retry
		if (!read->is_partial_download && !read->mem_load_mode && (read->moov_not_loaded==2) ) {
			isoffin_configure_pid(filter, read->pid, GF_FALSE);
			if (read->moov_not_loaded) return GF_OK;
		}
		if (read->mem_load_mode==2) {
			if (!read->force_fetch && read->mem_blob.size > read->mstore_size) {
				fetch_input = GF_FALSE;
			}
			read->force_fetch = GF_FALSE;
		}
		while (fetch_input) {
			GF_FilterPacket *pck = gf_filter_pid_get_packet(read->pid);
			if (!pck) {
				//we issued a seek, wait for the first packet to be received before fetching channels
				//otherwise we could end up reading from the wrong cache
				if (read->wait_for_source) {
					//something went wrong during the seek request
					if (gf_filter_pid_is_eos(read->pid))
						return GF_EOS;
					return GF_OK;
				}
				break;
			}
			read->wait_for_source = GF_FALSE;

			if (read->mem_load_mode) {
				u32 data_size;
				const u8 *pck_data = gf_filter_pck_get_data(pck, &data_size);
				isoffin_push_buffer(filter, read, pck_data, data_size);
			}
			//we just had a switch but init seg is not completely done: input packet is only a part of the init, drop it
			else if (read->moov_not_loaded==2) {
				gf_filter_pid_drop_packet(read->pid);
				return GF_OK;
			}
			gf_filter_pid_drop_packet(read->pid);
			has_new_data = GF_TRUE;
			if (read->in_error)
				return read->in_error;
		}
		if (gf_filter_pid_is_eos(read->pid)) {
			read->input_loaded = GF_TRUE;
			in_is_eos = GF_TRUE;
		}
		if (read->input_is_stop) {
			read->input_loaded = GF_TRUE;
			in_is_eos = GF_TRUE;
			read->input_is_stop = GF_FALSE;
		}
		if (!read->frag_type && read->input_loaded) {
			in_is_eos = GF_TRUE;
		}
        //segment is invalid, wait for eos on input an send eos on all channels
        if (read->invalid_segment) {
            if (!in_is_eos) return GF_OK;
            read->invalid_segment = GF_FALSE;

            for (i=0; ichannels, i);
                if (!ch->playing) {
                    continue;
                }
                if (!ch->eos_sent) {
                    ch->eos_sent = GF_TRUE;
                    gf_filter_pid_set_eos(ch->pid);
                }
            }
            read->eos_signaled = GF_TRUE;
            return GF_EOS;
        }
	} else if (read->extern_mov) {
		in_is_eos = GF_TRUE;
		read->input_loaded = GF_TRUE;
	}
	if (read->moov_not_loaded==1) {
		if (read->mem_load_mode)
			return GF_OK;
		read->moov_not_loaded = GF_FALSE;
		return isoffin_setup(filter, read);
	}

	if (read->refresh_fragmented) {
		const GF_PropertyValue *prop;

		if (in_is_eos) {
			read->refresh_fragmented = GF_FALSE;
		} else {
			prop = gf_filter_pid_get_property(read->pid, GF_PROP_PID_FILE_CACHED);
			if (prop && prop->value.boolean)
				read->refresh_fragmented = GF_FALSE;
		}

		if (has_new_data) {
			u64 bytesMissing=0;
			GF_Err e;
			const char *new_url = NULL;
			prop = gf_filter_pid_get_property(read->pid, GF_PROP_PID_FILEPATH);
			if (prop) new_url = prop->value.string;

			e = gf_isom_refresh_fragmented(read->mov, &bytesMissing, new_url);

			if (e && (e!= GF_ISOM_INCOMPLETE_FILE)) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_DASH, (""[IsoMedia] Failed to refresh current segment: %s\n"", gf_error_to_string(e) ));
				read->refresh_fragmented = GF_FALSE;
			} else {
				GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (""[IsoMedia] Refreshing current segment at UTC ""LLU"" - ""LLU"" bytes still missing - input is EOS %d\n"", gf_net_get_utc(), bytesMissing, in_is_eos));
			}

			if (!read->refresh_fragmented && (e==GF_ISOM_INCOMPLETE_FILE)) {
				GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, (""[IsoMedia] Incomplete Segment received - ""LLU"" bytes missing but EOF found\n"", bytesMissing ));
			}

#ifndef GPAC_DISABLE_LOG
			if (gf_log_tool_level_on(GF_LOG_DASH, GF_LOG_DEBUG)) {
				for (i=0; ichannels, i);
					GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (""[IsoMedia] refresh track %d fragment - cur sample %d - new sample count %d\n"", ch->track, ch->sample_num, gf_isom_get_sample_count(ch->owner->mov, ch->track) ));
				}
			}
#endif
			isor_check_producer_ref_time(read);
			if (!read->frag_type)
				read->refresh_fragmented = GF_FALSE;
		}
	}

	for (i=0; ichannels, i);
		if (!ch->playing) {
			nb_forced_end++;
			continue;
		}
		//eos not sent on this channel, we are active
		if (!ch->eos_sent)
			is_active = GF_TRUE;

		while (nb_pck) {
			ch->sample_data_offset = 0;
			if (!read->full_segment_flush && gf_filter_pid_would_block(ch->pid) )
				break;

			if (ch->item_id) {
				isor_reader_get_sample_from_item(ch);
			} else {
				isor_reader_get_sample(ch);
			}

			if (read->stsd && (ch->last_sample_desc_index != read->stsd) && ch->sample) {
				isor_reader_release_sample(ch);
				continue;
			}
			if (ch->sample) {
				u32 sample_dur;
				u8 dep_flags;
				u8 *subs_buf;
				u32 subs_buf_size;
				GF_FilterPacket *pck;
				if (ch->needs_pid_reconfig) {
					isor_update_channel_config(ch);
					ch->needs_pid_reconfig = GF_FALSE;
				}

				//we have at least two samples, update GF_PROP_PID_HAS_SYNC if needed
				if (ch->check_has_rap && (gf_isom_get_sample_count(ch->owner->mov, ch->track)>1) && (gf_isom_has_sync_points(ch->owner->mov, ch->track)==1)) {
					ch->check_has_rap = GF_FALSE;
					ch->has_rap = GF_TRUE;
					gf_filter_pid_set_property(ch->pid, GF_PROP_PID_HAS_SYNC, &PROP_BOOL(ch->has_rap) );
				}

				//strip param sets from payload, trigger reconfig if needed
				isor_reader_check_config(ch);

				if (read->nodata) {
					pck = gf_filter_pck_new_shared(ch->pid, NULL, ch->sample->dataLength, NULL);
					if (!pck) return GF_OUT_OF_MEM;
				} else {
					pck = gf_filter_pck_new_alloc(ch->pid, ch->sample->dataLength, &data);
					if (!pck) return GF_OUT_OF_MEM;

					memcpy(data, ch->sample->data, ch->sample->dataLength);
				}
				gf_filter_pck_set_dts(pck, ch->dts);
				gf_filter_pck_set_cts(pck, ch->cts);
				if (ch->sample->IsRAP==-1) {
					gf_filter_pck_set_sap(pck, GF_FILTER_SAP_1);
					ch->redundant = 1;
				} else {
					gf_filter_pck_set_sap(pck, (GF_FilterSAPType) ch->sample->IsRAP);
				}

				if (ch->sap_3)
					gf_filter_pck_set_sap(pck, GF_FILTER_SAP_3);
				else if (ch->sap_4_type) {
					gf_filter_pck_set_sap(pck, (ch->sap_4_type==GF_ISOM_SAMPLE_PREROLL) ? GF_FILTER_SAP_4_PROL : GF_FILTER_SAP_4);
					gf_filter_pck_set_roll_info(pck, ch->roll);
				}

				sample_dur = ch->au_duration;
				if (ch->sample->nb_pack)
					sample_dur *= ch->sample->nb_pack;
				gf_filter_pck_set_duration(pck, sample_dur);
				gf_filter_pck_set_seek_flag(pck, ch->seek_flag);

				//for now we only signal xPS mask for non-sap
				if (ch->xps_mask && !gf_filter_pck_get_sap(pck) ) {
					gf_filter_pck_set_property(pck, GF_PROP_PCK_XPS_MASK, &PROP_UINT(ch->xps_mask) );
				}

				dep_flags = ch->isLeading;
				dep_flags <<= 2;
				dep_flags |= ch->dependsOn;
				dep_flags <<= 2;
				dep_flags |= ch->dependedOn;
				dep_flags <<= 2;
				dep_flags |= ch->redundant;

				if (dep_flags)
					gf_filter_pck_set_dependency_flags(pck, dep_flags);

				gf_filter_pck_set_crypt_flags(pck, ch->pck_encrypted ? GF_FILTER_PCK_CRYPT : 0);
				gf_filter_pck_set_seq_num(pck, ch->sample_num);


				subs_buf = gf_isom_sample_get_subsamples_buffer(read->mov, ch->track, ch->sample_num, &subs_buf_size);
				if (subs_buf) {
					gf_filter_pck_set_property(pck, GF_PROP_PCK_SUBS, &PROP_DATA_NO_COPY(subs_buf, subs_buf_size) );
				}

				if (ch->sai_buffer && ch->pck_encrypted) {
					assert(ch->sai_buffer_size);
					gf_filter_pck_set_property(pck, GF_PROP_PCK_CENC_SAI, &PROP_DATA(ch->sai_buffer, ch->sai_buffer_size) );
				}

				if (read->sigfrag) {
					GF_ISOFragmentBoundaryInfo finfo;
					if (gf_isom_sample_is_fragment_start(read->mov, ch->track, ch->sample_num, &finfo) ) {
						u64 start=0;
						u32 traf_start = finfo.seg_start_plus_one ? 2 : 1;

						if (finfo.seg_start_plus_one)
							gf_filter_pck_set_property(pck, GF_PROP_PCK_CUE_START, &PROP_BOOL(GF_TRUE));

						gf_filter_pck_set_property(pck, GF_PROP_PCK_FRAG_START, &PROP_UINT(traf_start));

						start = finfo.frag_start;
						if (finfo.seg_start_plus_one) start = finfo.seg_start_plus_one-1;
						gf_filter_pck_set_property(pck, GF_PROP_PCK_FRAG_RANGE, &PROP_FRAC64_INT(start, finfo.mdat_end));
						if (finfo.moof_template) {
							gf_filter_pck_set_property(pck, GF_PROP_PCK_MOOF_TEMPLATE, &PROP_DATA((u8 *)finfo.moof_template, finfo.moof_template_size));
						}
						if (finfo.sidx_end) {
							gf_filter_pck_set_property(pck, GF_PROP_PCK_SIDX_RANGE, &PROP_FRAC64_INT(finfo.sidx_start , finfo.sidx_end));
						}

						if (read->seg_name_changed) {
							const GF_PropertyValue *p = gf_filter_pid_get_property(read->pid, GF_PROP_PID_URL);
							read->seg_name_changed = GF_FALSE;
							if (p && p->value.string) {
								gf_filter_pck_set_property(pck, GF_PROP_PID_URL, &PROP_STRING(p->value.string));
							}
						}
					}
				}
				if (ch->sender_ntp) {
					gf_filter_pck_set_property(pck, GF_PROP_PCK_SENDER_NTP, &PROP_LONGUINT(ch->sender_ntp));
					if (ch->ntp_at_server_ntp) {
						gf_filter_pck_set_property(pck, GF_PROP_PCK_RECEIVER_NTP, &PROP_LONGUINT(ch->ntp_at_server_ntp));
					}
				}
				ch->eos_sent = GF_FALSE;

				//this might not be the true end of stream
				if ((ch->streamType==GF_STREAM_AUDIO) && (ch->sample_num == gf_isom_get_sample_count(read->mov, ch->track))) {
					gf_filter_pck_set_property(pck, GF_PROP_PCK_END_RANGE, &PROP_BOOL(GF_TRUE));
				}

				gf_filter_pck_send(pck);
				isor_reader_release_sample(ch);

				ch->last_valid_sample_data_offset = ch->sample_data_offset;
				nb_pck--;
			} else if (ch->last_state==GF_EOS) {
				if (ch->playing == 2) {
					if (in_is_eos) {
						ch->playing = GF_FALSE;
					} else {
						nb_forced_end++;
						check_forced_end = GF_TRUE;
					}
				}
				if (in_is_eos && !ch->eos_sent) {
					void *tfrf;
					const void *gf_isom_get_tfrf(GF_ISOFile *movie, u32 trackNumber);

					ch->eos_sent = GF_TRUE;
					read->eos_signaled = GF_TRUE;

					tfrf = (void *) gf_isom_get_tfrf(read->mov, ch->track);
					if (tfrf) {
						gf_filter_pid_set_info_str(ch->pid, ""smooth_tfrf"", &PROP_POINTER(tfrf) );
						ch->last_has_tfrf = GF_TRUE;
					} else if (ch->last_has_tfrf) {
						gf_filter_pid_set_info_str(ch->pid, ""smooth_tfrf"", NULL);
						ch->last_has_tfrf = GF_FALSE;
					}

					gf_filter_pid_set_eos(ch->pid);
				}
				break;
			} else {
				read->force_fetch = GF_TRUE;
				break;
			}
		}
		if (!min_offset_plus_one || (min_offset_plus_one - 1 > ch->last_valid_sample_data_offset))
			min_offset_plus_one = 1 + ch->last_valid_sample_data_offset;
	}
	if (read->mem_load_mode && min_offset_plus_one) {
		isoffin_purge_mem(read, min_offset_plus_one-1);
	}

	//we reached end of playback due to play range request, we must send eos - however for safety reason with DASH, we first need to cancel the input
	if (read->pid && check_forced_end && (nb_forced_end==count)) {
		//abort input
		GF_FilterEvent evt;
		GF_FEVT_INIT(evt, GF_FEVT_STOP, read->pid);
		gf_filter_pid_send_event(read->pid, &evt);
	}


	if (!is_active) {
		return GF_EOS;
	}
	//if (in_is_eos)
//	gf_filter_ask_rt_reschedule(filter, 1);
	return GF_OK;

}",1
"proto_register_sysdig_event(void)
{
    /* XXX Match up with Sysdig's names. */
    static hf_register_info hf[] = {
        { &hf_se_cpu_id,
          { ""CPU ID"", ""sysdig.cpu_id"",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_se_thread_id,
          { ""Thread ID"", ""sysdig.thread_id"",
            FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_se_event_length,
          { ""Event length"", ""sysdig.event_len"",
            FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_se_nparams,
          { ""Number of parameters"", ""sysdig.nparams"",
            FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_se_event_type,
          { ""Event type"", ""sysdig.event_type"",
            FT_UINT16, BASE_DEC, VALS(event_type_vals), 0, NULL, HFILL }
        },
        { &hf_se_param_lens,
          { ""Parameter lengths"", ""sysdig.param.lens"",
            FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_se_param_len,
          { ""Parameter length"", ""sysdig.param.len"",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },

/* Header field registration. Automatically generated by tools/generate-sysdig-event.py */
        { &hf_param_ID_bytes, { ""ID"", ""sysdig.param.syscall.ID"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_action_uint32, { ""action"", ""sysdig.param.cpu_hotplug.action"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_addr_bytes, { ""addr"", ""sysdig.param.ptrace.addr"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_addr_uint64, { ""addr"", ""sysdig.param.page_fault.addr"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_args_string, { ""Program arguments"", ""sysdig.param.execve.args"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_argument_uint64, { ""I/O control: argument"", ""sysdig.param.ioctl.argument"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_backlog_uint32, { ""backlog"", ""sysdig.param.listen.backlog"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_cgroups_bytes, { ""cgroups"", ""sysdig.param.execve.cgroups"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_clockid_uint8, { ""clockid"", ""sysdig.param.timerfd_create.clockid"", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_cmd_bytes, { ""cmd"", ""sysdig.param.semctl.cmd"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_cmd_int64, { ""cmd"", ""sysdig.param.bpf.cmd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_comm_string, { ""Command"", ""sysdig.param.execve.comm"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_cpu_sys_uint64, { ""cpu_sys"", ""sysdig.param.procinfo.cpu_sys"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_cpu_uint32, { ""cpu"", ""sysdig.param.cpu_hotplug.cpu"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_cpu_usr_uint64, { ""cpu_usr"", ""sysdig.param.procinfo.cpu_usr"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_cur_int64, { ""cur"", ""sysdig.param.setrlimit.cur"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_cwd_string, { ""Current working directory"", ""sysdig.param.execve.cwd"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_data_bytes, { ""data"", ""sysdig.param.ptrace.data"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_desc_string, { ""desc"", ""sysdig.param.notification.desc"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_description_string, { ""description"", ""sysdig.param.infra.description"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dev_string, { ""dev"", ""sysdig.param.mount.dev"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dev_uint32, { ""dev"", ""sysdig.param.openat.dev"", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_dir_string, { ""dir"", ""sysdig.param.mount.dir"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dirfd_int64, { ""dirfd"", ""sysdig.param.openat.dirfd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_domain_bytes, { ""domain"", ""sysdig.param.socketpair.domain"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dpid_bytes, { ""dpid"", ""sysdig.param.signaldeliver.dpid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_bhardlimit_uint64, { ""dqb_bhardlimit"", ""sysdig.param.quotactl.dqb_bhardlimit"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_bsoftlimit_uint64, { ""dqb_bsoftlimit"", ""sysdig.param.quotactl.dqb_bsoftlimit"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_btime_bytes, { ""dqb_btime"", ""sysdig.param.quotactl.dqb_btime"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_curspace_uint64, { ""dqb_curspace"", ""sysdig.param.quotactl.dqb_curspace"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_ihardlimit_uint64, { ""dqb_ihardlimit"", ""sysdig.param.quotactl.dqb_ihardlimit"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_isoftlimit_uint64, { ""dqb_isoftlimit"", ""sysdig.param.quotactl.dqb_isoftlimit"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_dqb_itime_bytes, { ""dqb_itime"", ""sysdig.param.quotactl.dqb_itime"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dqi_bgrace_bytes, { ""dqi_bgrace"", ""sysdig.param.quotactl.dqi_bgrace"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dqi_flags_bytes, { ""dqi_flags"", ""sysdig.param.quotactl.dqi_flags"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_dqi_igrace_bytes, { ""dqi_igrace"", ""sysdig.param.quotactl.dqi_igrace"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_egid_bytes, { ""egid"", ""sysdig.param.getresgid.egid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_env_string, { ""env"", ""sysdig.param.execve.env"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_error_bytes, { ""error"", ""sysdig.param.page_fault.error"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_euid_bytes, { ""euid"", ""sysdig.param.getresuid.euid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_event_data_uint64, { ""event_data"", ""sysdig.param.sysdigevent.event_data"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_event_type_uint32, { ""event_type"", ""sysdig.param.sysdigevent.event_type"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_exe_string, { ""exe"", ""sysdig.param.execve.exe"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_fd1_int64, { ""fd1"", ""sysdig.param.pipe.fd1"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fd2_int64, { ""fd2"", ""sysdig.param.pipe.fd2"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fd_in_int64, { ""fd_in"", ""sysdig.param.splice.fd_in"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fd_int64, { ""fd"", ""sysdig.param.openat.fd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fd_out_int64, { ""fd_out"", ""sysdig.param.splice.fd_out"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fdlimit_int64, { ""fdlimit"", ""sysdig.param.vfork.fdlimit"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fdlimit_uint64, { ""fdlimit"", ""sysdig.param.execve.fdlimit"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_fds_bytes, { ""fds"", ""sysdig.param.ppoll.fds"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_filename_string, { ""filename"", ""sysdig.param.execve.filename"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_flags_bytes, { ""flags"", ""sysdig.param.linkat.flags"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_flags_uint32, { ""flags"", ""sysdig.param.accept.flags"", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_gid_bytes, { ""gid"", ""sysdig.param.getgid.gid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_gid_uint32, { ""gid"", ""sysdig.param.vfork.gid"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_how_bytes, { ""how"", ""sysdig.param.shutdown.how"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_id_int64, { ""id"", ""sysdig.param.tracer.id"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_id_string, { ""id"", ""sysdig.param.notification.id"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_id_uint32, { ""id"", ""sysdig.param.quotactl.id"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_image_string, { ""image"", ""sysdig.param.container.image"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_in_fd_int64, { ""in_fd"", ""sysdig.param.sendfile.in_fd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_initval_uint64, { ""initval"", ""sysdig.param.eventfd.initval"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_ino_uint64, { ""ino"", ""sysdig.param.pipe.ino"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_interval_bytes, { ""interval"", ""sysdig.param.nanosleep.interval"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_ip_uint64, { ""ip"", ""sysdig.param.page_fault.ip"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_json_string, { ""json"", ""sysdig.param.container.json"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_key_int32, { ""key"", ""sysdig.param.semget.key"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_length_uint64, { ""length"", ""sysdig.param.munmap.length"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_level_bytes, { ""level"", ""sysdig.param.getsockopt.level"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_linkdirfd_int64, { ""linkdirfd"", ""sysdig.param.symlinkat.linkdirfd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_linkpath_string, { ""linkpath"", ""sysdig.param.symlinkat.linkpath"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_loginuid_int32, { ""loginuid"", ""sysdig.param.execve.loginuid"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_mask_uint32, { ""mask"", ""sysdig.param.signalfd.mask"", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_max_int64, { ""max"", ""sysdig.param.setrlimit.max"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_maxevents_bytes, { ""maxevents"", ""sysdig.param.epoll_wait.maxevents"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_mode_bytes, { ""mode"", ""sysdig.param.access.mode"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_mode_uint32, { ""mode"", ""sysdig.param.openat.mode"", FT_UINT32, BASE_OCT, NULL, 0, NULL, HFILL } },
        { &hf_param_name_string, { ""name"", ""sysdig.param.openat.name"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_nativeID_uint16, { ""nativeID"", ""sysdig.param.syscall.nativeID"", FT_UINT16, BASE_DEC, VALS(nativeID_uint16_vals), 0, NULL, HFILL } },
        { &hf_param_newcur_int64, { ""newcur"", ""sysdig.param.prlimit.newcur"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_newdir_int64, { ""newdir"", ""sysdig.param.linkat.newdir"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_newdirfd_int64, { ""newdirfd"", ""sysdig.param.renameat.newdirfd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_newmax_int64, { ""newmax"", ""sysdig.param.prlimit.newmax"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_newpath_string, { ""newpath"", ""sysdig.param.linkat.newpath"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_next_bytes, { ""next"", ""sysdig.param.switch.next"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_nsems_int32, { ""nsems"", ""sysdig.param.semget.nsems"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_nsops_uint32, { ""nsops"", ""sysdig.param.semop.nsops"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_nstype_bytes, { ""nstype"", ""sysdig.param.setns.nstype"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_offset_uint64, { ""offset"", ""sysdig.param.sendfile.offset"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_oldcur_int64, { ""oldcur"", ""sysdig.param.prlimit.oldcur"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_olddir_int64, { ""olddir"", ""sysdig.param.linkat.olddir"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_olddirfd_int64, { ""olddirfd"", ""sysdig.param.renameat.olddirfd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_oldmax_int64, { ""oldmax"", ""sysdig.param.prlimit.oldmax"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_oldpath_string, { ""oldpath"", ""sysdig.param.linkat.oldpath"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_op_bytes, { ""op"", ""sysdig.param.futex.op"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_op_uint64, { ""op"", ""sysdig.param.seccomp.op"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_operation_bytes, { ""operation"", ""sysdig.param.flock.operation"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_optlen_uint32, { ""optlen"", ""sysdig.param.getsockopt.optlen"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_optname_bytes, { ""optname"", ""sysdig.param.getsockopt.optname"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_out_fd_int64, { ""out_fd"", ""sysdig.param.sendfile.out_fd"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_path_string, { ""path"", ""sysdig.param.mkdirat.path"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_peer_uint64, { ""peer"", ""sysdig.param.socketpair.peer"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_pgft_maj_uint64, { ""pgft_maj"", ""sysdig.param.execve.pgft_maj"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_pgft_min_uint64, { ""pgft_min"", ""sysdig.param.execve.pgft_min"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_pgid_bytes, { ""pgid"", ""sysdig.param.setpgid.pgid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_pgoffset_uint64, { ""pgoffset"", ""sysdig.param.mmap2.pgoffset"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_pid_bytes, { ""pid"", ""sysdig.param.setpgid.pid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_pos_uint64, { ""pos"", ""sysdig.param.pwritev.pos"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_prot_bytes, { ""prot"", ""sysdig.param.mmap2.prot"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_proto_uint32, { ""proto"", ""sysdig.param.socketpair.proto"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_ptid_bytes, { ""ptid"", ""sysdig.param.execve.ptid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_queuelen_uint32, { ""queuelen"", ""sysdig.param.accept.queuelen"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_queuemax_uint32, { ""queuemax"", ""sysdig.param.accept.queuemax"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_queuepct_uint8, { ""Accept queue per connection"", ""sysdig.param.accept.queuepct"", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_quota_fmt_bytes, { ""quota_fmt"", ""sysdig.param.quotactl.quota_fmt"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_quota_fmt_out_bytes, { ""quota_fmt_out"", ""sysdig.param.quotactl.quota_fmt_out"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_quotafilepath_string, { ""quotafilepath"", ""sysdig.param.quotactl.quotafilepath"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_ratio_uint32, { ""ratio"", ""sysdig.param.drop.ratio"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_request_bytes, { ""request"", ""sysdig.param.ptrace.request"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_request_uint64, { ""I/O control: request"", ""sysdig.param.ioctl.request"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_res_bytes, { ""res"", ""sysdig.param.linkat.res"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_res_int64, { ""res"", ""sysdig.param.fcntl.res"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_res_or_fd_bytes, { ""res_or_fd"", ""sysdig.param.bpf.res_or_fd"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_res_uint64, { ""res"", ""sysdig.param.mmap2.res"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_resource_bytes, { ""resource"", ""sysdig.param.prlimit.resource"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_rgid_bytes, { ""rgid"", ""sysdig.param.getresgid.rgid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_ruid_bytes, { ""ruid"", ""sysdig.param.getresuid.ruid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_scope_string, { ""scope"", ""sysdig.param.infra.scope"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_sem_flg_0_bytes, { ""sem_flg_0"", ""sysdig.param.semop.sem_flg_0"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_sem_flg_1_bytes, { ""sem_flg_1"", ""sysdig.param.semop.sem_flg_1"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_sem_num_0_uint16, { ""sem_num_0"", ""sysdig.param.semop.sem_num_0"", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_sem_num_1_uint16, { ""sem_num_1"", ""sysdig.param.semop.sem_num_1"", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_sem_op_0_int16, { ""sem_op_0"", ""sysdig.param.semop.sem_op_0"", FT_INT16, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_sem_op_1_int16, { ""sem_op_1"", ""sysdig.param.semop.sem_op_1"", FT_INT16, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_semflg_bytes, { ""semflg"", ""sysdig.param.semget.semflg"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_semid_int32, { ""semid"", ""sysdig.param.semctl.semid"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_semnum_int32, { ""semnum"", ""sysdig.param.semctl.semnum"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_sgid_bytes, { ""sgid"", ""sysdig.param.getresgid.sgid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_sig_bytes, { ""sig"", ""sysdig.param.signaldeliver.sig"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_sigmask_bytes, { ""sigmask"", ""sysdig.param.ppoll.sigmask"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_size_uint32, { ""size"", ""sysdig.param.pwritev.size"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_size_uint64, { ""size"", ""sysdig.param.sendfile.size"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_source_string, { ""source"", ""sysdig.param.infra.source"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_source_uint64, { ""source"", ""sysdig.param.socketpair.source"", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
        { &hf_param_special_string, { ""special"", ""sysdig.param.quotactl.special"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_spid_bytes, { ""spid"", ""sysdig.param.signaldeliver.spid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_status_bytes, { ""status"", ""sysdig.param.procexit.status"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_suid_bytes, { ""suid"", ""sysdig.param.getresuid.suid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_tags_bytes, { ""tags"", ""sysdig.param.tracer.tags"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_target_string, { ""target"", ""sysdig.param.symlinkat.target"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_tid_bytes, { ""tid"", ""sysdig.param.execve.tid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_timeout_bytes, { ""timeout"", ""sysdig.param.ppoll.timeout"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_timeout_int64, { ""timeout"", ""sysdig.param.poll.timeout"", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_tty_int32, { ""tty"", ""sysdig.param.execve.tty"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_tuple_bytes, { ""tuple"", ""sysdig.param.accept.tuple"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_type_bytes, { ""type"", ""sysdig.param.quotactl.type"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_type_string, { ""type"", ""sysdig.param.mount.type"", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_type_uint32, { ""type"", ""sysdig.param.container.type"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_uid_bytes, { ""uid"", ""sysdig.param.getuid.uid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_uid_uint32, { ""uid"", ""sysdig.param.vfork.uid"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_val_bytes, { ""val"", ""sysdig.param.getsockopt.val"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_val_int32, { ""val"", ""sysdig.param.semctl.val"", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_val_uint64, { ""val"", ""sysdig.param.futex.val"", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_vm_rss_uint32, { ""vm_rss"", ""sysdig.param.execve.vm_rss"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_vm_size_uint32, { ""vm_size"", ""sysdig.param.execve.vm_size"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_vm_swap_uint32, { ""vm_swap"", ""sysdig.param.execve.vm_swap"", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
        { &hf_param_vpid_bytes, { ""vpid"", ""sysdig.param.vfork.vpid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_vtid_bytes, { ""vtid"", ""sysdig.param.vfork.vtid"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_whence_bytes, { ""whence"", ""sysdig.param.llseek.whence"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_ret_bytes, { ""ret"", ""sysdig.param.procexit.ret"", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },
        { &hf_param_core_uint8, { ""core"", ""sysdig.param.procexit.core"", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },
    };

    /* Setup protocol subtree array */
    static gint *ett[] = {
        &ett_sysdig_event,
        &ett_sysdig_parm_lens,
        &ett_sysdig_syscall
    };

    /* Register the protocol name and description */
    proto_sysdig_event = proto_register_protocol(""Sysdig System Call"",
            ""Sysdig Event"", ""sysdig"");

    /* Required function calls to register the header fields and subtrees */
    proto_register_field_array(proto_sysdig_event, hf, array_length(hf));
    proto_register_subtree_array(ett, array_length(ett));

    register_dissector(""sysdig"", dissect_sysdig_event, proto_sysdig_event);
}",1
"void SparseFillEmptyRowsOpImpl(OpKernelContext* context,
                               AsyncOpKernel::DoneCallback done = nullptr) {
  // Note that setting this empty lambda as the default parameter value directly
  // can cause strange compiler/linker errors, so we do it like this instead.
  if (!done) {
    done = [] {};
  }

  const int kIndicesInput = 0;
  const int kValuesInput = 1;
  const int kDenseShapeInput = 2;
  const int kDefaultValueInput = 3;

  const Tensor& indices_t = context->input(kIndicesInput);
  const Tensor& values_t = context->input(kValuesInput);
  const Tensor& dense_shape_t = context->input(kDenseShapeInput);
  const Tensor& default_value_t = context->input(kDefaultValueInput);

  OP_REQUIRES_ASYNC(
      context, TensorShapeUtils::IsVector(dense_shape_t.shape()),
      errors::InvalidArgument(""dense_shape must be a vector, saw: "",
                              dense_shape_t.shape().DebugString()),
      done);
  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()),
                    errors::InvalidArgument(""indices must be a matrix, saw: "",
                                            indices_t.shape().DebugString()),
                    done);
  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()),
                    errors::InvalidArgument(""values must be a vector, saw: "",
                                            values_t.shape().DebugString()),
                    done);
  OP_REQUIRES_ASYNC(
      context, TensorShapeUtils::IsScalar(default_value_t.shape()),
      errors::InvalidArgument(""default_value must be a scalar, saw: "",
                              default_value_t.shape().DebugString()),
      done);
  // TODO(ebrevdo): add shape checks between values, indices,
  // Also add check that dense rank > 0.
  OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0,
                    errors::InvalidArgument(""Dense shape cannot be empty.""),
                    done);

  using FunctorType = functor::SparseFillEmptyRows;
  OP_REQUIRES_OK_ASYNC(context,
                       FunctorType()(context, default_value_t, indices_t,
                                     values_t, dense_shape_t, done),
                       done);
}",1
"Status ValidateInputs(const Tensor *a_indices, const Tensor *a_values,
                      const Tensor *a_shape, const Tensor *b) {
  if (!TensorShapeUtils::IsMatrix(a_indices->shape())) {
    return errors::InvalidArgument(
        ""Input a_indices should be a matrix but received shape: "",
        a_indices->shape().DebugString());
  }
  if (!TensorShapeUtils::IsVector(a_values->shape()) ||
      !TensorShapeUtils::IsVector(a_shape->shape())) {
    return errors::InvalidArgument(
        ""Inputs a_values and a_shape should be vectors ""
        ""but received shapes: "",
        a_values->shape().DebugString(), "" and "",
        a_shape->shape().DebugString());
  }
  if (a_shape->NumElements() != b->dims()) {
    return errors::InvalidArgument(
        ""Two operands have different ranks; received: "", a_shape->NumElements(),
        "" and "", b->dims());
  }
  const auto a_shape_flat = a_shape->flat();
  for (int i = 0; i < b->dims(); ++i) {
    if (a_shape_flat(i) != b->dim_size(i)) {
      return errors::InvalidArgument(
          ""Dimension "", i,
          "" does not equal (no broadcasting is supported): sparse side "",
          a_shape_flat(i), "" vs dense side "", b->dim_size(i));
    }
  }
  return Status::OK();
}",1
"static int ssl_check_dtls_clihlo_cookie(
                           mbedtls_ssl_context *ssl,
                           const unsigned char *cli_id, size_t cli_id_len,
                           const unsigned char *in, size_t in_len,
                           unsigned char *obuf, size_t buf_len, size_t *olen )
{
    size_t sid_len, cookie_len;
    unsigned char *p;

    /*
     * Structure of ClientHello with record and handshake headers,
     * and expected values. We don't need to check a lot, more checks will be
     * done when actually parsing the ClientHello - skipping those checks
     * avoids code duplication and does not make cookie forging any easier.
     *
     *  0-0  ContentType type;                  copied, must be handshake
     *  1-2  ProtocolVersion version;           copied
     *  3-4  uint16 epoch;                      copied, must be 0
     *  5-10 uint48 sequence_number;            copied
     * 11-12 uint16 length;                     (ignored)
     *
     * 13-13 HandshakeType msg_type;            (ignored)
     * 14-16 uint24 length;                     (ignored)
     * 17-18 uint16 message_seq;                copied
     * 19-21 uint24 fragment_offset;            copied, must be 0
     * 22-24 uint24 fragment_length;            (ignored)
     *
     * 25-26 ProtocolVersion client_version;    (ignored)
     * 27-58 Random random;                     (ignored)
     * 59-xx SessionID session_id;              1 byte len + sid_len content
     * 60+   opaque cookie<0..2^8-1>;           1 byte len + content
     *       ...
     *
     * Minimum length is 61 bytes.
     */
    MBEDTLS_SSL_DEBUG_MSG( 4, ( ""check cookie: in_len=%u"",
                                (unsigned) in_len ) );
    MBEDTLS_SSL_DEBUG_BUF( 4, ""cli_id"", cli_id, cli_id_len );
    if( in_len < 61 )
    {
        MBEDTLS_SSL_DEBUG_MSG( 4, ( ""check cookie: record too short"" ) );
        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }
    if( in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
        in[3] != 0 || in[4] != 0 ||
        in[19] != 0 || in[20] != 0 || in[21] != 0 )
    {
        MBEDTLS_SSL_DEBUG_MSG( 4, ( ""check cookie: not a good ClientHello"" ) );
        MBEDTLS_SSL_DEBUG_MSG( 4, ( ""    type=%u epoch=%u fragment_offset=%u"",
                                    in[0],
                                    (unsigned) in[3] << 8 | in[4],
                                    (unsigned) in[19] << 16 | in[20] << 8 | in[21] ) );
        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    sid_len = in[59];
    if( sid_len > in_len - 61 )
    {
        MBEDTLS_SSL_DEBUG_MSG( 4, ( ""check cookie: sid_len=%u > %u"",
                                    (unsigned) sid_len,
                                    (unsigned) in_len - 61 ) );
        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }
    MBEDTLS_SSL_DEBUG_BUF( 4, ""sid received from network"",
                           in + 60, sid_len );

    cookie_len = in[60 + sid_len];
    if( cookie_len > in_len - 60 ) {
        MBEDTLS_SSL_DEBUG_MSG( 4, ( ""check cookie: cookie_len=%u > %u"",
                                    (unsigned) cookie_len,
                                    (unsigned) in_len - 60 ) );
        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
    }

    MBEDTLS_SSL_DEBUG_BUF( 4, ""cookie received from network"",
                           in + sid_len + 61, cookie_len );
    if( ssl->conf->f_cookie_check( ssl->conf->p_cookie,
                                   in + sid_len + 61, cookie_len,
                                   cli_id, cli_id_len ) == 0 )
    {
        MBEDTLS_SSL_DEBUG_MSG( 4, ( ""check cookie: valid"" ) );
        return( 0 );
    }

    /*
     * If we get here, we've got an invalid cookie, let's prepare HVR.
     *
     *  0-0  ContentType type;                  copied
     *  1-2  ProtocolVersion version;           copied
     *  3-4  uint16 epoch;                      copied
     *  5-10 uint48 sequence_number;            copied
     * 11-12 uint16 length;                     olen - 13
     *
     * 13-13 HandshakeType msg_type;            hello_verify_request
     * 14-16 uint24 length;                     olen - 25
     * 17-18 uint16 message_seq;                copied
     * 19-21 uint24 fragment_offset;            copied
     * 22-24 uint24 fragment_length;            olen - 25
     *
     * 25-26 ProtocolVersion server_version;    0xfe 0xff
     * 27-27 opaque cookie<0..2^8-1>;           cookie_len = olen - 27, cookie
     *
     * Minimum length is 28.
     */
    if( buf_len < 28 )
        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );

    /* Copy most fields and adapt others */
    memcpy( obuf, in, 25 );
    obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
    obuf[25] = 0xfe;
    obuf[26] = 0xff;

    /* Generate and write actual cookie */
    p = obuf + 28;
    if( ssl->conf->f_cookie_write( ssl->conf->p_cookie,
                                   &p, obuf + buf_len,
                                   cli_id, cli_id_len ) != 0 )
    {
        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
    }

    *olen = p - obuf;

    /* Go back and fill length fields */
    obuf[27] = (unsigned char)( *olen - 28 );

    obuf[14] = obuf[22] = MBEDTLS_BYTE_2( *olen - 25 );
    obuf[15] = obuf[23] = MBEDTLS_BYTE_1( *olen - 25 );
    obuf[16] = obuf[24] = MBEDTLS_BYTE_0( *olen - 25 );

    MBEDTLS_PUT_UINT16_BE( *olen - 13, obuf, 11 );

    return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
}",1
"njs_array_prototype_sort(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
    njs_index_t unused)
{
    int64_t                i, und, len, nlen, length;
    njs_int_t              ret, fast_path;
    njs_array_t            *array;
    njs_value_t            *this, *comparefn, *start, *strings;
    njs_array_sort_ctx_t   ctx;
    njs_array_sort_slot_t  *p, *end, *slots, *nslots;

    comparefn = njs_arg(args, nargs, 1);

    if (njs_is_defined(comparefn)) {
        if (njs_slow_path(!njs_is_function(comparefn))) {
            njs_type_error(vm, ""comparefn must be callable or undefined"");
            return NJS_ERROR;
        }

        ctx.function = njs_function(comparefn);

    } else {
        ctx.function = NULL;
    }

    this = njs_argument(args, 0);

    ret = njs_value_to_object(vm, this);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    ret = njs_value_length(vm, this, &length);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    if (njs_slow_path(length < 2)) {
        vm->retval = *this;
        return NJS_OK;
    }

    slots = NULL;
    ctx.vm = vm;
    ctx.strings.separate = 0;
    ctx.strings.pointer = 0;
    ctx.exception = 0;

    fast_path = njs_is_fast_array(this);

    if (njs_fast_path(fast_path)) {
        array = njs_array(this);
        start = array->start;

        slots = njs_mp_alloc(vm->mem_pool,
                             sizeof(njs_array_sort_slot_t) * length);
        if (njs_slow_path(slots == NULL)) {
                return NJS_ERROR;
        }

        und = 0;
        p = slots;

        for (i = 0; i < length; i++) {
            if (njs_slow_path(!njs_is_valid(&start[i]))) {
                fast_path = 0;
                njs_mp_free(vm->mem_pool, slots);
                slots = NULL;
                goto slow_path;
            }

            if (njs_slow_path(njs_is_undefined(&start[i]))) {
                und++;
                continue;
            }

            p->value = start[i];
            p->pos = i;
            p->str = NULL;
            p++;
        }

        len = p - slots;

    } else {

slow_path:

        und = 0;
        p = NULL;
        end = NULL;

        for (i = 0; i < length; i++) {
            if (p >= end) {
                nlen = njs_min(njs_max((p - slots) * 2, 8), length);
                nslots = njs_mp_alloc(vm->mem_pool,
                                      sizeof(njs_array_sort_slot_t) * nlen);
                if (njs_slow_path(nslots == NULL)) {
                    njs_memory_error(vm);
                    return NJS_ERROR;
                }

                if (slots != NULL) {
                    p = (void *) njs_cpymem(nslots, slots,
                                  sizeof(njs_array_sort_slot_t) * (p - slots));
                    njs_mp_free(vm->mem_pool, slots);

                } else {
                    p = nslots;
                }

                slots = nslots;
                end = slots + nlen;
            }

            ret = njs_value_property_i64(vm, this, i, &p->value);
            if (njs_slow_path(ret == NJS_ERROR)) {
                ret = NJS_ERROR;
                goto exception;
            }

            if (ret == NJS_DECLINED) {
                continue;
            }

            if (njs_is_undefined(&p->value)) {
                und++;
                continue;
            }

            p->pos = i;
            p->str = NULL;
            p++;
        }

        len = p - slots;
    }

    strings = njs_arr_init(vm->mem_pool, &ctx.strings, NULL, len + 1,
                           sizeof(njs_value_t));
    if (njs_slow_path(strings == NULL)) {
        ret = NJS_ERROR;
        goto exception;
    }

    njs_qsort(slots, len, sizeof(njs_array_sort_slot_t), njs_array_compare,
              &ctx);

    if (ctx.exception) {
        ret = NJS_ERROR;
        goto exception;
    }

    if (njs_fast_path(fast_path)) {
        array = njs_array(this);
        start = array->start;

        for (i = 0; i < len; i++) {
            start[i] = slots[i].value;
        }

        for (i = len; und-- > 0; i++) {
            start[i] = njs_value_undefined;
        }

    } else {
        for (i = 0; i < len; i++) {
            if (slots[i].pos != i) {
                ret = njs_value_property_i64_set(vm, this, i, &slots[i].value);
                if (njs_slow_path(ret == NJS_ERROR)) {
                    goto exception;
                }
            }
        }

        for (i = len; und-- > 0; i++) {
            ret = njs_value_property_i64_set(vm, this, i,
                                          njs_value_arg(&njs_value_undefined));
            if (njs_slow_path(ret == NJS_ERROR)) {
                goto exception;
            }
        }

        for (; i < length; i++) {
            ret = njs_value_property_i64_delete(vm, this, i, NULL);
            if (njs_slow_path(ret == NJS_ERROR)) {
                goto exception;
            }
        }
    }

    vm->retval = *this;

    ret = NJS_OK;

exception:

    if (slots != NULL) {
        njs_mp_free(vm->mem_pool, slots);
    }

    njs_arr_destroy(&ctx.strings);

    return ret;
}",1
"GF_Err xtra_box_read(GF_Box *s, GF_BitStream *bs)
{
	GF_XtraBox *ptr = (GF_XtraBox *)s;
	while (ptr->size) {
		GF_XtraTag *tag;
		u32 prop_type = 0;

		char *data=NULL, *data2=NULL;
		ISOM_DECREASE_SIZE_NO_ERR(ptr, 8)
		s32 tag_size = gf_bs_read_u32(bs);
		u32 name_size = gf_bs_read_u32(bs);
		if (tag_size < 8) return GF_ISOM_INVALID_FILE;

		tag_size -= 8;
		if ((tag_size>ptr->size) || (name_size>ptr->size)) {
			return GF_ISOM_INVALID_FILE;
		}
		ISOM_DECREASE_SIZE_NO_ERR(ptr, 10)

		ISOM_DECREASE_SIZE_NO_ERR(ptr, name_size)
		data = gf_malloc(sizeof(char) * (name_size+1));
		gf_bs_read_data(bs, data, name_size);
		data[name_size] = 0;
		tag_size-=name_size;

		u32 flags = gf_bs_read_u32(bs);
		u32 prop_size = gf_bs_read_u32(bs);
		tag_size-=8;

		if (prop_size>4) {
			tag_size-=2;
			prop_type = gf_bs_read_u16(bs);
			prop_size -= 6;
			ISOM_DECREASE_SIZE_NO_ERR(ptr, prop_size)
			//add 2 extra bytes for UTF16 case string dump
			data2 = gf_malloc(sizeof(char) * (prop_size+2));
			gf_bs_read_data(bs, data2, prop_size);
			data2[prop_size] = 0;
			data2[prop_size+1] = 0;
			tag_size-=prop_size;
		} else {
			prop_size = 0;
		}
		GF_SAFEALLOC(tag, GF_XtraTag)
		tag->flags = flags;
		tag->name = data;
		tag->prop_size = prop_size;
		tag->prop_value = data2;
		tag->prop_type = prop_type;
		gf_list_add(ptr->tags, tag);

		if (tag_size) {
			GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[isom] invalid tag size in Xtra !\n""));
		}
	}
	return GF_OK;
}",1
"Status Examples::Initialize(OpKernelContext* const context,
                            const ModelWeights& weights,
                            const int num_sparse_features,
                            const int num_sparse_features_with_values,
                            const int num_dense_features) {
  num_features_ = num_sparse_features + num_dense_features;

  OpInputList sparse_example_indices_inputs;
  TF_RETURN_IF_ERROR(context->input_list(""sparse_example_indices"",
                                         &sparse_example_indices_inputs));
  if (sparse_example_indices_inputs.size() != num_sparse_features)
    return errors::InvalidArgument(
        ""Expected "", num_sparse_features,
        "" tensors in sparse_example_indices but got "",
        sparse_example_indices_inputs.size());
  OpInputList sparse_feature_indices_inputs;
  TF_RETURN_IF_ERROR(context->input_list(""sparse_feature_indices"",
                                         &sparse_feature_indices_inputs));
  if (sparse_feature_indices_inputs.size() != num_sparse_features)
    return errors::InvalidArgument(
        ""Expected "", num_sparse_features,
        "" tensors in sparse_feature_indices but got "",
        sparse_feature_indices_inputs.size());
  OpInputList sparse_feature_values_inputs;
  if (num_sparse_features_with_values > 0) {
    TF_RETURN_IF_ERROR(context->input_list(""sparse_feature_values"",
                                           &sparse_feature_values_inputs));
    if (sparse_feature_values_inputs.size() != num_sparse_features_with_values)
      return errors::InvalidArgument(
          ""Expected "", num_sparse_features_with_values,
          "" tensors in sparse_feature_values but got "",
          sparse_feature_values_inputs.size());
  }

  const Tensor* example_weights_t;
  TF_RETURN_IF_ERROR(context->input(""example_weights"", &example_weights_t));
  auto example_weights = example_weights_t->flat();

  if (example_weights.size() >= std::numeric_limits::max()) {
    return errors::InvalidArgument(strings::Printf(
        ""Too many examples in a mini-batch: %zu > %d"", example_weights.size(),
        std::numeric_limits::max()));
  }

  // The static_cast here is safe since num_examples can be at max an int.
  const int num_examples = static_cast(example_weights.size());
  const Tensor* example_labels_t;
  TF_RETURN_IF_ERROR(context->input(""example_labels"", &example_labels_t));
  auto example_labels = example_labels_t->flat();

  OpInputList dense_features_inputs;
  TF_RETURN_IF_ERROR(
      context->input_list(""dense_features"", &dense_features_inputs));

  examples_.clear();
  examples_.resize(num_examples);
  probabilities_.resize(num_examples);
  sampled_index_.resize(num_examples);
  sampled_count_.resize(num_examples);
  for (int example_id = 0; example_id < num_examples; ++example_id) {
    Example* const example = &examples_[example_id];
    example->sparse_features_.resize(num_sparse_features);
    example->dense_vectors_.resize(num_dense_features);
    example->example_weight_ = example_weights(example_id);
    example->example_label_ = example_labels(example_id);
  }
  const DeviceBase::CpuWorkerThreads& worker_threads =
      *context->device()->tensorflow_cpu_worker_threads();
  TF_RETURN_IF_ERROR(CreateSparseFeatureRepresentation(
      worker_threads, num_examples, num_sparse_features, weights,
      sparse_example_indices_inputs, sparse_feature_indices_inputs,
      sparse_feature_values_inputs, &examples_));
  TF_RETURN_IF_ERROR(CreateDenseFeatureRepresentation(
      worker_threads, num_examples, num_dense_features, weights,
      dense_features_inputs, &examples_));
  TF_RETURN_IF_ERROR(ComputeSquaredNormPerExample(
      worker_threads, num_examples, num_sparse_features, num_dense_features,
      &examples_));
  return Status::OK();
}",1
"char *make_argv(char *buf, size_t len, int argc, char **argv)
{
	size_t left= len;
	const char *arg;

	buf[0]= 0;
	++argv; --argc;
	while (argc > 0 && left > 0)
	{
		arg = *argv;
		if (strncmp(*argv, ""--password"", strlen(""--password"")) == 0) {
			arg = ""--password=..."";
		}
		if (strncmp(*argv, ""--encrypt-key"",
				strlen(""--encrypt-key"")) == 0) {
			arg = ""--encrypt-key=..."";
		}
		if (strncmp(*argv, ""--encrypt_key"",
				strlen(""--encrypt_key"")) == 0) {
			arg = ""--encrypt_key=..."";
		}
		if (strncmp(*argv, ""--transition-key"",
				strlen(""--transition-key"")) == 0) {
			arg = ""--transition-key=..."";
		}
		if (strncmp(*argv, ""--transition_key"",
				strlen(""--transition_key"")) == 0) {
			arg = ""--transition_key=..."";
		}
		left-= ut_snprintf(buf + len - left, left,
			""%s%c"", arg, argc > 1 ? ' ' : 0);
		++argv; --argc;
	}

	return buf;
}",1
"GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)
{
	u32 i, sceneT, odT, descIndex, size, size64;
	GF_InitialObjectDescriptor *iod;
	GF_SLConfig slc;
	GF_ISOSample *samp;
	Bool remove_ocr;
	u8 *buffer;
	char buf64[5000], sdpLine[5100];


	gf_isom_sdp_clean(file);

	if (bandwidth) {
		sprintf(buf64, ""b=AS:%d"", bandwidth);
		gf_isom_sdp_add_line(file, buf64);
	}
    //xtended attribute for copyright
    if (gf_sys_is_test_mode()) {
        sprintf(buf64, ""a=x-copyright: %s"", ""MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)"");
    } else {
        sprintf(buf64, ""a=x-copyright: MP4/3GP File hinted with GPAC %s - %s"", gf_gpac_version(), gf_gpac_copyright() );
    }
	gf_isom_sdp_add_line(file, buf64);

	if (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;

	odT = sceneT = 0;
	for (i=0; iESDescriptors)) {
			esd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);
			gf_odf_desc_del((GF_Descriptor *) esd);
			gf_list_rem(iod->ESDescriptors, 0);
		}


		/*get OD esd, and embbed stream data if possible*/
		if (odT) {
			esd = gf_isom_get_esd(file, odT, 1);
			if (gf_isom_get_sample_count(file, odT)==1) {
				samp = gf_isom_get_sample(file, odT, 1, &descIndex);
				if (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {
					InitSL_NULL(&slc);
					slc.predefined = 0;
					slc.hasRandomAccessUnitsOnlyFlag = 1;
					slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);
					slc.OCRResolution = 1000;
					slc.startCTS = samp->DTS+samp->CTS_Offset;
					slc.startDTS = samp->DTS;
					//set the SL for future extraction
					gf_isom_set_extraction_slc(file, odT, 1, &slc);

					size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);
					buf64[size64] = 0;
					sprintf(sdpLine, ""data:application/mpeg4-od-au;base64,%s"", buf64);

					if (esd->decoderConfig) {
						esd->decoderConfig->avgBitrate = 0;
						esd->decoderConfig->bufferSizeDB = samp->dataLength;
						esd->decoderConfig->maxBitrate = 0;
					}
					size64 = (u32) strlen(sdpLine)+1;
					esd->URLString = (char*)gf_malloc(sizeof(char) * size64);
					strcpy(esd->URLString, sdpLine);
				} else {
					GF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (""[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\n""));
					is_ok = 0;
				}
				gf_isom_sample_del(&samp);
			}
			if (remove_ocr) esd->OCRESID = 0;
			else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;

			//OK, add this to our IOD
			gf_list_add(iod->ESDescriptors, esd);
		}

		esd = gf_isom_get_esd(file, sceneT, 1);
		if (gf_isom_get_sample_count(file, sceneT)==1) {
			samp = gf_isom_get_sample(file, sceneT, 1, &descIndex);
			if (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {

				slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);
				slc.OCRResolution = 1000;
				slc.startCTS = samp->DTS+samp->CTS_Offset;
				slc.startDTS = samp->DTS;
				//set the SL for future extraction
				gf_isom_set_extraction_slc(file, sceneT, 1, &slc);
				//encode in Base64 the sample
				size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);
				buf64[size64] = 0;
				sprintf(sdpLine, ""data:application/mpeg4-bifs-au;base64,%s"", buf64);

				if (esd->decoderConfig) {
					esd->decoderConfig->avgBitrate = 0;
					esd->decoderConfig->bufferSizeDB = samp->dataLength;
					esd->decoderConfig->maxBitrate = 0;
				}
				esd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));
				strcpy(esd->URLString, sdpLine);
			} else {
				GF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (""[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\n""));
				is_ok = 0;
			}
			gf_isom_sample_del(&samp);
		}
		if (remove_ocr) esd->OCRESID = 0;
		else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;

		gf_list_add(iod->ESDescriptors, esd);

		if (is_ok) {
			u32 has_a, has_v, has_i_a, has_i_v;
			has_a = has_v = has_i_a = has_i_v = 0;
			for (i=0; idecoderConfig) {
					if (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {
						if (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;
						else has_v++;
					} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {
						if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;
						else has_a++;
					}
				}
				gf_odf_desc_del((GF_Descriptor *)esd);
			}
			/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/
			if (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {
				sprintf(sdpLine, ""a=isma-compliance:1,1.0,1"");
				gf_isom_sdp_add_line(file, sdpLine);
			}
		}
	}

	//encode the IOD
	buffer = NULL;
	size = 0;
	gf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);
	gf_odf_desc_del((GF_Descriptor *)iod);

	//encode in Base64 the iod
	size64 = gf_base64_encode(buffer, size, buf64, 2000);
	buf64[size64] = 0;
	gf_free(buffer);

	sprintf(sdpLine, ""a=mpeg4-iod:\""data:application/mpeg4-iod;base64,%s\"""", buf64);
	gf_isom_sdp_add_line(file, sdpLine);

	return GF_OK;
}",1
"mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)
{
  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */
  const mrb_irep *irep = proc->body.irep;
  const mrb_pool_value *pool = irep->pool;
  const mrb_sym *syms = irep->syms;
  mrb_code insn;
  int ai = mrb_gc_arena_save(mrb);
  struct mrb_jmpbuf *prev_jmp = mrb->jmp;
  struct mrb_jmpbuf c_jmp;
  uint32_t a;
  uint16_t b;
  uint16_t c;
  mrb_sym mid;
  const struct mrb_irep_catch_handler *ch;

#ifdef DIRECT_THREADED
  static const void * const optable[] = {
#define OPCODE(x,_) &&L_OP_ ## x,
#include ""mruby/ops.h""
#undef OPCODE
  };
#endif

  mrb_bool exc_catched = FALSE;
RETRY_TRY_BLOCK:

  MRB_TRY(&c_jmp) {

  if (exc_catched) {
    exc_catched = FALSE;
    mrb_gc_arena_restore(mrb, ai);
    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)
      goto L_BREAK;
    goto L_RAISE;
  }
  mrb->jmp = &c_jmp;
  mrb_vm_ci_proc_set(mrb->c->ci, proc);

#define regs (mrb->c->ci->stack)
  INIT_DISPATCH {
    CASE(OP_NOP, Z) {
      /* do nothing */
      NEXT;
    }

    CASE(OP_MOVE, BB) {
      regs[a] = regs[b];
      NEXT;
    }

    CASE(OP_LOADL, BB) {
      switch (pool[b].tt) {   /* number */
      case IREP_TT_INT32:
        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);
        break;
      case IREP_TT_INT64:
#if defined(MRB_INT64)
        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);
        break;
#else
#if defined(MRB_64BIT)
        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {
          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);
          break;
        }
#endif
        goto L_INT_OVERFLOW;
#endif
      case IREP_TT_BIGINT:
        goto L_INT_OVERFLOW;
#ifndef MRB_NO_FLOAT
      case IREP_TT_FLOAT:
        regs[a] = mrb_float_value(mrb, pool[b].u.f);
        break;
#endif
      default:
        /* should not happen (tt:string) */
        regs[a] = mrb_nil_value();
        break;
      }
      NEXT;
    }

    CASE(OP_LOADI, BB) {
      SET_FIXNUM_VALUE(regs[a], b);
      NEXT;
    }

    CASE(OP_LOADINEG, BB) {
      SET_FIXNUM_VALUE(regs[a], -b);
      NEXT;
    }

    CASE(OP_LOADI__1,B) goto L_LOADI;
    CASE(OP_LOADI_0,B) goto L_LOADI;
    CASE(OP_LOADI_1,B) goto L_LOADI;
    CASE(OP_LOADI_2,B) goto L_LOADI;
    CASE(OP_LOADI_3,B) goto L_LOADI;
    CASE(OP_LOADI_4,B) goto L_LOADI;
    CASE(OP_LOADI_5,B) goto L_LOADI;
    CASE(OP_LOADI_6,B) goto L_LOADI;
    CASE(OP_LOADI_7, B) {
    L_LOADI:
      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);
      NEXT;
    }

    CASE(OP_LOADI16, BS) {
      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);
      NEXT;
    }

    CASE(OP_LOADI32, BSS) {
      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));
      NEXT;
    }

    CASE(OP_LOADSYM, BB) {
      SET_SYM_VALUE(regs[a], syms[b]);
      NEXT;
    }

    CASE(OP_LOADNIL, B) {
      SET_NIL_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_LOADSELF, B) {
      regs[a] = regs[0];
      NEXT;
    }

    CASE(OP_LOADT, B) {
      SET_TRUE_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_LOADF, B) {
      SET_FALSE_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_GETGV, BB) {
      mrb_value val = mrb_gv_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETGV, BB) {
      mrb_gv_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETSV, BB) {
      mrb_value val = mrb_vm_special_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETSV, BB) {
      mrb_vm_special_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETIV, BB) {
      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);
      NEXT;
    }

    CASE(OP_SETIV, BB) {
      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETCV, BB) {
      mrb_value val;
      val = mrb_vm_cv_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETCV, BB) {
      mrb_vm_cv_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETIDX, B) {
      mrb_value va = regs[a], vb = regs[a+1];
      switch (mrb_type(va)) {
      case MRB_TT_ARRAY:
        if (!mrb_integer_p(vb)) goto getidx_fallback;
        regs[a] = mrb_ary_entry(va, mrb_integer(vb));
        break;
      case MRB_TT_HASH:
        regs[a] = mrb_hash_get(mrb, va, vb);
        break;
      case MRB_TT_STRING:
        switch (mrb_type(vb)) {
        case MRB_TT_INTEGER:
        case MRB_TT_STRING:
        case MRB_TT_RANGE:
          regs[a] = mrb_str_aref(mrb, va, vb, mrb_undef_value());
          break;
        default:
          goto getidx_fallback;
        }
        break;
      default:
      getidx_fallback:
        mid = MRB_OPSYM(aref);
        goto L_SEND_SYM;
      }
      NEXT;
    }

    CASE(OP_SETIDX, B) {
      c = 2;
      mid = MRB_OPSYM(aset);
      SET_NIL_VALUE(regs[a+3]);
      goto L_SENDB_SYM;
    }

    CASE(OP_GETCONST, BB) {
      regs[a] = mrb_vm_const_get(mrb, syms[b]);
      NEXT;
    }

    CASE(OP_SETCONST, BB) {
      mrb_vm_const_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETMCNST, BB) {
      regs[a] = mrb_const_get(mrb, regs[a], syms[b]);
      NEXT;
    }

    CASE(OP_SETMCNST, BB) {
      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETUPVAR, BBB) {
      mrb_value *regs_a = regs + a;
      struct REnv *e = uvenv(mrb, c);

      if (e && b < MRB_ENV_LEN(e)) {
        *regs_a = e->stack[b];
      }
      else {
        *regs_a = mrb_nil_value();
      }
      NEXT;
    }

    CASE(OP_SETUPVAR, BBB) {
      struct REnv *e = uvenv(mrb, c);

      if (e) {
        mrb_value *regs_a = regs + a;

        if (b < MRB_ENV_LEN(e)) {
          e->stack[b] = *regs_a;
          mrb_write_barrier(mrb, (struct RBasic*)e);
        }
      }
      NEXT;
    }

    CASE(OP_JMP, S) {
      pc += (int16_t)a;
      JUMP;
    }
    CASE(OP_JMPIF, BS) {
      if (mrb_test(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }
    CASE(OP_JMPNOT, BS) {
      if (!mrb_test(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }
    CASE(OP_JMPNIL, BS) {
      if (mrb_nil_p(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }

    CASE(OP_JMPUW, S) {
      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);
      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {
        struct RBreak *brk = (struct RBreak*)mrb->exc;
        mrb_value target = mrb_break_value_get(brk);
        mrb_assert(mrb_integer_p(target));
        a = (uint32_t)mrb_integer(target);
        mrb_assert(a >= 0 && a < irep->ilen);
      }
      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {
        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);
        if (ch) {
          /* avoiding a jump from a catch handler into the same handler */
          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {
            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));
          }
        }
      }
      CHECKPOINT_END(RBREAK_TAG_JUMP);

      mrb->exc = NULL; /* clear break object */
      pc = irep->iseq + a;
      JUMP;
    }

    CASE(OP_EXCEPT, B) {
      mrb_value exc;

      if (mrb->exc == NULL) {
        exc = mrb_nil_value();
      }
      else {
        switch (mrb->exc->tt) {
        case MRB_TT_BREAK:
        case MRB_TT_EXCEPTION:
          exc = mrb_obj_value(mrb->exc);
          break;
        default:
          mrb_assert(!""bad mrb_type"");
          exc = mrb_nil_value();
          break;
        }
        mrb->exc = NULL;
      }
      regs[a] = exc;
      NEXT;
    }
    CASE(OP_RESCUE, BB) {
      mrb_value exc = regs[a];  /* exc on stack */
      mrb_value e = regs[b];
      struct RClass *ec;

      switch (mrb_type(e)) {
      case MRB_TT_CLASS:
      case MRB_TT_MODULE:
        break;
      default:
        {
          mrb_value exc;

          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,
                                    ""class or module required for rescue clause"");
          mrb_exc_set(mrb, exc);
          goto L_RAISE;
        }
      }
      ec = mrb_class_ptr(e);
      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));
      NEXT;
    }

    CASE(OP_RAISEIF, B) {
      mrb_value exc = regs[a];
      if (mrb_break_p(exc)) {
        mrb->exc = mrb_obj_ptr(exc);
        goto L_BREAK;
      }
      mrb_exc_set(mrb, exc);
      if (mrb->exc) {
        goto L_RAISE;
      }
      NEXT;
    }

    CASE(OP_SSEND, BBB) {
      regs[a] = regs[0];
      insn = OP_SEND;
    }
    goto L_SENDB;

    CASE(OP_SSENDB, BBB) {
      regs[a] = regs[0];
    }
    goto L_SENDB;

    CASE(OP_SEND, BBB)
    goto L_SENDB;

    L_SEND_SYM:
    c = 1;
    /* push nil after arguments */
    SET_NIL_VALUE(regs[a+2]);
    goto L_SENDB_SYM;

    CASE(OP_SENDB, BBB)
    L_SENDB:
    mid = syms[b];
    L_SENDB_SYM:
    {
      mrb_callinfo *ci = mrb->c->ci;
      mrb_method_t m;
      struct RClass *cls;
      mrb_value recv, blk;

      ARGUMENT_NORMALIZE(a, &c, insn);

      recv = regs[a];
      cls = mrb_class(mrb, recv);
      m = mrb_method_search_vm(mrb, &cls, mid);
      if (MRB_METHOD_UNDEF_P(m)) {
        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);
        mid = MRB_SYM(method_missing);
      }

      /* push callinfo */
      ci = cipush(mrb, a, 0, cls, NULL, mid, c);

      if (MRB_METHOD_CFUNC_P(m)) {
        if (MRB_METHOD_PROC_P(m)) {
          struct RProc *p = MRB_METHOD_PROC(m);

          mrb_vm_ci_proc_set(ci, p);
          recv = p->body.func(mrb, recv);
        }
        else {
          if (MRB_METHOD_NOARG_P(m)) {
            check_method_noarg(mrb, ci);
          }
          recv = MRB_METHOD_FUNC(m)(mrb, recv);
        }
        mrb_gc_arena_shrink(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        ci = mrb->c->ci;
        if (mrb_proc_p(blk)) {
          struct RProc *p = mrb_proc_ptr(blk);
          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {
            p->flags |= MRB_PROC_ORPHAN;
          }
        }
        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */
          if (ci->cci == CINFO_RESUMED) {
            mrb->jmp = prev_jmp;
            return recv;
          }
          else {
            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
            proc = ci[-1].proc;
            irep = proc->body.irep;
            pool = irep->pool;
            syms = irep->syms;
          }
        }
        ci->stack[0] = recv;
        /* pop stackpos */
        ci = cipop(mrb);
        pc = ci->pc;
      }
      else {
        /* setup environment for calling method */
        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);
        pc = irep->iseq;
      }
    }
    JUMP;

    CASE(OP_CALL, Z) {
      mrb_callinfo *ci = mrb->c->ci;
      mrb_value recv = ci->stack[0];
      struct RProc *m = mrb_proc_ptr(recv);

      /* replace callinfo */
      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);
      mrb_vm_ci_proc_set(ci, m);
      if (MRB_PROC_ENV_P(m)) {
        ci->mid = MRB_PROC_ENV(m)->mid;
      }

      /* prepare stack */
      if (MRB_PROC_CFUNC_P(m)) {
        recv = MRB_PROC_CFUNC(m)(mrb, recv);
        mrb_gc_arena_shrink(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        /* pop stackpos */
        ci = cipop(mrb);
        pc = ci->pc;
        ci[1].stack[0] = recv;
        irep = mrb->c->ci->proc->body.irep;
      }
      else {
        /* setup environment for calling method */
        proc = m;
        irep = m->body.irep;
        if (!irep) {
          mrb->c->ci->stack[0] = mrb_nil_value();
          a = 0;
          c = OP_R_NORMAL;
          goto L_OP_RETURN_BODY;
        }
        mrb_int nargs = mrb_ci_bidx(ci)+1;
        if (nargs < irep->nregs) {
          mrb_stack_extend(mrb, irep->nregs);
          stack_clear(regs+nargs, irep->nregs-nargs);
        }
        if (MRB_PROC_ENV_P(m)) {
          regs[0] = MRB_PROC_ENV(m)->stack[0];
        }
        pc = irep->iseq;
      }
      pool = irep->pool;
      syms = irep->syms;
      JUMP;
    }

    CASE(OP_SUPER, BB) {
      mrb_method_t m;
      struct RClass *cls;
      mrb_callinfo *ci = mrb->c->ci;
      mrb_value recv, blk;
      const struct RProc *p = ci->proc;
      mrb_sym mid = ci->mid;
      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);

      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */
        mid = p->e.env->mid;    /* restore old mid */
      }

      if (mid == 0 || !target_class) {
        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }
      if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {
        target_class = mrb_vm_ci_target_class(ci);
      }
      else if (target_class->tt == MRB_TT_MODULE) {
        target_class = mrb_vm_ci_target_class(ci);
        if (target_class->tt != MRB_TT_ICLASS) {
          goto super_typeerror;
        }
      }
      recv = regs[0];
      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {
      super_typeerror: ;
        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,
                                            ""self has wrong type to call super in this context"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }

      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);

      cls = target_class->super;
      m = mrb_method_search_vm(mrb, &cls, mid);
      if (MRB_METHOD_UNDEF_P(m)) {
        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);
        mid = MRB_SYM(method_missing);
      }

      /* push callinfo */
      ci = cipush(mrb, a, 0, cls, NULL, mid, b);

      /* prepare stack */
      ci->stack[0] = recv;

      if (MRB_METHOD_CFUNC_P(m)) {
        mrb_value v;

        if (MRB_METHOD_PROC_P(m)) {
          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));
        }
        v = MRB_METHOD_CFUNC(m)(mrb, recv);
        mrb_gc_arena_restore(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        ci = mrb->c->ci;
        mrb_assert(!mrb_break_p(v));
        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */
          if (ci->cci == CINFO_RESUMED) {
            mrb->jmp = prev_jmp;
            return v;
          }
          else {
            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
            proc = ci[-1].proc;
            irep = proc->body.irep;
            pool = irep->pool;
            syms = irep->syms;
          }
        }
        mrb->c->ci->stack[0] = v;
        ci = cipop(mrb);
        pc = ci->pc;
      }
      else {
        /* setup environment for calling method */
        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);
        pc = irep->iseq;
      }
      JUMP;
    }

    CASE(OP_ARGARY, BS) {
      mrb_int m1 = (b>>11)&0x3f;
      mrb_int r  = (b>>10)&0x1;
      mrb_int m2 = (b>>5)&0x1f;
      mrb_int kd = (b>>4)&0x1;
      mrb_int lv = (b>>0)&0xf;
      mrb_value *stack;

      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {
        mrb_value exc;

      L_NOSUPER:
        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }
      if (lv == 0) stack = regs + 1;
      else {
        struct REnv *e = uvenv(mrb, lv-1);
        if (!e) goto L_NOSUPER;
        if (MRB_ENV_LEN(e) <= m1+r+m2+1)
          goto L_NOSUPER;
        stack = e->stack + 1;
      }
      if (r == 0) {
        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);
      }
      else {
        mrb_value *pp = NULL;
        struct RArray *rest;
        mrb_int len = 0;

        if (mrb_array_p(stack[m1])) {
          struct RArray *ary = mrb_ary_ptr(stack[m1]);

          pp = ARY_PTR(ary);
          len = ARY_LEN(ary);
        }
        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);
        rest = mrb_ary_ptr(regs[a]);
        if (m1 > 0) {
          stack_copy(ARY_PTR(rest), stack, m1);
        }
        if (len > 0) {
          stack_copy(ARY_PTR(rest)+m1, pp, len);
        }
        if (m2 > 0) {
          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);
        }
        ARY_SET_LEN(rest, m1+len+m2);
      }
      if (kd) {
        regs[a+1] = stack[m1+r+m2];
        regs[a+2] = stack[m1+r+m2+1];
      }
      else {
        regs[a+1] = stack[m1+r+m2];
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ENTER, W) {
      mrb_int m1 = MRB_ASPEC_REQ(a);
      mrb_int o  = MRB_ASPEC_OPT(a);
      mrb_int r  = MRB_ASPEC_REST(a);
      mrb_int m2 = MRB_ASPEC_POST(a);
      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;
      /* unused
      int b  = MRB_ASPEC_BLOCK(a);
      */
      mrb_int const len = m1 + o + r + m2;

      mrb_callinfo *ci = mrb->c->ci;
      mrb_int argc = ci->n;
      mrb_value *argv = regs+1;
      mrb_value * const argv0 = argv;
      mrb_int const kw_pos = len + kd;    /* where kwhash should be */
      mrb_int const blk_pos = kw_pos + 1; /* where block should be */
      mrb_value blk = regs[mrb_ci_bidx(ci)];
      mrb_value kdict = mrb_nil_value();

      /* keyword arguments */
      if (ci->nk > 0) {
        mrb_int kidx = mrb_ci_kidx(ci);
        kdict = regs[kidx];
        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {
          kdict = mrb_nil_value();
          ci->nk = 0;
        }
      }
      if (!kd && !mrb_nil_p(kdict)) {
        if (argc < 14) {
          ci->n++;
          argc++;    /* include kdict in normal arguments */
        }
        else if (argc == 14) {
          /* pack arguments and kdict */
          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);
          argc = ci->n = 15;
        }
        else {/* argc == 15 */
          /* push kdict to packed arguments */
          mrb_ary_push(mrb, regs[1], regs[2]);
        }
        ci->nk = 0;
      }
      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {
        kdict = mrb_hash_dup(mrb, kdict);
      }

      /* arguments is passed with Array */
      if (argc == 15) {
        struct RArray *ary = mrb_ary_ptr(regs[1]);
        argv = ARY_PTR(ary);
        argc = (int)ARY_LEN(ary);
        mrb_gc_protect(mrb, regs[1]);
      }

      /* strict argument check */
      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {
        if (argc < m1 + m2 || (r == 0 && argc > len)) {
          argnum_error(mrb, m1+m2);
          goto L_RAISE;
        }
      }
      /* extract first argument array to arguments */
      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {
        mrb_gc_protect(mrb, argv[0]);
        argc = (int)RARRAY_LEN(argv[0]);
        argv = RARRAY_PTR(argv[0]);
      }

      /* rest arguments */
      mrb_value rest = mrb_nil_value();
      if (argc < len) {
        mrb_int mlen = m2;
        if (argc < m1+m2) {
          mlen = m1 < argc ? argc - m1 : 0;
        }

        /* copy mandatory and optional arguments */
        if (argv0 != argv && argv) {
          value_move(®s[1], argv, argc-mlen); /* m1 + o */
        }
        if (argc < m1) {
          stack_clear(®s[argc+1], m1-argc);
        }
        /* copy post mandatory arguments */
        if (mlen) {
          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
        }
        if (mlen < m2) {
          stack_clear(®s[len-m2+mlen+1], m2-mlen);
        }
        /* initialize rest arguments with empty Array */
        if (r) {
          rest = mrb_ary_new_capa(mrb, 0);
          regs[m1+o+1] = rest;
        }
        /* skip initializer of passed arguments */
        if (o > 0 && argc > m1+m2)
          pc += (argc - m1 - m2)*3;
      }
      else {
        mrb_int rnum = 0;
        if (argv0 != argv) {
          value_move(®s[1], argv, m1+o);
        }
        if (r) {
          rnum = argc-m1-o-m2;
          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);
          regs[m1+o+1] = rest;
        }
        if (m2 > 0 && argc-m2 > m1) {
          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);
        }
        pc += o*3;
      }

      /* need to be update blk first to protect blk from GC */
      regs[blk_pos] = blk;              /* move block */
      if (kd) {
        if (mrb_nil_p(kdict))
          kdict = mrb_hash_new_capa(mrb, 0);
        regs[kw_pos] = kdict;           /* set kwhash */
      }

      /* format arguments for generated code */
      mrb->c->ci->n = len;

      /* clear local (but non-argument) variables */
      if (irep->nlocals-blk_pos-1 > 0) {
        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);
      }
      JUMP;
    }

    CASE(OP_KARG, BB) {
      mrb_value k = mrb_symbol_value(syms[b]);
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;

      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {
        mrb_value str = mrb_format(mrb, ""missing keyword: %v"", k);
        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));
        goto L_RAISE;
      }
      regs[a] = mrb_hash_get(mrb, kdict, k);
      mrb_hash_delete_key(mrb, kdict, k);
      NEXT;
    }

    CASE(OP_KEY_P, BB) {
      mrb_value k = mrb_symbol_value(syms[b]);
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;
      mrb_bool key_p = FALSE;

      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {
        key_p = mrb_hash_key_p(mrb, kdict, k);
      }
      regs[a] = mrb_bool_value(key_p);
      NEXT;
    }

    CASE(OP_KEYEND, Z) {
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;

      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {
        mrb_value keys = mrb_hash_keys(mrb, kdict);
        mrb_value key1 = RARRAY_PTR(keys)[0];
        mrb_value str = mrb_format(mrb, ""unknown keyword: %v"", key1);
        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));
        goto L_RAISE;
      }
      NEXT;
    }

    CASE(OP_BREAK, B) {
      c = OP_R_BREAK;
      goto L_RETURN;
    }
    CASE(OP_RETURN_BLK, B) {
      c = OP_R_RETURN;
      goto L_RETURN;
    }
    CASE(OP_RETURN, B)
    c = OP_R_NORMAL;
    L_RETURN:
    {
      mrb_callinfo *ci;

      ci = mrb->c->ci;
      if (ci->mid) {
        mrb_value blk = regs[mrb_ci_bidx(ci)];

        if (mrb_proc_p(blk)) {
          struct RProc *p = mrb_proc_ptr(blk);

          if (!MRB_PROC_STRICT_P(p) &&
              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {
            p->flags |= MRB_PROC_ORPHAN;
          }
        }
      }

      if (mrb->exc) {
      L_RAISE:
        ci = mrb->c->ci;
        if (ci == mrb->c->cibase) {
          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);
          if (ch == NULL) goto L_FTOP;
          goto L_CATCH;
        }
        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {
          ci = cipop(mrb);
          if (ci[1].cci == CINFO_SKIP && prev_jmp) {
            mrb->jmp = prev_jmp;
            MRB_THROW(prev_jmp);
          }
          pc = ci[0].pc;
          if (ci == mrb->c->cibase) {
            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);
            if (ch == NULL) {
            L_FTOP:             /* fiber top */
              if (mrb->c == mrb->root_c) {
                mrb->c->ci->stack = mrb->c->stbase;
                goto L_STOP;
              }
              else {
                struct mrb_context *c = mrb->c;

                c->status = MRB_FIBER_TERMINATED;
                mrb->c = c->prev;
                c->prev = NULL;
                goto L_RAISE;
              }
            }
            break;
          }
        }
      L_CATCH:
        if (ch == NULL) goto L_STOP;
        if (FALSE) {
        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */
          ci = mrb->c->ci;
        }
        proc = ci->proc;
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, irep->nregs);
        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);
      }
      else {
        mrb_int acc;
        mrb_value v;

        ci = mrb->c->ci;
        v = regs[a];
        mrb_gc_protect(mrb, v);
        switch (c) {
        case OP_R_RETURN:
          /* Fall through to OP_R_NORMAL otherwise */
          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {
            const struct RProc *dst;
            mrb_callinfo *cibase;
            cibase = mrb->c->cibase;
            dst = top_proc(mrb, proc);

            if (MRB_PROC_ENV_P(dst)) {
              struct REnv *e = MRB_PROC_ENV(dst);

              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {
                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
                goto L_RAISE;
              }
            }
            /* check jump destination */
            while (cibase <= ci && ci->proc != dst) {
              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */
                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
                goto L_RAISE;
              }
              ci--;
            }
            if (ci <= cibase) { /* no jump destination */
              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
              goto L_RAISE;
            }
            ci = mrb->c->ci;
            while (cibase <= ci && ci->proc != dst) {
              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {
                cibase = mrb->c->cibase;
                dst = top_proc(mrb, proc);
              }
              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {
                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);
              }
              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);
              ci = cipop(mrb);
              pc = ci->pc;
            }
            proc = ci->proc;
            mrb->exc = NULL; /* clear break object */
            break;
          }
          /* fallthrough */
        case OP_R_NORMAL:
        NORMAL_RETURN:
          if (ci == mrb->c->cibase) {
            struct mrb_context *c;
            c = mrb->c;

            if (!c->prev) { /* toplevel return */
              regs[irep->nlocals] = v;
              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);
            }
            if (!c->vmexec && c->prev->ci == c->prev->cibase) {
              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, ""double resume"");
              mrb_exc_set(mrb, exc);
              goto L_RAISE;
            }
            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {
              c = mrb->c;
            }
            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {
              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);
            }
            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);
            /* automatic yield at the end */
            c->status = MRB_FIBER_TERMINATED;
            mrb->c = c->prev;
            mrb->c->status = MRB_FIBER_RUNNING;
            c->prev = NULL;
            if (c->vmexec) {
              mrb_gc_arena_restore(mrb, ai);
              c->vmexec = FALSE;
              mrb->jmp = prev_jmp;
              return v;
            }
            ci = mrb->c->ci;
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_RETURN);
          mrb->exc = NULL; /* clear break object */
          break;
        case OP_R_BREAK:
          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;
          if (MRB_PROC_ORPHAN_P(proc)) {
            mrb_value exc;

          L_BREAK_ERROR:
            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,
                                      ""break from proc-closure"");
            mrb_exc_set(mrb, exc);
            goto L_RAISE;
          }
          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {
            goto L_BREAK_ERROR;
          }
          else {
            struct REnv *e = MRB_PROC_ENV(proc);

            if (e->cxt != mrb->c) {
              goto L_BREAK_ERROR;
            }
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_BREAK);
          /* break from fiber block */
          if (ci == mrb->c->cibase && ci->pc) {
            struct mrb_context *c = mrb->c;

            mrb->c = c->prev;
            c->prev = NULL;
            ci = mrb->c->ci;
          }
          if (ci->cci > CINFO_NONE) {
            ci = cipop(mrb);
            mrb_gc_arena_restore(mrb, ai);
            mrb->c->vmexec = FALSE;
            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);
            mrb->jmp = prev_jmp;
            MRB_THROW(prev_jmp);
          }
          if (FALSE) {
            struct RBreak *brk;

          L_BREAK:
            brk = (struct RBreak*)mrb->exc;
            proc = mrb_break_proc_get(brk);
            v = mrb_break_value_get(brk);
            ci = mrb->c->ci;

            switch (mrb_break_tag_get(brk)) {
#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);
              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)
#undef DISPATCH_CHECKPOINTS
              default:
                mrb_assert(!""wrong break tag"");
            }
          }
          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {
            if (ci[-1].cci == CINFO_SKIP) {
              goto L_BREAK_ERROR;
            }
            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {
              /* do nothing */
            }
            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {
              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);
            }
            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);
            ci = cipop(mrb);
            pc = ci->pc;
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);
          if (ci == mrb->c->cibase) {
            goto L_BREAK_ERROR;
          }
          mrb->exc = NULL; /* clear break object */
          break;
        default:
          /* cannot happen */
          break;
        }
        mrb_assert(ci == mrb->c->ci);
        mrb_assert(mrb->exc == NULL);

        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {
          mrb_gc_arena_restore(mrb, ai);
          mrb->c->vmexec = FALSE;
          mrb->jmp = prev_jmp;
          return v;
        }
        acc = ci->cci;
        ci = cipop(mrb);
        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {
          mrb_gc_arena_restore(mrb, ai);
          mrb->jmp = prev_jmp;
          return v;
        }
        pc = ci->pc;
        DEBUG(fprintf(stderr, ""from :%s\n"", mrb_sym_name(mrb, ci->mid)));
        proc = ci->proc;
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;

        ci[1].stack[0] = v;
        mrb_gc_arena_restore(mrb, ai);
      }
      JUMP;
    }

    CASE(OP_BLKPUSH, BS) {
      int m1 = (b>>11)&0x3f;
      int r  = (b>>10)&0x1;
      int m2 = (b>>5)&0x1f;
      int kd = (b>>4)&0x1;
      int lv = (b>>0)&0xf;
      mrb_value *stack;

      if (lv == 0) stack = regs + 1;
      else {
        struct REnv *e = uvenv(mrb, lv-1);
        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||
            MRB_ENV_LEN(e) <= m1+r+m2+1) {
          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
          goto L_RAISE;
        }
        stack = e->stack + 1;
      }
      if (mrb_nil_p(stack[m1+r+m2+kd])) {
        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
        goto L_RAISE;
      }
      regs[a] = stack[m1+r+m2+kd];
      NEXT;
    }

  L_INT_OVERFLOW:
    {
      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, ""integer overflow"");
      mrb_exc_set(mrb, exc);
    }
    goto L_RAISE;

#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))
#define OP_MATH(op_name)                                                    \
  /* need to check if op is overridden */                                   \
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \
    OP_MATH_CASE_INTEGER(op_name);                                          \
    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \
    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \
    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \
    OP_MATH_CASE_STRING_##op_name();                                        \
    default:                                                                \
      mid = MRB_OPSYM(op_name);                                             \
      goto L_SEND_SYM;                                                      \
  }                                                                         \
  NEXT;
#define OP_MATH_CASE_INTEGER(op_name)                                       \
  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \
    {                                                                       \
      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \
      if (mrb_int_##op_name##_overflow(x, y, &z))                           \
        OP_MATH_OVERFLOW_INT();                                             \
      else                                                                  \
        SET_INT_VALUE(mrb,regs[a], z);                                      \
    }                                                                       \
    break
#ifdef MRB_NO_FLOAT
#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0
#else
#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \
  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \
    {                                                                           \
      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \
      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \
    }                                                                           \
    break
#endif
#define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW
#define OP_MATH_CASE_STRING_add()                                           \
  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \
    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \
    mrb_gc_arena_restore(mrb, ai);                                          \
    break
#define OP_MATH_CASE_STRING_sub() (void)0
#define OP_MATH_CASE_STRING_mul() (void)0
#define OP_MATH_OP_add +
#define OP_MATH_OP_sub -
#define OP_MATH_OP_mul *
#define OP_MATH_TT_integer MRB_TT_INTEGER
#define OP_MATH_TT_float   MRB_TT_FLOAT

    CASE(OP_ADD, B) {
      OP_MATH(add);
    }

    CASE(OP_SUB, B) {
      OP_MATH(sub);
    }

    CASE(OP_MUL, B) {
      OP_MATH(mul);
    }

    CASE(OP_DIV, B) {
#ifndef MRB_NO_FLOAT
      mrb_float x, y, f;
#endif

      /* need to check if op is overridden */
      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):
        {
          mrb_int x = mrb_integer(regs[a]);
          mrb_int y = mrb_integer(regs[a+1]);
          mrb_int div = mrb_div_int(mrb, x, y);
          SET_INT_VALUE(mrb, regs[a], div);
        }
        NEXT;
#ifndef MRB_NO_FLOAT
      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):
        x = (mrb_float)mrb_integer(regs[a]);
        y = mrb_float(regs[a+1]);
        break;
      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):
        x = mrb_float(regs[a]);
        y = (mrb_float)mrb_integer(regs[a+1]);
        break;
      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
        x = mrb_float(regs[a]);
        y = mrb_float(regs[a+1]);
        break;
#endif
      default:
        mid = MRB_OPSYM(div);
        goto L_SEND_SYM;
      }

#ifndef MRB_NO_FLOAT
      f = mrb_div_float(x, y);
      SET_FLOAT_VALUE(mrb, regs[a], f);
#endif
      NEXT;
    }

#define OP_MATHI(op_name)                                                   \
  /* need to check if op is overridden */                                   \
  switch (mrb_type(regs[a])) {                                              \
    OP_MATHI_CASE_INTEGER(op_name);                                         \
    OP_MATHI_CASE_FLOAT(op_name);                                           \
    default:                                                                \
      SET_INT_VALUE(mrb,regs[a+1], b);                                      \
      mid = MRB_OPSYM(op_name);                                             \
      goto L_SEND_SYM;                                                      \
  }                                                                         \
  NEXT;
#define OP_MATHI_CASE_INTEGER(op_name)                                      \
  case MRB_TT_INTEGER:                                                      \
    {                                                                       \
      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \
      if (mrb_int_##op_name##_overflow(x, y, &z))                           \
        OP_MATH_OVERFLOW_INT();                                             \
      else                                                                  \
        SET_INT_VALUE(mrb,regs[a], z);                                      \
    }                                                                       \
    break
#ifdef MRB_NO_FLOAT
#define OP_MATHI_CASE_FLOAT(op_name) (void)0
#else
#define OP_MATHI_CASE_FLOAT(op_name)                                        \
  case MRB_TT_FLOAT:                                                        \
    {                                                                       \
      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \
      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \
    }                                                                       \
    break
#endif

    CASE(OP_ADDI, BB) {
      OP_MATHI(add);
    }

    CASE(OP_SUBI, BB) {
      OP_MATHI(sub);
    }

#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))

#ifdef MRB_NO_FLOAT
#define OP_CMP(op,sym) do {\
  int result;\
  /* need to check if - is overridden */\
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
    break;\
  default:\
    mid = MRB_OPSYM(sym);\
    goto L_SEND_SYM;\
  }\
  if (result) {\
    SET_TRUE_VALUE(regs[a]);\
  }\
  else {\
    SET_FALSE_VALUE(regs[a]);\
  }\
} while(0)
#else
#define OP_CMP(op, sym) do {\
  int result;\
  /* need to check if - is overridden */\
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
    break;\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\
    break;\
  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\
    break;\
  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\
    result = OP_CMP_BODY(op,mrb_float,mrb_float);\
    break;\
  default:\
    mid = MRB_OPSYM(sym);\
    goto L_SEND_SYM;\
  }\
  if (result) {\
    SET_TRUE_VALUE(regs[a]);\
  }\
  else {\
    SET_FALSE_VALUE(regs[a]);\
  }\
} while(0)
#endif

    CASE(OP_EQ, B) {
      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {
        SET_TRUE_VALUE(regs[a]);
      }
      else {
        OP_CMP(==,eq);
      }
      NEXT;
    }

    CASE(OP_LT, B) {
      OP_CMP(<,lt);
      NEXT;
    }

    CASE(OP_LE, B) {
      OP_CMP(<=,le);
      NEXT;
    }

    CASE(OP_GT, B) {
      OP_CMP(>,gt);
      NEXT;
    }

    CASE(OP_GE, B) {
      OP_CMP(>=,ge);
      NEXT;
    }

    CASE(OP_ARRAY, BB) {
      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }
    CASE(OP_ARRAY2, BBB) {
      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ARYCAT, B) {
      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);
      if (mrb_nil_p(regs[a])) {
        regs[a] = splat;
      }
      else {
        mrb_assert(mrb_array_p(regs[a]));
        mrb_ary_concat(mrb, regs[a], splat);
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ARYPUSH, BB) {
      mrb_assert(mrb_array_p(regs[a]));
      for (mrb_int i=0; i pre + post) {
        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);
        regs[a++] = v;
        while (post--) {
          regs[a++] = ARY_PTR(ary)[len-post-1];
        }
      }
      else {
        v = mrb_ary_new_capa(mrb, 0);
        regs[a++] = v;
        for (idx=0; idx+pre> 2;
      if (pool[b].tt & IREP_TT_SFLAG) {
        sym = mrb_intern_static(mrb, pool[b].u.str, len);
      }
      else {
        sym  = mrb_intern(mrb, pool[b].u.str, len);
      }
      regs[a] = mrb_symbol_value(sym);
      NEXT;
    }

    CASE(OP_STRING, BB) {
      mrb_int len;

      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);
      len = pool[b].tt >> 2;
      if (pool[b].tt & IREP_TT_SFLAG) {
        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);
      }
      else {
        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_STRCAT, B) {
      mrb_assert(mrb_string_p(regs[a]));
      mrb_str_concat(mrb, regs[a], regs[a+1]);
      NEXT;
    }

    CASE(OP_HASH, BB) {
      mrb_value hash = mrb_hash_new_capa(mrb, b);
      int i;
      int lim = a+b*2;

      for (i=a; ireps[b];

      if (c & OP_L_CAPTURE) {
        p = mrb_closure_new(mrb, nirep);
      }
      else {
        p = mrb_proc_new(mrb, nirep);
        p->flags |= MRB_PROC_SCOPE;
      }
      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;
      regs[a] = mrb_obj_value(p);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }
    CASE(OP_BLOCK, BB) {
      c = OP_L_BLOCK;
      goto L_MAKE_LAMBDA;
    }
    CASE(OP_METHOD, BB) {
      c = OP_L_METHOD;
      goto L_MAKE_LAMBDA;
    }

    CASE(OP_RANGE_INC, B) {
      regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_RANGE_EXC, B) {
      regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_OCLASS, B) {
      regs[a] = mrb_obj_value(mrb->object_class);
      NEXT;
    }

    CASE(OP_CLASS, BB) {
      struct RClass *c = 0, *baseclass;
      mrb_value base, super;
      mrb_sym id = syms[b];

      base = regs[a];
      super = regs[a+1];
      if (mrb_nil_p(base)) {
        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
        if (!baseclass) baseclass = mrb->object_class;
        base = mrb_obj_value(baseclass);
      }
      c = mrb_vm_define_class(mrb, base, super, id);
      regs[a] = mrb_obj_value(c);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_MODULE, BB) {
      struct RClass *cls = 0, *baseclass;
      mrb_value base;
      mrb_sym id = syms[b];

      base = regs[a];
      if (mrb_nil_p(base)) {
        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
        if (!baseclass) baseclass = mrb->object_class;
        base = mrb_obj_value(baseclass);
      }
      cls = mrb_vm_define_module(mrb, base, id);
      regs[a] = mrb_obj_value(cls);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_EXEC, BB)
    {
      mrb_value recv = regs[a];
      struct RProc *p;
      const mrb_irep *nirep = irep->reps[b];

      /* prepare closure */
      p = mrb_proc_new(mrb, nirep);
      p->c = NULL;
      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);
      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));
      p->flags |= MRB_PROC_SCOPE;

      /* prepare call stack */
      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);

      irep = p->body.irep;
      pool = irep->pool;
      syms = irep->syms;
      mrb_stack_extend(mrb, irep->nregs);
      stack_clear(regs+1, irep->nregs-1);
      pc = irep->iseq;
      JUMP;
    }

    CASE(OP_DEF, BB) {
      struct RClass *target = mrb_class_ptr(regs[a]);
      struct RProc *p = mrb_proc_ptr(regs[a+1]);
      mrb_method_t m;
      mrb_sym mid = syms[b];

      MRB_METHOD_FROM_PROC(m, p);
      mrb_define_method_raw(mrb, target, mid, m);
      mrb_method_added(mrb, target, mid);
      mrb_gc_arena_restore(mrb, ai);
      regs[a] = mrb_symbol_value(mid);
      NEXT;
    }

    CASE(OP_SCLASS, B) {
      regs[a] = mrb_singleton_class(mrb, regs[a]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_TCLASS, B) {
      struct RClass *target = check_target_class(mrb);
      if (!target) goto L_RAISE;
      regs[a] = mrb_obj_value(target);
      NEXT;
    }

    CASE(OP_ALIAS, BB) {
      struct RClass *target = check_target_class(mrb);

      if (!target) goto L_RAISE;
      mrb_alias_method(mrb, target, syms[a], syms[b]);
      mrb_method_added(mrb, target, syms[a]);
      NEXT;
    }
    CASE(OP_UNDEF, B) {
      struct RClass *target = check_target_class(mrb);

      if (!target) goto L_RAISE;
      mrb_undef_method_id(mrb, target, syms[a]);
      NEXT;
    }

    CASE(OP_DEBUG, Z) {
      FETCH_BBB();
#ifdef MRB_USE_DEBUG_HOOK
      mrb->debug_op_hook(mrb, irep, pc, regs);
#else
#ifndef MRB_NO_STDIO
      printf(""OP_DEBUG %d %d %d\n"", a, b, c);
#else
      abort();
#endif
#endif
      NEXT;
    }

    CASE(OP_ERR, B) {
      size_t len = pool[a].tt >> 2;
      mrb_value exc;

      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);
      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);
      mrb_exc_set(mrb, exc);
      goto L_RAISE;
    }

    CASE(OP_EXT1, Z) {
      insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }
    CASE(OP_EXT2, Z) {
      insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }
    CASE(OP_EXT3, Z) {
      uint8_t insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }

    CASE(OP_STOP, Z) {
      /*        stop VM */
      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {
        /* do nothing */
      }
      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {
        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());
      }
      CHECKPOINT_END(RBREAK_TAG_STOP);
    L_STOP:
      mrb->jmp = prev_jmp;
      if (mrb->exc) {
        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);
        return mrb_obj_value(mrb->exc);
      }
      return regs[irep->nlocals];
    }
  }
  END_DISPATCH;
#undef regs
  }
  MRB_CATCH(&c_jmp) {
    mrb_callinfo *ci = mrb->c->ci;
    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {
      ci = cipop(mrb);
    }
    exc_catched = TRUE;
    pc = ci->pc;
    goto RETRY_TRY_BLOCK;
  }
  MRB_END_EXC(&c_jmp);
}",1
"njs_array_convert_to_slow_array(njs_vm_t *vm, njs_array_t *array)
{
    uint32_t           i, length;
    njs_value_t        index, value;
    njs_object_prop_t  *prop;

    njs_set_array(&value, array);
    array->object.fast_array = 0;

    length = array->length;

    for (i = 0; i < length; i++) {
        if (njs_is_valid(&array->start[i])) {
            njs_uint32_to_string(&index, i);
            prop = njs_object_property_add(vm, &value, &index, 0);
            if (njs_slow_path(prop == NULL)) {
                return NJS_ERROR;
            }

            prop->value = array->start[i];
        }
    }

    /* GC: release value. */

    njs_mp_free(vm->mem_pool, array->start);
    array->start = NULL;

    return NJS_OK;
}",1
"static struct request_s *process_request (struct conn_s *connptr,
                                          orderedmap hashofheaders)
{
        char *url;
        struct request_s *request;
        int ret, skip_trans;
        size_t request_len;

        skip_trans = 0;

        /* NULL out all the fields so frees don't cause segfaults. */
        request =
            (struct request_s *) safecalloc (1, sizeof (struct request_s));
        if (!request)
                return NULL;

        request_len = strlen (connptr->request_line) + 1;

        request->method = (char *) safemalloc (request_len);
        url = (char *) safemalloc (request_len);
        request->protocol = (char *) safemalloc (request_len);

        if (!request->method || !url || !request->protocol) {
                goto fail;
        }

        ret = sscanf (connptr->request_line, ""%[^ ] %[^ ] %[^ ]"",
                      request->method, url, request->protocol);
        if (ret == 2 && !strcasecmp (request->method, ""GET"")) {
                request->protocol[0] = 0;

                /* Indicate that this is a HTTP/0.9 GET request */
                connptr->protocol.major = 0;
                connptr->protocol.minor = 9;
        } else if (ret == 3 && !strncasecmp (request->protocol, ""HTTP/"", 5)) {
                /*
                 * Break apart the protocol and update the connection
                 * structure.
                 */
                ret = sscanf (request->protocol + 5, ""%u.%u"",
                              &connptr->protocol.major,
                              &connptr->protocol.minor);

                /*
                 * If the conversion doesn't succeed, drop down below and
                 * send the error to the user.
                 */
                if (ret != 2)
                        goto BAD_REQUEST_ERROR;
        } else {
BAD_REQUEST_ERROR:
                log_message (LOG_ERR,
                             ""process_request: Bad Request on file descriptor %d"",
                             connptr->client_fd);
                indicate_http_error (connptr, 400, ""Bad Request"",
                                     ""detail"", ""Request has an invalid format"",
                                     ""url"", url, NULL);
                goto fail;
        }

#ifdef REVERSE_SUPPORT
        if (config->reversepath_list != NULL) {
                /*
                 * Rewrite the URL based on the reverse path.  After calling
                 * reverse_rewrite_url ""url"" can be freed since we either
                 * have the newly rewritten URL, or something failed and
                 * we'll be closing anyway.
                 */
                char *reverse_url;
                int reverse_status;

                reverse_url = reverse_rewrite_url (connptr, hashofheaders, url, &reverse_status);

                if (reverse_url != NULL) {
                        if (reverse_status == 301) {
                                char buf[PATH_MAX];
                                snprintf (buf, sizeof buf, ""Location: %s\r\n"", reverse_url);
                                send_http_headers (connptr, 301, ""Moved Permanently"", buf);
                                goto fail;
                        }
                        safefree (url);
                        url = reverse_url;
                        skip_trans = 1;
                } else if (config->reverseonly) {
                        log_message (LOG_ERR,
                                     ""Bad request, no mapping for '%s' found"",
                                     url);
                        indicate_http_error (connptr, 400, ""Bad Request"",
                                             ""detail"", ""No mapping found for ""
                                             ""requested url"", ""url"", url, NULL);
                        goto fail;
                }
        }
#endif

        if (strncasecmp (url, ""http://"", 7) == 0
            || (UPSTREAM_CONFIGURED () && strncasecmp (url, ""ftp://"", 6) == 0))
        {
                char *skipped_type = strstr (url, ""//"") + 2;

                if (extract_url (skipped_type, HTTP_PORT, request) < 0) {
                        indicate_http_error (connptr, 400, ""Bad Request"",
                                             ""detail"", ""Could not parse URL"",
                                             ""url"", url, NULL);
                        goto fail;
                }
        } else if (strcmp (request->method, ""CONNECT"") == 0) {
                if (extract_url (url, HTTP_PORT_SSL, request) < 0) {
                        indicate_http_error (connptr, 400, ""Bad Request"",
                                             ""detail"", ""Could not parse URL"",
                                             ""url"", url, NULL);
                        goto fail;
                }

                /* Verify that the port in the CONNECT method is allowed */
                if (!check_allowed_connect_ports (request->port,
                                                  config->connect_ports))
                {
                        indicate_http_error (connptr, 403, ""Access violation"",
                                             ""detail"",
                                             ""The CONNECT method not allowed ""
                                             ""with the port you tried to use."",
                                             ""url"", url, NULL);
                        log_message (LOG_INFO,
                                     ""Refused CONNECT method on port %d"",
                                     request->port);
                        goto fail;
                }

                connptr->connect_method = TRUE;
        } else {
#ifdef TRANSPARENT_PROXY
                if (!skip_trans) {
                        if (!do_transparent_proxy
                            (connptr, hashofheaders, request, config, &url))
                                goto fail;
                } else
#endif
                {
                indicate_http_error (connptr, 501, ""Not Implemented"",
                                     ""detail"",
                                     ""Unknown method or unsupported protocol."",
                                     ""url"", url, NULL);
                log_message (LOG_INFO, ""Unknown method (%s) or protocol (%s)"",
                             request->method, url);
                goto fail;
                }
        }

#ifdef FILTER_ENABLE
        /*
         * Filter restricted domains/urls
         */
        if (config->filter) {
                int fu = config->filter_opts & FILTER_OPT_URL;
                ret = filter_run (fu ? url : request->host);

                if (ret) {
                        update_stats (STAT_DENIED);

                        log_message (LOG_NOTICE,
                                     ""Proxying refused on filtered %s \""%s\"""",
                                     fu ? ""url"" : ""domain"",
                                     fu ? url : request->host);

                        indicate_http_error (connptr, 403, ""Filtered"",
                                             ""detail"",
                                             ""The request you made has been filtered"",
                                             ""url"", url, NULL);
                        goto fail;
                }
        }
#endif


        /*
         * Check to see if they're requesting the stat host
         */
        if (config->stathost && strcmp (config->stathost, request->host) == 0) {
                log_message (LOG_NOTICE, ""Request for the stathost."");
                connptr->show_stats = TRUE;
                goto fail;
        }

        safefree (url);

        return request;

fail:
        safefree (url);
        free_request_struct (request);
        return NULL;
}",1
"  void Compute(OpKernelContext* ctx) override {
    const Tensor& val = ctx->input(0);
    int64 id = ctx->session_state()->GetNewId();
    TensorStore::TensorAndKey tk{val, id, requested_device()};
    OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));

    Tensor* handle = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));
    if (ctx->expected_output_dtype(0) == DT_RESOURCE) {
      ResourceHandle resource_handle = MakeResourceHandle(
          ctx, SessionState::kTensorHandleResourceTypeName,
          tk.GetHandle(name()));
      resource_handle.set_maybe_type_name(
          SessionState::kTensorHandleResourceTypeName);
      handle->scalar()() = resource_handle;
    } else {
      // Legacy behavior in V1.
      handle->flat().setConstant(tk.GetHandle(name()));
    }
  }",1
"Status SparseCountSparseOutputShapeFn(InferenceContext *c) {
  auto rank = c->Dim(c->input(0), 1);
  auto nvals = c->UnknownDim();
  c->set_output(0, c->Matrix(nvals, rank));  // out.indices
  c->set_output(1, c->Vector(nvals));        // out.values
  c->set_output(2, c->Vector(rank));         // out.dense_shape
  return Status::OK();
}",1
"inline void FurnaceGUI::patternRow(int i, bool isPlaying, float lineHeight, int chans, int ord, const DivPattern** patCache) {
  static char id[32];
  bool selectedRow=(i>=sel1.y && i<=sel2.y);
  ImGui::TableNextRow(0,lineHeight);
  ImGui::TableNextColumn();
  float cursorPosY=ImGui::GetCursorPos().y-ImGui::GetScrollY();
  // check if the row is visible
  if (cursorPosY<-lineHeight || cursorPosY>ImGui::GetWindowSize().y) {
    return;
  }
  // check if we are in range
  if (ord<0 || ord>=e->song.ordersLen) {
    return;
  }
  if (i<0 || i>=e->song.patLen) {
    return;
  }
  bool isPushing=false;
  ImVec4 activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE];
  ImVec4 inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE];
  ImVec4 rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX];
  if (e->song.hilightB>0 && !(i%e->song.hilightB)) {
    activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI2];
    inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI2];
    rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI2];
  } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {
    activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI1];
    inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI1];
    rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI1];
  }
  // check overflow highlight
  if (settings.overflowHighlight) {
    if (edit && cursor.y==i) {
      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING]));
    } else if (isPlaying && oldRow==i) {
      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD]));
    } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) {
      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2]));
    } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {
      ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1]));
    }
  } else {
    isPushing=true;
    if (edit && cursor.y==i) {
      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING]));
    } else if (isPlaying && oldRow==i) {
      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD]));
    } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) {
      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2]));
    } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) {
      ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1]));
    } else {
      isPushing=false;
    }
  }
  // row number
  if (settings.patRowsBase==1) {
    ImGui::TextColored(rowIndexColor,"" %.2X "",i);
  } else {
    ImGui::TextColored(rowIndexColor,""%3d "",i);
  }
  // for each column
  for (int j=0; j