code
stringlengths
4
1.01M
/*************************************************************************** * Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk> * * Copyright (c) 2014 WandererFan <wandererfan@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWSYMBOL_H #define DRAWINGGUI_QGRAPHICSITEMVIEWSYMBOL_H #include <QObject> #include <QPainter> #include <QString> #include <QByteArray> #include <QSvgRenderer> #include <QGraphicsSvgItem> #include "QGIView.h" namespace TechDraw { class DrawViewSymbol; } namespace TechDrawGui { class QGCustomSvg; class QGDisplayArea; class TechDrawGuiExport QGIViewSymbol : public QGIView { public: QGIViewSymbol(); ~QGIViewSymbol(); enum {Type = QGraphicsItem::UserType + 121}; int type() const override { return Type;} virtual void updateView(bool update = false) override; void setViewSymbolFeature(TechDraw::DrawViewSymbol *obj); virtual void draw() override; virtual void rotateView(void) override; protected: virtual void drawSvg(); void symbolToSvg(QByteArray qba); QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; QGDisplayArea* m_displayArea; QGCustomSvg *m_svgItem; }; } // namespace #endif // DRAWINGGUI_QGRAPHICSITEMVIEWSYMBOL_H
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Backup * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Backup by cron backend model * * @category Mage * @package Mage_Backup * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Backup_Model_Config_Backend_Cron extends Mage_Core_Model_Config_Data { const CRON_STRING_PATH = 'crontab/jobs/system_backup/schedule/cron_expr'; const CRON_MODEL_PATH = 'crontab/jobs/system_backup/run/model'; const XML_PATH_BACKUP_ENABLED = 'groups/backup/fields/enabled/value'; const XML_PATH_BACKUP_TIME = 'groups/backup/fields/time/value'; const XML_PATH_BACKUP_FREQUENCY = 'groups/backup/fields/frequency/value'; /** * Cron settings after save * * @return Mage_Adminhtml_Model_System_Config_Backend_Log_Cron */ protected function _afterSave() { $enabled = $this->getData(self::XML_PATH_BACKUP_ENABLED); $time = $this->getData(self::XML_PATH_BACKUP_TIME); $frequency = $this->getData(self::XML_PATH_BACKUP_FREQUENCY); $frequencyWeekly = Mage_Adminhtml_Model_System_Config_Source_Cron_Frequency::CRON_WEEKLY; $frequencyMonthly = Mage_Adminhtml_Model_System_Config_Source_Cron_Frequency::CRON_MONTHLY; if ($enabled) { $cronExprArray = array( intval($time[1]), # Minute intval($time[0]), # Hour ($frequency == $frequencyMonthly) ? '1' : '*', # Day of the Month '*', # Month of the Year ($frequency == $frequencyWeekly) ? '1' : '*', # Day of the Week ); $cronExprString = join(' ', $cronExprArray); } else { $cronExprString = ''; } try { Mage::getModel('core/config_data') ->load(self::CRON_STRING_PATH, 'path') ->setValue($cronExprString) ->setPath(self::CRON_STRING_PATH) ->save(); Mage::getModel('core/config_data') ->load(self::CRON_MODEL_PATH, 'path') ->setValue((string) Mage::getConfig()->getNode(self::CRON_MODEL_PATH)) ->setPath(self::CRON_MODEL_PATH) ->save(); } catch (Exception $e) { Mage::throwException(Mage::helper('backup')->__('Unable to save the cron expression.')); } } }
// Copyright 2011 Software Freedom Conservancy // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "command.h" #include "command_types.h" #include "logging.h" namespace webdriver { Command::Command() : command_type_(webdriver::CommandType::NoCommand) { } Command::~Command() { } void Command::Populate(const std::string& json_command) { LOG(TRACE) << "Entering Command::Populate"; // Clear the existing maps. this->command_parameters_.clear(); this->locator_parameters_.clear(); LOG(DEBUG) << "Raw JSON command: " << json_command; Json::Value root; Json::Reader reader; bool successful_parse = reader.parse(json_command, root); if (!successful_parse) { // report to the user the failure and their locations in the document. LOG(WARN) << "Failed to parse configuration due " << reader.getFormatedErrorMessages() << std::endl << "JSON command: '" << json_command << "'"; } this->command_type_ = root.get("command", webdriver::CommandType::NoCommand).asString(); if (this->command_type_ != webdriver::CommandType::NoCommand) { Json::Value locator_parameter_object = root["locator"]; Json::Value::iterator it = locator_parameter_object.begin(); Json::Value::iterator end = locator_parameter_object.end(); for (; it != end; ++it) { std::string key = it.key().asString(); std::string value = locator_parameter_object[key].asString(); this->locator_parameters_[key] = value; } Json::Value command_parameter_object = root["parameters"]; it = command_parameter_object.begin(); end = command_parameter_object.end(); for (; it != end; ++it) { std::string key = it.key().asString(); Json::Value value = command_parameter_object[key]; this->command_parameters_[key] = value; } } else { LOG(DEBUG) << "Command type is zero, no 'command' attribute in JSON object"; } } } // namespace webdriver
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package e2e import ( "fmt" "strings" "time" "k8s.io/kubernetes/pkg/api" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( // Interval to framework.Poll /runningpods on a node pollInterval = 1 * time.Second // Interval to framework.Poll /stats/container on a node containerStatsPollingInterval = 5 * time.Second // Maximum number of nodes that we constraint to maxNodesToCheck = 10 ) // getPodMatches returns a set of pod names on the given node that matches the // podNamePrefix and namespace. func getPodMatches(c *client.Client, nodeName string, podNamePrefix string, namespace string) sets.String { matches := sets.NewString() framework.Logf("Checking pods on node %v via /runningpods endpoint", nodeName) runningPods, err := framework.GetKubeletPods(c, nodeName) if err != nil { framework.Logf("Error checking running pods on %v: %v", nodeName, err) return matches } for _, pod := range runningPods.Items { if pod.Namespace == namespace && strings.HasPrefix(pod.Name, podNamePrefix) { matches.Insert(pod.Name) } } return matches } // waitTillNPodsRunningOnNodes polls the /runningpods endpoint on kubelet until // it finds targetNumPods pods that match the given criteria (namespace and // podNamePrefix). Note that we usually use label selector to filter pods that // belong to the same RC. However, we use podNamePrefix with namespace here // because pods returned from /runningpods do not contain the original label // information; they are reconstructed by examining the container runtime. In // the scope of this test, we do not expect pod naming conflicts so // podNamePrefix should be sufficient to identify the pods. func waitTillNPodsRunningOnNodes(c *client.Client, nodeNames sets.String, podNamePrefix string, namespace string, targetNumPods int, timeout time.Duration) error { return wait.Poll(pollInterval, timeout, func() (bool, error) { matchCh := make(chan sets.String, len(nodeNames)) for _, item := range nodeNames.List() { // Launch a goroutine per node to check the pods running on the nodes. nodeName := item go func() { matchCh <- getPodMatches(c, nodeName, podNamePrefix, namespace) }() } seen := sets.NewString() for i := 0; i < len(nodeNames.List()); i++ { seen = seen.Union(<-matchCh) } if seen.Len() == targetNumPods { return true, nil } framework.Logf("Waiting for %d pods to be running on the node; %d are currently running;", targetNumPods, seen.Len()) return false, nil }) } // updates labels of nodes given by nodeNames. // In case a given label already exists, it overwrites it. If label to remove doesn't exist // it silently ignores it. func updateNodeLabels(c *client.Client, nodeNames sets.String, toAdd, toRemove map[string]string) { const maxRetries = 5 for nodeName := range nodeNames { var node *api.Node var err error for i := 0; i < maxRetries; i++ { node, err = c.Nodes().Get(nodeName) if err != nil { framework.Logf("Error getting node %s: %v", nodeName, err) continue } if toAdd != nil { for k, v := range toAdd { node.ObjectMeta.Labels[k] = v } } if toRemove != nil { for k := range toRemove { delete(node.ObjectMeta.Labels, k) } } _, err = c.Nodes().Update(node) if err != nil { framework.Logf("Error updating node %s: %v", nodeName, err) } else { break } } Expect(err).NotTo(HaveOccurred()) } } var _ = framework.KubeDescribe("kubelet", func() { var c *client.Client var numNodes int var nodeNames sets.String var nodeLabels map[string]string f := framework.NewDefaultFramework("kubelet") var resourceMonitor *framework.ResourceMonitor BeforeEach(func() { c = f.Client nodes := framework.GetReadySchedulableNodesOrDie(f.Client) numNodes = len(nodes.Items) nodeNames = sets.NewString() // If there are a lot of nodes, we don't want to use all of them // (if there are 1000 nodes in the cluster, starting 10 pods/node // will take ~10 minutes today). And there is also deletion phase. // // Instead, we choose at most 10 nodes and will constraint pods // that we are creating to be scheduled only on that nodes. if numNodes > maxNodesToCheck { numNodes = maxNodesToCheck nodeLabels = make(map[string]string) nodeLabels["kubelet_cleanup"] = "true" } for i := 0; i < numNodes; i++ { nodeNames.Insert(nodes.Items[i].Name) } updateNodeLabels(c, nodeNames, nodeLabels, nil) // Start resourceMonitor only in small clusters. if len(nodes.Items) <= maxNodesToCheck { resourceMonitor = framework.NewResourceMonitor(f.Client, framework.TargetContainers(), containerStatsPollingInterval) resourceMonitor.Start() } }) AfterEach(func() { if resourceMonitor != nil { resourceMonitor.Stop() } // If we added labels to nodes in this test, remove them now. updateNodeLabels(c, nodeNames, nil, nodeLabels) }) framework.KubeDescribe("Clean up pods on node", func() { type DeleteTest struct { podsPerNode int timeout time.Duration } deleteTests := []DeleteTest{ {podsPerNode: 10, timeout: 1 * time.Minute}, } for _, itArg := range deleteTests { name := fmt.Sprintf( "kubelet should be able to delete %d pods per node in %v.", itArg.podsPerNode, itArg.timeout) It(name, func() { totalPods := itArg.podsPerNode * numNodes By(fmt.Sprintf("Creating a RC of %d pods and wait until all pods of this RC are running", totalPods)) rcName := fmt.Sprintf("cleanup%d-%s", totalPods, string(util.NewUUID())) Expect(framework.RunRC(framework.RCConfig{ Client: f.Client, Name: rcName, Namespace: f.Namespace.Name, Image: framework.GetPauseImageName(f.Client), Replicas: totalPods, NodeSelector: nodeLabels, })).NotTo(HaveOccurred()) // Perform a sanity check so that we know all desired pods are // running on the nodes according to kubelet. The timeout is set to // only 30 seconds here because framework.RunRC already waited for all pods to // transition to the running status. Expect(waitTillNPodsRunningOnNodes(f.Client, nodeNames, rcName, f.Namespace.Name, totalPods, time.Second*30)).NotTo(HaveOccurred()) if resourceMonitor != nil { resourceMonitor.LogLatest() } By("Deleting the RC") framework.DeleteRC(f.Client, f.Namespace.Name, rcName) // Check that the pods really are gone by querying /runningpods on the // node. The /runningpods handler checks the container runtime (or its // cache) and returns a list of running pods. Some possible causes of // failures are: // - kubelet deadlock // - a bug in graceful termination (if it is enabled) // - docker slow to delete pods (or resource problems causing slowness) start := time.Now() Expect(waitTillNPodsRunningOnNodes(f.Client, nodeNames, rcName, f.Namespace.Name, 0, itArg.timeout)).NotTo(HaveOccurred()) framework.Logf("Deleting %d pods on %d nodes completed in %v after the RC was deleted", totalPods, len(nodeNames), time.Since(start)) if resourceMonitor != nil { resourceMonitor.LogCPUSummary() } }) } }) })
package org.apereo.cas.audit; import org.apereo.inspektr.audit.AuditActionContext; import org.apereo.inspektr.audit.AuditTrailManager; import java.time.LocalDate; import java.util.List; import java.util.Set; /** * This is {@link AuditTrailExecutionPlan}. * * @author Misagh Moayyed * @since 5.3.0 */ public interface AuditTrailExecutionPlan { /** * Register audit trail manager. * * @param manager the manager */ void registerAuditTrailManager(AuditTrailManager manager); /** * Gets audit trail managers. * * @return the audit trail managers */ List<AuditTrailManager> getAuditTrailManagers(); /** * Record. * * @param audit the audit */ void record(AuditActionContext audit); /** * Gets audit records since the specified date. * * @param sinceDate the since date * @return the audit records since */ Set<AuditActionContext> getAuditRecordsSince(LocalDate sinceDate); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.extendedset.intset; import java.util.NoSuchElementException; public final class EmptyIntIterator implements IntSet.IntIterator { private static final EmptyIntIterator INSTANCE = new EmptyIntIterator(); public static EmptyIntIterator instance() { return INSTANCE; } private EmptyIntIterator() { } @Override public boolean hasNext() { return false; } @Override public int next() { throw new NoSuchElementException(); } @Override public void skipAllBefore(int element) { // nothing to skip } @Override public IntSet.IntIterator clone() { return new EmptyIntIterator(); } }
using Provisioning.Common.Authentication; using Provisioning.Common.Configuration; using Provisioning.Common.Configuration.Application; using Provisioning.Common.Utilities; using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.Online.SharePoint.TenantManagement; using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Provisioning.Common.Data.Templates; namespace Provisioning.Common { /// <summary> /// Implementation class for Provisioning an Office 365 Site. /// </summary> public class Office365SiteProvisioningService : AbstractSiteProvisioningService { #region Constructor /// <summary> /// Constructor /// </summary> public Office365SiteProvisioningService() : base() { } #endregion public override void CreateSiteCollection(SiteRequestInformation siteRequest, Template template) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); UsingContext(ctx => { try { Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; SpoOperation op = _tenant.CreateSite(_newsite); ctx.Load(_tenant); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); ctx.ExecuteQuery(); } var _site = _tenant.GetSiteByUrl(siteRequest.Url); var _web = _site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); ctx.Load(_web); ctx.ExecuteQuery(); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successfull, siteRequest.Url); }); } /// <summary> /// /// </summary> /// <param name="siteInfo"></param> public override void SetExternalSharing(SiteRequestInformation siteInfo) { UsingContext(ctx => { try { Tenant _tenant = new Tenant(ctx); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteInfo.Url, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; if(siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) { _targetSharingCapability = SharingCapabilities.ExternalUserSharingOnly; _shouldBeUpdated = true; } if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { _siteProps.SharingCapability = _targetSharingCapability; _siteProps.Update(); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Successfull, siteInfo.Url); } } catch(Exception _ex) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Exception, siteInfo.Url, _ex); } }); } } }
require 'spec_helper' describe 'docker::exec', :type => :define do let(:title) { 'sample' } context 'when running detached' do let(:params) { {'command' => 'command', 'container' => 'container', 'detach' => true} } it { should contain_exec('docker exec --detach=true container command') } end context 'when running with tty' do let(:params) { {'command' => 'command', 'container' => 'container', 'tty' => true} } it { should contain_exec('docker exec --tty=true container command') } end context 'when running with interactive' do let(:params) { {'command' => 'command', 'container' => 'container', 'interactive' => true} } it { should contain_exec('docker exec --interactive=true container command') } end context 'when running with unless' do let(:params) { {'command' => 'command', 'container' => 'container', 'interactive' => true, 'unless' => 'some_command arg1'} } it { should contain_exec('docker exec --interactive=true container command').with_unless ('docker exec --interactive=true container some_command arg1') } end context 'when running without unless' do let(:params) { {'command' => 'command', 'container' => 'container', 'interactive' => true,} } it { should contain_exec('docker exec --interactive=true container command').with_unless (nil) } end end
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.pgevent.springboot; import org.apache.camel.CamelContext; import org.apache.camel.component.pgevent.PgEventComponent; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionMessage; import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.core.type.AnnotatedTypeMetadata; /** * Generated by camel-package-maven-plugin - do not edit this file! */ @Configuration @ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration") @Conditional(PgEventComponentAutoConfiguration.Condition.class) @AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration") public class PgEventComponentAutoConfiguration { @Lazy @Bean(name = "pgevent-component") @ConditionalOnClass(CamelContext.class) @ConditionalOnMissingBean(PgEventComponent.class) public PgEventComponent configurePgEventComponent(CamelContext camelContext) throws Exception { PgEventComponent component = new PgEventComponent(); component.setCamelContext(camelContext); return component; } public static class Condition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome( ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { boolean groupEnabled = isEnabled(conditionContext, "camel.component.", true); ConditionMessage.Builder message = ConditionMessage .forCondition("camel.component.pgevent"); if (isEnabled(conditionContext, "camel.component.pgevent.", groupEnabled)) { return ConditionOutcome.match(message.because("enabled")); } return ConditionOutcome.noMatch(message.because("not enabled")); } private boolean isEnabled( org.springframework.context.annotation.ConditionContext context, java.lang.String prefix, boolean defaultValue) { RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( context.getEnvironment(), prefix); return resolver.getProperty("enabled", Boolean.class, defaultValue); } } }
package etcd import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/registry/generic/registry" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/apiserver/pkg/storage" "k8s.io/kubernetes/pkg/printers" printerstorage "k8s.io/kubernetes/pkg/printers/storage" "github.com/openshift/api/oauth" oauthapi "github.com/openshift/origin/pkg/oauth/apis/oauth" "github.com/openshift/origin/pkg/oauth/apiserver/registry/oauthauthorizetoken" "github.com/openshift/origin/pkg/oauth/apiserver/registry/oauthclient" printersinternal "github.com/openshift/origin/pkg/printers/internalversion" ) // rest implements a RESTStorage for authorize tokens against etcd type REST struct { *registry.Store } var _ rest.StandardStorage = &REST{} // NewREST returns a RESTStorage object that will work against authorize tokens func NewREST(optsGetter generic.RESTOptionsGetter, clientGetter oauthclient.Getter) (*REST, error) { strategy := oauthauthorizetoken.NewStrategy(clientGetter) store := &registry.Store{ NewFunc: func() runtime.Object { return &oauthapi.OAuthAuthorizeToken{} }, NewListFunc: func() runtime.Object { return &oauthapi.OAuthAuthorizeTokenList{} }, DefaultQualifiedResource: oauth.Resource("oauthauthorizetokens"), TableConvertor: printerstorage.TableConvertor{TablePrinter: printers.NewTablePrinter().With(printersinternal.AddHandlers)}, TTLFunc: func(obj runtime.Object, existing uint64, update bool) (uint64, error) { token := obj.(*oauthapi.OAuthAuthorizeToken) expires := uint64(token.ExpiresIn) return expires, nil }, CreateStrategy: strategy, UpdateStrategy: strategy, DeleteStrategy: strategy, } options := &generic.StoreOptions{ RESTOptions: optsGetter, AttrFunc: storage.AttrFunc(storage.DefaultNamespaceScopedAttr).WithFieldMutation(oauthapi.OAuthAuthorizeTokenFieldSelector), } if err := store.CompleteWithOptions(options); err != nil { return nil, err } return &REST{store}, nil }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.dataflow.worker; import com.google.api.services.dataflow.model.CounterUpdate; import org.apache.beam.runners.dataflow.worker.util.common.worker.WorkExecutor; /** An general executor for work in the Dataflow legacy and Beam harness. */ public interface DataflowWorkExecutor extends WorkExecutor { /** * Extract metric updates that are still pending to be reported to the Dataflow service, removing * them from this {@link DataflowWorkExecutor}. */ Iterable<CounterUpdate> extractMetricUpdates(); }
package org.gwtbootstrap3.client.ui.base.button; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 - 2014 GwtBootstrap3 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.tree; import java.util.Objects; import java.util.Optional; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; public class Prepare extends Statement { private final String name; private final Statement statement; public Prepare(NodeLocation location, String name, Statement statement) { this(Optional.of(location), name, statement); } public Prepare(String name, Statement statement) { this(Optional.empty(), name, statement); } private Prepare(Optional<NodeLocation> location, String name, Statement statement) { super(location); this.name = requireNonNull(name, "name is null"); this.statement = requireNonNull(statement, "statement is null"); } public String getName() { return name; } public Statement getStatement() { return statement; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitPrepare(this, context); } @Override public int hashCode() { return Objects.hash(name, statement); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } Prepare o = (Prepare) obj; return Objects.equals(name, o.name) && Objects.equals(statement, o.statement); } @Override public String toString() { return toStringHelper(this) .add("name", name) .add("statement", statement) .toString(); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> <title>LoggerPatternConverter xref</title> <link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../../apidocs/org/apache/log4j/pattern/LoggerPatternConverter.html">View Javadoc</a></div><pre> <a name="1" href="#1">1</a> <em class="jxr_comment">/*</em> <a name="2" href="#2">2</a> <em class="jxr_comment"> * Licensed to the Apache Software Foundation (ASF) under one or more</em> <a name="3" href="#3">3</a> <em class="jxr_comment"> * contributor license agreements. See the NOTICE file distributed with</em> <a name="4" href="#4">4</a> <em class="jxr_comment"> * this work for additional information regarding copyright ownership.</em> <a name="5" href="#5">5</a> <em class="jxr_comment"> * The ASF licenses this file to You under the Apache License, Version 2.0</em> <a name="6" href="#6">6</a> <em class="jxr_comment"> * (the "License"); you may not use this file except in compliance with</em> <a name="7" href="#7">7</a> <em class="jxr_comment"> * the License. You may obtain a copy of the License at</em> <a name="8" href="#8">8</a> <em class="jxr_comment"> *</em> <a name="9" href="#9">9</a> <em class="jxr_comment"> * <a href="http://www.apache.org/licenses/LICENSE-2.0" target="alexandria_uri">http://www.apache.org/licenses/LICENSE-2.0</a></em> <a name="10" href="#10">10</a> <em class="jxr_comment"> *</em> <a name="11" href="#11">11</a> <em class="jxr_comment"> * Unless required by applicable law or agreed to in writing, software</em> <a name="12" href="#12">12</a> <em class="jxr_comment"> * distributed under the License is distributed on an "AS IS" BASIS,</em> <a name="13" href="#13">13</a> <em class="jxr_comment"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</em> <a name="14" href="#14">14</a> <em class="jxr_comment"> * See the License for the specific language governing permissions and</em> <a name="15" href="#15">15</a> <em class="jxr_comment"> * limitations under the License.</em> <a name="16" href="#16">16</a> <em class="jxr_comment"> */</em> <a name="17" href="#17">17</a> <a name="18" href="#18">18</a> <strong class="jxr_keyword">package</strong> org.apache.log4j.pattern; <a name="19" href="#19">19</a> <a name="20" href="#20">20</a> <strong class="jxr_keyword">import</strong> org.apache.log4j.spi.LoggingEvent; <a name="21" href="#21">21</a> <a name="22" href="#22">22</a> <a name="23" href="#23">23</a> <em class="jxr_javadoccomment">/**</em> <a name="24" href="#24">24</a> <em class="jxr_javadoccomment"> * Formats a logger name.</em> <a name="25" href="#25">25</a> <em class="jxr_javadoccomment"> *</em> <a name="26" href="#26">26</a> <em class="jxr_javadoccomment"> * @author Ceki G&amp;uuml;lc&amp;uuml;</em> <a name="27" href="#27">27</a> <em class="jxr_javadoccomment"> *</em> <a name="28" href="#28">28</a> <em class="jxr_javadoccomment"> */</em> <a name="29" href="#29">29</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../org/apache/log4j/pattern/LoggerPatternConverter.html">LoggerPatternConverter</a> <strong class="jxr_keyword">extends</strong> <a href="../../../../org/apache/log4j/pattern/NamePatternConverter.html">NamePatternConverter</a> { <a name="30" href="#30">30</a> <em class="jxr_javadoccomment">/**</em> <a name="31" href="#31">31</a> <em class="jxr_javadoccomment"> * Singleton.</em> <a name="32" href="#32">32</a> <em class="jxr_javadoccomment"> */</em> <a name="33" href="#33">33</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <a href="../../../../org/apache/log4j/pattern/LoggerPatternConverter.html">LoggerPatternConverter</a> INSTANCE = <a name="34" href="#34">34</a> <strong class="jxr_keyword">new</strong> <a href="../../../../org/apache/log4j/pattern/LoggerPatternConverter.html">LoggerPatternConverter</a>(<strong class="jxr_keyword">null</strong>); <a name="35" href="#35">35</a> <a name="36" href="#36">36</a> <em class="jxr_javadoccomment">/**</em> <a name="37" href="#37">37</a> <em class="jxr_javadoccomment"> * Private constructor.</em> <a name="38" href="#38">38</a> <em class="jxr_javadoccomment"> * @param options options, may be null.</em> <a name="39" href="#39">39</a> <em class="jxr_javadoccomment"> */</em> <a name="40" href="#40">40</a> <strong class="jxr_keyword">private</strong> <a href="../../../../org/apache/log4j/pattern/LoggerPatternConverter.html">LoggerPatternConverter</a>(<strong class="jxr_keyword">final</strong> String[] options) { <a name="41" href="#41">41</a> <strong class="jxr_keyword">super</strong>(<span class="jxr_string">"Logger"</span>, <span class="jxr_string">"logger"</span>, options); <a name="42" href="#42">42</a> } <a name="43" href="#43">43</a> <a name="44" href="#44">44</a> <em class="jxr_javadoccomment">/**</em> <a name="45" href="#45">45</a> <em class="jxr_javadoccomment"> * Obtains an instance of pattern converter.</em> <a name="46" href="#46">46</a> <em class="jxr_javadoccomment"> * @param options options, may be null.</em> <a name="47" href="#47">47</a> <em class="jxr_javadoccomment"> * @return instance of pattern converter.</em> <a name="48" href="#48">48</a> <em class="jxr_javadoccomment"> */</em> <a name="49" href="#49">49</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">static</strong> <a href="../../../../org/apache/log4j/pattern/LoggerPatternConverter.html">LoggerPatternConverter</a> newInstance( <a name="50" href="#50">50</a> <strong class="jxr_keyword">final</strong> String[] options) { <a name="51" href="#51">51</a> <strong class="jxr_keyword">if</strong> ((options == <strong class="jxr_keyword">null</strong>) || (options.length == 0)) { <a name="52" href="#52">52</a> <strong class="jxr_keyword">return</strong> INSTANCE; <a name="53" href="#53">53</a> } <a name="54" href="#54">54</a> <a name="55" href="#55">55</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">new</strong> <a href="../../../../org/apache/log4j/pattern/LoggerPatternConverter.html">LoggerPatternConverter</a>(options); <a name="56" href="#56">56</a> } <a name="57" href="#57">57</a> <a name="58" href="#58">58</a> <em class="jxr_javadoccomment">/**</em> <a name="59" href="#59">59</a> <em class="jxr_javadoccomment"> * {@inheritDoc}</em> <a name="60" href="#60">60</a> <em class="jxr_javadoccomment"> */</em> <a name="61" href="#61">61</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> format(<strong class="jxr_keyword">final</strong> <a href="../../../../org/apache/log4j/spi/LoggingEvent.html">LoggingEvent</a> event, <strong class="jxr_keyword">final</strong> StringBuffer toAppendTo) { <a name="62" href="#62">62</a> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">int</strong> initialLength = toAppendTo.length(); <a name="63" href="#63">63</a> toAppendTo.append(event.getLoggerName()); <a name="64" href="#64">64</a> abbreviate(initialLength, toAppendTo); <a name="65" href="#65">65</a> } <a name="66" href="#66">66</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.jdbc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.sql.Date; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.TimeZone; /** * A RowHolder implementation that is for cached results (a-la * mysql_store_result()). * * @version $Id: $ */ public class ByteArrayRow extends ResultSetRow { byte[][] internalRowData; public ByteArrayRow(byte[][] internalRowData, ExceptionInterceptor exceptionInterceptor) { super(exceptionInterceptor); this.internalRowData = internalRowData; } public byte[] getColumnValue(int index) throws SQLException { return this.internalRowData[index]; } public void setColumnValue(int index, byte[] value) throws SQLException { this.internalRowData[index] = value; } public String getString(int index, String encoding, MySQLConnection conn) throws SQLException { byte[] columnData = this.internalRowData[index]; if (columnData == null) { return null; } return getString(encoding, conn, columnData, 0, columnData.length); } public boolean isNull(int index) throws SQLException { return this.internalRowData[index] == null; } public boolean isFloatingPointNumber(int index) throws SQLException { byte[] numAsBytes = this.internalRowData[index]; if (this.internalRowData[index] == null || this.internalRowData[index].length == 0) { return false; } for (int i = 0; i < numAsBytes.length; i++) { if (((char) numAsBytes[i] == 'e') || ((char) numAsBytes[i] == 'E')) { return true; } } return false; } public long length(int index) throws SQLException { if (this.internalRowData[index] == null) { return 0; } return this.internalRowData[index].length; } public int getInt(int columnIndex) { if (this.internalRowData[columnIndex] == null) { return 0; } return StringUtils.getInt(this.internalRowData[columnIndex]); } public long getLong(int columnIndex) { if (this.internalRowData[columnIndex] == null) { return 0; } return StringUtils.getLong(this.internalRowData[columnIndex]); } public Timestamp getTimestampFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getTimestampFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs); } public double getNativeDouble(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeDouble(this.internalRowData[columnIndex], 0); } public float getNativeFloat(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeFloat(this.internalRowData[columnIndex], 0); } public int getNativeInt(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeInt(this.internalRowData[columnIndex], 0); } public long getNativeLong(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeLong(this.internalRowData[columnIndex], 0); } public short getNativeShort(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeShort(this.internalRowData[columnIndex], 0); } public Timestamp getNativeTimestamp(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] bits = this.internalRowData[columnIndex]; if (bits == null) { return null; } return getNativeTimestamp(bits, 0, bits.length, targetCalendar, tz, rollForward, conn, rs); } public void closeOpenStreams() { // no-op for this type } public InputStream getBinaryInputStream(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return null; } return new ByteArrayInputStream(this.internalRowData[columnIndex]); } public Reader getReader(int columnIndex) throws SQLException { InputStream stream = getBinaryInputStream(columnIndex); if (stream == null) { return null; } try { return new InputStreamReader(stream, this.metadata[columnIndex] .getCharacterSet()); } catch (UnsupportedEncodingException e) { SQLException sqlEx = SQLError.createSQLException("", this.exceptionInterceptor); sqlEx.initCause(e); throw sqlEx; } } public Time getTimeFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getTimeFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs); } public Date getDateFast(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getDateFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, conn, rs, targetCalendar); } public Object getNativeDateTimeValue(int columnIndex, Calendar targetCalendar, int jdbcType, int mysqlType, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getNativeDateTimeValue(columnIndex, columnValue, 0, columnValue.length, targetCalendar, jdbcType, mysqlType, tz, rollForward, conn, rs); } public Date getNativeDate(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar cal) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getNativeDate(columnIndex, columnValue, 0, columnValue.length, conn, rs, cal); } public Time getNativeTime(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getNativeTime(columnIndex, columnValue, 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs); } public int getBytesSize() { if (internalRowData == null) { return 0; } int bytesSize = 0; for (int i = 0; i < internalRowData.length; i++) { if (internalRowData[i] != null) { bytesSize += internalRowData[i].length; } } return bytesSize; } }
var names = Alloy.Collections.name; function green(str) { return '\x1B[32m' + str + '\x1B[39m'; } function red(str) { return '\x1B[31m' + str + '\x1B[39m'; } // show the info from the selected model function showInfo(e) { // get the model id from the list item var modelId = e.section.getItemAt(e.itemIndex).properties.modelId; // fetch a specific model based on the given id var model = Alloy.createModel('info'); model.fetch({ id: modelId }); // assert we got the right data back var pass = JSON.stringify(model.attributes) === JSON.stringify({ id: modelId, info: 'info ' + modelId }); Ti.API.info('Assert single info model returned with "{id:' + modelId + '}": ' + (pass ? green('OK') : red('FAIL'))); } // fetch the data to update the UI names.fetch(); // open the window $.index.open();
# Copyright 2014, Rackspace, US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This package holds the REST API that supports the Horizon dashboard Javascript code. It is not intended to be used outside of Horizon, and makes no promises of stability or fitness for purpose outside of that scope. It does not promise to adhere to the general OpenStack API Guidelines set out in https://wiki.openstack.org/wiki/APIChangeGuidelines. """ # import REST API modules here from . import cinder #flake8: noqa from . import config #flake8: noqa from . import glance #flake8: noqa from . import heat #flake8: noqa from . import keystone #flake8: noqa from . import network #flake8: noqa from . import neutron #flake8: noqa from . import nova #flake8: noqa from . import policy #flake8: noqa
package org.wso2.carbon.apimgt.webapp.publisher.config; public class APIResourceManagementException extends Exception { private static final long serialVersionUID = -3151279311929070297L; public APIResourceManagementException(String msg, Exception nestedEx) { super(msg, nestedEx); } }
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.cvsSupport2; import com.intellij.cvsSupport2.checkinProject.AdditionalOptionsPanel; import com.intellij.cvsSupport2.config.CvsConfiguration; import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.CheckinProjectPanel; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsRoot; import com.intellij.openapi.vcs.actions.VcsContextFactory; import com.intellij.openapi.vcs.checkin.CheckinHandler; import com.intellij.openapi.vcs.checkin.VcsCheckinHandlerFactory; import com.intellij.openapi.vcs.ui.RefreshableOnComponent; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; /** * @author yole */ class CvsCheckinHandlerFactory extends VcsCheckinHandlerFactory { CvsCheckinHandlerFactory() { super(CvsVcs2.getKey()); } @NotNull @Override protected CheckinHandler createVcsHandler(final CheckinProjectPanel panel) { return new CheckinHandler() { @Nullable public RefreshableOnComponent getAfterCheckinConfigurationPanel(Disposable parentDisposable) { final Project project = panel.getProject(); final CvsVcs2 cvs = CvsVcs2.getInstance(project); final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project); final Collection<VirtualFile> roots = panel.getRoots(); final Collection<FilePath> files = new HashSet<>(); for (VirtualFile root : roots) { final VcsRoot vcsRoot = vcsManager.getVcsRootObjectFor(root); if (vcsRoot == null || vcsRoot.getVcs() != cvs) { continue; } files.add(VcsContextFactory.SERVICE.getInstance().createFilePathOn(root)); } return new AdditionalOptionsPanel(CvsConfiguration.getInstance(project), files, project); } }; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.streaming import org.scalatest.BeforeAndAfterAll import org.apache.spark.sql.catalyst.streaming.InternalOutputModes._ import org.apache.spark.sql.execution.streaming.MemoryStream import org.apache.spark.sql.execution.streaming.state.StateStore import org.apache.spark.sql.functions._ class DeduplicateSuite extends StateStoreMetricsTest with BeforeAndAfterAll { import testImplicits._ override def afterAll(): Unit = { super.afterAll() StateStore.stop() } test("deduplicate with all columns") { val inputData = MemoryStream[String] val result = inputData.toDS().dropDuplicates() testStream(result, Append)( AddData(inputData, "a"), CheckLastBatch("a"), assertNumStateRows(total = 1, updated = 1), AddData(inputData, "a"), CheckLastBatch(), assertNumStateRows(total = 1, updated = 0), AddData(inputData, "b"), CheckLastBatch("b"), assertNumStateRows(total = 2, updated = 1) ) } test("deduplicate with some columns") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS().dropDuplicates("_1") testStream(result, Append)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1), assertNumStateRows(total = 1, updated = 1), AddData(inputData, "a" -> 2), // Dropped CheckLastBatch(), assertNumStateRows(total = 1, updated = 0), AddData(inputData, "b" -> 1), CheckLastBatch("b" -> 1), assertNumStateRows(total = 2, updated = 1) ) } test("multiple deduplicates") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS().dropDuplicates().dropDuplicates("_1") testStream(result, Append)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)), AddData(inputData, "a" -> 2), // Dropped from the second `dropDuplicates` CheckLastBatch(), assertNumStateRows(total = Seq(1L, 2L), updated = Seq(0L, 1L)), AddData(inputData, "b" -> 1), CheckLastBatch("b" -> 1), assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L)) ) } test("deduplicate with watermark") { val inputData = MemoryStream[Int] val result = inputData.toDS() .withColumn("eventTime", $"value".cast("timestamp")) .withWatermark("eventTime", "10 seconds") .dropDuplicates() .select($"eventTime".cast("long").as[Long]) testStream(result, Append)( AddData(inputData, (1 to 5).flatMap(_ => (10 to 15)): _*), CheckLastBatch(10 to 15: _*), assertNumStateRows(total = 6, updated = 6), AddData(inputData, 25), // Advance watermark to 15 seconds CheckLastBatch(25), assertNumStateRows(total = 7, updated = 1), AddData(inputData, 25), // Drop states less than watermark CheckLastBatch(), assertNumStateRows(total = 1, updated = 0), AddData(inputData, 10), // Should not emit anything as data less than watermark CheckLastBatch(), assertNumStateRows(total = 1, updated = 0), AddData(inputData, 45), // Advance watermark to 35 seconds CheckLastBatch(45), assertNumStateRows(total = 2, updated = 1), AddData(inputData, 45), // Drop states less than watermark CheckLastBatch(), assertNumStateRows(total = 1, updated = 0) ) } test("deduplicate with aggregate - append mode") { val inputData = MemoryStream[Int] val windowedaggregate = inputData.toDS() .withColumn("eventTime", $"value".cast("timestamp")) .withWatermark("eventTime", "10 seconds") .dropDuplicates() .withWatermark("eventTime", "10 seconds") .groupBy(window($"eventTime", "5 seconds") as 'window) .agg(count("*") as 'count) .select($"window".getField("start").cast("long").as[Long], $"count".as[Long]) testStream(windowedaggregate)( AddData(inputData, (1 to 5).flatMap(_ => (10 to 15)): _*), CheckLastBatch(), // states in aggregate in [10, 14), [15, 20) (2 windows) // states in deduplicate is 10 to 15 assertNumStateRows(total = Seq(2L, 6L), updated = Seq(2L, 6L)), AddData(inputData, 25), // Advance watermark to 15 seconds CheckLastBatch(), // states in aggregate in [10, 14), [15, 20) and [25, 30) (3 windows) // states in deduplicate is 10 to 15 and 25 assertNumStateRows(total = Seq(3L, 7L), updated = Seq(1L, 1L)), AddData(inputData, 25), // Emit items less than watermark and drop their state CheckLastBatch((10 -> 5)), // 5 items (10 to 14) after deduplicate // states in aggregate in [15, 20) and [25, 30) (2 windows, note aggregate uses the end of // window to evict items, so [15, 20) is still in the state store) // states in deduplicate is 25 assertNumStateRows(total = Seq(2L, 1L), updated = Seq(0L, 0L)), AddData(inputData, 10), // Should not emit anything as data less than watermark CheckLastBatch(), assertNumStateRows(total = Seq(2L, 1L), updated = Seq(0L, 0L)), AddData(inputData, 40), // Advance watermark to 30 seconds CheckLastBatch(), // states in aggregate in [15, 20), [25, 30) and [40, 45) // states in deduplicate is 25 and 40, assertNumStateRows(total = Seq(3L, 2L), updated = Seq(1L, 1L)), AddData(inputData, 40), // Emit items less than watermark and drop their state CheckLastBatch((15 -> 1), (25 -> 1)), // states in aggregate in [40, 45) // states in deduplicate is 40, assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)) ) } test("deduplicate with aggregate - update mode") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS() .select($"_1" as "str", $"_2" as "num") .dropDuplicates() .groupBy("str") .agg(sum("num")) .as[(String, Long)] testStream(result, Update)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1L), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)), AddData(inputData, "a" -> 1), // Dropped CheckLastBatch(), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)), AddData(inputData, "a" -> 2), CheckLastBatch("a" -> 3L), assertNumStateRows(total = Seq(1L, 2L), updated = Seq(1L, 1L)), AddData(inputData, "b" -> 1), CheckLastBatch("b" -> 1L), assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L)) ) } test("deduplicate with aggregate - complete mode") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS() .select($"_1" as "str", $"_2" as "num") .dropDuplicates() .groupBy("str") .agg(sum("num")) .as[(String, Long)] testStream(result, Complete)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1L), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)), AddData(inputData, "a" -> 1), // Dropped CheckLastBatch("a" -> 1L), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)), AddData(inputData, "a" -> 2), CheckLastBatch("a" -> 3L), assertNumStateRows(total = Seq(1L, 2L), updated = Seq(1L, 1L)), AddData(inputData, "b" -> 1), CheckLastBatch("a" -> 3L, "b" -> 1L), assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L)) ) } test("deduplicate with file sink") { withTempDir { output => withTempDir { checkpointDir => val outputPath = output.getAbsolutePath val inputData = MemoryStream[String] val result = inputData.toDS().dropDuplicates() val q = result.writeStream .format("parquet") .outputMode(Append) .option("checkpointLocation", checkpointDir.getPath) .start(outputPath) try { inputData.addData("a") q.processAllAvailable() checkDataset(spark.read.parquet(outputPath).as[String], "a") inputData.addData("a") // Dropped q.processAllAvailable() checkDataset(spark.read.parquet(outputPath).as[String], "a") inputData.addData("b") q.processAllAvailable() checkDataset(spark.read.parquet(outputPath).as[String], "a", "b") } finally { q.stop() } } } } test("SPARK-19841: watermarkPredicate should filter based on keys") { val input = MemoryStream[(Int, Int)] val df = input.toDS.toDF("time", "id") .withColumn("time", $"time".cast("timestamp")) .withWatermark("time", "1 second") .dropDuplicates("id", "time") // Change the column positions .select($"id") testStream(df)( AddData(input, 1 -> 1, 1 -> 1, 1 -> 2), CheckLastBatch(1, 2), AddData(input, 1 -> 1, 2 -> 3, 2 -> 4), CheckLastBatch(3, 4), AddData(input, 1 -> 0, 1 -> 1, 3 -> 5, 3 -> 6), // Drop (1 -> 0, 1 -> 1) due to watermark CheckLastBatch(5, 6), AddData(input, 1 -> 0, 4 -> 7), // Drop (1 -> 0) due to watermark CheckLastBatch(7) ) } test("SPARK-21546: dropDuplicates should ignore watermark when it's not a key") { val input = MemoryStream[(Int, Int)] val df = input.toDS.toDF("id", "time") .withColumn("time", $"time".cast("timestamp")) .withWatermark("time", "1 second") .dropDuplicates("id") .select($"id", $"time".cast("long")) testStream(df)( AddData(input, 1 -> 1, 1 -> 2, 2 -> 2), CheckLastBatch(1 -> 1, 2 -> 2) ) } }
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions to provide simpler and prettier logging.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import logging_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import tensor_array_ops __all__ = ["print_op"] def _get_tensor_repr(t, print_tensor_name=True, print_tensor_type=True, print_shape=True, summarize_indicator_vector=True): """Return a list of Tensors that summarize the given tensor t.""" tensor_list = [] if print_tensor_name and isinstance(t, ops.Tensor): tensor_list.append(constant_op.constant("Name: " + t.name)) if print_tensor_type: if isinstance(t, ops.Tensor): t_type_str = "Type: Tensor ({})".format(t.dtype.name) elif isinstance(t, ops.SparseTensor): t_type_str = "Type: SparseTensor ({})".format(t.dtype.name) elif isinstance(t, tensor_array_ops.TensorArray): t_type_str = "Type: TensorArray ({})".format(t.dtype.name) tensor_list.append(constant_op.constant(t_type_str)) if print_shape: if isinstance(t, ops.SparseTensor): tensor_list.append(constant_op.constant("Shape:")) tensor_list.append(t.shape) elif isinstance(t, ops.Tensor): tensor_list.append(constant_op.constant("Shape: " + str(t.get_shape( ).dims))) elif isinstance(t, tensor_array_ops.TensorArray): tensor_list.append(constant_op.constant("Size:")) tensor_list.append(t.size()) if summarize_indicator_vector and t.dtype == dtypes.bool: int_tensor = math_ops.cast(t, dtypes.uint8) tensor_list.append(constant_op.constant("First True in Boolean tensor at:")) tensor_list.append(math_ops.argmax(int_tensor, 0)) if isinstance(t, ops.SparseTensor): tensor_list.append(constant_op.constant("Sparse indices:")) tensor_list.append(t.indices) tensor_list.append(constant_op.constant("Sparse values:")) tensor_list.append(t.values) elif isinstance(t, ops.Tensor): tensor_list.append(constant_op.constant("Value:")) tensor_list.append(t) elif isinstance(t, tensor_array_ops.TensorArray): tensor_list.append(constant_op.constant("Value:")) tensor_list.append(t.pack()) return tensor_list def print_op(input_, data=None, message=None, first_n=None, summarize=20, print_tensor_name=True, print_tensor_type=True, print_shape=True, summarize_indicator_vector=True, name=None): """Creates a print op that will print when a tensor is accessed. Wraps the tensor passed in so that whenever that tensor is accessed, the message `message` is printed, along with the current value of the tensor `t` and an optional list of other tensors. Args: input_: A Tensor/SparseTensor/TensorArray to print when it is evaluated. data: A list of other tensors to print. message: A string message to print as a prefix. first_n: Only log `first_n` number of times. Negative numbers log always; this is the default. summarize: Print this number of elements in the tensor. print_tensor_name: Print the tensor name. print_tensor_type: Print the tensor type. print_shape: Print the tensor's shape. summarize_indicator_vector: Whether to print the index of the first true value in an indicator vector (a Boolean tensor). name: The name to give this op. Returns: A Print op. The Print op returns `input_`. Raises: ValueError: If the tensor `input_` is not a Tensor, SparseTensor or TensorArray. """ message = message or "" if input_ is None: raise ValueError("input_ must be of type " "Tensor, SparseTensor or TensorArray") tensor_list = _get_tensor_repr(input_, print_tensor_name, print_tensor_type, print_shape, summarize_indicator_vector) if data is not None: for t in data: tensor_list.extend(_get_tensor_repr(t, print_tensor_name, print_tensor_type, print_shape, summarize_indicator_vector)) if isinstance(input_, ops.Tensor): input_ = logging_ops.Print(input_, tensor_list, message, first_n, summarize, name) elif isinstance(input_, ops.SparseTensor): p = logging_ops.Print( constant_op.constant([]), tensor_list, message, first_n, summarize, name) with ops.control_dependencies([p]): input_ = ops.SparseTensor(array_ops.identity(input_.indices), array_ops.identity(input_.values), array_ops.identity(input_.shape)) elif isinstance(input_, tensor_array_ops.TensorArray): p = logging_ops.Print( constant_op.constant([]), tensor_list, message, first_n, summarize, name) with ops.control_dependencies([p]): input_ = tensor_array_ops.TensorArray(dtype=input_.dtype, handle=input_.handle) else: raise ValueError("input_ must be of type " "Tensor, SparseTensor or TensorArray") return input_
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openwhisk.core.entity.test import org.apache.openwhisk.core.database.DocumentFactory import spray.json._ import org.apache.openwhisk.core.entity._ /** * Contains types which represent former versions of database schemas * to be able to test migration path */ /** * Old schema of rules, containing the rules' status in the rule record * itself */ case class OldWhiskRule(namespace: EntityPath, override val name: EntityName, trigger: EntityName, action: EntityName, status: Status, version: SemVer = SemVer(), publish: Boolean = false, annotations: Parameters = Parameters()) extends WhiskEntity(name, "rule") { def toJson = OldWhiskRule.serdes.write(this).asJsObject def toWhiskRule = { WhiskRule( namespace, name, FullyQualifiedEntityName(namespace, trigger), FullyQualifiedEntityName(namespace, action), version, publish, annotations) } } object OldWhiskRule extends DocumentFactory[OldWhiskRule] with WhiskEntityQueries[OldWhiskRule] with DefaultJsonProtocol { override val collectionName = "rules" override implicit val serdes = jsonFormat8(OldWhiskRule.apply) } /** * Old schema of triggers, not containing a map of ReducedRules */ case class OldWhiskTrigger(namespace: EntityPath, override val name: EntityName, parameters: Parameters = Parameters(), limits: TriggerLimits = TriggerLimits(), version: SemVer = SemVer(), publish: Boolean = false, annotations: Parameters = Parameters()) extends WhiskEntity(name, "trigger") { def toJson = OldWhiskTrigger.serdes.write(this).asJsObject def toWhiskTrigger = WhiskTrigger(namespace, name, parameters, limits, version, publish, annotations) } object OldWhiskTrigger extends DocumentFactory[OldWhiskTrigger] with WhiskEntityQueries[OldWhiskTrigger] with DefaultJsonProtocol { override val collectionName = "triggers" override implicit val serdes = jsonFormat7(OldWhiskTrigger.apply) }
//// [tests/cases/compiler/extendingClassFromAliasAndUsageInIndexer.ts] //// //// [extendingClassFromAliasAndUsageInIndexer_backbone.ts] export class Model { public someData: string; } //// [extendingClassFromAliasAndUsageInIndexer_moduleA.ts] import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); export class VisualizationModel extends Backbone.Model { // interesting stuff here } //// [extendingClassFromAliasAndUsageInIndexer_moduleB.ts] import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); export class VisualizationModel extends Backbone.Model { // different interesting stuff here } //// [extendingClassFromAliasAndUsageInIndexer_main.ts] import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); import moduleA = require("./extendingClassFromAliasAndUsageInIndexer_moduleA"); import moduleB = require("./extendingClassFromAliasAndUsageInIndexer_moduleB"); interface IHasVisualizationModel { VisualizationModel: typeof Backbone.Model; } var moduleATyped: IHasVisualizationModel = moduleA; var moduleMap: { [key: string]: IHasVisualizationModel } = { "moduleA": moduleA, "moduleB": moduleB }; var moduleName: string; var visModel = new moduleMap[moduleName].VisualizationModel(); //// [extendingClassFromAliasAndUsageInIndexer_backbone.js] "use strict"; var Model = (function () { function Model() { } return Model; }()); exports.Model = Model; //// [extendingClassFromAliasAndUsageInIndexer_moduleA.js] "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); var VisualizationModel = (function (_super) { __extends(VisualizationModel, _super); function VisualizationModel() { _super.apply(this, arguments); } return VisualizationModel; }(Backbone.Model)); exports.VisualizationModel = VisualizationModel; //// [extendingClassFromAliasAndUsageInIndexer_moduleB.js] "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); var VisualizationModel = (function (_super) { __extends(VisualizationModel, _super); function VisualizationModel() { _super.apply(this, arguments); } return VisualizationModel; }(Backbone.Model)); exports.VisualizationModel = VisualizationModel; //// [extendingClassFromAliasAndUsageInIndexer_main.js] "use strict"; var moduleA = require("./extendingClassFromAliasAndUsageInIndexer_moduleA"); var moduleB = require("./extendingClassFromAliasAndUsageInIndexer_moduleB"); var moduleATyped = moduleA; var moduleMap = { "moduleA": moduleA, "moduleB": moduleB }; var moduleName; var visModel = new moduleMap[moduleName].VisualizationModel();
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.wm.impl.status; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.Gray; import com.intellij.util.ui.UIUtil; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ComponentUI; import java.awt.*; /** * User: spLeaner */ public class StatusBarUI extends ComponentUI { private static final Dimension MAX_SIZE = new Dimension(Integer.MAX_VALUE, 23); private static final Dimension MIN_SIZE = new Dimension(100, 23); private static final Border BACKGROUND_PAINTER = new BackgroundPainter(); @Override public void paint(final Graphics g, final JComponent c) { final Rectangle bounds = c.getBounds(); BACKGROUND_PAINTER.paintBorder(c, g, 0, 0, bounds.width, bounds.height); } @Override public Dimension getMinimumSize(JComponent c) { return MIN_SIZE; // TODO } @Override public Dimension getMaximumSize(JComponent c) { return MAX_SIZE; } private static final class BackgroundPainter implements Border { private static final Color BORDER_TOP_COLOR = Gray._145; private static final Color BORDER2_TOP_COLOR = Gray._255; private static final Color BORDER_BOTTOM_COLOR = Gray._255; private static final Insets INSETS = new Insets(0, 0, 0, 0); public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) { final Graphics2D g2d = (Graphics2D) g.create(); final Color background = UIUtil.getPanelBackground(); g2d.setColor(background); g2d.fillRect(0, 0, width, height); Color topColor = UIUtil.isUnderDarcula() ? BORDER_TOP_COLOR.darker().darker() : BORDER_TOP_COLOR; if (SystemInfo.isMac && UIUtil.isUnderIntelliJLaF()) { topColor = Gray.xC9; } g2d.setColor(topColor); g2d.drawLine(0, 0, width, 0); if (!UIUtil.isUnderDarcula()) { g2d.setColor(BORDER_BOTTOM_COLOR); g2d.drawLine(0, height, width, height); } g2d.dispose(); } public Insets getBorderInsets(Component c) { return (Insets)INSETS.clone(); } public boolean isBorderOpaque() { return true; } } }
# # Description: This method checks to see if the configured_system has been provisioned # # Get current provisioning status task = $evm.root['miq_provision_task'] task_status = task['status'] result = task.statemachine_task_status $evm.log('info', "ProvisionCheck returned <#{result}> for state <#{task.state}> and status <#{task_status}>") case result when 'error' $evm.root['ae_result'] = 'error' reason = $evm.root['miq_provision_task'].message reason = reason[7..-1] if reason[0..6] == 'Error: ' $evm.root['ae_reason'] = reason when 'retry' $evm.root['ae_result'] = 'retry' $evm.root['ae_retry_interval'] = '1.minute' when 'ok' # Bump State $evm.root['ae_result'] = 'ok' end
/* Processed by ecpg (regression mode) */ /* These include files are added by the preprocessor */ #include <ecpglib.h> #include <ecpgerrno.h> #include <sqlca.h> /* End of automatic include section */ #define ECPGdebug(X,Y) ECPGdebug((X)+100,(Y)) #line 1 "func.pgc" #include <stdio.h> #include <stdlib.h> #include <string.h> #line 1 "regression.h" #line 5 "func.pgc" int main() { #line 8 "func.pgc" char text [ 25 ] ; #line 8 "func.pgc" ECPGdebug(1, stderr); { ECPGconnect(__LINE__, 0, "ecpg1_regression" , NULL, NULL , NULL, 0); } #line 11 "func.pgc" { ECPGsetcommit(__LINE__, "on", NULL);} #line 13 "func.pgc" /* exec sql whenever sql_warning sqlprint ; */ #line 14 "func.pgc" /* exec sql whenever sqlerror sqlprint ; */ #line 15 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "create table My_Table ( Item1 int , Item2 text )", ECPGt_EOIT, ECPGt_EORT); #line 17 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 17 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 17 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "create table Log ( name text , w text )", ECPGt_EOIT, ECPGt_EORT); #line 18 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 18 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 18 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "create function My_Table_Check ( ) returns trigger as $test$\ BEGIN\ INSERT INTO Log VALUES(TG_NAME, TG_WHEN);\ RETURN NEW;\ END; $test$ language plpgsql", ECPGt_EOIT, ECPGt_EORT); #line 26 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 26 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 26 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "create trigger My_Table_Check_Trigger before insert on My_Table for each row execute procedure My_Table_Check ( )", ECPGt_EOIT, ECPGt_EORT); #line 32 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 32 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 32 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into My_Table values ( 1234 , 'Some random text' )", ECPGt_EOIT, ECPGt_EORT); #line 34 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 34 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 34 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into My_Table values ( 5678 , 'The Quick Brown' )", ECPGt_EOIT, ECPGt_EORT); #line 35 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 35 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 35 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select name from Log limit 1", ECPGt_EOIT, ECPGt_char,(text),(long)25,(long)1,(25)*sizeof(char), ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT); #line 36 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 36 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 36 "func.pgc" printf("Trigger %s fired.\n", text); { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "drop trigger My_Table_Check_Trigger on My_Table", ECPGt_EOIT, ECPGt_EORT); #line 39 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 39 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 39 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "drop function My_Table_Check ( )", ECPGt_EOIT, ECPGt_EORT); #line 40 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 40 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 40 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "drop table Log", ECPGt_EOIT, ECPGt_EORT); #line 41 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 41 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 41 "func.pgc" { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "drop table My_Table", ECPGt_EOIT, ECPGt_EORT); #line 42 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 42 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 42 "func.pgc" { ECPGdisconnect(__LINE__, "ALL"); #line 44 "func.pgc" if (sqlca.sqlwarn[0] == 'W') sqlprint(); #line 44 "func.pgc" if (sqlca.sqlcode < 0) sqlprint();} #line 44 "func.pgc" return 0; }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.structuralsearch.impl.matcher.predicates; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiType; import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.siyeh.ig.psiutils.ExpectedTypeUtils; public class FormalArgTypePredicate extends ExprTypePredicate { public FormalArgTypePredicate(String type, String baseName, boolean withinHierarchy, boolean caseSensitiveMatch, boolean target) { super(type, baseName, withinHierarchy, caseSensitiveMatch, target); } @Override protected PsiType evalType(PsiExpression match, MatchContext context) { return ExpectedTypeUtils.findExpectedType(match, true, true); } }
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Issue 4691: Ensure that functional-struct-updates operates // correctly and moves rather than copy when appropriate. #![allow(unknown_features)] #![feature(box_syntax)] use std::marker::NoCopy as NP; struct ncint { np: NP, v: int } fn ncint(v: int) -> ncint { ncint { np: NP, v: v } } struct NoFoo { copied: int, nocopy: ncint, } impl NoFoo { fn new(x:int,y:int) -> NoFoo { NoFoo { copied: x, nocopy: ncint(y) } } } struct MoveFoo { copied: int, moved: Box<int>, } impl MoveFoo { fn new(x:int,y:int) -> MoveFoo { MoveFoo { copied: x, moved: box y } } } struct DropNoFoo { inner: NoFoo } impl DropNoFoo { fn new(x:int,y:int) -> DropNoFoo { DropNoFoo { inner: NoFoo::new(x,y) } } } impl Drop for DropNoFoo { fn drop(&mut self) { } } struct DropMoveFoo { inner: MoveFoo } impl DropMoveFoo { fn new(x:int,y:int) -> DropMoveFoo { DropMoveFoo { inner: MoveFoo::new(x,y) } } } impl Drop for DropMoveFoo { fn drop(&mut self) { } } fn test0() { // just copy implicitly copyable fields from `f`, no moves // (and thus it is okay that these are Drop; compare against // compile-fail test: borrowck-struct-update-with-dtor.rs). // Case 1: Nocopyable let f = DropNoFoo::new(1, 2); let b = DropNoFoo { inner: NoFoo { nocopy: ncint(3), ..f.inner }}; let c = DropNoFoo { inner: NoFoo { nocopy: ncint(4), ..f.inner }}; assert_eq!(f.inner.copied, 1); assert_eq!(f.inner.nocopy.v, 2); assert_eq!(b.inner.copied, 1); assert_eq!(b.inner.nocopy.v, 3); assert_eq!(c.inner.copied, 1); assert_eq!(c.inner.nocopy.v, 4); // Case 2: Owned let f = DropMoveFoo::new(5, 6); let b = DropMoveFoo { inner: MoveFoo { moved: box 7, ..f.inner }}; let c = DropMoveFoo { inner: MoveFoo { moved: box 8, ..f.inner }}; assert_eq!(f.inner.copied, 5); assert_eq!(*f.inner.moved, 6); assert_eq!(b.inner.copied, 5); assert_eq!(*b.inner.moved, 7); assert_eq!(c.inner.copied, 5); assert_eq!(*c.inner.moved, 8); } fn test1() { // copying move-by-default fields from `f`, so it moves: let f = MoveFoo::new(11, 12); let b = MoveFoo {moved: box 13, ..f}; let c = MoveFoo {copied: 14, ..f}; assert_eq!(b.copied, 11); assert_eq!(*b.moved, 13); assert_eq!(c.copied, 14); assert_eq!(*c.moved, 12); } fn test2() { // move non-copyable field let f = NoFoo::new(21, 22); let b = NoFoo {nocopy: ncint(23), ..f}; let c = NoFoo {copied: 24, ..f}; assert_eq!(b.copied, 21); assert_eq!(b.nocopy.v, 23); assert_eq!(c.copied, 24); assert_eq!(c.nocopy.v, 22); } pub fn main() { test0(); test1(); test2(); }
<!DOCTYPE html> <!-- Distributed under both the W3C Test Suite License [1] and the W3C 3-clause BSD License [2]. To contribute to a W3C Test Suite, see the policies and contribution forms [3]. [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license [3] http://www.w3.org/2004/10/27-testcases --> <html> <head> <title>Shadow DOM Test: A_08_02_02</title> <link rel="author" title="Sergey G. Grekhov" href="mailto:sgrekhov@unipro.ru"> <link rel="help" href="http://www.w3.org/TR/2013/WD-shadow-dom-20130514/#html-forms"> <meta name="assert" content="HTML Elements in shadow trees: Form elements and form-associated elements in shadow tree must be accessible using shadow tree accessors"> <script src="../../../../../../resources/testharness.js"></script> <script src="../../../../../../resources/testharnessreport.js"></script> <script src="../../testcommon.js"></script> <link rel="stylesheet" href="../../../../../../resources/testharness.css"> </head> <body> <div id="log"></div> <script> //test form-associated elements test(function () { var d = newHTMLDocument(); var form = d.createElement('form'); form.setAttribute('id', 'form_id'); d.body.appendChild(form); var div = d.createElement('div'); d.body.appendChild(div); var s = div.createShadowRoot(); HTML5_FORM_ASSOCIATED_ELEMENTS.forEach(function (tagName) { var el = d.createElement(tagName); el.setAttribute('form', 'form_id'); el.setAttribute('id', tagName + '_id'); s.appendChild(el); assert_true(s.querySelector('#' + tagName + '_id') != null, 'Form-associated element ' + tagName + ' in shadow tree must be accessible shadow tree accessors'); assert_equals(s.querySelector('#' + tagName + '_id').getAttribute('id'), tagName + '_id', 'Form-associated element ' + tagName + ' in shadow tree must be accessible shadow tree accessors'); }); }, 'A_08_02_02_T01'); //test form elements test(function () { var d = newHTMLDocument(); var form = d.createElement('form'); d.body.appendChild(form); var div = d.createElement('div'); form.appendChild(div); var s = div.createShadowRoot(); HTML5_FORM_ASSOCIATED_ELEMENTS.forEach(function (tagName) { var el = d.createElement(tagName); el.setAttribute('id', tagName + '_id'); s.appendChild(el); assert_true(s.querySelector('#' + tagName + '_id') != null, 'Form-associated element ' + tagName + ' in shadow tree must be accessible shadow tree accessors'); assert_equals(s.querySelector('#' + tagName + '_id').getAttribute('id'), tagName + '_id', 'Form element ' + tagName + ' in shadow tree must be accessible shadow tree accessors'); }); }, 'A_08_02_02_T02'); //test distributed form elements test(function () { var d = newHTMLDocument(); HTML5_FORM_ASSOCIATED_ELEMENTS.forEach(function (tagName) { var form = d.createElement('form'); d.body.appendChild(form); var div = d.createElement('div'); form.appendChild(div); var el = d.createElement(tagName); el.setAttribute('id', tagName + '_id'); div.appendChild(el); var s = div.createShadowRoot(); s.innerHTML = '<content select="' + tagName + '"></content>'; assert_true(s.querySelector('#' + tagName + '_id') == null, 'Distributed form-associated element ' + tagName + ' in shadow tree must not be accessible shadow tree accessors'); }); }, 'A_08_02_02_T03'); </script> </body> </html>
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "SerialExecutor.h" namespace facebook { namespace hermes { namespace inspector { namespace detail { SerialExecutor::SerialExecutor(const std::string &name) : finish_(false), thread_(name, [this]() { runLoop(); }) {} SerialExecutor::~SerialExecutor() { { std::lock_guard<std::mutex> lock(mutex_); finish_ = true; wakeup_.notify_one(); } thread_.join(); } void SerialExecutor::add(folly::Func func) { std::lock_guard<std::mutex> lock(mutex_); funcs_.push(std::move(func)); wakeup_.notify_one(); } void SerialExecutor::runLoop() { bool shouldExit = false; while (!shouldExit) { folly::Func func; { std::unique_lock<std::mutex> lock(mutex_); wakeup_.wait(lock, [this] { return finish_ || !funcs_.empty(); }); if (!funcs_.empty()) { func = std::move(funcs_.front()); funcs_.pop(); } shouldExit = funcs_.empty() && finish_; } if (func) { func(); } } } } // namespace detail } // namespace inspector } // namespace hermes } // namespace facebook
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/browser_window.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExtensionFullscreenAccessFail) { // Test that fullscreen can be accessed from an extension without permission. ASSERT_TRUE(RunPlatformAppTest("fullscreen/no_permission")) << message_; } // Disabled, a user gesture is required for fullscreen. http://crbug.com/174178 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExtensionFullscreenAccessPass) { // Test that fullscreen can be accessed from an extension with permission. ASSERT_TRUE(RunPlatformAppTest("fullscreen/has_permission")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotExitFullscreen) { browser()->window()->EnterFullscreen( GURL(), EXCLUSIVE_ACCESS_BUBBLE_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION, false); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } // Fails flakily: http://crbug.com/308041 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_UpdateWindowSizeExitsFullscreen) { browser()->window()->EnterFullscreen( GURL(), EXCLUSIVE_ACCESS_BUBBLE_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION, false); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); }
import { ChangeDetectorRef, Component, ElementRef, Input, Optional, Renderer, ViewChild, ViewEncapsulation } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { clamp, isTrueProperty } from '../../util/util'; import { Config } from '../../config/config'; import { DomController } from '../../platform/dom-controller'; import { Form } from '../../util/form'; import { Haptic } from '../../tap-click/haptic'; import { BaseInput } from '../../util/base-input'; import { Item } from '../item/item'; import { Platform } from '../../platform/platform'; import { pointerCoord } from '../../util/dom'; import { UIEventManager } from '../../gestures/ui-event-manager'; /** * \@name Range * \@description * The Range slider lets users select from a range of values by moving * the slider knob. It can accept dual knobs, but by default one knob * controls the value of the range. * * ### Range Labels * Labels can be placed on either side of the range by adding the * `range-left` or `range-right` property to the element. The element * doesn't have to be an `ion-label`, it can be added to any element * to place it to the left or right of the range. See [usage](#usage) * below for examples. * * * ### Minimum and Maximum Values * Minimum and maximum values can be passed to the range through the `min` * and `max` properties, respectively. By default, the range sets the `min` * to `0` and the `max` to `100`. * * * ### Steps and Snaps * The `step` property specifies the value granularity of the range's value. * It can be useful to set the `step` when the value isn't in increments of `1`. * Setting the `step` property will show tick marks on the range for each step. * The `snaps` property can be set to automatically move the knob to the nearest * tick mark based on the step property value. * * * ### Dual Knobs * Setting the `dualKnobs` property to `true` on the range component will * enable two knobs on the range. If the range has two knobs, the value will * be an object containing two properties: `lower` and `upper`. * * * \@usage * ```html * <ion-list> * <ion-item> * <ion-range [(ngModel)]="singleValue" color="danger" pin="true"></ion-range> * </ion-item> * * <ion-item> * <ion-range min="-200" max="200" [(ngModel)]="saturation" color="secondary"> * <ion-label range-left>-200</ion-label> * <ion-label range-right>200</ion-label> * </ion-range> * </ion-item> * * <ion-item> * <ion-range min="20" max="80" step="2" [(ngModel)]="brightness"> * <ion-icon small range-left name="sunny"></ion-icon> * <ion-icon range-right name="sunny"></ion-icon> * </ion-range> * </ion-item> * * <ion-item> * <ion-label>step=100, snaps, {{singleValue4}}</ion-label> * <ion-range min="1000" max="2000" step="100" snaps="true" color="secondary" [(ngModel)]="singleValue4"></ion-range> * </ion-item> * * <ion-item> * <ion-label>dual, step=3, snaps, {{dualValue2 | json}}</ion-label> * <ion-range dualKnobs="true" [(ngModel)]="dualValue2" min="21" max="72" step="3" snaps="true"></ion-range> * </ion-item> * </ion-list> * ``` * * * \@demo /docs/demos/src/range/ */ export class Range extends BaseInput { /** * @param {?} form * @param {?} _haptic * @param {?} item * @param {?} config * @param {?} _plt * @param {?} elementRef * @param {?} renderer * @param {?} _dom * @param {?} _cd */ constructor(form, _haptic, item, config, _plt, elementRef, renderer, _dom, _cd) { super(config, elementRef, renderer, 'range', 0, form, item, null); this._haptic = _haptic; this._plt = _plt; this._dom = _dom; this._cd = _cd; this._min = 0; this._max = 100; this._step = 1; this._valA = 0; this._valB = 0; this._ratioA = 0; this._ratioB = 0; this._events = new UIEventManager(_plt); } /** * \@input {number} Minimum integer value of the range. Defaults to `0`. * @return {?} */ get min() { return this._min; } /** * @param {?} val * @return {?} */ set min(val) { val = Math.round(val); if (!isNaN(val)) { this._min = val; this._inputUpdated(); } } /** * \@input {number} Maximum integer value of the range. Defaults to `100`. * @return {?} */ get max() { return this._max; } /** * @param {?} val * @return {?} */ set max(val) { val = Math.round(val); if (!isNaN(val)) { this._max = val; this._inputUpdated(); } } /** * \@input {number} Specifies the value granularity. Defaults to `1`. * @return {?} */ get step() { return this._step; } /** * @param {?} val * @return {?} */ set step(val) { val = Math.round(val); if (!isNaN(val) && val > 0) { this._step = val; } } /** * \@input {boolean} If true, the knob snaps to tick marks evenly spaced based * on the step property value. Defaults to `false`. * @return {?} */ get snaps() { return this._snaps; } /** * @param {?} val * @return {?} */ set snaps(val) { this._snaps = isTrueProperty(val); } /** * \@input {boolean} If true, a pin with integer value is shown when the knob * is pressed. Defaults to `false`. * @return {?} */ get pin() { return this._pin; } /** * @param {?} val * @return {?} */ set pin(val) { this._pin = isTrueProperty(val); } /** * \@input {number} How long, in milliseconds, to wait to trigger the * `ionChange` event after each change in the range value. Default `0`. * @return {?} */ get debounce() { return this._debouncer.wait; } /** * @param {?} val * @return {?} */ set debounce(val) { this._debouncer.wait = val; } /** * \@input {boolean} Show two knobs. Defaults to `false`. * @return {?} */ get dualKnobs() { return this._dual; } /** * @param {?} val * @return {?} */ set dualKnobs(val) { this._dual = isTrueProperty(val); } /** * Returns the ratio of the knob's is current location, which is a number * between `0` and `1`. If two knobs are used, this property represents * the lower value. * @return {?} */ get ratio() { if (this._dual) { return Math.min(this._ratioA, this._ratioB); } return this._ratioA; } /** * Returns the ratio of the upper value's is current location, which is * a number between `0` and `1`. If there is only one knob, then this * will return `null`. * @return {?} */ get ratioUpper() { if (this._dual) { return Math.max(this._ratioA, this._ratioB); } return null; } /** * @hidden * @return {?} */ ngAfterContentInit() { this._initialize(); // add touchstart/mousedown listeners this._events.pointerEvents({ element: this._slider.nativeElement, pointerDown: this._pointerDown.bind(this), pointerMove: this._pointerMove.bind(this), pointerUp: this._pointerUp.bind(this), zone: true }); // build all the ticks if there are any to show this._createTicks(); } /** * \@internal * @param {?} ev * @return {?} */ _pointerDown(ev) { // TODO: we could stop listening for events instead of checking this._disabled. // since there are a lot of events involved, this solution is // enough for the moment if (this._disabled) { return false; } // trigger ionFocus event this._fireFocus(); // prevent default so scrolling does not happen ev.preventDefault(); ev.stopPropagation(); // get the start coordinates const /** @type {?} */ current = pointerCoord(ev); // get the full dimensions of the slider element const /** @type {?} */ rect = this._rect = this._plt.getElementBoundingClientRect(this._slider.nativeElement); // figure out which knob they started closer to const /** @type {?} */ ratio = clamp(0, (current.x - rect.left) / (rect.width), 1); this._activeB = this._dual && (Math.abs(ratio - this._ratioA) > Math.abs(ratio - this._ratioB)); // update the active knob's position this._update(current, rect, true); // trigger a haptic start this._haptic.gestureSelectionStart(); // return true so the pointer events // know everything's still valid return true; } /** * \@internal * @param {?} ev * @return {?} */ _pointerMove(ev) { if (this._disabled) { return; } // prevent default so scrolling does not happen ev.preventDefault(); ev.stopPropagation(); // update the active knob's position const /** @type {?} */ hasChanged = this._update(pointerCoord(ev), this._rect, true); if (hasChanged && this._snaps) { // trigger a haptic selection changed event // if this is a snap range this._haptic.gestureSelectionChanged(); } } /** * \@internal * @param {?} ev * @return {?} */ _pointerUp(ev) { if (this._disabled) { return; } // prevent default so scrolling does not happen ev.preventDefault(); ev.stopPropagation(); // update the active knob's position this._update(pointerCoord(ev), this._rect, false); // trigger a haptic end this._haptic.gestureSelectionEnd(); // trigger ionBlur event this._fireBlur(); } /** * \@internal * @param {?} current * @param {?} rect * @param {?} isPressed * @return {?} */ _update(current, rect, isPressed) { // figure out where the pointer is currently at // update the knob being interacted with let /** @type {?} */ ratio = clamp(0, (current.x - rect.left) / (rect.width), 1); let /** @type {?} */ val = this._ratioToValue(ratio); if (this._snaps) { // snaps the ratio to the current value ratio = this._valueToRatio(val); } // update which knob is pressed this._pressed = isPressed; let /** @type {?} */ valChanged = false; if (this._activeB) { // when the pointer down started it was determined // that knob B was the one they were interacting with this._pressedB = isPressed; this._pressedA = false; this._ratioB = ratio; valChanged = val === this._valB; this._valB = val; } else { // interacting with knob A this._pressedA = isPressed; this._pressedB = false; this._ratioA = ratio; valChanged = val === this._valA; this._valA = val; } this._updateBar(); if (valChanged) { return false; } // value has been updated let /** @type {?} */ value; if (this._dual) { // dual knobs have an lower and upper value value = { lower: Math.min(this._valA, this._valB), upper: Math.max(this._valA, this._valB) }; (void 0) /* console.debug */; } else { // single knob only has one value value = this._valA; (void 0) /* console.debug */; } // Update input value this.value = value; return true; } /** * \@internal * @return {?} */ _updateBar() { const /** @type {?} */ ratioA = this._ratioA; const /** @type {?} */ ratioB = this._ratioB; if (this._dual) { this._barL = `${(Math.min(ratioA, ratioB) * 100)}%`; this._barR = `${100 - (Math.max(ratioA, ratioB) * 100)}%`; } else { this._barL = ''; this._barR = `${100 - (ratioA * 100)}%`; } this._updateTicks(); } /** * \@internal * @return {?} */ _createTicks() { if (this._snaps) { this._dom.write(() => { // TODO: Fix to not use RAF this._ticks = []; for (var /** @type {?} */ value = this._min; value <= this._max; value += this._step) { var /** @type {?} */ ratio = this._valueToRatio(value); this._ticks.push({ ratio: ratio, left: `${ratio * 100}%`, }); } this._updateTicks(); }); } } /** * \@internal * @return {?} */ _updateTicks() { const /** @type {?} */ ticks = this._ticks; const /** @type {?} */ ratio = this.ratio; if (this._snaps && ticks) { if (this._dual) { var /** @type {?} */ upperRatio = this.ratioUpper; ticks.forEach(t => { t.active = (t.ratio >= ratio && t.ratio <= upperRatio); }); } else { ticks.forEach(t => { t.active = (t.ratio <= ratio); }); } } } /** * @hidden * @param {?} isIncrease * @param {?} isKnobB * @return {?} */ _keyChg(isIncrease, isKnobB) { const /** @type {?} */ step = this._step; if (isKnobB) { if (isIncrease) { this._valB += step; } else { this._valB -= step; } this._valB = clamp(this._min, this._valB, this._max); this._ratioB = this._valueToRatio(this._valB); } else { if (isIncrease) { this._valA += step; } else { this._valA -= step; } this._valA = clamp(this._min, this._valA, this._max); this._ratioA = this._valueToRatio(this._valA); } this._updateBar(); } /** * \@internal * @param {?} ratio * @return {?} */ _ratioToValue(ratio) { ratio = Math.round(((this._max - this._min) * ratio)); ratio = Math.round(ratio / this._step) * this._step + this._min; return clamp(this._min, ratio, this._max); } /** * \@internal * @param {?} value * @return {?} */ _valueToRatio(value) { value = Math.round((value - this._min) / this._step) * this._step; value = value / (this._max - this._min); return clamp(0, value, 1); } /** * @param {?} val * @return {?} */ _inputNormalize(val) { if (this._dual) { return val; } else { val = parseFloat(val); return isNaN(val) ? undefined : val; } } /** * @hidden * @return {?} */ _inputUpdated() { const /** @type {?} */ val = this.value; if (this._dual) { this._valA = val.lower; this._valB = val.upper; this._ratioA = this._valueToRatio(val.lower); this._ratioB = this._valueToRatio(val.upper); } else { this._valA = val; this._ratioA = this._valueToRatio(val); } this._updateBar(); this._cd.detectChanges(); } /** * @hidden * @return {?} */ ngOnDestroy() { super.ngOnDestroy(); this._events.destroy(); } } Range.decorators = [ { type: Component, args: [{ selector: 'ion-range', template: '<ng-content select="[range-left]"></ng-content>' + '<div class="range-slider" #slider>' + '<div class="range-tick" *ngFor="let t of _ticks" [style.left]="t.left" [class.range-tick-active]="t.active" role="presentation"></div>' + '<div class="range-bar" role="presentation"></div>' + '<div class="range-bar range-bar-active" [style.left]="_barL" [style.right]="_barR" #bar role="presentation"></div>' + '<div class="range-knob-handle" (ionIncrease)="_keyChg(true, false)" (ionDecrease)="_keyChg(false, false)" [ratio]="_ratioA" [val]="_valA" [pin]="_pin" [pressed]="_pressedA" [min]="_min" [max]="_max" [disabled]="_disabled" [labelId]="_labelId"></div>' + '<div class="range-knob-handle" (ionIncrease)="_keyChg(true, true)" (ionDecrease)="_keyChg(false, true)" [ratio]="_ratioB" [val]="_valB" [pin]="_pin" [pressed]="_pressedB" [min]="_min" [max]="_max" [disabled]="_disabled" [labelId]="_labelId" *ngIf="_dual"></div>' + '</div>' + '<ng-content select="[range-right]"></ng-content>', host: { '[class.range-disabled]': '_disabled', '[class.range-pressed]': '_pressed', '[class.range-has-pin]': '_pin' }, providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: Range, multi: true }], encapsulation: ViewEncapsulation.None, },] }, ]; /** * @nocollapse */ Range.ctorParameters = () => [ { type: Form, }, { type: Haptic, }, { type: Item, decorators: [{ type: Optional },] }, { type: Config, }, { type: Platform, }, { type: ElementRef, }, { type: Renderer, }, { type: DomController, }, { type: ChangeDetectorRef, }, ]; Range.propDecorators = { '_slider': [{ type: ViewChild, args: ['slider',] },], 'min': [{ type: Input },], 'max': [{ type: Input },], 'step': [{ type: Input },], 'snaps': [{ type: Input },], 'pin': [{ type: Input },], 'debounce': [{ type: Input },], 'dualKnobs': [{ type: Input },], }; function Range_tsickle_Closure_declarations() { /** @type {?} */ Range.decorators; /** * @nocollapse * @type {?} */ Range.ctorParameters; /** @type {?} */ Range.propDecorators; /** @type {?} */ Range.prototype._dual; /** @type {?} */ Range.prototype._pin; /** @type {?} */ Range.prototype._pressed; /** @type {?} */ Range.prototype._activeB; /** @type {?} */ Range.prototype._rect; /** @type {?} */ Range.prototype._ticks; /** @type {?} */ Range.prototype._min; /** @type {?} */ Range.prototype._max; /** @type {?} */ Range.prototype._step; /** @type {?} */ Range.prototype._snaps; /** @type {?} */ Range.prototype._valA; /** @type {?} */ Range.prototype._valB; /** @type {?} */ Range.prototype._ratioA; /** @type {?} */ Range.prototype._ratioB; /** @type {?} */ Range.prototype._pressedA; /** @type {?} */ Range.prototype._pressedB; /** @type {?} */ Range.prototype._barL; /** @type {?} */ Range.prototype._barR; /** @type {?} */ Range.prototype._events; /** @type {?} */ Range.prototype._slider; /** @type {?} */ Range.prototype._haptic; /** @type {?} */ Range.prototype._plt; /** @type {?} */ Range.prototype._dom; /** @type {?} */ Range.prototype._cd; } //# sourceMappingURL=range.js.map
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.tabmodel; import org.chromium.chrome.browser.Tab; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; import java.util.List; /** * An interface to be notified about changes to a TabModel. */ public interface TabModelObserver { /** * Called when a tab is selected. * * @param tab The newly selected tab. * @param type The type of selection. * @param lastId The ID of the last selected tab, or {@link Tab#INVALID_TAB_ID} if no tab was * selected. */ void didSelectTab(Tab tab, TabSelectionType type, int lastId); /** * Called when a tab starts closing. * * @param tab The tab to close. * @param animate Whether or not to animate the closing. */ void willCloseTab(Tab tab, boolean animate); /** * Called right after {@code tab} has been destroyed. * * @param tab The tab that has been destroyed. */ void didCloseTab(Tab tab); /** * Called before a tab will be added to the {@link TabModel}. * * @param tab The tab about to be added. * @param type The type of tab launch. */ void willAddTab(Tab tab, TabLaunchType type); /** * Called after a tab has been added to the {@link TabModel}. * * @param tab The newly added tab. * @param type The type of tab launch. */ void didAddTab(Tab tab, TabLaunchType type); /** * Called after a tab has been moved from one position in the {@link TabModel} to another. * * @param tab The tab which has been moved. * @param newIndex The new index of the tab in the model. * @param curIndex The old index of the tab in the model. */ void didMoveTab(Tab tab, int newIndex, int curIndex); /** * Called when a tab is pending closure, i.e. the user has just closed it, but it can still be * undone. At this point, the Tab has been removed from the TabModel and can only be accessed * via {@link TabModel#getComprehensiveModel()}. * * @param tab The tab that is pending closure. */ void tabPendingClosure(Tab tab); /** * Called when a tab closure is undone. * * @param tab The tab that has been reopened. */ void tabClosureUndone(Tab tab); /** * Called when a tab closure is committed and can't be undone anymore. * * @param tab The tab that has been closed. */ void tabClosureCommitted(Tab tab); /** * Called when "all tabs" are pending closure. * * @param tabIds The list of tabs IDs that are pending closure. */ void allTabsPendingClosure(List<Integer> tabIds); /** * Called when an "all tabs" closure has been committed and can't be undone anymore. */ void allTabsClosureCommitted(); }
package org.motechproject.mds.test.service.manytomany; import org.motechproject.mds.annotations.Lookup; import org.motechproject.mds.annotations.LookupField; import org.motechproject.mds.service.MotechDataService; import org.motechproject.mds.test.domain.manytomany.Product;; public interface ProductDataService extends MotechDataService<Product> { @Lookup Product findByProductName(@LookupField(name = "productName") String productName); }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gsub.h" #include <limits> #include <vector> #include "gdef.h" #include "gpos.h" #include "layout.h" #include "maxp.h" // GSUB - The Glyph Substitution Table // http://www.microsoft.com/typography/otspec/gsub.htm namespace { // The GSUB header size const size_t kGsubHeaderSize = 4 + 3 * 2; enum GSUB_TYPE { GSUB_TYPE_SINGLE = 1, GSUB_TYPE_MULTIPLE = 2, GSUB_TYPE_ALTERNATE = 3, GSUB_TYPE_LIGATURE = 4, GSUB_TYPE_CONTEXT = 5, GSUB_TYPE_CHANGING_CONTEXT = 6, GSUB_TYPE_EXTENSION_SUBSTITUTION = 7, GSUB_TYPE_REVERSE_CHAINING_CONTEXT_SINGLE = 8, GSUB_TYPE_RESERVED = 9 }; // Lookup type parsers. bool ParseSingleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseMutipleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseAlternateSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseLigatureSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseChainingContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseExtensionSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseReverseChainingContextSingleSubstitution( const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); const ots::LookupSubtableParser::TypeParser kGsubTypeParsers[] = { {GSUB_TYPE_SINGLE, ParseSingleSubstitution}, {GSUB_TYPE_MULTIPLE, ParseMutipleSubstitution}, {GSUB_TYPE_ALTERNATE, ParseAlternateSubstitution}, {GSUB_TYPE_LIGATURE, ParseLigatureSubstitution}, {GSUB_TYPE_CONTEXT, ParseContextSubstitution}, {GSUB_TYPE_CHANGING_CONTEXT, ParseChainingContextSubstitution}, {GSUB_TYPE_EXTENSION_SUBSTITUTION, ParseExtensionSubstitution}, {GSUB_TYPE_REVERSE_CHAINING_CONTEXT_SINGLE, ParseReverseChainingContextSingleSubstitution} }; const ots::LookupSubtableParser kGsubLookupSubtableParser = { arraysize(kGsubTypeParsers), GSUB_TYPE_EXTENSION_SUBSTITUTION, kGsubTypeParsers }; // Lookup Type 1: // Single Substitution Subtable bool ParseSingleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage)) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; if (format == 1) { // Parse SingleSubstFormat1 int16_t delta_glyph_id = 0; if (!subtable.ReadS16(&delta_glyph_id)) { return OTS_FAILURE(); } if (std::abs(delta_glyph_id) >= num_glyphs) { return OTS_FAILURE(); } } else if (format == 2) { // Parse SingleSubstFormat2 uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t substitute = 0; if (!subtable.ReadU16(&substitute)) { return OTS_FAILURE(); } if (substitute >= num_glyphs) { OTS_WARNING("too large substitute: %u", substitute); return OTS_FAILURE(); } } } else { return OTS_FAILURE(); } if (offset_coverage < subtable.offset() || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } bool ParseSequenceTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t substitute = 0; if (!subtable.ReadU16(&substitute)) { return OTS_FAILURE(); } if (substitute >= num_glyphs) { return OTS_FAILURE(); } } return true; } // Lookup Type 2: // Multiple Substitution Subtable bool ParseMutipleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; uint16_t sequence_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&sequence_count)) { return OTS_FAILURE(); } if (format != 1) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; const unsigned sequence_end = static_cast<unsigned>(6) + sequence_count * 2; if (sequence_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < sequence_count; ++i) { uint16_t offset_sequence = 0; if (!subtable.ReadU16(&offset_sequence)) { return OTS_FAILURE(); } if (offset_sequence < sequence_end || offset_sequence >= length) { return OTS_FAILURE(); } if (!ParseSequenceTable(data + offset_sequence, length - offset_sequence, num_glyphs)) { return OTS_FAILURE(); } } if (offset_coverage < sequence_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } bool ParseAlternateSetTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t alternate = 0; if (!subtable.ReadU16(&alternate)) { return OTS_FAILURE(); } if (alternate >= num_glyphs) { OTS_WARNING("too arge alternate: %u", alternate); return OTS_FAILURE(); } } return true; } // Lookup Type 3: // Alternate Substitution Subtable bool ParseAlternateSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; uint16_t alternate_set_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&alternate_set_count)) { return OTS_FAILURE(); } if (format != 1) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; const unsigned alternate_set_end = static_cast<unsigned>(6) + alternate_set_count * 2; if (alternate_set_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < alternate_set_count; ++i) { uint16_t offset_alternate_set = 0; if (!subtable.ReadU16(&offset_alternate_set)) { return OTS_FAILURE(); } if (offset_alternate_set < alternate_set_end || offset_alternate_set >= length) { return OTS_FAILURE(); } if (!ParseAlternateSetTable(data + offset_alternate_set, length - offset_alternate_set, num_glyphs)) { return OTS_FAILURE(); } } if (offset_coverage < alternate_set_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } bool ParseLigatureTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t lig_glyph = 0; uint16_t comp_count = 0; if (!subtable.ReadU16(&lig_glyph) || !subtable.ReadU16(&comp_count)) { return OTS_FAILURE(); } if (lig_glyph >= num_glyphs) { OTS_WARNING("too large lig_glyph: %u", lig_glyph); return OTS_FAILURE(); } if (comp_count == 0 || comp_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < comp_count - static_cast<unsigned>(1); ++i) { uint16_t component = 0; if (!subtable.ReadU16(&component)) { return OTS_FAILURE(); } if (component >= num_glyphs) { return OTS_FAILURE(); } } return true; } bool ParseLigatureSetTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t ligature_count = 0; if (!subtable.ReadU16(&ligature_count)) { return OTS_FAILURE(); } const unsigned ligature_end = static_cast<unsigned>(2) + ligature_count * 2; if (ligature_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < ligature_count; ++i) { uint16_t offset_ligature = 0; if (!subtable.ReadU16(&offset_ligature)) { return OTS_FAILURE(); } if (offset_ligature < ligature_end || offset_ligature >= length) { return OTS_FAILURE(); } if (!ParseLigatureTable(data + offset_ligature, length - offset_ligature, num_glyphs)) { return OTS_FAILURE(); } } return true; } // Lookup Type 4: // Ligature Substitution Subtable bool ParseLigatureSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; uint16_t lig_set_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&lig_set_count)) { return OTS_FAILURE(); } if (format != 1) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; const unsigned ligature_set_end = static_cast<unsigned>(6) + lig_set_count * 2; if (ligature_set_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < lig_set_count; ++i) { uint16_t offset_ligature_set = 0; if (!subtable.ReadU16(&offset_ligature_set)) { return OTS_FAILURE(); } if (offset_ligature_set < ligature_set_end || offset_ligature_set >= length) { return OTS_FAILURE(); } if (!ParseLigatureSetTable(data + offset_ligature_set, length - offset_ligature_set, num_glyphs)) { return OTS_FAILURE(); } } if (offset_coverage < ligature_set_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } // Lookup Type 5: // Contextual Substitution Subtable bool ParseContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { return ots::ParseContextSubtable(data, length, file->maxp->num_glyphs, file->gsub->num_lookups); } // Lookup Type 6: // Chaining Contextual Substitution Subtable bool ParseChainingContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { return ots::ParseChainingContextSubtable(data, length, file->maxp->num_glyphs, file->gsub->num_lookups); } // Lookup Type 7: // Extension Substition bool ParseExtensionSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { return ots::ParseExtensionSubtable(file, data, length, &kGsubLookupSubtableParser); } // Lookup Type 8: // Reverse Chaining Contexual Single Substitution Subtable bool ParseReverseChainingContextSingleSubstitution( const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage)) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; uint16_t backtrack_glyph_count = 0; if (!subtable.ReadU16(&backtrack_glyph_count)) { return OTS_FAILURE(); } if (backtrack_glyph_count > num_glyphs) { return OTS_FAILURE(); } std::vector<uint16_t> offsets_backtrack; offsets_backtrack.reserve(backtrack_glyph_count); for (unsigned i = 0; i < backtrack_glyph_count; ++i) { uint16_t offset = 0; if (!subtable.ReadU16(&offset)) { return OTS_FAILURE(); } offsets_backtrack.push_back(offset); } uint16_t lookahead_glyph_count = 0; if (!subtable.ReadU16(&lookahead_glyph_count)) { return OTS_FAILURE(); } if (lookahead_glyph_count > num_glyphs) { return OTS_FAILURE(); } std::vector<uint16_t> offsets_lookahead; offsets_lookahead.reserve(lookahead_glyph_count); for (unsigned i = 0; i < lookahead_glyph_count; ++i) { uint16_t offset = 0; if (!subtable.ReadU16(&offset)) { return OTS_FAILURE(); } offsets_lookahead.push_back(offset); } uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t substitute = 0; if (!subtable.ReadU16(&substitute)) { return OTS_FAILURE(); } if (substitute >= num_glyphs) { return OTS_FAILURE(); } } const unsigned substitute_end = static_cast<unsigned>(10) + (backtrack_glyph_count + lookahead_glyph_count + glyph_count) * 2; if (substitute_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } if (offset_coverage < substitute_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } for (unsigned i = 0; i < backtrack_glyph_count; ++i) { if (offsets_backtrack[i] < substitute_end || offsets_backtrack[i] >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offsets_backtrack[i], length - offsets_backtrack[i], num_glyphs)) { return OTS_FAILURE(); } } for (unsigned i = 0; i < lookahead_glyph_count; ++i) { if (offsets_lookahead[i] < substitute_end || offsets_lookahead[i] >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offsets_lookahead[i], length - offsets_lookahead[i], num_glyphs)) { return OTS_FAILURE(); } } return true; } } // namespace #define DROP_THIS_TABLE \ do { file->gsub->data = 0; file->gsub->length = 0; } while (0) namespace ots { // As far as I checked, following fonts contain invalid values in GSUB table. // OTS will drop their GSUB table. // // # too large substitute (value is 0xFFFF) // kaiu.ttf // mingliub2.ttf // mingliub1.ttf // mingliub0.ttf // GraublauWeb.otf // GraublauWebBold.otf // // # too large alternate (value is 0xFFFF) // ManchuFont.ttf // // # bad offset to lang sys table (NULL offset) // DejaVuMonoSansBold.ttf // DejaVuMonoSansBoldOblique.ttf // DejaVuMonoSansOblique.ttf // DejaVuSansMono-BoldOblique.ttf // DejaVuSansMono-Oblique.ttf // DejaVuSansMono-Bold.ttf // // # bad start coverage index // GenBasBI.ttf // GenBasI.ttf // AndBasR.ttf // GenBkBasI.ttf // CharisSILR.ttf // CharisSILBI.ttf // CharisSILI.ttf // CharisSILB.ttf // DoulosSILR.ttf // CharisSILBI.ttf // GenBkBasB.ttf // GenBkBasR.ttf // GenBkBasBI.ttf // GenBasB.ttf // GenBasR.ttf // // # glyph range is overlapping // KacstTitleL.ttf // KacstDecorative.ttf // KacstTitle.ttf // KacstArt.ttf // KacstPoster.ttf // KacstQurn.ttf // KacstDigital.ttf // KacstBook.ttf // KacstFarsi.ttf bool ots_gsub_parse(OpenTypeFile *file, const uint8_t *data, size_t length) { // Parsing gsub table requires |file->maxp->num_glyphs| if (!file->maxp) { return OTS_FAILURE(); } Buffer table(data, length); OpenTypeGSUB *gsub = new OpenTypeGSUB; file->gsub = gsub; uint32_t version = 0; uint16_t offset_script_list = 0; uint16_t offset_feature_list = 0; uint16_t offset_lookup_list = 0; if (!table.ReadU32(&version) || !table.ReadU16(&offset_script_list) || !table.ReadU16(&offset_feature_list) || !table.ReadU16(&offset_lookup_list)) { return OTS_FAILURE(); } if (version != 0x00010000) { OTS_WARNING("bad GSUB version"); DROP_THIS_TABLE; return true; } if ((offset_script_list < kGsubHeaderSize || offset_script_list >= length) || (offset_feature_list < kGsubHeaderSize || offset_feature_list >= length) || (offset_lookup_list < kGsubHeaderSize || offset_lookup_list >= length)) { OTS_WARNING("bad offset in GSUB header"); DROP_THIS_TABLE; return true; } if (!ParseLookupListTable(file, data + offset_lookup_list, length - offset_lookup_list, &kGsubLookupSubtableParser, &gsub->num_lookups)) { OTS_WARNING("faild to parse lookup list table"); DROP_THIS_TABLE; return true; } uint16_t num_features = 0; if (!ParseFeatureListTable(data + offset_feature_list, length - offset_feature_list, gsub->num_lookups, &num_features)) { OTS_WARNING("faild to parse feature list table"); DROP_THIS_TABLE; return true; } if (!ParseScriptListTable(data + offset_script_list, length - offset_script_list, num_features)) { OTS_WARNING("faild to parse script list table"); DROP_THIS_TABLE; return true; } gsub->data = data; gsub->length = length; return true; } bool ots_gsub_should_serialise(OpenTypeFile *file) { const bool needed_tables_dropped = (file->gdef && file->gdef->data == NULL) || (file->gpos && file->gpos->data == NULL); return file->gsub != NULL && file->gsub->data != NULL && !needed_tables_dropped; } bool ots_gsub_serialise(OTSStream *out, OpenTypeFile *file) { if (!out->Write(file->gsub->data, file->gsub->length)) { return OTS_FAILURE(); } return true; } void ots_gsub_free(OpenTypeFile *file) { delete file->gsub; } } // namespace ots
/** * @file * Styles for password suggestions in Bartik. */ .password-suggestions { border: 0; }
/* * OF helpers for parsing display timings * * Copyright (c) 2012 Steffen Trumtrar <s.trumtrar@pengutronix.de>, Pengutronix * * based on of_videomode.c by Sascha Hauer <s.hauer@pengutronix.de> * * This file is released under the GPLv2 */ #include <linux/export.h> #include <linux/of.h> #include <linux/slab.h> #include <video/display_timing.h> #include <video/of_display_timing.h> /** * parse_timing_property - parse timing_entry from device_node * @np: device_node with the property * @name: name of the property * @result: will be set to the return value * * DESCRIPTION: * Every display_timing can be specified with either just the typical value or * a range consisting of min/typ/max. This function helps handling this **/ static int parse_timing_property(struct device_node *np, const char *name, struct timing_entry *result) { struct property *prop; int length, cells, ret; prop = of_find_property(np, name, &length); if (!prop) { pr_err("%s: could not find property %s\n", of_node_full_name(np), name); return -EINVAL; } cells = length / sizeof(u32); if (cells == 1) { ret = of_property_read_u32(np, name, &result->typ); result->min = result->typ; result->max = result->typ; } else if (cells == 3) { ret = of_property_read_u32_array(np, name, &result->min, cells); } else { pr_err("%s: illegal timing specification in %s\n", of_node_full_name(np), name); return -EINVAL; } return ret; } /** * of_get_display_timing - parse display_timing entry from device_node * @np: device_node with the properties **/ static struct display_timing *of_get_display_timing(struct device_node *np) { struct display_timing *dt; u32 val = 0; int ret = 0; dt = kzalloc(sizeof(*dt), GFP_KERNEL); if (!dt) { pr_err("%s: could not allocate display_timing struct\n", of_node_full_name(np)); return NULL; } ret |= parse_timing_property(np, "hback-porch", &dt->hback_porch); ret |= parse_timing_property(np, "hfront-porch", &dt->hfront_porch); ret |= parse_timing_property(np, "hactive", &dt->hactive); ret |= parse_timing_property(np, "hsync-len", &dt->hsync_len); ret |= parse_timing_property(np, "vback-porch", &dt->vback_porch); ret |= parse_timing_property(np, "vfront-porch", &dt->vfront_porch); ret |= parse_timing_property(np, "vactive", &dt->vactive); ret |= parse_timing_property(np, "vsync-len", &dt->vsync_len); ret |= parse_timing_property(np, "clock-frequency", &dt->pixelclock); dt->flags = 0; if (!of_property_read_u32(np, "vsync-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_VSYNC_HIGH : DISPLAY_FLAGS_VSYNC_LOW; if (!of_property_read_u32(np, "hsync-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_HSYNC_HIGH : DISPLAY_FLAGS_HSYNC_LOW; if (!of_property_read_u32(np, "de-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_DE_HIGH : DISPLAY_FLAGS_DE_LOW; if (!of_property_read_u32(np, "pixelclk-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_PIXDATA_POSEDGE : DISPLAY_FLAGS_PIXDATA_NEGEDGE; if (of_property_read_bool(np, "interlaced")) dt->flags |= DISPLAY_FLAGS_INTERLACED; if (of_property_read_bool(np, "doublescan")) dt->flags |= DISPLAY_FLAGS_DOUBLESCAN; if (ret) { pr_err("%s: error reading timing properties\n", of_node_full_name(np)); kfree(dt); return NULL; } return dt; } /** * of_get_display_timings - parse all display_timing entries from a device_node * @np: device_node with the subnodes **/ struct display_timings *of_get_display_timings(struct device_node *np) { struct device_node *timings_np; struct device_node *entry; struct device_node *native_mode; struct display_timings *disp; if (!np) { pr_err("%s: no devicenode given\n", of_node_full_name(np)); return NULL; } timings_np = of_find_node_by_name(np, "display-timings"); if (!timings_np) { pr_err("%s: could not find display-timings node\n", of_node_full_name(np)); return NULL; } disp = kzalloc(sizeof(*disp), GFP_KERNEL); if (!disp) { pr_err("%s: could not allocate struct disp'\n", of_node_full_name(np)); goto dispfail; } entry = of_parse_phandle(timings_np, "native-mode", 0); /* assume first child as native mode if none provided */ if (!entry) entry = of_get_next_child(np, NULL); /* if there is no child, it is useless to go on */ if (!entry) { pr_err("%s: no timing specifications given\n", of_node_full_name(np)); goto entryfail; } pr_debug("%s: using %s as default timing\n", of_node_full_name(np), entry->name); native_mode = entry; disp->num_timings = of_get_child_count(timings_np); if (disp->num_timings == 0) { /* should never happen, as entry was already found above */ pr_err("%s: no timings specified\n", of_node_full_name(np)); goto entryfail; } disp->timings = kzalloc(sizeof(struct display_timing *) * disp->num_timings, GFP_KERNEL); if (!disp->timings) { pr_err("%s: could not allocate timings array\n", of_node_full_name(np)); goto entryfail; } disp->num_timings = 0; disp->native_mode = 0; for_each_child_of_node(timings_np, entry) { struct display_timing *dt; dt = of_get_display_timing(entry); if (!dt) { /* * to not encourage wrong devicetrees, fail in case of * an error */ pr_err("%s: error in timing %d\n", of_node_full_name(np), disp->num_timings + 1); goto timingfail; } if (native_mode == entry) disp->native_mode = disp->num_timings; disp->timings[disp->num_timings] = dt; disp->num_timings++; } of_node_put(timings_np); /* * native_mode points to the device_node returned by of_parse_phandle * therefore call of_node_put on it */ of_node_put(native_mode); pr_debug("%s: got %d timings. Using timing #%d as default\n", of_node_full_name(np), disp->num_timings, disp->native_mode + 1); return disp; timingfail: if (native_mode) of_node_put(native_mode); display_timings_release(disp); entryfail: kfree(disp); dispfail: of_node_put(timings_np); return NULL; } EXPORT_SYMBOL_GPL(of_get_display_timings); /** * of_display_timings_exist - check if a display-timings node is provided * @np: device_node with the timing **/ int of_display_timings_exist(struct device_node *np) { struct device_node *timings_np; if (!np) return -EINVAL; timings_np = of_parse_phandle(np, "display-timings", 0); if (!timings_np) return -EINVAL; of_node_put(timings_np); return 1; } EXPORT_SYMBOL_GPL(of_display_timings_exist);
<?php // autoload.php generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit518a89b59c2eb3bdea93f03672c19e1a::getLoader();
/**************************************************************************//** * @file efm32lg_rtc.h * @brief EFM32LG_RTC register and bit field definitions * @version 4.2.0 ****************************************************************************** * @section License * <b>Copyright 2015 Silicon Laboratories, Inc. http://www.silabs.com</b> ****************************************************************************** * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software.@n * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software.@n * 3. This notice may not be removed or altered from any source distribution. * * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Laboratories, Inc. * has no obligation to support this Software. Silicon Laboratories, Inc. is * providing the Software "AS IS", with no express or implied warranties of any * kind, including, but not limited to, any implied warranties of * merchantability or fitness for any particular purpose or warranties against * infringement of any proprietary rights of a third party. * * Silicon Laboratories, Inc. will not be liable for any consequential, * incidental, or special damages, or any other relief, or for any claim by * any third party, arising from your use of this Software. * *****************************************************************************/ /**************************************************************************//** * @addtogroup Parts * @{ ******************************************************************************/ /**************************************************************************//** * @defgroup EFM32LG_RTC * @{ * @brief EFM32LG_RTC Register Declaration *****************************************************************************/ typedef struct { __IO uint32_t CTRL; /**< Control Register */ __IO uint32_t CNT; /**< Counter Value Register */ __IO uint32_t COMP0; /**< Compare Value Register 0 */ __IO uint32_t COMP1; /**< Compare Value Register 1 */ __I uint32_t IF; /**< Interrupt Flag Register */ __IO uint32_t IFS; /**< Interrupt Flag Set Register */ __IO uint32_t IFC; /**< Interrupt Flag Clear Register */ __IO uint32_t IEN; /**< Interrupt Enable Register */ __IO uint32_t FREEZE; /**< Freeze Register */ __I uint32_t SYNCBUSY; /**< Synchronization Busy Register */ } RTC_TypeDef; /** @} */ /**************************************************************************//** * @defgroup EFM32LG_RTC_BitFields * @{ *****************************************************************************/ /* Bit fields for RTC CTRL */ #define _RTC_CTRL_RESETVALUE 0x00000000UL /**< Default value for RTC_CTRL */ #define _RTC_CTRL_MASK 0x00000007UL /**< Mask for RTC_CTRL */ #define RTC_CTRL_EN (0x1UL << 0) /**< RTC Enable */ #define _RTC_CTRL_EN_SHIFT 0 /**< Shift value for RTC_EN */ #define _RTC_CTRL_EN_MASK 0x1UL /**< Bit mask for RTC_EN */ #define _RTC_CTRL_EN_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_CTRL */ #define RTC_CTRL_EN_DEFAULT (_RTC_CTRL_EN_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_CTRL */ #define RTC_CTRL_DEBUGRUN (0x1UL << 1) /**< Debug Mode Run Enable */ #define _RTC_CTRL_DEBUGRUN_SHIFT 1 /**< Shift value for RTC_DEBUGRUN */ #define _RTC_CTRL_DEBUGRUN_MASK 0x2UL /**< Bit mask for RTC_DEBUGRUN */ #define _RTC_CTRL_DEBUGRUN_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_CTRL */ #define RTC_CTRL_DEBUGRUN_DEFAULT (_RTC_CTRL_DEBUGRUN_DEFAULT << 1) /**< Shifted mode DEFAULT for RTC_CTRL */ #define RTC_CTRL_COMP0TOP (0x1UL << 2) /**< Compare Channel 0 is Top Value */ #define _RTC_CTRL_COMP0TOP_SHIFT 2 /**< Shift value for RTC_COMP0TOP */ #define _RTC_CTRL_COMP0TOP_MASK 0x4UL /**< Bit mask for RTC_COMP0TOP */ #define _RTC_CTRL_COMP0TOP_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_CTRL */ #define _RTC_CTRL_COMP0TOP_DISABLE 0x00000000UL /**< Mode DISABLE for RTC_CTRL */ #define _RTC_CTRL_COMP0TOP_ENABLE 0x00000001UL /**< Mode ENABLE for RTC_CTRL */ #define RTC_CTRL_COMP0TOP_DEFAULT (_RTC_CTRL_COMP0TOP_DEFAULT << 2) /**< Shifted mode DEFAULT for RTC_CTRL */ #define RTC_CTRL_COMP0TOP_DISABLE (_RTC_CTRL_COMP0TOP_DISABLE << 2) /**< Shifted mode DISABLE for RTC_CTRL */ #define RTC_CTRL_COMP0TOP_ENABLE (_RTC_CTRL_COMP0TOP_ENABLE << 2) /**< Shifted mode ENABLE for RTC_CTRL */ /* Bit fields for RTC CNT */ #define _RTC_CNT_RESETVALUE 0x00000000UL /**< Default value for RTC_CNT */ #define _RTC_CNT_MASK 0x00FFFFFFUL /**< Mask for RTC_CNT */ #define _RTC_CNT_CNT_SHIFT 0 /**< Shift value for RTC_CNT */ #define _RTC_CNT_CNT_MASK 0xFFFFFFUL /**< Bit mask for RTC_CNT */ #define _RTC_CNT_CNT_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_CNT */ #define RTC_CNT_CNT_DEFAULT (_RTC_CNT_CNT_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_CNT */ /* Bit fields for RTC COMP0 */ #define _RTC_COMP0_RESETVALUE 0x00000000UL /**< Default value for RTC_COMP0 */ #define _RTC_COMP0_MASK 0x00FFFFFFUL /**< Mask for RTC_COMP0 */ #define _RTC_COMP0_COMP0_SHIFT 0 /**< Shift value for RTC_COMP0 */ #define _RTC_COMP0_COMP0_MASK 0xFFFFFFUL /**< Bit mask for RTC_COMP0 */ #define _RTC_COMP0_COMP0_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_COMP0 */ #define RTC_COMP0_COMP0_DEFAULT (_RTC_COMP0_COMP0_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_COMP0 */ /* Bit fields for RTC COMP1 */ #define _RTC_COMP1_RESETVALUE 0x00000000UL /**< Default value for RTC_COMP1 */ #define _RTC_COMP1_MASK 0x00FFFFFFUL /**< Mask for RTC_COMP1 */ #define _RTC_COMP1_COMP1_SHIFT 0 /**< Shift value for RTC_COMP1 */ #define _RTC_COMP1_COMP1_MASK 0xFFFFFFUL /**< Bit mask for RTC_COMP1 */ #define _RTC_COMP1_COMP1_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_COMP1 */ #define RTC_COMP1_COMP1_DEFAULT (_RTC_COMP1_COMP1_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_COMP1 */ /* Bit fields for RTC IF */ #define _RTC_IF_RESETVALUE 0x00000000UL /**< Default value for RTC_IF */ #define _RTC_IF_MASK 0x00000007UL /**< Mask for RTC_IF */ #define RTC_IF_OF (0x1UL << 0) /**< Overflow Interrupt Flag */ #define _RTC_IF_OF_SHIFT 0 /**< Shift value for RTC_OF */ #define _RTC_IF_OF_MASK 0x1UL /**< Bit mask for RTC_OF */ #define _RTC_IF_OF_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IF */ #define RTC_IF_OF_DEFAULT (_RTC_IF_OF_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_IF */ #define RTC_IF_COMP0 (0x1UL << 1) /**< Compare Match 0 Interrupt Flag */ #define _RTC_IF_COMP0_SHIFT 1 /**< Shift value for RTC_COMP0 */ #define _RTC_IF_COMP0_MASK 0x2UL /**< Bit mask for RTC_COMP0 */ #define _RTC_IF_COMP0_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IF */ #define RTC_IF_COMP0_DEFAULT (_RTC_IF_COMP0_DEFAULT << 1) /**< Shifted mode DEFAULT for RTC_IF */ #define RTC_IF_COMP1 (0x1UL << 2) /**< Compare Match 1 Interrupt Flag */ #define _RTC_IF_COMP1_SHIFT 2 /**< Shift value for RTC_COMP1 */ #define _RTC_IF_COMP1_MASK 0x4UL /**< Bit mask for RTC_COMP1 */ #define _RTC_IF_COMP1_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IF */ #define RTC_IF_COMP1_DEFAULT (_RTC_IF_COMP1_DEFAULT << 2) /**< Shifted mode DEFAULT for RTC_IF */ /* Bit fields for RTC IFS */ #define _RTC_IFS_RESETVALUE 0x00000000UL /**< Default value for RTC_IFS */ #define _RTC_IFS_MASK 0x00000007UL /**< Mask for RTC_IFS */ #define RTC_IFS_OF (0x1UL << 0) /**< Set Overflow Interrupt Flag */ #define _RTC_IFS_OF_SHIFT 0 /**< Shift value for RTC_OF */ #define _RTC_IFS_OF_MASK 0x1UL /**< Bit mask for RTC_OF */ #define _RTC_IFS_OF_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IFS */ #define RTC_IFS_OF_DEFAULT (_RTC_IFS_OF_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_IFS */ #define RTC_IFS_COMP0 (0x1UL << 1) /**< Set Compare match 0 Interrupt Flag */ #define _RTC_IFS_COMP0_SHIFT 1 /**< Shift value for RTC_COMP0 */ #define _RTC_IFS_COMP0_MASK 0x2UL /**< Bit mask for RTC_COMP0 */ #define _RTC_IFS_COMP0_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IFS */ #define RTC_IFS_COMP0_DEFAULT (_RTC_IFS_COMP0_DEFAULT << 1) /**< Shifted mode DEFAULT for RTC_IFS */ #define RTC_IFS_COMP1 (0x1UL << 2) /**< Set Compare match 1 Interrupt Flag */ #define _RTC_IFS_COMP1_SHIFT 2 /**< Shift value for RTC_COMP1 */ #define _RTC_IFS_COMP1_MASK 0x4UL /**< Bit mask for RTC_COMP1 */ #define _RTC_IFS_COMP1_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IFS */ #define RTC_IFS_COMP1_DEFAULT (_RTC_IFS_COMP1_DEFAULT << 2) /**< Shifted mode DEFAULT for RTC_IFS */ /* Bit fields for RTC IFC */ #define _RTC_IFC_RESETVALUE 0x00000000UL /**< Default value for RTC_IFC */ #define _RTC_IFC_MASK 0x00000007UL /**< Mask for RTC_IFC */ #define RTC_IFC_OF (0x1UL << 0) /**< Clear Overflow Interrupt Flag */ #define _RTC_IFC_OF_SHIFT 0 /**< Shift value for RTC_OF */ #define _RTC_IFC_OF_MASK 0x1UL /**< Bit mask for RTC_OF */ #define _RTC_IFC_OF_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IFC */ #define RTC_IFC_OF_DEFAULT (_RTC_IFC_OF_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_IFC */ #define RTC_IFC_COMP0 (0x1UL << 1) /**< Clear Compare match 0 Interrupt Flag */ #define _RTC_IFC_COMP0_SHIFT 1 /**< Shift value for RTC_COMP0 */ #define _RTC_IFC_COMP0_MASK 0x2UL /**< Bit mask for RTC_COMP0 */ #define _RTC_IFC_COMP0_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IFC */ #define RTC_IFC_COMP0_DEFAULT (_RTC_IFC_COMP0_DEFAULT << 1) /**< Shifted mode DEFAULT for RTC_IFC */ #define RTC_IFC_COMP1 (0x1UL << 2) /**< Clear Compare match 1 Interrupt Flag */ #define _RTC_IFC_COMP1_SHIFT 2 /**< Shift value for RTC_COMP1 */ #define _RTC_IFC_COMP1_MASK 0x4UL /**< Bit mask for RTC_COMP1 */ #define _RTC_IFC_COMP1_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IFC */ #define RTC_IFC_COMP1_DEFAULT (_RTC_IFC_COMP1_DEFAULT << 2) /**< Shifted mode DEFAULT for RTC_IFC */ /* Bit fields for RTC IEN */ #define _RTC_IEN_RESETVALUE 0x00000000UL /**< Default value for RTC_IEN */ #define _RTC_IEN_MASK 0x00000007UL /**< Mask for RTC_IEN */ #define RTC_IEN_OF (0x1UL << 0) /**< Overflow Interrupt Enable */ #define _RTC_IEN_OF_SHIFT 0 /**< Shift value for RTC_OF */ #define _RTC_IEN_OF_MASK 0x1UL /**< Bit mask for RTC_OF */ #define _RTC_IEN_OF_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IEN */ #define RTC_IEN_OF_DEFAULT (_RTC_IEN_OF_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_IEN */ #define RTC_IEN_COMP0 (0x1UL << 1) /**< Compare Match 0 Interrupt Enable */ #define _RTC_IEN_COMP0_SHIFT 1 /**< Shift value for RTC_COMP0 */ #define _RTC_IEN_COMP0_MASK 0x2UL /**< Bit mask for RTC_COMP0 */ #define _RTC_IEN_COMP0_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IEN */ #define RTC_IEN_COMP0_DEFAULT (_RTC_IEN_COMP0_DEFAULT << 1) /**< Shifted mode DEFAULT for RTC_IEN */ #define RTC_IEN_COMP1 (0x1UL << 2) /**< Compare Match 1 Interrupt Enable */ #define _RTC_IEN_COMP1_SHIFT 2 /**< Shift value for RTC_COMP1 */ #define _RTC_IEN_COMP1_MASK 0x4UL /**< Bit mask for RTC_COMP1 */ #define _RTC_IEN_COMP1_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_IEN */ #define RTC_IEN_COMP1_DEFAULT (_RTC_IEN_COMP1_DEFAULT << 2) /**< Shifted mode DEFAULT for RTC_IEN */ /* Bit fields for RTC FREEZE */ #define _RTC_FREEZE_RESETVALUE 0x00000000UL /**< Default value for RTC_FREEZE */ #define _RTC_FREEZE_MASK 0x00000001UL /**< Mask for RTC_FREEZE */ #define RTC_FREEZE_REGFREEZE (0x1UL << 0) /**< Register Update Freeze */ #define _RTC_FREEZE_REGFREEZE_SHIFT 0 /**< Shift value for RTC_REGFREEZE */ #define _RTC_FREEZE_REGFREEZE_MASK 0x1UL /**< Bit mask for RTC_REGFREEZE */ #define _RTC_FREEZE_REGFREEZE_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_FREEZE */ #define _RTC_FREEZE_REGFREEZE_UPDATE 0x00000000UL /**< Mode UPDATE for RTC_FREEZE */ #define _RTC_FREEZE_REGFREEZE_FREEZE 0x00000001UL /**< Mode FREEZE for RTC_FREEZE */ #define RTC_FREEZE_REGFREEZE_DEFAULT (_RTC_FREEZE_REGFREEZE_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_FREEZE */ #define RTC_FREEZE_REGFREEZE_UPDATE (_RTC_FREEZE_REGFREEZE_UPDATE << 0) /**< Shifted mode UPDATE for RTC_FREEZE */ #define RTC_FREEZE_REGFREEZE_FREEZE (_RTC_FREEZE_REGFREEZE_FREEZE << 0) /**< Shifted mode FREEZE for RTC_FREEZE */ /* Bit fields for RTC SYNCBUSY */ #define _RTC_SYNCBUSY_RESETVALUE 0x00000000UL /**< Default value for RTC_SYNCBUSY */ #define _RTC_SYNCBUSY_MASK 0x00000007UL /**< Mask for RTC_SYNCBUSY */ #define RTC_SYNCBUSY_CTRL (0x1UL << 0) /**< CTRL Register Busy */ #define _RTC_SYNCBUSY_CTRL_SHIFT 0 /**< Shift value for RTC_CTRL */ #define _RTC_SYNCBUSY_CTRL_MASK 0x1UL /**< Bit mask for RTC_CTRL */ #define _RTC_SYNCBUSY_CTRL_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_SYNCBUSY */ #define RTC_SYNCBUSY_CTRL_DEFAULT (_RTC_SYNCBUSY_CTRL_DEFAULT << 0) /**< Shifted mode DEFAULT for RTC_SYNCBUSY */ #define RTC_SYNCBUSY_COMP0 (0x1UL << 1) /**< COMP0 Register Busy */ #define _RTC_SYNCBUSY_COMP0_SHIFT 1 /**< Shift value for RTC_COMP0 */ #define _RTC_SYNCBUSY_COMP0_MASK 0x2UL /**< Bit mask for RTC_COMP0 */ #define _RTC_SYNCBUSY_COMP0_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_SYNCBUSY */ #define RTC_SYNCBUSY_COMP0_DEFAULT (_RTC_SYNCBUSY_COMP0_DEFAULT << 1) /**< Shifted mode DEFAULT for RTC_SYNCBUSY */ #define RTC_SYNCBUSY_COMP1 (0x1UL << 2) /**< COMP1 Register Busy */ #define _RTC_SYNCBUSY_COMP1_SHIFT 2 /**< Shift value for RTC_COMP1 */ #define _RTC_SYNCBUSY_COMP1_MASK 0x4UL /**< Bit mask for RTC_COMP1 */ #define _RTC_SYNCBUSY_COMP1_DEFAULT 0x00000000UL /**< Mode DEFAULT for RTC_SYNCBUSY */ #define RTC_SYNCBUSY_COMP1_DEFAULT (_RTC_SYNCBUSY_COMP1_DEFAULT << 2) /**< Shifted mode DEFAULT for RTC_SYNCBUSY */ /** @} End of group EFM32LG_RTC */ /** @} End of group Parts */
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once #include "../common/geometry.h" #include "../common/ray.h" #include "../common/hit.h" #include "../common/context.h" namespace embree { namespace isa { __forceinline bool runIntersectionFilter1Helper(RTCFilterFunctionNArguments* args, const Geometry* const geometry, IntersectContext* context) { if (geometry->intersectionFilterN) { assert(context->scene->hasGeometryFilterFunction()); geometry->intersectionFilterN(args); if (args->valid[0] == 0) return false; } if (context->user->filter) { assert(context->scene->hasContextFilterFunction()); context->user->filter(args); if (args->valid[0] == 0) return false; } copyHitToRay(*(RayHit*)args->ray,*(Hit*)args->hit); return true; } __forceinline bool runIntersectionFilter1(const Geometry* const geometry, RayHit& ray, IntersectContext* context, Hit& hit) { RTCFilterFunctionNArguments args; int mask = -1; args.valid = &mask; args.geometryUserPtr = geometry->userPtr; args.context = context->user; args.ray = (RTCRayN*)&ray; args.hit = (RTCHitN*)&hit; args.N = 1; return runIntersectionFilter1Helper(&args,geometry,context); } __forceinline void reportIntersection1(IntersectFunctionNArguments* args, const RTCFilterFunctionNArguments* filter_args) { #if defined(EMBREE_FILTER_FUNCTION) IntersectContext* MAYBE_UNUSED context = args->internal_context; const Geometry* const geometry = args->geometry; if (geometry->intersectionFilterN) { assert(context->scene->hasGeometryFilterFunction()); geometry->intersectionFilterN(filter_args); } //if (args->valid[0] == 0) // return; if (context->user->filter) { assert(context->scene->hasContextFilterFunction()); context->user->filter(filter_args); } #endif } __forceinline bool runOcclusionFilter1Helper(RTCFilterFunctionNArguments* args, const Geometry* const geometry, IntersectContext* context) { if (geometry->occlusionFilterN) { assert(context->scene->hasGeometryFilterFunction()); geometry->occlusionFilterN(args); if (args->valid[0] == 0) return false; } if (context->user->filter) { assert(context->scene->hasContextFilterFunction()); context->user->filter(args); if (args->valid[0] == 0) return false; } return true; } __forceinline bool runOcclusionFilter1(const Geometry* const geometry, Ray& ray, IntersectContext* context, Hit& hit) { RTCFilterFunctionNArguments args; int mask = -1; args.valid = &mask; args.geometryUserPtr = geometry->userPtr; args.context = context->user; args.ray = (RTCRayN*)&ray; args.hit = (RTCHitN*)&hit; args.N = 1; return runOcclusionFilter1Helper(&args,geometry,context); } __forceinline void reportOcclusion1(OccludedFunctionNArguments* args, const RTCFilterFunctionNArguments* filter_args) { #if defined(EMBREE_FILTER_FUNCTION) IntersectContext* MAYBE_UNUSED context = args->internal_context; const Geometry* const geometry = args->geometry; if (geometry->occlusionFilterN) { assert(context->scene->hasGeometryFilterFunction()); geometry->occlusionFilterN(filter_args); } //if (args->valid[0] == 0) // return false; if (context->user->filter) { assert(context->scene->hasContextFilterFunction()); context->user->filter(filter_args); } #endif } template<int K> __forceinline vbool<K> runIntersectionFilterHelper(RTCFilterFunctionNArguments* args, const Geometry* const geometry, IntersectContext* context) { vint<K>* mask = (vint<K>*) args->valid; if (geometry->intersectionFilterN) { assert(context->scene->hasGeometryFilterFunction()); geometry->intersectionFilterN(args); } vbool<K> valid_o = *mask != vint<K>(zero); if (none(valid_o)) return valid_o; if (context->user->filter) { assert(context->scene->hasContextFilterFunction()); context->user->filter(args); } valid_o = *mask != vint<K>(zero); if (none(valid_o)) return valid_o; copyHitToRay(valid_o,*(RayHitK<K>*)args->ray,*(HitK<K>*)args->hit); return valid_o; } template<int K> __forceinline vbool<K> runIntersectionFilter(const vbool<K>& valid, const Geometry* const geometry, RayHitK<K>& ray, IntersectContext* context, HitK<K>& hit) { RTCFilterFunctionNArguments args; vint<K> mask = valid.mask32(); args.valid = (int*)&mask; args.geometryUserPtr = geometry->userPtr; args.context = context->user; args.ray = (RTCRayN*)&ray; args.hit = (RTCHitN*)&hit; args.N = K; return runIntersectionFilterHelper<K>(&args,geometry,context); } template<int K> __forceinline vbool<K> runOcclusionFilterHelper(RTCFilterFunctionNArguments* args, const Geometry* const geometry, IntersectContext* context) { vint<K>* mask = (vint<K>*) args->valid; if (geometry->occlusionFilterN) { assert(context->scene->hasGeometryFilterFunction()); geometry->occlusionFilterN(args); } vbool<K> valid_o = *mask != vint<K>(zero); if (none(valid_o)) return valid_o; if (context->user->filter) { assert(context->scene->hasContextFilterFunction()); context->user->filter(args); } valid_o = *mask != vint<K>(zero); RayK<K>* ray = (RayK<K>*) args->ray; ray->tfar = select(valid_o, vfloat<K>(neg_inf), ray->tfar); return valid_o; } template<int K> __forceinline vbool<K> runOcclusionFilter(const vbool<K>& valid, const Geometry* const geometry, RayK<K>& ray, IntersectContext* context, HitK<K>& hit) { RTCFilterFunctionNArguments args; vint<K> mask = valid.mask32(); args.valid = (int*)&mask; args.geometryUserPtr = geometry->userPtr; args.context = context->user; args.ray = (RTCRayN*)&ray; args.hit = (RTCHitN*)&hit; args.N = K; return runOcclusionFilterHelper<K>(&args,geometry,context); } } }
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join the network together again - verify that getchaintips now returns two chain tips. """ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal class GetChainTipsTest (BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 def run_test(self): tips = self.nodes[0].getchaintips() assert_equal(len(tips), 1) assert_equal(tips[0]['branchlen'], 0) assert_equal(tips[0]['height'], 200) assert_equal(tips[0]['status'], 'active') # Split the network and build two chains of different lengths. self.split_network() self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address) self.nodes[2].generatetoaddress(20, self.nodes[2].get_deterministic_priv_key().address) self.sync_all([self.nodes[:2], self.nodes[2:]]) tips = self.nodes[1].getchaintips () assert_equal (len (tips), 1) shortTip = tips[0] assert_equal (shortTip['branchlen'], 0) assert_equal (shortTip['height'], 210) assert_equal (tips[0]['status'], 'active') tips = self.nodes[3].getchaintips () assert_equal (len (tips), 1) longTip = tips[0] assert_equal (longTip['branchlen'], 0) assert_equal (longTip['height'], 220) assert_equal (tips[0]['status'], 'active') # Join the network halves and check that we now have two tips # (at least at the nodes that previously had the short chain). self.join_network () tips = self.nodes[0].getchaintips () assert_equal (len (tips), 2) assert_equal (tips[0], longTip) assert_equal (tips[1]['branchlen'], 10) assert_equal (tips[1]['status'], 'valid-fork') tips[1]['branchlen'] = 0 tips[1]['status'] = 'active' assert_equal (tips[1], shortTip) if __name__ == '__main__': GetChainTipsTest ().main ()
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http.WinHttpHandlerUnitTests { public class WinHttpRequestStreamTest { public WinHttpRequestStreamTest() { TestControl.ResetAll(); } [Fact] public void CanWrite_WhenCreated_ReturnsTrue() { Stream stream = MakeRequestStream(); bool result = stream.CanWrite; Assert.True(result); } [Fact] public void CanWrite_WhenDisposed_ReturnsFalse() { Stream stream = MakeRequestStream(); stream.Dispose(); bool result = stream.CanWrite; Assert.False(result); } [Fact] public void CanSeek_Always_ReturnsFalse() { Stream stream = MakeRequestStream(); bool result = stream.CanSeek; Assert.False(result); } [Fact] public void CanRead_Always_ReturnsFalse() { Stream stream = MakeRequestStream(); bool result = stream.CanRead; Assert.False(result); } [Fact] public void Length_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Length); } [Fact] public void Length_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Length); } [Fact] public void Position_WhenCreatedDoGet_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Position); } [Fact] public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Position); } [Fact] public void Position_WhenCreatedDoSet_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Position = 0); } [Fact] public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Position = 0); } [Fact] public void Seek_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin)); } [Fact] public void Seek_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin)); } [Fact] public void SetLength_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.SetLength(0)); } [Fact] public void SetLength_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.SetLength(0)); } [Fact] public void Read_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Read(new byte[1], 0, 1)); } [Fact] public void Read_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Read(new byte[1], 0, 1)); } [Fact] public void Write_BufferIsNull_ThrowsArgumentNullException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentNullException>(() => stream.Write(null, 0, 1)); } [Fact] public void Write_OffsetIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[1], -1, 1)); } [Fact] public void Write_CountIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[1], 0, -1)); } [Fact] public void Write_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentException>(() => stream.Write(new byte[1], 0, 3)); } [Fact] public void Write_OffsetPlusCountMaxValueExceedsBufferLength_ThrowsArgumentException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentException>(() => stream.Write(new byte[1], int.MaxValue, int.MaxValue)); } [Fact] public void Write_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Write(new byte[1], 0, 1)); } [Fact] public void Write_NetworkFails_ThrowsIOException() { Stream stream = MakeRequestStream(); TestControl.WinHttpWriteData.ErrorOnCompletion = true; Assert.Throws<IOException>(() => stream.Write(new byte[1], 0, 1)); } [Fact] public void Write_NoOffset_AllDataIsWritten() { Stream stream = MakeRequestStream(); string data = "Test Data"; byte[] buffer = Encoding.ASCII.GetBytes(data); stream.Write(buffer, 0, buffer.Length); byte[] serverBytes = TestServer.RequestBody; Assert.Equal(buffer, serverBytes); } [Fact] public void Write_UsingOffset_DataFromOffsetIsWritten() { Stream stream = MakeRequestStream(); string data = "Test Data"; byte[] buffer = Encoding.ASCII.GetBytes(data); int offset = 5; stream.Write(buffer, offset, buffer.Length - offset); byte[] serverBytes = TestServer.RequestBody; Assert.Equal( new ArraySegment<byte>(buffer, offset, buffer.Length - offset), new ArraySegment<byte>(serverBytes, 0, serverBytes.Length)); } [Fact] public void WriteAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => { Task t = stream.WriteAsync(new byte[1], -1, 1); }); } [Fact] public async Task WriteAsync_NetworkFails_TaskIsFaultedWithIOException() { Stream stream = MakeRequestStream(); TestControl.WinHttpWriteData.ErrorOnCompletion = true; await Assert.ThrowsAsync<IOException>(() => stream.WriteAsync(new byte[1], 0, 1)); } [Fact] public void WriteAsync_TokenIsAlreadyCanceled_TaskIsCanceled() { Stream stream = MakeRequestStream(); var cts = new CancellationTokenSource(); cts.Cancel(); Task t = stream.WriteAsync(new byte[1], 0, 1, cts.Token); Assert.True(t.IsCanceled); } [Fact] public void WtiteAsync_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { Task t = stream.WriteAsync(new byte[1], 0, 1); }); } [Fact] public void WriteAsync_PriorWriteInProgress_ThrowsInvalidOperationException() { Stream stream = MakeRequestStream(); TestControl.WinHttpWriteData.Pause(); Task t1 = stream.WriteAsync(new byte[1], 0, 1); Assert.Throws<InvalidOperationException>(() => { Task t2 = stream.WriteAsync(new byte[1], 0, 1); }); TestControl.WinHttpWriteData.Resume(); t1.Wait(); } internal Stream MakeRequestStream() { var state = new WinHttpRequestState(); var handle = new FakeSafeWinHttpHandle(true); handle.Callback = WinHttpRequestCallback.StaticCallbackDelegate; handle.Context = state.ToIntPtr(); state.RequestHandle = handle; return new WinHttpRequestStream(state, false); } } }
package com.appMobi.appMobiLib; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.SimpleTimeZone; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import com.appMobi.appMobiLib.util.Debug; import android.telephony.TelephonyManager; import android.util.Log; import com.appMobi.appMobiLib.AppMobiActivity.AppInfo; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class AppMobiAnalytics extends AppMobiCommand { private static String deviceKey = null; private static final String OFFLINE = "OFFLINE"; Collection<PageEvent> events; final Object lock; static { initStoredDeviceKey(); } public AppMobiAnalytics(AppMobiActivity activity, AppMobiWebView webview){ super(activity, webview); lock = this; //load events from disk loadEvents(); new Thread("AppMobiAnalytics:constructor") { public void run() { //if there were any saved events, submit them now if( events != null && events.size() > 0 ) { if(lock==null) return; synchronized(lock) { submitEvents(); } } } }.start(); } private void saveEvents() { File eventsFile = new File(activity.baseDir(), "analytics.dat"); String json = null; json = PageEvent.toJSON(events); try { FileWriter writer = new FileWriter(eventsFile); writer.write(json); writer.flush(); writer.close(); } catch (IOException e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } } private void loadEvents() { File eventsFile = new File(activity.baseDir(), "analytics.dat"); if(eventsFile.exists()) { try { FileInputStream fis = new FileInputStream(eventsFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtils.copyInputStream(fis, baos); events = PageEvent.fromJSON(baos.toString()); if (events == null) events = new LinkedList<PageEvent>(); //remove events that are older than 30 days Date now = new Date(); ArrayList<PageEvent> toBeRemoved = new ArrayList<PageEvent>(0); for(PageEvent event:events) { long diff = now.getTime() - event.date.getTime(); if(diff/(1000*60*60*24*30) > 30) { toBeRemoved.add(event); } if(OFFLINE.equals(event.ip)) { event.ip = getIpFromServer(); } } events.removeAll(toBeRemoved); } catch (Exception e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } } else { events = new LinkedList<PageEvent>(); } } public void logPageEvent(String page, String query, String status, String method, String bytes, String userReferer) { if( !webview.config.hasAnalytics ) return; final PageEvent event = new PageEvent(page, query, status, method, bytes, userReferer); new Thread("AppMobiAnalytics:logPageEvent") { public void run() { synchronized(lock) { events.add(event); saveEvents(); submitEvents(); } } }.start(); } private void submitEvents() { if(webview!=null && webview.config != null && webview.config.analyticsUrl!=null && webview.config.analyticsUrl.length()>0) { ArrayList<PageEvent> toBeRemoved = new ArrayList<PageEvent>(0); for(PageEvent event:events) { String url = webview.config.analyticsUrl + "?Action=SendMessage&MessageBody=" + event.getPageString() + "&Version=2009-02-01"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; try { response = httpclient.execute(new HttpGet(url)); } catch (Exception e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } if(response!=null && response.getEntity()!=null) { int responseLength = (int)response.getEntity().getContentLength(); ByteArrayOutputStream baos = new ByteArrayOutputStream(responseLength>0?responseLength:1024); try { FileUtils.copyInputStream(response.getEntity().getContent(), baos); } catch (Exception e) { } if(baos.toString().indexOf("<SendMessageResponse")!=-1) { toBeRemoved.add(event); } } } events.removeAll(toBeRemoved); saveEvents(); } } private static String getIpFromServer() { String ip = null; String url = "http://services.appmobi.com/external/echoip.aspx"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; try { response = httpclient.execute(new HttpGet(url)); } catch (Exception e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } // make sure we get a response and that it is only an IP -- hotel wifi accepting screen bypass if(response!=null && response.getEntity()!=null && response.getEntity().getContentLength()<16) { int responseLength = (int)response.getEntity().getContentLength(); ByteArrayOutputStream baos = new ByteArrayOutputStream(responseLength>0?responseLength:1024); try { FileUtils.copyInputStream(response.getEntity().getContent(), baos); } catch (Exception e) { } String temp = baos.toString(); if(response.getStatusLine().getStatusCode()==200 && temp.length()>0) ip = temp; } return ip==null?OFFLINE:ip; } static String getDeviceKey() { if(deviceKey==null) { initStoredDeviceKey(); } return deviceKey; } private static void initStoredDeviceKey() { final String USER_DATA = "analytics_user_data"; SharedPreferences prefs = AppMobiActivity.sharedActivity.getSharedPreferences(AppInfo.APP_PREFS, Context.MODE_PRIVATE); deviceKey = prefs.getString(USER_DATA, null); if(deviceKey==null) { String deviceid = AppMobiActivity.sharedActivity.getDeviceID(); long timestamp = System.currentTimeMillis(); deviceKey = (deviceid.hashCode() + "." + timestamp).replace(' ', '+'); SharedPreferences.Editor editor = prefs.edit(); editor.putString(USER_DATA, deviceKey); editor.commit(); } } final static class PageEvent { private String page; private String query; private String status; private String method; private String bytes; private Date date; private String dateTime; private String ip; private String userAgent; private String referer; public PageEvent() { super(); } public PageEvent(String page, String query, String status, String method, String bytes, String userReferer) { super(); this.page = page.replace(' ', '+'); this.query = query.replace(' ', '+'); this.status = status.replace(' ', '+'); this.method = method.replace(' ', '+'); this.bytes = bytes.replace(' ', '+'); //format the date for the log SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT")); format.setCalendar(cal); this.date = new Date(); this.dateTime = format.format(this.date); this.ip = getIpFromServer(); this.userAgent = ("Mozilla/5.0+(Linux;+U;+Android+" + Build.VERSION.RELEASE + //osVersion ";+en-us;+" + Build.MODEL + //device name "+Build/FRF91)+AppleWebKit/533.1+(KHTML,+like+Gecko)+Version/4.0+Mobile+Safari/533.1+(" + AppMobiAnalytics.deviceKey + ")").replace(' ', '+'); this.referer = ("http://" + AppMobiActivity.sharedActivity.configData.appName + "-" + AppMobiActivity.sharedActivity.configData.releaseName + "-" + userReferer).replace(' ', '+'); } //check if the ip is valid, if not try to get it again //return the private String getPageString() { if(this.ip == OFFLINE) { this.ip = getIpFromServer(); } String pageStr = URLEncoder.encode( (dateTime + " " + //date/time ip + " " + deviceKey + " " + //ip, userData method + " " + //method page + " " + query + " " + status + " " + //page, query, status bytes + " " + //bytes userAgent + " " + referer) ); if(Debug.isDebuggerConnected()) { Log.d("[appMobi]","logPageEvent ~~ " + pageStr); } return pageStr; } //write to json public static String toJSON(Collection<PageEvent> pageEvents) { String json = new Gson().toJson(pageEvents, new TypeToken<Collection<PageEvent>>(){}.getType()); return json; } //read from JSON public static Collection<PageEvent> fromJSON(String json) { Collection<PageEvent> pageEvents = null; pageEvents = new Gson().fromJson(json, new TypeToken<Collection<PageEvent>>(){}.getType()); return pageEvents; } } }
<?php /* * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace JMS\Serializer; use JMS\Serializer\Metadata\ClassMetadata; use JMS\Serializer\Exception\InvalidArgumentException; use JMS\Serializer\Metadata\PropertyMetadata; abstract class GenericSerializationVisitor extends AbstractVisitor { private $navigator; private $root; private $dataStack; private $data; public function setNavigator(GraphNavigator $navigator) { $this->navigator = $navigator; $this->root = null; $this->dataStack = new \SplStack; } /** * @return GraphNavigator */ public function getNavigator() { return $this->navigator; } public function visitNull($data, array $type, Context $context) { return null; } public function visitString($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (string) $data; } public function visitBoolean($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (boolean) $data; } public function visitInteger($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (int) $data; } public function visitDouble($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (float) $data; } /** * @param array $data * @param array $type */ public function visitArray($data, array $type, Context $context) { if (null === $this->root) { $this->root = array(); $rs = &$this->root; } else { $rs = array(); } foreach ($data as $k => $v) { $v = $this->navigator->accept($v, isset($type['params'][1]) ? $type['params'][1] : null, $context); if (null === $v && (!is_string($k) || !$context->shouldSerializeNull())) { continue; } $rs[$k] = $v; } return $rs; } public function startVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context) { if (null === $this->root) { $this->root = new \stdClass; } $this->dataStack->push($this->data); $this->data = array(); } public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context) { $rs = $this->data; $this->data = $this->dataStack->pop(); if ($this->root instanceof \stdClass && 0 === $this->dataStack->count()) { $this->root = $rs; } return $rs; } public function visitProperty(PropertyMetadata $metadata, $data, Context $context) { $v = $metadata->getValue($data); $v = $this->navigator->accept($v, $metadata->type, $context); if (null === $v && !$context->shouldSerializeNull()) { return; } $k = $this->namingStrategy->translateName($metadata); if ($metadata->inline && is_array($v)) { $this->data = array_merge($this->data, $v); } else { $this->data[$k] = $v; } } /** * Allows you to add additional data to the current object/root element. * * @param string $key * @param scalar|array $value This value must either be a regular scalar, or an array. * It must not contain any objects anymore. */ public function addData($key, $value) { if (isset($this->data[$key])) { throw new InvalidArgumentException(sprintf('There is already data for "%s".', $key)); } $this->data[$key] = $value; } public function getRoot() { return $this->root; } /** * @param array|\ArrayObject $data the passed data must be understood by whatever encoding function is applied later. */ public function setRoot($data) { $this->root = $data; } }
package im.actor.images.ops; import android.graphics.*; import im.actor.images.common.WorkCache; import static im.actor.images.ops.ImageDrawing.*; /** * Scaling images effectively with keeping good quality. * * @author Stepan ex3ndr Korshakov me@ex3ndr.com */ public class ImageScaling { /** * Scaling bitmap to fill rect with centering. Method keep aspect ratio. * * @param src source bitmap * @param w width of result * @param h height of result * @return scaled bitmap */ public static Bitmap scaleFill(Bitmap src, int w, int h) { Bitmap res = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); scaleFill(src, res); return res; } /** * Scaling src bitmap to fill dest bitmap with centering. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap */ public static void scaleFill(Bitmap src, Bitmap dest) { scaleFill(src, dest, CLEAR_COLOR); } /** * Scaling src bitmap to fill dest bitmap with centering. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing */ public static void scaleFill(Bitmap src, Bitmap dest, int clearColor) { float ratio = Math.max(dest.getWidth() / (float) src.getWidth(), dest.getHeight() / (float) src.getHeight()); int newW = (int) (src.getWidth() * ratio); int newH = (int) (src.getHeight() * ratio); int paddingTop = (dest.getHeight() - (int) (src.getHeight() * ratio)) / 2; int paddingLeft = (dest.getWidth() - (int) (src.getWidth() * ratio)) / 2; scale(src, dest, clearColor, 0, 0, src.getWidth(), src.getHeight(), paddingLeft, paddingTop, newW + paddingLeft, newH + paddingTop); } /** * Scaling bitmap to fit required sizes. Method keep aspect ratio. * * @param src source bitmap * @param maxW maximum width of result bitmap * @param maxH maximum height of result bitmap * @return scaled bitmap */ public static Bitmap scaleFit(Bitmap src, int maxW, int maxH) { float ratio = Math.min(maxW / (float) src.getWidth(), maxH / (float) src.getHeight()); int newW = (int) (src.getWidth() * ratio); int newH = (int) (src.getHeight() * ratio); return scale(src, newW, newH); } /** * Scaling src Bitmap to fit and cenetered in dest bitmap. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap */ public static void scaleFit(Bitmap src, Bitmap dest) { scaleFit(src, dest, CLEAR_COLOR); } /** * Scaling src Bitmap to fit and cenetered in dest bitmap. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing */ public static void scaleFit(Bitmap src, Bitmap dest, int clearColor) { float ratio = Math.min(dest.getWidth() / (float) src.getWidth(), dest.getHeight() / (float) src.getHeight()); int newW = (int) (src.getWidth() * ratio); int newH = (int) (src.getHeight() * ratio); int paddingTop = (dest.getHeight() - (int) (src.getHeight() * ratio)) / 2; int paddingLeft = (dest.getWidth() - (int) (src.getWidth() * ratio)) / 2; scale(src, dest, clearColor, 0, 0, src.getWidth(), src.getHeight(), paddingLeft, paddingTop, newW + paddingLeft, newH + paddingTop); } /** * Scaling bitmap to specific width and height without keeping aspect ratio. * * @param src source bitmap * @param dw new width * @param dh new height * @return scaled bitmap */ public static Bitmap scale(Bitmap src, int dw, int dh) { Bitmap res = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888); scale(src, res); return res; } /** * Scaling bitmap to fill dest bitmap without keeping aspect ratio. * * @param src source bitmap * @param dest destination bitmap */ public static void scale(Bitmap src, Bitmap dest) { scale(src, dest, CLEAR_COLOR); } /** * Scaling bitmap to fill dest bitmap without keeping aspect ratio. * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing */ public static void scale(Bitmap src, Bitmap dest, int clearColor) { scale(src, dest, clearColor, 0, 0, src.getWidth(), src.getHeight(), 0, 0, dest.getWidth(), dest.getHeight()); } /** * Scaling region of bitmap to destination bitmap region * * @param src source bitmap * @param dest destination bitmap * @param x source x * @param y source y * @param sw source width * @param sh source height * @param dx destination x * @param dy destination y * @param dw destination width * @param dh destination height */ public static void scale(Bitmap src, Bitmap dest, int x, int y, int sw, int sh, int dx, int dy, int dw, int dh) { scale(src, dest, CLEAR_COLOR, x, y, sw, sh, dx, dy, dw, dh); } /** * Scaling region of bitmap to destination bitmap region * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing * @param x source x * @param y source y * @param sw source width * @param sh source height * @param dx destination x * @param dy destination y * @param dw destination width * @param dh destination height */ public static void scale(Bitmap src, Bitmap dest, int clearColor, int x, int y, int sw, int sh, int dx, int dy, int dw, int dh) { clearBitmap(dest, clearColor); Canvas canvas = new Canvas(dest); Paint paint = WorkCache.PAINT.get(); paint.setFilterBitmap(true); canvas.drawBitmap(src, new Rect(x + 1, y + 1, sw - 1, sh - 1), new Rect(dx, dy, dw, dh), paint); canvas.setBitmap(null); } protected ImageScaling() { } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\ResourceBundle\Controller; use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandler as RestViewHandler; use JMS\Serializer\SerializationContext; use PhpSpec\ObjectBehavior; use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration; use Sylius\Bundle\ResourceBundle\Controller\ViewHandler; use Sylius\Bundle\ResourceBundle\Controller\ViewHandlerInterface; use Symfony\Component\HttpFoundation\Response; /** * @mixin ViewHandler * * @author Paweł Jędrzejewski <pawel@sylius.org> */ class ViewHandlerSpec extends ObjectBehavior { function let(RestViewHandler $restViewHandler) { $this->beConstructedWith($restViewHandler); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\ResourceBundle\Controller\ViewHandler'); } function it_implements_view_handler_interface() { $this->shouldImplement(ViewHandlerInterface::class); } function it_handles_view_normally_for_html_requests( RequestConfiguration $requestConfiguration, RestViewHandler $restViewHandler, Response $response ) { $requestConfiguration->isHtmlRequest()->willReturn(true); $view = View::create(); $restViewHandler->handle($view)->willReturn($response); $this->handle($requestConfiguration, $view)->shouldReturn($response); } function it_sets_proper_values_for_non_html_requests( RequestConfiguration $requestConfiguration, RestViewHandler $restViewHandler, Response $response ) { $requestConfiguration->isHtmlRequest()->willReturn(false); $view = View::create(); $view->setSerializationContext(new SerializationContext()); $requestConfiguration->getSerializationGroups()->willReturn(['Detailed']); $requestConfiguration->getSerializationVersion()->willReturn('2.0.0'); $restViewHandler->setExclusionStrategyGroups(['Detailed'])->shouldBeCalled(); $restViewHandler->setExclusionStrategyVersion('2.0.0')->shouldBeCalled(); $restViewHandler->handle($view)->willReturn($response); $this->handle($requestConfiguration, $view)->shouldReturn($response); } }
/* libs/graphics/animator/SkDisplayType.h ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #ifndef SkDisplayType_DEFINED #define SkDisplayType_DEFINED #include "SkMath.h" #include "SkScalar.h" #ifdef SK_DEBUG #ifdef SK_CAN_USE_FLOAT #define SK_DUMP_ENABLED #endif #ifdef SK_BUILD_FOR_MAC #define SK_FIND_LEAKS #endif #endif #define SK_LITERAL_STR_EQUAL(str, token, len) (sizeof(str) - 1 == len \ && strncmp(str, token, sizeof(str) - 1) == 0) class SkAnimateMaker; class SkDisplayable; struct SkMemberInfo; enum SkDisplayTypes { SkType_Unknown, SkType_Math, // for ecmascript compatible Math functions and constants SkType_Number, // for for ecmascript compatible Number functions and constants SkType_Add, SkType_AddCircle, SkType_AddGeom, SkType_AddMode, SkType_AddOval, SkType_AddPath, SkType_AddRect, // path part SkType_AddRoundRect, SkType_Align, SkType_Animate, SkType_AnimateBase, // base type for animate, set SkType_Apply, SkType_ApplyMode, SkType_ApplyTransition, SkType_Array, SkType_ARGB, SkType_Base64, SkType_BaseBitmap, SkType_BaseClassInfo, SkType_Bitmap, SkType_BitmapEncoding, SkType_BitmapFormat, SkType_BitmapShader, SkType_Blur, SkType_Boolean, // can have values -1 (uninitialized), 0, 1 SkType_Boundable, SkType_Bounds, SkType_Cap, SkType_Clear, SkType_Clip, SkType_Close, SkType_Color, SkType_CubicTo, SkType_Dash, SkType_DataInput, SkType_Discrete, SkType_Displayable, SkType_Drawable, SkType_DrawTo, SkType_Dump, SkType_DynamicString, // evaluate at draw time SkType_Emboss, SkType_Event, SkType_EventCode, SkType_EventKind, SkType_EventMode, SkType_FillType, SkType_FilterType, SkType_Float, SkType_FontStyle, SkType_FromPath, SkType_FromPathMode, SkType_Full, SkType_Gradient, SkType_Group, SkType_HitClear, SkType_HitTest, SkType_Image, SkType_Include, SkType_Input, SkType_Int, SkType_Join, SkType_Line, // simple line primitive SkType_LineTo, // used as part of path construction SkType_LinearGradient, SkType_MaskFilter, SkType_MaskFilterBlurStyle, SkType_MaskFilterLight, SkType_Matrix, SkType_MemberFunction, SkType_MemberProperty, SkType_Move, SkType_MoveTo, SkType_Movie, SkType_MSec, SkType_Oval, SkType_Paint, SkType_Path, SkType_PathDirection, SkType_PathEffect, SkType_Point, // used inside other structures, no vtable SkType_DrawPoint, // used to draw points, has a vtable SkType_PolyToPoly, SkType_Polygon, SkType_Polyline, SkType_Post, SkType_QuadTo, SkType_RCubicTo, SkType_RLineTo, SkType_RMoveTo, SkType_RQuadTo, SkType_RadialGradient, SkType_Random, SkType_Rect, SkType_RectToRect, SkType_Remove, SkType_Replace, SkType_Rotate, SkType_RoundRect, SkType_Save, SkType_SaveLayer, SkType_Scale, SkType_Screenplay, SkType_Set, SkType_Shader, SkType_Skew, SkType_3D_Camera, SkType_3D_Patch, SkType_3D_Point, SkType_Snapshot, SkType_String, // pointer to SkString SkType_Style, SkType_Text, SkType_TextBox, SkType_TextBoxAlign, SkType_TextBoxMode, SkType_TextOnPath, SkType_TextToPath, SkType_TileMode, SkType_Translate, SkType_TransparentShader, SkType_Typeface, SkType_Xfermode, kNumberOfTypes }; struct TypeNames { const char* fName; SkDisplayTypes fType; #if defined SK_DEBUG || defined SK_BUILD_CONDENSED bool fDrawPrefix; bool fDisplayPrefix; #endif }; #ifdef SK_DEBUG typedef SkDisplayTypes SkFunctionParamType; #else typedef unsigned char SkFunctionParamType; #endif extern const TypeNames gTypeNames[]; extern const int kTypeNamesSize; class SkDisplayType { public: static SkDisplayTypes Find(SkAnimateMaker* , const SkMemberInfo* ); static const SkMemberInfo* GetMember(SkAnimateMaker* , SkDisplayTypes , const char** ); static const SkMemberInfo* GetMembers(SkAnimateMaker* , SkDisplayTypes , int* infoCountPtr); static SkDisplayTypes GetParent(SkAnimateMaker* , SkDisplayTypes ); static bool IsDisplayable(SkAnimateMaker* , SkDisplayTypes ); static bool IsEnum(SkAnimateMaker* , SkDisplayTypes ); static bool IsStruct(SkAnimateMaker* , SkDisplayTypes ); static SkDisplayTypes RegisterNewType(); static SkDisplayTypes Resolve(const char[] , const SkMemberInfo** ); #ifdef SK_DEBUG static bool IsAnimate(SkDisplayTypes type ) { return type == SkType_Animate || type == SkType_Set; } static const char* GetName(SkAnimateMaker* , SkDisplayTypes ); #endif #ifdef SK_SUPPORT_UNITTEST static void UnitTest(); #endif #if defined SK_DEBUG || defined SK_BUILD_CONDENSED static void BuildCondensedInfo(SkAnimateMaker* ); #endif static SkDisplayTypes GetType(SkAnimateMaker* , const char[] , size_t len); static SkDisplayable* CreateInstance(SkAnimateMaker* , SkDisplayTypes ); private: static SkDisplayTypes gNewTypes; }; #endif // SkDisplayType_DEFINED
import unittest import time from datetime import datetime from app import create_app, db from app.models import User, AnonymousUser, Role, Permission class UserModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Role.insert_roles() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_password_setter(self): u = User(password='cat') self.assertTrue(u.password_hash is not None) def test_no_password_getter(self): u = User(password='cat') with self.assertRaises(AttributeError): u.password def test_password_verification(self): u = User(password='cat') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog')) def test_password_salts_are_random(self): u = User(password='cat') u2 = User(password='cat') self.assertTrue(u.password_hash != u2.password_hash) def test_valid_confirmation_token(self): u = User(password='cat') db.session.add(u) db.session.commit() token = u.generate_confirmation_token() self.assertTrue(u.confirm(token)) def test_invalid_confirmation_token(self): u1 = User(password='cat') u2 = User(password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_confirmation_token() self.assertFalse(u2.confirm(token)) def test_expired_confirmation_token(self): u = User(password='cat') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token)) def test_valid_reset_token(self): u = User(password='cat') db.session.add(u) db.session.commit() token = u.generate_reset_token() self.assertTrue(u.reset_password(token, 'dog')) self.assertTrue(u.verify_password('dog')) def test_invalid_reset_token(self): u1 = User(password='cat') u2 = User(password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_reset_token() self.assertFalse(u2.reset_password(token, 'horse')) self.assertTrue(u2.verify_password('dog')) def test_valid_email_change_token(self): u = User(email='john@example.com', password='cat') db.session.add(u) db.session.commit() token = u.generate_email_change_token('susan@example.org') self.assertTrue(u.change_email(token)) self.assertTrue(u.email == 'susan@example.org') def test_invalid_email_change_token(self): u1 = User(email='john@example.com', password='cat') u2 = User(email='susan@example.org', password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_email_change_token('david@example.net') self.assertFalse(u2.change_email(token)) self.assertTrue(u2.email == 'susan@example.org') def test_duplicate_email_change_token(self): u1 = User(email='john@example.com', password='cat') u2 = User(email='susan@example.org', password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u2.generate_email_change_token('john@example.com') self.assertFalse(u2.change_email(token)) self.assertTrue(u2.email == 'susan@example.org') def test_roles_and_permissions(self): u = User(email='john@example.com', password='cat') self.assertTrue(u.can(Permission.WRITE_ARTICLES)) self.assertFalse(u.can(Permission.MODERATE_COMMENTS)) def test_anonymous_user(self): u = AnonymousUser() self.assertFalse(u.can(Permission.FOLLOW)) def test_timestamps(self): u = User(password='cat') db.session.add(u) db.session.commit() self.assertTrue( (datetime.utcnow() - u.member_since).total_seconds() < 3) self.assertTrue( (datetime.utcnow() - u.last_seen).total_seconds() < 3) def test_ping(self): u = User(password='cat') db.session.add(u) db.session.commit() time.sleep(2) last_seen_before = u.last_seen u.ping() self.assertTrue(u.last_seen > last_seen_before) def test_gravatar(self): u = User(email='john@example.com', password='cat') with self.app.test_request_context('/'): gravatar = u.gravatar() gravatar_256 = u.gravatar(size=256) gravatar_pg = u.gravatar(rating='pg') gravatar_retro = u.gravatar(default='retro') with self.app.test_request_context('/', base_url='https://example.com'): gravatar_ssl = u.gravatar() self.assertTrue('http://www.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6'in gravatar) self.assertTrue('s=256' in gravatar_256) self.assertTrue('r=pg' in gravatar_pg) self.assertTrue('d=retro' in gravatar_retro) self.assertTrue('https://secure.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6' in gravatar_ssl)
# # Makefile for the HISILICON network device drivers. # obj-$(CONFIG_HIX5HD2_GMAC) += hix5hd2_gmac.o obj-$(CONFIG_HIP04_ETH) += hip04_eth.o obj-$(CONFIG_HNS_MDIO) += hns_mdio.o obj-$(CONFIG_HNS) += hns/ obj-$(CONFIG_HNS3) += hns3/ obj-$(CONFIG_HISI_FEMAC) += hisi_femac.o
obj-y := setup.o io.o
#!/usr/bin/perl # Copyright © 2011 Rafaël Carré <funman at videolanorg> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. # use warnings; if ($#ARGV != 0) { die "Need exactly one argument"; } open F, "+<$ARGV[0]" or die "Can't open `$ARGV[0]'"; binmode F; seek F, 0x3c, 0; my $offset = get_le(4); seek F, $offset, 0; if (get_le(4) != 0x00004550) { # IMAGE_NT_SIGNATURE die "Not a NT executable"; } seek F, 20 + 70, 1; my $flags = get_le(2); seek F, -2, 1; $flags |= 0x100; # NX Compat $flags |= 0x40; # Dynamic Base printf F "%c%c", $flags & 0xff,($flags >> 8) & 0xff; close F; sub get_le { my $bytes; read F, $bytes, $_[0]; if (length $bytes ne $_[0]) { die "Couldn't read"; } my $ret = 0; my @array = split //, $bytes; for (my $shift = 0, my $i = 0; $i < $_[0]; $i++, $shift += 8) { $ret += (ord $array[$i]) << $shift; } return $ret; }
/* * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_CI_CISIGNATURE_HPP #define SHARE_VM_CI_CISIGNATURE_HPP #include "ci/ciClassList.hpp" #include "ci/ciSymbol.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/growableArray.hpp" // ciSignature // // This class represents the signature of a method. class ciSignature : public ResourceObj { private: ciSymbol* _symbol; ciKlass* _accessing_klass; GrowableArray<ciType*>* _types; int _size; // number of stack slots required for arguments int _count; // number of parameter types in the signature friend class ciMethod; friend class ciBytecodeStream; friend class ciObjectFactory; ciSignature(ciKlass* accessing_klass, constantPoolHandle cpool, ciSymbol* signature); ciSignature(ciKlass* accessing_klass, ciSymbol* signature, ciMethodType* method_type); void get_all_klasses(); Symbol* get_symbol() const { return _symbol->get_symbol(); } public: ciSymbol* as_symbol() const { return _symbol; } ciKlass* accessing_klass() const { return _accessing_klass; } ciType* return_type() const; ciType* type_at(int index) const; int size() const { return _size; } int count() const { return _count; } int arg_size_for_bc(Bytecodes::Code bc) { return size() + (Bytecodes::has_receiver(bc) ? 1 : 0); } bool equals(ciSignature* that); void print_signature(); void print(); }; #endif // SHARE_VM_CI_CISIGNATURE_HPP
#ifndef _VKMS_DRV_H_ #define _VKMS_DRV_H_ #include <drm/drmP.h> #include <drm/drm.h> #include <drm/drm_gem.h> #include <drm/drm_encoder.h> #include <linux/hrtimer.h> #define XRES_MIN 20 #define YRES_MIN 20 #define XRES_DEF 1024 #define YRES_DEF 768 #define XRES_MAX 8192 #define YRES_MAX 8192 extern bool enable_cursor; static const u32 vkms_formats[] = { DRM_FORMAT_XRGB8888, }; static const u32 vkms_cursor_formats[] = { DRM_FORMAT_ARGB8888, }; struct vkms_crc_data { struct drm_framebuffer fb; struct drm_rect src, dst; unsigned int offset; unsigned int pitch; unsigned int cpp; }; /** * vkms_plane_state - Driver specific plane state * @base: base plane state * @crc_data: data required for CRC computation */ struct vkms_plane_state { struct drm_plane_state base; struct vkms_crc_data *crc_data; }; /** * vkms_crtc_state - Driver specific CRTC state * @base: base CRTC state * @crc_work: work struct to compute and add CRC entries * @n_frame_start: start frame number for computed CRC * @n_frame_end: end frame number for computed CRC */ struct vkms_crtc_state { struct drm_crtc_state base; struct work_struct crc_work; u64 frame_start; u64 frame_end; }; struct vkms_output { struct drm_crtc crtc; struct drm_encoder encoder; struct drm_connector connector; struct hrtimer vblank_hrtimer; ktime_t period_ns; struct drm_pending_vblank_event *event; bool crc_enabled; /* ordered wq for crc_work */ struct workqueue_struct *crc_workq; /* protects concurrent access to crc_data */ spinlock_t lock; /* protects concurrent access to crtc_state */ spinlock_t state_lock; }; struct vkms_device { struct drm_device drm; struct platform_device *platform; struct vkms_output output; }; struct vkms_gem_object { struct drm_gem_object gem; struct mutex pages_lock; /* Page lock used in page fault handler */ struct page **pages; unsigned int vmap_count; void *vaddr; }; #define drm_crtc_to_vkms_output(target) \ container_of(target, struct vkms_output, crtc) #define drm_device_to_vkms_device(target) \ container_of(target, struct vkms_device, drm) #define drm_gem_to_vkms_gem(target)\ container_of(target, struct vkms_gem_object, gem) #define to_vkms_crtc_state(target)\ container_of(target, struct vkms_crtc_state, base) #define to_vkms_plane_state(target)\ container_of(target, struct vkms_plane_state, base) /* CRTC */ int vkms_crtc_init(struct drm_device *dev, struct drm_crtc *crtc, struct drm_plane *primary, struct drm_plane *cursor); bool vkms_get_vblank_timestamp(struct drm_device *dev, unsigned int pipe, int *max_error, ktime_t *vblank_time, bool in_vblank_irq); int vkms_output_init(struct vkms_device *vkmsdev); struct drm_plane *vkms_plane_init(struct vkms_device *vkmsdev, enum drm_plane_type type); /* Gem stuff */ struct drm_gem_object *vkms_gem_create(struct drm_device *dev, struct drm_file *file, u32 *handle, u64 size); vm_fault_t vkms_gem_fault(struct vm_fault *vmf); int vkms_dumb_create(struct drm_file *file, struct drm_device *dev, struct drm_mode_create_dumb *args); void vkms_gem_free_object(struct drm_gem_object *obj); int vkms_gem_vmap(struct drm_gem_object *obj); void vkms_gem_vunmap(struct drm_gem_object *obj); /* CRC Support */ int vkms_set_crc_source(struct drm_crtc *crtc, const char *src_name); int vkms_verify_crc_source(struct drm_crtc *crtc, const char *source_name, size_t *values_cnt); void vkms_crc_work_handle(struct work_struct *work); #endif /* _VKMS_DRV_H_ */
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.vm.ci.code; /** * Exception thrown by the runtime in case an invalidated machine code is called. */ public final class InvalidInstalledCodeException extends Exception { private static final long serialVersionUID = -3540232440794244844L; }
/* /linux/drivers/misc/modem_if/modem_modemctl_device_mdm6600.c * * Copyright (C) 2010 Google, Inc. * Copyright (C) 2010 Samsung Electronics. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/init.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/platform_device.h> #include <linux/platform_data/modem.h> #include "modem_prj.h" #include <linux/regulator/consumer.h> #include <plat/gpio-cfg.h> #if defined(CONFIG_MACH_M0_CTC) #include <linux/mfd/max77693.h> #endif #if defined(CONFIG_MACH_U1_KOR_LGT) #include <linux/mfd/max8997.h> static int mdm6600_on(struct modem_ctl *mc) { pr_info("[MODEM_IF] mdm6600_on()\n"); if (!mc->gpio_cp_reset || !mc->gpio_cp_reset_msm || !mc->gpio_cp_on) { pr_err("[MODEM_IF] no gpio data\n"); return -ENXIO; } gpio_set_value(mc->gpio_pda_active, 0); gpio_set_value(mc->gpio_cp_reset, 1); gpio_set_value(mc->gpio_cp_reset_msm, 1); msleep(30); gpio_set_value(mc->gpio_cp_on, 1); msleep(300); gpio_set_value(mc->gpio_cp_on, 0); msleep(500); gpio_set_value(mc->gpio_pda_active, 1); mc->iod->modem_state_changed(mc->iod, STATE_BOOTING); return 0; } static int mdm6600_off(struct modem_ctl *mc) { pr_info("[MODEM_IF] mdm6600_off()\n"); if (!mc->gpio_cp_reset || !mc->gpio_cp_reset_msm || !mc->gpio_cp_on) { pr_err("[MODEM_IF] no gpio data\n"); return -ENXIO; } gpio_set_value(mc->gpio_cp_on, 0); gpio_set_value(mc->gpio_cp_reset, 0); gpio_set_value(mc->gpio_cp_reset_msm, 0); mc->iod->modem_state_changed(mc->iod, STATE_OFFLINE); return 0; } static int mdm6600_reset(struct modem_ctl *mc) { int ret; pr_info("[MODEM_IF] mdm6600_reset()\n"); if (!mc->gpio_cp_reset || !mc->gpio_cp_reset_msm || !mc->gpio_cp_on) { pr_err("[MODEM_IF] no gpio data\n"); return -ENXIO; } if (system_rev >= 0x05) { dev_err(mc->dev, "[%s] system_rev: %d\n", __func__, system_rev); gpio_set_value(mc->gpio_cp_reset_msm, 0); msleep(100); /* no spec, confirm later exactly how much time needed to initialize CP with RESET_PMU_N */ gpio_set_value(mc->gpio_cp_reset_msm, 1); msleep(40); /* > 37.2 + 2 msec */ } else { dev_err(mc->dev, "[%s] system_rev: %d\n", __func__, system_rev); gpio_set_value(mc->gpio_cp_reset, 0); msleep(500); /* no spec, confirm later exactly how much time needed to initialize CP with RESET_PMU_N */ gpio_set_value(mc->gpio_cp_reset, 1); msleep(40); /* > 37.2 + 2 msec */ } return 0; } static int mdm6600_boot_on(struct modem_ctl *mc) { pr_info("[MODEM_IF] mdm6600_boot_on()\n"); if (!mc->gpio_boot_sw_sel) { pr_err("[MODEM_IF] no gpio data\n"); return -ENXIO; } if (mc->vbus_on) mc->vbus_on(); if (mc->gpio_boot_sw_sel) gpio_set_value(mc->gpio_boot_sw_sel, 0); mc->usb_boot = true; return 0; } static int mdm6600_boot_off(struct modem_ctl *mc) { pr_info("[MODEM_IF] mdm6600_boot_off()\n"); if (!mc->gpio_boot_sw_sel) { pr_err("[MODEM_IF] no gpio data\n"); return -ENXIO; } if (mc->vbus_off) mc->vbus_off(); if (mc->gpio_boot_sw_sel) gpio_set_value(mc->gpio_boot_sw_sel, 1); mc->usb_boot = false; return 0; } static int count; static irqreturn_t phone_active_irq_handler(int irq, void *_mc) { int phone_reset = 0; int phone_active_value = 0; int cp_dump_value = 0; int phone_state = 0; struct modem_ctl *mc = (struct modem_ctl *)_mc; if (!mc->gpio_cp_reset || !mc->gpio_phone_active /*|| !mc->gpio_cp_dump_int */) { pr_err("[MODEM_IF] no gpio data\n"); return IRQ_HANDLED; } phone_reset = gpio_get_value(mc->gpio_cp_reset); phone_active_value = gpio_get_value(mc->gpio_phone_active); pr_info("[MODEM_IF] PA EVENT : reset =%d, pa=%d, cp_dump=%d\n", phone_reset, phone_active_value, cp_dump_value); if (phone_reset && phone_active_value) { phone_state = STATE_ONLINE; if (mc->iod && mc->iod->modem_state_changed) mc->iod->modem_state_changed(mc->iod, phone_state); } else if (phone_reset && !phone_active_value) { if (count == 1) { phone_state = STATE_CRASH_EXIT; if (mc->iod) { ld = get_current_link(mc->iod); if (ld->terminate_comm) ld->terminate_comm(ld, mc->iod); } if (mc->iod && mc->iod->modem_state_changed) mc->iod->modem_state_changed (mc->iod, phone_state); count = 0; } else { count++; } } else { phone_state = STATE_OFFLINE; if (mc->iod && mc->iod->modem_state_changed) mc->iod->modem_state_changed(mc->iod, phone_state); } pr_info("phone_active_irq_handler : phone_state=%d\n", phone_state); return IRQ_HANDLED; } static void mdm6600_get_ops(struct modem_ctl *mc) { mc->ops.modem_on = mdm6600_on; mc->ops.modem_off = mdm6600_off; mc->ops.modem_reset = mdm6600_reset; mc->ops.modem_boot_on = mdm6600_boot_on; mc->ops.modem_boot_off = mdm6600_boot_off; } int mdm6600_init_modemctl_device(struct modem_ctl *mc, struct modem_data *pdata) { int ret; struct platform_device *pdev; mc->gpio_cp_on = pdata->gpio_cp_on; mc->gpio_cp_reset = pdata->gpio_cp_reset; mc->gpio_pda_active = pdata->gpio_pda_active; mc->gpio_phone_active = pdata->gpio_phone_active; mc->gpio_cp_reset_msm = pdata->gpio_cp_reset_msm; mc->gpio_boot_sw_sel = pdata->gpio_boot_sw_sel; mc->vbus_on = pdata->vbus_on; mc->vbus_off = pdata->vbus_off; pdev = to_platform_device(mc->dev); mc->irq_phone_active = platform_get_irq_byname(pdev, "cp_active_irq"); pr_info("[MODEM_IF] <%s> PHONE_ACTIVE IRQ# = %d\n", __func__, mc->irq_phone_active); mdm6600_get_ops(mc); ret = request_irq(mc->irq_phone_active, phone_active_irq_handler, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "phone_active", mc); if (ret) { pr_err("[MODEM_IF] %s: failed to request_irq:%d\n", __func__, ret); goto err_request_irq; } ret = enable_irq_wake(mc->irq_phone_active); if (ret) { pr_err("[MODEM_IF] %s: failed to enable_irq_wake:%d\n", __func__, ret); goto err_set_wake_irq; } return ret; err_set_wake_irq: free_irq(mc->irq_phone_active, mc); err_request_irq: return ret; } #endif /* CONFIG_MACH_U1_KOR_LGT */ #if defined(CONFIG_MACH_C1CTC) || defined(CONFIG_MACH_M0_CTC) #include "modem_link_device_dpram.h" #define PIF_TIMEOUT (180 * HZ) #define DPRAM_INIT_TIMEOUT (30 * HZ) static int mdm6600_on(struct modem_ctl *mc) { pr_info("[MSM] <%s>\n", __func__); if (!mc->gpio_reset_req_n || !mc->gpio_cp_reset || !mc->gpio_cp_on || !mc->gpio_pda_active) { pr_err("[MSM] no gpio data\n"); return -ENXIO; } gpio_set_value(mc->gpio_reset_req_n, 1); gpio_set_value(mc->gpio_cp_reset, 1); msleep(30); gpio_set_value(mc->gpio_cp_on, 1); msleep(500); gpio_set_value(mc->gpio_cp_on, 0); msleep(500); gpio_set_value(mc->gpio_pda_active, 1); mc->iod->modem_state_changed(mc->iod, STATE_BOOTING); return 0; } static int mdm6600_off(struct modem_ctl *mc) { pr_info("[MSM] <%s>\n", __func__); if (!mc->gpio_cp_reset || !mc->gpio_cp_on) { pr_err("[MSM] no gpio data\n"); return -ENXIO; } gpio_set_value(mc->gpio_cp_reset, 0); gpio_set_value(mc->gpio_cp_on, 0); mc->iod->modem_state_changed(mc->iod, STATE_OFFLINE); return 0; } static int mdm6600_reset(struct modem_ctl *mc) { int ret = 0; pr_info("[MSM] <%s>\n", __func__); ret = mdm6600_off(mc); if (ret) return -ENXIO; #if 0 msleep(100); #endif ret = mdm6600_on(mc); if (ret) return -ENXIO; return 0; } static int mdm6600_boot_on(struct modem_ctl *mc) { pr_info("[MSM] <%s>\n", __func__); if (!mc->gpio_flm_uart_sel) { pr_err("[MSM] no gpio data\n"); return -ENXIO; } pr_info("[MSM] <%s> %s\n", __func__, "USB_BOOT_EN initializing"); if (system_rev < 11) { gpio_direction_output(GPIO_USB_BOOT_EN, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN, 0); gpio_direction_output(GPIO_USB_BOOT_EN, 1); gpio_set_value(GPIO_USB_BOOT_EN, 1); pr_info("[MSM] <%s> USB_BOOT_EN:[%d]\n", __func__, gpio_get_value(GPIO_USB_BOOT_EN)); } else if (system_rev == 11) { gpio_direction_output(GPIO_USB_BOOT_EN, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN, 0); gpio_direction_output(GPIO_USB_BOOT_EN, 1); gpio_set_value(GPIO_USB_BOOT_EN, 1); pr_info("[MSM] <%s> USB_BOOT_EN:[%d]\n", __func__, gpio_get_value(GPIO_USB_BOOT_EN)); gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 0); gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 1); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 1); pr_info("[MSM] <%s> USB_BOOT_EN:[%d]\n", __func__, gpio_get_value(GPIO_USB_BOOT_EN_REV06)); } else { /* system_rev>11 */ gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 0); gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 1); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 1); pr_info("[MSM] <%s> USB_BOOT_EN:[%d]\n", __func__, gpio_get_value(GPIO_USB_BOOT_EN_REV06)); } gpio_direction_output(mc->gpio_flm_uart_sel, 0); s3c_gpio_setpull(mc->gpio_flm_uart_sel, S3C_GPIO_PULL_NONE); gpio_set_value(mc->gpio_flm_uart_sel, 0); gpio_direction_output(mc->gpio_flm_uart_sel, 1); gpio_set_value(mc->gpio_flm_uart_sel, 1); pr_info("[MSM] <%s> BOOT_SW_SEL : [%d]\n", __func__, gpio_get_value(mc->gpio_flm_uart_sel)); mc->iod->modem_state_changed(mc->iod, STATE_BOOTING); return 0; } static int mdm6600_boot_off(struct modem_ctl *mc) { pr_info("[MSM] <%s>\n", __func__); if (!mc->gpio_flm_uart_sel || !mc->gpio_flm_uart_sel_rev06) { pr_err("[MSM] no gpio data\n"); return -ENXIO; } if (system_rev < 11) { gpio_direction_output(GPIO_USB_BOOT_EN, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN, 0); gpio_direction_output(GPIO_BOOT_SW_SEL, 0); s3c_gpio_setpull(GPIO_BOOT_SW_SEL, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_BOOT_SW_SEL, 0); } else if (system_rev == 11) { gpio_direction_output(GPIO_USB_BOOT_EN, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN, 0); gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 0); gpio_direction_output(GPIO_BOOT_SW_SEL, 0); s3c_gpio_setpull(GPIO_BOOT_SW_SEL, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_BOOT_SW_SEL, 0); gpio_direction_output(GPIO_BOOT_SW_SEL_REV06, 0); s3c_gpio_setpull(GPIO_BOOT_SW_SEL_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_BOOT_SW_SEL_REV06, 0); } else { /* system_rev>11 */ gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 0); s3c_gpio_setpull(GPIO_USB_BOOT_EN_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 0); gpio_direction_output(GPIO_BOOT_SW_SEL_REV06, 0); s3c_gpio_setpull(GPIO_BOOT_SW_SEL_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_BOOT_SW_SEL_REV06, 0); } if (max7693_muic_cp_usb_state()) { msleep(30); gpio_direction_output(GPIO_USB_BOOT_EN, 1); s3c_gpio_setpull(GPIO_USB_BOOT_EN, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN, 1); gpio_direction_output(GPIO_USB_BOOT_EN_REV06, 1); s3c_gpio_setpull(GPIO_USB_BOOT_EN_REV06, S3C_GPIO_PULL_NONE); gpio_set_value(GPIO_USB_BOOT_EN_REV06, 1); } gpio_set_value(mc->gpio_flm_uart_sel, 0); return 0; } static irqreturn_t phone_active_irq_handler(int irq, void *arg) { struct modem_ctl *mc = (struct modem_ctl *)arg; int phone_reset = 0; int phone_active = 0; int phone_state = 0; if (!mc->gpio_cp_reset || !mc->gpio_phone_active) { pr_err("[MSM] no gpio data\n"); return IRQ_HANDLED; } phone_reset = gpio_get_value(mc->gpio_cp_reset); phone_active = gpio_get_value(mc->gpio_phone_active); pr_info("[MSM] <%s> phone_reset = %d, phone_active = %d\n", __func__, phone_reset, phone_active); if (phone_reset && phone_active) { phone_state = STATE_ONLINE; if (mc->iod && mc->iod->modem_state_changed) mc->iod->modem_state_changed(mc->iod, phone_state); } else if (phone_reset && !phone_active) { if (mc->phone_state == STATE_ONLINE) { phone_state = STATE_CRASH_EXIT; if (mc->iod && mc->iod->modem_state_changed) mc->iod->modem_state_changed(mc->iod, phone_state); } } else { phone_state = STATE_OFFLINE; if (mc->iod && mc->iod->modem_state_changed) mc->iod->modem_state_changed(mc->iod, phone_state); } if (phone_active) irq_set_irq_type(mc->irq_phone_active, IRQ_TYPE_LEVEL_LOW); else irq_set_irq_type(mc->irq_phone_active, IRQ_TYPE_LEVEL_HIGH); pr_info("[MSM] <%s> phone_state = %d\n", __func__, phone_state); return IRQ_HANDLED; } static void mdm6600_get_ops(struct modem_ctl *mc) { mc->ops.modem_on = mdm6600_on; mc->ops.modem_off = mdm6600_off; mc->ops.modem_reset = mdm6600_reset; mc->ops.modem_boot_on = mdm6600_boot_on; mc->ops.modem_boot_off = mdm6600_boot_off; } int mdm6600_init_modemctl_device(struct modem_ctl *mc, struct modem_data *pdata) { int ret = 0; struct platform_device *pdev; mc->gpio_cp_on = pdata->gpio_cp_on; mc->gpio_reset_req_n = pdata->gpio_reset_req_n; mc->gpio_cp_reset = pdata->gpio_cp_reset; mc->gpio_pda_active = pdata->gpio_pda_active; mc->gpio_phone_active = pdata->gpio_phone_active; mc->gpio_cp_dump_int = pdata->gpio_cp_dump_int; mc->gpio_flm_uart_sel = pdata->gpio_flm_uart_sel; #if 1 mc->gpio_flm_uart_sel_rev06 = pdata->gpio_flm_uart_sel_rev06; #endif mc->gpio_cp_warm_reset = pdata->gpio_cp_warm_reset; gpio_set_value(mc->gpio_cp_reset, 0); gpio_set_value(mc->gpio_cp_on, 0); pdev = to_platform_device(mc->dev); mc->irq_phone_active = platform_get_irq_byname(pdev, "cp_active_irq"); pr_info("[MSM] <%s> PHONE_ACTIVE IRQ# = %d\n", __func__, mc->irq_phone_active); mdm6600_get_ops(mc); ret = request_irq(mc->irq_phone_active, phone_active_irq_handler, IRQF_TRIGGER_HIGH, "msm_active", mc); if (ret) { pr_err("[MSM] <%s> failed to request_irq IRQ# %d (err=%d)\n", __func__, mc->irq_phone_active, ret); return ret; } ret = enable_irq_wake(mc->irq_phone_active); if (ret) { pr_err("[MSM] %s: failed to enable_irq_wake IRQ# %d (err=%d)\n", __func__, mc->irq_phone_active, ret); free_irq(mc->irq_phone_active, mc); return ret; } return ret; } #endif
<?php /** * @package Joomla.UnitTest * @subpackage Twitter * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JTwitterLists. * * @package Joomla.UnitTest * @subpackage Twitter * * @since 3.1.4 */ class JTwitterListsTest extends TestCase { /** * @var JRegistry Options for the Twitter object. * @since 3.1.4 */ protected $options; /** * @var JHttp Mock client object. * @since 3.1.4 */ protected $client; /** * @var JInput The input object to use in retrieving GET/POST data. * @since 3.1.4 */ protected $input; /** * @var JTwitterLists Object under test. * @since 3.1.4 */ protected $object; /** * @var JTwitterOauth Authentication object for the Twitter object. * @since 3.1.4 */ protected $oauth; /** * @var string Sample JSON string. * @since 3.1.4 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON error message. * @since 3.1.4 */ protected $errorString = '{"error":"Generic error"}'; /** * @var string Sample JSON string. * @since 3.1.4 */ protected $rateLimit = '{"resources": {"lists": { "/lists/list": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/statuses": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers/create": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/members/show": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers/show": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers/destroy": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/members/create_all": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/members": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/show": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscriptions": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/update": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/create": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/destroy": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"} }}}'; /** * Backup of the SERVER superglobal * * @var array * @since 3.6 */ protected $backupServer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected * * @return void */ protected function setUp() { $this->backupServer = $_SERVER; $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0'; $_SERVER['REQUEST_URI'] = '/index.php'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $key = "app_key"; $secret = "app_secret"; $my_url = "http://127.0.0.1/gsoc/joomla-platform/twitter_test.php"; $access_token = array('key' => 'token_key', 'secret' => 'token_secret'); $this->options = new JRegistry; $this->input = new JInput; $this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock(); $this->oauth = new JTwitterOAuth($this->options, $this->client, $this->input); $this->oauth->setToken($access_token); $this->object = new JTwitterLists($this->options, $this->client, $this->oauth); $this->options->set('consumer_key', $key); $this->options->set('consumer_secret', $secret); $this->options->set('callback', $my_url); $this->options->set('sendheaders', true); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * * @see \PHPUnit\Framework\TestCase::tearDown() * @since 3.6 */ protected function tearDown() { $_SERVER = $this->backupServer; unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedUser() { // User ID or screen name return array( array(234654235457), array('testUser'), array(null) ); } /** * Tests the getAllLists method * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser */ public function testGetLists($user) { $reverse = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getLists($user); } $data['reverse'] = true; $path = $this->object->fetchUrl('/lists/list.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getLists($user, $reverse), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getAllLists method - failure * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser * @expectedException DomainException */ public function testGetListsFailure($user) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getLists($user); } $path = $this->object->fetchUrl('/lists/list.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getLists($user); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedListStatuses() { // List ID or slug and owner return array( array(234654235457, null), array('test-list', 'testUser'), array('test-list', 12345), array('test-list', null), array(null, null) ); } /** * Tests the getListStatuses method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetStatuses($list, $owner) { $since_id = 12345; $max_id = 54321; $count = 10; $entities = true; $include_rts = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } $data['since_id'] = $since_id; $data['max_id'] = $max_id; $data['count'] = $count; $data['include_entities'] = $entities; $data['include_rts'] = $include_rts; $path = $this->object->fetchUrl('/lists/statuses.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getStatuses($list, $owner, $since_id, $max_id, $count, $entities, $include_rts), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListStatuses method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetStatusesFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } $path = $this->object->fetchUrl('/lists/statuses.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getStatuses($list, $owner); } /** * Tests the getListSubscribers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetSubscribers($list, $owner) { $cursor = 1234; $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } $data['cursor'] = $cursor; $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getSubscribers($list, $owner, $cursor, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListSubscribers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetSubscribersFailure($list, $owner) { $cursor = 1234; $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } $data['cursor'] = $cursor; $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getSubscribers($list, $owner, $cursor, $entities, $skip_status); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedMembers() { // List, User ID, screen name and owner. return array( array(234654235457, null, '234654235457', null), array('test-list', null, 'userTest', 'testUser'), array('test-list', '234654235457', null, '56165105642'), array('test-list', 'testUser', null, null), array('test-list', null, null, 'testUser'), array('test-list', 'testUser', '234654235457', 'userTest'), array(null, null, null, null) ); } /** * Tests the deleteListMembers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedMembers */ public function testDeleteMembers($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/destroy_all.json'); $this->client->expects($this->once()) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->deleteMembers($list, $user_id, $screen_name, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the deleteListMembers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedMembers * @expectedException DomainException */ public function testDeleteMembersFailure($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/destroy_all.json'); $this->client->expects($this->once()) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } /** * Tests the subscribe method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testSubscribe($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->subscribe($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the subscribe method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testSubscribeFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->subscribe($list, $owner); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedListUserOwner() { // List, User and Owner. return array( array(234654235457, '234654235457', null), array('test-list', 'userTest', 'testUser'), array('test-list', '234654235457', '56165105642'), array('test-list', 'testUser', null), array('test-list', null, 'testUser'), array(null, null, null) ); } /** * Tests the isListMember method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner */ public function testIsMember($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->isMember($list, $user, $owner, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the isListMember method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner * @expectedException DomainException */ public function testIsMemberFailure($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->isMember($list, $user, $owner, $entities, $skip_status); } /** * Tests the isListSubscriber method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner */ public function testIsSubscriber($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->isSubscriber($list, $user, $owner, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the isListSubscriber method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner * @expectedException DomainException */ public function testIsSubscriberFailure($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->isSubscriber($list, $user, $owner, $entities, $skip_status); } /** * Tests the unsubscribe method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testUnsubscribe($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->unsubscribe($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the unsubscribe method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testUnsubscribeFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->unsubscribe($list, $owner); } /** * Tests the addListMembers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedMembers */ public function testAddMembers($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/create_all.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->addMembers($list, $user_id, $screen_name, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the addListMembers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedMembers * @expectedException DomainException */ public function testAddMembersFailure($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/create_all.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->addMembers($list, $user_id, $screen_name, $owner); } /** * Tests the getListMembers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetMembers($list, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getMembers($list, $owner, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListMembers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetMembersFailure($list, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getMembers($list, $owner, $entities, $skip_status); } /** * Tests the getListById method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetListById($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } $path = $this->object->fetchUrl('/lists/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getListById($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListById method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetListByIdFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } $path = $this->object->fetchUrl('/lists/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getListById($list, $owner); } /** * Tests the getSubscriptions method * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser */ public function testGetSubscriptions($user) { $count = 10; $cursor = 1234; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscriptions($user); } $data['count'] = $count; $data['cursor'] = $cursor; $path = $this->object->fetchUrl('/lists/subscriptions.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getSubscriptions($user, $count, $cursor), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getSubscriptions method - failure * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser * @expectedException DomainException */ public function testGetSubscriptionsFailure($user) { $count = 10; $cursor = 1234; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscriptions($user); } $data['count'] = $count; $data['cursor'] = $cursor; $path = $this->object->fetchUrl('/lists/subscriptions.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getSubscriptions($user, $count, $cursor); } /** * Tests the updateList method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testUpdate($list, $owner) { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/update.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->update($list, $owner, $name, $mode, $description), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the updateList method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testUpdateFailure($list, $owner) { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/update.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->update($list, $owner, $name, $mode, $description); } /** * Tests the createList method * * @return void * * @since 3.1.4 */ public function testCreate() { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->create($name, $mode, $description), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the createList method - failure * * @return void * * @since 3.1.4 * @expectedException DomainException */ public function testCreateFailure() { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->create($name, $mode, $description); } /** * Tests the deleteList method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testDelete($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } $path = $this->object->fetchUrl('/lists/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->delete($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the deleteList method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testDeleteFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } $path = $this->object->fetchUrl('/lists/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->delete($list, $owner); } }
<?php namespace OpenCloud\Base\Exceptions; class NetworkUrlError extends \Exception {}
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef GRAPHICS_PRIMITIVES_H #define GRAPHICS_PRIMITIVES_H namespace Graphics { void drawLine(int x0, int y0, int x1, int y1, int color, void (*plotProc)(int, int, int, void *), void *data); void drawThickLine(int x0, int y0, int x1, int y1, int penX, int penY, int color, void (*plotProc)(int, int, int, void *), void *data); } // End of namespace Graphics #endif
.threecol-split-row-3-9--12 .hr--1-2 .l-r:first-child, .threecol-split-row-3-9--12 .arc--3 .l-r:first-child { width: 23.72881%; float: left; margin-right: 1.69492%; } .threecol-split-row-3-9--12 .hr--1-2 .l-r:last-child, .threecol-split-row-3-9--12 .arc--3 .l-r:nth-child(2) { width: 74.57627%; float: right; margin-right: 0; } .threecol-split-row-3-9--12 .arc--3 .l-r:last-child { clear: both; }
obj-y += utglobal.o obj-y += utmisc.o
// MELFAS HEX to C converter v1.6 [2008.05.26] const UINT16 MELFAS_binary_nLength = 0x21FC; // 8.5 KBytes ( 8700 Bytes ) const UINT8 MELFAS_binary[] = { // Model name : // Module revision : // Firmware version : 7 0xF0,0x1F,0x00,0x20,0xC1,0x00,0x00,0x00,0xD5,0x00,0x00,0x00,0xD7,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD9,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDB,0x00,0x00,0x00,0xDD,0x00,0x00,0x00, 0x4D,0x1D,0x00,0x00,0xC3,0x13,0x00,0x00,0x7D,0x1D,0x00,0x00,0xCB,0x1D,0x00,0x00, 0xDF,0x00,0x00,0x00,0xED,0x00,0x00,0x00,0x21,0x15,0x00,0x00,0xE7,0x00,0x00,0x00, 0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00, 0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00, 0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00, 0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00, 0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00, 0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00,0xE7,0x00,0x00,0x00, 0x03,0x48,0x85,0x46,0x02,0xF0,0x40,0xF8,0x00,0x48,0x00,0x47,0xDB,0x1D,0x00,0x00, 0xF0,0x1F,0x00,0x20,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7, 0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7,0xFE,0xE7, 0x0A,0x46,0x03,0x46,0x70,0x47,0xFE,0xE7,0x70,0x47,0x00,0x00,0x00,0x00,0x00,0x00, 0x4F,0x43,0x54,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x52,0x41,0x30,0x37,0x56,0x41,0x30,0x31,0x32,0x30,0x31,0x31,0x30,0x35,0x32,0x32, 0x10,0xB5,0x5B,0x21,0x09,0x01,0x9E,0x48,0x01,0xF0,0xF1,0xFF,0x5B,0x21,0xC9,0x00, 0x9C,0x48,0x01,0xF0,0xEC,0xFF,0xFF,0x21,0x6D,0x31,0x9B,0x48,0x01,0xF0,0xE7,0xFF, 0x00,0x20,0x9A,0x49,0xC0,0x43,0x9A,0x4A,0x08,0x80,0x10,0x80,0x05,0x23,0x48,0x80, 0x50,0x80,0x09,0x1D,0x12,0x1D,0x08,0x80,0x10,0x80,0x5B,0x1E,0xF7,0xD1,0x10,0xBD, 0xF0,0xB5,0x94,0x48,0x00,0x21,0x41,0x56,0x85,0xB0,0x93,0x48,0x02,0x91,0x0D,0x22, 0x19,0x21,0x02,0x60,0x81,0x60,0x00,0x21,0x41,0x60,0x0D,0x46,0xC1,0x60,0xEA,0x01, 0x03,0x92,0x68,0x22,0x86,0x4B,0x6A,0x43,0xD2,0x18,0x01,0x92,0x86,0x48,0x1A,0x22, 0x6A,0x43,0x10,0x18,0x00,0x90,0x83,0x49,0x34,0x20,0x00,0x24,0x68,0x43,0x46,0x18, 0x03,0x98,0x62,0x00,0x81,0x18,0x85,0x48,0x0F,0x18,0x04,0x21,0x79,0x5E,0xB0,0x5E, 0xB1,0x52,0x40,0x1A,0x00,0xD5,0x40,0x42,0x04,0x28,0x03,0xDD,0x00,0x98,0x00,0x22, 0x02,0x55,0x06,0xE0,0x00,0x98,0x00,0x57,0x05,0x28,0x02,0xD0,0x00,0x9A,0x40,0x1C, 0x10,0x55,0x01,0x98,0xA3,0x00,0xC2,0x58,0xC8,0x01,0x84,0x46,0x01,0x21,0x10,0x1A, 0x89,0x02,0x88,0x42,0x11,0xDD,0x74,0x49,0x4A,0x68,0xAA,0x42,0x00,0xDA,0x4D,0x60, 0xCA,0x68,0xA2,0x42,0x00,0xDA,0xCC,0x60,0x0A,0x68,0xAA,0x42,0x00,0xDD,0x0D,0x60, 0x8A,0x68,0xA2,0x42,0x11,0xDD,0x8C,0x60,0x0F,0xE0,0x6D,0x49,0x88,0x42,0x08,0xDA, 0x00,0x2A,0x0A,0xD1,0x01,0x99,0x62,0x46,0xCA,0x50,0x00,0x99,0x00,0x22,0x0A,0x55, 0x03,0xE0,0xC1,0x11,0x52,0x1A,0x01,0x99,0xCA,0x50,0x02,0x99,0x00,0x29,0x0B,0xD0, 0xFF,0x21,0x01,0x31,0x88,0x42,0x04,0xDD,0x41,0x02,0x62,0x48,0x08,0x18,0x00,0x14, 0x0F,0xE0,0x00,0x20,0xB8,0x80,0x0D,0xE0,0x00,0x28,0x17,0xDD,0x00,0x2C,0x03,0xD0, 0x19,0x2C,0x01,0xD0,0xC0,0x11,0x04,0xE0,0xC0,0x11,0x40,0x00,0x03,0x21,0x01,0xF0, 0x3B,0xFF,0xB8,0x80,0x64,0x1C,0x1A,0x2C,0x9A,0xDB,0x6D,0x1C,0x0E,0x2D,0x86,0xDB, 0x51,0x49,0x08,0x68,0x02,0x28,0x03,0xDD,0x80,0x1E,0x04,0xE0,0x00,0x20,0xF0,0xE7, 0x01,0x28,0x01,0xDD,0x40,0x1E,0x08,0x60,0x88,0x68,0x02,0x28,0x01,0xDD,0x80,0x1E, 0x02,0xE0,0x01,0x28,0x01,0xDD,0x40,0x1E,0x88,0x60,0x48,0x68,0x0C,0x28,0x01,0xDA, 0x80,0x1C,0x02,0xE0,0x0D,0x28,0x01,0xDA,0x40,0x1C,0x48,0x60,0xC8,0x68,0x18,0x28, 0x01,0xDA,0x80,0x1C,0x02,0xE0,0x19,0x28,0x01,0xDA,0x40,0x1C,0xC8,0x60,0x42,0x48, 0x00,0x78,0x00,0x28,0x0D,0xD0,0x41,0xA0,0x00,0xF0,0xCC,0xFE,0x34,0x4D,0x00,0x24, 0x68,0x20,0x60,0x43,0x41,0x19,0x1A,0x20,0x00,0xF0,0x22,0xFF,0x64,0x1C,0x0E,0x2C, 0xF6,0xDB,0x05,0xB0,0xF0,0xBD,0xF8,0xB5,0x00,0x22,0x3C,0x4B,0x11,0x46,0x00,0x24, 0x0D,0x20,0x95,0x01,0x2E,0x19,0xF6,0x18,0x71,0x70,0xB1,0x70,0xA4,0x1C,0x40,0x1E, 0xF8,0xD1,0x52,0x1C,0x0E,0x2A,0xF2,0xDB,0x35,0x4F,0x36,0x48,0x01,0x22,0xD5,0x01, 0xEE,0x19,0x31,0x80,0x94,0x01,0x24,0x18,0x21,0x70,0x71,0x80,0x61,0x70,0x32,0x4E, 0xAD,0x19,0x69,0x83,0x61,0x77,0x29,0x83,0x21,0x77,0x52,0x1C,0x11,0x2A,0xEE,0xDB, 0x2E,0x4E,0x2F,0x4B,0x01,0x22,0x3D,0x46,0x54,0x00,0x67,0x19,0x39,0x80,0x17,0x18, 0x39,0x70,0x2C,0x4F,0xE7,0x19,0x39,0x80,0x24,0x4F,0xD7,0x19,0x39,0x70,0xA7,0x19, 0x39,0x80,0xD7,0x18,0x39,0x70,0x28,0x4F,0xE4,0x19,0x21,0x80,0x27,0x4C,0x14,0x19, 0x21,0x70,0x52,0x1C,0x1D,0x2A,0xE7,0xDB,0x29,0x80,0x1F,0x4A,0x51,0x83,0x31,0x80, 0x23,0x4A,0x51,0x83,0x01,0x70,0x41,0x77,0x19,0x70,0x59,0x77,0x21,0x48,0x00,0x78, 0x00,0x28,0x0C,0xD0,0x20,0xA0,0x00,0xF0,0x6D,0xFE,0x22,0x4D,0x00,0x24,0xE0,0x01, 0x41,0x19,0x1A,0x20,0x00,0xF0,0x95,0xFE,0x64,0x1C,0x0E,0x2C,0xF7,0xDB,0xF8,0xBD, 0x2C,0x00,0x00,0x20,0xDC,0x05,0x00,0x20,0xB4,0x08,0x00,0x20,0xCE,0x0C,0x00,0x20, 0xE4,0x0C,0x00,0x20,0x11,0x00,0x00,0x20,0x00,0x00,0x00,0x20,0x00,0x41,0x00,0x40, 0x00,0xFC,0xFF,0xFF,0x00,0x00,0xFE,0xFF,0x1B,0x00,0x00,0x20,0x52,0x65,0x66,0x65, 0x72,0x65,0x6E,0x63,0x65,0x20,0x49,0x6D,0x61,0x67,0x65,0x00,0x40,0x20,0x00,0x40, 0x00,0x40,0x00,0x40,0x00,0x20,0x00,0x40,0x20,0x40,0x00,0x40,0x80,0x48,0x00,0x40, 0x40,0x24,0x00,0x40,0x80,0x40,0x00,0x40,0x00,0x48,0x00,0x40,0x00,0x24,0x00,0x40, 0xA0,0x48,0x00,0x40,0x1C,0x00,0x00,0x20,0x49,0x6E,0x74,0x65,0x6E,0x73,0x69,0x74, 0x79,0x00,0x00,0x00,0x04,0x41,0x00,0x40,0xF0,0xB5,0xD3,0xB0,0x00,0x24,0xFF,0x48, 0xC4,0x21,0x06,0x68,0xFE,0x48,0x00,0x68,0x03,0x94,0x08,0x94,0x04,0x94,0x0D,0x94, 0x05,0x94,0x06,0x94,0x07,0x94,0x09,0x94,0x12,0x90,0x0A,0x94,0x0B,0x94,0x0C,0x94, 0x0E,0x94,0x21,0xA8,0x01,0xF0,0x63,0xFE,0xF6,0x48,0x00,0x78,0x00,0x28,0x0C,0xD0, 0xF5,0xA0,0x00,0xF0,0x07,0xFE,0xF7,0x4F,0x00,0x25,0xA8,0x01,0xC1,0x19,0x1A,0x20, 0x00,0xF0,0xD4,0xFD,0x6D,0x1C,0x0E,0x2D,0xF7,0xDB,0xF3,0x48,0x03,0x21,0x41,0x56, 0x02,0x29,0x01,0xDA,0x03,0x20,0x00,0xE0,0x0A,0x20,0x1A,0x90,0xEF,0x48,0x76,0x1C, 0x05,0x68,0x13,0x96,0xB5,0x42,0x39,0xDA,0x12,0x9A,0x52,0x1C,0xEC,0x4B,0x12,0x9E, 0x18,0x68,0x00,0x21,0x36,0x1A,0x77,0x1C,0x00,0x2F,0x01,0xDD,0x01,0x21,0xB1,0x43, 0x0B,0x18,0x83,0x42,0x0F,0xDD,0xAE,0x01,0xE6,0x4B,0x37,0x18,0xFB,0x18,0x02,0x27, 0xDF,0x57,0x0C,0x2F,0x01,0xDD,0x00,0x27,0x9F,0x70,0xE1,0x4B,0x40,0x1C,0x1B,0x68, 0xCB,0x18,0x83,0x42,0xF0,0xDC,0xDE,0x48,0x00,0x68,0x08,0x18,0x90,0x42,0x11,0xDA, 0x00,0x26,0xAB,0x01,0xDB,0x49,0x1F,0x18,0x79,0x18,0x02,0x27,0xCF,0x57,0x0C,0x2F, 0x00,0xDD,0x8E,0x70,0x03,0x27,0xCF,0x57,0x0C,0x2F,0x00,0xDD,0xCE,0x70,0x80,0x1C, 0x90,0x42,0xEF,0xDB,0x13,0x98,0x6D,0x1C,0x85,0x42,0xC7,0xDB,0xCF,0x48,0x13,0x99, 0x00,0x68,0x02,0x90,0x88,0x42,0x7E,0xDA,0x12,0x98,0x40,0x1C,0x1B,0x90,0xCC,0x48, 0x02,0x68,0x1B,0x98,0x82,0x42,0x77,0xDA,0x02,0x98,0xC0,0xB2,0x20,0x90,0x02,0x98, 0xC0,0x01,0x1C,0x90,0x02,0x98,0x80,0x01,0x1F,0x90,0x80,0x18,0xC5,0x49,0x84,0x46, 0x43,0x18,0x02,0x20,0x18,0x56,0x1C,0x9D,0x51,0x00,0x6D,0x18,0xC2,0x49,0x6D,0x18, 0x04,0x21,0x69,0x5E,0x00,0x28,0x09,0xD0,0x03,0xAD,0x2E,0x5C,0x8E,0x42,0x05,0xDC, 0x29,0x54,0x07,0xAE,0x20,0x9D,0x35,0x54,0x0B,0xAD,0x2A,0x54,0x84,0x42,0x00,0xDA, 0xC4,0xB2,0x00,0x28,0x53,0xD1,0x1A,0x98,0x81,0x42,0x50,0xDD,0xB7,0x4D,0xFF,0x20, 0x65,0x44,0x6E,0x78,0x00,0x21,0xAF,0x78,0xED,0x78,0x1D,0x96,0xDE,0x78,0x15,0x97, 0x67,0x46,0xAC,0x46,0xB2,0x4D,0x17,0x96,0x7D,0x19,0xEF,0x78,0xAE,0x78,0x6D,0x78, 0x18,0x97,0x5F,0x78,0x19,0x96,0x1D,0x9E,0x00,0x2E,0x03,0xD0,0x01,0x21,0xFF,0x2E, 0x00,0xD2,0x30,0x46,0x15,0x9E,0x00,0x2E,0x03,0xD0,0x49,0x1C,0x86,0x42,0x00,0xD2, 0x30,0x46,0x66,0x46,0x00,0x2E,0x03,0xD0,0x49,0x1C,0x84,0x45,0x00,0xD2,0x30,0x46, 0x17,0x9E,0x00,0x2E,0x03,0xD0,0x49,0x1C,0x86,0x42,0x00,0xD2,0x30,0x46,0x18,0x9E, 0x00,0x2E,0x03,0xD0,0x49,0x1C,0x86,0x42,0x00,0xD2,0x30,0x46,0x19,0x9E,0x00,0x2E, 0x03,0xD0,0x49,0x1C,0x86,0x42,0x00,0xD2,0x30,0x46,0x00,0x2D,0x03,0xD0,0x49,0x1C, 0x85,0x42,0x00,0xD2,0x28,0x46,0x3D,0x00,0x03,0xD0,0x49,0x1C,0x87,0x42,0x00,0xD2, 0x28,0x46,0x00,0x29,0x01,0xE0,0x94,0xE0,0x07,0xE0,0x00,0xD0,0x98,0x70,0x1B,0x98, 0x52,0x1C,0x82,0x42,0x01,0xDA,0x1F,0x98,0x87,0xE7,0x02,0x98,0x13,0x99,0x40,0x1C, 0x02,0x90,0x88,0x42,0x00,0xDA,0x72,0xE7,0x02,0x20,0x64,0x1C,0x14,0x94,0x01,0x90, 0x02,0x2C,0x7E,0xD9,0x01,0x99,0x07,0xA8,0x42,0x5C,0x01,0x98,0x0B,0xA9,0x08,0x5C, 0x92,0x1C,0x80,0x1C,0x84,0x46,0xD1,0x01,0x40,0x00,0x09,0x18,0x81,0x48,0x08,0x18, 0x00,0x24,0x04,0x5F,0x80,0x4B,0xCD,0x18,0x1E,0x23,0xEB,0x5E,0x1B,0x1D,0x9C,0x42, 0x21,0xDC,0x00,0x24,0x04,0x5F,0x7D,0x4B,0xCD,0x18,0x00,0x23,0xEB,0x5E,0x09,0x33, 0x9C,0x42,0x08,0xDD,0x00,0x24,0x04,0x5F,0x79,0x4B,0xCD,0x18,0x1E,0x23,0xEB,0x5E, 0x09,0x33,0x9C,0x42,0x0F,0xDC,0x95,0x01,0x76,0x4C,0x65,0x44,0x01,0x23,0x2C,0x19, 0x00,0x26,0xA6,0x57,0x74,0x4C,0x2D,0x19,0x1F,0x24,0x2C,0x57,0x0E,0x27,0x21,0xAD, 0x7C,0x43,0x64,0x19,0x33,0x55,0x00,0x25,0x45,0x5F,0x6C,0x4B,0xCC,0x18,0x02,0x23, 0x15,0x94,0xE3,0x5E,0x1B,0x1D,0x9D,0x42,0x1E,0xDC,0x00,0x25,0x45,0x5F,0x23,0x46, 0x00,0x24,0x1C,0x5F,0x09,0x34,0xA5,0x42,0x06,0xDD,0x00,0x24,0x04,0x5F,0x02,0x23, 0xC3,0x5E,0x09,0x33,0x9C,0x42,0x0F,0xDC,0x95,0x01,0x64,0x46,0x2C,0x19,0x61,0x4D, 0x01,0x23,0x65,0x19,0x00,0x26,0xAE,0x57,0x60,0x4D,0x65,0x19,0xEC,0x56,0x0E,0x27, 0x21,0xAD,0x7C,0x43,0x64,0x19,0x33,0x55,0x00,0x24,0x04,0x5F,0x5C,0x4B,0xCD,0x18, 0x1E,0x23,0xEB,0x5E,0x1B,0x1D,0x9C,0x42,0x24,0xDC,0x00,0x24,0x04,0x5F,0x59,0x4B, 0xCD,0x18,0x00,0x23,0xEB,0x5E,0x09,0x33,0x9C,0x42,0x08,0xDD,0x00,0x24,0x04,0x5F, 0x4F,0x4B,0xCD,0x18,0x1E,0x23,0xEB,0x5E,0x09,0x33,0x9C,0x42,0x12,0xDC,0x01,0x23, 0x00,0xE0,0xD0,0xE0,0x95,0x01,0x64,0x46,0x2C,0x19,0x4A,0x4D,0x65,0x19,0x00,0x26, 0xAE,0x57,0x4D,0x4D,0x65,0x19,0x1F,0x24,0x2C,0x57,0x0E,0x27,0x21,0xAD,0x7C,0x43, 0x64,0x19,0x33,0x55,0x00,0x24,0x04,0x5F,0x46,0x4B,0xCB,0x18,0x02,0x25,0x16,0x93, 0x5D,0x5F,0x2D,0x1D,0xAC,0x42,0x1D,0xDC,0x00,0x25,0x45,0x5F,0x00,0x24,0x1C,0x5F, 0x09,0x34,0xA5,0x42,0x06,0xDD,0x00,0x24,0x04,0x5F,0x02,0x23,0xC3,0x5E,0x09,0x33, 0x9C,0x42,0x0F,0xDC,0x95,0x01,0x64,0x46,0x2C,0x19,0x36,0x4D,0x01,0x23,0x65,0x19, 0x00,0x26,0xAE,0x57,0x2D,0x4D,0x65,0x19,0xEC,0x56,0x0E,0x27,0x21,0xAD,0x7C,0x43, 0x64,0x19,0x33,0x55,0x00,0x23,0xC3,0x5E,0x15,0x9C,0x00,0x25,0x65,0x5F,0x2D,0x1D, 0xAB,0x42,0x10,0xDC,0x95,0x01,0x64,0x46,0x2C,0x19,0x2A,0x4D,0x01,0x23,0x65,0x19, 0x00,0x26,0xAE,0x57,0x29,0x4D,0x65,0x19,0x00,0x24,0x2C,0x57,0x0E,0x27,0x21,0xAD, 0x7C,0x43,0x64,0x19,0x33,0x55,0x00,0x25,0x45,0x5F,0x16,0x9C,0x00,0x23,0xE3,0x5E, 0x1B,0x1D,0x9D,0x42,0x10,0xDC,0x95,0x01,0x64,0x46,0x2C,0x19,0x1D,0x4D,0x01,0x23, 0x65,0x19,0x00,0x26,0xAE,0x57,0x15,0x4D,0x65,0x19,0x00,0x24,0x2C,0x57,0x0E,0x27, 0x21,0xAD,0x7C,0x43,0x64,0x19,0x33,0x55,0x00,0x24,0x04,0x5F,0x14,0x4B,0xCB,0x18, 0x1E,0x21,0x59,0x5E,0x09,0x1D,0x8C,0x42,0x41,0xDC,0x2F,0xE0,0x04,0x00,0x00,0x20, 0x0C,0x00,0x00,0x20,0x1D,0x00,0x00,0x20,0x47,0x72,0x6F,0x75,0x70,0x20,0x49,0x6D, 0x61,0x67,0x65,0x00,0x82,0x20,0x00,0x40,0x10,0x00,0x00,0x20,0x00,0x00,0x00,0x20, 0x08,0x00,0x00,0x20,0x80,0x20,0x00,0x40,0x00,0x41,0x00,0x40,0x40,0x20,0x00,0x40, 0xC0,0x20,0x00,0x40,0x00,0x40,0x00,0x40,0x60,0x3F,0x00,0x40,0x80,0x3F,0x00,0x40, 0xE0,0x3F,0x00,0x40,0x00,0x20,0x00,0x40,0xA0,0x1F,0x00,0x40,0xC0,0x1F,0x00,0x40, 0x60,0x40,0x00,0x40,0x80,0x40,0x00,0x40,0x20,0x20,0x00,0x40,0x94,0x01,0x61,0x46, 0x61,0x18,0xFD,0x4C,0x01,0x23,0x0D,0x19,0x00,0x24,0x2C,0x57,0xFB,0x4D,0x49,0x19, 0x1F,0x25,0x4D,0x57,0x0E,0x26,0x21,0xA9,0x75,0x43,0x69,0x18,0x63,0x54,0x00,0x23, 0xC3,0x5E,0x02,0x21,0x41,0x5E,0x09,0x1D,0x8B,0x42,0x0C,0xDC,0x92,0x01,0xF2,0x48, 0x62,0x44,0x01,0x21,0x10,0x18,0x00,0x23,0xC3,0x56,0x42,0x56,0x0E,0x24,0x21,0xA8, 0x62,0x43,0x10,0x18,0x19,0x54,0x01,0x98,0x14,0x99,0x40,0x1C,0xC0,0xB2,0x01,0x90, 0x88,0x42,0x00,0xD2,0xAE,0xE6,0x0D,0x21,0x21,0xA8,0x01,0xF0,0x18,0xFC,0x02,0x21, 0x01,0x24,0x21,0xA8,0x00,0x22,0x00,0x29,0x08,0xDD,0x0E,0x23,0x53,0x43,0x1B,0x18, 0x5B,0x5C,0x01,0x2B,0x11,0xD0,0x52,0x1C,0x8A,0x42,0xF6,0xDB,0x49,0x1C,0x0D,0x29, 0xF0,0xDB,0x00,0x25,0x01,0x46,0x2A,0x46,0x0D,0x23,0x00,0x24,0x0C,0x57,0x00,0x2C, 0x0F,0xD0,0x6D,0x1C,0xED,0xB2,0x04,0x5D,0x0C,0xE0,0x83,0x56,0x00,0x2B,0x01,0xD0, 0x43,0x54,0x00,0xE0,0x42,0x54,0x0E,0x22,0x4A,0x43,0x12,0x18,0x52,0x18,0xD4,0x73, 0xE4,0xE7,0x54,0x1B,0x0C,0x70,0x49,0x1C,0x52,0x1C,0x5B,0x1E,0xE5,0xD1,0xD0,0x49, 0x0E,0x68,0x13,0x99,0x8E,0x42,0x15,0xDA,0x12,0x9A,0xCE,0x4F,0x52,0x1C,0xCE,0x49, 0x09,0x68,0x91,0x42,0x0A,0xDA,0xB4,0x01,0x63,0x18,0xDB,0x19,0x9D,0x78,0x45,0x57, 0x00,0x2D,0x00,0xD0,0x9D,0x70,0x49,0x1C,0x91,0x42,0xF5,0xDB,0x13,0x99,0x76,0x1C, 0x8E,0x42,0xEC,0xDB,0x53,0xB0,0xF0,0xBD,0xF0,0xB5,0x9F,0xB0,0xFF,0xF7,0x4C,0xFD, 0xC2,0x48,0x00,0x23,0x06,0x68,0xC2,0x48,0xC2,0x49,0x04,0x68,0x00,0x93,0x01,0x93, 0x02,0x93,0xC1,0x48,0xC1,0x4A,0x03,0x93,0x04,0x93,0x05,0x93,0x06,0x93,0x0D,0x25, 0x07,0x93,0x00,0x23,0xDB,0x43,0x08,0xC1,0x00,0x23,0x08,0xC0,0x08,0xC2,0x6D,0x1E, 0xF7,0xD1,0xBB,0x48,0x00,0x78,0x00,0x28,0x0B,0xD0,0xBA,0xA0,0x00,0xF0,0x52,0xFB, 0xBC,0x4F,0xA8,0x01,0xC1,0x19,0x1A,0x20,0x00,0xF0,0x20,0xFB,0x6D,0x1C,0x0E,0x2D, 0xF7,0xDB,0x00,0x20,0x0C,0x90,0xAA,0x48,0x76,0x1C,0x00,0x68,0x0F,0x96,0x0A,0x90, 0xB0,0x42,0x57,0xDA,0xA8,0x48,0x64,0x1C,0x00,0x68,0x12,0x90,0x12,0x98,0xA0,0x42, 0x4A,0xDA,0x0A,0x99,0x89,0x01,0x8C,0x46,0x0A,0x99,0xC9,0x01,0x11,0x91,0x61,0x46, 0x0A,0x18,0xA0,0x49,0x51,0x18,0x02,0x22,0x8A,0x56,0x00,0x2A,0x39,0xD0,0x0C,0x99, 0x91,0x42,0x00,0xDA,0x0C,0x92,0x11,0x9D,0x41,0x00,0x6D,0x18,0xA6,0x49,0x53,0x1E, 0x6D,0x18,0x04,0x21,0x69,0x5E,0x95,0x00,0x9A,0x4E,0x2D,0x1F,0x77,0x59,0x0A,0x9D, 0x96,0x00,0x4D,0x43,0x7D,0x19,0x97,0x4F,0x36,0x1F,0xBD,0x51,0x92,0x00,0x96,0x4E, 0x12,0x1F,0xB2,0x58,0x00,0x28,0x07,0xD0,0x18,0x28,0x08,0xD0,0x19,0x28,0x3B,0xD0, 0xC5,0x00,0x2D,0x1D,0x4D,0x43,0x04,0xE0,0x8D,0x00,0x6D,0x42,0x01,0xE0,0xC6,0x25, 0x33,0xE0,0xAA,0x18,0x9D,0x00,0x72,0x51,0x8C,0x4A,0x56,0x59,0x76,0x18,0x56,0x51, 0x6A,0x46,0xD5,0x5C,0x6D,0x1C,0xD5,0x54,0x04,0xAA,0xD5,0x5C,0x8D,0x42,0x00,0xDA, 0xD1,0x54,0x40,0x1C,0xA0,0x42,0xBA,0xDB,0x0A,0x98,0x40,0x1C,0x0A,0x90,0x0F,0x99, 0x88,0x42,0xAB,0xDB,0x89,0x49,0x0C,0x98,0x88,0x70,0x0C,0x98,0x00,0x28,0x63,0xDD, 0x04,0xA8,0x0F,0x90,0x68,0x46,0x11,0x90,0x7C,0x4E,0x85,0x4F,0x79,0x4C,0x7A,0x4D, 0x0C,0x98,0x09,0x90,0x01,0xCE,0x08,0x90,0x00,0x28,0x48,0xD0,0x0F,0x98,0x00,0x78, 0x0C,0x28,0x04,0xD2,0x01,0x20,0x03,0xE0,0xD4,0x25,0x4D,0x43,0xC9,0xE7,0x00,0x20, 0x38,0x70,0x2D,0x21,0x20,0x68,0x09,0x01,0x48,0x43,0x0D,0x21,0x01,0xF0,0xFC,0xFA, 0x08,0x99,0x01,0xF0,0xF9,0xFA,0x00,0x21,0x20,0x60,0x00,0x28,0x00,0xDD,0x01,0x46, 0x21,0x60,0x05,0x21,0x28,0x68,0x09,0x02,0x48,0x43,0x1A,0x21,0x01,0xF0,0xEC,0xFA, 0x08,0x99,0x01,0xF0,0xE9,0xFA,0xC1,0x17,0x49,0x0F,0x08,0x18,0xC0,0x10,0x28,0x60, 0x11,0x98,0x00,0x78,0x32,0x28,0x02,0xD9,0x68,0x49,0x01,0x20,0x08,0x70,0x21,0x68, 0x00,0x29,0x02,0xDA,0x00,0x20,0x20,0x60,0x05,0xE0,0x2D,0x20,0x00,0x01,0x81,0x42, 0x00,0xDC,0x08,0x46,0x20,0x60,0x29,0x68,0x00,0x29,0x02,0xDA,0x00,0x20,0x28,0x60, 0x05,0xE0,0x05,0x20,0x00,0x02,0x81,0x42,0x00,0xDC,0x08,0x46,0x28,0x60,0x0F,0x98, 0x7F,0x1C,0x40,0x1C,0x0F,0x90,0x11,0x98,0x24,0x1D,0x40,0x1C,0x11,0x90,0x09,0x98, 0x2D,0x1D,0x40,0x1E,0x09,0x90,0xA5,0xD1,0x0C,0x98,0x00,0x28,0x7E,0xD0,0x53,0x49, 0x00,0x20,0x48,0x70,0x53,0x48,0x00,0x78,0x00,0x28,0x3D,0xD0,0x00,0x20,0x0A,0x90, 0x0B,0x90,0x0D,0x90,0x0E,0x90,0x0C,0x90,0x0F,0x90,0x10,0x90,0x12,0x90,0x13,0x90, 0x14,0x90,0x15,0x90,0x16,0x90,0x17,0x90,0x18,0x90,0x12,0xA8,0x1D,0x90,0x3F,0x4C, 0x0D,0x20,0x0A,0xAE,0x04,0xAD,0x6F,0x46,0x09,0x90,0x28,0x78,0x39,0x78,0x04,0xCC, 0x32,0x80,0x0A,0x22,0x6D,0x1C,0x7F,0x1C,0xB6,0x1C,0x50,0x43,0x01,0xF0,0x76,0xFA, 0x1D,0x99,0x08,0x80,0x1D,0x98,0x80,0x1C,0x1D,0x90,0x09,0x98,0x40,0x1E,0x09,0x90, 0xEB,0xD1,0x3D,0xA0,0x00,0xF0,0x46,0xFA,0x04,0xA9,0x0D,0x20,0x00,0xF0,0x16,0xFA, 0x69,0x46,0x0D,0x20,0x00,0xF0,0x12,0xFA,0x0A,0xA9,0x0D,0x20,0x00,0xF0,0x69,0xFA, 0x12,0xA9,0x0D,0x20,0x00,0xF0,0x65,0xFA,0x00,0x20,0x41,0x1E,0x27,0x4C,0x08,0x91, 0x07,0x90,0x22,0x68,0x35,0x4B,0x52,0x10,0x12,0xB2,0x03,0x92,0x34,0x48,0x35,0x4A, 0x0B,0x25,0x00,0x21,0xC9,0x43,0x19,0x80,0x01,0x80,0x11,0x70,0x9B,0x1C,0x80,0x1C, 0x52,0x1C,0x6D,0x1E,0xAC,0x46,0xF4,0xD1,0x24,0x49,0x02,0x20,0x08,0x56,0x0A,0x90, 0x60,0x46,0x40,0x00,0x2C,0x49,0x0B,0x90,0x08,0x5E,0x0F,0x90,0x40,0x1C,0x7E,0xD0, 0x60,0x46,0x80,0x00,0x29,0x4D,0x02,0x90,0x29,0x58,0x29,0x48,0x08,0x18,0x00,0x90, 0x04,0x90,0x0A,0x98,0x00,0x28,0x6C,0xDD,0x0E,0x48,0x22,0x49,0x0E,0x4A,0x0A,0x9C, 0x00,0x23,0x05,0x68,0x6E,0x1C,0x5E,0xD0,0x00,0x26,0x00,0xE0,0x42,0xE0,0x8E,0x57, 0x76,0x1C,0x43,0xD0,0x57,0xE0,0x00,0x00,0x00,0x20,0x00,0x40,0xE0,0x1F,0x00,0x40, 0x00,0x00,0x00,0x20,0x80,0x20,0x00,0x40,0x08,0x00,0x00,0x20,0x04,0x00,0x00,0x20, 0x0C,0x00,0x00,0x20,0x14,0x0B,0x00,0x20,0x48,0x0B,0x00,0x20,0x7C,0x0B,0x00,0x20, 0x1D,0x00,0x00,0x20,0x47,0x72,0x6F,0x75,0x70,0x20,0x49,0x6D,0x61,0x67,0x65,0x32, 0x00,0x00,0x00,0x00,0x82,0x20,0x00,0x40,0x00,0x41,0x00,0x40,0x10,0x00,0x00,0x20, 0x54,0x0A,0x00,0x20,0x1E,0x00,0x00,0x20,0x49,0x6E,0x74,0x65,0x6E,0x73,0x69,0x74, 0x79,0x20,0x50,0x72,0x6F,0x66,0x69,0x6C,0x65,0x00,0x00,0x00,0xBE,0x0B,0x00,0x20, 0xD4,0x0B,0x00,0x20,0xB0,0x0B,0x00,0x20,0x00,0x0C,0x00,0x20,0x20,0x0A,0x00,0x20, 0x10,0x27,0x00,0x00,0xB0,0x48,0x01,0x21,0x41,0x70,0x3B,0xE7,0x0F,0x9E,0x17,0x68, 0xAE,0x1B,0xB6,0x46,0xAD,0x4D,0x0B,0x9E,0xAD,0x5F,0x76,0x46,0x7D,0x1B,0x76,0x43, 0x6D,0x43,0x75,0x19,0x00,0x9E,0xB5,0x42,0x05,0xDA,0x5E,0xB2,0x08,0x96,0xA8,0x4F, 0x02,0x9E,0x00,0x95,0xBD,0x51,0x00,0x1D,0x49,0x1C,0x12,0x1D,0x5B,0x1C,0x64,0x1E, 0x97,0xD1,0x04,0x99,0x00,0x98,0x88,0x42,0x19,0xD0,0x08,0x98,0x00,0xE0,0x16,0xE0, 0xA0,0x49,0x80,0x00,0xA0,0x4B,0x0B,0x9A,0x09,0x58,0x99,0x52,0x9F,0x49,0x0B,0x9B, 0x0A,0x58,0x9F,0x49,0xCA,0x52,0x9F,0x49,0x0A,0x58,0x9F,0x49,0x0B,0x98,0x0A,0x52, 0x07,0x98,0x9E,0x49,0x40,0x1C,0x07,0x90,0x08,0x9A,0x60,0x46,0x88,0x54,0x60,0x46, 0x40,0x1C,0x84,0x46,0x0B,0x28,0x00,0xDA,0x5A,0xE7,0x00,0x20,0x0A,0x9A,0x01,0x46, 0x00,0x2A,0x1E,0xDD,0x95,0x4D,0x96,0x4A,0x6B,0x56,0x5B,0x1C,0x15,0xD1,0x0A,0x9B, 0x01,0x2B,0x05,0xDD,0x8F,0x4B,0x8C,0x00,0x1C,0x59,0x03,0x9B,0x9C,0x42,0x0C,0xDB, 0x90,0x4B,0x5B,0x5C,0x00,0x2B,0x08,0xD1,0x0B,0x28,0x06,0xDA,0x43,0x00,0xD3,0x5E, 0x5B,0x1C,0x7E,0xD0,0x40,0x1C,0x0B,0x28,0xF8,0xDB,0x0A,0x9B,0x49,0x1C,0x99,0x42, 0xE2,0xDB,0x7D,0x4B,0x07,0x98,0x98,0x70,0x81,0x49,0x00,0x20,0xD8,0x70,0x8C,0x46, 0x7D,0x4D,0x83,0x48,0x79,0x4A,0x16,0x31,0x0B,0x24,0x63,0x46,0x1E,0x88,0x9B,0x1C, 0x9C,0x46,0x00,0x23,0xCB,0x5E,0x2F,0x88,0x9E,0x46,0x07,0x80,0x93,0x1C,0x16,0x80, 0x1A,0x46,0x73,0x46,0xAD,0x1C,0x1B,0x11,0x0E,0x2B,0x00,0xDD,0x0E,0x23,0x00,0x26, 0x86,0x5F,0x80,0x1C,0x76,0x1C,0x03,0xD0,0x6B,0x4E,0xF7,0x78,0x7F,0x1C,0xF7,0x70, 0x0B,0x80,0x89,0x1C,0x64,0x1E,0xE0,0xD1,0x60,0x00,0x6D,0x4A,0x6A,0x49,0x87,0x18, 0x16,0x32,0x82,0x18,0x0B,0x92,0x46,0x18,0x6F,0x4A,0x23,0x01,0x08,0x5E,0x9D,0x18, 0x40,0x1C,0x7E,0xD0,0x00,0x21,0x69,0x56,0x03,0x20,0x4A,0x1C,0x03,0x2A,0x00,0xDC, 0x48,0x1C,0x41,0xB2,0x09,0x91,0x68,0x88,0x00,0x23,0x40,0xB2,0x84,0x46,0xC0,0x1C, 0xC1,0x0F,0x09,0x18,0x49,0x08,0x49,0x00,0x40,0x1A,0x40,0xB2,0x06,0x90,0x0B,0x9A, 0x00,0x20,0x00,0x21,0xD3,0x5E,0x30,0x5E,0x79,0x5E,0x01,0x90,0x0A,0x91,0x60,0x46, 0x40,0x00,0x41,0x19,0x00,0x93,0x04,0x20,0x08,0x22,0x0C,0x23,0x08,0x5E,0x8A,0x5E, 0xCB,0x5E,0x09,0x99,0x03,0x93,0x02,0x29,0x02,0x92,0x4F,0xDD,0x01,0x99,0x01,0x9A, 0x41,0x1A,0x12,0x1A,0x00,0xD4,0x11,0x46,0x07,0x91,0x0A,0x99,0x02,0x9A,0x0B,0x46, 0x52,0x1A,0x02,0x99,0x59,0x1A,0x00,0xD4,0x0A,0x46,0x94,0x46,0x03,0x9A,0x00,0x99, 0x00,0xE0,0x60,0xE0,0x03,0x9B,0x52,0x1A,0xC9,0x1A,0x00,0xD4,0x0A,0x46,0x0C,0x92, 0x07,0x9A,0x61,0x46,0x51,0x18,0x07,0x91,0x4B,0x21,0xC9,0x00,0x48,0x43,0x4B,0x22, 0x07,0x99,0xD2,0x00,0x89,0x18,0x05,0x91,0x49,0x10,0x42,0x18,0x0E,0x91,0x07,0x99, 0x01,0x98,0x48,0x43,0x10,0x18,0x05,0x99,0x01,0xF0,0xF6,0xF8,0x00,0xB2,0x01,0x90, 0x4B,0x21,0x02,0x98,0xC9,0x00,0x48,0x43,0x0E,0x99,0x42,0x18,0x07,0x99,0x0A,0x98, 0x48,0x43,0x10,0x18,0x05,0x99,0x01,0xF0,0xE7,0xF8,0x00,0xB2,0x0A,0x90,0x03,0x98, 0x64,0x21,0x48,0x43,0x0C,0x99,0x64,0x31,0x4A,0x10,0x83,0x18,0x0C,0x9A,0x00,0x98, 0x50,0x43,0x18,0x18,0x01,0xF0,0xD8,0xF8,0x00,0xB2,0x00,0x90,0x01,0x98,0x30,0x80, 0x00,0xE0,0x37,0xE0,0x06,0x99,0x49,0x00,0x49,0x19,0x88,0x80,0x0A,0x98,0x38,0x80, 0x08,0x81,0x0B,0x9A,0x00,0x98,0x10,0x80,0x88,0x81,0x06,0x98,0x68,0x80,0x09,0x98, 0x28,0x70,0x09,0x98,0x02,0x28,0x08,0xDA,0x00,0x20,0xC0,0x43,0x16,0x49,0x30,0x80, 0xC8,0x78,0x40,0x1E,0xC8,0x70,0x00,0x20,0x48,0x70,0x64,0x1C,0x0B,0x2C,0x00,0xDA, 0x52,0xE7,0x1F,0xB0,0xF0,0xBD,0x13,0x4B,0x8C,0x00,0x1E,0x59,0x12,0x4F,0x43,0x00, 0xFE,0x52,0x12,0x4E,0x16,0x37,0x36,0x59,0xFE,0x52,0x12,0x4E,0x34,0x59,0x6E,0x36, 0xF4,0x52,0x0B,0x4B,0x00,0x24,0x86,0x00,0x9C,0x51,0x07,0x9B,0x5B,0x1C,0x40,0x1C, 0x07,0x93,0x0A,0xE7,0x00,0x20,0x28,0x70,0x40,0x1E,0x30,0x80,0x38,0x80,0xDC,0xE7, 0x10,0xB5,0x00,0xF0,0xE9,0xF8,0x10,0xBD,0x10,0x00,0x00,0x20,0x16,0x0C,0x00,0x20, 0x20,0x0A,0x00,0x20,0x14,0x0B,0x00,0x20,0xBE,0x0B,0x00,0x20,0x48,0x0B,0x00,0x20, 0xD4,0x0B,0x00,0x20,0x7C,0x0B,0x00,0x20,0xEA,0x0B,0x00,0x20,0xB0,0x0B,0x00,0x20, 0x00,0x0C,0x00,0x20,0x54,0x0A,0x00,0x20,0x62,0x0A,0x00,0x20,0xF9,0x4A,0x11,0x54, 0x70,0x47,0xF8,0x49,0x08,0x5C,0x70,0x47,0xF7,0x48,0x07,0x21,0x01,0x70,0x01,0x21, 0x41,0x70,0x41,0x21,0x81,0x70,0x42,0x21,0xC1,0x70,0x70,0x47,0xF3,0x4A,0xD2,0x7A, 0x00,0x2A,0x26,0xD0,0xF8,0xB5,0xF2,0x4D,0x10,0x22,0x2A,0x70,0x68,0x70,0x00,0x24, 0x02,0x22,0x23,0x46,0x00,0x28,0x0B,0xDD,0xE7,0x00,0xCE,0x5C,0x7F,0x19,0xBE,0x54, 0x52,0x1C,0x08,0x2A,0x01,0xD1,0x64,0x1C,0x00,0x22,0x5B,0x1C,0x83,0x42,0xF3,0xDB, 0xE6,0x4C,0x02,0x20,0xE0,0x70,0x00,0x25,0xA5,0x70,0x00,0xF0,0x6D,0xFE,0x65,0x71, 0xA0,0x78,0xE1,0x78,0x88,0x42,0xFB,0xD3,0x00,0xF0,0x6B,0xFE,0x01,0x20,0x60,0x71, 0xF8,0xBD,0x70,0x47,0xF8,0xB5,0x04,0x46,0x01,0xF0,0x5D,0xF8,0xDB,0x49,0xC0,0xB2, 0xC9,0x7A,0x00,0x29,0x24,0xD0,0xDA,0x4D,0x30,0x21,0x29,0x70,0x68,0x70,0x00,0x23, 0x02,0x21,0x1A,0x46,0x00,0x28,0x0B,0xDD,0xDF,0x00,0xA6,0x5C,0x7F,0x19,0x7E,0x54, 0x49,0x1C,0x08,0x29,0x01,0xD1,0x5B,0x1C,0x00,0x21,0x52,0x1C,0x82,0x42,0xF3,0xDB, 0xCE,0x4C,0x02,0x20,0xE0,0x70,0x00,0x25,0xA5,0x70,0x00,0xF0,0x3D,0xFE,0x65,0x71, 0xA0,0x78,0xE1,0x78,0x88,0x42,0xFB,0xD3,0x00,0xF0,0x3B,0xFE,0x01,0x20,0x60,0x71, 0xF8,0xBD,0xC6,0x4A,0xD2,0x7A,0x00,0x2A,0x29,0xD0,0xF8,0xB5,0xC4,0x4D,0x20,0x22, 0x2A,0x70,0x68,0x70,0x00,0x24,0x01,0x22,0x23,0x46,0x00,0x28,0x0E,0xDD,0x5D,0x00, 0x4E,0x5B,0xBF,0x4D,0xE7,0x00,0x7D,0x19,0x57,0x00,0xEE,0x53,0x52,0x1C,0x04,0x2A, 0x01,0xD1,0x64,0x1C,0x00,0x22,0x5B,0x1C,0x83,0x42,0xF0,0xDB,0xB7,0x4C,0x02,0x20, 0xE0,0x70,0x00,0x25,0xA5,0x70,0x00,0xF0,0x0F,0xFE,0x65,0x71,0xA0,0x78,0xE1,0x78, 0x88,0x42,0xFB,0xD3,0x00,0xF0,0x0D,0xFE,0x01,0x20,0x60,0x71,0xF8,0xBD,0x70,0x47, 0xAE,0x4A,0xD2,0x7A,0x00,0x2A,0x2E,0xD0,0xF8,0xB5,0xAD,0x4D,0x20,0x22,0x2A,0x70, 0x68,0x70,0x00,0x24,0x01,0x22,0x23,0x46,0x00,0x28,0x13,0xDD,0x9D,0x00,0x4D,0x59, 0xE7,0x00,0xEE,0x17,0x76,0x0E,0x75,0x19,0x6D,0x02,0x2E,0x0C,0xA4,0x4D,0x7D,0x19, 0x57,0x00,0xEE,0x53,0x52,0x1C,0x04,0x2A,0x01,0xD1,0x64,0x1C,0x00,0x22,0x5B,0x1C, 0x83,0x42,0xEB,0xDB,0x9D,0x4C,0x02,0x20,0xE0,0x70,0x00,0x25,0xA5,0x70,0x00,0xF0, 0xDB,0xFD,0x65,0x71,0xA0,0x78,0xE1,0x78,0x88,0x42,0xFB,0xD3,0x00,0xF0,0xD9,0xFD, 0x01,0x20,0x60,0x71,0xF8,0xBD,0x70,0x47,0xF8,0xB5,0x94,0x48,0xC1,0x7A,0x00,0x29, 0x02,0xD0,0x94,0x49,0x09,0x78,0x8A,0xE0,0x90,0x48,0x00,0x79,0x00,0x28,0xFB,0xD1, 0x84,0x46,0x01,0x46,0x90,0x48,0x11,0x24,0x00,0x22,0x0B,0x29,0x03,0xDA,0x0B,0x22, 0x52,0x1A,0xD2,0x07,0xD2,0x0F,0x53,0x18,0x8B,0x42,0x0A,0xDD,0x8B,0x4A,0x4D,0x00, 0x56,0x5F,0x76,0x1C,0x1F,0xD1,0x45,0x5F,0x6D,0x1C,0x1C,0xD1,0x49,0x1C,0x8B,0x42, 0xF5,0xDC,0x19,0x46,0x0B,0x2B,0x16,0xDA,0x84,0x4A,0x4B,0x00,0xD5,0x5E,0x6D,0x1C, 0x11,0xD1,0xC5,0x5E,0x6D,0x1C,0x0E,0xD1,0x9E,0x18,0x02,0x25,0x75,0x5F,0x6D,0x1C, 0x04,0xD1,0x1D,0x18,0x02,0x23,0xEB,0x5E,0x5B,0x1C,0x01,0xD0,0x49,0x1C,0x02,0xE0, 0x89,0x1C,0x0B,0x29,0xE9,0xDB,0x0B,0x29,0x29,0xD0,0x78,0x4B,0x4A,0x00,0x9B,0x5E, 0x5D,0x1C,0x4E,0xD0,0x85,0x5E,0x6D,0x1C,0x75,0x4D,0xAD,0x5A,0x5C,0xD0,0x2D,0x01, 0x10,0x35,0x6E,0x18,0x6E,0x4D,0x2E,0x55,0x5E,0x11,0x38,0x27,0x3E,0x40,0x71,0x4F, 0xBF,0x5A,0xBE,0x46,0x7F,0x05,0x7F,0x0F,0xF6,0x19,0x80,0x36,0x2D,0x19,0x6E,0x70, 0xAB,0x70,0x77,0x46,0xEF,0x70,0x83,0x52,0x6A,0x4B,0x24,0x1D,0x9D,0x5A,0x6A,0x4B, 0x49,0x1C,0x9D,0x52,0x62,0x46,0x52,0x1C,0x94,0x46,0x0B,0x29,0xA4,0xDB,0x63,0x49, 0x64,0x4A,0x0C,0x88,0x04,0x80,0x64,0x4B,0x15,0x88,0x05,0x24,0x1D,0x80,0x4F,0x88, 0x05,0x46,0x6F,0x80,0x1E,0x46,0x55,0x88,0x09,0x1D,0x00,0x1D,0x75,0x80,0x12,0x1D, 0x0D,0x88,0x1B,0x1D,0x05,0x80,0x15,0x88,0x64,0x1E,0x1D,0x80,0xEF,0xD1,0x60,0x46, 0x53,0x49,0xC0,0xB2,0x08,0x74,0x61,0x46,0x00,0x29,0x05,0xD0,0x4F,0x4C,0x20,0x71, 0x00,0xF0,0x42,0xFD,0x00,0x20,0x60,0x71,0x4E,0x48,0x01,0x78,0x4B,0x48,0x81,0x73, 0xF8,0xBD,0x4B,0x4D,0x29,0x55,0x85,0x5A,0x38,0x27,0x6E,0x11,0x3E,0x40,0x4E,0x4F, 0xBF,0x5A,0xBE,0x46,0x7F,0x05,0x7F,0x0F,0xF7,0x19,0x45,0x4E,0x36,0x19,0x77,0x70, 0xB5,0x70,0x77,0x46,0xF7,0x70,0xB6,0xE7,0x2D,0x01,0x10,0x35,0x40,0x4E,0x6D,0x18, 0x35,0x55,0x5D,0x11,0x38,0x26,0x35,0x40,0x42,0x4E,0xB7,0x5A,0x7E,0x05,0x76,0x0F, 0xAE,0x19,0x3B,0x4D,0x40,0x36,0x2D,0x19,0x6E,0x70,0xAB,0x70,0xA2,0xE7,0x70,0xB5, 0x3E,0x4A,0x01,0x21,0x00,0x25,0x35,0x4C,0x00,0x28,0x14,0xD0,0x01,0x28,0x19,0xD0, 0xA0,0x28,0x16,0xD1,0xC3,0x05,0x18,0x7B,0xE0,0x72,0x18,0x7B,0x1A,0x28,0x17,0xD0, 0x00,0x20,0x02,0x46,0x06,0x2A,0x40,0xD2,0x7A,0x44,0x12,0x79,0x92,0x18,0x97,0x44, 0x3C,0x1A,0x21,0x28,0x2F,0x36,0x15,0x70,0x21,0x71,0x00,0xF0,0xFA,0xFC,0xA5,0x70, 0xE5,0x70,0x70,0xBD,0x11,0x70,0x00,0xF0,0xF4,0xFC,0xA5,0x70,0xE5,0x70,0x70,0xBD, 0x21,0x73,0x20,0x4C,0x00,0x20,0xC2,0x18,0x12,0x7B,0x81,0xB2,0x62,0x54,0x40,0x1C, 0x05,0x28,0xF8,0xDB,0x70,0xBD,0x5A,0x7B,0x92,0x07,0x01,0xD5,0xA1,0x71,0x1C,0xE0, 0xA5,0x71,0x1A,0xE0,0x5A,0x7B,0x52,0x07,0x01,0xD5,0xE1,0x71,0x15,0xE0,0xE5,0x71, 0x13,0xE0,0x5A,0x7B,0x12,0x07,0x01,0xD5,0x21,0x72,0x0E,0xE0,0x25,0x72,0x0C,0xE0, 0x5A,0x7B,0xD2,0x06,0x01,0xD5,0x61,0x72,0x07,0xE0,0x65,0x72,0x05,0xE0,0x5A,0x7B, 0x92,0x06,0x01,0xD5,0xA1,0x72,0x00,0xE0,0xA5,0x72,0x40,0x1C,0x08,0x28,0xB8,0xDB, 0x70,0xBD,0xF8,0xB5,0x05,0x24,0x24,0x07,0x20,0x7A,0xA7,0x7A,0x06,0x07,0x36,0x0F, 0x06,0x4D,0x01,0x2E,0x1C,0xD0,0x08,0x2E,0x46,0xD0,0x02,0x2E,0x5E,0xD0,0x04,0x2E, 0x7D,0xD0,0x95,0xE0,0xC4,0x0C,0x00,0x20,0x8C,0x0C,0x00,0x20,0x14,0x00,0x00,0x20, 0x2C,0x0C,0x00,0x20,0x13,0x00,0x00,0x20,0xCE,0x0C,0x00,0x20,0xBE,0x0B,0x00,0x20, 0xEA,0x0B,0x00,0x20,0xD4,0x0B,0x00,0x20,0xE4,0x0C,0x00,0x20,0x24,0x00,0x00,0x20, 0xE8,0x78,0x00,0x28,0x00,0xD0,0x00,0x27,0x6F,0x70,0x00,0xF0,0x92,0xFC,0x01,0x20, 0x68,0x71,0xA8,0x2F,0x17,0xD0,0x41,0x48,0xF0,0x2F,0x1A,0xD0,0xC1,0x5D,0x21,0x73, 0xC0,0x19,0x41,0x78,0x61,0x73,0x81,0x78,0xA1,0x73,0xC1,0x78,0xE1,0x73,0x01,0x79, 0x21,0x74,0x41,0x79,0x61,0x74,0x81,0x79,0xA1,0x74,0xC0,0x79,0xE0,0x74,0x68,0x78, 0x08,0x30,0x68,0x70,0x5C,0xE0,0x36,0x48,0x01,0x7A,0x21,0x73,0x40,0x7A,0x60,0x73, 0xF5,0xE7,0x00,0x6E,0xE0,0x60,0xF2,0xE7,0x69,0x78,0x30,0x48,0x42,0x5C,0x22,0x73, 0x40,0x18,0x41,0x78,0x61,0x73,0x81,0x78,0xA1,0x73,0xC1,0x78,0xE1,0x73,0x01,0x79, 0x21,0x74,0x41,0x79,0x61,0x74,0x81,0x79,0xA1,0x74,0xC0,0x79,0xE0,0x74,0x68,0x78, 0x60,0x21,0x08,0x30,0x00,0xF0,0x12,0xFE,0x69,0x70,0x39,0xE0,0x68,0x7B,0x01,0x28, 0x0B,0xD0,0x08,0x28,0x09,0xD0,0xE0,0x7A,0x01,0x07,0x09,0x0F,0x05,0xD0,0x38,0x46, 0xFF,0xF7,0x2D,0xFF,0x00,0x20,0x28,0x70,0xE8,0x70,0x10,0x2F,0x03,0xD0,0x15,0x2F, 0x04,0xD0,0x05,0xE0,0x0B,0xE0,0x28,0x79,0x01,0x28,0x01,0xD1,0x00,0x20,0x28,0x71, 0xE8,0x78,0x00,0x28,0x1C,0xD0,0xA8,0x78,0x40,0x1C,0xA8,0x70,0x18,0xE0,0xE0,0x68, 0x29,0x78,0x14,0x4F,0x89,0x00,0x78,0x50,0x28,0x78,0x40,0x1C,0xC0,0xB2,0x28,0x70, 0x0C,0x21,0x00,0xF0,0xE3,0xFD,0x29,0x70,0x20,0x69,0x29,0x78,0x89,0x00,0x78,0x50, 0x28,0x78,0x40,0x1C,0xC0,0xB2,0x28,0x70,0x0C,0x21,0x00,0xF0,0xD7,0xFD,0x29,0x70, 0x01,0x20,0x20,0x72,0x6E,0x73,0x10,0x20,0x20,0x72,0x00,0x20,0x20,0x72,0xF8,0xBD, 0x01,0x20,0x05,0x21,0x09,0x07,0x08,0x72,0x70,0x47,0x00,0x00,0x2C,0x0C,0x00,0x20, 0xC4,0x0C,0x00,0x20,0x94,0x0C,0x00,0x20,0xF0,0xB5,0xFF,0xB0,0xC8,0xB0,0x5B,0x21, 0xC9,0x00,0x10,0xA8,0x00,0xF0,0xEB,0xFD,0xD9,0x48,0x04,0x21,0x41,0x70,0x00,0xF0, 0x0B,0xFC,0x00,0xF0,0x05,0xFC,0x00,0xF0,0x19,0xFC,0x00,0x20,0x00,0x90,0xD5,0x48, 0x41,0x78,0x82,0x78,0x48,0x08,0x09,0x90,0xD2,0x48,0xC1,0x78,0x50,0x08,0x0A,0x90, 0xD0,0x48,0x02,0x79,0x48,0x08,0x0B,0x90,0xCE,0x48,0x41,0x79,0x50,0x08,0x0C,0x90, 0xCC,0x48,0x82,0x79,0x48,0x08,0x0D,0x90,0x50,0x08,0x0E,0x90,0xCA,0x48,0x01,0x78, 0x49,0x08,0x01,0x91,0x41,0x78,0x82,0x78,0x49,0x08,0x02,0x91,0xC3,0x78,0x51,0x08, 0x03,0x91,0x02,0x79,0x59,0x08,0x04,0x91,0x43,0x79,0x51,0x08,0x05,0x91,0x81,0x79, 0x58,0x08,0x06,0x90,0xBF,0x48,0x02,0x78,0x48,0x08,0x07,0x90,0x50,0x08,0x08,0x90, 0xFF,0x20,0x00,0x99,0x00,0x22,0x01,0x30,0x40,0x1A,0xC4,0xB2,0x01,0x99,0x90,0x01, 0x46,0x18,0xBA,0x49,0x76,0x18,0x34,0x70,0x02,0x9E,0x86,0x19,0x76,0x18,0x34,0x70, 0x03,0x9E,0x86,0x19,0x76,0x18,0x34,0x70,0x04,0x9E,0x86,0x19,0x76,0x18,0x34,0x70, 0x05,0x9E,0x86,0x19,0x76,0x18,0x34,0x70,0x06,0x9E,0x86,0x19,0x76,0x18,0x34,0x70, 0x07,0x9E,0x86,0x19,0x71,0x18,0x0C,0x70,0x08,0x99,0x46,0x18,0xAC,0x49,0x76,0x18, 0x34,0x70,0x09,0x9E,0x86,0x19,0x76,0x18,0x34,0x70,0x0A,0x9E,0x86,0x19,0x76,0x18, 0x34,0x70,0x0B,0x9E,0x86,0x19,0x76,0x18,0x34,0x70,0x0C,0x9E,0x86,0x19,0x76,0x18, 0x34,0x70,0x0D,0x9E,0x86,0x19,0x76,0x18,0x34,0x70,0x0E,0x9E,0x80,0x19,0x40,0x18, 0x04,0x70,0x52,0x1C,0x1A,0x2A,0xC1,0xDB,0x00,0xF0,0x8E,0xFB,0x00,0xF0,0x88,0xFB, 0x00,0xF0,0x9C,0xFB,0x00,0x20,0x86,0x46,0x70,0x46,0x34,0x21,0x48,0x43,0x10,0xA9, 0x41,0x18,0x70,0x46,0x1A,0x22,0x50,0x43,0x96,0x4A,0x75,0x46,0x83,0x18,0x00,0x22, 0x1A,0x20,0xED,0x01,0xAC,0x46,0x66,0x46,0x55,0x00,0x76,0x19,0x92,0x4D,0x75,0x19, 0x04,0x26,0xAE,0x5F,0x00,0x27,0xCF,0x5F,0xBE,0x42,0x02,0xDD,0xAD,0x88,0x0D,0x80, 0x1C,0x70,0x89,0x1C,0x5B,0x1C,0x52,0x1C,0x40,0x1E,0xEC,0xD1,0x71,0x46,0x49,0x1C, 0x8E,0x46,0x0E,0x29,0xD8,0xDB,0x00,0x99,0x49,0x1C,0x49,0xB2,0x00,0x91,0x14,0x29, 0x86,0xDB,0x7F,0x49,0x02,0x22,0x4A,0x70,0x82,0x4E,0x01,0x9B,0x81,0x01,0x34,0x5C, 0xCD,0x18,0x7E,0x4B,0x64,0x1E,0xED,0x18,0x2C,0x70,0x32,0x18,0x34,0x24,0xA4,0x5C, 0x02,0x9D,0x64,0x1E,0x4D,0x19,0xED,0x18,0x2C,0x70,0x68,0x24,0xA4,0x5C,0x03,0x9D, 0x64,0x1E,0x4D,0x19,0xED,0x18,0x2C,0x70,0x9C,0x24,0xA4,0x5C,0x04,0x9D,0x64,0x1E, 0x4D,0x19,0xED,0x18,0x2C,0x70,0xD0,0x24,0xA4,0x5C,0x05,0x9D,0x64,0x1E,0x4D,0x19, 0xED,0x18,0x2C,0x70,0xFF,0x24,0x05,0x34,0xA4,0x5C,0x06,0x9D,0x64,0x1E,0x4D,0x19, 0xED,0x18,0x2C,0x70,0xFF,0x24,0x39,0x34,0xA4,0x5C,0x07,0x9D,0x64,0x1E,0x4D,0x19, 0xEB,0x18,0x1C,0x70,0x08,0x9B,0x92,0x7E,0xCD,0x18,0x65,0x4B,0x52,0x1E,0xED,0x18, 0x2A,0x70,0x01,0x22,0x34,0x24,0x15,0x46,0x65,0x43,0x62,0x4C,0x2C,0x19,0x25,0x18, 0x5C,0x4C,0xAE,0x7E,0xA7,0x5C,0x76,0x1E,0x7F,0x08,0xCF,0x19,0xFF,0x18,0x3E,0x70, 0xA4,0x18,0x40,0x35,0x64,0x78,0xAD,0x7B,0x64,0x08,0x6D,0x1E,0x0C,0x19,0xE4,0x18, 0x25,0x70,0x92,0x1C,0x07,0x2A,0xE5,0xDB,0x40,0x1C,0x1A,0x28,0xA4,0xDB,0x57,0x4E, 0x30,0x78,0x00,0x28,0x1B,0xD0,0x56,0xA0,0xFF,0xF7,0x7C,0xFC,0x51,0x4D,0x00,0x24, 0x1A,0x20,0x60,0x43,0x41,0x19,0x1A,0x20,0xFF,0xF7,0x48,0xFC,0x64,0x1C,0x0E,0x2C, 0xF6,0xDB,0x30,0x78,0x00,0x28,0x0A,0xD0,0x00,0x24,0x10,0xAD,0x34,0x20,0x60,0x43, 0x41,0x19,0x1A,0x20,0xFF,0xF7,0x95,0xFC,0x64,0x1C,0x0E,0x2C,0xF6,0xDB,0x7F,0xB0, 0x48,0xB0,0xF0,0xBD,0xF8,0xB5,0x01,0x28,0x42,0xD0,0x00,0x20,0x3F,0x4A,0x00,0x21, 0x48,0x4C,0x83,0x01,0x9A,0x18,0x34,0x25,0x3E,0x4E,0x4D,0x43,0xAD,0x19,0x2E,0x5C, 0x39,0x4D,0x14,0x3E,0x6D,0x5C,0x6D,0x08,0x5F,0x19,0x38,0x4D,0x7D,0x19,0x2E,0x70, 0x27,0x5C,0x01,0x26,0xBE,0x40,0x96,0x61,0x49,0x1C,0xC9,0xB2,0x07,0x29,0xEA,0xD3, 0x30,0x4E,0x33,0x4F,0x00,0x21,0x34,0x24,0x32,0x4D,0x4C,0x43,0x64,0x19,0x24,0x18, 0x75,0x5C,0xA4,0x7E,0x6D,0x08,0x14,0x3C,0x5D,0x19,0xED,0x19,0x2C,0x70,0x35,0x4C, 0x25,0x5C,0x01,0x24,0xAC,0x40,0x94,0x63,0x49,0x1C,0xC9,0xB2,0x07,0x29,0xEA,0xD3, 0x40,0x1C,0xC0,0xB2,0x1A,0x28,0xC9,0xD3,0x00,0x24,0x00,0xF0,0x9D,0xFA,0x00,0xF0, 0x97,0xFA,0x00,0xF0,0xAB,0xFA,0x64,0x1C,0xE4,0xB2,0x32,0x2C,0xF5,0xD3,0xF8,0xBD, 0x00,0x20,0x1E,0x4A,0x00,0x21,0x27,0x4B,0x85,0x01,0xAC,0x18,0x34,0x22,0x1D,0x4E, 0x4A,0x43,0x92,0x19,0x16,0x5C,0x18,0x4A,0x52,0x5C,0x52,0x08,0xAF,0x18,0x17,0x4A, 0xBA,0x18,0x16,0x70,0x1F,0x5C,0x01,0x22,0x16,0x46,0xBE,0x40,0xA6,0x61,0x49,0x1C, 0xC9,0xB2,0x07,0x29,0xEA,0xD3,0x00,0x21,0x34,0x23,0x12,0x4E,0x4B,0x43,0x9B,0x19, 0x1B,0x18,0x9E,0x7E,0x0B,0x4B,0x5B,0x5C,0x5B,0x08,0xEF,0x18,0x0C,0x4B,0xFB,0x18, 0x1E,0x70,0x14,0x4B,0x1E,0x5C,0x13,0x46,0xB3,0x40,0xA3,0x63,0x49,0x1C,0xC9,0xB2, 0x07,0x29,0xE9,0xD3,0x40,0x1C,0xC0,0xB2,0x1A,0x28,0xCA,0xD3,0xBC,0xE7,0x00,0x00, 0x40,0x00,0x00,0x40,0xA9,0x21,0x00,0x00,0xA2,0x21,0x00,0x00,0x00,0x10,0x00,0x40, 0x20,0x10,0x00,0x40,0xFA,0x0C,0x00,0x20,0x00,0x41,0x00,0x40,0x23,0x00,0x00,0x20, 0x44,0x65,0x6C,0x61,0x79,0x20,0x70,0x65,0x72,0x20,0x63,0x68,0x61,0x6E,0x6E,0x65, 0x6C,0x00,0x00,0x00,0x88,0x21,0x00,0x00,0xF0,0xB5,0x00,0x20,0x84,0x46,0x83,0xB0, 0xFB,0x48,0x00,0x90,0xFB,0x48,0x41,0x78,0x01,0x20,0x88,0x40,0x01,0x90,0x00,0x23, 0xF9,0x4C,0x60,0x46,0x19,0x46,0x1F,0x46,0x80,0x01,0x42,0x18,0x12,0x19,0x97,0x72, 0xD7,0x72,0x89,0x1C,0x0A,0x29,0xF8,0xDB,0xF4,0x4A,0x00,0x21,0x54,0x5C,0xFF,0x25, 0x64,0x08,0x06,0x19,0xF0,0x4C,0x36,0x19,0x35,0x70,0x56,0x5C,0x4D,0x00,0x76,0x08, 0xAD,0x1C,0x86,0x19,0x34,0x19,0xA5,0x72,0x55,0x5C,0x01,0x24,0xAC,0x40,0xE3,0x18, 0x49,0x1C,0x07,0x29,0xEA,0xDB,0xE8,0x49,0x41,0x18,0x8E,0x46,0xCB,0x61,0x62,0x46, 0x92,0x1C,0xD2,0xB2,0x02,0x92,0x0A,0x75,0xE2,0x4A,0x63,0x46,0xD3,0x5C,0x01,0x22, 0x9A,0x40,0x8A,0x61,0x61,0x46,0x19,0x29,0x02,0xD0,0x00,0x29,0x08,0xD0,0x0C,0xE0, 0xDF,0x49,0x8A,0x69,0x00,0x9B,0x01,0x26,0xDB,0x7F,0x9E,0x40,0x32,0x43,0x03,0xE0, 0xD9,0x49,0x8A,0x69,0x01,0x9B,0x1A,0x43,0x8A,0x61,0x00,0x23,0xD9,0x4A,0x19,0x46, 0x3D,0x46,0x44,0x18,0xA4,0x18,0xA5,0x72,0xE5,0x72,0x89,0x1C,0x0A,0x29,0xF8,0xDB, 0x00,0x21,0x01,0x27,0xD4,0x4C,0xFF,0x25,0x66,0x5C,0x76,0x08,0x86,0x19,0xB6,0x18, 0x35,0x70,0x66,0x5C,0x4D,0x00,0x76,0x08,0xED,0x1C,0x86,0x19,0xB6,0x18,0xB5,0x72, 0x65,0x5C,0x3C,0x46,0xAC,0x40,0xE3,0x18,0x49,0x1C,0x07,0x29,0xEA,0xDB,0xC6,0x49, 0x74,0x46,0xE3,0x63,0x80,0x18,0x02,0x9B,0x03,0x75,0xC2,0x48,0x62,0x46,0x80,0x5C, 0x87,0x40,0x70,0x46,0x87,0x63,0x60,0x46,0x19,0x2A,0x07,0xD0,0x00,0x28,0x0F,0xD0, 0x40,0x1C,0x84,0x46,0x1A,0x28,0x82,0xDB,0x03,0xB0,0xF0,0xBD,0xBC,0x48,0x82,0x6B, 0x00,0x99,0xCB,0x7F,0x01,0x21,0x99,0x40,0x0A,0x43,0x82,0x63,0x03,0xB0,0xF0,0xBD, 0x88,0x6B,0x01,0x9A,0x10,0x43,0x88,0x63,0x01,0x20,0x84,0x46,0x6F,0xE7,0x10,0xB4, 0x52,0x21,0x48,0x07,0x01,0x77,0x0C,0x21,0x41,0x77,0x96,0x21,0x81,0x77,0x18,0x21, 0xC1,0x77,0xB3,0x48,0xB1,0x49,0x01,0x80,0x00,0x21,0x41,0x80,0xB1,0x49,0x81,0x80, 0x13,0x22,0xC2,0x80,0x01,0x81,0x42,0x81,0xAF,0x4B,0x83,0x81,0xAF,0x4C,0xC4,0x81, 0x03,0x82,0x44,0x82,0x81,0x82,0xC2,0x82,0x01,0x83,0x42,0x83,0x81,0x83,0xC2,0x83, 0x10,0xBC,0x70,0x47,0xF0,0xB4,0x09,0x21,0x88,0x07,0x41,0x83,0x1E,0x21,0x01,0x76, 0x12,0x21,0x41,0x76,0x00,0x21,0xA6,0x4E,0xA6,0x4C,0x0F,0x22,0x08,0x46,0x4B,0x00, 0x9D,0x19,0x28,0x80,0x0B,0x19,0x18,0x70,0x68,0x80,0x58,0x70,0x89,0x1C,0x52,0x1E, 0xF5,0xD1,0x00,0x21,0x8C,0x46,0x63,0x46,0x00,0x21,0x0F,0x22,0x9D,0x01,0xDF,0x01, 0x4B,0x00,0xFC,0x18,0x9C,0x4B,0xE4,0x18,0x20,0x80,0x9C,0x4B,0x6E,0x18,0xF3,0x18, 0x18,0x70,0x60,0x80,0x58,0x70,0x89,0x1C,0x52,0x1E,0xF1,0xD1,0x61,0x46,0x49,0x1C, 0x8C,0x46,0x12,0x29,0xE7,0xDB,0xF0,0xBC,0x70,0x47,0x10,0xB5,0x94,0x48,0x82,0x21, 0x41,0x70,0x02,0x21,0x41,0x70,0x42,0x23,0x05,0x22,0x12,0x07,0xD3,0x72,0x48,0x23, 0x93,0x72,0x41,0x70,0xFF,0xF7,0x90,0xFA,0x10,0xBD,0x00,0x21,0x01,0x20,0x80,0x07, 0x81,0x70,0xC1,0x60,0xF3,0x21,0x01,0x74,0x70,0x21,0x81,0x74,0x7F,0x21,0xC1,0x74, 0xFF,0x21,0x41,0x74,0x70,0x47,0x10,0xB5,0x86,0x49,0x0F,0x20,0x08,0x60,0x86,0x49, 0x00,0x20,0x08,0x60,0x03,0x21,0x00,0xF0,0xC5,0xF8,0x00,0x21,0x01,0x20,0x00,0xF0, 0xC1,0xF8,0x02,0x21,0x08,0x46,0x00,0xF0,0xBD,0xF8,0x01,0x21,0x03,0x20,0x00,0xF0, 0xB9,0xF8,0x01,0x21,0x04,0x20,0x00,0xF0,0xB5,0xF8,0x02,0x21,0x05,0x20,0x00,0xF0, 0xB1,0xF8,0x00,0x21,0x06,0x20,0x00,0xF0,0xAD,0xF8,0x78,0x48,0x01,0x69,0x04,0x22, 0x11,0x43,0x01,0x61,0x10,0xBD,0xF8,0xB5,0x01,0x20,0x85,0x07,0x68,0x72,0x00,0x24, 0xEC,0x80,0xCC,0x20,0x28,0x71,0xBA,0x20,0x68,0x71,0x6D,0x4E,0xC3,0x20,0xB0,0x70, 0x0F,0x20,0x28,0x72,0xBD,0x21,0xA9,0x72,0x55,0x21,0xE9,0x72,0x33,0x21,0x31,0x70, 0x6B,0x49,0x71,0x60,0x34,0x72,0x67,0x49,0x08,0x60,0x67,0x48,0x04,0x60,0x03,0x21, 0x00,0x20,0x00,0xF0,0x87,0xF8,0x00,0x21,0x01,0x20,0x00,0xF0,0x83,0xF8,0x02,0x21, 0x08,0x46,0x00,0xF0,0x7F,0xF8,0x01,0x21,0x03,0x20,0x00,0xF0,0x7B,0xF8,0x01,0x21, 0x04,0x20,0x00,0xF0,0x77,0xF8,0x02,0x21,0x05,0x20,0x00,0xF0,0x73,0xF8,0x00,0x21, 0x06,0x20,0x00,0xF0,0x6F,0xF8,0x59,0x48,0x01,0x69,0x04,0x22,0x11,0x43,0x01,0x61, 0xAC,0x70,0xEC,0x60,0xF3,0x20,0x28,0x74,0x70,0x20,0xA8,0x74,0x7F,0x20,0xE8,0x74, 0xFF,0x20,0x68,0x74,0x82,0x20,0x70,0x70,0x02,0x20,0x70,0x70,0x42,0x22,0x05,0x21, 0x09,0x07,0xCA,0x72,0x48,0x22,0x8A,0x72,0x70,0x70,0xFF,0xF7,0x05,0xFA,0x09,0x20, 0x68,0x83,0x1E,0x20,0x28,0x76,0x12,0x20,0x68,0x76,0x00,0x20,0x40,0x4E,0x41,0x4B, 0x0F,0x21,0x42,0x00,0x95,0x19,0x2C,0x80,0xC2,0x18,0x14,0x70,0x6C,0x80,0x54,0x70, 0x80,0x1C,0x49,0x1E,0xF5,0xD1,0x00,0x20,0x84,0x46,0x62,0x46,0x00,0x20,0x0F,0x21, 0x95,0x01,0xD7,0x01,0x42,0x00,0xBB,0x18,0x37,0x4A,0x9B,0x18,0x1C,0x80,0x37,0x4A, 0x2E,0x18,0xB2,0x18,0x14,0x70,0x5C,0x80,0x54,0x70,0x80,0x1C,0x49,0x1E,0xF1,0xD1, 0x60,0x46,0x40,0x1C,0x84,0x46,0x12,0x28,0xE7,0xDB,0x52,0x21,0x48,0x07,0x01,0x77, 0x0C,0x21,0x41,0x77,0x96,0x21,0x81,0x77,0x18,0x21,0xC1,0x77,0x24,0x48,0x23,0x49, 0x01,0x80,0x44,0x80,0x23,0x49,0x81,0x80,0x13,0x22,0xC2,0x80,0x01,0x81,0x42,0x81, 0x21,0x4B,0x83,0x81,0x21,0x4C,0xC4,0x81,0x03,0x82,0x44,0x82,0x81,0x82,0xC2,0x82, 0x01,0x83,0x42,0x83,0x81,0x83,0xC2,0x83,0xFF,0xF7,0x26,0xFE,0xFE,0xF7,0x48,0xFA, 0x62,0xB6,0xF8,0xBD,0x83,0x07,0xFF,0x22,0xDB,0x0E,0x9A,0x40,0x89,0x07,0x09,0x0E, 0x99,0x40,0x00,0x28,0x0B,0xDA,0x00,0x07,0x00,0x0F,0x08,0x38,0x83,0x08,0x1B,0x48, 0x9B,0x00,0x18,0x18,0xC3,0x69,0x93,0x43,0x0B,0x43,0xC3,0x61,0x70,0x47,0x83,0x08, 0x18,0x48,0x9B,0x00,0x18,0x18,0x03,0x68,0x93,0x43,0x0B,0x43,0x03,0x60,0x70,0x47, 0x81,0x21,0x00,0x00,0x88,0x21,0x00,0x00,0x00,0x10,0x00,0x40,0xA2,0x21,0x00,0x00, 0x40,0x16,0x00,0x40,0x20,0x10,0x00,0x40,0xA9,0x21,0x00,0x00,0x64,0x08,0x00,0x00, 0x20,0x00,0x00,0x40,0x13,0x04,0x00,0x00,0x13,0x06,0x00,0x00,0x13,0x02,0x00,0x00, 0x00,0x49,0x00,0x40,0x80,0x24,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x20,0x00,0x40, 0x40,0x00,0x00,0x40,0x00,0xE1,0x00,0xE0,0x00,0xE2,0x00,0xE0,0x00,0xED,0x00,0xE0, 0xFF,0xFF,0x0F,0x00,0x00,0xE4,0x00,0xE0,0xFB,0x20,0x01,0x21,0x89,0x07,0x48,0x74, 0x70,0x47,0xFF,0x20,0x01,0x21,0x89,0x07,0x48,0x74,0x70,0x47,0x73,0x49,0x48,0x06, 0x41,0x61,0x73,0x4A,0x01,0x21,0x51,0x70,0x00,0x22,0xC2,0x75,0xC1,0x75,0x70,0x47, 0x70,0x49,0x01,0x20,0x08,0x72,0x70,0x47,0x6D,0x49,0x00,0x20,0x88,0x70,0x6D,0x49, 0x08,0x72,0x09,0x06,0x08,0x70,0x01,0x20,0x08,0x70,0x70,0x47,0x68,0x49,0x01,0x20, 0x88,0x70,0x00,0x20,0x01,0x21,0x89,0x07,0x08,0x70,0x70,0x47,0x64,0x48,0x72,0xB6, 0x81,0x78,0x00,0x29,0x05,0xD0,0x62,0xB6,0x63,0x48,0x00,0x78,0x00,0x28,0x05,0xD1, 0x70,0x47,0x00,0xBF,0x00,0xBF,0x62,0xB6,0x30,0xBF,0xF0,0xE7,0x70,0xB5,0x5F,0xA0, 0xFF,0xF7,0x60,0xF9,0x60,0x4D,0x00,0x24,0xE0,0x01,0x41,0x19,0x1A,0x20,0xFF,0xF7, 0x88,0xF9,0x64,0x1C,0x0E,0x2C,0xF7,0xDB,0x70,0xBD,0x55,0x49,0x01,0x20,0xC8,0x70, 0x00,0x20,0x01,0x21,0x89,0x07,0x48,0x70,0x70,0x47,0xFF,0xF7,0xBC,0xFE,0x50,0x48, 0x00,0x24,0x84,0x70,0x4F,0x4F,0x3C,0x72,0x3D,0x06,0x2C,0x70,0x01,0x26,0x2E,0x70, 0x3E,0x72,0xFF,0xF7,0xCB,0xFF,0x4A,0x48,0x84,0x70,0x3C,0x72,0x2C,0x70,0x2E,0x70, 0x3E,0x72,0xFF,0xF7,0xC3,0xFF,0x46,0x48,0x84,0x70,0x3C,0x72,0x2C,0x70,0x2E,0x70, 0x3E,0x72,0xFF,0xF7,0xBB,0xFF,0x42,0x48,0x84,0x70,0x3C,0x72,0x2C,0x70,0x2E,0x70, 0x3E,0x72,0xFF,0xF7,0xB3,0xFF,0xFF,0xF7,0x87,0xFB,0x3D,0x48,0x84,0x70,0x3C,0x72, 0x2C,0x70,0x2E,0x70,0x3E,0x72,0xFF,0xF7,0xA9,0xFF,0x39,0x48,0x84,0x70,0x3C,0x72, 0x2C,0x70,0x2E,0x70,0x3E,0x72,0xFF,0xF7,0xA1,0xFF,0x35,0x48,0x44,0x70,0x33,0x48, 0x68,0x61,0xEE,0x75,0x32,0x4D,0x28,0x78,0x00,0x28,0x13,0xD0,0x01,0x20,0x2C,0x70, 0x80,0x07,0x44,0x72,0x04,0x72,0x01,0x21,0x05,0x22,0x12,0x07,0x51,0x72,0x11,0x23, 0xC3,0x70,0xC4,0x70,0x0F,0x23,0x03,0x72,0x41,0x72,0x54,0x72,0xBF,0xF3,0x60,0x8F, 0xFE,0xF7,0x56,0xF9,0x2D,0x48,0x00,0x78,0x00,0x28,0x02,0xD0,0x00,0xF0,0xAB,0xF8, 0xE1,0xE7,0xAC,0x70,0x23,0x48,0x04,0x72,0x06,0x06,0x34,0x70,0x01,0x27,0x37,0x70, 0xFE,0xF7,0x66,0xF9,0xFE,0xF7,0x27,0xFA,0xEC,0x70,0x74,0x70,0x77,0x70,0x72,0xB6, 0xE8,0x78,0x00,0x28,0x23,0xD0,0x62,0xB6,0xFE,0xF7,0x66,0xFD,0xFF,0xF7,0x80,0xF8, 0x18,0x48,0x07,0x72,0x72,0xB6,0xA8,0x78,0x00,0x28,0x1D,0xD0,0x62,0xB6,0x16,0x48, 0x00,0x78,0x00,0x28,0x0C,0xD0,0x15,0xA0,0xFF,0xF7,0xCC,0xF8,0x16,0x4F,0x00,0x26, 0xF0,0x01,0xC1,0x19,0x1A,0x20,0xFF,0xF7,0xF4,0xF8,0x76,0x1C,0x0E,0x2E,0xF7,0xDB, 0x72,0xB6,0x68,0x78,0x00,0x28,0x0C,0xD0,0x62,0xB6,0x6C,0x70,0xAB,0xE7,0x00,0xBF, 0x00,0xBF,0x62,0xB6,0x30,0xBF,0xD2,0xE7,0x00,0xBF,0x00,0xBF,0x62,0xB6,0x30,0xBF, 0xD8,0xE7,0x00,0xBF,0x00,0xBF,0x62,0xB6,0x30,0xBF,0xE9,0xE7,0xA0,0x86,0x01,0x00, 0x24,0x00,0x00,0x20,0x40,0x00,0x00,0x40,0x1A,0x00,0x00,0x20,0x52,0x61,0x77,0x20, 0x49,0x6D,0x61,0x67,0x65,0x00,0x00,0x00,0x04,0x41,0x00,0x40,0x20,0x00,0x00,0x20, 0x58,0x48,0x00,0x78,0x70,0x47,0xF0,0xB5,0xFF,0xB0,0xB8,0xB0,0x01,0x20,0xFF,0xF7, 0x31,0xFC,0x55,0x4C,0x00,0x27,0x36,0x20,0x39,0x46,0x41,0x43,0x53,0x48,0x54,0x4A, 0x08,0x18,0x89,0x18,0x00,0x22,0x1A,0x23,0xFE,0x01,0x55,0x00,0x75,0x19,0x2D,0x19, 0xAD,0x88,0x05,0x80,0x0D,0x80,0x80,0x1C,0x89,0x1C,0x52,0x1C,0x5B,0x1E,0xF4,0xD1, 0x7F,0x1C,0xFF,0xB2,0x0E,0x2F,0xE6,0xD3,0x00,0x20,0xFF,0xF7,0x13,0xFC,0x00,0x20, 0x84,0x46,0x34,0x21,0x48,0x43,0x69,0x46,0x41,0x18,0x60,0x46,0x36,0x22,0x50,0x43, 0x42,0x4A,0x1A,0x23,0x80,0x18,0x00,0x22,0x64,0x46,0xE7,0x01,0x54,0x00,0x3D,0x19, 0x3D,0x4C,0x2C,0x19,0xA4,0x88,0x0C,0x80,0x00,0x25,0x45,0x5F,0x26,0xB2,0xAC,0x1B, 0x02,0xD5,0x74,0x1B,0x04,0x80,0x00,0xE0,0x04,0x80,0x89,0x1C,0x80,0x1C,0x52,0x1C, 0x5B,0x1E,0xEB,0xD1,0x60,0x46,0x40,0x1C,0xC0,0xB2,0x84,0x46,0x0E,0x28,0xD8,0xD3, 0x7F,0xB0,0x38,0xB0,0xF0,0xBD,0xF8,0xB5,0x32,0x49,0x01,0x20,0x48,0x70,0x04,0x20, 0xFF,0xF7,0x07,0xF8,0x00,0x24,0x30,0x4D,0x01,0x28,0x28,0xD0,0x04,0x20,0xFF,0xF7, 0x00,0xF8,0x02,0x28,0x2D,0xD0,0x04,0x20,0xFE,0xF7,0xFB,0xFF,0x03,0x28,0x1D,0xD1, 0x01,0x20,0xFE,0xF7,0xF6,0xFF,0x06,0x46,0x02,0x20,0xFE,0xF7,0xF2,0xFF,0x36,0x21, 0x48,0x43,0x23,0x49,0x76,0x00,0x47,0x18,0xB8,0x5B,0x40,0x04,0x41,0x0E,0x08,0x20, 0xFE,0xF7,0xE4,0xFF,0xB8,0x5B,0xC1,0xB2,0x09,0x20,0xFE,0xF7,0xDF,0xFF,0x00,0x21, 0x04,0x20,0xFE,0xF7,0xDB,0xFF,0xFF,0xF7,0x77,0xFE,0x2C,0x70,0xF8,0xBD,0xFF,0xF7, 0x7A,0xFF,0x00,0x21,0x04,0x20,0xFE,0xF7,0xD1,0xFF,0xFF,0xF7,0x6D,0xFE,0x2C,0x70, 0xF8,0xBD,0x01,0x20,0xFE,0xF7,0xCD,0xFF,0x06,0x46,0x02,0x20,0xFE,0xF7,0xC9,0xFF, 0x36,0x21,0x48,0x43,0x0D,0x49,0x76,0x00,0x47,0x18,0xB8,0x5B,0x40,0x04,0x41,0x0E, 0x08,0x20,0xFE,0xF7,0xBB,0xFF,0xB8,0x5B,0xC1,0xB2,0x09,0x20,0xFE,0xF7,0xB6,0xFF, 0x00,0x21,0x04,0x20,0xFE,0xF7,0xB2,0xFF,0xFF,0xF7,0x4E,0xFE,0x2C,0x70,0xF8,0xBD, 0xA1,0xE7,0x00,0x00,0x28,0x00,0x00,0x20,0x00,0x41,0x00,0x40,0x66,0x0E,0x00,0x20, 0x5A,0x11,0x00,0x20,0x40,0x00,0x00,0x40,0x19,0x00,0x00,0x20,0x30,0xB5,0x0B,0x46, 0x01,0x46,0x00,0x20,0x20,0x22,0x01,0x24,0x09,0xE0,0x0D,0x46,0xD5,0x40,0x9D,0x42, 0x05,0xD3,0x1D,0x46,0x95,0x40,0x49,0x1B,0x25,0x46,0x95,0x40,0x40,0x19,0x15,0x46, 0x52,0x1E,0x00,0x2D,0xF1,0xDC,0x30,0xBD,0x70,0xB5,0x00,0x24,0x25,0x46,0x00,0x28, 0x01,0xDA,0x01,0x24,0x40,0x42,0x00,0x29,0x01,0xDA,0x01,0x25,0x49,0x42,0xFF,0xF7, 0xDD,0xFF,0xAC,0x42,0x00,0xD0,0x40,0x42,0x00,0x2C,0x00,0xD0,0x49,0x42,0x70,0xBD, 0xD2,0xB2,0x01,0xE0,0x02,0x70,0x40,0x1C,0x49,0x1E,0xFB,0xD2,0x70,0x47,0x00,0x22, 0xF6,0xE7,0x10,0xB5,0x04,0x46,0x08,0x46,0x11,0x46,0x02,0x46,0x20,0x46,0xFF,0xF7, 0xEF,0xFF,0x20,0x46,0x10,0xBD,0x01,0x46,0x00,0x20,0x00,0xE0,0x40,0x1C,0x0A,0x5C, 0x00,0x2A,0xFB,0xD1,0x70,0x47,0x00,0x00,0x06,0x4C,0x01,0x25,0x06,0x4E,0x05,0xE0, 0x20,0x46,0xE3,0x68,0x07,0xC8,0x2B,0x43,0x98,0x47,0x10,0x34,0xB4,0x42,0xF7,0xD3, 0xFD,0xF7,0xB2,0xFF,0xB0,0x21,0x00,0x00,0xD0,0x21,0x00,0x00,0x02,0xE0,0x08,0xC8, 0x12,0x1F,0x08,0xC1,0x00,0x2A,0xFA,0xD1,0x70,0x47,0x00,0x20,0x01,0xE0,0x01,0xC1, 0x12,0x1F,0x00,0x2A,0xFB,0xD1,0x70,0x47,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x0A, 0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x19,0x1A,0x1B,0x1C,0x1D, 0x1E,0x1F,0x02,0x04,0x06,0x08,0x0C,0x0E,0x10,0x03,0x05,0x07,0x0B,0x0D,0x0F,0x11, 0xD0,0x21,0x00,0x00,0x00,0x00,0x00,0x20,0x2C,0x00,0x00,0x00,0x6C,0x21,0x00,0x00, 0xFC,0x21,0x00,0x00,0x2C,0x00,0x00,0x20,0x24,0x14,0x00,0x00,0x7A,0x21,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, };
/* PR middle-end/47893 */ /* { dg-do run } */ /* { dg-options "-O2" } */ /* { dg-options "-O2 -mtune=atom -fno-omit-frame-pointer -fno-strict-aliasing" { target { { i?86-*-* x86_64-*-* } && ilp32 } } } */ extern void abort (void); struct S { unsigned s1:4, s2:2, s3:2, s4:2, s5:2, s6:1, s7:1, s8:1, s9:1, s10:1; int s11:16; unsigned s12:4; int s13:16; unsigned s14:2; int s15:16; unsigned s16:4; int s17:16; unsigned s18:2; }; struct T { unsigned t[3]; }; struct U { unsigned u1, u2; }; struct V; struct W { char w1[24]; struct V *w2; unsigned w3; char w4[28912]; unsigned int w5; char w6[60]; }; struct X { unsigned int x[2]; }; struct V { int v1; struct X v2[3]; char v3[28]; }; struct Y { void *y1; char y2[3076]; struct T y3[32]; char y4[1052]; }; volatile struct S v1 = { .s15 = -1, .s16 = 15, .s17 = -1, .s18 = 3 }; __attribute__ ((noinline, noclone)) int fn1 (int x) { int r; __asm__ volatile ("" : "=r" (r) : "0" (1), "r" (x) : "memory"); return r; } volatile int cnt; __attribute__ ((noinline, noclone)) #ifdef __i386__ __attribute__ ((regparm (2))) #endif struct S fn2 (struct Y *x, const struct X *y) { if (++cnt > 1) abort (); __asm__ volatile ("" : : "r" (x), "r" (y) : "memory"); return v1; } __attribute__ ((noinline, noclone)) void fn3 (void *x, unsigned y, const struct S *z, unsigned w) { __asm__ volatile ("" : : "r" (x), "r" (y), "r" (z), "r" (w) : "memory"); } volatile struct U v2; __attribute__ ((noinline, noclone)) struct U fn4 (void *x, unsigned y) { __asm__ volatile ("" : : "r" (x), "r" (y) : "memory"); return v2; } __attribute__ ((noinline, noclone)) struct S fn5 (void *x) { __asm__ volatile ("" : : "r" (x) : "memory"); return v1; } volatile struct T v3; __attribute__ ((noinline, noclone)) struct T fn6 (void *x) { __asm__ volatile ("" : : "r" (x) : "memory"); return v3; } __attribute__ ((noinline, noclone)) struct T fn7 (void *x, unsigned y, unsigned z) { __asm__ volatile ("" : : "r" (x), "r" (y), "r" (z) : "memory"); return v3; } static void fn8 (struct Y *x, const struct V *y) { void *a = x->y1; struct S b[4]; unsigned i, c; c = fn1 (y->v1); for (i = 0; i < c; i++) b[i] = fn2 (x, &y->v2[i]); fn3 (a, y->v1, b, c); } static inline void fn9 (void *x, struct S y __attribute__((unused))) { fn4 (x, 8); } static void fn10 (struct Y *x) { void *a = x->y1; struct T b __attribute__((unused)) = fn6 (a); fn9 (a, fn5 (a)); } __attribute__((noinline, noclone)) int fn11 (unsigned int x, void *y, const struct W *z, unsigned int w, const char *v, const char *u) { struct Y a, *t; unsigned i; t = &a; __builtin_memset (t, 0, sizeof *t); t->y1 = y; if (x == 0) { if (z->w3 & 1) fn10 (t); for (i = 0; i < w; i++) { if (v[i] == 0) t->y3[i] = fn7 (y, 0, u[i]); else return 0; } } else for (i = 0; i < w; i++) t->y3[i] = fn7 (y, v[i], u[i]); for (i = 0; i < z->w5; i++) fn8 (t, &z->w2[i]); return 0; } volatile int i; const char *volatile p = ""; int main () { struct V v = { .v1 = 0 }; struct W w = { .w5 = 1, .w2 = &v }; fn11 (i + 1, (void *) p, &w, i, (const char *) p, (const char *) p); if (cnt != 1) abort (); return 0; }
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #if HAS_SPI_TFT || HAS_FSMC_TFT #error "Sorry! TFT displays are not available for HAL/TEENSY35_36." #endif
/* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.security.cert; import java.io.IOException; import sun.security.util.HexDumpEncoder; import sun.security.util.DerValue; /** * An immutable policy qualifier represented by the ASN.1 PolicyQualifierInfo * structure. * * <p>The ASN.1 definition is as follows: * <pre> * PolicyQualifierInfo ::= SEQUENCE { * policyQualifierId PolicyQualifierId, * qualifier ANY DEFINED BY policyQualifierId } * </pre> * <p> * A certificate policies extension, if present in an X.509 version 3 * certificate, contains a sequence of one or more policy information terms, * each of which consists of an object identifier (OID) and optional * qualifiers. In an end-entity certificate, these policy information terms * indicate the policy under which the certificate has been issued and the * purposes for which the certificate may be used. In a CA certificate, these * policy information terms limit the set of policies for certification paths * which include this certificate. * <p> * A {@code Set} of {@code PolicyQualifierInfo} objects are returned * by the {@link PolicyNode#getPolicyQualifiers PolicyNode.getPolicyQualifiers} * method. This allows applications with specific policy requirements to * process and validate each policy qualifier. Applications that need to * process policy qualifiers should explicitly set the * {@code policyQualifiersRejected} flag to false (by calling the * {@link PKIXParameters#setPolicyQualifiersRejected * PKIXParameters.setPolicyQualifiersRejected} method) before validating * a certification path. * * <p>Note that the PKIX certification path validation algorithm specifies * that any policy qualifier in a certificate policies extension that is * marked critical must be processed and validated. Otherwise the * certification path must be rejected. If the * {@code policyQualifiersRejected} flag is set to false, it is up to * the application to validate all policy qualifiers in this manner in order * to be PKIX compliant. * * <p><b>Concurrent Access</b> * * <p>All {@code PolicyQualifierInfo} objects must be immutable and * thread-safe. That is, multiple threads may concurrently invoke the * methods defined in this class on a single {@code PolicyQualifierInfo} * object (or more than one) with no ill effects. Requiring * {@code PolicyQualifierInfo} objects to be immutable and thread-safe * allows them to be passed around to various pieces of code without * worrying about coordinating access. * * @author seth proctor * @author Sean Mullan * @since 1.4 */ public class PolicyQualifierInfo { private byte [] mEncoded; private String mId; private byte [] mData; private String pqiString; /** * Creates an instance of {@code PolicyQualifierInfo} from the * encoded bytes. The encoded byte array is copied on construction. * * @param encoded a byte array containing the qualifier in DER encoding * @exception IOException thrown if the byte array does not represent a * valid and parsable policy qualifier */ public PolicyQualifierInfo(byte[] encoded) throws IOException { mEncoded = encoded.clone(); DerValue val = new DerValue(mEncoded); if (val.tag != DerValue.tag_Sequence) throw new IOException("Invalid encoding for PolicyQualifierInfo"); mId = (val.data.getDerValue()).getOID().toString(); byte [] tmp = val.data.toByteArray(); if (tmp == null) { mData = null; } else { mData = new byte[tmp.length]; System.arraycopy(tmp, 0, mData, 0, tmp.length); } } /** * Returns the {@code policyQualifierId} field of this * {@code PolicyQualifierInfo}. The {@code policyQualifierId} * is an Object Identifier (OID) represented by a set of nonnegative * integers separated by periods. * * @return the OID (never {@code null}) */ public final String getPolicyQualifierId() { return mId; } /** * Returns the ASN.1 DER encoded form of this * {@code PolicyQualifierInfo}. * * @return the ASN.1 DER encoded bytes (never {@code null}). * Note that a copy is returned, so the data is cloned each time * this method is called. */ public final byte[] getEncoded() { return mEncoded.clone(); } /** * Returns the ASN.1 DER encoded form of the {@code qualifier} * field of this {@code PolicyQualifierInfo}. * * @return the ASN.1 DER encoded bytes of the {@code qualifier} * field. Note that a copy is returned, so the data is cloned each * time this method is called. */ public final byte[] getPolicyQualifier() { return (mData == null ? null : mData.clone()); } /** * Return a printable representation of this * {@code PolicyQualifierInfo}. * * @return a {@code String} describing the contents of this * {@code PolicyQualifierInfo} */ public String toString() { if (pqiString != null) return pqiString; HexDumpEncoder enc = new HexDumpEncoder(); StringBuilder sb = new StringBuilder(); sb.append("PolicyQualifierInfo: [\n"); sb.append(" qualifierID: " + mId + "\n"); sb.append(" qualifier: " + (mData == null ? "null" : enc.encodeBuffer(mData)) + "\n"); sb.append("]"); pqiString = sb.toString(); return pqiString; } }
/* * NSA Security-Enhanced Linux (SELinux) security module * * This file contains the SELinux hook function implementations. * * Authors: Stephen Smalley, <sds@epoch.ncsc.mil> * Chris Vance, <cvance@nai.com> * Wayne Salamon, <wsalamon@nai.com> * James Morris <jmorris@redhat.com> * * Copyright (C) 2001,2002 Networks Associates Technology, Inc. * Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com> * Eric Paris <eparis@redhat.com> * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc. * <dgoeddel@trustedcs.com> * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P. * Paul Moore <paul.moore@hp.com> * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd. * Yuichi Nakamura <ynakam@hitachisoft.jp> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/kd.h> #include <linux/kernel.h> #include <linux/tracehook.h> #include <linux/errno.h> #include <linux/ext2_fs.h> #include <linux/sched.h> #include <linux/security.h> #include <linux/xattr.h> #include <linux/capability.h> #include <linux/unistd.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/proc_fs.h> #include <linux/swap.h> #include <linux/spinlock.h> #include <linux/syscalls.h> #include <linux/dcache.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/namei.h> #include <linux/mount.h> #include <linux/netfilter_ipv4.h> #include <linux/netfilter_ipv6.h> #include <linux/tty.h> #include <net/icmp.h> #include <net/ip.h> /* for local_port_range[] */ #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */ #include <net/net_namespace.h> #include <net/netlabel.h> #include <linux/uaccess.h> #include <asm/ioctls.h> #include <asm/atomic.h> #include <linux/bitops.h> #include <linux/interrupt.h> #include <linux/netdevice.h> /* for network interface checks */ #include <linux/netlink.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/dccp.h> #include <linux/quota.h> #include <linux/un.h> /* for Unix socket types */ #include <net/af_unix.h> /* for Unix socket types */ #include <linux/parser.h> #include <linux/nfs_mount.h> #include <net/ipv6.h> #include <linux/hugetlb.h> #include <linux/personality.h> #include <linux/audit.h> #include <linux/string.h> #include <linux/selinux.h> #include <linux/mutex.h> #include <linux/posix-timers.h> #include <linux/syslog.h> #include <linux/user_namespace.h> #include "avc.h" #include "objsec.h" #include "netif.h" #include "netnode.h" #include "netport.h" #include "xfrm.h" #include "netlabel.h" #include "audit.h" #define NUM_SEL_MNT_OPTS 5 extern int selinux_nlmsg_lookup(u16 sclass, u16 nlmsg_type, u32 *perm); extern struct security_operations *security_ops; /* SECMARK reference count */ atomic_t selinux_secmark_refcount = ATOMIC_INIT(0); #ifdef CONFIG_SECURITY_SELINUX_DEVELOP int selinux_enforcing; static int __init enforcing_setup(char *str) { unsigned long enforcing; if (!strict_strtoul(str, 0, &enforcing)) selinux_enforcing = enforcing ? 1 : 0; return 1; } __setup("enforcing=", enforcing_setup); #endif #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM int selinux_enabled = CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE; static int __init selinux_enabled_setup(char *str) { unsigned long enabled; if (!strict_strtoul(str, 0, &enabled)) selinux_enabled = enabled ? 1 : 0; return 1; } __setup("selinux=", selinux_enabled_setup); #else int selinux_enabled = 1; #endif static struct kmem_cache *sel_inode_cache; /** * selinux_secmark_enabled - Check to see if SECMARK is currently enabled * * Description: * This function checks the SECMARK reference counter to see if any SECMARK * targets are currently configured, if the reference counter is greater than * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is * enabled, false (0) if SECMARK is disabled. * */ static int selinux_secmark_enabled(void) { return (atomic_read(&selinux_secmark_refcount) > 0); } /* * initialise the security for the init task */ static void cred_init_security(void) { struct cred *cred = (struct cred *) current->real_cred; struct task_security_struct *tsec; tsec = kzalloc(sizeof(struct task_security_struct), GFP_KERNEL); if (!tsec) panic("SELinux: Failed to initialize initial task.\n"); tsec->osid = tsec->sid = SECINITSID_KERNEL; cred->security = tsec; } /* * get the security ID of a set of credentials */ static inline u32 cred_sid(const struct cred *cred) { const struct task_security_struct *tsec; tsec = cred->security; return tsec->sid; } /* * get the objective security ID of a task */ static inline u32 task_sid(const struct task_struct *task) { u32 sid; rcu_read_lock(); sid = cred_sid(__task_cred(task)); rcu_read_unlock(); return sid; } /* * get the subjective security ID of the current task */ static inline u32 current_sid(void) { const struct task_security_struct *tsec = current_security(); return tsec->sid; } /* Allocate and free functions for each kind of security blob. */ static int inode_alloc_security(struct inode *inode) { struct inode_security_struct *isec; u32 sid = current_sid(); isec = kmem_cache_zalloc(sel_inode_cache, GFP_NOFS); if (!isec) return -ENOMEM; mutex_init(&isec->lock); INIT_LIST_HEAD(&isec->list); isec->inode = inode; isec->sid = SECINITSID_UNLABELED; isec->sclass = SECCLASS_FILE; isec->task_sid = sid; inode->i_security = isec; return 0; } static void inode_free_rcu(struct rcu_head *head) { struct inode_security_struct *isec; isec = container_of(head, struct inode_security_struct, rcu); kmem_cache_free(sel_inode_cache, isec); } static void inode_free_security(struct inode *inode) { struct inode_security_struct *isec = inode->i_security; struct superblock_security_struct *sbsec = inode->i_sb->s_security; spin_lock(&sbsec->isec_lock); if (!list_empty(&isec->list)) list_del_init(&isec->list); spin_unlock(&sbsec->isec_lock); /* * The inode may still be referenced in a path walk and * a call to selinux_inode_permission() can be made * after inode_free_security() is called. Ideally, the VFS * wouldn't do this, but fixing that is a much harder * job. For now, simply free the i_security via RCU, and * leave the current inode->i_security pointer intact. * The inode will be freed after the RCU grace period too. */ call_rcu(&isec->rcu, inode_free_rcu); } static int file_alloc_security(struct file *file) { struct file_security_struct *fsec; u32 sid = current_sid(); fsec = kzalloc(sizeof(struct file_security_struct), GFP_KERNEL); if (!fsec) return -ENOMEM; fsec->sid = sid; fsec->fown_sid = sid; file->f_security = fsec; return 0; } static void file_free_security(struct file *file) { struct file_security_struct *fsec = file->f_security; file->f_security = NULL; kfree(fsec); } static int superblock_alloc_security(struct super_block *sb) { struct superblock_security_struct *sbsec; sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL); if (!sbsec) return -ENOMEM; mutex_init(&sbsec->lock); INIT_LIST_HEAD(&sbsec->isec_head); spin_lock_init(&sbsec->isec_lock); sbsec->sb = sb; sbsec->sid = SECINITSID_UNLABELED; sbsec->def_sid = SECINITSID_FILE; sbsec->mntpoint_sid = SECINITSID_UNLABELED; sb->s_security = sbsec; return 0; } static void superblock_free_security(struct super_block *sb) { struct superblock_security_struct *sbsec = sb->s_security; sb->s_security = NULL; kfree(sbsec); } /* The security server must be initialized before any labeling or access decisions can be provided. */ extern int ss_initialized; /* The file system's label must be initialized prior to use. */ static const char *labeling_behaviors[6] = { "uses xattr", "uses transition SIDs", "uses task SIDs", "uses genfs_contexts", "not configured for labeling", "uses mountpoint labeling", }; static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry); static inline int inode_doinit(struct inode *inode) { return inode_doinit_with_dentry(inode, NULL); } enum { Opt_error = -1, Opt_context = 1, Opt_fscontext = 2, Opt_defcontext = 3, Opt_rootcontext = 4, Opt_labelsupport = 5, }; static const match_table_t tokens = { {Opt_context, CONTEXT_STR "%s"}, {Opt_fscontext, FSCONTEXT_STR "%s"}, {Opt_defcontext, DEFCONTEXT_STR "%s"}, {Opt_rootcontext, ROOTCONTEXT_STR "%s"}, {Opt_labelsupport, LABELSUPP_STR}, {Opt_error, NULL}, }; #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n" static int may_context_mount_sb_relabel(u32 sid, struct superblock_security_struct *sbsec, const struct cred *cred) { const struct task_security_struct *tsec = cred->security; int rc; rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM, FILESYSTEM__RELABELFROM, NULL); if (rc) return rc; rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM, FILESYSTEM__RELABELTO, NULL); return rc; } static int may_context_mount_inode_relabel(u32 sid, struct superblock_security_struct *sbsec, const struct cred *cred) { const struct task_security_struct *tsec = cred->security; int rc; rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM, FILESYSTEM__RELABELFROM, NULL); if (rc) return rc; rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, FILESYSTEM__ASSOCIATE, NULL); return rc; } static int sb_finish_set_opts(struct super_block *sb) { struct superblock_security_struct *sbsec = sb->s_security; struct dentry *root = sb->s_root; struct inode *root_inode = root->d_inode; int rc = 0; if (sbsec->behavior == SECURITY_FS_USE_XATTR) { /* Make sure that the xattr handler exists and that no error other than -ENODATA is returned by getxattr on the root directory. -ENODATA is ok, as this may be the first boot of the SELinux kernel before we have assigned xattr values to the filesystem. */ if (!root_inode->i_op->getxattr) { printk(KERN_WARNING "SELinux: (dev %s, type %s) has no " "xattr support\n", sb->s_id, sb->s_type->name); rc = -EOPNOTSUPP; goto out; } rc = root_inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0); if (rc < 0 && rc != -ENODATA) { if (rc == -EOPNOTSUPP) printk(KERN_WARNING "SELinux: (dev %s, type " "%s) has no security xattr handler\n", sb->s_id, sb->s_type->name); else printk(KERN_WARNING "SELinux: (dev %s, type " "%s) getxattr errno %d\n", sb->s_id, sb->s_type->name, -rc); goto out; } } sbsec->flags |= (SE_SBINITIALIZED | SE_SBLABELSUPP); if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors)) printk(KERN_ERR "SELinux: initialized (dev %s, type %s), unknown behavior\n", sb->s_id, sb->s_type->name); else printk(KERN_DEBUG "SELinux: initialized (dev %s, type %s), %s\n", sb->s_id, sb->s_type->name, labeling_behaviors[sbsec->behavior-1]); if (sbsec->behavior == SECURITY_FS_USE_GENFS || sbsec->behavior == SECURITY_FS_USE_MNTPOINT || sbsec->behavior == SECURITY_FS_USE_NONE || sbsec->behavior > ARRAY_SIZE(labeling_behaviors)) sbsec->flags &= ~SE_SBLABELSUPP; /* Special handling. Is genfs but also has in-core setxattr handler*/ if (!strcmp(sb->s_type->name, "sysfs") || !strcmp(sb->s_type->name, "pstore") || !strcmp(sb->s_type->name, "debugfs") || !strcmp(sb->s_type->name, "rootfs")) sbsec->flags |= SE_SBLABELSUPP; /* Initialize the root inode. */ rc = inode_doinit_with_dentry(root_inode, root); /* Initialize any other inodes associated with the superblock, e.g. inodes created prior to initial policy load or inodes created during get_sb by a pseudo filesystem that directly populates itself. */ spin_lock(&sbsec->isec_lock); next_inode: if (!list_empty(&sbsec->isec_head)) { struct inode_security_struct *isec = list_entry(sbsec->isec_head.next, struct inode_security_struct, list); struct inode *inode = isec->inode; list_del_init(&isec->list); spin_unlock(&sbsec->isec_lock); inode = igrab(inode); if (inode) { if (!IS_PRIVATE(inode)) inode_doinit(inode); iput(inode); } spin_lock(&sbsec->isec_lock); goto next_inode; } spin_unlock(&sbsec->isec_lock); out: return rc; } /* * This function should allow an FS to ask what it's mount security * options were so it can use those later for submounts, displaying * mount options, or whatever. */ static int selinux_get_mnt_opts(const struct super_block *sb, struct security_mnt_opts *opts) { int rc = 0, i; struct superblock_security_struct *sbsec = sb->s_security; char *context = NULL; u32 len; char tmp; security_init_mnt_opts(opts); if (!(sbsec->flags & SE_SBINITIALIZED)) return -EINVAL; if (!ss_initialized) return -EINVAL; tmp = sbsec->flags & SE_MNTMASK; /* count the number of mount options for this sb */ for (i = 0; i < 8; i++) { if (tmp & 0x01) opts->num_mnt_opts++; tmp >>= 1; } /* Check if the Label support flag is set */ if (sbsec->flags & SE_SBLABELSUPP) opts->num_mnt_opts++; opts->mnt_opts = kcalloc(opts->num_mnt_opts, sizeof(char *), GFP_ATOMIC); if (!opts->mnt_opts) { rc = -ENOMEM; goto out_free; } opts->mnt_opts_flags = kcalloc(opts->num_mnt_opts, sizeof(int), GFP_ATOMIC); if (!opts->mnt_opts_flags) { rc = -ENOMEM; goto out_free; } i = 0; if (sbsec->flags & FSCONTEXT_MNT) { rc = security_sid_to_context(sbsec->sid, &context, &len); if (rc) goto out_free; opts->mnt_opts[i] = context; opts->mnt_opts_flags[i++] = FSCONTEXT_MNT; } if (sbsec->flags & CONTEXT_MNT) { rc = security_sid_to_context(sbsec->mntpoint_sid, &context, &len); if (rc) goto out_free; opts->mnt_opts[i] = context; opts->mnt_opts_flags[i++] = CONTEXT_MNT; } if (sbsec->flags & DEFCONTEXT_MNT) { rc = security_sid_to_context(sbsec->def_sid, &context, &len); if (rc) goto out_free; opts->mnt_opts[i] = context; opts->mnt_opts_flags[i++] = DEFCONTEXT_MNT; } if (sbsec->flags & ROOTCONTEXT_MNT) { struct inode *root = sbsec->sb->s_root->d_inode; struct inode_security_struct *isec = root->i_security; rc = security_sid_to_context(isec->sid, &context, &len); if (rc) goto out_free; opts->mnt_opts[i] = context; opts->mnt_opts_flags[i++] = ROOTCONTEXT_MNT; } if (sbsec->flags & SE_SBLABELSUPP) { opts->mnt_opts[i] = NULL; opts->mnt_opts_flags[i++] = SE_SBLABELSUPP; } BUG_ON(i != opts->num_mnt_opts); return 0; out_free: security_free_mnt_opts(opts); return rc; } static int bad_option(struct superblock_security_struct *sbsec, char flag, u32 old_sid, u32 new_sid) { char mnt_flags = sbsec->flags & SE_MNTMASK; /* check if the old mount command had the same options */ if (sbsec->flags & SE_SBINITIALIZED) if (!(sbsec->flags & flag) || (old_sid != new_sid)) return 1; /* check if we were passed the same options twice, * aka someone passed context=a,context=b */ if (!(sbsec->flags & SE_SBINITIALIZED)) if (mnt_flags & flag) return 1; return 0; } /* * Allow filesystems with binary mount data to explicitly set mount point * labeling information. */ static int selinux_set_mnt_opts(struct super_block *sb, struct security_mnt_opts *opts) { const struct cred *cred = current_cred(); int rc = 0, i; struct superblock_security_struct *sbsec = sb->s_security; const char *name = sb->s_type->name; struct inode *inode = sbsec->sb->s_root->d_inode; struct inode_security_struct *root_isec = inode->i_security; u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0; u32 defcontext_sid = 0; char **mount_options = opts->mnt_opts; int *flags = opts->mnt_opts_flags; int num_opts = opts->num_mnt_opts; mutex_lock(&sbsec->lock); if (!ss_initialized) { if (!num_opts) { /* Defer initialization until selinux_complete_init, after the initial policy is loaded and the security server is ready to handle calls. */ goto out; } rc = -EINVAL; printk(KERN_WARNING "SELinux: Unable to set superblock options " "before the security server is initialized\n"); goto out; } /* * Binary mount data FS will come through this function twice. Once * from an explicit call and once from the generic calls from the vfs. * Since the generic VFS calls will not contain any security mount data * we need to skip the double mount verification. * * This does open a hole in which we will not notice if the first * mount using this sb set explict options and a second mount using * this sb does not set any security options. (The first options * will be used for both mounts) */ if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA) && (num_opts == 0)) goto out; /* * parse the mount options, check if they are valid sids. * also check if someone is trying to mount the same sb more * than once with different security options. */ for (i = 0; i < num_opts; i++) { u32 sid; if (flags[i] == SE_SBLABELSUPP) continue; rc = security_context_to_sid(mount_options[i], strlen(mount_options[i]), &sid); if (rc) { printk(KERN_WARNING "SELinux: security_context_to_sid" "(%s) failed for (dev %s, type %s) errno=%d\n", mount_options[i], sb->s_id, name, rc); goto out; } switch (flags[i]) { case FSCONTEXT_MNT: fscontext_sid = sid; if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, fscontext_sid)) goto out_double_mount; sbsec->flags |= FSCONTEXT_MNT; break; case CONTEXT_MNT: context_sid = sid; if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, context_sid)) goto out_double_mount; sbsec->flags |= CONTEXT_MNT; break; case ROOTCONTEXT_MNT: rootcontext_sid = sid; if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, rootcontext_sid)) goto out_double_mount; sbsec->flags |= ROOTCONTEXT_MNT; break; case DEFCONTEXT_MNT: defcontext_sid = sid; if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, defcontext_sid)) goto out_double_mount; sbsec->flags |= DEFCONTEXT_MNT; break; default: rc = -EINVAL; goto out; } } if (sbsec->flags & SE_SBINITIALIZED) { /* previously mounted with options, but not on this attempt? */ if ((sbsec->flags & SE_MNTMASK) && !num_opts) goto out_double_mount; rc = 0; goto out; } if (strcmp(sb->s_type->name, "proc") == 0) sbsec->flags |= SE_SBPROC; /* Determine the labeling behavior to use for this filesystem type. */ rc = security_fs_use((sbsec->flags & SE_SBPROC) ? "proc" : sb->s_type->name, &sbsec->behavior, &sbsec->sid); if (rc) { printk(KERN_WARNING "%s: security_fs_use(%s) returned %d\n", __func__, sb->s_type->name, rc); goto out; } /* sets the context of the superblock for the fs being mounted. */ if (fscontext_sid) { rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred); if (rc) goto out; sbsec->sid = fscontext_sid; } /* * Switch to using mount point labeling behavior. * sets the label used on all file below the mountpoint, and will set * the superblock context if not already set. */ if (context_sid) { if (!fscontext_sid) { rc = may_context_mount_sb_relabel(context_sid, sbsec, cred); if (rc) goto out; sbsec->sid = context_sid; } else { rc = may_context_mount_inode_relabel(context_sid, sbsec, cred); if (rc) goto out; } if (!rootcontext_sid) rootcontext_sid = context_sid; sbsec->mntpoint_sid = context_sid; sbsec->behavior = SECURITY_FS_USE_MNTPOINT; } if (rootcontext_sid) { rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec, cred); if (rc) goto out; root_isec->sid = rootcontext_sid; root_isec->initialized = 1; } if (defcontext_sid) { if (sbsec->behavior != SECURITY_FS_USE_XATTR) { rc = -EINVAL; printk(KERN_WARNING "SELinux: defcontext option is " "invalid for this filesystem type\n"); goto out; } if (defcontext_sid != sbsec->def_sid) { rc = may_context_mount_inode_relabel(defcontext_sid, sbsec, cred); if (rc) goto out; } sbsec->def_sid = defcontext_sid; } rc = sb_finish_set_opts(sb); out: mutex_unlock(&sbsec->lock); return rc; out_double_mount: rc = -EINVAL; printk(KERN_WARNING "SELinux: mount invalid. Same superblock, different " "security settings for (dev %s, type %s)\n", sb->s_id, name); goto out; } static void selinux_sb_clone_mnt_opts(const struct super_block *oldsb, struct super_block *newsb) { const struct superblock_security_struct *oldsbsec = oldsb->s_security; struct superblock_security_struct *newsbsec = newsb->s_security; int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT); int set_context = (oldsbsec->flags & CONTEXT_MNT); int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT); /* * if the parent was able to be mounted it clearly had no special lsm * mount options. thus we can safely deal with this superblock later */ if (!ss_initialized) return; /* how can we clone if the old one wasn't set up?? */ BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED)); /* if fs is reusing a sb, just let its options stand... */ if (newsbsec->flags & SE_SBINITIALIZED) return; mutex_lock(&newsbsec->lock); newsbsec->flags = oldsbsec->flags; newsbsec->sid = oldsbsec->sid; newsbsec->def_sid = oldsbsec->def_sid; newsbsec->behavior = oldsbsec->behavior; if (set_context) { u32 sid = oldsbsec->mntpoint_sid; if (!set_fscontext) newsbsec->sid = sid; if (!set_rootcontext) { struct inode *newinode = newsb->s_root->d_inode; struct inode_security_struct *newisec = newinode->i_security; newisec->sid = sid; } newsbsec->mntpoint_sid = sid; } if (set_rootcontext) { const struct inode *oldinode = oldsb->s_root->d_inode; const struct inode_security_struct *oldisec = oldinode->i_security; struct inode *newinode = newsb->s_root->d_inode; struct inode_security_struct *newisec = newinode->i_security; newisec->sid = oldisec->sid; } sb_finish_set_opts(newsb); mutex_unlock(&newsbsec->lock); } static int selinux_parse_opts_str(char *options, struct security_mnt_opts *opts) { char *p; char *context = NULL, *defcontext = NULL; char *fscontext = NULL, *rootcontext = NULL; int rc, num_mnt_opts = 0; opts->num_mnt_opts = 0; /* Standard string-based options. */ while ((p = strsep(&options, "|")) != NULL) { int token; substring_t args[MAX_OPT_ARGS]; if (!*p) continue; token = match_token(p, tokens, args); switch (token) { case Opt_context: if (context || defcontext) { rc = -EINVAL; printk(KERN_WARNING SEL_MOUNT_FAIL_MSG); goto out_err; } context = match_strdup(&args[0]); if (!context) { rc = -ENOMEM; goto out_err; } break; case Opt_fscontext: if (fscontext) { rc = -EINVAL; printk(KERN_WARNING SEL_MOUNT_FAIL_MSG); goto out_err; } fscontext = match_strdup(&args[0]); if (!fscontext) { rc = -ENOMEM; goto out_err; } break; case Opt_rootcontext: if (rootcontext) { rc = -EINVAL; printk(KERN_WARNING SEL_MOUNT_FAIL_MSG); goto out_err; } rootcontext = match_strdup(&args[0]); if (!rootcontext) { rc = -ENOMEM; goto out_err; } break; case Opt_defcontext: if (context || defcontext) { rc = -EINVAL; printk(KERN_WARNING SEL_MOUNT_FAIL_MSG); goto out_err; } defcontext = match_strdup(&args[0]); if (!defcontext) { rc = -ENOMEM; goto out_err; } break; case Opt_labelsupport: break; default: rc = -EINVAL; printk(KERN_WARNING "SELinux: unknown mount option\n"); goto out_err; } } rc = -ENOMEM; opts->mnt_opts = kcalloc(NUM_SEL_MNT_OPTS, sizeof(char *), GFP_ATOMIC); if (!opts->mnt_opts) goto out_err; opts->mnt_opts_flags = kcalloc(NUM_SEL_MNT_OPTS, sizeof(int), GFP_ATOMIC); if (!opts->mnt_opts_flags) { kfree(opts->mnt_opts); goto out_err; } if (fscontext) { opts->mnt_opts[num_mnt_opts] = fscontext; opts->mnt_opts_flags[num_mnt_opts++] = FSCONTEXT_MNT; } if (context) { opts->mnt_opts[num_mnt_opts] = context; opts->mnt_opts_flags[num_mnt_opts++] = CONTEXT_MNT; } if (rootcontext) { opts->mnt_opts[num_mnt_opts] = rootcontext; opts->mnt_opts_flags[num_mnt_opts++] = ROOTCONTEXT_MNT; } if (defcontext) { opts->mnt_opts[num_mnt_opts] = defcontext; opts->mnt_opts_flags[num_mnt_opts++] = DEFCONTEXT_MNT; } opts->num_mnt_opts = num_mnt_opts; return 0; out_err: kfree(context); kfree(defcontext); kfree(fscontext); kfree(rootcontext); return rc; } /* * string mount options parsing and call set the sbsec */ static int superblock_doinit(struct super_block *sb, void *data) { int rc = 0; char *options = data; struct security_mnt_opts opts; security_init_mnt_opts(&opts); if (!data) goto out; BUG_ON(sb->s_type->fs_flags & FS_BINARY_MOUNTDATA); rc = selinux_parse_opts_str(options, &opts); if (rc) goto out_err; out: rc = selinux_set_mnt_opts(sb, &opts); out_err: security_free_mnt_opts(&opts); return rc; } static void selinux_write_opts(struct seq_file *m, struct security_mnt_opts *opts) { int i; char *prefix; for (i = 0; i < opts->num_mnt_opts; i++) { char *has_comma; if (opts->mnt_opts[i]) has_comma = strchr(opts->mnt_opts[i], ','); else has_comma = NULL; switch (opts->mnt_opts_flags[i]) { case CONTEXT_MNT: prefix = CONTEXT_STR; break; case FSCONTEXT_MNT: prefix = FSCONTEXT_STR; break; case ROOTCONTEXT_MNT: prefix = ROOTCONTEXT_STR; break; case DEFCONTEXT_MNT: prefix = DEFCONTEXT_STR; break; case SE_SBLABELSUPP: seq_putc(m, ','); seq_puts(m, LABELSUPP_STR); continue; default: BUG(); return; }; /* we need a comma before each option */ seq_putc(m, ','); seq_puts(m, prefix); if (has_comma) seq_putc(m, '\"'); seq_puts(m, opts->mnt_opts[i]); if (has_comma) seq_putc(m, '\"'); } } static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb) { struct security_mnt_opts opts; int rc; rc = selinux_get_mnt_opts(sb, &opts); if (rc) { /* before policy load we may get EINVAL, don't show anything */ if (rc == -EINVAL) rc = 0; return rc; } selinux_write_opts(m, &opts); security_free_mnt_opts(&opts); return rc; } static inline u16 inode_mode_to_security_class(umode_t mode) { switch (mode & S_IFMT) { case S_IFSOCK: return SECCLASS_SOCK_FILE; case S_IFLNK: return SECCLASS_LNK_FILE; case S_IFREG: return SECCLASS_FILE; case S_IFBLK: return SECCLASS_BLK_FILE; case S_IFDIR: return SECCLASS_DIR; case S_IFCHR: return SECCLASS_CHR_FILE; case S_IFIFO: return SECCLASS_FIFO_FILE; } return SECCLASS_FILE; } static inline int default_protocol_stream(int protocol) { return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP); } static inline int default_protocol_dgram(int protocol) { return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP); } static inline u16 socket_type_to_security_class(int family, int type, int protocol) { switch (family) { case PF_UNIX: switch (type) { case SOCK_STREAM: case SOCK_SEQPACKET: return SECCLASS_UNIX_STREAM_SOCKET; case SOCK_DGRAM: return SECCLASS_UNIX_DGRAM_SOCKET; } break; case PF_INET: case PF_INET6: switch (type) { case SOCK_STREAM: if (default_protocol_stream(protocol)) return SECCLASS_TCP_SOCKET; else return SECCLASS_RAWIP_SOCKET; case SOCK_DGRAM: if (default_protocol_dgram(protocol)) return SECCLASS_UDP_SOCKET; else return SECCLASS_RAWIP_SOCKET; case SOCK_DCCP: return SECCLASS_DCCP_SOCKET; default: return SECCLASS_RAWIP_SOCKET; } break; case PF_NETLINK: switch (protocol) { case NETLINK_ROUTE: return SECCLASS_NETLINK_ROUTE_SOCKET; case NETLINK_FIREWALL: return SECCLASS_NETLINK_FIREWALL_SOCKET; case NETLINK_INET_DIAG: return SECCLASS_NETLINK_TCPDIAG_SOCKET; case NETLINK_NFLOG: return SECCLASS_NETLINK_NFLOG_SOCKET; case NETLINK_XFRM: return SECCLASS_NETLINK_XFRM_SOCKET; case NETLINK_SELINUX: return SECCLASS_NETLINK_SELINUX_SOCKET; case NETLINK_AUDIT: return SECCLASS_NETLINK_AUDIT_SOCKET; case NETLINK_IP6_FW: return SECCLASS_NETLINK_IP6FW_SOCKET; case NETLINK_DNRTMSG: return SECCLASS_NETLINK_DNRT_SOCKET; case NETLINK_KOBJECT_UEVENT: return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET; default: return SECCLASS_NETLINK_SOCKET; } case PF_PACKET: return SECCLASS_PACKET_SOCKET; case PF_KEY: return SECCLASS_KEY_SOCKET; case PF_APPLETALK: return SECCLASS_APPLETALK_SOCKET; } return SECCLASS_SOCKET; } #ifdef CONFIG_PROC_FS static int selinux_proc_get_sid(struct dentry *dentry, u16 tclass, u32 *sid) { int rc; char *buffer, *path; buffer = (char *)__get_free_page(GFP_KERNEL); if (!buffer) return -ENOMEM; path = dentry_path_raw(dentry, buffer, PAGE_SIZE); if (IS_ERR(path)) rc = PTR_ERR(path); else { /* each process gets a /proc/PID/ entry. Strip off the * PID part to get a valid selinux labeling. * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */ while (path[1] >= '0' && path[1] <= '9') { path[1] = '/'; path++; } rc = security_genfs_sid("proc", path, tclass, sid); } free_page((unsigned long)buffer); return rc; } #else static int selinux_proc_get_sid(struct dentry *dentry, u16 tclass, u32 *sid) { return -EINVAL; } #endif /* The inode's security attributes must be initialized before first use. */ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry) { struct superblock_security_struct *sbsec = NULL; struct inode_security_struct *isec = inode->i_security; u32 sid; struct dentry *dentry; #define INITCONTEXTLEN 255 char *context = NULL; unsigned len = 0; int rc = 0; if (isec->initialized) goto out; mutex_lock(&isec->lock); if (isec->initialized) goto out_unlock; sbsec = inode->i_sb->s_security; if (!(sbsec->flags & SE_SBINITIALIZED)) { /* Defer initialization until selinux_complete_init, after the initial policy is loaded and the security server is ready to handle calls. */ spin_lock(&sbsec->isec_lock); if (list_empty(&isec->list)) list_add(&isec->list, &sbsec->isec_head); spin_unlock(&sbsec->isec_lock); goto out_unlock; } switch (sbsec->behavior) { case SECURITY_FS_USE_XATTR: if (!inode->i_op->getxattr) { isec->sid = sbsec->def_sid; break; } /* Need a dentry, since the xattr API requires one. Life would be simpler if we could just pass the inode. */ if (opt_dentry) { /* Called from d_instantiate or d_splice_alias. */ dentry = dget(opt_dentry); } else { /* Called from selinux_complete_init, try to find a dentry. */ dentry = d_find_alias(inode); } if (!dentry) { /* * this is can be hit on boot when a file is accessed * before the policy is loaded. When we load policy we * may find inodes that have no dentry on the * sbsec->isec_head list. No reason to complain as these * will get fixed up the next time we go through * inode_doinit with a dentry, before these inodes could * be used again by userspace. */ goto out_unlock; } len = INITCONTEXTLEN; context = kmalloc(len+1, GFP_NOFS); if (!context) { rc = -ENOMEM; dput(dentry); goto out_unlock; } context[len] = '\0'; rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX, context, len); if (rc == -ERANGE) { kfree(context); /* Need a larger buffer. Query for the right size. */ rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX, NULL, 0); if (rc < 0) { dput(dentry); goto out_unlock; } len = rc; context = kmalloc(len+1, GFP_NOFS); if (!context) { rc = -ENOMEM; dput(dentry); goto out_unlock; } context[len] = '\0'; rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX, context, len); } dput(dentry); if (rc < 0) { if (rc != -ENODATA) { printk(KERN_WARNING "SELinux: %s: getxattr returned " "%d for dev=%s ino=%ld\n", __func__, -rc, inode->i_sb->s_id, inode->i_ino); kfree(context); goto out_unlock; } /* Map ENODATA to the default file SID */ sid = sbsec->def_sid; rc = 0; } else { rc = security_context_to_sid_default(context, rc, &sid, sbsec->def_sid, GFP_NOFS); if (rc) { char *dev = inode->i_sb->s_id; unsigned long ino = inode->i_ino; if (rc == -EINVAL) { if (printk_ratelimit()) printk(KERN_NOTICE "SELinux: inode=%lu on dev=%s was found to have an invalid " "context=%s. This indicates you may need to relabel the inode or the " "filesystem in question.\n", ino, dev, context); } else { printk(KERN_WARNING "SELinux: %s: context_to_sid(%s) " "returned %d for dev=%s ino=%ld\n", __func__, context, -rc, dev, ino); } kfree(context); /* Leave with the unlabeled SID */ rc = 0; break; } } kfree(context); isec->sid = sid; break; case SECURITY_FS_USE_TASK: isec->sid = isec->task_sid; break; case SECURITY_FS_USE_TRANS: /* Default to the fs SID. */ isec->sid = sbsec->sid; /* Try to obtain a transition SID. */ isec->sclass = inode_mode_to_security_class(inode->i_mode); rc = security_transition_sid(isec->task_sid, sbsec->sid, isec->sclass, NULL, &sid); if (rc) goto out_unlock; isec->sid = sid; break; case SECURITY_FS_USE_MNTPOINT: isec->sid = sbsec->mntpoint_sid; break; default: /* Default to the fs superblock SID. */ isec->sid = sbsec->sid; if ((sbsec->flags & SE_SBPROC) && !S_ISLNK(inode->i_mode)) { if (opt_dentry) { isec->sclass = inode_mode_to_security_class(inode->i_mode); rc = selinux_proc_get_sid(opt_dentry, isec->sclass, &sid); if (rc) goto out_unlock; isec->sid = sid; } } break; } isec->initialized = 1; out_unlock: mutex_unlock(&isec->lock); out: if (isec->sclass == SECCLASS_FILE) isec->sclass = inode_mode_to_security_class(inode->i_mode); return rc; } /* Convert a Linux signal to an access vector. */ static inline u32 signal_to_av(int sig) { u32 perm = 0; switch (sig) { case SIGCHLD: /* Commonly granted from child to parent. */ perm = PROCESS__SIGCHLD; break; case SIGKILL: /* Cannot be caught or ignored */ perm = PROCESS__SIGKILL; break; case SIGSTOP: /* Cannot be caught or ignored */ perm = PROCESS__SIGSTOP; break; default: /* All other signals. */ perm = PROCESS__SIGNAL; break; } return perm; } /* * Check permission between a pair of credentials * fork check, ptrace check, etc. */ static int cred_has_perm(const struct cred *actor, const struct cred *target, u32 perms) { u32 asid = cred_sid(actor), tsid = cred_sid(target); return avc_has_perm(asid, tsid, SECCLASS_PROCESS, perms, NULL); } /* * Check permission between a pair of tasks, e.g. signal checks, * fork check, ptrace check, etc. * tsk1 is the actor and tsk2 is the target * - this uses the default subjective creds of tsk1 */ static int task_has_perm(const struct task_struct *tsk1, const struct task_struct *tsk2, u32 perms) { const struct task_security_struct *__tsec1, *__tsec2; u32 sid1, sid2; rcu_read_lock(); __tsec1 = __task_cred(tsk1)->security; sid1 = __tsec1->sid; __tsec2 = __task_cred(tsk2)->security; sid2 = __tsec2->sid; rcu_read_unlock(); return avc_has_perm(sid1, sid2, SECCLASS_PROCESS, perms, NULL); } /* * Check permission between current and another task, e.g. signal checks, * fork check, ptrace check, etc. * current is the actor and tsk2 is the target * - this uses current's subjective creds */ static int current_has_perm(const struct task_struct *tsk, u32 perms) { u32 sid, tsid; sid = current_sid(); tsid = task_sid(tsk); return avc_has_perm(sid, tsid, SECCLASS_PROCESS, perms, NULL); } #if CAP_LAST_CAP > 63 #error Fix SELinux to handle capabilities > 63. #endif /* Check whether a task is allowed to use a capability. */ static int task_has_capability(struct task_struct *tsk, const struct cred *cred, int cap, int audit) { struct common_audit_data ad; struct av_decision avd; u16 sclass; u32 sid = cred_sid(cred); u32 av = CAP_TO_MASK(cap); int rc; COMMON_AUDIT_DATA_INIT(&ad, CAP); ad.tsk = tsk; ad.u.cap = cap; switch (CAP_TO_INDEX(cap)) { case 0: sclass = SECCLASS_CAPABILITY; break; case 1: sclass = SECCLASS_CAPABILITY2; break; default: printk(KERN_ERR "SELinux: out of range capability %d\n", cap); BUG(); return -EINVAL; } rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd); if (audit == SECURITY_CAP_AUDIT) { int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad, 0); if (rc2) return rc2; } return rc; } /* Check whether a task is allowed to use a system operation. */ static int task_has_system(struct task_struct *tsk, u32 perms) { u32 sid = task_sid(tsk); return avc_has_perm(sid, SECINITSID_KERNEL, SECCLASS_SYSTEM, perms, NULL); } /* Check whether a task has a particular permission to an inode. The 'adp' parameter is optional and allows other audit data to be passed (e.g. the dentry). */ static int inode_has_perm(const struct cred *cred, struct inode *inode, u32 perms, struct common_audit_data *adp, unsigned flags) { struct inode_security_struct *isec; u32 sid; validate_creds(cred); if (unlikely(IS_PRIVATE(inode))) return 0; sid = cred_sid(cred); isec = inode->i_security; return avc_has_perm_flags(sid, isec->sid, isec->sclass, perms, adp, flags); } static int inode_has_perm_noadp(const struct cred *cred, struct inode *inode, u32 perms, unsigned flags) { struct common_audit_data ad; COMMON_AUDIT_DATA_INIT(&ad, INODE); ad.u.inode = inode; return inode_has_perm(cred, inode, perms, &ad, flags); } /* Same as inode_has_perm, but pass explicit audit data containing the dentry to help the auditing code to more easily generate the pathname if needed. */ static inline int dentry_has_perm(const struct cred *cred, struct dentry *dentry, u32 av) { struct inode *inode = dentry->d_inode; struct common_audit_data ad; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = dentry; return inode_has_perm(cred, inode, av, &ad, 0); } /* Same as inode_has_perm, but pass explicit audit data containing the path to help the auditing code to more easily generate the pathname if needed. */ static inline int path_has_perm(const struct cred *cred, struct path *path, u32 av) { struct inode *inode = path->dentry->d_inode; struct common_audit_data ad; COMMON_AUDIT_DATA_INIT(&ad, PATH); ad.u.path = *path; return inode_has_perm(cred, inode, av, &ad, 0); } /* Check whether a task can use an open file descriptor to access an inode in a given way. Check access to the descriptor itself, and then use dentry_has_perm to check a particular permission to the file. Access to the descriptor is implicitly granted if it has the same SID as the process. If av is zero, then access to the file is not checked, e.g. for cases where only the descriptor is affected like seek. */ static int file_has_perm(const struct cred *cred, struct file *file, u32 av) { struct file_security_struct *fsec = file->f_security; struct inode *inode = file->f_path.dentry->d_inode; struct common_audit_data ad; u32 sid = cred_sid(cred); int rc; COMMON_AUDIT_DATA_INIT(&ad, PATH); ad.u.path = file->f_path; if (sid != fsec->sid) { rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad); if (rc) goto out; } /* av is zero if only checking access to the descriptor. */ rc = 0; if (av) rc = inode_has_perm(cred, inode, av, &ad, 0); out: return rc; } /* Check whether a task can create a file. */ static int may_create(struct inode *dir, struct dentry *dentry, u16 tclass) { const struct task_security_struct *tsec = current_security(); struct inode_security_struct *dsec; struct superblock_security_struct *sbsec; u32 sid, newsid; struct common_audit_data ad; int rc; dsec = dir->i_security; sbsec = dir->i_sb->s_security; sid = tsec->sid; newsid = tsec->create_sid; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = dentry; rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, DIR__ADD_NAME | DIR__SEARCH, &ad); if (rc) return rc; if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) { rc = security_transition_sid(sid, dsec->sid, tclass, &dentry->d_name, &newsid); if (rc) return rc; } rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad); if (rc) return rc; return avc_has_perm(newsid, sbsec->sid, SECCLASS_FILESYSTEM, FILESYSTEM__ASSOCIATE, &ad); } /* Check whether a task can create a key. */ static int may_create_key(u32 ksid, struct task_struct *ctx) { u32 sid = task_sid(ctx); return avc_has_perm(sid, ksid, SECCLASS_KEY, KEY__CREATE, NULL); } #define MAY_LINK 0 #define MAY_UNLINK 1 #define MAY_RMDIR 2 /* Check whether a task can link, unlink, or rmdir a file/directory. */ static int may_link(struct inode *dir, struct dentry *dentry, int kind) { struct inode_security_struct *dsec, *isec; struct common_audit_data ad; u32 sid = current_sid(); u32 av; int rc; dsec = dir->i_security; isec = dentry->d_inode->i_security; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = dentry; av = DIR__SEARCH; av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME); rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad); if (rc) return rc; switch (kind) { case MAY_LINK: av = FILE__LINK; break; case MAY_UNLINK: av = FILE__UNLINK; break; case MAY_RMDIR: av = DIR__RMDIR; break; default: printk(KERN_WARNING "SELinux: %s: unrecognized kind %d\n", __func__, kind); return 0; } rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad); return rc; } static inline int may_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec; struct common_audit_data ad; u32 sid = current_sid(); u32 av; int old_is_dir, new_is_dir; int rc; old_dsec = old_dir->i_security; old_isec = old_dentry->d_inode->i_security; old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode); new_dsec = new_dir->i_security; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = old_dentry; rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR, DIR__REMOVE_NAME | DIR__SEARCH, &ad); if (rc) return rc; rc = avc_has_perm(sid, old_isec->sid, old_isec->sclass, FILE__RENAME, &ad); if (rc) return rc; if (old_is_dir && new_dir != old_dir) { rc = avc_has_perm(sid, old_isec->sid, old_isec->sclass, DIR__REPARENT, &ad); if (rc) return rc; } ad.u.dentry = new_dentry; av = DIR__ADD_NAME | DIR__SEARCH; if (new_dentry->d_inode) av |= DIR__REMOVE_NAME; rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad); if (rc) return rc; if (new_dentry->d_inode) { new_isec = new_dentry->d_inode->i_security; new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode); rc = avc_has_perm(sid, new_isec->sid, new_isec->sclass, (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad); if (rc) return rc; } return 0; } /* Check whether a task can perform a filesystem operation. */ static int superblock_has_perm(const struct cred *cred, struct super_block *sb, u32 perms, struct common_audit_data *ad) { struct superblock_security_struct *sbsec; u32 sid = cred_sid(cred); sbsec = sb->s_security; return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad); } /* Convert a Linux mode and permission mask to an access vector. */ static inline u32 file_mask_to_av(int mode, int mask) { u32 av = 0; if ((mode & S_IFMT) != S_IFDIR) { if (mask & MAY_EXEC) av |= FILE__EXECUTE; if (mask & MAY_READ) av |= FILE__READ; if (mask & MAY_APPEND) av |= FILE__APPEND; else if (mask & MAY_WRITE) av |= FILE__WRITE; } else { if (mask & MAY_EXEC) av |= DIR__SEARCH; if (mask & MAY_WRITE) av |= DIR__WRITE; if (mask & MAY_READ) av |= DIR__READ; } return av; } /* Convert a Linux file to an access vector. */ static inline u32 file_to_av(struct file *file) { u32 av = 0; if (file->f_mode & FMODE_READ) av |= FILE__READ; if (file->f_mode & FMODE_WRITE) { if (file->f_flags & O_APPEND) av |= FILE__APPEND; else av |= FILE__WRITE; } if (!av) { /* * Special file opened with flags 3 for ioctl-only use. */ av = FILE__IOCTL; } return av; } /* * Convert a file to an access vector and include the correct open * open permission. */ static inline u32 open_file_to_av(struct file *file) { u32 av = file_to_av(file); if (selinux_policycap_openperm) av |= FILE__OPEN; return av; } /* Hook functions begin here. */ static int selinux_binder_set_context_mgr(struct task_struct *mgr) { u32 mysid = current_sid(); u32 mgrsid = task_sid(mgr); return avc_has_perm(mysid, mgrsid, SECCLASS_BINDER, BINDER__SET_CONTEXT_MGR, NULL); } static int selinux_binder_transaction(struct task_struct *from, struct task_struct *to) { u32 mysid = current_sid(); u32 fromsid = task_sid(from); u32 tosid = task_sid(to); int rc; if (mysid != fromsid) { rc = avc_has_perm(mysid, fromsid, SECCLASS_BINDER, BINDER__IMPERSONATE, NULL); if (rc) return rc; } return avc_has_perm(fromsid, tosid, SECCLASS_BINDER, BINDER__CALL, NULL); } static int selinux_binder_transfer_binder(struct task_struct *from, struct task_struct *to) { u32 fromsid = task_sid(from); u32 tosid = task_sid(to); return avc_has_perm(fromsid, tosid, SECCLASS_BINDER, BINDER__TRANSFER, NULL); } static int selinux_binder_transfer_file(struct task_struct *from, struct task_struct *to, struct file *file) { u32 sid = task_sid(to); struct file_security_struct *fsec = file->f_security; struct inode *inode = file->f_path.dentry->d_inode; struct inode_security_struct *isec = inode->i_security; struct common_audit_data ad; int rc; COMMON_AUDIT_DATA_INIT(&ad, PATH); ad.u.path = file->f_path; if (sid != fsec->sid) { rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad); if (rc) return rc; } if (unlikely(IS_PRIVATE(inode))) return 0; return avc_has_perm(sid, isec->sid, isec->sclass, file_to_av(file), &ad); } static int selinux_ptrace_access_check(struct task_struct *child, unsigned int mode) { int rc; rc = cap_ptrace_access_check(child, mode); if (rc) return rc; if (mode == PTRACE_MODE_READ) { u32 sid = current_sid(); u32 csid = task_sid(child); return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ, NULL); } return current_has_perm(child, PROCESS__PTRACE); } static int selinux_ptrace_traceme(struct task_struct *parent) { int rc; rc = cap_ptrace_traceme(parent); if (rc) return rc; return task_has_perm(parent, current, PROCESS__PTRACE); } static int selinux_capget(struct task_struct *target, kernel_cap_t *effective, kernel_cap_t *inheritable, kernel_cap_t *permitted) { int error; error = current_has_perm(target, PROCESS__GETCAP); if (error) return error; return cap_capget(target, effective, inheritable, permitted); } static int selinux_capset(struct cred *new, const struct cred *old, const kernel_cap_t *effective, const kernel_cap_t *inheritable, const kernel_cap_t *permitted) { int error; error = cap_capset(new, old, effective, inheritable, permitted); if (error) return error; return cred_has_perm(old, new, PROCESS__SETCAP); } /* * (This comment used to live with the selinux_task_setuid hook, * which was removed). * * Since setuid only affects the current process, and since the SELinux * controls are not based on the Linux identity attributes, SELinux does not * need to control this operation. However, SELinux does control the use of * the CAP_SETUID and CAP_SETGID capabilities using the capable hook. */ static int selinux_capable(struct task_struct *tsk, const struct cred *cred, struct user_namespace *ns, int cap, int audit) { int rc; rc = cap_capable(tsk, cred, ns, cap, audit); if (rc) return rc; return task_has_capability(tsk, cred, cap, audit); } static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb) { const struct cred *cred = current_cred(); int rc = 0; if (!sb) return 0; switch (cmds) { case Q_SYNC: case Q_QUOTAON: case Q_QUOTAOFF: case Q_SETINFO: case Q_SETQUOTA: rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL); break; case Q_GETFMT: case Q_GETINFO: case Q_GETQUOTA: rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL); break; default: rc = 0; /* let the kernel handle invalid cmds */ break; } return rc; } static int selinux_quota_on(struct dentry *dentry) { const struct cred *cred = current_cred(); return dentry_has_perm(cred, dentry, FILE__QUOTAON); } static int selinux_syslog(int type) { int rc; switch (type) { case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */ case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */ rc = task_has_system(current, SYSTEM__SYSLOG_READ); break; case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */ case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */ /* Set level of messages printed to console */ case SYSLOG_ACTION_CONSOLE_LEVEL: rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE); break; case SYSLOG_ACTION_CLOSE: /* Close log */ case SYSLOG_ACTION_OPEN: /* Open log */ case SYSLOG_ACTION_READ: /* Read from log */ case SYSLOG_ACTION_READ_CLEAR: /* Read/clear last kernel messages */ case SYSLOG_ACTION_CLEAR: /* Clear ring buffer */ default: rc = task_has_system(current, SYSTEM__SYSLOG_MOD); break; } return rc; } /* * Check that a process has enough memory to allocate a new virtual * mapping. 0 means there is enough memory for the allocation to * succeed and -ENOMEM implies there is not. * * Do not audit the selinux permission check, as this is applied to all * processes that allocate mappings. */ static int selinux_vm_enough_memory(struct mm_struct *mm, long pages) { int rc, cap_sys_admin = 0; rc = selinux_capable(current, current_cred(), &init_user_ns, CAP_SYS_ADMIN, SECURITY_CAP_NOAUDIT); if (rc == 0) cap_sys_admin = 1; return __vm_enough_memory(mm, pages, cap_sys_admin); } /* binprm security operations */ static int selinux_bprm_set_creds(struct linux_binprm *bprm) { const struct task_security_struct *old_tsec; struct task_security_struct *new_tsec; struct inode_security_struct *isec; struct common_audit_data ad; struct inode *inode = bprm->file->f_path.dentry->d_inode; int rc; rc = cap_bprm_set_creds(bprm); if (rc) return rc; /* SELinux context only depends on initial program or script and not * the script interpreter */ if (bprm->cred_prepared) return 0; old_tsec = current_security(); new_tsec = bprm->cred->security; isec = inode->i_security; /* Default to the current task SID. */ new_tsec->sid = old_tsec->sid; new_tsec->osid = old_tsec->sid; /* Reset fs, key, and sock SIDs on execve. */ new_tsec->create_sid = 0; new_tsec->keycreate_sid = 0; new_tsec->sockcreate_sid = 0; if (old_tsec->exec_sid) { new_tsec->sid = old_tsec->exec_sid; /* Reset exec SID on execve. */ new_tsec->exec_sid = 0; } else { /* Check for a default transition on this program. */ rc = security_transition_sid(old_tsec->sid, isec->sid, SECCLASS_PROCESS, NULL, &new_tsec->sid); if (rc) return rc; } COMMON_AUDIT_DATA_INIT(&ad, PATH); ad.u.path = bprm->file->f_path; if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) new_tsec->sid = old_tsec->sid; if (new_tsec->sid == old_tsec->sid) { rc = avc_has_perm(old_tsec->sid, isec->sid, SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad); if (rc) return rc; } else { /* Check permissions for the transition. */ rc = avc_has_perm(old_tsec->sid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__TRANSITION, &ad); if (rc) return rc; rc = avc_has_perm(new_tsec->sid, isec->sid, SECCLASS_FILE, FILE__ENTRYPOINT, &ad); if (rc) return rc; /* Check for shared state */ if (bprm->unsafe & LSM_UNSAFE_SHARE) { rc = avc_has_perm(old_tsec->sid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__SHARE, NULL); if (rc) return -EPERM; } /* Make sure that anyone attempting to ptrace over a task that * changes its SID has the appropriate permit */ if (bprm->unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) { struct task_struct *tracer; struct task_security_struct *sec; u32 ptsid = 0; rcu_read_lock(); tracer = tracehook_tracer_task(current); if (likely(tracer != NULL)) { sec = __task_cred(tracer)->security; ptsid = sec->sid; } rcu_read_unlock(); if (ptsid != 0) { rc = avc_has_perm(ptsid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL); if (rc) return -EPERM; } } /* Clear any possibly unsafe personality bits on exec: */ bprm->per_clear |= PER_CLEAR_ON_SETID; } return 0; } static int selinux_bprm_secureexec(struct linux_binprm *bprm) { const struct task_security_struct *tsec = current_security(); u32 sid, osid; int atsecure = 0; sid = tsec->sid; osid = tsec->osid; if (osid != sid) { /* Enable secure mode for SIDs transitions unless the noatsecure permission is granted between the two SIDs, i.e. ahp returns 0. */ atsecure = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__NOATSECURE, NULL); } return (atsecure || cap_bprm_secureexec(bprm)); } extern struct vfsmount *selinuxfs_mount; extern struct dentry *selinux_null; /* Derived from fs/exec.c:flush_old_files. */ static inline void flush_unauthorized_files(const struct cred *cred, struct files_struct *files) { struct common_audit_data ad; struct file *file, *devnull = NULL; struct tty_struct *tty; struct fdtable *fdt; long j = -1; int drop_tty = 0; tty = get_current_tty(); if (tty) { spin_lock(&tty_files_lock); if (!list_empty(&tty->tty_files)) { struct tty_file_private *file_priv; struct inode *inode; /* Revalidate access to controlling tty. Use inode_has_perm on the tty inode directly rather than using file_has_perm, as this particular open file may belong to another process and we are only interested in the inode-based check here. */ file_priv = list_first_entry(&tty->tty_files, struct tty_file_private, list); file = file_priv->file; inode = file->f_path.dentry->d_inode; if (inode_has_perm_noadp(cred, inode, FILE__READ | FILE__WRITE, 0)) { drop_tty = 1; } } spin_unlock(&tty_files_lock); tty_kref_put(tty); } /* Reset controlling tty. */ if (drop_tty) no_tty(); /* Revalidate access to inherited open files. */ COMMON_AUDIT_DATA_INIT(&ad, INODE); spin_lock(&files->file_lock); for (;;) { unsigned long set, i; int fd; j++; i = j * __NFDBITS; fdt = files_fdtable(files); if (i >= fdt->max_fds) break; set = fdt->open_fds->fds_bits[j]; if (!set) continue; spin_unlock(&files->file_lock); for ( ; set ; i++, set >>= 1) { if (set & 1) { file = fget(i); if (!file) continue; if (file_has_perm(cred, file, file_to_av(file))) { sys_close(i); fd = get_unused_fd(); if (fd != i) { if (fd >= 0) put_unused_fd(fd); fput(file); continue; } if (devnull) { get_file(devnull); } else { devnull = dentry_open( dget(selinux_null), mntget(selinuxfs_mount), O_RDWR, cred); if (IS_ERR(devnull)) { devnull = NULL; put_unused_fd(fd); fput(file); continue; } } fd_install(fd, devnull); } fput(file); } } spin_lock(&files->file_lock); } spin_unlock(&files->file_lock); } /* * Prepare a process for imminent new credential changes due to exec */ static void selinux_bprm_committing_creds(struct linux_binprm *bprm) { struct task_security_struct *new_tsec; struct rlimit *rlim, *initrlim; int rc, i; new_tsec = bprm->cred->security; if (new_tsec->sid == new_tsec->osid) return; /* Close files for which the new task SID is not authorized. */ flush_unauthorized_files(bprm->cred, current->files); /* Always clear parent death signal on SID transitions. */ current->pdeath_signal = 0; /* Check whether the new SID can inherit resource limits from the old * SID. If not, reset all soft limits to the lower of the current * task's hard limit and the init task's soft limit. * * Note that the setting of hard limits (even to lower them) can be * controlled by the setrlimit check. The inclusion of the init task's * soft limit into the computation is to avoid resetting soft limits * higher than the default soft limit for cases where the default is * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK. */ rc = avc_has_perm(new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__RLIMITINH, NULL); if (rc) { /* protect against do_prlimit() */ task_lock(current); for (i = 0; i < RLIM_NLIMITS; i++) { rlim = current->signal->rlim + i; initrlim = init_task.signal->rlim + i; rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur); } task_unlock(current); update_rlimit_cpu(current, rlimit(RLIMIT_CPU)); } } /* * Clean up the process immediately after the installation of new credentials * due to exec */ static void selinux_bprm_committed_creds(struct linux_binprm *bprm) { const struct task_security_struct *tsec = current_security(); struct itimerval itimer; u32 osid, sid; int rc, i; osid = tsec->osid; sid = tsec->sid; if (sid == osid) return; /* Check whether the new SID can inherit signal state from the old SID. * If not, clear itimers to avoid subsequent signal generation and * flush and unblock signals. * * This must occur _after_ the task SID has been updated so that any * kill done after the flush will be checked against the new SID. */ rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL); if (rc) { memset(&itimer, 0, sizeof itimer); for (i = 0; i < 3; i++) do_setitimer(i, &itimer, NULL); spin_lock_irq(&current->sighand->siglock); if (!(current->signal->flags & SIGNAL_GROUP_EXIT)) { __flush_signals(current); flush_signal_handlers(current, 1); sigemptyset(&current->blocked); } spin_unlock_irq(&current->sighand->siglock); } /* Wake up the parent if it is waiting so that it can recheck * wait permission to the new task SID. */ read_lock(&tasklist_lock); __wake_up_parent(current, current->real_parent); read_unlock(&tasklist_lock); } /* superblock security operations */ static int selinux_sb_alloc_security(struct super_block *sb) { return superblock_alloc_security(sb); } static void selinux_sb_free_security(struct super_block *sb) { superblock_free_security(sb); } static inline int match_prefix(char *prefix, int plen, char *option, int olen) { if (plen > olen) return 0; return !memcmp(prefix, option, plen); } static inline int selinux_option(char *option, int len) { return (match_prefix(CONTEXT_STR, sizeof(CONTEXT_STR)-1, option, len) || match_prefix(FSCONTEXT_STR, sizeof(FSCONTEXT_STR)-1, option, len) || match_prefix(DEFCONTEXT_STR, sizeof(DEFCONTEXT_STR)-1, option, len) || match_prefix(ROOTCONTEXT_STR, sizeof(ROOTCONTEXT_STR)-1, option, len) || match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, len)); } static inline void take_option(char **to, char *from, int *first, int len) { if (!*first) { **to = ','; *to += 1; } else *first = 0; memcpy(*to, from, len); *to += len; } static inline void take_selinux_option(char **to, char *from, int *first, int len) { int current_size = 0; if (!*first) { **to = '|'; *to += 1; } else *first = 0; while (current_size < len) { if (*from != '"') { **to = *from; *to += 1; } from += 1; current_size += 1; } } static int selinux_sb_copy_data(char *orig, char *copy) { int fnosec, fsec, rc = 0; char *in_save, *in_curr, *in_end; char *sec_curr, *nosec_save, *nosec; int open_quote = 0; in_curr = orig; sec_curr = copy; nosec = (char *)get_zeroed_page(GFP_KERNEL); if (!nosec) { rc = -ENOMEM; goto out; } nosec_save = nosec; fnosec = fsec = 1; in_save = in_end = orig; do { if (*in_end == '"') open_quote = !open_quote; if ((*in_end == ',' && open_quote == 0) || *in_end == '\0') { int len = in_end - in_curr; if (selinux_option(in_curr, len)) take_selinux_option(&sec_curr, in_curr, &fsec, len); else take_option(&nosec, in_curr, &fnosec, len); in_curr = in_end + 1; } } while (*in_end++); strcpy(in_save, nosec_save); free_page((unsigned long)nosec_save); out: return rc; } static int selinux_sb_remount(struct super_block *sb, void *data) { int rc, i, *flags; struct security_mnt_opts opts; char *secdata, **mount_options; struct superblock_security_struct *sbsec = sb->s_security; if (!(sbsec->flags & SE_SBINITIALIZED)) return 0; if (!data) return 0; if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA) return 0; security_init_mnt_opts(&opts); secdata = alloc_secdata(); if (!secdata) return -ENOMEM; rc = selinux_sb_copy_data(data, secdata); if (rc) goto out_free_secdata; rc = selinux_parse_opts_str(secdata, &opts); if (rc) goto out_free_secdata; mount_options = opts.mnt_opts; flags = opts.mnt_opts_flags; for (i = 0; i < opts.num_mnt_opts; i++) { u32 sid; size_t len; if (flags[i] == SE_SBLABELSUPP) continue; len = strlen(mount_options[i]); rc = security_context_to_sid(mount_options[i], len, &sid); if (rc) { printk(KERN_WARNING "SELinux: security_context_to_sid" "(%s) failed for (dev %s, type %s) errno=%d\n", mount_options[i], sb->s_id, sb->s_type->name, rc); goto out_free_opts; } rc = -EINVAL; switch (flags[i]) { case FSCONTEXT_MNT: if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid)) goto out_bad_option; break; case CONTEXT_MNT: if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid)) goto out_bad_option; break; case ROOTCONTEXT_MNT: { struct inode_security_struct *root_isec; root_isec = sb->s_root->d_inode->i_security; if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid)) goto out_bad_option; break; } case DEFCONTEXT_MNT: if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid)) goto out_bad_option; break; default: goto out_free_opts; } } rc = 0; out_free_opts: security_free_mnt_opts(&opts); out_free_secdata: free_secdata(secdata); return rc; out_bad_option: printk(KERN_WARNING "SELinux: unable to change security options " "during remount (dev %s, type=%s)\n", sb->s_id, sb->s_type->name); goto out_free_opts; } static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data) { const struct cred *cred = current_cred(); struct common_audit_data ad; int rc; rc = superblock_doinit(sb, data); if (rc) return rc; /* Allow all mounts performed by the kernel */ if (flags & MS_KERNMOUNT) return 0; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = sb->s_root; return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad); } static int selinux_sb_statfs(struct dentry *dentry) { const struct cred *cred = current_cred(); struct common_audit_data ad; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = dentry->d_sb->s_root; return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad); } static int selinux_mount(char *dev_name, struct path *path, char *type, unsigned long flags, void *data) { const struct cred *cred = current_cred(); if (flags & MS_REMOUNT) return superblock_has_perm(cred, path->mnt->mnt_sb, FILESYSTEM__REMOUNT, NULL); else return path_has_perm(cred, path, FILE__MOUNTON); } static int selinux_umount(struct vfsmount *mnt, int flags) { const struct cred *cred = current_cred(); return superblock_has_perm(cred, mnt->mnt_sb, FILESYSTEM__UNMOUNT, NULL); } /* inode security operations */ static int selinux_inode_alloc_security(struct inode *inode) { return inode_alloc_security(inode); } static void selinux_inode_free_security(struct inode *inode) { inode_free_security(inode); } static int selinux_inode_init_security(struct inode *inode, struct inode *dir, const struct qstr *qstr, char **name, void **value, size_t *len) { const struct task_security_struct *tsec = current_security(); struct inode_security_struct *dsec; struct superblock_security_struct *sbsec; u32 sid, newsid, clen; int rc; char *namep = NULL, *context; dsec = dir->i_security; sbsec = dir->i_sb->s_security; sid = tsec->sid; newsid = tsec->create_sid; if ((sbsec->flags & SE_SBINITIALIZED) && (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) newsid = sbsec->mntpoint_sid; else if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) { rc = security_transition_sid(sid, dsec->sid, inode_mode_to_security_class(inode->i_mode), qstr, &newsid); if (rc) { printk(KERN_WARNING "%s: " "security_transition_sid failed, rc=%d (dev=%s " "ino=%ld)\n", __func__, -rc, inode->i_sb->s_id, inode->i_ino); return rc; } } /* Possibly defer initialization to selinux_complete_init. */ if (sbsec->flags & SE_SBINITIALIZED) { struct inode_security_struct *isec = inode->i_security; isec->sclass = inode_mode_to_security_class(inode->i_mode); isec->sid = newsid; isec->initialized = 1; } if (!ss_initialized || !(sbsec->flags & SE_SBLABELSUPP)) return -EOPNOTSUPP; if (name) { namep = kstrdup(XATTR_SELINUX_SUFFIX, GFP_NOFS); if (!namep) return -ENOMEM; *name = namep; } if (value && len) { rc = security_sid_to_context_force(newsid, &context, &clen); if (rc) { kfree(namep); return rc; } *value = context; *len = clen; } return 0; } static int selinux_inode_create(struct inode *dir, struct dentry *dentry, int mask) { return may_create(dir, dentry, SECCLASS_FILE); } static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry) { return may_link(dir, old_dentry, MAY_LINK); } static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry) { return may_link(dir, dentry, MAY_UNLINK); } static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name) { return may_create(dir, dentry, SECCLASS_LNK_FILE); } static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, int mask) { return may_create(dir, dentry, SECCLASS_DIR); } static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry) { return may_link(dir, dentry, MAY_RMDIR); } static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev) { return may_create(dir, dentry, inode_mode_to_security_class(mode)); } static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry, struct inode *new_inode, struct dentry *new_dentry) { return may_rename(old_inode, old_dentry, new_inode, new_dentry); } static int selinux_inode_readlink(struct dentry *dentry) { const struct cred *cred = current_cred(); return dentry_has_perm(cred, dentry, FILE__READ); } static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata) { const struct cred *cred = current_cred(); return dentry_has_perm(cred, dentry, FILE__READ); } static int selinux_inode_permission(struct inode *inode, int mask, unsigned flags) { const struct cred *cred = current_cred(); struct common_audit_data ad; u32 perms; bool from_access; from_access = mask & MAY_ACCESS; mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND); /* No permission to check. Existence test. */ if (!mask) return 0; COMMON_AUDIT_DATA_INIT(&ad, INODE); ad.u.inode = inode; if (from_access) ad.selinux_audit_data.auditdeny |= FILE__AUDIT_ACCESS; perms = file_mask_to_av(inode->i_mode, mask); return inode_has_perm(cred, inode, perms, &ad, flags); } static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr) { const struct cred *cred = current_cred(); unsigned int ia_valid = iattr->ia_valid; /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */ if (ia_valid & ATTR_FORCE) { ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE | ATTR_FORCE); if (!ia_valid) return 0; } if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID | ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET)) return dentry_has_perm(cred, dentry, FILE__SETATTR); return dentry_has_perm(cred, dentry, FILE__WRITE); } static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry) { const struct cred *cred = current_cred(); struct path path; path.dentry = dentry; path.mnt = mnt; return path_has_perm(cred, &path, FILE__GETATTR); } static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name) { const struct cred *cred = current_cred(); if (!strncmp(name, XATTR_SECURITY_PREFIX, sizeof XATTR_SECURITY_PREFIX - 1)) { if (!strcmp(name, XATTR_NAME_CAPS)) { if (!capable(CAP_SETFCAP)) return -EPERM; } else if (!capable(CAP_SYS_ADMIN)) { /* A different attribute in the security namespace. Restrict to administrator. */ return -EPERM; } } /* Not an attribute we recognize, so just check the ordinary setattr permission. */ return dentry_has_perm(cred, dentry, FILE__SETATTR); } static int selinux_inode_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags) { struct inode *inode = dentry->d_inode; struct inode_security_struct *isec = inode->i_security; struct superblock_security_struct *sbsec; struct common_audit_data ad; u32 newsid, sid = current_sid(); int rc = 0; if (strcmp(name, XATTR_NAME_SELINUX)) return selinux_inode_setotherxattr(dentry, name); sbsec = inode->i_sb->s_security; if (!(sbsec->flags & SE_SBLABELSUPP)) return -EOPNOTSUPP; if (!inode_owner_or_capable(inode)) return -EPERM; COMMON_AUDIT_DATA_INIT(&ad, DENTRY); ad.u.dentry = dentry; rc = avc_has_perm(sid, isec->sid, isec->sclass, FILE__RELABELFROM, &ad); if (rc) return rc; rc = security_context_to_sid(value, size, &newsid); if (rc == -EINVAL) { if (!capable(CAP_MAC_ADMIN)) return rc; rc = security_context_to_sid_force(value, size, &newsid); } if (rc) return rc; rc = avc_has_perm(sid, newsid, isec->sclass, FILE__RELABELTO, &ad); if (rc) return rc; rc = security_validate_transition(isec->sid, newsid, sid, isec->sclass); if (rc) return rc; return avc_has_perm(newsid, sbsec->sid, SECCLASS_FILESYSTEM, FILESYSTEM__ASSOCIATE, &ad); } static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags) { struct inode *inode = dentry->d_inode; struct inode_security_struct *isec = inode->i_security; u32 newsid; int rc; if (strcmp(name, XATTR_NAME_SELINUX)) { /* Not an attribute we recognize, so nothing to do. */ return; } rc = security_context_to_sid_force(value, size, &newsid); if (rc) { printk(KERN_ERR "SELinux: unable to map context to SID" "for (%s, %lu), rc=%d\n", inode->i_sb->s_id, inode->i_ino, -rc); return; } isec->sid = newsid; return; } static int selinux_inode_getxattr(struct dentry *dentry, const char *name) { const struct cred *cred = current_cred(); return dentry_has_perm(cred, dentry, FILE__GETATTR); } static int selinux_inode_listxattr(struct dentry *dentry) { const struct cred *cred = current_cred(); return dentry_has_perm(cred, dentry, FILE__GETATTR); } static int selinux_inode_removexattr(struct dentry *dentry, const char *name) { if (strcmp(name, XATTR_NAME_SELINUX)) return selinux_inode_setotherxattr(dentry, name); /* No one is allowed to remove a SELinux security label. You can change the label, but all data must be labeled. */ return -EACCES; } /* * Copy the inode security context value to the user. * * Permission check is handled by selinux_inode_getxattr hook. */ static int selinux_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc) { u32 size; int error; char *context = NULL; struct inode_security_struct *isec = inode->i_security; if (strcmp(name, XATTR_SELINUX_SUFFIX)) return -EOPNOTSUPP; /* * If the caller has CAP_MAC_ADMIN, then get the raw context * value even if it is not defined by current policy; otherwise, * use the in-core value under current policy. * Use the non-auditing forms of the permission checks since * getxattr may be called by unprivileged processes commonly * and lack of permission just means that we fall back to the * in-core context value, not a denial. */ error = selinux_capable(current, current_cred(), &init_user_ns, CAP_MAC_ADMIN, SECURITY_CAP_NOAUDIT); if (!error) error = security_sid_to_context_force(isec->sid, &context, &size); else error = security_sid_to_context(isec->sid, &context, &size); if (error) return error; error = size; if (alloc) { *buffer = context; goto out_nofree; } kfree(context); out_nofree: return error; } static int selinux_inode_setsecurity(struct inode *inode, const char *name, const void *value, size_t size, int flags) { struct inode_security_struct *isec = inode->i_security; u32 newsid; int rc; if (strcmp(name, XATTR_SELINUX_SUFFIX)) return -EOPNOTSUPP; if (!value || !size) return -EACCES; rc = security_context_to_sid((void *)value, size, &newsid); if (rc) return rc; isec->sid = newsid; isec->initialized = 1; return 0; } static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size) { const int len = sizeof(XATTR_NAME_SELINUX); if (buffer && len <= buffer_size) memcpy(buffer, XATTR_NAME_SELINUX, len); return len; } static void selinux_inode_getsecid(const struct inode *inode, u32 *secid) { struct inode_security_struct *isec = inode->i_security; *secid = isec->sid; } /* file security operations */ static int selinux_revalidate_file_permission(struct file *file, int mask) { const struct cred *cred = current_cred(); struct inode *inode = file->f_path.dentry->d_inode; /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */ if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE)) mask |= MAY_APPEND; return file_has_perm(cred, file, file_mask_to_av(inode->i_mode, mask)); } static int selinux_file_permission(struct file *file, int mask) { struct inode *inode = file->f_path.dentry->d_inode; struct file_security_struct *fsec = file->f_security; struct inode_security_struct *isec = inode->i_security; u32 sid = current_sid(); if (!mask) /* No permission to check. Existence test. */ return 0; if (sid == fsec->sid && fsec->isid == isec->sid && fsec->pseqno == avc_policy_seqno()) /* No change since dentry_open check. */ return 0; return selinux_revalidate_file_permission(file, mask); } static int selinux_file_alloc_security(struct file *file) { return file_alloc_security(file); } static void selinux_file_free_security(struct file *file) { file_free_security(file); } /* * Check whether a task has the ioctl permission and cmd * operation to an inode. */ int ioctl_has_perm(const struct cred *cred, struct file *file, u32 requested, u16 cmd) { struct common_audit_data ad; struct file_security_struct *fsec = file->f_security; struct inode *inode = file->f_path.dentry->d_inode; struct inode_security_struct *isec = inode->i_security; struct lsm_ioctlop_audit ioctl; u32 ssid = cred_sid(cred); int rc; COMMON_AUDIT_DATA_INIT(&ad, IOCTL_OP); ad.u.op = &ioctl; ad.u.op->cmd = cmd; ad.u.op->path = file->f_path; if (ssid != fsec->sid) { rc = avc_has_perm(ssid, fsec->sid, SECCLASS_FD, FD__USE, &ad); if (rc) goto out; } if (unlikely(IS_PRIVATE(inode))) return 0; rc = avc_has_operation(ssid, isec->sid, isec->sclass, requested, cmd, &ad); out: return rc; } static int selinux_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { const struct cred *cred = current_cred(); int error = 0; switch (cmd) { case FIONREAD: /* fall through */ case FIBMAP: /* fall through */ case FIGETBSZ: /* fall through */ case EXT2_IOC_GETFLAGS: /* fall through */ case EXT2_IOC_GETVERSION: error = file_has_perm(cred, file, FILE__GETATTR); break; case EXT2_IOC_SETFLAGS: /* fall through */ case EXT2_IOC_SETVERSION: error = file_has_perm(cred, file, FILE__SETATTR); break; /* sys_ioctl() checks */ case FIONBIO: /* fall through */ case FIOASYNC: error = file_has_perm(cred, file, 0); break; case KDSKBENT: case KDSKBSENT: error = task_has_capability(current, cred, CAP_SYS_TTY_CONFIG, SECURITY_CAP_AUDIT); break; /* default case assumes that the command will go * to the file's ioctl() function. */ default: error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd); } return error; } static int default_noexec; static int file_map_prot_check(struct file *file, unsigned long prot, int shared) { const struct cred *cred = current_cred(); int rc = 0; if (default_noexec && (prot & PROT_EXEC) && (!file || (!shared && (prot & PROT_WRITE)))) { /* * We are making executable an anonymous mapping or a * private file mapping that will also be writable. * This has an additional check. */ rc = cred_has_perm(cred, cred, PROCESS__EXECMEM); if (rc) goto error; } if (file) { /* read access is always possible with a mapping */ u32 av = FILE__READ; /* write access only matters if the mapping is shared */ if (shared && (prot & PROT_WRITE)) av |= FILE__WRITE; if (prot & PROT_EXEC) av |= FILE__EXECUTE; return file_has_perm(cred, file, av); } error: return rc; } static int selinux_file_mmap(struct file *file, unsigned long reqprot, unsigned long prot, unsigned long flags, unsigned long addr, unsigned long addr_only) { int rc = 0; u32 sid = current_sid(); /* * notice that we are intentionally putting the SELinux check before * the secondary cap_file_mmap check. This is such a likely attempt * at bad behaviour/exploit that we always want to get the AVC, even * if DAC would have also denied the operation. */ if (addr < CONFIG_LSM_MMAP_MIN_ADDR) { rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT, MEMPROTECT__MMAP_ZERO, NULL); if (rc) return rc; } /* do DAC check on address space usage */ rc = cap_file_mmap(file, reqprot, prot, flags, addr, addr_only); if (rc || addr_only) return rc; if (selinux_checkreqprot) prot = reqprot; return file_map_prot_check(file, prot, (flags & MAP_TYPE) == MAP_SHARED); } static int selinux_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot) { const struct cred *cred = current_cred(); if (selinux_checkreqprot) prot = reqprot; if (default_noexec && (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) { int rc = 0; if (vma->vm_start >= vma->vm_mm->start_brk && vma->vm_end <= vma->vm_mm->brk) { rc = cred_has_perm(cred, cred, PROCESS__EXECHEAP); } else if (!vma->vm_file && vma->vm_start <= vma->vm_mm->start_stack && vma->vm_end >= vma->vm_mm->start_stack) { rc = current_has_perm(current, PROCESS__EXECSTACK); } else if (vma->vm_file && vma->anon_vma) { /* * We are making executable a file mapping that has * had some COW done. Since pages might have been * written, check ability to execute the possibly * modified content. This typically should only * occur for text relocations. */ rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD); } if (rc) return rc; } return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED); } static int selinux_file_lock(struct file *file, unsigned int cmd) { const struct cred *cred = current_cred(); return file_has_perm(cred, file, FILE__LOCK); } static int selinux_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { const struct cred *cred = current_cred(); int err = 0; switch (cmd) { case F_SETFL: if (!file->f_path.dentry || !file->f_path.dentry->d_inode) { err = -EINVAL; break; } if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) { err = file_has_perm(cred, file, FILE__WRITE); break; } /* fall through */ case F_SETOWN: case F_SETSIG: case F_GETFL: case F_GETOWN: case F_GETSIG: /* Just check FD__USE permission */ err = file_has_perm(cred, file, 0); break; case F_GETLK: case F_SETLK: case F_SETLKW: #if BITS_PER_LONG == 32 case F_GETLK64: case F_SETLK64: case F_SETLKW64: #endif if (!file->f_path.dentry || !file->f_path.dentry->d_inode) { err = -EINVAL; break; } err = file_has_perm(cred, file, FILE__LOCK); break; } return err; } static int selinux_file_set_fowner(struct file *file) { struct file_security_struct *fsec; fsec = file->f_security; fsec->fown_sid = current_sid(); return 0; } static int selinux_file_send_sigiotask(struct task_struct *tsk, struct fown_struct *fown, int signum) { struct file *file; u32 sid = task_sid(tsk); u32 perm; struct file_security_struct *fsec; /* struct fown_struct is never outside the context of a struct file */ file = container_of(fown, struct file, f_owner); fsec = file->f_security; if (!signum) perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */ else perm = signal_to_av(signum); return avc_has_perm(fsec->fown_sid, sid, SECCLASS_PROCESS, perm, NULL); } static int selinux_file_receive(struct file *file) { const struct cred *cred = current_cred(); return file_has_perm(cred, file, file_to_av(file)); } static int selinux_dentry_open(struct file *file, const struct cred *cred) { struct file_security_struct *fsec; struct inode *inode; struct inode_security_struct *isec; inode = file->f_path.dentry->d_inode; fsec = file->f_security; isec = inode->i_security; /* * Save inode label and policy sequence number * at open-time so that selinux_file_permission * can determine whether revalidation is necessary. * Task label is already saved in the file security * struct as its SID. */ fsec->isid = isec->sid; fsec->pseqno = avc_policy_seqno(); /* * Since the inode label or policy seqno may have changed * between the selinux_inode_permission check and the saving * of state above, recheck that access is still permitted. * Otherwise, access might never be revalidated against the * new inode label or new policy. * This check is not redundant - do not remove. */ return inode_has_perm_noadp(cred, inode, open_file_to_av(file), 0); } /* task security operations */ static int selinux_task_create(unsigned long clone_flags) { return current_has_perm(current, PROCESS__FORK); } /* * allocate the SELinux part of blank credentials */ static int selinux_cred_alloc_blank(struct cred *cred, gfp_t gfp) { struct task_security_struct *tsec; tsec = kzalloc(sizeof(struct task_security_struct), gfp); if (!tsec) return -ENOMEM; cred->security = tsec; return 0; } /* * detach and free the LSM part of a set of credentials */ static void selinux_cred_free(struct cred *cred) { struct task_security_struct *tsec = cred->security; /* * cred->security == NULL if security_cred_alloc_blank() or * security_prepare_creds() returned an error. */ BUG_ON(cred->security && (unsigned long) cred->security < PAGE_SIZE); cred->security = (void *) 0x7UL; kfree(tsec); } /* * prepare a new set of credentials for modification */ static int selinux_cred_prepare(struct cred *new, const struct cred *old, gfp_t gfp) { const struct task_security_struct *old_tsec; struct task_security_struct *tsec; old_tsec = old->security; tsec = kmemdup(old_tsec, sizeof(struct task_security_struct), gfp); if (!tsec) return -ENOMEM; new->security = tsec; return 0; } /* * transfer the SELinux data to a blank set of creds */ static void selinux_cred_transfer(struct cred *new, const struct cred *old) { const struct task_security_struct *old_tsec = old->security; struct task_security_struct *tsec = new->security; *tsec = *old_tsec; } /* * set the security data for a kernel service * - all the creation contexts are set to unlabelled */ static int selinux_kernel_act_as(struct cred *new, u32 secid) { struct task_security_struct *tsec = new->security; u32 sid = current_sid(); int ret; ret = avc_has_perm(sid, secid, SECCLASS_KERNEL_SERVICE, KERNEL_SERVICE__USE_AS_OVERRIDE, NULL); if (ret == 0) { tsec->sid = secid; tsec->create_sid = 0; tsec->keycreate_sid = 0; tsec->sockcreate_sid = 0; } return ret; } /* * set the file creation context in a security record to the same as the * objective context of the specified inode */ static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode) { struct inode_security_struct *isec = inode->i_security; struct task_security_struct *tsec = new->security; u32 sid = current_sid(); int ret; ret = avc_has_perm(sid, isec->sid, SECCLASS_KERNEL_SERVICE, KERNEL_SERVICE__CREATE_FILES_AS, NULL); if (ret == 0) tsec->create_sid = isec->sid; return ret; } static int selinux_kernel_module_request(char *kmod_name) { u32 sid; struct common_audit_data ad; sid = task_sid(current); COMMON_AUDIT_DATA_INIT(&ad, KMOD); ad.u.kmod_name = kmod_name; return avc_has_perm(sid, SECINITSID_KERNEL, SECCLASS_SYSTEM, SYSTEM__MODULE_REQUEST, &ad); } static int selinux_task_setpgid(struct task_struct *p, pid_t pgid) { return current_has_perm(p, PROCESS__SETPGID); } static int selinux_task_getpgid(struct task_struct *p) { return current_has_perm(p, PROCESS__GETPGID); } static int selinux_task_getsid(struct task_struct *p) { return current_has_perm(p, PROCESS__GETSESSION); } static void selinux_task_getsecid(struct task_struct *p, u32 *secid) { *secid = task_sid(p); } static int selinux_task_setnice(struct task_struct *p, int nice) { int rc; rc = cap_task_setnice(p, nice); if (rc) return rc; return current_has_perm(p, PROCESS__SETSCHED); } static int selinux_task_setioprio(struct task_struct *p, int ioprio) { int rc; rc = cap_task_setioprio(p, ioprio); if (rc) return rc; return current_has_perm(p, PROCESS__SETSCHED); } static int selinux_task_getioprio(struct task_struct *p) { return current_has_perm(p, PROCESS__GETSCHED); } static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource, struct rlimit *new_rlim) { struct rlimit *old_rlim = p->signal->rlim + resource; /* Control the ability to change the hard limit (whether lowering or raising it), so that the hard limit can later be used as a safe reset point for the soft limit upon context transitions. See selinux_bprm_committing_creds. */ if (old_rlim->rlim_max != new_rlim->rlim_max) return current_has_perm(p, PROCESS__SETRLIMIT); return 0; } static int selinux_task_setscheduler(struct task_struct *p) { int rc; rc = cap_task_setscheduler(p); if (rc) return rc; return current_has_perm(p, PROCESS__SETSCHED); } static int selinux_task_getscheduler(struct task_struct *p) { return current_has_perm(p, PROCESS__GETSCHED); } static int selinux_task_movememory(struct task_struct *p) { return current_has_perm(p, PROCESS__SETSCHED); } static int selinux_task_kill(struct task_struct *p, struct siginfo *info, int sig, u32 secid) { u32 perm; int rc; if (!sig) perm = PROCESS__SIGNULL; /* null signal; existence test */ else perm = signal_to_av(sig); if (secid) rc = avc_has_perm(secid, task_sid(p), SECCLASS_PROCESS, perm, NULL); else rc = current_has_perm(p, perm); return rc; } static int selinux_task_wait(struct task_struct *p) { return task_has_perm(p, current, PROCESS__SIGCHLD); } static void selinux_task_to_inode(struct task_struct *p, struct inode *inode) { struct inode_security_struct *isec = inode->i_security; u32 sid = task_sid(p); isec->sid = sid; isec->initialized = 1; } /* Returns error only if unable to parse addresses */ static int selinux_parse_skb_ipv4(struct sk_buff *skb, struct common_audit_data *ad, u8 *proto) { int offset, ihlen, ret = -EINVAL; struct iphdr _iph, *ih; offset = skb_network_offset(skb); ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph); if (ih == NULL) goto out; ihlen = ih->ihl * 4; if (ihlen < sizeof(_iph)) goto out; ad->u.net.v4info.saddr = ih->saddr; ad->u.net.v4info.daddr = ih->daddr; ret = 0; if (proto) *proto = ih->protocol; switch (ih->protocol) { case IPPROTO_TCP: { struct tcphdr _tcph, *th; if (ntohs(ih->frag_off) & IP_OFFSET) break; offset += ihlen; th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph); if (th == NULL) break; ad->u.net.sport = th->source; ad->u.net.dport = th->dest; break; } case IPPROTO_UDP: { struct udphdr _udph, *uh; if (ntohs(ih->frag_off) & IP_OFFSET) break; offset += ihlen; uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph); if (uh == NULL) break; ad->u.net.sport = uh->source; ad->u.net.dport = uh->dest; break; } case IPPROTO_DCCP: { struct dccp_hdr _dccph, *dh; if (ntohs(ih->frag_off) & IP_OFFSET) break; offset += ihlen; dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph); if (dh == NULL) break; ad->u.net.sport = dh->dccph_sport; ad->u.net.dport = dh->dccph_dport; break; } default: break; } out: return ret; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) /* Returns error only if unable to parse addresses */ static int selinux_parse_skb_ipv6(struct sk_buff *skb, struct common_audit_data *ad, u8 *proto) { u8 nexthdr; int ret = -EINVAL, offset; struct ipv6hdr _ipv6h, *ip6; offset = skb_network_offset(skb); ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h); if (ip6 == NULL) goto out; ipv6_addr_copy(&ad->u.net.v6info.saddr, &ip6->saddr); ipv6_addr_copy(&ad->u.net.v6info.daddr, &ip6->daddr); ret = 0; nexthdr = ip6->nexthdr; offset += sizeof(_ipv6h); offset = ipv6_skip_exthdr(skb, offset, &nexthdr); if (offset < 0) goto out; if (proto) *proto = nexthdr; switch (nexthdr) { case IPPROTO_TCP: { struct tcphdr _tcph, *th; th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph); if (th == NULL) break; ad->u.net.sport = th->source; ad->u.net.dport = th->dest; break; } case IPPROTO_UDP: { struct udphdr _udph, *uh; uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph); if (uh == NULL) break; ad->u.net.sport = uh->source; ad->u.net.dport = uh->dest; break; } case IPPROTO_DCCP: { struct dccp_hdr _dccph, *dh; dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph); if (dh == NULL) break; ad->u.net.sport = dh->dccph_sport; ad->u.net.dport = dh->dccph_dport; break; } /* includes fragments */ default: break; } out: return ret; } #endif /* IPV6 */ static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad, char **_addrp, int src, u8 *proto) { char *addrp; int ret; switch (ad->u.net.family) { case PF_INET: ret = selinux_parse_skb_ipv4(skb, ad, proto); if (ret) goto parse_error; addrp = (char *)(src ? &ad->u.net.v4info.saddr : &ad->u.net.v4info.daddr); goto okay; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case PF_INET6: ret = selinux_parse_skb_ipv6(skb, ad, proto); if (ret) goto parse_error; addrp = (char *)(src ? &ad->u.net.v6info.saddr : &ad->u.net.v6info.daddr); goto okay; #endif /* IPV6 */ default: addrp = NULL; goto okay; } parse_error: printk(KERN_WARNING "SELinux: failure in selinux_parse_skb()," " unable to parse packet\n"); return ret; okay: if (_addrp) *_addrp = addrp; return 0; } /** * selinux_skb_peerlbl_sid - Determine the peer label of a packet * @skb: the packet * @family: protocol family * @sid: the packet's peer label SID * * Description: * Check the various different forms of network peer labeling and determine * the peer label/SID for the packet; most of the magic actually occurs in * the security server function security_net_peersid_cmp(). The function * returns zero if the value in @sid is valid (although it may be SECSID_NULL) * or -EACCES if @sid is invalid due to inconsistencies with the different * peer labels. * */ static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid) { int err; u32 xfrm_sid; u32 nlbl_sid; u32 nlbl_type; selinux_skb_xfrm_sid(skb, &xfrm_sid); selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid); err = security_net_peersid_resolve(nlbl_sid, nlbl_type, xfrm_sid, sid); if (unlikely(err)) { printk(KERN_WARNING "SELinux: failure in selinux_skb_peerlbl_sid()," " unable to determine packet's peer label\n"); return -EACCES; } return 0; } /* socket security operations */ static int socket_sockcreate_sid(const struct task_security_struct *tsec, u16 secclass, u32 *socksid) { if (tsec->sockcreate_sid > SECSID_NULL) { *socksid = tsec->sockcreate_sid; return 0; } return security_transition_sid(tsec->sid, tsec->sid, secclass, NULL, socksid); } static int sock_has_perm(struct task_struct *task, struct sock *sk, u32 perms) { struct sk_security_struct *sksec = sk->sk_security; struct common_audit_data ad; u32 tsid = task_sid(task); if (sksec->sid == SECINITSID_KERNEL) return 0; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.sk = sk; return avc_has_perm(tsid, sksec->sid, sksec->sclass, perms, &ad); } static int selinux_socket_create(int family, int type, int protocol, int kern) { const struct task_security_struct *tsec = current_security(); u32 newsid; u16 secclass; int rc; if (kern) return 0; secclass = socket_type_to_security_class(family, type, protocol); rc = socket_sockcreate_sid(tsec, secclass, &newsid); if (rc) return rc; return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL); } static int selinux_socket_post_create(struct socket *sock, int family, int type, int protocol, int kern) { const struct task_security_struct *tsec = current_security(); struct inode_security_struct *isec = SOCK_INODE(sock)->i_security; struct sk_security_struct *sksec; int err = 0; isec->sclass = socket_type_to_security_class(family, type, protocol); if (kern) isec->sid = SECINITSID_KERNEL; else { err = socket_sockcreate_sid(tsec, isec->sclass, &(isec->sid)); if (err) return err; } isec->initialized = 1; if (sock->sk) { sksec = sock->sk->sk_security; sksec->sid = isec->sid; sksec->sclass = isec->sclass; err = selinux_netlbl_socket_post_create(sock->sk, family); } return err; } /* Range of port numbers used to automatically bind. Need to determine whether we should perform a name_bind permission check between the socket and the port number. */ static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen) { struct sock *sk = sock->sk; u16 family; int err; err = sock_has_perm(current, sk, SOCKET__BIND); if (err) goto out; /* * If PF_INET or PF_INET6, check name_bind permission for the port. * Multiple address binding for SCTP is not supported yet: we just * check the first address now. */ family = sk->sk_family; if (family == PF_INET || family == PF_INET6) { char *addrp; struct sk_security_struct *sksec = sk->sk_security; struct common_audit_data ad; struct sockaddr_in *addr4 = NULL; struct sockaddr_in6 *addr6 = NULL; unsigned short snum; u32 sid, node_perm; if (family == PF_INET) { addr4 = (struct sockaddr_in *)address; snum = ntohs(addr4->sin_port); addrp = (char *)&addr4->sin_addr.s_addr; } else { addr6 = (struct sockaddr_in6 *)address; snum = ntohs(addr6->sin6_port); addrp = (char *)&addr6->sin6_addr.s6_addr; } if (snum) { int low, high; inet_get_local_port_range(&low, &high); if (snum < max(PROT_SOCK, low) || snum > high) { err = sel_netport_sid(sk->sk_protocol, snum, &sid); if (err) goto out; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.sport = htons(snum); ad.u.net.family = family; err = avc_has_perm(sksec->sid, sid, sksec->sclass, SOCKET__NAME_BIND, &ad); if (err) goto out; } } switch (sksec->sclass) { case SECCLASS_TCP_SOCKET: node_perm = TCP_SOCKET__NODE_BIND; break; case SECCLASS_UDP_SOCKET: node_perm = UDP_SOCKET__NODE_BIND; break; case SECCLASS_DCCP_SOCKET: node_perm = DCCP_SOCKET__NODE_BIND; break; default: node_perm = RAWIP_SOCKET__NODE_BIND; break; } err = sel_netnode_sid(addrp, family, &sid); if (err) goto out; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.sport = htons(snum); ad.u.net.family = family; if (family == PF_INET) ad.u.net.v4info.saddr = addr4->sin_addr.s_addr; else ipv6_addr_copy(&ad.u.net.v6info.saddr, &addr6->sin6_addr); err = avc_has_perm(sksec->sid, sid, sksec->sclass, node_perm, &ad); if (err) goto out; } out: return err; } static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen) { struct sock *sk = sock->sk; struct sk_security_struct *sksec = sk->sk_security; int err; err = sock_has_perm(current, sk, SOCKET__CONNECT); if (err) return err; /* * If a TCP or DCCP socket, check name_connect permission for the port. */ if (sksec->sclass == SECCLASS_TCP_SOCKET || sksec->sclass == SECCLASS_DCCP_SOCKET) { struct common_audit_data ad; struct sockaddr_in *addr4 = NULL; struct sockaddr_in6 *addr6 = NULL; unsigned short snum; u32 sid, perm; if (sk->sk_family == PF_INET) { addr4 = (struct sockaddr_in *)address; if (addrlen < sizeof(struct sockaddr_in)) return -EINVAL; snum = ntohs(addr4->sin_port); } else { addr6 = (struct sockaddr_in6 *)address; if (addrlen < SIN6_LEN_RFC2133) return -EINVAL; snum = ntohs(addr6->sin6_port); } err = sel_netport_sid(sk->sk_protocol, snum, &sid); if (err) goto out; perm = (sksec->sclass == SECCLASS_TCP_SOCKET) ? TCP_SOCKET__NAME_CONNECT : DCCP_SOCKET__NAME_CONNECT; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.dport = htons(snum); ad.u.net.family = sk->sk_family; err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad); if (err) goto out; } err = selinux_netlbl_socket_connect(sk, address); out: return err; } static int selinux_socket_listen(struct socket *sock, int backlog) { return sock_has_perm(current, sock->sk, SOCKET__LISTEN); } static int selinux_socket_accept(struct socket *sock, struct socket *newsock) { int err; struct inode_security_struct *isec; struct inode_security_struct *newisec; err = sock_has_perm(current, sock->sk, SOCKET__ACCEPT); if (err) return err; newisec = SOCK_INODE(newsock)->i_security; isec = SOCK_INODE(sock)->i_security; newisec->sclass = isec->sclass; newisec->sid = isec->sid; newisec->initialized = 1; return 0; } static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg, int size) { return sock_has_perm(current, sock->sk, SOCKET__WRITE); } static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg, int size, int flags) { return sock_has_perm(current, sock->sk, SOCKET__READ); } static int selinux_socket_getsockname(struct socket *sock) { return sock_has_perm(current, sock->sk, SOCKET__GETATTR); } static int selinux_socket_getpeername(struct socket *sock) { return sock_has_perm(current, sock->sk, SOCKET__GETATTR); } static int selinux_socket_setsockopt(struct socket *sock, int level, int optname) { int err; err = sock_has_perm(current, sock->sk, SOCKET__SETOPT); if (err) return err; return selinux_netlbl_socket_setsockopt(sock, level, optname); } static int selinux_socket_getsockopt(struct socket *sock, int level, int optname) { return sock_has_perm(current, sock->sk, SOCKET__GETOPT); } static int selinux_socket_shutdown(struct socket *sock, int how) { return sock_has_perm(current, sock->sk, SOCKET__SHUTDOWN); } static int selinux_socket_unix_stream_connect(struct sock *sock, struct sock *other, struct sock *newsk) { struct sk_security_struct *sksec_sock = sock->sk_security; struct sk_security_struct *sksec_other = other->sk_security; struct sk_security_struct *sksec_new = newsk->sk_security; struct common_audit_data ad; int err; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.sk = other; err = avc_has_perm(sksec_sock->sid, sksec_other->sid, sksec_other->sclass, UNIX_STREAM_SOCKET__CONNECTTO, &ad); if (err) return err; /* server child socket */ sksec_new->peer_sid = sksec_sock->sid; err = security_sid_mls_copy(sksec_other->sid, sksec_sock->sid, &sksec_new->sid); if (err) return err; /* connecting socket */ sksec_sock->peer_sid = sksec_new->sid; return 0; } static int selinux_socket_unix_may_send(struct socket *sock, struct socket *other) { struct sk_security_struct *ssec = sock->sk->sk_security; struct sk_security_struct *osec = other->sk->sk_security; struct common_audit_data ad; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.sk = other->sk; return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO, &ad); } static int selinux_inet_sys_rcv_skb(int ifindex, char *addrp, u16 family, u32 peer_sid, struct common_audit_data *ad) { int err; u32 if_sid; u32 node_sid; err = sel_netif_sid(ifindex, &if_sid); if (err) return err; err = avc_has_perm(peer_sid, if_sid, SECCLASS_NETIF, NETIF__INGRESS, ad); if (err) return err; err = sel_netnode_sid(addrp, family, &node_sid); if (err) return err; return avc_has_perm(peer_sid, node_sid, SECCLASS_NODE, NODE__RECVFROM, ad); } static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb, u16 family) { int err = 0; struct sk_security_struct *sksec = sk->sk_security; u32 sk_sid = sksec->sid; struct common_audit_data ad; char *addrp; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.netif = skb->skb_iif; ad.u.net.family = family; err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL); if (err) return err; if (selinux_secmark_enabled()) { err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET, PACKET__RECV, &ad); if (err) return err; } err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad); if (err) return err; err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad); return err; } static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; struct sk_security_struct *sksec = sk->sk_security; u16 family = sk->sk_family; u32 sk_sid = sksec->sid; struct common_audit_data ad; char *addrp; u8 secmark_active; u8 peerlbl_active; if (family != PF_INET && family != PF_INET6) return 0; /* Handle mapped IPv4 packets arriving via IPv6 sockets */ if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP)) family = PF_INET; /* If any sort of compatibility mode is enabled then handoff processing * to the selinux_sock_rcv_skb_compat() function to deal with the * special handling. We do this in an attempt to keep this function * as fast and as clean as possible. */ if (!selinux_policycap_netpeer) return selinux_sock_rcv_skb_compat(sk, skb, family); secmark_active = selinux_secmark_enabled(); peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled(); if (!secmark_active && !peerlbl_active) return 0; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.netif = skb->skb_iif; ad.u.net.family = family; err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL); if (err) return err; if (peerlbl_active) { u32 peer_sid; err = selinux_skb_peerlbl_sid(skb, family, &peer_sid); if (err) return err; err = selinux_inet_sys_rcv_skb(skb->skb_iif, addrp, family, peer_sid, &ad); if (err) { selinux_netlbl_err(skb, err, 0); return err; } err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER, PEER__RECV, &ad); if (err) selinux_netlbl_err(skb, err, 0); } if (secmark_active) { err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET, PACKET__RECV, &ad); if (err) return err; } return err; } static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval, int __user *optlen, unsigned len) { int err = 0; char *scontext; u32 scontext_len; struct sk_security_struct *sksec = sock->sk->sk_security; u32 peer_sid = SECSID_NULL; if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET || sksec->sclass == SECCLASS_TCP_SOCKET) peer_sid = sksec->peer_sid; if (peer_sid == SECSID_NULL) return -ENOPROTOOPT; err = security_sid_to_context(peer_sid, &scontext, &scontext_len); if (err) return err; if (scontext_len > len) { err = -ERANGE; goto out_len; } if (copy_to_user(optval, scontext, scontext_len)) err = -EFAULT; out_len: if (put_user(scontext_len, optlen)) err = -EFAULT; kfree(scontext); return err; } static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid) { u32 peer_secid = SECSID_NULL; u16 family; if (skb && skb->protocol == htons(ETH_P_IP)) family = PF_INET; else if (skb && skb->protocol == htons(ETH_P_IPV6)) family = PF_INET6; else if (sock) family = sock->sk->sk_family; else goto out; if (sock && family == PF_UNIX) selinux_inode_getsecid(SOCK_INODE(sock), &peer_secid); else if (skb) selinux_skb_peerlbl_sid(skb, family, &peer_secid); out: *secid = peer_secid; if (peer_secid == SECSID_NULL) return -EINVAL; return 0; } static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority) { struct sk_security_struct *sksec; sksec = kzalloc(sizeof(*sksec), priority); if (!sksec) return -ENOMEM; sksec->peer_sid = SECINITSID_UNLABELED; sksec->sid = SECINITSID_UNLABELED; selinux_netlbl_sk_security_reset(sksec); sk->sk_security = sksec; return 0; } static void selinux_sk_free_security(struct sock *sk) { struct sk_security_struct *sksec = sk->sk_security; sk->sk_security = NULL; selinux_netlbl_sk_security_free(sksec); kfree(sksec); } static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk) { struct sk_security_struct *sksec = sk->sk_security; struct sk_security_struct *newsksec = newsk->sk_security; newsksec->sid = sksec->sid; newsksec->peer_sid = sksec->peer_sid; newsksec->sclass = sksec->sclass; selinux_netlbl_sk_security_reset(newsksec); } static void selinux_sk_getsecid(struct sock *sk, u32 *secid) { if (!sk) *secid = SECINITSID_ANY_SOCKET; else { struct sk_security_struct *sksec = sk->sk_security; *secid = sksec->sid; } } static void selinux_sock_graft(struct sock *sk, struct socket *parent) { struct inode_security_struct *isec = SOCK_INODE(parent)->i_security; struct sk_security_struct *sksec = sk->sk_security; if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 || sk->sk_family == PF_UNIX) isec->sid = sksec->sid; sksec->sclass = isec->sclass; } static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb, struct request_sock *req) { struct sk_security_struct *sksec = sk->sk_security; int err; u16 family = sk->sk_family; u32 newsid; u32 peersid; /* handle mapped IPv4 packets arriving via IPv6 sockets */ if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP)) family = PF_INET; err = selinux_skb_peerlbl_sid(skb, family, &peersid); if (err) return err; if (peersid == SECSID_NULL) { req->secid = sksec->sid; req->peer_secid = SECSID_NULL; } else { err = security_sid_mls_copy(sksec->sid, peersid, &newsid); if (err) return err; req->secid = newsid; req->peer_secid = peersid; } return selinux_netlbl_inet_conn_request(req, family); } static void selinux_inet_csk_clone(struct sock *newsk, const struct request_sock *req) { struct sk_security_struct *newsksec = newsk->sk_security; newsksec->sid = req->secid; newsksec->peer_sid = req->peer_secid; /* NOTE: Ideally, we should also get the isec->sid for the new socket in sync, but we don't have the isec available yet. So we will wait until sock_graft to do it, by which time it will have been created and available. */ /* We don't need to take any sort of lock here as we are the only * thread with access to newsksec */ selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family); } static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb) { u16 family = sk->sk_family; struct sk_security_struct *sksec = sk->sk_security; /* handle mapped IPv4 packets arriving via IPv6 sockets */ if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP)) family = PF_INET; selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid); } static int selinux_secmark_relabel_packet(u32 sid) { const struct task_security_struct *__tsec; u32 tsid; __tsec = current_security(); tsid = __tsec->sid; return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO, NULL); } static void selinux_secmark_refcount_inc(void) { atomic_inc(&selinux_secmark_refcount); } static void selinux_secmark_refcount_dec(void) { atomic_dec(&selinux_secmark_refcount); } static void selinux_req_classify_flow(const struct request_sock *req, struct flowi *fl) { fl->flowi_secid = req->secid; } static int selinux_tun_dev_create(void) { u32 sid = current_sid(); /* we aren't taking into account the "sockcreate" SID since the socket * that is being created here is not a socket in the traditional sense, * instead it is a private sock, accessible only to the kernel, and * representing a wide range of network traffic spanning multiple * connections unlike traditional sockets - check the TUN driver to * get a better understanding of why this socket is special */ return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE, NULL); } static void selinux_tun_dev_post_create(struct sock *sk) { struct sk_security_struct *sksec = sk->sk_security; /* we don't currently perform any NetLabel based labeling here and it * isn't clear that we would want to do so anyway; while we could apply * labeling without the support of the TUN user the resulting labeled * traffic from the other end of the connection would almost certainly * cause confusion to the TUN user that had no idea network labeling * protocols were being used */ /* see the comments in selinux_tun_dev_create() about why we don't use * the sockcreate SID here */ sksec->sid = current_sid(); sksec->sclass = SECCLASS_TUN_SOCKET; } static int selinux_tun_dev_attach(struct sock *sk) { struct sk_security_struct *sksec = sk->sk_security; u32 sid = current_sid(); int err; err = avc_has_perm(sid, sksec->sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__RELABELFROM, NULL); if (err) return err; err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__RELABELTO, NULL); if (err) return err; sksec->sid = sid; return 0; } static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb) { int err = 0; u32 perm; struct nlmsghdr *nlh; struct sk_security_struct *sksec = sk->sk_security; if (skb->len < NLMSG_SPACE(0)) { err = -EINVAL; goto out; } nlh = nlmsg_hdr(skb); err = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm); if (err) { if (err == -EINVAL) { audit_log(current->audit_context, GFP_KERNEL, AUDIT_SELINUX_ERR, "SELinux: unrecognized netlink message" " type=%hu for sclass=%hu\n", nlh->nlmsg_type, sksec->sclass); if (!selinux_enforcing || security_get_allow_unknown()) err = 0; } /* Ignore */ if (err == -ENOENT) err = 0; goto out; } err = sock_has_perm(current, sk, perm); out: return err; } #ifdef CONFIG_NETFILTER static unsigned int selinux_ip_forward(struct sk_buff *skb, int ifindex, u16 family) { int err; char *addrp; u32 peer_sid; struct common_audit_data ad; u8 secmark_active; u8 netlbl_active; u8 peerlbl_active; if (!selinux_policycap_netpeer) return NF_ACCEPT; secmark_active = selinux_secmark_enabled(); netlbl_active = netlbl_enabled(); peerlbl_active = netlbl_active || selinux_xfrm_enabled(); if (!secmark_active && !peerlbl_active) return NF_ACCEPT; if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0) return NF_DROP; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.netif = ifindex; ad.u.net.family = family; if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0) return NF_DROP; if (peerlbl_active) { err = selinux_inet_sys_rcv_skb(ifindex, addrp, family, peer_sid, &ad); if (err) { selinux_netlbl_err(skb, err, 1); return NF_DROP; } } if (secmark_active) if (avc_has_perm(peer_sid, skb->secmark, SECCLASS_PACKET, PACKET__FORWARD_IN, &ad)) return NF_DROP; if (netlbl_active) /* we do this in the FORWARD path and not the POST_ROUTING * path because we want to make sure we apply the necessary * labeling before IPsec is applied so we can leverage AH * protection */ if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0) return NF_DROP; return NF_ACCEPT; } static unsigned int selinux_ipv4_forward(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { return selinux_ip_forward(skb, in->ifindex, PF_INET); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static unsigned int selinux_ipv6_forward(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { return selinux_ip_forward(skb, in->ifindex, PF_INET6); } #endif /* IPV6 */ static unsigned int selinux_ip_output(struct sk_buff *skb, u16 family) { u32 sid; if (!netlbl_enabled()) return NF_ACCEPT; /* we do this in the LOCAL_OUT path and not the POST_ROUTING path * because we want to make sure we apply the necessary labeling * before IPsec is applied so we can leverage AH protection */ if (skb->sk) { struct sk_security_struct *sksec = skb->sk->sk_security; sid = sksec->sid; } else sid = SECINITSID_KERNEL; if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0) return NF_DROP; return NF_ACCEPT; } static unsigned int selinux_ipv4_output(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { return selinux_ip_output(skb, PF_INET); } static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb, int ifindex, u16 family) { struct sock *sk = skb->sk; struct sk_security_struct *sksec; struct common_audit_data ad; char *addrp; u8 proto; if (sk == NULL) return NF_ACCEPT; sksec = sk->sk_security; COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.netif = ifindex; ad.u.net.family = family; if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto)) return NF_DROP; if (selinux_secmark_enabled()) if (avc_has_perm(sksec->sid, skb->secmark, SECCLASS_PACKET, PACKET__SEND, &ad)) return NF_DROP_ERR(-ECONNREFUSED); if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto)) return NF_DROP_ERR(-ECONNREFUSED); return NF_ACCEPT; } static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex, u16 family) { u32 secmark_perm; u32 peer_sid; struct sock *sk; struct common_audit_data ad; char *addrp; u8 secmark_active; u8 peerlbl_active; /* If any sort of compatibility mode is enabled then handoff processing * to the selinux_ip_postroute_compat() function to deal with the * special handling. We do this in an attempt to keep this function * as fast and as clean as possible. */ if (!selinux_policycap_netpeer) return selinux_ip_postroute_compat(skb, ifindex, family); #ifdef CONFIG_XFRM /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec * packet transformation so allow the packet to pass without any checks * since we'll have another chance to perform access control checks * when the packet is on it's final way out. * NOTE: there appear to be some IPv6 multicast cases where skb->dst * is NULL, in this case go ahead and apply access control. */ if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL) return NF_ACCEPT; #endif secmark_active = selinux_secmark_enabled(); peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled(); if (!secmark_active && !peerlbl_active) return NF_ACCEPT; /* if the packet is being forwarded then get the peer label from the * packet itself; otherwise check to see if it is from a local * application or the kernel, if from an application get the peer label * from the sending socket, otherwise use the kernel's sid */ sk = skb->sk; if (sk == NULL) { if (skb->skb_iif) { secmark_perm = PACKET__FORWARD_OUT; if (selinux_skb_peerlbl_sid(skb, family, &peer_sid)) return NF_DROP; } else { secmark_perm = PACKET__SEND; peer_sid = SECINITSID_KERNEL; } } else { struct sk_security_struct *sksec = sk->sk_security; peer_sid = sksec->sid; secmark_perm = PACKET__SEND; } COMMON_AUDIT_DATA_INIT(&ad, NET); ad.u.net.netif = ifindex; ad.u.net.family = family; if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL)) return NF_DROP; if (secmark_active) if (avc_has_perm(peer_sid, skb->secmark, SECCLASS_PACKET, secmark_perm, &ad)) return NF_DROP_ERR(-ECONNREFUSED); if (peerlbl_active) { u32 if_sid; u32 node_sid; if (sel_netif_sid(ifindex, &if_sid)) return NF_DROP; if (avc_has_perm(peer_sid, if_sid, SECCLASS_NETIF, NETIF__EGRESS, &ad)) return NF_DROP_ERR(-ECONNREFUSED); if (sel_netnode_sid(addrp, family, &node_sid)) return NF_DROP; if (avc_has_perm(peer_sid, node_sid, SECCLASS_NODE, NODE__SENDTO, &ad)) return NF_DROP_ERR(-ECONNREFUSED); } return NF_ACCEPT; } static unsigned int selinux_ipv4_postroute(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { return selinux_ip_postroute(skb, out->ifindex, PF_INET); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static unsigned int selinux_ipv6_postroute(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { return selinux_ip_postroute(skb, out->ifindex, PF_INET6); } #endif /* IPV6 */ #endif /* CONFIG_NETFILTER */ static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb) { int err; err = cap_netlink_send(sk, skb); if (err) return err; return selinux_nlmsg_perm(sk, skb); } static int selinux_netlink_recv(struct sk_buff *skb, int capability) { int err; struct common_audit_data ad; u32 sid; err = cap_netlink_recv(skb, capability); if (err) return err; COMMON_AUDIT_DATA_INIT(&ad, CAP); ad.u.cap = capability; security_task_getsecid(current, &sid); return avc_has_perm(sid, sid, SECCLASS_CAPABILITY, CAP_TO_MASK(capability), &ad); } static int ipc_alloc_security(struct task_struct *task, struct kern_ipc_perm *perm, u16 sclass) { struct ipc_security_struct *isec; u32 sid; isec = kzalloc(sizeof(struct ipc_security_struct), GFP_KERNEL); if (!isec) return -ENOMEM; sid = task_sid(task); isec->sclass = sclass; isec->sid = sid; perm->security = isec; return 0; } static void ipc_free_security(struct kern_ipc_perm *perm) { struct ipc_security_struct *isec = perm->security; perm->security = NULL; kfree(isec); } static int msg_msg_alloc_security(struct msg_msg *msg) { struct msg_security_struct *msec; msec = kzalloc(sizeof(struct msg_security_struct), GFP_KERNEL); if (!msec) return -ENOMEM; msec->sid = SECINITSID_UNLABELED; msg->security = msec; return 0; } static void msg_msg_free_security(struct msg_msg *msg) { struct msg_security_struct *msec = msg->security; msg->security = NULL; kfree(msec); } static int ipc_has_perm(struct kern_ipc_perm *ipc_perms, u32 perms) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); isec = ipc_perms->security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = ipc_perms->key; return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad); } static int selinux_msg_msg_alloc_security(struct msg_msg *msg) { return msg_msg_alloc_security(msg); } static void selinux_msg_msg_free_security(struct msg_msg *msg) { msg_msg_free_security(msg); } /* message queue security operations */ static int selinux_msg_queue_alloc_security(struct msg_queue *msq) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); int rc; rc = ipc_alloc_security(current, &msq->q_perm, SECCLASS_MSGQ); if (rc) return rc; isec = msq->q_perm.security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = msq->q_perm.key; rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ, MSGQ__CREATE, &ad); if (rc) { ipc_free_security(&msq->q_perm); return rc; } return 0; } static void selinux_msg_queue_free_security(struct msg_queue *msq) { ipc_free_security(&msq->q_perm); } static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); isec = msq->q_perm.security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = msq->q_perm.key; return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ, MSGQ__ASSOCIATE, &ad); } static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd) { int err; int perms; switch (cmd) { case IPC_INFO: case MSG_INFO: /* No specific object, just general system-wide information. */ return task_has_system(current, SYSTEM__IPC_INFO); case IPC_STAT: case MSG_STAT: perms = MSGQ__GETATTR | MSGQ__ASSOCIATE; break; case IPC_SET: perms = MSGQ__SETATTR; break; case IPC_RMID: perms = MSGQ__DESTROY; break; default: return 0; } err = ipc_has_perm(&msq->q_perm, perms); return err; } static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg) { struct ipc_security_struct *isec; struct msg_security_struct *msec; struct common_audit_data ad; u32 sid = current_sid(); int rc; isec = msq->q_perm.security; msec = msg->security; /* * First time through, need to assign label to the message */ if (msec->sid == SECINITSID_UNLABELED) { /* * Compute new sid based on current process and * message queue this message will be stored in */ rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG, NULL, &msec->sid); if (rc) return rc; } COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = msq->q_perm.key; /* Can this process write to the queue? */ rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ, MSGQ__WRITE, &ad); if (!rc) /* Can this process send the message */ rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG, MSG__SEND, &ad); if (!rc) /* Can the message be put in the queue? */ rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ, MSGQ__ENQUEUE, &ad); return rc; } static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg, struct task_struct *target, long type, int mode) { struct ipc_security_struct *isec; struct msg_security_struct *msec; struct common_audit_data ad; u32 sid = task_sid(target); int rc; isec = msq->q_perm.security; msec = msg->security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = msq->q_perm.key; rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ, MSGQ__READ, &ad); if (!rc) rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG, MSG__RECEIVE, &ad); return rc; } /* Shared Memory security operations */ static int selinux_shm_alloc_security(struct shmid_kernel *shp) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); int rc; rc = ipc_alloc_security(current, &shp->shm_perm, SECCLASS_SHM); if (rc) return rc; isec = shp->shm_perm.security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = shp->shm_perm.key; rc = avc_has_perm(sid, isec->sid, SECCLASS_SHM, SHM__CREATE, &ad); if (rc) { ipc_free_security(&shp->shm_perm); return rc; } return 0; } static void selinux_shm_free_security(struct shmid_kernel *shp) { ipc_free_security(&shp->shm_perm); } static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); isec = shp->shm_perm.security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = shp->shm_perm.key; return avc_has_perm(sid, isec->sid, SECCLASS_SHM, SHM__ASSOCIATE, &ad); } /* Note, at this point, shp is locked down */ static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd) { int perms; int err; switch (cmd) { case IPC_INFO: case SHM_INFO: /* No specific object, just general system-wide information. */ return task_has_system(current, SYSTEM__IPC_INFO); case IPC_STAT: case SHM_STAT: perms = SHM__GETATTR | SHM__ASSOCIATE; break; case IPC_SET: perms = SHM__SETATTR; break; case SHM_LOCK: case SHM_UNLOCK: perms = SHM__LOCK; break; case IPC_RMID: perms = SHM__DESTROY; break; default: return 0; } err = ipc_has_perm(&shp->shm_perm, perms); return err; } static int selinux_shm_shmat(struct shmid_kernel *shp, char __user *shmaddr, int shmflg) { u32 perms; if (shmflg & SHM_RDONLY) perms = SHM__READ; else perms = SHM__READ | SHM__WRITE; return ipc_has_perm(&shp->shm_perm, perms); } /* Semaphore security operations */ static int selinux_sem_alloc_security(struct sem_array *sma) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); int rc; rc = ipc_alloc_security(current, &sma->sem_perm, SECCLASS_SEM); if (rc) return rc; isec = sma->sem_perm.security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = sma->sem_perm.key; rc = avc_has_perm(sid, isec->sid, SECCLASS_SEM, SEM__CREATE, &ad); if (rc) { ipc_free_security(&sma->sem_perm); return rc; } return 0; } static void selinux_sem_free_security(struct sem_array *sma) { ipc_free_security(&sma->sem_perm); } static int selinux_sem_associate(struct sem_array *sma, int semflg) { struct ipc_security_struct *isec; struct common_audit_data ad; u32 sid = current_sid(); isec = sma->sem_perm.security; COMMON_AUDIT_DATA_INIT(&ad, IPC); ad.u.ipc_id = sma->sem_perm.key; return avc_has_perm(sid, isec->sid, SECCLASS_SEM, SEM__ASSOCIATE, &ad); } /* Note, at this point, sma is locked down */ static int selinux_sem_semctl(struct sem_array *sma, int cmd) { int err; u32 perms; switch (cmd) { case IPC_INFO: case SEM_INFO: /* No specific object, just general system-wide information. */ return task_has_system(current, SYSTEM__IPC_INFO); case GETPID: case GETNCNT: case GETZCNT: perms = SEM__GETATTR; break; case GETVAL: case GETALL: perms = SEM__READ; break; case SETVAL: case SETALL: perms = SEM__WRITE; break; case IPC_RMID: perms = SEM__DESTROY; break; case IPC_SET: perms = SEM__SETATTR; break; case IPC_STAT: case SEM_STAT: perms = SEM__GETATTR | SEM__ASSOCIATE; break; default: return 0; } err = ipc_has_perm(&sma->sem_perm, perms); return err; } static int selinux_sem_semop(struct sem_array *sma, struct sembuf *sops, unsigned nsops, int alter) { u32 perms; if (alter) perms = SEM__READ | SEM__WRITE; else perms = SEM__READ; return ipc_has_perm(&sma->sem_perm, perms); } static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag) { u32 av = 0; av = 0; if (flag & S_IRUGO) av |= IPC__UNIX_READ; if (flag & S_IWUGO) av |= IPC__UNIX_WRITE; if (av == 0) return 0; return ipc_has_perm(ipcp, av); } static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid) { struct ipc_security_struct *isec = ipcp->security; *secid = isec->sid; } static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode) { if (inode) inode_doinit_with_dentry(inode, dentry); } static int selinux_getprocattr(struct task_struct *p, char *name, char **value) { const struct task_security_struct *__tsec; u32 sid; int error; unsigned len; if (current != p) { error = current_has_perm(p, PROCESS__GETATTR); if (error) return error; } rcu_read_lock(); __tsec = __task_cred(p)->security; if (!strcmp(name, "current")) sid = __tsec->sid; else if (!strcmp(name, "prev")) sid = __tsec->osid; else if (!strcmp(name, "exec")) sid = __tsec->exec_sid; else if (!strcmp(name, "fscreate")) sid = __tsec->create_sid; else if (!strcmp(name, "keycreate")) sid = __tsec->keycreate_sid; else if (!strcmp(name, "sockcreate")) sid = __tsec->sockcreate_sid; else goto invalid; rcu_read_unlock(); if (!sid) return 0; error = security_sid_to_context(sid, value, &len); if (error) return error; return len; invalid: rcu_read_unlock(); return -EINVAL; } static int selinux_setprocattr(struct task_struct *p, char *name, void *value, size_t size) { struct task_security_struct *tsec; struct task_struct *tracer; struct cred *new; u32 sid = 0, ptsid; int error; char *str = value; if (current != p) { /* SELinux only allows a process to change its own security attributes. */ return -EACCES; } /* * Basic control over ability to set these attributes at all. * current == p, but we'll pass them separately in case the * above restriction is ever removed. */ if (!strcmp(name, "exec")) error = current_has_perm(p, PROCESS__SETEXEC); else if (!strcmp(name, "fscreate")) error = current_has_perm(p, PROCESS__SETFSCREATE); else if (!strcmp(name, "keycreate")) error = current_has_perm(p, PROCESS__SETKEYCREATE); else if (!strcmp(name, "sockcreate")) error = current_has_perm(p, PROCESS__SETSOCKCREATE); else if (!strcmp(name, "current")) error = current_has_perm(p, PROCESS__SETCURRENT); else error = -EINVAL; if (error) return error; /* Obtain a SID for the context, if one was specified. */ if (size && str[1] && str[1] != '\n') { if (str[size-1] == '\n') { str[size-1] = 0; size--; } error = security_context_to_sid(value, size, &sid); if (error == -EINVAL && !strcmp(name, "fscreate")) { if (!capable(CAP_MAC_ADMIN)) return error; error = security_context_to_sid_force(value, size, &sid); } if (error) return error; } new = prepare_creds(); if (!new) return -ENOMEM; /* Permission checking based on the specified context is performed during the actual operation (execve, open/mkdir/...), when we know the full context of the operation. See selinux_bprm_set_creds for the execve checks and may_create for the file creation checks. The operation will then fail if the context is not permitted. */ tsec = new->security; if (!strcmp(name, "exec")) { tsec->exec_sid = sid; } else if (!strcmp(name, "fscreate")) { tsec->create_sid = sid; } else if (!strcmp(name, "keycreate")) { error = may_create_key(sid, p); if (error) goto abort_change; tsec->keycreate_sid = sid; } else if (!strcmp(name, "sockcreate")) { tsec->sockcreate_sid = sid; } else if (!strcmp(name, "current")) { error = -EINVAL; if (sid == 0) goto abort_change; /* Only allow single threaded processes to change context */ error = -EPERM; if (!current_is_single_threaded()) { error = security_bounded_transition(tsec->sid, sid); if (error) goto abort_change; } /* Check permissions for the transition. */ error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS, PROCESS__DYNTRANSITION, NULL); if (error) goto abort_change; /* Check for ptracing, and update the task SID if ok. Otherwise, leave SID unchanged and fail. */ ptsid = 0; task_lock(p); tracer = tracehook_tracer_task(p); if (tracer) ptsid = task_sid(tracer); task_unlock(p); if (tracer) { error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL); if (error) goto abort_change; } tsec->sid = sid; } else { error = -EINVAL; goto abort_change; } commit_creds(new); return size; abort_change: abort_creds(new); return error; } static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen) { return security_sid_to_context(secid, secdata, seclen); } static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid) { return security_context_to_sid(secdata, seclen, secid); } static void selinux_release_secctx(char *secdata, u32 seclen) { kfree(secdata); } /* * called with inode->i_mutex locked */ static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen) { return selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, ctxlen, 0); } /* * called with inode->i_mutex locked */ static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen) { return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0); } static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen) { int len = 0; len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, true); if (len < 0) return len; *ctxlen = len; return 0; } #ifdef CONFIG_KEYS static int selinux_key_alloc(struct key *k, const struct cred *cred, unsigned long flags) { const struct task_security_struct *tsec; struct key_security_struct *ksec; ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL); if (!ksec) return -ENOMEM; tsec = cred->security; if (tsec->keycreate_sid) ksec->sid = tsec->keycreate_sid; else ksec->sid = tsec->sid; k->security = ksec; return 0; } static void selinux_key_free(struct key *k) { struct key_security_struct *ksec = k->security; k->security = NULL; kfree(ksec); } static int selinux_key_permission(key_ref_t key_ref, const struct cred *cred, key_perm_t perm) { struct key *key; struct key_security_struct *ksec; u32 sid; /* if no specific permissions are requested, we skip the permission check. No serious, additional covert channels appear to be created. */ if (perm == 0) return 0; sid = cred_sid(cred); key = key_ref_to_ptr(key_ref); ksec = key->security; return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL); } static int selinux_key_getsecurity(struct key *key, char **_buffer) { struct key_security_struct *ksec = key->security; char *context = NULL; unsigned len; int rc; rc = security_sid_to_context(ksec->sid, &context, &len); if (!rc) rc = len; *_buffer = context; return rc; } #endif static struct security_operations selinux_ops = { .name = "selinux", .binder_set_context_mgr = selinux_binder_set_context_mgr, .binder_transaction = selinux_binder_transaction, .binder_transfer_binder = selinux_binder_transfer_binder, .binder_transfer_file = selinux_binder_transfer_file, .ptrace_access_check = selinux_ptrace_access_check, .ptrace_traceme = selinux_ptrace_traceme, .capget = selinux_capget, .capset = selinux_capset, .capable = selinux_capable, .quotactl = selinux_quotactl, .quota_on = selinux_quota_on, .syslog = selinux_syslog, .vm_enough_memory = selinux_vm_enough_memory, .netlink_send = selinux_netlink_send, .netlink_recv = selinux_netlink_recv, .bprm_set_creds = selinux_bprm_set_creds, .bprm_committing_creds = selinux_bprm_committing_creds, .bprm_committed_creds = selinux_bprm_committed_creds, .bprm_secureexec = selinux_bprm_secureexec, .sb_alloc_security = selinux_sb_alloc_security, .sb_free_security = selinux_sb_free_security, .sb_copy_data = selinux_sb_copy_data, .sb_remount = selinux_sb_remount, .sb_kern_mount = selinux_sb_kern_mount, .sb_show_options = selinux_sb_show_options, .sb_statfs = selinux_sb_statfs, .sb_mount = selinux_mount, .sb_umount = selinux_umount, .sb_set_mnt_opts = selinux_set_mnt_opts, .sb_clone_mnt_opts = selinux_sb_clone_mnt_opts, .sb_parse_opts_str = selinux_parse_opts_str, .inode_alloc_security = selinux_inode_alloc_security, .inode_free_security = selinux_inode_free_security, .inode_init_security = selinux_inode_init_security, .inode_create = selinux_inode_create, .inode_link = selinux_inode_link, .inode_unlink = selinux_inode_unlink, .inode_symlink = selinux_inode_symlink, .inode_mkdir = selinux_inode_mkdir, .inode_rmdir = selinux_inode_rmdir, .inode_mknod = selinux_inode_mknod, .inode_rename = selinux_inode_rename, .inode_readlink = selinux_inode_readlink, .inode_follow_link = selinux_inode_follow_link, .inode_permission = selinux_inode_permission, .inode_setattr = selinux_inode_setattr, .inode_getattr = selinux_inode_getattr, .inode_setxattr = selinux_inode_setxattr, .inode_post_setxattr = selinux_inode_post_setxattr, .inode_getxattr = selinux_inode_getxattr, .inode_listxattr = selinux_inode_listxattr, .inode_removexattr = selinux_inode_removexattr, .inode_getsecurity = selinux_inode_getsecurity, .inode_setsecurity = selinux_inode_setsecurity, .inode_listsecurity = selinux_inode_listsecurity, .inode_getsecid = selinux_inode_getsecid, .file_permission = selinux_file_permission, .file_alloc_security = selinux_file_alloc_security, .file_free_security = selinux_file_free_security, .file_ioctl = selinux_file_ioctl, .file_mmap = selinux_file_mmap, .file_mprotect = selinux_file_mprotect, .file_lock = selinux_file_lock, .file_fcntl = selinux_file_fcntl, .file_set_fowner = selinux_file_set_fowner, .file_send_sigiotask = selinux_file_send_sigiotask, .file_receive = selinux_file_receive, .dentry_open = selinux_dentry_open, .task_create = selinux_task_create, .cred_alloc_blank = selinux_cred_alloc_blank, .cred_free = selinux_cred_free, .cred_prepare = selinux_cred_prepare, .cred_transfer = selinux_cred_transfer, .kernel_act_as = selinux_kernel_act_as, .kernel_create_files_as = selinux_kernel_create_files_as, .kernel_module_request = selinux_kernel_module_request, .task_setpgid = selinux_task_setpgid, .task_getpgid = selinux_task_getpgid, .task_getsid = selinux_task_getsid, .task_getsecid = selinux_task_getsecid, .task_setnice = selinux_task_setnice, .task_setioprio = selinux_task_setioprio, .task_getioprio = selinux_task_getioprio, .task_setrlimit = selinux_task_setrlimit, .task_setscheduler = selinux_task_setscheduler, .task_getscheduler = selinux_task_getscheduler, .task_movememory = selinux_task_movememory, .task_kill = selinux_task_kill, .task_wait = selinux_task_wait, .task_to_inode = selinux_task_to_inode, .ipc_permission = selinux_ipc_permission, .ipc_getsecid = selinux_ipc_getsecid, .msg_msg_alloc_security = selinux_msg_msg_alloc_security, .msg_msg_free_security = selinux_msg_msg_free_security, .msg_queue_alloc_security = selinux_msg_queue_alloc_security, .msg_queue_free_security = selinux_msg_queue_free_security, .msg_queue_associate = selinux_msg_queue_associate, .msg_queue_msgctl = selinux_msg_queue_msgctl, .msg_queue_msgsnd = selinux_msg_queue_msgsnd, .msg_queue_msgrcv = selinux_msg_queue_msgrcv, .shm_alloc_security = selinux_shm_alloc_security, .shm_free_security = selinux_shm_free_security, .shm_associate = selinux_shm_associate, .shm_shmctl = selinux_shm_shmctl, .shm_shmat = selinux_shm_shmat, .sem_alloc_security = selinux_sem_alloc_security, .sem_free_security = selinux_sem_free_security, .sem_associate = selinux_sem_associate, .sem_semctl = selinux_sem_semctl, .sem_semop = selinux_sem_semop, .d_instantiate = selinux_d_instantiate, .getprocattr = selinux_getprocattr, .setprocattr = selinux_setprocattr, .secid_to_secctx = selinux_secid_to_secctx, .secctx_to_secid = selinux_secctx_to_secid, .release_secctx = selinux_release_secctx, .inode_notifysecctx = selinux_inode_notifysecctx, .inode_setsecctx = selinux_inode_setsecctx, .inode_getsecctx = selinux_inode_getsecctx, .unix_stream_connect = selinux_socket_unix_stream_connect, .unix_may_send = selinux_socket_unix_may_send, .socket_create = selinux_socket_create, .socket_post_create = selinux_socket_post_create, .socket_bind = selinux_socket_bind, .socket_connect = selinux_socket_connect, .socket_listen = selinux_socket_listen, .socket_accept = selinux_socket_accept, .socket_sendmsg = selinux_socket_sendmsg, .socket_recvmsg = selinux_socket_recvmsg, .socket_getsockname = selinux_socket_getsockname, .socket_getpeername = selinux_socket_getpeername, .socket_getsockopt = selinux_socket_getsockopt, .socket_setsockopt = selinux_socket_setsockopt, .socket_shutdown = selinux_socket_shutdown, .socket_sock_rcv_skb = selinux_socket_sock_rcv_skb, .socket_getpeersec_stream = selinux_socket_getpeersec_stream, .socket_getpeersec_dgram = selinux_socket_getpeersec_dgram, .sk_alloc_security = selinux_sk_alloc_security, .sk_free_security = selinux_sk_free_security, .sk_clone_security = selinux_sk_clone_security, .sk_getsecid = selinux_sk_getsecid, .sock_graft = selinux_sock_graft, .inet_conn_request = selinux_inet_conn_request, .inet_csk_clone = selinux_inet_csk_clone, .inet_conn_established = selinux_inet_conn_established, .secmark_relabel_packet = selinux_secmark_relabel_packet, .secmark_refcount_inc = selinux_secmark_refcount_inc, .secmark_refcount_dec = selinux_secmark_refcount_dec, .req_classify_flow = selinux_req_classify_flow, .tun_dev_create = selinux_tun_dev_create, .tun_dev_post_create = selinux_tun_dev_post_create, .tun_dev_attach = selinux_tun_dev_attach, #ifdef CONFIG_SECURITY_NETWORK_XFRM .xfrm_policy_alloc_security = selinux_xfrm_policy_alloc, .xfrm_policy_clone_security = selinux_xfrm_policy_clone, .xfrm_policy_free_security = selinux_xfrm_policy_free, .xfrm_policy_delete_security = selinux_xfrm_policy_delete, .xfrm_state_alloc_security = selinux_xfrm_state_alloc, .xfrm_state_free_security = selinux_xfrm_state_free, .xfrm_state_delete_security = selinux_xfrm_state_delete, .xfrm_policy_lookup = selinux_xfrm_policy_lookup, .xfrm_state_pol_flow_match = selinux_xfrm_state_pol_flow_match, .xfrm_decode_session = selinux_xfrm_decode_session, #endif #ifdef CONFIG_KEYS .key_alloc = selinux_key_alloc, .key_free = selinux_key_free, .key_permission = selinux_key_permission, .key_getsecurity = selinux_key_getsecurity, #endif #ifdef CONFIG_AUDIT .audit_rule_init = selinux_audit_rule_init, .audit_rule_known = selinux_audit_rule_known, .audit_rule_match = selinux_audit_rule_match, .audit_rule_free = selinux_audit_rule_free, #endif }; static __init int selinux_init(void) { if (!security_module_enable(&selinux_ops)) { selinux_enabled = 0; return 0; } if (!selinux_enabled) { printk(KERN_INFO "SELinux: Disabled at boot.\n"); return 0; } printk(KERN_INFO "SELinux: Initializing.\n"); /* Set the security state for the initial task. */ cred_init_security(); default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC); sel_inode_cache = kmem_cache_create("selinux_inode_security", sizeof(struct inode_security_struct), 0, SLAB_PANIC, NULL); avc_init(); if (register_security(&selinux_ops)) panic("SELinux: Unable to register with kernel.\n"); if (selinux_enforcing) printk(KERN_DEBUG "SELinux: Starting in enforcing mode\n"); else printk(KERN_DEBUG "SELinux: Starting in permissive mode\n"); return 0; } static void delayed_superblock_init(struct super_block *sb, void *unused) { superblock_doinit(sb, NULL); } void selinux_complete_init(void) { printk(KERN_DEBUG "SELinux: Completing initialization.\n"); /* Set up any superblocks initialized prior to the policy load. */ printk(KERN_DEBUG "SELinux: Setting up existing superblocks.\n"); iterate_supers(delayed_superblock_init, NULL); } /* SELinux requires early initialization in order to label all processes and objects when they are created. */ security_initcall(selinux_init); #if defined(CONFIG_NETFILTER) static struct nf_hook_ops selinux_ipv4_ops[] = { { .hook = selinux_ipv4_postroute, .owner = THIS_MODULE, .pf = PF_INET, .hooknum = NF_INET_POST_ROUTING, .priority = NF_IP_PRI_SELINUX_LAST, }, { .hook = selinux_ipv4_forward, .owner = THIS_MODULE, .pf = PF_INET, .hooknum = NF_INET_FORWARD, .priority = NF_IP_PRI_SELINUX_FIRST, }, { .hook = selinux_ipv4_output, .owner = THIS_MODULE, .pf = PF_INET, .hooknum = NF_INET_LOCAL_OUT, .priority = NF_IP_PRI_SELINUX_FIRST, } }; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static struct nf_hook_ops selinux_ipv6_ops[] = { { .hook = selinux_ipv6_postroute, .owner = THIS_MODULE, .pf = PF_INET6, .hooknum = NF_INET_POST_ROUTING, .priority = NF_IP6_PRI_SELINUX_LAST, }, { .hook = selinux_ipv6_forward, .owner = THIS_MODULE, .pf = PF_INET6, .hooknum = NF_INET_FORWARD, .priority = NF_IP6_PRI_SELINUX_FIRST, } }; #endif /* IPV6 */ static int __init selinux_nf_ip_init(void) { int err = 0; if (!selinux_enabled) goto out; printk(KERN_DEBUG "SELinux: Registering netfilter hooks\n"); err = nf_register_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops)); if (err) panic("SELinux: nf_register_hooks for IPv4: error %d\n", err); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) err = nf_register_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops)); if (err) panic("SELinux: nf_register_hooks for IPv6: error %d\n", err); #endif /* IPV6 */ out: return err; } __initcall(selinux_nf_ip_init); #ifdef CONFIG_SECURITY_SELINUX_DISABLE static void selinux_nf_ip_exit(void) { printk(KERN_DEBUG "SELinux: Unregistering netfilter hooks\n"); nf_unregister_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops)); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) nf_unregister_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops)); #endif /* IPV6 */ } #endif #else /* CONFIG_NETFILTER */ #ifdef CONFIG_SECURITY_SELINUX_DISABLE #define selinux_nf_ip_exit() #endif #endif /* CONFIG_NETFILTER */ #ifdef CONFIG_SECURITY_SELINUX_DISABLE static int selinux_disabled; int selinux_disable(void) { extern void exit_sel_fs(void); if (ss_initialized) { /* Not permitted after initial policy load. */ return -EINVAL; } if (selinux_disabled) { /* Only do this once. */ return -EINVAL; } printk(KERN_INFO "SELinux: Disabled at runtime.\n"); selinux_disabled = 1; selinux_enabled = 0; reset_security_ops(); /* Try to destroy the avc node cache */ avc_disable(); /* Unregister netfilter hooks. */ selinux_nf_ip_exit(); /* Unregister selinuxfs. */ exit_sel_fs(); return 0; } #endif
/* binder.c * * Android IPC Subsystem * * Copyright (C) 2007-2008 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <asm/cacheflush.h> #include <linux/fdtable.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/list.h> #include <linux/miscdevice.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/nsproxy.h> #include <linux/poll.h> #include <linux/debugfs.h> #include <linux/rbtree.h> #include <linux/sched.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/vmalloc.h> #include "binder.h" static DEFINE_MUTEX(binder_lock); static DEFINE_MUTEX(binder_deferred_lock); static HLIST_HEAD(binder_procs); static HLIST_HEAD(binder_deferred_list); static HLIST_HEAD(binder_dead_nodes); static struct dentry *binder_debugfs_dir_entry_root; static struct dentry *binder_debugfs_dir_entry_proc; static struct binder_node *binder_context_mgr_node; static uid_t binder_context_mgr_uid = -1; static int binder_last_id; static struct workqueue_struct *binder_deferred_workqueue; #define BINDER_DEBUG_ENTRY(name) \ static int binder_##name##_open(struct inode *inode, struct file *file) \ { \ return single_open(file, binder_##name##_show, inode->i_private); \ } \ \ static const struct file_operations binder_##name##_fops = { \ .owner = THIS_MODULE, \ .open = binder_##name##_open, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ } static int binder_proc_show(struct seq_file *m, void *unused); BINDER_DEBUG_ENTRY(proc); /* This is only defined in include/asm-arm/sizes.h */ #ifndef SZ_1K #define SZ_1K 0x400 #endif #ifndef SZ_4M #define SZ_4M 0x400000 #endif #define FORBIDDEN_MMAP_FLAGS (VM_WRITE) #define BINDER_SMALL_BUF_SIZE (PAGE_SIZE * 64) enum { BINDER_DEBUG_USER_ERROR = 1U << 0, BINDER_DEBUG_FAILED_TRANSACTION = 1U << 1, BINDER_DEBUG_DEAD_TRANSACTION = 1U << 2, BINDER_DEBUG_OPEN_CLOSE = 1U << 3, BINDER_DEBUG_DEAD_BINDER = 1U << 4, BINDER_DEBUG_DEATH_NOTIFICATION = 1U << 5, BINDER_DEBUG_READ_WRITE = 1U << 6, BINDER_DEBUG_USER_REFS = 1U << 7, BINDER_DEBUG_THREADS = 1U << 8, BINDER_DEBUG_TRANSACTION = 1U << 9, BINDER_DEBUG_TRANSACTION_COMPLETE = 1U << 10, BINDER_DEBUG_FREE_BUFFER = 1U << 11, BINDER_DEBUG_INTERNAL_REFS = 1U << 12, BINDER_DEBUG_BUFFER_ALLOC = 1U << 13, BINDER_DEBUG_PRIORITY_CAP = 1U << 14, BINDER_DEBUG_BUFFER_ALLOC_ASYNC = 1U << 15, }; static uint32_t binder_debug_mask = BINDER_DEBUG_USER_ERROR | BINDER_DEBUG_FAILED_TRANSACTION | BINDER_DEBUG_DEAD_TRANSACTION; module_param_named(debug_mask, binder_debug_mask, uint, S_IWUSR | S_IRUGO); static int binder_debug_no_lock; module_param_named(proc_no_lock, binder_debug_no_lock, bool, S_IWUSR | S_IRUGO); static DECLARE_WAIT_QUEUE_HEAD(binder_user_error_wait); static int binder_stop_on_user_error; static int binder_set_stop_on_user_error(const char *val, struct kernel_param *kp) { int ret; ret = param_set_int(val, kp); if (binder_stop_on_user_error < 2) wake_up(&binder_user_error_wait); return ret; } module_param_call(stop_on_user_error, binder_set_stop_on_user_error, param_get_int, &binder_stop_on_user_error, S_IWUSR | S_IRUGO); #define binder_debug(mask, x...) \ do { \ if (binder_debug_mask & mask) \ printk(KERN_INFO x); \ } while (0) #define binder_user_error(x...) \ do { \ if (binder_debug_mask & BINDER_DEBUG_USER_ERROR) \ printk(KERN_INFO x); \ if (binder_stop_on_user_error) \ binder_stop_on_user_error = 2; \ } while (0) enum binder_stat_types { BINDER_STAT_PROC, BINDER_STAT_THREAD, BINDER_STAT_NODE, BINDER_STAT_REF, BINDER_STAT_DEATH, BINDER_STAT_TRANSACTION, BINDER_STAT_TRANSACTION_COMPLETE, BINDER_STAT_COUNT }; struct binder_stats { int br[_IOC_NR(BR_FAILED_REPLY) + 1]; int bc[_IOC_NR(BC_DEAD_BINDER_DONE) + 1]; int obj_created[BINDER_STAT_COUNT]; int obj_deleted[BINDER_STAT_COUNT]; }; static struct binder_stats binder_stats; static inline void binder_stats_deleted(enum binder_stat_types type) { binder_stats.obj_deleted[type]++; } static inline void binder_stats_created(enum binder_stat_types type) { binder_stats.obj_created[type]++; } struct binder_transaction_log_entry { int debug_id; int call_type; int from_proc; int from_thread; int target_handle; int to_proc; int to_thread; int to_node; int data_size; int offsets_size; }; struct binder_transaction_log { int next; int full; struct binder_transaction_log_entry entry[32]; }; static struct binder_transaction_log binder_transaction_log; static struct binder_transaction_log binder_transaction_log_failed; static struct binder_transaction_log_entry *binder_transaction_log_add( struct binder_transaction_log *log) { struct binder_transaction_log_entry *e; e = &log->entry[log->next]; memset(e, 0, sizeof(*e)); log->next++; if (log->next == ARRAY_SIZE(log->entry)) { log->next = 0; log->full = 1; } return e; } struct binder_work { struct list_head entry; enum { BINDER_WORK_TRANSACTION = 1, BINDER_WORK_TRANSACTION_COMPLETE, BINDER_WORK_NODE, BINDER_WORK_DEAD_BINDER, BINDER_WORK_DEAD_BINDER_AND_CLEAR, BINDER_WORK_CLEAR_DEATH_NOTIFICATION, } type; }; struct binder_node { int debug_id; struct binder_work work; union { struct rb_node rb_node; struct hlist_node dead_node; }; struct binder_proc *proc; struct hlist_head refs; int internal_strong_refs; int local_weak_refs; int local_strong_refs; void __user *ptr; void __user *cookie; unsigned has_strong_ref:1; unsigned pending_strong_ref:1; unsigned has_weak_ref:1; unsigned pending_weak_ref:1; unsigned has_async_transaction:1; unsigned accept_fds:1; unsigned min_priority:8; struct list_head async_todo; }; struct binder_ref_death { struct binder_work work; void __user *cookie; }; struct binder_ref { /* Lookups needed: */ /* node + proc => ref (transaction) */ /* desc + proc => ref (transaction, inc/dec ref) */ /* node => refs + procs (proc exit) */ int debug_id; struct rb_node rb_node_desc; struct rb_node rb_node_node; struct hlist_node node_entry; struct binder_proc *proc; struct binder_node *node; uint32_t desc; int strong; int weak; struct binder_ref_death *death; }; struct binder_buffer { struct list_head entry; /* free and allocated entries by addesss */ struct rb_node rb_node; /* free entry by size or allocated entry */ /* by address */ unsigned free:1; unsigned allow_user_free:1; unsigned async_transaction:1; unsigned debug_id:29; struct binder_transaction *transaction; struct binder_node *target_node; size_t data_size; size_t offsets_size; uint8_t data[0]; }; enum binder_deferred_state { BINDER_DEFERRED_PUT_FILES = 0x01, BINDER_DEFERRED_FLUSH = 0x02, BINDER_DEFERRED_RELEASE = 0x04, }; struct binder_proc { struct hlist_node proc_node; struct rb_root threads; struct rb_root nodes; struct rb_root refs_by_desc; struct rb_root refs_by_node; int pid; struct vm_area_struct *vma; struct task_struct *tsk; struct files_struct *files; struct hlist_node deferred_work_node; int deferred_work; void *buffer; ptrdiff_t user_buffer_offset; struct list_head buffers; struct rb_root free_buffers; struct rb_root allocated_buffers; size_t free_async_space; struct page **pages; size_t buffer_size; uint32_t buffer_free; struct list_head todo; wait_queue_head_t wait; struct binder_stats stats; struct list_head delivered_death; int max_threads; int requested_threads; int requested_threads_started; int ready_threads; long default_priority; struct dentry *debugfs_entry; }; enum { BINDER_LOOPER_STATE_REGISTERED = 0x01, BINDER_LOOPER_STATE_ENTERED = 0x02, BINDER_LOOPER_STATE_EXITED = 0x04, BINDER_LOOPER_STATE_INVALID = 0x08, BINDER_LOOPER_STATE_WAITING = 0x10, BINDER_LOOPER_STATE_NEED_RETURN = 0x20 }; struct binder_thread { struct binder_proc *proc; struct rb_node rb_node; int pid; int looper; struct binder_transaction *transaction_stack; struct list_head todo; uint32_t return_error; /* Write failed, return error code in read buf */ uint32_t return_error2; /* Write failed, return error code in read */ /* buffer. Used when sending a reply to a dead process that */ /* we are also waiting on */ wait_queue_head_t wait; struct binder_stats stats; }; struct binder_transaction { int debug_id; struct binder_work work; struct binder_thread *from; struct binder_transaction *from_parent; struct binder_proc *to_proc; struct binder_thread *to_thread; struct binder_transaction *to_parent; unsigned need_reply:1; /* unsigned is_dead:1; */ /* not used at the moment */ struct binder_buffer *buffer; unsigned int code; unsigned int flags; long priority; long saved_priority; uid_t sender_euid; }; static void binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer); /* * copied from get_unused_fd_flags */ int task_get_unused_fd_flags(struct binder_proc *proc, int flags) { struct files_struct *files = proc->files; int fd, error; struct fdtable *fdt; unsigned long rlim_cur; unsigned long irqs; if (files == NULL) return -ESRCH; error = -EMFILE; spin_lock(&files->file_lock); repeat: fdt = files_fdtable(files); fd = find_next_zero_bit(fdt->open_fds->fds_bits, fdt->max_fds, files->next_fd); /* * N.B. For clone tasks sharing a files structure, this test * will limit the total number of files that can be opened. */ rlim_cur = 0; if (lock_task_sighand(proc->tsk, &irqs)) { rlim_cur = proc->tsk->signal->rlim[RLIMIT_NOFILE].rlim_cur; unlock_task_sighand(proc->tsk, &irqs); } if (fd >= rlim_cur) goto out; /* Do we need to expand the fd array or fd set? */ error = expand_files(files, fd); if (error < 0) goto out; if (error) { /* * If we needed to expand the fs array we * might have blocked - try again. */ error = -EMFILE; goto repeat; } FD_SET(fd, fdt->open_fds); if (flags & O_CLOEXEC) FD_SET(fd, fdt->close_on_exec); else FD_CLR(fd, fdt->close_on_exec); files->next_fd = fd + 1; #if 1 /* Sanity check */ if (fdt->fd[fd] != NULL) { printk(KERN_WARNING "get_unused_fd: slot %d not NULL!\n", fd); fdt->fd[fd] = NULL; } #endif error = fd; out: spin_unlock(&files->file_lock); return error; } /* * copied from fd_install */ static void task_fd_install( struct binder_proc *proc, unsigned int fd, struct file *file) { struct files_struct *files = proc->files; struct fdtable *fdt; if (files == NULL) return; spin_lock(&files->file_lock); fdt = files_fdtable(files); BUG_ON(fdt->fd[fd] != NULL); rcu_assign_pointer(fdt->fd[fd], file); spin_unlock(&files->file_lock); } /* * copied from __put_unused_fd in open.c */ static void __put_unused_fd(struct files_struct *files, unsigned int fd) { struct fdtable *fdt = files_fdtable(files); __FD_CLR(fd, fdt->open_fds); if (fd < files->next_fd) files->next_fd = fd; } /* * copied from sys_close */ static long task_close_fd(struct binder_proc *proc, unsigned int fd) { struct file *filp; struct files_struct *files = proc->files; struct fdtable *fdt; int retval; if (files == NULL) return -ESRCH; spin_lock(&files->file_lock); fdt = files_fdtable(files); if (fd >= fdt->max_fds) goto out_unlock; filp = fdt->fd[fd]; if (!filp) goto out_unlock; rcu_assign_pointer(fdt->fd[fd], NULL); FD_CLR(fd, fdt->close_on_exec); __put_unused_fd(files, fd); spin_unlock(&files->file_lock); retval = filp_close(filp, files); /* can't restart close syscall because file table entry was cleared */ if (unlikely(retval == -ERESTARTSYS || retval == -ERESTARTNOINTR || retval == -ERESTARTNOHAND || retval == -ERESTART_RESTARTBLOCK)) retval = -EINTR; return retval; out_unlock: spin_unlock(&files->file_lock); return -EBADF; } static void binder_set_nice(long nice) { long min_nice; if (can_nice(current, nice)) { set_user_nice(current, nice); return; } min_nice = 20 - current->signal->rlim[RLIMIT_NICE].rlim_cur; binder_debug(BINDER_DEBUG_PRIORITY_CAP, "binder: %d: nice value %ld not allowed use " "%ld instead\n", current->pid, nice, min_nice); set_user_nice(current, min_nice); if (min_nice < 20) return; binder_user_error("binder: %d RLIMIT_NICE not set\n", current->pid); } static size_t binder_buffer_size(struct binder_proc *proc, struct binder_buffer *buffer) { if (list_is_last(&buffer->entry, &proc->buffers)) return proc->buffer + proc->buffer_size - (void *)buffer->data; else return (size_t)list_entry(buffer->entry.next, struct binder_buffer, entry) - (size_t)buffer->data; } static void binder_insert_free_buffer(struct binder_proc *proc, struct binder_buffer *new_buffer) { struct rb_node **p = &proc->free_buffers.rb_node; struct rb_node *parent = NULL; struct binder_buffer *buffer; size_t buffer_size; size_t new_buffer_size; BUG_ON(!new_buffer->free); new_buffer_size = binder_buffer_size(proc, new_buffer); binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: add free buffer, size %zd, " "at %p\n", proc->pid, new_buffer_size, new_buffer); while (*p) { parent = *p; buffer = rb_entry(parent, struct binder_buffer, rb_node); BUG_ON(!buffer->free); buffer_size = binder_buffer_size(proc, buffer); if (new_buffer_size < buffer_size) p = &parent->rb_left; else p = &parent->rb_right; } rb_link_node(&new_buffer->rb_node, parent, p); rb_insert_color(&new_buffer->rb_node, &proc->free_buffers); } static void binder_insert_allocated_buffer(struct binder_proc *proc, struct binder_buffer *new_buffer) { struct rb_node **p = &proc->allocated_buffers.rb_node; struct rb_node *parent = NULL; struct binder_buffer *buffer; BUG_ON(new_buffer->free); while (*p) { parent = *p; buffer = rb_entry(parent, struct binder_buffer, rb_node); BUG_ON(buffer->free); if (new_buffer < buffer) p = &parent->rb_left; else if (new_buffer > buffer) p = &parent->rb_right; else BUG(); } rb_link_node(&new_buffer->rb_node, parent, p); rb_insert_color(&new_buffer->rb_node, &proc->allocated_buffers); } static struct binder_buffer *binder_buffer_lookup(struct binder_proc *proc, void __user *user_ptr) { struct rb_node *n = proc->allocated_buffers.rb_node; struct binder_buffer *buffer; struct binder_buffer *kern_ptr; kern_ptr = user_ptr - proc->user_buffer_offset - offsetof(struct binder_buffer, data); while (n) { buffer = rb_entry(n, struct binder_buffer, rb_node); BUG_ON(buffer->free); if (kern_ptr < buffer) n = n->rb_left; else if (kern_ptr > buffer) n = n->rb_right; else return buffer; } return NULL; } static int binder_update_page_range(struct binder_proc *proc, int allocate, void *start, void *end, struct vm_area_struct *vma) { void *page_addr; unsigned long user_page_addr; struct vm_struct tmp_area; struct page **page; struct mm_struct *mm; binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: %s pages %p-%p\n", proc->pid, allocate ? "allocate" : "free", start, end); if (end <= start) return 0; if (vma) mm = NULL; else mm = get_task_mm(proc->tsk); if (mm) { down_write(&mm->mmap_sem); vma = proc->vma; } if (allocate == 0) goto free_range; if (vma == NULL) { printk(KERN_ERR "binder: %d: binder_alloc_buf failed to " "map pages in userspace, no vma\n", proc->pid); goto err_no_vma; } for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) { int ret; struct page **page_array_ptr; page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE]; BUG_ON(*page); *page = alloc_page(GFP_KERNEL | __GFP_ZERO); if (*page == NULL) { printk(KERN_ERR "binder: %d: binder_alloc_buf failed " "for page at %p\n", proc->pid, page_addr); goto err_alloc_page_failed; } tmp_area.addr = page_addr; tmp_area.size = PAGE_SIZE + PAGE_SIZE /* guard page? */; page_array_ptr = page; ret = map_vm_area(&tmp_area, PAGE_KERNEL, &page_array_ptr); if (ret) { printk(KERN_ERR "binder: %d: binder_alloc_buf failed " "to map page at %p in kernel\n", proc->pid, page_addr); goto err_map_kernel_failed; } user_page_addr = (uintptr_t)page_addr + proc->user_buffer_offset; ret = vm_insert_page(vma, user_page_addr, page[0]); if (ret) { printk(KERN_ERR "binder: %d: binder_alloc_buf failed " "to map page at %lx in userspace\n", proc->pid, user_page_addr); goto err_vm_insert_page_failed; } /* vm_insert_page does not seem to increment the refcount */ } if (mm) { up_write(&mm->mmap_sem); mmput(mm); } return 0; free_range: for (page_addr = end - PAGE_SIZE; page_addr >= start; page_addr -= PAGE_SIZE) { page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE]; if (vma) zap_page_range(vma, (uintptr_t)page_addr + proc->user_buffer_offset, PAGE_SIZE, NULL); err_vm_insert_page_failed: unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE); err_map_kernel_failed: __free_page(*page); *page = NULL; err_alloc_page_failed: ; } err_no_vma: if (mm) { up_write(&mm->mmap_sem); mmput(mm); } return -ENOMEM; } static struct binder_buffer *binder_alloc_buf(struct binder_proc *proc, size_t data_size, size_t offsets_size, int is_async) { struct rb_node *n = proc->free_buffers.rb_node; struct binder_buffer *buffer; size_t buffer_size; struct rb_node *best_fit = NULL; void *has_page_addr; void *end_page_addr; size_t size; if (proc->vma == NULL) { printk(KERN_ERR "binder: %d: binder_alloc_buf, no vma\n", proc->pid); return NULL; } size = ALIGN(data_size, sizeof(void *)) + ALIGN(offsets_size, sizeof(void *)); if (size < data_size || size < offsets_size) { binder_user_error("binder: %d: got transaction with invalid " "size %zd-%zd\n", proc->pid, data_size, offsets_size); return NULL; } if (is_async && proc->free_async_space < size + sizeof(struct binder_buffer)) { binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: binder_alloc_buf size %zd" "failed, no async space left\n", proc->pid, size); return NULL; } while (n) { buffer = rb_entry(n, struct binder_buffer, rb_node); BUG_ON(!buffer->free); buffer_size = binder_buffer_size(proc, buffer); if (size < buffer_size) { best_fit = n; n = n->rb_left; } else if (size > buffer_size) n = n->rb_right; else { best_fit = n; break; } } if (best_fit == NULL) { printk(KERN_ERR "binder: %d: binder_alloc_buf size %zd failed, " "no address space. buffer_size=%d\n", proc->pid, size, buffer_size); return NULL; } if (n == NULL) { buffer = rb_entry(best_fit, struct binder_buffer, rb_node); buffer_size = binder_buffer_size(proc, buffer); } binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: binder_alloc_buf size %zd got buff" "er %p size %zd\n", proc->pid, size, buffer, buffer_size); has_page_addr = (void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK); if (n == NULL) { if (size + sizeof(struct binder_buffer) + 4 >= buffer_size) buffer_size = size; /* no room for other buffers */ else buffer_size = size + sizeof(struct binder_buffer); } end_page_addr = (void *)PAGE_ALIGN((uintptr_t)buffer->data + buffer_size); if (end_page_addr > has_page_addr) end_page_addr = has_page_addr; if (binder_update_page_range(proc, 1, (void *)PAGE_ALIGN((uintptr_t)buffer->data), end_page_addr, NULL)) return NULL; rb_erase(best_fit, &proc->free_buffers); buffer->free = 0; binder_insert_allocated_buffer(proc, buffer); if (buffer_size != size) { struct binder_buffer *new_buffer = (void *)buffer->data + size; list_add(&new_buffer->entry, &buffer->entry); new_buffer->free = 1; binder_insert_free_buffer(proc, new_buffer); } binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: binder_alloc_buf size %zd got " "%p\n", proc->pid, size, buffer); buffer->data_size = data_size; buffer->offsets_size = offsets_size; buffer->async_transaction = is_async; if (is_async) { proc->free_async_space -= size + sizeof(struct binder_buffer); binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC, "binder: %d: binder_alloc_buf size %zd " "async free %zd\n", proc->pid, size, proc->free_async_space); } return buffer; } static void *buffer_start_page(struct binder_buffer *buffer) { return (void *)((uintptr_t)buffer & PAGE_MASK); } static void *buffer_end_page(struct binder_buffer *buffer) { return (void *)(((uintptr_t)(buffer + 1) - 1) & PAGE_MASK); } static void binder_delete_free_buffer(struct binder_proc *proc, struct binder_buffer *buffer) { struct binder_buffer *prev, *next = NULL; int free_page_end = 1; int free_page_start = 1; BUG_ON(proc->buffers.next == &buffer->entry); prev = list_entry(buffer->entry.prev, struct binder_buffer, entry); BUG_ON(!prev->free); if (buffer_end_page(prev) == buffer_start_page(buffer)) { free_page_start = 0; if (buffer_end_page(prev) == buffer_end_page(buffer)) free_page_end = 0; binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: merge free, buffer %p " "share page with prev %p\n", proc->pid, buffer, prev); } if (!list_is_last(&buffer->entry, &proc->buffers)) { next = list_entry(buffer->entry.next, struct binder_buffer, entry); if (buffer_start_page(next) == buffer_end_page(buffer)) { free_page_end = 0; if (buffer_start_page(next) == buffer_start_page(buffer)) free_page_start = 0; binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: merge free, buffer" " %p share page with next %p\n", proc->pid, buffer, next); } } list_del(&buffer->entry); if (free_page_start || free_page_end) { binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: merge free, buffer %p do " "not share page%s%s with with %p or %p\n", proc->pid, buffer, free_page_start ? "" : " end", free_page_end ? "" : " start", prev, next); binder_update_page_range(proc, 0, free_page_start ? buffer_start_page(buffer) : buffer_end_page(buffer), (free_page_end ? buffer_end_page(buffer) : buffer_start_page(buffer)) + PAGE_SIZE, NULL); } } static void binder_free_buf(struct binder_proc *proc, struct binder_buffer *buffer) { size_t size, buffer_size; buffer_size = binder_buffer_size(proc, buffer); size = ALIGN(buffer->data_size, sizeof(void *)) + ALIGN(buffer->offsets_size, sizeof(void *)); binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder: %d: binder_free_buf %p size %zd buffer" "_size %zd\n", proc->pid, buffer, size, buffer_size); BUG_ON(buffer->free); BUG_ON(size > buffer_size); BUG_ON(buffer->transaction != NULL); BUG_ON((void *)buffer < proc->buffer); BUG_ON((void *)buffer > proc->buffer + proc->buffer_size); if (buffer->async_transaction) { proc->free_async_space += size + sizeof(struct binder_buffer); binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC, "binder: %d: binder_free_buf size %zd " "async free %zd\n", proc->pid, size, proc->free_async_space); } binder_update_page_range(proc, 0, (void *)PAGE_ALIGN((uintptr_t)buffer->data), (void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK), NULL); rb_erase(&buffer->rb_node, &proc->allocated_buffers); buffer->free = 1; if (!list_is_last(&buffer->entry, &proc->buffers)) { struct binder_buffer *next = list_entry(buffer->entry.next, struct binder_buffer, entry); if (next->free) { rb_erase(&next->rb_node, &proc->free_buffers); binder_delete_free_buffer(proc, next); } } if (proc->buffers.next != &buffer->entry) { struct binder_buffer *prev = list_entry(buffer->entry.prev, struct binder_buffer, entry); if (prev->free) { binder_delete_free_buffer(proc, buffer); rb_erase(&prev->rb_node, &proc->free_buffers); buffer = prev; } } binder_insert_free_buffer(proc, buffer); } static struct binder_node *binder_get_node(struct binder_proc *proc, void __user *ptr) { struct rb_node *n = proc->nodes.rb_node; struct binder_node *node; while (n) { node = rb_entry(n, struct binder_node, rb_node); if (ptr < node->ptr) n = n->rb_left; else if (ptr > node->ptr) n = n->rb_right; else return node; } return NULL; } static struct binder_node *binder_new_node(struct binder_proc *proc, void __user *ptr, void __user *cookie) { struct rb_node **p = &proc->nodes.rb_node; struct rb_node *parent = NULL; struct binder_node *node; while (*p) { parent = *p; node = rb_entry(parent, struct binder_node, rb_node); if (ptr < node->ptr) p = &(*p)->rb_left; else if (ptr > node->ptr) p = &(*p)->rb_right; else return NULL; } node = kzalloc(sizeof(*node), GFP_KERNEL); if (node == NULL) return NULL; binder_stats_created(BINDER_STAT_NODE); rb_link_node(&node->rb_node, parent, p); rb_insert_color(&node->rb_node, &proc->nodes); node->debug_id = ++binder_last_id; node->proc = proc; node->ptr = ptr; node->cookie = cookie; node->work.type = BINDER_WORK_NODE; INIT_LIST_HEAD(&node->work.entry); INIT_LIST_HEAD(&node->async_todo); binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: %d:%d node %d u%p c%p created\n", proc->pid, current->pid, node->debug_id, node->ptr, node->cookie); return node; } static int binder_inc_node(struct binder_node *node, int strong, int internal, struct list_head *target_list) { if (strong) { if (internal) { if (target_list == NULL && node->internal_strong_refs == 0 && !(node == binder_context_mgr_node && node->has_strong_ref)) { printk(KERN_ERR "binder: invalid inc strong " "node for %d\n", node->debug_id); return -EINVAL; } node->internal_strong_refs++; } else node->local_strong_refs++; if (!node->has_strong_ref && target_list) { list_del_init(&node->work.entry); list_add_tail(&node->work.entry, target_list); } } else { if (!internal) node->local_weak_refs++; if (!node->has_weak_ref && list_empty(&node->work.entry)) { if (target_list == NULL) { printk(KERN_ERR "binder: invalid inc weak node " "for %d\n", node->debug_id); return -EINVAL; } list_add_tail(&node->work.entry, target_list); } } return 0; } static int binder_dec_node(struct binder_node *node, int strong, int internal) { if (strong) { if (internal) node->internal_strong_refs--; else node->local_strong_refs--; if (node->local_strong_refs || node->internal_strong_refs) return 0; } else { if (!internal) node->local_weak_refs--; if (node->local_weak_refs || !hlist_empty(&node->refs)) return 0; } if (node->proc && (node->has_strong_ref || node->has_weak_ref)) { if (list_empty(&node->work.entry)) { list_add_tail(&node->work.entry, &node->proc->todo); wake_up_interruptible(&node->proc->wait); } } else { if (hlist_empty(&node->refs) && !node->local_strong_refs && !node->local_weak_refs) { list_del_init(&node->work.entry); if (node->proc) { rb_erase(&node->rb_node, &node->proc->nodes); binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: refless node %d deleted\n", node->debug_id); } else { hlist_del(&node->dead_node); binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: dead node %d deleted\n", node->debug_id); } kfree(node); binder_stats_deleted(BINDER_STAT_NODE); } } return 0; } static struct binder_ref *binder_get_ref(struct binder_proc *proc, uint32_t desc) { struct rb_node *n = proc->refs_by_desc.rb_node; struct binder_ref *ref; while (n) { ref = rb_entry(n, struct binder_ref, rb_node_desc); if (desc < ref->desc) n = n->rb_left; else if (desc > ref->desc) n = n->rb_right; else return ref; } return NULL; } static struct binder_ref *binder_get_ref_for_node(struct binder_proc *proc, struct binder_node *node) { struct rb_node *n; struct rb_node **p = &proc->refs_by_node.rb_node; struct rb_node *parent = NULL; struct binder_ref *ref, *new_ref; while (*p) { parent = *p; ref = rb_entry(parent, struct binder_ref, rb_node_node); if (node < ref->node) p = &(*p)->rb_left; else if (node > ref->node) p = &(*p)->rb_right; else return ref; } new_ref = kzalloc(sizeof(*ref), GFP_KERNEL); if (new_ref == NULL) return NULL; binder_stats_created(BINDER_STAT_REF); new_ref->debug_id = ++binder_last_id; new_ref->proc = proc; new_ref->node = node; rb_link_node(&new_ref->rb_node_node, parent, p); rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node); new_ref->desc = (node == binder_context_mgr_node) ? 0 : 1; for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) { ref = rb_entry(n, struct binder_ref, rb_node_desc); if (ref->desc > new_ref->desc) break; new_ref->desc = ref->desc + 1; } p = &proc->refs_by_desc.rb_node; while (*p) { parent = *p; ref = rb_entry(parent, struct binder_ref, rb_node_desc); if (new_ref->desc < ref->desc) p = &(*p)->rb_left; else if (new_ref->desc > ref->desc) p = &(*p)->rb_right; else BUG(); } rb_link_node(&new_ref->rb_node_desc, parent, p); rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc); if (node) { hlist_add_head(&new_ref->node_entry, &node->refs); binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: %d new ref %d desc %d for " "node %d\n", proc->pid, new_ref->debug_id, new_ref->desc, node->debug_id); } else { binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: %d new ref %d desc %d for " "dead node\n", proc->pid, new_ref->debug_id, new_ref->desc); } return new_ref; } static void binder_delete_ref(struct binder_ref *ref) { binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: %d delete ref %d desc %d for " "node %d\n", ref->proc->pid, ref->debug_id, ref->desc, ref->node->debug_id); rb_erase(&ref->rb_node_desc, &ref->proc->refs_by_desc); rb_erase(&ref->rb_node_node, &ref->proc->refs_by_node); if (ref->strong) binder_dec_node(ref->node, 1, 1); hlist_del(&ref->node_entry); binder_dec_node(ref->node, 0, 1); if (ref->death) { binder_debug(BINDER_DEBUG_DEAD_BINDER, "binder: %d delete ref %d desc %d " "has death notification\n", ref->proc->pid, ref->debug_id, ref->desc); list_del(&ref->death->work.entry); kfree(ref->death); binder_stats_deleted(BINDER_STAT_DEATH); } kfree(ref); binder_stats_deleted(BINDER_STAT_REF); } static int binder_inc_ref(struct binder_ref *ref, int strong, struct list_head *target_list) { int ret; if (strong) { if (ref->strong == 0) { ret = binder_inc_node(ref->node, 1, 1, target_list); if (ret) return ret; } ref->strong++; } else { if (ref->weak == 0) { ret = binder_inc_node(ref->node, 0, 1, target_list); if (ret) return ret; } ref->weak++; } return 0; } static int binder_dec_ref(struct binder_ref *ref, int strong) { if (strong) { if (ref->strong == 0) { binder_user_error("binder: %d invalid dec strong, " "ref %d desc %d s %d w %d\n", ref->proc->pid, ref->debug_id, ref->desc, ref->strong, ref->weak); return -EINVAL; } ref->strong--; if (ref->strong == 0) { int ret; ret = binder_dec_node(ref->node, strong, 1); if (ret) return ret; } } else { if (ref->weak == 0) { binder_user_error("binder: %d invalid dec weak, " "ref %d desc %d s %d w %d\n", ref->proc->pid, ref->debug_id, ref->desc, ref->strong, ref->weak); return -EINVAL; } ref->weak--; } if (ref->strong == 0 && ref->weak == 0) binder_delete_ref(ref); return 0; } static void binder_pop_transaction(struct binder_thread *target_thread, struct binder_transaction *t) { if (target_thread) { BUG_ON(target_thread->transaction_stack != t); BUG_ON(target_thread->transaction_stack->from != target_thread); target_thread->transaction_stack = target_thread->transaction_stack->from_parent; t->from = NULL; } t->need_reply = 0; if (t->buffer) t->buffer->transaction = NULL; kfree(t); binder_stats_deleted(BINDER_STAT_TRANSACTION); } static void binder_send_failed_reply(struct binder_transaction *t, uint32_t error_code) { struct binder_thread *target_thread; BUG_ON(t->flags & TF_ONE_WAY); while (1) { target_thread = t->from; if (target_thread) { if (target_thread->return_error != BR_OK && target_thread->return_error2 == BR_OK) { target_thread->return_error2 = target_thread->return_error; target_thread->return_error = BR_OK; } if (target_thread->return_error == BR_OK) { binder_debug(BINDER_DEBUG_FAILED_TRANSACTION, "binder: send failed reply for " "transaction %d to %d:%d\n", t->debug_id, target_thread->proc->pid, target_thread->pid); binder_pop_transaction(target_thread, t); target_thread->return_error = error_code; wake_up_interruptible(&target_thread->wait); } else { printk(KERN_ERR "binder: reply failed, target " "thread, %d:%d, has error code %d " "already\n", target_thread->proc->pid, target_thread->pid, target_thread->return_error); } return; } else { struct binder_transaction *next = t->from_parent; binder_debug(BINDER_DEBUG_FAILED_TRANSACTION, "binder: send failed reply " "for transaction %d, target dead\n", t->debug_id); binder_pop_transaction(target_thread, t); if (next == NULL) { binder_debug(BINDER_DEBUG_DEAD_BINDER, "binder: reply failed," " no target thread at root\n"); return; } t = next; binder_debug(BINDER_DEBUG_DEAD_BINDER, "binder: reply failed, no target " "thread -- retry %d\n", t->debug_id); } } } static void binder_transaction_buffer_release(struct binder_proc *proc, struct binder_buffer *buffer, size_t *failed_at) { size_t *offp, *off_end; int debug_id = buffer->debug_id; binder_debug(BINDER_DEBUG_TRANSACTION, "binder: %d buffer release %d, size %zd-%zd, failed at %p\n", proc->pid, buffer->debug_id, buffer->data_size, buffer->offsets_size, failed_at); if (buffer->target_node) binder_dec_node(buffer->target_node, 1, 0); offp = (size_t *)(buffer->data + ALIGN(buffer->data_size, sizeof(void *))); if (failed_at) off_end = failed_at; else off_end = (void *)offp + buffer->offsets_size; for (; offp < off_end; offp++) { struct flat_binder_object *fp; if (*offp > buffer->data_size - sizeof(*fp) || buffer->data_size < sizeof(*fp) || !IS_ALIGNED(*offp, sizeof(void *))) { printk(KERN_ERR "binder: transaction release %d bad" "offset %zd, size %zd\n", debug_id, *offp, buffer->data_size); continue; } fp = (struct flat_binder_object *)(buffer->data + *offp); switch (fp->type) { case BINDER_TYPE_BINDER: case BINDER_TYPE_WEAK_BINDER: { struct binder_node *node = binder_get_node(proc, fp->binder); if (node == NULL) { printk(KERN_ERR "binder: transaction release %d" " bad node %p\n", debug_id, fp->binder); break; } binder_debug(BINDER_DEBUG_TRANSACTION, " node %d u%p\n", node->debug_id, node->ptr); binder_dec_node(node, fp->type == BINDER_TYPE_BINDER, 0); } break; case BINDER_TYPE_HANDLE: case BINDER_TYPE_WEAK_HANDLE: { struct binder_ref *ref = binder_get_ref(proc, fp->handle); if (ref == NULL) { printk(KERN_ERR "binder: transaction release %d" " bad handle %ld\n", debug_id, fp->handle); break; } binder_debug(BINDER_DEBUG_TRANSACTION, " ref %d desc %d (node %d)\n", ref->debug_id, ref->desc, ref->node->debug_id); binder_dec_ref(ref, fp->type == BINDER_TYPE_HANDLE); } break; case BINDER_TYPE_FD: binder_debug(BINDER_DEBUG_TRANSACTION, " fd %ld\n", fp->handle); if (failed_at) task_close_fd(proc, fp->handle); break; default: printk(KERN_ERR "binder: transaction release %d bad " "object type %lx\n", debug_id, fp->type); break; } } } static void binder_transaction(struct binder_proc *proc, struct binder_thread *thread, struct binder_transaction_data *tr, int reply) { struct binder_transaction *t; struct binder_work *tcomplete; size_t *offp, *off_end; struct binder_proc *target_proc; struct binder_thread *target_thread = NULL; struct binder_node *target_node = NULL; struct list_head *target_list; wait_queue_head_t *target_wait; struct binder_transaction *in_reply_to = NULL; struct binder_transaction_log_entry *e; uint32_t return_error; e = binder_transaction_log_add(&binder_transaction_log); e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY); e->from_proc = proc->pid; e->from_thread = thread->pid; e->target_handle = tr->target.handle; e->data_size = tr->data_size; e->offsets_size = tr->offsets_size; if (reply) { in_reply_to = thread->transaction_stack; if (in_reply_to == NULL) { binder_user_error("binder: %d:%d got reply transaction " "with no transaction stack\n", proc->pid, thread->pid); return_error = BR_FAILED_REPLY; goto err_empty_call_stack; } binder_set_nice(in_reply_to->saved_priority); if (in_reply_to->to_thread != thread) { binder_user_error("binder: %d:%d got reply transaction " "with bad transaction stack," " transaction %d has target %d:%d\n", proc->pid, thread->pid, in_reply_to->debug_id, in_reply_to->to_proc ? in_reply_to->to_proc->pid : 0, in_reply_to->to_thread ? in_reply_to->to_thread->pid : 0); return_error = BR_FAILED_REPLY; in_reply_to = NULL; goto err_bad_call_stack; } thread->transaction_stack = in_reply_to->to_parent; target_thread = in_reply_to->from; if (target_thread == NULL) { return_error = BR_DEAD_REPLY; goto err_dead_binder; } if (target_thread->transaction_stack != in_reply_to) { binder_user_error("binder: %d:%d got reply transaction " "with bad target transaction stack %d, " "expected %d\n", proc->pid, thread->pid, target_thread->transaction_stack ? target_thread->transaction_stack->debug_id : 0, in_reply_to->debug_id); return_error = BR_FAILED_REPLY; in_reply_to = NULL; target_thread = NULL; goto err_dead_binder; } target_proc = target_thread->proc; } else { if (tr->target.handle) { struct binder_ref *ref; ref = binder_get_ref(proc, tr->target.handle); if (ref == NULL) { binder_user_error("binder: %d:%d got " "transaction to invalid handle\n", proc->pid, thread->pid); return_error = BR_FAILED_REPLY; goto err_invalid_target_handle; } target_node = ref->node; } else { target_node = binder_context_mgr_node; if (target_node == NULL) { return_error = BR_DEAD_REPLY; goto err_no_context_mgr_node; } } e->to_node = target_node->debug_id; target_proc = target_node->proc; if (target_proc == NULL) { return_error = BR_DEAD_REPLY; goto err_dead_binder; } if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) { struct binder_transaction *tmp; tmp = thread->transaction_stack; if (tmp->to_thread != thread) { binder_user_error("binder: %d:%d got new " "transaction with bad transaction stack" ", transaction %d has target %d:%d\n", proc->pid, thread->pid, tmp->debug_id, tmp->to_proc ? tmp->to_proc->pid : 0, tmp->to_thread ? tmp->to_thread->pid : 0); return_error = BR_FAILED_REPLY; goto err_bad_call_stack; } while (tmp) { if (tmp->from && tmp->from->proc == target_proc) target_thread = tmp->from; tmp = tmp->from_parent; } } } if (target_thread) { e->to_thread = target_thread->pid; target_list = &target_thread->todo; target_wait = &target_thread->wait; } else { target_list = &target_proc->todo; target_wait = &target_proc->wait; } e->to_proc = target_proc->pid; /* TODO: reuse incoming transaction for reply */ t = kzalloc(sizeof(*t), GFP_KERNEL); if (t == NULL) { return_error = BR_FAILED_REPLY; goto err_alloc_t_failed; } binder_stats_created(BINDER_STAT_TRANSACTION); tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL); if (tcomplete == NULL) { return_error = BR_FAILED_REPLY; goto err_alloc_tcomplete_failed; } binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE); t->debug_id = ++binder_last_id; e->debug_id = t->debug_id; if (reply) binder_debug(BINDER_DEBUG_TRANSACTION, "binder: %d:%d BC_REPLY %d -> %d:%d, " "data %p-%p size %zd-%zd\n", proc->pid, thread->pid, t->debug_id, target_proc->pid, target_thread->pid, tr->data.ptr.buffer, tr->data.ptr.offsets, tr->data_size, tr->offsets_size); else binder_debug(BINDER_DEBUG_TRANSACTION, "binder: %d:%d BC_TRANSACTION %d -> " "%d - node %d, data %p-%p size %zd-%zd\n", proc->pid, thread->pid, t->debug_id, target_proc->pid, target_node->debug_id, tr->data.ptr.buffer, tr->data.ptr.offsets, tr->data_size, tr->offsets_size); if (!reply && !(tr->flags & TF_ONE_WAY)) t->from = thread; else t->from = NULL; t->sender_euid = proc->tsk->cred->euid; t->to_proc = target_proc; t->to_thread = target_thread; t->code = tr->code; t->flags = tr->flags; t->priority = task_nice(current); t->buffer = binder_alloc_buf(target_proc, tr->data_size, tr->offsets_size, !reply && (t->flags & TF_ONE_WAY)); if (t->buffer == NULL) { return_error = BR_FAILED_REPLY; goto err_binder_alloc_buf_failed; } t->buffer->allow_user_free = 0; t->buffer->debug_id = t->debug_id; t->buffer->transaction = t; t->buffer->target_node = target_node; if (target_node) binder_inc_node(target_node, 1, 0, NULL); offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *))); if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) { binder_user_error("binder: %d:%d got transaction with invalid " "data ptr\n", proc->pid, thread->pid); return_error = BR_FAILED_REPLY; goto err_copy_data_failed; } if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) { binder_user_error("binder: %d:%d got transaction with invalid " "offsets ptr\n", proc->pid, thread->pid); return_error = BR_FAILED_REPLY; goto err_copy_data_failed; } if (!IS_ALIGNED(tr->offsets_size, sizeof(size_t))) { binder_user_error("binder: %d:%d got transaction with " "invalid offsets size, %zd\n", proc->pid, thread->pid, tr->offsets_size); return_error = BR_FAILED_REPLY; goto err_bad_offset; } off_end = (void *)offp + tr->offsets_size; for (; offp < off_end; offp++) { struct flat_binder_object *fp; if (*offp > t->buffer->data_size - sizeof(*fp) || t->buffer->data_size < sizeof(*fp) || !IS_ALIGNED(*offp, sizeof(void *))) { binder_user_error("binder: %d:%d got transaction with " "invalid offset, %zd\n", proc->pid, thread->pid, *offp); return_error = BR_FAILED_REPLY; goto err_bad_offset; } fp = (struct flat_binder_object *)(t->buffer->data + *offp); switch (fp->type) { case BINDER_TYPE_BINDER: case BINDER_TYPE_WEAK_BINDER: { struct binder_ref *ref; struct binder_node *node = binder_get_node(proc, fp->binder); if (node == NULL) { node = binder_new_node(proc, fp->binder, fp->cookie); if (node == NULL) { return_error = BR_FAILED_REPLY; goto err_binder_new_node_failed; } node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK; node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS); } if (fp->cookie != node->cookie) { binder_user_error("binder: %d:%d sending u%p " "node %d, cookie mismatch %p != %p\n", proc->pid, thread->pid, fp->binder, node->debug_id, fp->cookie, node->cookie); goto err_binder_get_ref_for_node_failed; } ref = binder_get_ref_for_node(target_proc, node); if (ref == NULL) { return_error = BR_FAILED_REPLY; goto err_binder_get_ref_for_node_failed; } if (fp->type == BINDER_TYPE_BINDER) fp->type = BINDER_TYPE_HANDLE; else fp->type = BINDER_TYPE_WEAK_HANDLE; fp->handle = ref->desc; binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE, &thread->todo); binder_debug(BINDER_DEBUG_TRANSACTION, " node %d u%p -> ref %d desc %d\n", node->debug_id, node->ptr, ref->debug_id, ref->desc); } break; case BINDER_TYPE_HANDLE: case BINDER_TYPE_WEAK_HANDLE: { struct binder_ref *ref = binder_get_ref(proc, fp->handle); if (ref == NULL) { binder_user_error("binder: %d:%d got " "transaction with invalid " "handle, %ld\n", proc->pid, thread->pid, fp->handle); return_error = BR_FAILED_REPLY; goto err_binder_get_ref_failed; } if (ref->node->proc == target_proc) { if (fp->type == BINDER_TYPE_HANDLE) fp->type = BINDER_TYPE_BINDER; else fp->type = BINDER_TYPE_WEAK_BINDER; fp->binder = ref->node->ptr; fp->cookie = ref->node->cookie; binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL); binder_debug(BINDER_DEBUG_TRANSACTION, " ref %d desc %d -> node %d u%p\n", ref->debug_id, ref->desc, ref->node->debug_id, ref->node->ptr); } else { struct binder_ref *new_ref; new_ref = binder_get_ref_for_node(target_proc, ref->node); if (new_ref == NULL) { return_error = BR_FAILED_REPLY; goto err_binder_get_ref_for_node_failed; } fp->handle = new_ref->desc; binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL); binder_debug(BINDER_DEBUG_TRANSACTION, " ref %d desc %d -> ref %d desc %d (node %d)\n", ref->debug_id, ref->desc, new_ref->debug_id, new_ref->desc, ref->node->debug_id); } } break; case BINDER_TYPE_FD: { int target_fd; struct file *file; if (reply) { if (!(in_reply_to->flags & TF_ACCEPT_FDS)) { binder_user_error("binder: %d:%d got reply with fd, %ld, but target does not allow fds\n", proc->pid, thread->pid, fp->handle); return_error = BR_FAILED_REPLY; goto err_fd_not_allowed; } } else if (!target_node->accept_fds) { binder_user_error("binder: %d:%d got transaction with fd, %ld, but target does not allow fds\n", proc->pid, thread->pid, fp->handle); return_error = BR_FAILED_REPLY; goto err_fd_not_allowed; } file = fget(fp->handle); if (file == NULL) { binder_user_error("binder: %d:%d got transaction with invalid fd, %ld\n", proc->pid, thread->pid, fp->handle); return_error = BR_FAILED_REPLY; goto err_fget_failed; } target_fd = task_get_unused_fd_flags(target_proc, O_CLOEXEC); if (target_fd < 0) { fput(file); return_error = BR_FAILED_REPLY; goto err_get_unused_fd_failed; } task_fd_install(target_proc, target_fd, file); binder_debug(BINDER_DEBUG_TRANSACTION, " fd %ld -> %d\n", fp->handle, target_fd); /* TODO: fput? */ fp->handle = target_fd; } break; default: binder_user_error("binder: %d:%d got transactio" "n with invalid object type, %lx\n", proc->pid, thread->pid, fp->type); return_error = BR_FAILED_REPLY; goto err_bad_object_type; } } if (reply) { BUG_ON(t->buffer->async_transaction != 0); binder_pop_transaction(target_thread, in_reply_to); } else if (!(t->flags & TF_ONE_WAY)) { BUG_ON(t->buffer->async_transaction != 0); t->need_reply = 1; t->from_parent = thread->transaction_stack; thread->transaction_stack = t; } else { BUG_ON(target_node == NULL); BUG_ON(t->buffer->async_transaction != 1); if (target_node->has_async_transaction) { target_list = &target_node->async_todo; target_wait = NULL; } else target_node->has_async_transaction = 1; } t->work.type = BINDER_WORK_TRANSACTION; list_add_tail(&t->work.entry, target_list); tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE; list_add_tail(&tcomplete->entry, &thread->todo); if (target_wait) wake_up_interruptible(target_wait); return; err_get_unused_fd_failed: err_fget_failed: err_fd_not_allowed: err_binder_get_ref_for_node_failed: err_binder_get_ref_failed: err_binder_new_node_failed: err_bad_object_type: err_bad_offset: err_copy_data_failed: binder_transaction_buffer_release(target_proc, t->buffer, offp); t->buffer->transaction = NULL; binder_free_buf(target_proc, t->buffer); err_binder_alloc_buf_failed: kfree(tcomplete); binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE); err_alloc_tcomplete_failed: kfree(t); binder_stats_deleted(BINDER_STAT_TRANSACTION); err_alloc_t_failed: err_bad_call_stack: err_empty_call_stack: err_dead_binder: err_invalid_target_handle: err_no_context_mgr_node: binder_debug(BINDER_DEBUG_FAILED_TRANSACTION, "binder: %d:%d transaction failed %d, size %zd-%zd\n", proc->pid, thread->pid, return_error, tr->data_size, tr->offsets_size); { struct binder_transaction_log_entry *fe; fe = binder_transaction_log_add(&binder_transaction_log_failed); *fe = *e; } BUG_ON(thread->return_error != BR_OK); if (in_reply_to) { thread->return_error = BR_TRANSACTION_COMPLETE; binder_send_failed_reply(in_reply_to, return_error); } else thread->return_error = return_error; } int binder_thread_write(struct binder_proc *proc, struct binder_thread *thread, void __user *buffer, int size, signed long *consumed) { uint32_t cmd; void __user *ptr = buffer + *consumed; void __user *end = buffer + size; while (ptr < end && thread->return_error == BR_OK) { if (get_user(cmd, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) { binder_stats.bc[_IOC_NR(cmd)]++; proc->stats.bc[_IOC_NR(cmd)]++; thread->stats.bc[_IOC_NR(cmd)]++; } switch (cmd) { case BC_INCREFS: case BC_ACQUIRE: case BC_RELEASE: case BC_DECREFS: { uint32_t target; struct binder_ref *ref; const char *debug_string; if (get_user(target, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (target == 0 && binder_context_mgr_node && (cmd == BC_INCREFS || cmd == BC_ACQUIRE)) { ref = binder_get_ref_for_node(proc, binder_context_mgr_node); if (ref->desc != target) { binder_user_error("binder: %d:" "%d tried to acquire " "reference to desc 0, " "got %d instead\n", proc->pid, thread->pid, ref->desc); } } else ref = binder_get_ref(proc, target); if (ref == NULL) { binder_user_error("binder: %d:%d refcou" "nt change on invalid ref %d\n", proc->pid, thread->pid, target); break; } switch (cmd) { case BC_INCREFS: debug_string = "IncRefs"; binder_inc_ref(ref, 0, NULL); break; case BC_ACQUIRE: debug_string = "Acquire"; binder_inc_ref(ref, 1, NULL); break; case BC_RELEASE: debug_string = "Release"; binder_dec_ref(ref, 1); break; case BC_DECREFS: default: debug_string = "DecRefs"; binder_dec_ref(ref, 0); break; } binder_debug(BINDER_DEBUG_USER_REFS, "binder: %d:%d %s ref %d desc %d s %d w %d for node %d\n", proc->pid, thread->pid, debug_string, ref->debug_id, ref->desc, ref->strong, ref->weak, ref->node->debug_id); break; } case BC_INCREFS_DONE: case BC_ACQUIRE_DONE: { void __user *node_ptr; void *cookie; struct binder_node *node; if (get_user(node_ptr, (void * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); if (get_user(cookie, (void * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); node = binder_get_node(proc, node_ptr); if (node == NULL) { binder_user_error("binder: %d:%d " "%s u%p no match\n", proc->pid, thread->pid, cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE", node_ptr); break; } if (cookie != node->cookie) { binder_user_error("binder: %d:%d %s u%p node %d" " cookie mismatch %p != %p\n", proc->pid, thread->pid, cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE", node_ptr, node->debug_id, cookie, node->cookie); break; } if (cmd == BC_ACQUIRE_DONE) { if (node->pending_strong_ref == 0) { binder_user_error("binder: %d:%d " "BC_ACQUIRE_DONE node %d has " "no pending acquire request\n", proc->pid, thread->pid, node->debug_id); break; } node->pending_strong_ref = 0; } else { if (node->pending_weak_ref == 0) { binder_user_error("binder: %d:%d " "BC_INCREFS_DONE node %d has " "no pending increfs request\n", proc->pid, thread->pid, node->debug_id); break; } node->pending_weak_ref = 0; } binder_dec_node(node, cmd == BC_ACQUIRE_DONE, 0); binder_debug(BINDER_DEBUG_USER_REFS, "binder: %d:%d %s node %d ls %d lw %d\n", proc->pid, thread->pid, cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE", node->debug_id, node->local_strong_refs, node->local_weak_refs); break; } case BC_ATTEMPT_ACQUIRE: printk(KERN_ERR "binder: BC_ATTEMPT_ACQUIRE not supported\n"); return -EINVAL; case BC_ACQUIRE_RESULT: printk(KERN_ERR "binder: BC_ACQUIRE_RESULT not supported\n"); return -EINVAL; case BC_FREE_BUFFER: { void __user *data_ptr; struct binder_buffer *buffer; if (get_user(data_ptr, (void * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); buffer = binder_buffer_lookup(proc, data_ptr); if (buffer == NULL) { binder_user_error("binder: %d:%d " "BC_FREE_BUFFER u%p no match\n", proc->pid, thread->pid, data_ptr); break; } if (!buffer->allow_user_free) { binder_user_error("binder: %d:%d " "BC_FREE_BUFFER u%p matched " "unreturned buffer\n", proc->pid, thread->pid, data_ptr); break; } binder_debug(BINDER_DEBUG_FREE_BUFFER, "binder: %d:%d BC_FREE_BUFFER u%p found buffer %d for %s transaction\n", proc->pid, thread->pid, data_ptr, buffer->debug_id, buffer->transaction ? "active" : "finished"); if (buffer->transaction) { buffer->transaction->buffer = NULL; buffer->transaction = NULL; } if (buffer->async_transaction && buffer->target_node) { BUG_ON(!buffer->target_node->has_async_transaction); if (list_empty(&buffer->target_node->async_todo)) buffer->target_node->has_async_transaction = 0; else list_move_tail(buffer->target_node->async_todo.next, &thread->todo); } binder_transaction_buffer_release(proc, buffer, NULL); binder_free_buf(proc, buffer); break; } case BC_TRANSACTION: case BC_REPLY: { struct binder_transaction_data tr; if (copy_from_user(&tr, ptr, sizeof(tr))) return -EFAULT; ptr += sizeof(tr); binder_transaction(proc, thread, &tr, cmd == BC_REPLY); break; } case BC_REGISTER_LOOPER: binder_debug(BINDER_DEBUG_THREADS, "binder: %d:%d BC_REGISTER_LOOPER\n", proc->pid, thread->pid); if (thread->looper & BINDER_LOOPER_STATE_ENTERED) { thread->looper |= BINDER_LOOPER_STATE_INVALID; binder_user_error("binder: %d:%d ERROR:" " BC_REGISTER_LOOPER called " "after BC_ENTER_LOOPER\n", proc->pid, thread->pid); } else if (proc->requested_threads == 0) { thread->looper |= BINDER_LOOPER_STATE_INVALID; binder_user_error("binder: %d:%d ERROR:" " BC_REGISTER_LOOPER called " "without request\n", proc->pid, thread->pid); } else { proc->requested_threads--; proc->requested_threads_started++; } thread->looper |= BINDER_LOOPER_STATE_REGISTERED; break; case BC_ENTER_LOOPER: binder_debug(BINDER_DEBUG_THREADS, "binder: %d:%d BC_ENTER_LOOPER\n", proc->pid, thread->pid); if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) { thread->looper |= BINDER_LOOPER_STATE_INVALID; binder_user_error("binder: %d:%d ERROR:" " BC_ENTER_LOOPER called after " "BC_REGISTER_LOOPER\n", proc->pid, thread->pid); } thread->looper |= BINDER_LOOPER_STATE_ENTERED; break; case BC_EXIT_LOOPER: binder_debug(BINDER_DEBUG_THREADS, "binder: %d:%d BC_EXIT_LOOPER\n", proc->pid, thread->pid); thread->looper |= BINDER_LOOPER_STATE_EXITED; break; case BC_REQUEST_DEATH_NOTIFICATION: case BC_CLEAR_DEATH_NOTIFICATION: { uint32_t target; void __user *cookie; struct binder_ref *ref; struct binder_ref_death *death; if (get_user(target, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (get_user(cookie, (void __user * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); ref = binder_get_ref(proc, target); if (ref == NULL) { binder_user_error("binder: %d:%d %s " "invalid ref %d\n", proc->pid, thread->pid, cmd == BC_REQUEST_DEATH_NOTIFICATION ? "BC_REQUEST_DEATH_NOTIFICATION" : "BC_CLEAR_DEATH_NOTIFICATION", target); break; } binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION, "binder: %d:%d %s %p ref %d desc %d s %d w %d for node %d\n", proc->pid, thread->pid, cmd == BC_REQUEST_DEATH_NOTIFICATION ? "BC_REQUEST_DEATH_NOTIFICATION" : "BC_CLEAR_DEATH_NOTIFICATION", cookie, ref->debug_id, ref->desc, ref->strong, ref->weak, ref->node->debug_id); if (cmd == BC_REQUEST_DEATH_NOTIFICATION) { if (ref->death) { binder_user_error("binder: %d:%" "d BC_REQUEST_DEATH_NOTI" "FICATION death notific" "ation already set\n", proc->pid, thread->pid); break; } death = kzalloc(sizeof(*death), GFP_KERNEL); if (death == NULL) { thread->return_error = BR_ERROR; binder_debug(BINDER_DEBUG_FAILED_TRANSACTION, "binder: %d:%d " "BC_REQUEST_DEATH_NOTIFICATION failed\n", proc->pid, thread->pid); break; } binder_stats_created(BINDER_STAT_DEATH); INIT_LIST_HEAD(&death->work.entry); death->cookie = cookie; ref->death = death; if (ref->node->proc == NULL) { ref->death->work.type = BINDER_WORK_DEAD_BINDER; if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) { list_add_tail(&ref->death->work.entry, &thread->todo); } else { list_add_tail(&ref->death->work.entry, &proc->todo); wake_up_interruptible(&proc->wait); } } } else { if (ref->death == NULL) { binder_user_error("binder: %d:%" "d BC_CLEAR_DEATH_NOTIFI" "CATION death notificat" "ion not active\n", proc->pid, thread->pid); break; } death = ref->death; if (death->cookie != cookie) { binder_user_error("binder: %d:%" "d BC_CLEAR_DEATH_NOTIFI" "CATION death notificat" "ion cookie mismatch " "%p != %p\n", proc->pid, thread->pid, death->cookie, cookie); break; } ref->death = NULL; if (list_empty(&death->work.entry)) { death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION; if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) { list_add_tail(&death->work.entry, &thread->todo); } else { list_add_tail(&death->work.entry, &proc->todo); wake_up_interruptible(&proc->wait); } } else { BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER); death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR; } } } break; case BC_DEAD_BINDER_DONE: { struct binder_work *w; void __user *cookie; struct binder_ref_death *death = NULL; if (get_user(cookie, (void __user * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); list_for_each_entry(w, &proc->delivered_death, entry) { struct binder_ref_death *tmp_death = container_of(w, struct binder_ref_death, work); if (tmp_death->cookie == cookie) { death = tmp_death; break; } } binder_debug(BINDER_DEBUG_DEAD_BINDER, "binder: %d:%d BC_DEAD_BINDER_DONE %p found %p\n", proc->pid, thread->pid, cookie, death); if (death == NULL) { binder_user_error("binder: %d:%d BC_DEAD" "_BINDER_DONE %p not found\n", proc->pid, thread->pid, cookie); break; } list_del_init(&death->work.entry); if (death->work.type == BINDER_WORK_DEAD_BINDER_AND_CLEAR) { death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION; if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) { list_add_tail(&death->work.entry, &thread->todo); } else { list_add_tail(&death->work.entry, &proc->todo); wake_up_interruptible(&proc->wait); } } } break; default: printk(KERN_ERR "binder: %d:%d unknown command %d\n", proc->pid, thread->pid, cmd); return -EINVAL; } *consumed = ptr - buffer; } return 0; } void binder_stat_br(struct binder_proc *proc, struct binder_thread *thread, uint32_t cmd) { if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.br)) { binder_stats.br[_IOC_NR(cmd)]++; proc->stats.br[_IOC_NR(cmd)]++; thread->stats.br[_IOC_NR(cmd)]++; } } static int binder_has_proc_work(struct binder_proc *proc, struct binder_thread *thread) { return !list_empty(&proc->todo) || (thread->looper & BINDER_LOOPER_STATE_NEED_RETURN); } static int binder_has_thread_work(struct binder_thread *thread) { return !list_empty(&thread->todo) || thread->return_error != BR_OK || (thread->looper & BINDER_LOOPER_STATE_NEED_RETURN); } static int binder_thread_read(struct binder_proc *proc, struct binder_thread *thread, void __user *buffer, int size, signed long *consumed, int non_block) { void __user *ptr = buffer + *consumed; void __user *end = buffer + size; int ret = 0; int wait_for_proc_work; if (*consumed == 0) { if (put_user(BR_NOOP, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); } retry: wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo); if (thread->return_error != BR_OK && ptr < end) { if (thread->return_error2 != BR_OK) { if (put_user(thread->return_error2, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (ptr == end) goto done; thread->return_error2 = BR_OK; } if (put_user(thread->return_error, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); thread->return_error = BR_OK; goto done; } thread->looper |= BINDER_LOOPER_STATE_WAITING; if (wait_for_proc_work) proc->ready_threads++; mutex_unlock(&binder_lock); if (wait_for_proc_work) { if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED))) { binder_user_error("binder: %d:%d ERROR: Thread waiting " "for process work before calling BC_REGISTER_" "LOOPER or BC_ENTER_LOOPER (state %x)\n", proc->pid, thread->pid, thread->looper); wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2); } binder_set_nice(proc->default_priority); if (non_block) { if (!binder_has_proc_work(proc, thread)) ret = -EAGAIN; } else ret = wait_event_interruptible_exclusive(proc->wait, binder_has_proc_work(proc, thread)); } else { if (non_block) { if (!binder_has_thread_work(thread)) ret = -EAGAIN; } else ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread)); } mutex_lock(&binder_lock); if (wait_for_proc_work) proc->ready_threads--; thread->looper &= ~BINDER_LOOPER_STATE_WAITING; if (ret) return ret; while (1) { uint32_t cmd; struct binder_transaction_data tr; struct binder_work *w; struct binder_transaction *t = NULL; if (!list_empty(&thread->todo)) w = list_first_entry(&thread->todo, struct binder_work, entry); else if (!list_empty(&proc->todo) && wait_for_proc_work) w = list_first_entry(&proc->todo, struct binder_work, entry); else { if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */ goto retry; break; } if (end - ptr < sizeof(tr) + 4) break; switch (w->type) { case BINDER_WORK_TRANSACTION: { t = container_of(w, struct binder_transaction, work); } break; case BINDER_WORK_TRANSACTION_COMPLETE: { cmd = BR_TRANSACTION_COMPLETE; if (put_user(cmd, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); binder_stat_br(proc, thread, cmd); binder_debug(BINDER_DEBUG_TRANSACTION_COMPLETE, "binder: %d:%d BR_TRANSACTION_COMPLETE\n", proc->pid, thread->pid); list_del(&w->entry); kfree(w); binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE); } break; case BINDER_WORK_NODE: { struct binder_node *node = container_of(w, struct binder_node, work); uint32_t cmd = BR_NOOP; const char *cmd_name; int strong = node->internal_strong_refs || node->local_strong_refs; int weak = !hlist_empty(&node->refs) || node->local_weak_refs || strong; if (weak && !node->has_weak_ref) { cmd = BR_INCREFS; cmd_name = "BR_INCREFS"; node->has_weak_ref = 1; node->pending_weak_ref = 1; node->local_weak_refs++; } else if (strong && !node->has_strong_ref) { cmd = BR_ACQUIRE; cmd_name = "BR_ACQUIRE"; node->has_strong_ref = 1; node->pending_strong_ref = 1; node->local_strong_refs++; } else if (!strong && node->has_strong_ref) { cmd = BR_RELEASE; cmd_name = "BR_RELEASE"; node->has_strong_ref = 0; } else if (!weak && node->has_weak_ref) { cmd = BR_DECREFS; cmd_name = "BR_DECREFS"; node->has_weak_ref = 0; } if (cmd != BR_NOOP) { if (put_user(cmd, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (put_user(node->ptr, (void * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); if (put_user(node->cookie, (void * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); binder_stat_br(proc, thread, cmd); binder_debug(BINDER_DEBUG_USER_REFS, "binder: %d:%d %s %d u%p c%p\n", proc->pid, thread->pid, cmd_name, node->debug_id, node->ptr, node->cookie); } else { list_del_init(&w->entry); if (!weak && !strong) { binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: %d:%d node %d u%p c%p deleted\n", proc->pid, thread->pid, node->debug_id, node->ptr, node->cookie); rb_erase(&node->rb_node, &proc->nodes); kfree(node); binder_stats_deleted(BINDER_STAT_NODE); } else { binder_debug(BINDER_DEBUG_INTERNAL_REFS, "binder: %d:%d node %d u%p c%p state unchanged\n", proc->pid, thread->pid, node->debug_id, node->ptr, node->cookie); } } } break; case BINDER_WORK_DEAD_BINDER: case BINDER_WORK_DEAD_BINDER_AND_CLEAR: case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: { struct binder_ref_death *death; uint32_t cmd; death = container_of(w, struct binder_ref_death, work); if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE; else cmd = BR_DEAD_BINDER; if (put_user(cmd, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (put_user(death->cookie, (void * __user *)ptr)) return -EFAULT; ptr += sizeof(void *); binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION, "binder: %d:%d %s %p\n", proc->pid, thread->pid, cmd == BR_DEAD_BINDER ? "BR_DEAD_BINDER" : "BR_CLEAR_DEATH_NOTIFICATION_DONE", death->cookie); if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) { list_del(&w->entry); kfree(death); binder_stats_deleted(BINDER_STAT_DEATH); } else list_move(&w->entry, &proc->delivered_death); if (cmd == BR_DEAD_BINDER) goto done; /* DEAD_BINDER notifications can cause transactions */ } break; } if (!t) continue; BUG_ON(t->buffer == NULL); if (t->buffer->target_node) { struct binder_node *target_node = t->buffer->target_node; tr.target.ptr = target_node->ptr; tr.cookie = target_node->cookie; t->saved_priority = task_nice(current); if (t->priority < target_node->min_priority && !(t->flags & TF_ONE_WAY)) binder_set_nice(t->priority); else if (!(t->flags & TF_ONE_WAY) || t->saved_priority > target_node->min_priority) binder_set_nice(target_node->min_priority); cmd = BR_TRANSACTION; } else { tr.target.ptr = NULL; tr.cookie = NULL; cmd = BR_REPLY; } tr.code = t->code; tr.flags = t->flags; tr.sender_euid = t->sender_euid; if (t->from) { struct task_struct *sender = t->from->proc->tsk; tr.sender_pid = task_tgid_nr_ns(sender, current->nsproxy->pid_ns); } else { tr.sender_pid = 0; } tr.data_size = t->buffer->data_size; tr.offsets_size = t->buffer->offsets_size; tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset; tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *)); if (put_user(cmd, (uint32_t __user *)ptr)) return -EFAULT; ptr += sizeof(uint32_t); if (copy_to_user(ptr, &tr, sizeof(tr))) return -EFAULT; ptr += sizeof(tr); binder_stat_br(proc, thread, cmd); binder_debug(BINDER_DEBUG_TRANSACTION, "binder: %d:%d %s %d %d:%d, cmd %d" "size %zd-%zd ptr %p-%p\n", proc->pid, thread->pid, (cmd == BR_TRANSACTION) ? "BR_TRANSACTION" : "BR_REPLY", t->debug_id, t->from ? t->from->proc->pid : 0, t->from ? t->from->pid : 0, cmd, t->buffer->data_size, t->buffer->offsets_size, tr.data.ptr.buffer, tr.data.ptr.offsets); list_del(&t->work.entry); t->buffer->allow_user_free = 1; if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) { t->to_parent = thread->transaction_stack; t->to_thread = thread; thread->transaction_stack = t; } else { t->buffer->transaction = NULL; kfree(t); binder_stats_deleted(BINDER_STAT_TRANSACTION); } break; } done: *consumed = ptr - buffer; if (proc->requested_threads + proc->ready_threads == 0 && proc->requested_threads_started < proc->max_threads && (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) /* the user-space code fails to */ /*spawn a new thread if we leave this out */) { proc->requested_threads++; binder_debug(BINDER_DEBUG_THREADS, "binder: %d:%d BR_SPAWN_LOOPER\n", proc->pid, thread->pid); if (put_user(BR_SPAWN_LOOPER, (uint32_t __user *)buffer)) return -EFAULT; } return 0; } static void binder_release_work(struct list_head *list) { struct binder_work *w; while (!list_empty(list)) { w = list_first_entry(list, struct binder_work, entry); list_del_init(&w->entry); switch (w->type) { case BINDER_WORK_TRANSACTION: { struct binder_transaction *t; t = container_of(w, struct binder_transaction, work); if (t->buffer->target_node && !(t->flags & TF_ONE_WAY)) binder_send_failed_reply(t, BR_DEAD_REPLY); } break; case BINDER_WORK_TRANSACTION_COMPLETE: { kfree(w); binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE); } break; default: break; } } } static struct binder_thread *binder_get_thread(struct binder_proc *proc) { struct binder_thread *thread = NULL; struct rb_node *parent = NULL; struct rb_node **p = &proc->threads.rb_node; while (*p) { parent = *p; thread = rb_entry(parent, struct binder_thread, rb_node); if (current->pid < thread->pid) p = &(*p)->rb_left; else if (current->pid > thread->pid) p = &(*p)->rb_right; else break; } if (*p == NULL) { thread = kzalloc(sizeof(*thread), GFP_KERNEL); if (thread == NULL) return NULL; binder_stats_created(BINDER_STAT_THREAD); thread->proc = proc; thread->pid = current->pid; init_waitqueue_head(&thread->wait); INIT_LIST_HEAD(&thread->todo); rb_link_node(&thread->rb_node, parent, p); rb_insert_color(&thread->rb_node, &proc->threads); thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN; thread->return_error = BR_OK; thread->return_error2 = BR_OK; } return thread; } static int binder_free_thread(struct binder_proc *proc, struct binder_thread *thread) { struct binder_transaction *t; struct binder_transaction *send_reply = NULL; int active_transactions = 0; rb_erase(&thread->rb_node, &proc->threads); t = thread->transaction_stack; if (t && t->to_thread == thread) send_reply = t; while (t) { active_transactions++; binder_debug(BINDER_DEBUG_DEAD_TRANSACTION, "binder: release %d:%d transaction %d " "%s, still active\n", proc->pid, thread->pid, t->debug_id, (t->to_thread == thread) ? "in" : "out"); if (t->to_thread == thread) { t->to_proc = NULL; t->to_thread = NULL; if (t->buffer) { t->buffer->transaction = NULL; t->buffer = NULL; } t = t->to_parent; } else if (t->from == thread) { t->from = NULL; t = t->from_parent; } else BUG(); } if (send_reply) binder_send_failed_reply(send_reply, BR_DEAD_REPLY); binder_release_work(&thread->todo); kfree(thread); binder_stats_deleted(BINDER_STAT_THREAD); return active_transactions; } static unsigned int binder_poll(struct file *filp, struct poll_table_struct *wait) { struct binder_proc *proc = filp->private_data; struct binder_thread *thread = NULL; int wait_for_proc_work; mutex_lock(&binder_lock); thread = binder_get_thread(proc); wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo) && thread->return_error == BR_OK; mutex_unlock(&binder_lock); if (wait_for_proc_work) { if (binder_has_proc_work(proc, thread)) return POLLIN; poll_wait(filp, &proc->wait, wait); if (binder_has_proc_work(proc, thread)) return POLLIN; } else { if (binder_has_thread_work(thread)) return POLLIN; poll_wait(filp, &thread->wait, wait); if (binder_has_thread_work(thread)) return POLLIN; } return 0; } static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { int ret; struct binder_proc *proc = filp->private_data; struct binder_thread *thread; unsigned int size = _IOC_SIZE(cmd); void __user *ubuf = (void __user *)arg; /*printk(KERN_INFO "binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/ ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2); if (ret) return ret; mutex_lock(&binder_lock); thread = binder_get_thread(proc); if (thread == NULL) { ret = -ENOMEM; goto err; } switch (cmd) { case BINDER_WRITE_READ: { struct binder_write_read bwr; if (size != sizeof(struct binder_write_read)) { ret = -EINVAL; goto err; } if (copy_from_user(&bwr, ubuf, sizeof(bwr))) { ret = -EFAULT; goto err; } binder_debug(BINDER_DEBUG_READ_WRITE, "binder: %d:%d write %ld at %08lx, read %ld at %08lx\n", proc->pid, thread->pid, bwr.write_size, bwr.write_buffer, bwr.read_size, bwr.read_buffer); if (bwr.write_size > 0) { ret = binder_thread_write(proc, thread, (void __user *)bwr.write_buffer, bwr.write_size, &bwr.write_consumed); if (ret < 0) { bwr.read_consumed = 0; if (copy_to_user(ubuf, &bwr, sizeof(bwr))) ret = -EFAULT; goto err; } } if (bwr.read_size > 0) { ret = binder_thread_read(proc, thread, (void __user *)bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK); if (!list_empty(&proc->todo)) wake_up_interruptible(&proc->wait); if (ret < 0) { if (copy_to_user(ubuf, &bwr, sizeof(bwr))) ret = -EFAULT; goto err; } } binder_debug(BINDER_DEBUG_READ_WRITE, "binder: %d:%d wrote %ld of %ld, read return %ld of %ld\n", proc->pid, thread->pid, bwr.write_consumed, bwr.write_size, bwr.read_consumed, bwr.read_size); if (copy_to_user(ubuf, &bwr, sizeof(bwr))) { ret = -EFAULT; goto err; } break; } case BINDER_SET_MAX_THREADS: if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) { ret = -EINVAL; goto err; } break; case BINDER_SET_CONTEXT_MGR: if (binder_context_mgr_node != NULL) { printk(KERN_ERR "binder: BINDER_SET_CONTEXT_MGR already set\n"); ret = -EBUSY; goto err; } if (binder_context_mgr_uid != -1) { if (binder_context_mgr_uid != current->cred->euid) { printk(KERN_ERR "binder: BINDER_SET_" "CONTEXT_MGR bad uid %d != %d\n", current->cred->euid, binder_context_mgr_uid); ret = -EPERM; goto err; } } else binder_context_mgr_uid = current->cred->euid; binder_context_mgr_node = binder_new_node(proc, NULL, NULL); if (binder_context_mgr_node == NULL) { ret = -ENOMEM; goto err; } binder_context_mgr_node->local_weak_refs++; binder_context_mgr_node->local_strong_refs++; binder_context_mgr_node->has_strong_ref = 1; binder_context_mgr_node->has_weak_ref = 1; break; case BINDER_THREAD_EXIT: binder_debug(BINDER_DEBUG_THREADS, "binder: %d:%d exit\n", proc->pid, thread->pid); binder_free_thread(proc, thread); thread = NULL; break; case BINDER_VERSION: if (size != sizeof(struct binder_version)) { ret = -EINVAL; goto err; } if (put_user(BINDER_CURRENT_PROTOCOL_VERSION, &((struct binder_version *)ubuf)->protocol_version)) { ret = -EINVAL; goto err; } break; default: ret = -EINVAL; goto err; } ret = 0; err: if (thread) thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN; mutex_unlock(&binder_lock); wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2); if (ret && ret != -ERESTARTSYS) printk(KERN_INFO "binder: %d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret); return ret; } static void binder_vma_open(struct vm_area_struct *vma) { struct binder_proc *proc = vma->vm_private_data; binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder: %d open vm area %lx-%lx (%ld K) vma %lx pagep %lx\n", proc->pid, vma->vm_start, vma->vm_end, (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags, (unsigned long)pgprot_val(vma->vm_page_prot)); dump_stack(); } static void binder_vma_close(struct vm_area_struct *vma) { struct binder_proc *proc = vma->vm_private_data; binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder: %d close vm area %lx-%lx (%ld K) vma %lx pagep %lx\n", proc->pid, vma->vm_start, vma->vm_end, (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags, (unsigned long)pgprot_val(vma->vm_page_prot)); proc->vma = NULL; binder_defer_work(proc, BINDER_DEFERRED_PUT_FILES); } static struct vm_operations_struct binder_vm_ops = { .open = binder_vma_open, .close = binder_vma_close, }; static int binder_mmap(struct file *filp, struct vm_area_struct *vma) { int ret; struct vm_struct *area; struct binder_proc *proc = filp->private_data; const char *failure_string; struct binder_buffer *buffer; if ((vma->vm_end - vma->vm_start) > SZ_4M) vma->vm_end = vma->vm_start + SZ_4M; binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_mmap: %d %lx-%lx (%ld K) vma %lx pagep %lx\n", proc->pid, vma->vm_start, vma->vm_end, (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags, (unsigned long)pgprot_val(vma->vm_page_prot)); if (vma->vm_flags & FORBIDDEN_MMAP_FLAGS) { ret = -EPERM; failure_string = "bad vm_flags"; goto err_bad_arg; } vma->vm_flags = (vma->vm_flags | VM_DONTCOPY) & ~VM_MAYWRITE; if (proc->buffer) { ret = -EBUSY; failure_string = "already mapped"; goto err_already_mapped; } area = get_vm_area(vma->vm_end - vma->vm_start, VM_IOREMAP); if (area == NULL) { ret = -ENOMEM; failure_string = "get_vm_area"; goto err_get_vm_area_failed; } proc->buffer = area->addr; proc->user_buffer_offset = vma->vm_start - (uintptr_t)proc->buffer; #ifdef CONFIG_CPU_CACHE_VIPT if (cache_is_vipt_aliasing()) { while (CACHE_COLOUR((vma->vm_start ^ (uint32_t)proc->buffer))) { printk(KERN_INFO "binder_mmap: %d %lx-%lx maps %p bad alignment\n", proc->pid, vma->vm_start, vma->vm_end, proc->buffer); vma->vm_start += PAGE_SIZE; } } #endif proc->pages = kzalloc(sizeof(proc->pages[0]) * ((vma->vm_end - vma->vm_start) / PAGE_SIZE), GFP_KERNEL); if (proc->pages == NULL) { ret = -ENOMEM; failure_string = "alloc page array"; goto err_alloc_pages_failed; } proc->buffer_size = vma->vm_end - vma->vm_start; vma->vm_ops = &binder_vm_ops; vma->vm_private_data = proc; if (binder_update_page_range(proc, 1, proc->buffer, proc->buffer + PAGE_SIZE, vma)) { ret = -ENOMEM; failure_string = "alloc small buf"; goto err_alloc_small_buf_failed; } buffer = proc->buffer; INIT_LIST_HEAD(&proc->buffers); list_add(&buffer->entry, &proc->buffers); buffer->free = 1; binder_insert_free_buffer(proc, buffer); proc->free_async_space = proc->buffer_size / 2; barrier(); proc->files = get_files_struct(current); proc->vma = vma; /*printk(KERN_INFO "binder_mmap: %d %lx-%lx maps %p\n", proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/ return 0; err_alloc_small_buf_failed: kfree(proc->pages); proc->pages = NULL; err_alloc_pages_failed: vfree(proc->buffer); proc->buffer = NULL; err_get_vm_area_failed: err_already_mapped: err_bad_arg: printk(KERN_ERR "binder_mmap: %d %lx-%lx %s failed %d\n", proc->pid, vma->vm_start, vma->vm_end, failure_string, ret); return ret; } static int binder_open(struct inode *nodp, struct file *filp) { struct binder_proc *proc; binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_open: %d:%d\n", current->group_leader->pid, current->pid); proc = kzalloc(sizeof(*proc), GFP_KERNEL); if (proc == NULL) return -ENOMEM; get_task_struct(current); proc->tsk = current; INIT_LIST_HEAD(&proc->todo); init_waitqueue_head(&proc->wait); proc->default_priority = task_nice(current); mutex_lock(&binder_lock); binder_stats_created(BINDER_STAT_PROC); hlist_add_head(&proc->proc_node, &binder_procs); proc->pid = current->group_leader->pid; INIT_LIST_HEAD(&proc->delivered_death); filp->private_data = proc; mutex_unlock(&binder_lock); if (binder_debugfs_dir_entry_proc) { char strbuf[11]; snprintf(strbuf, sizeof(strbuf), "%u", proc->pid); proc->debugfs_entry = debugfs_create_file(strbuf, S_IRUGO, binder_debugfs_dir_entry_proc, proc, &binder_proc_fops); } return 0; } static int binder_flush(struct file *filp, fl_owner_t id) { struct binder_proc *proc = filp->private_data; binder_defer_work(proc, BINDER_DEFERRED_FLUSH); return 0; } static void binder_deferred_flush(struct binder_proc *proc) { struct rb_node *n; int wake_count = 0; for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) { struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node); thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN; if (thread->looper & BINDER_LOOPER_STATE_WAITING) { wake_up_interruptible(&thread->wait); wake_count++; } } wake_up_interruptible_all(&proc->wait); binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_flush: %d woke %d threads\n", proc->pid, wake_count); } static int binder_release(struct inode *nodp, struct file *filp) { struct binder_proc *proc = filp->private_data; debugfs_remove(proc->debugfs_entry); binder_defer_work(proc, BINDER_DEFERRED_RELEASE); return 0; } static void binder_deferred_release(struct binder_proc *proc) { struct hlist_node *pos; struct binder_transaction *t; struct rb_node *n; int threads, nodes, incoming_refs, outgoing_refs, buffers, active_transactions, page_count; BUG_ON(proc->vma); BUG_ON(proc->files); hlist_del(&proc->proc_node); if (binder_context_mgr_node && binder_context_mgr_node->proc == proc) { binder_debug(BINDER_DEBUG_DEAD_BINDER, "binder_release: %d context_mgr_node gone\n", proc->pid); binder_context_mgr_node = NULL; } threads = 0; active_transactions = 0; while ((n = rb_first(&proc->threads))) { struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node); threads++; active_transactions += binder_free_thread(proc, thread); } nodes = 0; incoming_refs = 0; while ((n = rb_first(&proc->nodes))) { struct binder_node *node = rb_entry(n, struct binder_node, rb_node); nodes++; rb_erase(&node->rb_node, &proc->nodes); list_del_init(&node->work.entry); if (hlist_empty(&node->refs)) { kfree(node); binder_stats_deleted(BINDER_STAT_NODE); } else { struct binder_ref *ref; int death = 0; node->proc = NULL; node->local_strong_refs = 0; node->local_weak_refs = 0; hlist_add_head(&node->dead_node, &binder_dead_nodes); hlist_for_each_entry(ref, pos, &node->refs, node_entry) { incoming_refs++; if (ref->death) { death++; if (list_empty(&ref->death->work.entry)) { ref->death->work.type = BINDER_WORK_DEAD_BINDER; list_add_tail(&ref->death->work.entry, &ref->proc->todo); wake_up_interruptible(&ref->proc->wait); } else BUG(); } } binder_debug(BINDER_DEBUG_DEAD_BINDER, "binder: node %d now dead, " "refs %d, death %d\n", node->debug_id, incoming_refs, death); } } outgoing_refs = 0; while ((n = rb_first(&proc->refs_by_desc))) { struct binder_ref *ref = rb_entry(n, struct binder_ref, rb_node_desc); outgoing_refs++; binder_delete_ref(ref); } binder_release_work(&proc->todo); buffers = 0; while ((n = rb_first(&proc->allocated_buffers))) { struct binder_buffer *buffer = rb_entry(n, struct binder_buffer, rb_node); t = buffer->transaction; if (t) { t->buffer = NULL; buffer->transaction = NULL; printk(KERN_ERR "binder: release proc %d, " "transaction %d, not freed\n", proc->pid, t->debug_id); /*BUG();*/ } binder_free_buf(proc, buffer); buffers++; } binder_stats_deleted(BINDER_STAT_PROC); page_count = 0; if (proc->pages) { int i; for (i = 0; i < proc->buffer_size / PAGE_SIZE; i++) { if (proc->pages[i]) { void *page_addr = proc->buffer + i * PAGE_SIZE; binder_debug(BINDER_DEBUG_BUFFER_ALLOC, "binder_release: %d: " "page %d at %p not freed\n", proc->pid, i, page_addr); unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE); __free_page(proc->pages[i]); page_count++; } } kfree(proc->pages); vfree(proc->buffer); } put_task_struct(proc->tsk); binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_release: %d threads %d, nodes %d (ref %d), " "refs %d, active transactions %d, buffers %d, " "pages %d\n", proc->pid, threads, nodes, incoming_refs, outgoing_refs, active_transactions, buffers, page_count); kfree(proc); } static void binder_deferred_func(struct work_struct *work) { struct binder_proc *proc; struct files_struct *files; int defer; do { mutex_lock(&binder_lock); mutex_lock(&binder_deferred_lock); if (!hlist_empty(&binder_deferred_list)) { proc = hlist_entry(binder_deferred_list.first, struct binder_proc, deferred_work_node); hlist_del_init(&proc->deferred_work_node); defer = proc->deferred_work; proc->deferred_work = 0; } else { proc = NULL; defer = 0; } mutex_unlock(&binder_deferred_lock); files = NULL; if (defer & BINDER_DEFERRED_PUT_FILES) { files = proc->files; if (files) proc->files = NULL; } if (defer & BINDER_DEFERRED_FLUSH) binder_deferred_flush(proc); if (defer & BINDER_DEFERRED_RELEASE) binder_deferred_release(proc); /* frees proc */ mutex_unlock(&binder_lock); if (files) put_files_struct(files); } while (proc); } static DECLARE_WORK(binder_deferred_work, binder_deferred_func); static void binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer) { mutex_lock(&binder_deferred_lock); proc->deferred_work |= defer; if (hlist_unhashed(&proc->deferred_work_node)) { hlist_add_head(&proc->deferred_work_node, &binder_deferred_list); queue_work(binder_deferred_workqueue, &binder_deferred_work); } mutex_unlock(&binder_deferred_lock); } static void print_binder_transaction(struct seq_file *m, const char *prefix, struct binder_transaction *t) { seq_printf(m, "%s %d: %p from %d:%d to %d:%d code %x flags %x pri %ld r%d", prefix, t->debug_id, t, t->from ? t->from->proc->pid : 0, t->from ? t->from->pid : 0, t->to_proc ? t->to_proc->pid : 0, t->to_thread ? t->to_thread->pid : 0, t->code, t->flags, t->priority, t->need_reply); if (t->buffer == NULL) { seq_puts(m, " buffer free\n"); return; } if (t->buffer->target_node) seq_printf(m, " node %d", t->buffer->target_node->debug_id); seq_printf(m, " size %zd:%zd data %p\n", t->buffer->data_size, t->buffer->offsets_size, t->buffer->data); } static void print_binder_buffer(struct seq_file *m, const char *prefix, struct binder_buffer *buffer) { seq_printf(m, "%s %d: %p size %zd:%zd %s\n", prefix, buffer->debug_id, buffer->data, buffer->data_size, buffer->offsets_size, buffer->transaction ? "active" : "delivered"); } static void print_binder_work(struct seq_file *m, const char *prefix, const char *transaction_prefix, struct binder_work *w) { struct binder_node *node; struct binder_transaction *t; switch (w->type) { case BINDER_WORK_TRANSACTION: t = container_of(w, struct binder_transaction, work); print_binder_transaction(m, transaction_prefix, t); break; case BINDER_WORK_TRANSACTION_COMPLETE: seq_printf(m, "%stransaction complete\n", prefix); break; case BINDER_WORK_NODE: node = container_of(w, struct binder_node, work); seq_printf(m, "%snode work %d: u%p c%p\n", prefix, node->debug_id, node->ptr, node->cookie); break; case BINDER_WORK_DEAD_BINDER: seq_printf(m, "%shas dead binder\n", prefix); break; case BINDER_WORK_DEAD_BINDER_AND_CLEAR: seq_printf(m, "%shas cleared dead binder\n", prefix); break; case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: seq_printf(m, "%shas cleared death notification\n", prefix); break; default: seq_printf(m, "%sunknown work: type %d\n", prefix, w->type); break; } } static void print_binder_thread(struct seq_file *m, struct binder_thread *thread, int print_always) { struct binder_transaction *t; struct binder_work *w; size_t start_pos = m->count; size_t header_pos; seq_printf(m, " thread %d: l %02x\n", thread->pid, thread->looper); header_pos = m->count; t = thread->transaction_stack; while (t) { if (t->from == thread) { print_binder_transaction(m, " outgoing transaction", t); t = t->from_parent; } else if (t->to_thread == thread) { print_binder_transaction(m, " incoming transaction", t); t = t->to_parent; } else { print_binder_transaction(m, " bad transaction", t); t = NULL; } } list_for_each_entry(w, &thread->todo, entry) { print_binder_work(m, " ", " pending transaction", w); } if (!print_always && m->count == header_pos) m->count = start_pos; } static void print_binder_node(struct seq_file *m, struct binder_node *node) { struct binder_ref *ref; struct hlist_node *pos; struct binder_work *w; int count; count = 0; hlist_for_each_entry(ref, pos, &node->refs, node_entry) count++; seq_printf(m, " node %d: u%p c%p hs %d hw %d ls %d lw %d is %d iw %d", node->debug_id, node->ptr, node->cookie, node->has_strong_ref, node->has_weak_ref, node->local_strong_refs, node->local_weak_refs, node->internal_strong_refs, count); if (count) { seq_puts(m, " proc"); hlist_for_each_entry(ref, pos, &node->refs, node_entry) seq_printf(m, " %d", ref->proc->pid); } seq_puts(m, "\n"); list_for_each_entry(w, &node->async_todo, entry) print_binder_work(m, " ", " pending async transaction", w); } static void print_binder_ref(struct seq_file *m, struct binder_ref *ref) { seq_printf(m, " ref %d: desc %d %snode %d s %d w %d d %p\n", ref->debug_id, ref->desc, ref->node->proc ? "" : "dead ", ref->node->debug_id, ref->strong, ref->weak, ref->death); } static void print_binder_proc(struct seq_file *m, struct binder_proc *proc, int print_all) { struct binder_work *w; struct rb_node *n; size_t start_pos = m->count; size_t header_pos; seq_printf(m, "proc %d\n", proc->pid); header_pos = m->count; for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) print_binder_thread(m, rb_entry(n, struct binder_thread, rb_node), print_all); for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) { struct binder_node *node = rb_entry(n, struct binder_node, rb_node); if (print_all || node->has_async_transaction) print_binder_node(m, node); } if (print_all) { for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) print_binder_ref(m, rb_entry(n, struct binder_ref, rb_node_desc)); } for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n)) print_binder_buffer(m, " buffer", rb_entry(n, struct binder_buffer, rb_node)); list_for_each_entry(w, &proc->todo, entry) print_binder_work(m, " ", " pending transaction", w); list_for_each_entry(w, &proc->delivered_death, entry) { seq_puts(m, " has delivered dead binder\n"); break; } if (!print_all && m->count == header_pos) m->count = start_pos; } static const char *binder_return_strings[] = { "BR_ERROR", "BR_OK", "BR_TRANSACTION", "BR_REPLY", "BR_ACQUIRE_RESULT", "BR_DEAD_REPLY", "BR_TRANSACTION_COMPLETE", "BR_INCREFS", "BR_ACQUIRE", "BR_RELEASE", "BR_DECREFS", "BR_ATTEMPT_ACQUIRE", "BR_NOOP", "BR_SPAWN_LOOPER", "BR_FINISHED", "BR_DEAD_BINDER", "BR_CLEAR_DEATH_NOTIFICATION_DONE", "BR_FAILED_REPLY" }; static const char *binder_command_strings[] = { "BC_TRANSACTION", "BC_REPLY", "BC_ACQUIRE_RESULT", "BC_FREE_BUFFER", "BC_INCREFS", "BC_ACQUIRE", "BC_RELEASE", "BC_DECREFS", "BC_INCREFS_DONE", "BC_ACQUIRE_DONE", "BC_ATTEMPT_ACQUIRE", "BC_REGISTER_LOOPER", "BC_ENTER_LOOPER", "BC_EXIT_LOOPER", "BC_REQUEST_DEATH_NOTIFICATION", "BC_CLEAR_DEATH_NOTIFICATION", "BC_DEAD_BINDER_DONE" }; static const char *binder_objstat_strings[] = { "proc", "thread", "node", "ref", "death", "transaction", "transaction_complete" }; static void print_binder_stats(struct seq_file *m, const char *prefix, struct binder_stats *stats) { int i; BUILD_BUG_ON(ARRAY_SIZE(stats->bc) != ARRAY_SIZE(binder_command_strings)); for (i = 0; i < ARRAY_SIZE(stats->bc); i++) { if (stats->bc[i]) seq_printf(m, "%s%s: %d\n", prefix, binder_command_strings[i], stats->bc[i]); } BUILD_BUG_ON(ARRAY_SIZE(stats->br) != ARRAY_SIZE(binder_return_strings)); for (i = 0; i < ARRAY_SIZE(stats->br); i++) { if (stats->br[i]) seq_printf(m, "%s%s: %d\n", prefix, binder_return_strings[i], stats->br[i]); } BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) != ARRAY_SIZE(binder_objstat_strings)); BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) != ARRAY_SIZE(stats->obj_deleted)); for (i = 0; i < ARRAY_SIZE(stats->obj_created); i++) { if (stats->obj_created[i] || stats->obj_deleted[i]) seq_printf(m, "%s%s: active %d total %d\n", prefix, binder_objstat_strings[i], stats->obj_created[i] - stats->obj_deleted[i], stats->obj_created[i]); } } static void print_binder_proc_stats(struct seq_file *m, struct binder_proc *proc) { struct binder_work *w; struct rb_node *n; int count, strong, weak; seq_printf(m, "proc %d\n", proc->pid); count = 0; for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) count++; seq_printf(m, " threads: %d\n", count); seq_printf(m, " requested threads: %d+%d/%d\n" " ready threads %d\n" " free async space %zd\n", proc->requested_threads, proc->requested_threads_started, proc->max_threads, proc->ready_threads, proc->free_async_space); count = 0; for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) count++; seq_printf(m, " nodes: %d\n", count); count = 0; strong = 0; weak = 0; for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) { struct binder_ref *ref = rb_entry(n, struct binder_ref, rb_node_desc); count++; strong += ref->strong; weak += ref->weak; } seq_printf(m, " refs: %d s %d w %d\n", count, strong, weak); count = 0; for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n)) count++; seq_printf(m, " buffers: %d\n", count); count = 0; list_for_each_entry(w, &proc->todo, entry) { switch (w->type) { case BINDER_WORK_TRANSACTION: count++; break; default: break; } } seq_printf(m, " pending transactions: %d\n", count); print_binder_stats(m, " ", &proc->stats); } static int binder_state_show(struct seq_file *m, void *unused) { struct binder_proc *proc; struct hlist_node *pos; struct binder_node *node; int do_lock = !binder_debug_no_lock; if (do_lock) mutex_lock(&binder_lock); seq_puts(m, "binder state:\n"); if (!hlist_empty(&binder_dead_nodes)) seq_puts(m, "dead nodes:\n"); hlist_for_each_entry(node, pos, &binder_dead_nodes, dead_node) print_binder_node(m, node); hlist_for_each_entry(proc, pos, &binder_procs, proc_node) print_binder_proc(m, proc, 1); if (do_lock) mutex_unlock(&binder_lock); return 0; } static int binder_stats_show(struct seq_file *m, void *unused) { struct binder_proc *proc; struct hlist_node *pos; int do_lock = !binder_debug_no_lock; if (do_lock) mutex_lock(&binder_lock); seq_puts(m, "binder stats:\n"); print_binder_stats(m, "", &binder_stats); hlist_for_each_entry(proc, pos, &binder_procs, proc_node) print_binder_proc_stats(m, proc); if (do_lock) mutex_unlock(&binder_lock); return 0; } static int binder_transactions_show(struct seq_file *m, void *unused) { struct binder_proc *proc; struct hlist_node *pos; int do_lock = !binder_debug_no_lock; if (do_lock) mutex_lock(&binder_lock); seq_puts(m, "binder transactions:\n"); hlist_for_each_entry(proc, pos, &binder_procs, proc_node) print_binder_proc(m, proc, 0); if (do_lock) mutex_unlock(&binder_lock); return 0; } static int binder_proc_show(struct seq_file *m, void *unused) { struct binder_proc *proc = m->private; int do_lock = !binder_debug_no_lock; if (do_lock) mutex_lock(&binder_lock); seq_puts(m, "binder proc state:\n"); print_binder_proc(m, proc, 1); if (do_lock) mutex_unlock(&binder_lock); return 0; } static void print_binder_transaction_log_entry(struct seq_file *m, struct binder_transaction_log_entry *e) { seq_printf(m, "%d: %s from %d:%d to %d:%d node %d handle %d size %d:%d\n", e->debug_id, (e->call_type == 2) ? "reply" : ((e->call_type == 1) ? "async" : "call "), e->from_proc, e->from_thread, e->to_proc, e->to_thread, e->to_node, e->target_handle, e->data_size, e->offsets_size); } static int binder_transaction_log_show(struct seq_file *m, void *unused) { struct binder_transaction_log *log = m->private; int i; if (log->full) { for (i = log->next; i < ARRAY_SIZE(log->entry); i++) print_binder_transaction_log_entry(m, &log->entry[i]); } for (i = 0; i < log->next; i++) print_binder_transaction_log_entry(m, &log->entry[i]); return 0; } static const struct file_operations binder_fops = { .owner = THIS_MODULE, .poll = binder_poll, .unlocked_ioctl = binder_ioctl, .mmap = binder_mmap, .open = binder_open, .flush = binder_flush, .release = binder_release, }; static struct miscdevice binder_miscdev = { .minor = MISC_DYNAMIC_MINOR, .name = "binder", .fops = &binder_fops }; BINDER_DEBUG_ENTRY(state); BINDER_DEBUG_ENTRY(stats); BINDER_DEBUG_ENTRY(transactions); BINDER_DEBUG_ENTRY(transaction_log); static int __init binder_init(void) { int ret; binder_deferred_workqueue = create_singlethread_workqueue("binder"); if (!binder_deferred_workqueue) return -ENOMEM; binder_debugfs_dir_entry_root = debugfs_create_dir("binder", NULL); if (binder_debugfs_dir_entry_root) binder_debugfs_dir_entry_proc = debugfs_create_dir("proc", binder_debugfs_dir_entry_root); ret = misc_register(&binder_miscdev); if (binder_debugfs_dir_entry_root) { debugfs_create_file("state", S_IRUGO, binder_debugfs_dir_entry_root, NULL, &binder_state_fops); debugfs_create_file("stats", S_IRUGO, binder_debugfs_dir_entry_root, NULL, &binder_stats_fops); debugfs_create_file("transactions", S_IRUGO, binder_debugfs_dir_entry_root, NULL, &binder_transactions_fops); debugfs_create_file("transaction_log", S_IRUGO, binder_debugfs_dir_entry_root, &binder_transaction_log, &binder_transaction_log_fops); debugfs_create_file("failed_transaction_log", S_IRUGO, binder_debugfs_dir_entry_root, &binder_transaction_log_failed, &binder_transaction_log_fops); } return ret; } device_initcall(binder_init); MODULE_LICENSE("GPL v2");
package org.thoughtcrime.securesms.service; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.thoughtcrime.redphone.signaling.RedPhoneAccountAttributes; import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager; import org.thoughtcrime.redphone.signaling.RedPhoneTrustStore; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; import org.thoughtcrime.securesms.crypto.PreKeyUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.jobs.GcmRefreshJob; import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.util.DirectoryHelper; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.IdentityKeyPair; import org.whispersystems.libaxolotl.state.PreKeyRecord; import org.whispersystems.libaxolotl.state.SignedPreKeyRecord; import org.whispersystems.libaxolotl.util.KeyHelper; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.ExpectationFailedException; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * The RegisterationService handles the process of PushService registration and verification. * If it receives an intent with a REGISTER_NUMBER_ACTION, it does the following through * an executor: * * 1) Generate secrets. * 2) Register the specified number and those secrets with the server. * 3) Wait for a challenge SMS. * 4) Verify the challenge with the server. * 5) Start the GCM registration process. * 6) Retrieve the current directory. * * The RegistrationService broadcasts its state throughout this process, and also makes its * state available through service binding. This enables a View to display progress. * * @author Moxie Marlinspike * */ public class RegistrationService extends Service { public static final String REGISTER_NUMBER_ACTION = "org.thoughtcrime.securesms.RegistrationService.REGISTER_NUMBER"; public static final String VOICE_REQUESTED_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REQUESTED"; public static final String VOICE_REGISTER_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REGISTER"; public static final String NOTIFICATION_TITLE = "org.thoughtcrime.securesms.NOTIFICATION_TITLE"; public static final String NOTIFICATION_TEXT = "org.thoughtcrime.securesms.NOTIFICATION_TEXT"; public static final String CHALLENGE_EVENT = "org.thoughtcrime.securesms.CHALLENGE_EVENT"; public static final String REGISTRATION_EVENT = "org.thoughtcrime.securesms.REGISTRATION_EVENT"; public static final String CHALLENGE_EXTRA = "CAAChallenge"; private static final long REGISTRATION_TIMEOUT_MILLIS = 120000; private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final Binder binder = new RegistrationServiceBinder(); private volatile RegistrationState registrationState = new RegistrationState(RegistrationState.STATE_IDLE); private volatile WeakReference<Handler> registrationStateHandler; private volatile ChallengeReceiver challengeReceiver; private String challenge; private long verificationStartTime; private boolean generatingPreKeys; @Override public int onStartCommand(final Intent intent, int flags, int startId) { if (intent != null) { executor.execute(new Runnable() { @Override public void run() { if (REGISTER_NUMBER_ACTION.equals(intent.getAction())) handleSmsRegistrationIntent(intent); else if (VOICE_REQUESTED_ACTION.equals(intent.getAction())) handleVoiceRequestedIntent(intent); else if (VOICE_REGISTER_ACTION.equals(intent.getAction())) handleVoiceRegistrationIntent(intent); } }); } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); executor.shutdown(); shutdown(); } @Override public IBinder onBind(Intent intent) { return binder; } public void shutdown() { shutdownChallengeListener(); markAsVerifying(false); registrationState = new RegistrationState(RegistrationState.STATE_IDLE); } public synchronized int getSecondsRemaining() { long millisPassed; if (verificationStartTime == 0) millisPassed = 0; else millisPassed = System.currentTimeMillis() - verificationStartTime; return Math.max((int)(REGISTRATION_TIMEOUT_MILLIS - millisPassed) / 1000, 0); } public RegistrationState getRegistrationState() { return registrationState; } private void initializeChallengeListener() { this.challenge = null; challengeReceiver = new ChallengeReceiver(); IntentFilter filter = new IntentFilter(CHALLENGE_EVENT); registerReceiver(challengeReceiver, filter); } private synchronized void shutdownChallengeListener() { if (challengeReceiver != null) { unregisterReceiver(challengeReceiver); challengeReceiver = null; } } private void handleVoiceRequestedIntent(Intent intent) { setState(new RegistrationState(RegistrationState.STATE_VOICE_REQUESTED, intent.getStringExtra("e164number"), intent.getStringExtra("password"))); } private void handleVoiceRegistrationIntent(Intent intent) { markAsVerifying(true); String number = intent.getStringExtra("e164number"); String password = intent.getStringExtra("password"); String signalingKey = intent.getStringExtra("signaling_key"); try { TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password); handleCommonRegistration(accountManager, number, password, signalingKey); markAsVerified(number, password, signalingKey); setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number)); broadcastComplete(true); } catch (UnsupportedOperationException uoe) { Log.w("RegistrationService", uoe); setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number)); broadcastComplete(false); } catch (IOException e) { Log.w("RegistrationService", e); setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number)); broadcastComplete(false); } } private void handleSmsRegistrationIntent(Intent intent) { markAsVerifying(true); String number = intent.getStringExtra("e164number"); int registrationId = TextSecurePreferences.getLocalRegistrationId(this); if (registrationId == 0) { registrationId = KeyHelper.generateRegistrationId(false); TextSecurePreferences.setLocalRegistrationId(this, registrationId); } try { String password = Util.getSecret(18); String signalingKey = Util.getSecret(52); initializeChallengeListener(); setState(new RegistrationState(RegistrationState.STATE_CONNECTING, number)); TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password); accountManager.requestSmsVerificationCode(); setState(new RegistrationState(RegistrationState.STATE_VERIFYING, number)); String challenge = waitForChallenge(); accountManager.verifyAccountWithCode(challenge, signalingKey, registrationId, true); handleCommonRegistration(accountManager, number, password, signalingKey); markAsVerified(number, password, signalingKey); setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number)); broadcastComplete(true); } catch (ExpectationFailedException efe) { Log.w("RegistrationService", efe); setState(new RegistrationState(RegistrationState.STATE_MULTI_REGISTERED, number)); broadcastComplete(false); } catch (UnsupportedOperationException uoe) { Log.w("RegistrationService", uoe); setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number)); broadcastComplete(false); } catch (AccountVerificationTimeoutException avte) { Log.w("RegistrationService", avte); setState(new RegistrationState(RegistrationState.STATE_TIMEOUT, number)); broadcastComplete(false); } catch (IOException e) { Log.w("RegistrationService", e); setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number)); broadcastComplete(false); } finally { shutdownChallengeListener(); } } private void handleCommonRegistration(TextSecureAccountManager accountManager, String number, String password, String signalingKey) throws IOException { setState(new RegistrationState(RegistrationState.STATE_GENERATING_KEYS, number)); Recipient self = RecipientFactory.getRecipientsFromString(this, number, false).getPrimaryRecipient(); IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(this); List<PreKeyRecord> records = PreKeyUtil.generatePreKeys(this); PreKeyRecord lastResort = PreKeyUtil.generateLastResortKey(this); SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(this, identityKey); accountManager.setPreKeys(identityKey.getPublicKey(),lastResort, signedPreKey, records); setState(new RegistrationState(RegistrationState.STATE_GCM_REGISTERING, number)); String gcmRegistrationId = GoogleCloudMessaging.getInstance(this).register(GcmRefreshJob.REGISTRATION_ID); accountManager.setGcmId(Optional.of(gcmRegistrationId)); TextSecurePreferences.setGcmRegistrationId(this, gcmRegistrationId); TextSecurePreferences.setWebsocketRegistered(this, true); DatabaseFactory.getIdentityDatabase(this).saveIdentity(self.getRecipientId(), identityKey.getPublicKey()); DirectoryHelper.refreshDirectory(this, accountManager, number); RedPhoneAccountManager redPhoneAccountManager = new RedPhoneAccountManager(BuildConfig.REDPHONE_MASTER_URL, new RedPhoneTrustStore(this), number, password); String verificationToken = accountManager.getAccountVerificationToken(); redPhoneAccountManager.createAccount(verificationToken, new RedPhoneAccountAttributes(signalingKey, gcmRegistrationId)); DirectoryRefreshListener.schedule(this); } private synchronized String waitForChallenge() throws AccountVerificationTimeoutException { this.verificationStartTime = System.currentTimeMillis(); if (this.challenge == null) { try { wait(REGISTRATION_TIMEOUT_MILLIS); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } if (this.challenge == null) throw new AccountVerificationTimeoutException(); return this.challenge; } private synchronized void challengeReceived(String challenge) { this.challenge = challenge; notifyAll(); } private void markAsVerifying(boolean verifying) { TextSecurePreferences.setVerifying(this, verifying); if (verifying) { TextSecurePreferences.setPushRegistered(this, false); } } private void markAsVerified(String number, String password, String signalingKey) { TextSecurePreferences.setVerifying(this, false); TextSecurePreferences.setPushRegistered(this, true); TextSecurePreferences.setLocalNumber(this, number); TextSecurePreferences.setPushServerPassword(this, password); TextSecurePreferences.setSignalingKey(this, signalingKey); TextSecurePreferences.setSignedPreKeyRegistered(this, true); TextSecurePreferences.setPromptedPushRegistration(this, true); } private void setState(RegistrationState state) { this.registrationState = state; Handler registrationStateHandler = this.registrationStateHandler.get(); if (registrationStateHandler != null) { registrationStateHandler.obtainMessage(state.state, state).sendToTarget(); } } private void broadcastComplete(boolean success) { Intent intent = new Intent(); intent.setAction(REGISTRATION_EVENT); if (success) { intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_complete)); intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_successfully_completed)); } else { intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_error)); intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_encountered_a_problem)); } this.sendOrderedBroadcast(intent, null); } public void setRegistrationStateHandler(Handler registrationStateHandler) { this.registrationStateHandler = new WeakReference<>(registrationStateHandler); } public class RegistrationServiceBinder extends Binder { public RegistrationService getService() { return RegistrationService.this; } } private class ChallengeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.w("RegistrationService", "Got a challenge broadcast..."); challengeReceived(intent.getStringExtra(CHALLENGE_EXTRA)); } } public static class RegistrationState { public static final int STATE_IDLE = 0; public static final int STATE_CONNECTING = 1; public static final int STATE_VERIFYING = 2; public static final int STATE_TIMER = 3; public static final int STATE_COMPLETE = 4; public static final int STATE_TIMEOUT = 5; public static final int STATE_NETWORK_ERROR = 6; public static final int STATE_GCM_UNSUPPORTED = 8; public static final int STATE_GCM_REGISTERING = 9; public static final int STATE_GCM_TIMEOUT = 10; public static final int STATE_VOICE_REQUESTED = 12; public static final int STATE_GENERATING_KEYS = 13; public static final int STATE_MULTI_REGISTERED = 14; public final int state; public final String number; public final String password; public RegistrationState(int state) { this(state, null); } public RegistrationState(int state, String number) { this(state, number, null); } public RegistrationState(int state, String number, String password) { this.state = state; this.number = number; this.password = password; } } }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Why my application fails to link with Boost.Log? What's the fuss about library namespaces?</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Boost.Log v2"> <link rel="up" href="../rationale.html" title="Rationale and FAQ"> <link rel="prev" href="why_crash_on_term.html" title="Why my application crashes on process termination when file sinks are used?"> <link rel="next" href="msvc_link_fails_lnk1123.html" title="Why MSVC 2010 fails to link the library with error LNK1123: failure during conversion to COFF: file invalid or corrupt?"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="why_crash_on_term.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../rationale.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="msvc_link_fails_lnk1123.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="log.rationale.namespace_mangling"></a><a class="link" href="namespace_mangling.html" title="Why my application fails to link with Boost.Log? What's the fuss about library namespaces?">Why my application fails to link with Boost.Log? What's the fuss about library namespaces?</a> </h3></div></div></div> <p> The library declares the <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">log</span></code> namespace which should be used in client code to access library components. However, internally the library uses another nested namespace for actual implementation. The namespace name is configuration and platform dependent, it can change between different releases of the library, so it should never be used in the user side code. This is done in order to make the library configuration synchronized with the application as much as possible and eliminate problems caused by configuration mismatch. </p> <p> Most of the time users won't even notice the existence of this internal namespace, but it often appears in compiler and linker errors and in some cases it is useful to know how to decode its name. Currently, the namespace name is composed from the following elements: </p> <pre class="programlisting">&lt;version&gt;&lt;linkage&gt;_&lt;threading&gt;_&lt;system&gt;</pre> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> The <code class="computeroutput"><span class="special">&lt;</span><span class="identifier">version</span><span class="special">&gt;</span></code> component describes the library major version. It is currently <code class="computeroutput"><span class="identifier">v2</span></code>. </li> <li class="listitem"> The <code class="computeroutput"><span class="special">&lt;</span><span class="identifier">linkage</span><span class="special">&gt;</span></code> component tells whether the library is linked statically or dynamically. It is <code class="computeroutput"><span class="identifier">s</span></code> if the library is linked statically and empty otherwise. </li> <li class="listitem"> The <code class="computeroutput"><span class="special">&lt;</span><span class="identifier">threading</span><span class="special">&gt;</span></code> component is <code class="computeroutput"><span class="identifier">st</span></code> for single-threaded builds and <code class="computeroutput"><span class="identifier">mt</span></code> for multi-threaded ones. </li> <li class="listitem"> The <code class="computeroutput"><span class="special">&lt;</span><span class="identifier">system</span><span class="special">&gt;</span></code> component describes the underlying OS API used by the library. Currently, it is only specified for multi-threaded builds. Depending on the target platform and configuration, it can be <code class="computeroutput"><span class="identifier">posix</span></code>, <code class="computeroutput"><span class="identifier">nt5</span></code> or <code class="computeroutput"><span class="identifier">nt6</span></code>. </li> </ul></div> <p> As a couple quick examples, <code class="computeroutput"><span class="identifier">v2s_st</span></code> corresponds to v2 static single-threaded build of the library and <code class="computeroutput"><span class="identifier">v2_mt_posix</span></code> - to v2 dynamic multi-threaded build for POSIX system API. </p> <p> Namespace mangling may lead to linking errors if the application is misconfigured. One common mistake is to build dynamic version of the library and not define <code class="computeroutput"><span class="identifier">BOOST_LOG_DYN_LINK</span></code> or <code class="computeroutput"><span class="identifier">BOOST_ALL_DYN_LINK</span></code> when building the application, so that the library assumes static linking by default. Whenever such linking errors appear, one can decode the namespace name in the missing symbols and the exported symbols of Boost.Log library and adjust library or application <a class="link" href="../installation/config.html" title="Configuring and building the library">configuration</a> accordingly. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2007-2015 Andrey Semashev<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>). </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="why_crash_on_term.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../rationale.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="msvc_link_fails_lnk1123.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
import getCompletions from "./get-completions" // Add an autosuggest completer export const addAutosuggestionCompleters = (ori, system) => (context) => { return ori(context).concat([{ getCompletions(...args) { // Add `context`, then `system` as the last args return getCompletions(...args, context, system) } }]) }
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2011 University of California, Los Angeles * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> */ #ifndef LFU_POLICY_H_ #define LFU_POLICY_H_ #include <boost/intrusive/options.hpp> #include <boost/intrusive/set.hpp> namespace ns3 { namespace ndn { namespace ndnSIM { /** * @brief Traits for LFU replacement policy */ struct lfu_policy_traits { /// @brief Name that can be used to identify the policy (for NS-3 object model and logging) static std::string GetName () { return "Lfu"; } struct policy_hook_type : public boost::intrusive::set_member_hook<> { double frequency; }; template<class Container> struct container_hook { typedef boost::intrusive::member_hook< Container, policy_hook_type, &Container::policy_hook_ > type; }; template<class Base, class Container, class Hook> struct policy { static double& get_order (typename Container::iterator item) { return static_cast<policy_hook_type*> (policy_container::value_traits::to_node_ptr(*item))->frequency; } static const double& get_order (typename Container::const_iterator item) { return static_cast<const policy_hook_type*> (policy_container::value_traits::to_node_ptr(*item))->frequency; } template<class Key> struct MemberHookLess { bool operator () (const Key &a, const Key &b) const { return get_order (&a) < get_order (&b); } }; typedef boost::intrusive::multiset< Container, boost::intrusive::compare< MemberHookLess< Container > >, Hook > policy_container; // could be just typedef class type : public policy_container { public: typedef policy policy_base; // to get access to get_order methods from outside typedef Container parent_trie; type (Base &base) : base_ (base) , max_size_ (100) { } inline void update (typename parent_trie::iterator item) { policy_container::erase (policy_container::s_iterator_to (*item)); get_order (item) += 1; policy_container::insert (*item); } inline bool insert (typename parent_trie::iterator item) { get_order (item) = 0; if (max_size_ != 0 && policy_container::size () >= max_size_) { // this erases the "least frequently used item" from cache base_.erase (&(*policy_container::begin ())); } policy_container::insert (*item); return true; } inline void lookup (typename parent_trie::iterator item) { policy_container::erase (policy_container::s_iterator_to (*item)); get_order (item) += 1; policy_container::insert (*item); } inline void erase (typename parent_trie::iterator item) { policy_container::erase (policy_container::s_iterator_to (*item)); } inline void clear () { policy_container::clear (); } inline void set_max_size (size_t max_size) { max_size_ = max_size; } inline size_t get_max_size () const { return max_size_; } private: type () : base_(*((Base*)0)) { }; private: Base &base_; size_t max_size_; }; }; }; } // ndnSIM } // ndn } // ns3 #endif // LFU_POLICY_H
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Kevin Hughes */ #ifndef FFSEP_H_ #define FFSEP_H_ #include <shogun/lib/config.h> #ifdef HAVE_EIGEN3 #include <shogun/lib/SGNDArray.h> #include <shogun/features/Features.h> #include <shogun/converter/ica/ICAConverter.h> namespace shogun { class CFeatures; /** @brief class FFSep * * Implements the FFSep algorithm for Independent * Component Analysis (ICA) and Blind Source * Separation (BSS). * * Ziehe, A., Laskov, P., Nolte, G., & Müller, K. R. (2004). * A fast algorithm for joint diagonalization with non-orthogonal transformations * and its application to blind source separation. * The Journal of Machine Learning Research, 5, 777-800. * */ class CFFSep: public CICAConverter { public: /** constructor */ CFFSep(); /** destructor */ virtual ~CFFSep(); /** apply to features * @param features features to embed */ virtual CFeatures* apply(CFeatures* features); /** getter for tau parameter * @return tau vector */ SGVector<float64_t> get_tau() const; /** setter for tau parameter * @param tau vector */ void set_tau(SGVector<float64_t> tau); /** getter for time sep cov matrices * @return cov matrices */ SGNDArray<float64_t> get_covs() const; /** @return object name */ virtual const char* get_name() const { return "FFSep"; }; protected: /** init */ void init(); private: /** tau vector */ SGVector<float64_t> m_tau; /** cov matrices */ SGNDArray<float64_t> m_covs; }; } #endif // HAVE_EIGEN3 #endif // FFSEP
<?php /** * @package Mautic * @copyright 2014 Mautic Contributors. All rights reserved. * @author Mautic * @link http://mautic.org * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ echo $view->render( 'MauticFormBundle:Field:text.html.php', array( 'field' => $field, 'inForm' => (isset($inForm)) ? $inForm : false, 'type' => 'email', 'id' => $id, 'deleted' => (!empty($deleted)) ? true : false, 'formId' => (isset($formId)) ? $formId : 0, 'formName' => (isset($formName)) ? $formName : '' ) );
/* Copyright (C) 2005-2016 Free Software Foundation, Inc. Contributed by Richard Henderson <rth@redhat.com>. This file is part of the GNU Offloading and Multi Processing Library (libgomp). Libgomp is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* This is the default PTHREADS implementation of the public OpenMP locking primitives. Because OpenMP uses different entry points for normal and recursive locks, and pthreads uses only one entry point, a system may be able to do better and streamline the locking as well as reduce the size of the types exported. */ /* We need UNIX98/XPG5 extensions to get recursive locks. Request XPG6 since Solaris requires this for C99 and later. */ #define _XOPEN_SOURCE 600 #include "libgomp.h" #ifdef HAVE_BROKEN_POSIX_SEMAPHORES void gomp_init_lock_30 (omp_lock_t *lock) { pthread_mutex_init (lock, NULL); } void gomp_destroy_lock_30 (omp_lock_t *lock) { pthread_mutex_destroy (lock); } void gomp_set_lock_30 (omp_lock_t *lock) { pthread_mutex_lock (lock); } void gomp_unset_lock_30 (omp_lock_t *lock) { pthread_mutex_unlock (lock); } int gomp_test_lock_30 (omp_lock_t *lock) { return pthread_mutex_trylock (lock) == 0; } void gomp_init_nest_lock_30 (omp_nest_lock_t *lock) { pthread_mutex_init (&lock->lock, NULL); lock->count = 0; lock->owner = NULL; } void gomp_destroy_nest_lock_30 (omp_nest_lock_t *lock) { pthread_mutex_destroy (&lock->lock); } void gomp_set_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { pthread_mutex_lock (&lock->lock); lock->owner = me; } lock->count++; } void gomp_unset_nest_lock_30 (omp_nest_lock_t *lock) { if (--lock->count == 0) { lock->owner = NULL; pthread_mutex_unlock (&lock->lock); } } int gomp_test_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { if (pthread_mutex_trylock (&lock->lock) != 0) return 0; lock->owner = me; } return ++lock->count; } #else void gomp_init_lock_30 (omp_lock_t *lock) { sem_init (lock, 0, 1); } void gomp_destroy_lock_30 (omp_lock_t *lock) { sem_destroy (lock); } void gomp_set_lock_30 (omp_lock_t *lock) { while (sem_wait (lock) != 0) ; } void gomp_unset_lock_30 (omp_lock_t *lock) { sem_post (lock); } int gomp_test_lock_30 (omp_lock_t *lock) { return sem_trywait (lock) == 0; } void gomp_init_nest_lock_30 (omp_nest_lock_t *lock) { sem_init (&lock->lock, 0, 1); lock->count = 0; lock->owner = NULL; } void gomp_destroy_nest_lock_30 (omp_nest_lock_t *lock) { sem_destroy (&lock->lock); } void gomp_set_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { while (sem_wait (&lock->lock) != 0) ; lock->owner = me; } lock->count++; } void gomp_unset_nest_lock_30 (omp_nest_lock_t *lock) { if (--lock->count == 0) { lock->owner = NULL; sem_post (&lock->lock); } } int gomp_test_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { if (sem_trywait (&lock->lock) != 0) return 0; lock->owner = me; } return ++lock->count; } #endif #ifdef LIBGOMP_GNU_SYMBOL_VERSIONING void gomp_init_lock_25 (omp_lock_25_t *lock) { pthread_mutex_init (lock, NULL); } void gomp_destroy_lock_25 (omp_lock_25_t *lock) { pthread_mutex_destroy (lock); } void gomp_set_lock_25 (omp_lock_25_t *lock) { pthread_mutex_lock (lock); } void gomp_unset_lock_25 (omp_lock_25_t *lock) { pthread_mutex_unlock (lock); } int gomp_test_lock_25 (omp_lock_25_t *lock) { return pthread_mutex_trylock (lock) == 0; } void gomp_init_nest_lock_25 (omp_nest_lock_25_t *lock) { pthread_mutexattr_t attr; pthread_mutexattr_init (&attr); pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init (&lock->lock, &attr); lock->count = 0; pthread_mutexattr_destroy (&attr); } void gomp_destroy_nest_lock_25 (omp_nest_lock_25_t *lock) { pthread_mutex_destroy (&lock->lock); } void gomp_set_nest_lock_25 (omp_nest_lock_25_t *lock) { pthread_mutex_lock (&lock->lock); lock->count++; } void gomp_unset_nest_lock_25 (omp_nest_lock_25_t *lock) { lock->count--; pthread_mutex_unlock (&lock->lock); } int gomp_test_nest_lock_25 (omp_nest_lock_25_t *lock) { if (pthread_mutex_trylock (&lock->lock) == 0) return ++lock->count; return 0; } omp_lock_symver (omp_init_lock) omp_lock_symver (omp_destroy_lock) omp_lock_symver (omp_set_lock) omp_lock_symver (omp_unset_lock) omp_lock_symver (omp_test_lock) omp_lock_symver (omp_init_nest_lock) omp_lock_symver (omp_destroy_nest_lock) omp_lock_symver (omp_set_nest_lock) omp_lock_symver (omp_unset_nest_lock) omp_lock_symver (omp_test_nest_lock) #else ialias (omp_init_lock) ialias (omp_init_nest_lock) ialias (omp_destroy_lock) ialias (omp_destroy_nest_lock) ialias (omp_set_lock) ialias (omp_set_nest_lock) ialias (omp_unset_lock) ialias (omp_unset_nest_lock) ialias (omp_test_lock) ialias (omp_test_nest_lock) #endif
----------------------------------- -- -- Zone: RoMaeve (122) -- ----------------------------------- package.loaded["scripts/zones/RoMaeve/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/RoMaeve/TextIDs"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17277227,17277228}; SetFieldManual(manuals); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-0.008,-33.595,123.478,62); end if (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0003; -- doll telling "you're in the right area" end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onGameDay ----------------------------------- function onGameDay() -- Moongates local Moongate_Offset = 17277195; -- _3e0 in npc_list local direction = VanadielMoonDirection(); local phase = VanadielMoonPhase(); if (((direction == 2 and phase >= 90) or (direction == 1 and phase >= 95)) and GetNPCByID(Moongate_Offset):getWeather() == 0) then GetNPCByID(Moongate_Offset):openDoor(432); GetNPCByID(Moongate_Offset+1):openDoor(432); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using referrer-policy/generic/template/test.release.html.template. --> <html> <head> <title>Referrer-Policy: Referrer Policy is set to 'no-referrer-when-downgrade'</title> <meta name="description" content="Check that non a priori insecure subresource gets the full Referrer URL. A priori insecure subresource gets no referrer information."> <link rel="author" title="Kristijan Burnik" href="burnik@chromium.org"> <link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-no-referrer-when-downgrade"> <meta name="assert" content="The referrer URL is stripped-referrer when a document served over http requires an https sub-resource via iframe-tag using the attr-referrer delivery method with no-redirect and when the target request is same-origin."> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <!-- TODO(kristijanburnik): Minify and merge both: --> <script src="/_mozilla/mozilla/referrer-policy/generic/common.js"></script> <script src="/_mozilla/mozilla/referrer-policy/generic/referrer-policy-test-case.js?pipe=sub"></script> </head> <body> <script> ReferrerPolicyTestCase( { "referrer_policy": "no-referrer-when-downgrade", "delivery_method": "attr-referrer", "redirection": "no-redirect", "origin": "same-origin", "source_protocol": "http", "target_protocol": "https", "subresource": "iframe-tag", "subresource_path": "/referrer-policy/generic/subresource/document.py", "referrer_url": "stripped-referrer" }, document.querySelector("meta[name=assert]").content, new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
package loader import ( "errors" "fmt" "go/ast" "go/parser" "go/scanner" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/go/packages" ) // Graph resolves patterns and returns packages with all the // information required to later load type information, and optionally // syntax trees. // // The provided config can set any setting with the exception of Mode. func Graph(cfg packages.Config, patterns ...string) ([]*packages.Package, error) { cfg.Mode = packages.NeedName | packages.NeedImports | packages.NeedDeps | packages.NeedExportsFile | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedTypesSizes pkgs, err := packages.Load(&cfg, patterns...) if err != nil { return nil, err } fset := token.NewFileSet() packages.Visit(pkgs, nil, func(pkg *packages.Package) { pkg.Fset = fset }) n := 0 for _, pkg := range pkgs { if len(pkg.CompiledGoFiles) == 0 && len(pkg.Errors) == 0 && pkg.PkgPath != "unsafe" { // If a package consists only of test files, then // go/packages incorrectly(?) returns an empty package for // the non-test variant. Get rid of those packages. See // #646. // // Do not, however, skip packages that have errors. Those, // too, may have no files, but we want to print the // errors. continue } pkgs[n] = pkg n++ } return pkgs[:n], nil } // LoadFromExport loads a package from export data. All of its // dependencies must have been loaded already. func LoadFromExport(pkg *packages.Package) error { pkg.IllTyped = true for path, pkg := range pkg.Imports { if pkg.Types == nil { return fmt.Errorf("dependency %q hasn't been loaded yet", path) } } if pkg.ExportFile == "" { return fmt.Errorf("no export data for %q", pkg.ID) } f, err := os.Open(pkg.ExportFile) if err != nil { return err } defer f.Close() r, err := gcexportdata.NewReader(f) if err != nil { return err } view := make(map[string]*types.Package) // view seen by gcexportdata seen := make(map[*packages.Package]bool) // all visited packages var visit func(pkgs map[string]*packages.Package) visit = func(pkgs map[string]*packages.Package) { for _, pkg := range pkgs { if !seen[pkg] { seen[pkg] = true view[pkg.PkgPath] = pkg.Types visit(pkg.Imports) } } } visit(pkg.Imports) tpkg, err := gcexportdata.Read(r, pkg.Fset, view, pkg.PkgPath) if err != nil { return err } pkg.Types = tpkg pkg.IllTyped = false return nil } // LoadFromSource loads a package from source. All of its dependencies // must have been loaded already. func LoadFromSource(pkg *packages.Package) error { pkg.IllTyped = true pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name) // OPT(dh): many packages have few files, much fewer than there // are CPU cores. Additionally, parsing each individual file is // very fast. A naive parallel implementation of this loop won't // be faster, and tends to be slower due to extra scheduling, // bookkeeping and potentially false sharing of cache lines. pkg.Syntax = make([]*ast.File, len(pkg.CompiledGoFiles)) for i, file := range pkg.CompiledGoFiles { f, err := parser.ParseFile(pkg.Fset, file, nil, parser.ParseComments) if err != nil { pkg.Errors = append(pkg.Errors, convertError(err)...) return err } pkg.Syntax[i] = f } pkg.TypesInfo = &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } importer := func(path string) (*types.Package, error) { if path == "unsafe" { return types.Unsafe, nil } if path == "C" { // go/packages doesn't tell us that cgo preprocessing // failed. When we subsequently try to parse the package, // we'll encounter the raw C import. return nil, errors.New("cgo preprocessing failed") } imp := pkg.Imports[path] if imp == nil { return nil, nil } if len(imp.Errors) > 0 { return nil, imp.Errors[0] } return imp.Types, nil } tc := &types.Config{ Importer: importerFunc(importer), Error: func(err error) { pkg.Errors = append(pkg.Errors, convertError(err)...) }, } err := types.NewChecker(tc, pkg.Fset, pkg.Types, pkg.TypesInfo).Files(pkg.Syntax) if err != nil { return err } pkg.IllTyped = false return nil } func convertError(err error) []packages.Error { var errs []packages.Error // taken from go/packages switch err := err.(type) { case packages.Error: // from driver errs = append(errs, err) case *os.PathError: // from parser errs = append(errs, packages.Error{ Pos: err.Path + ":1", Msg: err.Err.Error(), Kind: packages.ParseError, }) case scanner.ErrorList: // from parser for _, err := range err { errs = append(errs, packages.Error{ Pos: err.Pos.String(), Msg: err.Msg, Kind: packages.ParseError, }) } case types.Error: // from type checker errs = append(errs, packages.Error{ Pos: err.Fset.Position(err.Pos).String(), Msg: err.Msg, Kind: packages.TypeError, }) default: // unexpected impoverished error from parser? errs = append(errs, packages.Error{ Pos: "-", Msg: err.Error(), Kind: packages.UnknownError, }) // If you see this error message, please file a bug. log.Printf("internal error: error %q (%T) without position", err, err) } return errs } type importerFunc func(path string) (*types.Package, error) func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * Copyright (C) 2008 WEmu Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" class ProtectingtheShipment : public QuestScript { public: void OnQuestStart(Player* mTarget, QuestLogEntry* qLogEntry) { float SSX = mTarget->GetPositionX(); float SSY = mTarget->GetPositionY(); float SSZ = mTarget->GetPositionZ(); Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 1379); if(creat == NULL) return; creat->m_escorter = mTarget; creat->GetAIInterface()->setMoveType(11); creat->GetAIInterface()->StopMovement(3000); creat->GetAIInterface()->SetAllowedToEnterCombat(false); creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Okay let's do!"); creat->SetUInt32Value(UNIT_NPC_FLAGS, 0); sEAS.CreateCustomWaypointMap(creat); sEAS.WaypointCreate(creat, -5753.780762f, -3433.290039f, 301.628387f, 4.834769f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5744.062500f, -3476.653564f, 302.269287f, 5.580896f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5674.703125f, -3543.583984f, 303.273682f, 4.775867f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5670.187500f, -3595.618164f, 311.888153f, 4.791576f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5664.515625f, -3687.601563f, 317.954590f, 4.131842f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5705.745117f, -3755.254150f, 321.452118f, 4.457779f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5711.766113f, -3778.145752f, 322.827942f, 4.473486f, 0, 256, 1417); sEAS.EnableWaypoints(creat); } }; class Miran : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(Miran); Miran(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnReachWP(uint32 iWaypointId, bool bForwards) { if(iWaypointId == 7) { _unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Thanks, I'm outta here!"); _unit->Despawn(5000, 1000); sEAS.DeleteWaypoints(_unit); if(_unit->m_escorter == NULL) return; Player* plr = _unit->m_escorter; _unit->m_escorter = NULL; plr->GetQuestLogForEntry(309)->SendQuestComplete(); } } }; void SetupLochModan(ScriptMgr* mgr) { mgr->register_creature_script(1379, &Miran::Create); /*mgr->register_quest_script(309, new ProtectingtheShipment());*/ }
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" enum ENCOUNTER_CREATURES { CN_SARTHARION = 28860, CN_FLAME_TSUNAMI = 30616, CN_LAVA_BLAZE = 30643, CN_CYCLON = 30648, CN_DRAKE_TENEBRON = 30452, CN_DRAKE_VESPERON = 30449, CN_DRAKE_SHADRON = 30451, }; enum SARTHARION_DATA { DRAKE_TENEBRON, DRAKE_VESPERON, DRAKE_SHADRON, BOSS_SARTHARION, OS_DATA_END = 4 }; #define SARTHARION_FLAME_BREATH HeroicInt( 56908, 58956 ) #define SARTHARION_TAIL_LASH HeroicInt( 56910, 58957 ) enum ENCOUNTER_SPELLS { // Sartharion SARTHARION_CLEAVE = 56909, SARTHARION_ENRAGE = 61632, SARTHARION_AURA = 61254, // Tsunami spells TSUNAMI = 57492, TSUNAMI_VISUAL = 57494, // Cyclon spells CYCLON_AURA = 57562, CYCLON_SPELL = 57560, // TODO: add drake spells SHADRON_AURA = 58105, TENEBRON_AURA = 61248, VESPERON_AURA = 61251, }; static Location TSUNAMI_SPAWN[] = { // Right { 3283.215820f, 511.234100f, 59.288776f, 3.148659f }, { 3286.661133f, 533.317261f, 59.366989f, 3.156505f }, { 3283.311035f, 556.839611f, 59.397129f, 3.105450f }, // Left { 3211.564697f, 505.982727f, 59.556610f, 0.000000f }, { 3214.280029f, 531.491089f, 59.168331f, 0.000000f }, { 3211.609131f, 560.359375f, 59.420803f, 0.000000f }, }; static Location TSUNAMI_MOVE[] = { // Left if right { 3211.564697f, 505.982727f, 59.556610f, 3.148659f }, { 3214.280029f, 531.491089f, 59.168331f, 3.156505f }, { 3211.609131f, 560.359375f, 59.420803f, 3.105450f }, // Right 1 if left 1 { 3283.215820f, 511.234100f, 59.288776f, 3.148659f }, { 3286.661133f, 533.317261f, 59.366989f, 3.156505f }, { 3283.311035f, 556.839611f, 59.397129f, 3.105450f } }; #define MAP_OS 615 class ObsidianSanctumScript : public MoonInstanceScript { public: uint32 m_creatureGuid[OS_DATA_END]; MOONSCRIPT_INSTANCE_FACTORY_FUNCTION(ObsidianSanctumScript, MoonInstanceScript); ObsidianSanctumScript(MapMgr* pMapMgr) : MoonInstanceScript(pMapMgr) { memset(m_creatureGuid, 0, sizeof(m_creatureGuid)); }; void OnCreaturePushToWorld(Creature* pCreature) { switch(pCreature->GetEntry()) { case CN_DRAKE_TENEBRON: m_creatureGuid[DRAKE_TENEBRON] = pCreature->GetLowGUID(); break; case CN_DRAKE_VESPERON: m_creatureGuid[DRAKE_VESPERON] = pCreature->GetLowGUID(); break; case CN_DRAKE_SHADRON: m_creatureGuid[DRAKE_SHADRON] = pCreature->GetLowGUID(); break; case CN_SARTHARION: m_creatureGuid[BOSS_SARTHARION] = pCreature->GetLowGUID(); break; default: break; }; }; void OnCreatureDeath(Creature* pVictim, Unit* pKiller) { switch(pVictim->GetEntry()) { case CN_SARTHARION: m_creatureGuid[BOSS_SARTHARION] = 0; break; default: break; }; }; void DoDrakeAura(uint8 pData) { uint32 pSpellEntry = 0; switch(pData) { case DRAKE_TENEBRON: pSpellEntry = TENEBRON_AURA; break; case DRAKE_SHADRON: pSpellEntry = SHADRON_AURA; break; case DRAKE_VESPERON: pSpellEntry = VESPERON_AURA; break; default: break; }; Creature* pSartharion = GetCreature(BOSS_SARTHARION); if(pSartharion == NULL) return; pSartharion->CastSpell(pSartharion, pSpellEntry, true); pSartharion->RemoveAura(pSpellEntry); // unproper hackfix }; Creature* GetCreature(uint8 pData) { if(pData >= OS_DATA_END) // impossible tho return NULL; return GetCreatureByGuid(m_creatureGuid[pData]); }; }; void SpellFunc_FlameTsunami(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { if(pCreatureAI != NULL) { pCreatureAI->GetUnit()->SendChatMessage(CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, "The lava surrounding Sartharion churns!"); uint32 RandomSpeach = rand() % 4; switch(RandomSpeach) { case 0: pCreatureAI->Emote("Such flammable little insects....", Text_Yell, 14100); break; case 1: pCreatureAI->Emote("Your charred bones will litter the floor!", Text_Yell, 14101); break; case 2: pCreatureAI->Emote("How much heat can you take?", Text_Yell, 14102); break; case 3: pCreatureAI->Emote("All will be reduced to ash!", Text_Yell, 14103); break; }; uint32 RndSide = rand() % 2; Creature* Tsunami = NULL; for(int i = 0; i < 3; ++i) { switch(RndSide) { case 0: Tsunami = pCreatureAI->GetUnit()->GetMapMgr()->GetInterface()->SpawnCreature(CN_FLAME_TSUNAMI, TSUNAMI_SPAWN[i].x, TSUNAMI_SPAWN[i].y, TSUNAMI_SPAWN[i].z, TSUNAMI_SPAWN[i].o, true, true, 0, 0); if(Tsunami != NULL) Tsunami->GetAIInterface()->MoveTo(TSUNAMI_MOVE[i].x, TSUNAMI_MOVE[i].y, TSUNAMI_MOVE[i].z, TSUNAMI_MOVE[i].o); break; case 1: Tsunami = pCreatureAI->GetUnit()->GetMapMgr()->GetInterface()->SpawnCreature(CN_FLAME_TSUNAMI, TSUNAMI_SPAWN[i + 3].x, TSUNAMI_SPAWN[i + 3].y, TSUNAMI_SPAWN[i + 3].z, TSUNAMI_SPAWN[i + 3].o, true, true, 0, 0); if(Tsunami != NULL) Tsunami->GetAIInterface()->MoveTo(TSUNAMI_MOVE[i + 3].x, TSUNAMI_MOVE[i + 3].y, TSUNAMI_MOVE[i + 3].z, TSUNAMI_MOVE[i + 3].o); }; Tsunami = NULL; }; }; }; void SpellFunc_LavaSpawn(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { if(pCreatureAI == NULL) return; for(int i = 0; i < 2; ++i) { uint32 j = rand() % 6; pCreatureAI->SpawnCreature(CN_LAVA_BLAZE, pTarget->GetPositionX() + j, pTarget->GetPositionY() + j, pTarget->GetPositionZ(), pTarget->GetOrientation(), true); }; }; class SartharionAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(SartharionAI, MoonScriptBossAI); SartharionAI(Creature* pCreature) : MoonScriptBossAI(pCreature) { mInstance = dynamic_cast<ObsidianSanctumScript*>(GetInstanceScript()); AddSpell(SARTHARION_CLEAVE, Target_Current, 24, 0, 8); SpellDesc* mFlame = AddSpell(SARTHARION_FLAME_BREATH, Target_Self, 18, 2, 16); mFlame->AddEmote("Burn, you miserable wretches!", Text_Yell, 14098); AddSpell(SARTHARION_TAIL_LASH, Target_Self, 40, 0, 12); mFlameTsunami = AddSpellFunc(&SpellFunc_FlameTsunami, Target_Self, 99, 0, 25); mSummonLava = AddSpellFunc(&SpellFunc_LavaSpawn, Target_RandomUnitNotCurrent, 25, 0, 8); AddEmote(Event_OnTargetDied, "You will make a fine meal for the hatchlings.", Text_Yell, 14094); AddEmote(Event_OnTargetDied, "You are at a grave disadvantage!", Text_Yell, 14096); AddEmote(Event_OnTargetDied, "This is why we call you lesser beings.", Text_Yell, 14097); AddEmote(Event_OnCombatStart, "It is my charge to watch over these eggs. I will see you burn before any harm comes to them!", Text_Yell, 14093); for(int i = 0; i < OS_DATA_END - 1; i++) { m_bDrakes[i] = false; m_cDrakes[i] = NULL; } mDrakeTimer = 0; m_bEnraged = false; m_iDrakeCount = 0; }; void OnCombatStart(Unit* pTarget) { m_bEnraged = false; mFlameTsunami->TriggerCooldown(); CheckDrakes(); if(m_iDrakeCount >= 1) //HardMode! { mDrakeTimer = AddTimer(30000); ApplyAura(SARTHARION_AURA); RemoveAuraOnPlayers(SARTHARION_AURA); // unproper hackfix Regenerate();// Lets heal him as aura increase his hp for 25% }; ParentClass::OnCombatStart(pTarget); }; void AIUpdate() { if(m_iDrakeCount >= 1) { if(IsTimerFinished(mDrakeTimer)) { if(m_bDrakes[DRAKE_TENEBRON] == true) CallTenebron(); else if(m_bDrakes[DRAKE_SHADRON] == true) CallShadron(); else if(m_bDrakes[DRAKE_VESPERON] == true) CallVesperon(); ResetTimer(mDrakeTimer, 45000); }; }; if(GetHealthPercent() <= 10 && m_bEnraged == false) // enrage phase { for(uint32 i = 0; i < 3; ++i) CastSpellNowNoScheduling(mSummonLava); m_bEnraged = true; }; ParentClass::AIUpdate(); }; void CheckDrakes() { if(mInstance == NULL) return; m_iDrakeCount = 0; for(uint8 i = 0; i < (OS_DATA_END - 1); ++i) { m_cDrakes[i] = mInstance->GetCreature(i); if(m_cDrakes[i] != NULL && m_cDrakes[i]->isAlive()) { m_bDrakes[i] = true; m_iDrakeCount++; mInstance->DoDrakeAura(i); }; }; }; void CallTenebron() { if(m_cDrakes[DRAKE_TENEBRON] != NULL && m_cDrakes[DRAKE_TENEBRON]->isAlive()) { Emote("Tenebron! The eggs are yours to protect as well!", Text_Yell, 14106); m_cDrakes[DRAKE_TENEBRON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_TENEBRON] = false; }; void CallShadron() { if(m_cDrakes[DRAKE_SHADRON] != NULL && m_cDrakes[DRAKE_SHADRON]->isAlive()) { Emote("Shadron! The clutch is in danger! Assist me!", Text_Yell, 14104); m_cDrakes[DRAKE_SHADRON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_SHADRON] = false; }; void CallVesperon() { if(m_cDrakes[DRAKE_VESPERON] != NULL && m_cDrakes[DRAKE_VESPERON]->isAlive()) { Emote("Vesperon! Come to me, all is at risk!", Text_Yell, 14105); m_cDrakes[DRAKE_VESPERON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_VESPERON] = false; }; void OnDied(Unit* pKiller) { Emote("Such is the price... of failure...", Text_Yell, 14107); RemoveAIUpdateEvent(); ParentClass::OnDied(pKiller); }; private: bool m_bDrakes[OS_DATA_END - 1]; int32 mDrakeTimer; bool m_bEnraged; int m_iDrakeCount; ObsidianSanctumScript* mInstance; Creature* m_cDrakes[OS_DATA_END - 1]; // exclude boss SpellDesc* mFlameTsunami, *mSummonLava; }; class TsunamiAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(TsunamiAI, MoonScriptBossAI); TsunamiAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { RegisterAIUpdateEvent(1000); SetFlyMode(true); SetCanEnterCombat(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Despawn(11500, 0); ParentClass::OnLoad(); }; void AIUpdate() { ApplyAura(TSUNAMI); ApplyAura(TSUNAMI_VISUAL); RegisterAIUpdateEvent(11000); ParentClass::OnLoad(); }; }; class CyclonAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(CyclonAI, MoonScriptBossAI); CyclonAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { SetCanMove(false); SetCanEnterCombat(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); ApplyAura(CYCLON_SPELL); ApplyAura(CYCLON_AURA); ParentClass::OnLoad(); }; }; class LavaBlazeAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(LavaBlazeAI, MoonScriptBossAI); LavaBlazeAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { AggroNearestPlayer(1); ParentClass::OnLoad(); }; void OnCombatStop(Unit* pTarget) { Despawn(1000, 0); }; void OnDied(Unit* pKiller) { Despawn(1000, 0); }; }; void SetupTheObsidianSanctum(ScriptMgr* mgr) { ////////////////////////////////////////////////////////////////////////////////////////// ///////// Mobs ////////////////////////////////////////////////////////////////////////////////////////// ///////// Bosses mgr->register_creature_script(CN_SARTHARION, &SartharionAI::Create); mgr->register_creature_script(CN_FLAME_TSUNAMI, &TsunamiAI::Create); mgr->register_creature_script(CN_CYCLON, &CyclonAI::Create); mgr->register_creature_script(CN_LAVA_BLAZE, &LavaBlazeAI::Create); ////////////////////////////////////////////////////////////////////////////////////////// ///////// Instance mgr->register_instance_script(MAP_OS, &ObsidianSanctumScript::Create); };
from ..libmp.backend import xrange from .functions import defun, defun_wrapped, defun_static @defun def stieltjes(ctx, n, a=1): n = ctx.convert(n) a = ctx.convert(a) if n < 0: return ctx.bad_domain("Stieltjes constants defined for n >= 0") if hasattr(ctx, "stieltjes_cache"): stieltjes_cache = ctx.stieltjes_cache else: stieltjes_cache = ctx.stieltjes_cache = {} if a == 1: if n == 0: return +ctx.euler if n in stieltjes_cache: prec, s = stieltjes_cache[n] if prec >= ctx.prec: return +s mag = 1 def f(x): xa = x/a v = (xa-ctx.j)*ctx.ln(a-ctx.j*x)**n/(1+xa**2)/(ctx.exp(2*ctx.pi*x)-1) return ctx._re(v) / mag orig = ctx.prec try: # Normalize integrand by approx. magnitude to # speed up quadrature (which uses absolute error) if n > 50: ctx.prec = 20 mag = ctx.quad(f, [0,ctx.inf], maxdegree=3) ctx.prec = orig + 10 + int(n**0.5) s = ctx.quad(f, [0,ctx.inf], maxdegree=20) v = ctx.ln(a)**n/(2*a) - ctx.ln(a)**(n+1)/(n+1) + 2*s/a*mag finally: ctx.prec = orig if a == 1 and ctx.isint(n): stieltjes_cache[n] = (ctx.prec, v) return +v @defun_wrapped def siegeltheta(ctx, t, derivative=0): d = int(derivative) if (t == ctx.inf or t == ctx.ninf): if d < 2: if t == ctx.ninf and d == 0: return ctx.ninf return ctx.inf else: return ctx.zero if d == 0: if ctx._im(t): # XXX: cancellation occurs a = ctx.loggamma(0.25+0.5j*t) b = ctx.loggamma(0.25-0.5j*t) return -ctx.ln(ctx.pi)/2*t - 0.5j*(a-b) else: if ctx.isinf(t): return t return ctx._im(ctx.loggamma(0.25+0.5j*t)) - ctx.ln(ctx.pi)/2*t if d > 0: a = (-0.5j)**(d-1)*ctx.polygamma(d-1, 0.25-0.5j*t) b = (0.5j)**(d-1)*ctx.polygamma(d-1, 0.25+0.5j*t) if ctx._im(t): if d == 1: return -0.5*ctx.log(ctx.pi)+0.25*(a+b) else: return 0.25*(a+b) else: if d == 1: return ctx._re(-0.5*ctx.log(ctx.pi)+0.25*(a+b)) else: return ctx._re(0.25*(a+b)) @defun_wrapped def grampoint(ctx, n): # asymptotic expansion, from # http://mathworld.wolfram.com/GramPoint.html g = 2*ctx.pi*ctx.exp(1+ctx.lambertw((8*n+1)/(8*ctx.e))) return ctx.findroot(lambda t: ctx.siegeltheta(t)-ctx.pi*n, g) @defun_wrapped def siegelz(ctx, t, **kwargs): d = int(kwargs.get("derivative", 0)) t = ctx.convert(t) t1 = ctx._re(t) t2 = ctx._im(t) prec = ctx.prec try: if abs(t1) > 500*prec and t2**2 < t1: v = ctx.rs_z(t, d) if ctx._is_real_type(t): return ctx._re(v) return v except NotImplementedError: pass ctx.prec += 21 e1 = ctx.expj(ctx.siegeltheta(t)) z = ctx.zeta(0.5+ctx.j*t) if d == 0: v = e1*z ctx.prec=prec if ctx._is_real_type(t): return ctx._re(v) return +v z1 = ctx.zeta(0.5+ctx.j*t, derivative=1) theta1 = ctx.siegeltheta(t, derivative=1) if d == 1: v = ctx.j*e1*(z1+z*theta1) ctx.prec=prec if ctx._is_real_type(t): return ctx._re(v) return +v z2 = ctx.zeta(0.5+ctx.j*t, derivative=2) theta2 = ctx.siegeltheta(t, derivative=2) comb1 = theta1**2-ctx.j*theta2 if d == 2: def terms(): return [2*z1*theta1, z2, z*comb1] v = ctx.sum_accurately(terms, 1) v = -e1*v ctx.prec = prec if ctx._is_real_type(t): return ctx._re(v) return +v ctx.prec += 10 z3 = ctx.zeta(0.5+ctx.j*t, derivative=3) theta3 = ctx.siegeltheta(t, derivative=3) comb2 = theta1**3-3*ctx.j*theta1*theta2-theta3 if d == 3: def terms(): return [3*theta1*z2, 3*z1*comb1, z3+z*comb2] v = ctx.sum_accurately(terms, 1) v = -ctx.j*e1*v ctx.prec = prec if ctx._is_real_type(t): return ctx._re(v) return +v z4 = ctx.zeta(0.5+ctx.j*t, derivative=4) theta4 = ctx.siegeltheta(t, derivative=4) def terms(): return [theta1**4, -6*ctx.j*theta1**2*theta2, -3*theta2**2, -4*theta1*theta3, ctx.j*theta4] comb3 = ctx.sum_accurately(terms, 1) if d == 4: def terms(): return [6*theta1**2*z2, -6*ctx.j*z2*theta2, 4*theta1*z3, 4*z1*comb2, z4, z*comb3] v = ctx.sum_accurately(terms, 1) v = e1*v ctx.prec = prec if ctx._is_real_type(t): return ctx._re(v) return +v if d > 4: h = lambda x: ctx.siegelz(x, derivative=4) return ctx.diff(h, t, n=d-4) _zeta_zeros = [ 14.134725142,21.022039639,25.010857580,30.424876126,32.935061588, 37.586178159,40.918719012,43.327073281,48.005150881,49.773832478, 52.970321478,56.446247697,59.347044003,60.831778525,65.112544048, 67.079810529,69.546401711,72.067157674,75.704690699,77.144840069, 79.337375020,82.910380854,84.735492981,87.425274613,88.809111208, 92.491899271,94.651344041,95.870634228,98.831194218,101.317851006, 103.725538040,105.446623052,107.168611184,111.029535543,111.874659177, 114.320220915,116.226680321,118.790782866,121.370125002,122.946829294, 124.256818554,127.516683880,129.578704200,131.087688531,133.497737203, 134.756509753,138.116042055,139.736208952,141.123707404,143.111845808, 146.000982487,147.422765343,150.053520421,150.925257612,153.024693811, 156.112909294,157.597591818,158.849988171,161.188964138,163.030709687, 165.537069188,167.184439978,169.094515416,169.911976479,173.411536520, 174.754191523,176.441434298,178.377407776,179.916484020,182.207078484, 184.874467848,185.598783678,187.228922584,189.416158656,192.026656361, 193.079726604,195.265396680,196.876481841,198.015309676,201.264751944, 202.493594514,204.189671803,205.394697202,207.906258888,209.576509717, 211.690862595,213.347919360,214.547044783,216.169538508,219.067596349, 220.714918839,221.430705555,224.007000255,224.983324670,227.421444280, 229.337413306,231.250188700,231.987235253,233.693404179,236.524229666, ] def _load_zeta_zeros(url): import urllib d = urllib.urlopen(url) L = [float(x) for x in d.readlines()] # Sanity check assert round(L[0]) == 14 _zeta_zeros[:] = L @defun def oldzetazero(ctx, n, url='http://www.dtc.umn.edu/~odlyzko/zeta_tables/zeros1'): n = int(n) if n < 0: return ctx.zetazero(-n).conjugate() if n == 0: raise ValueError("n must be nonzero") if n > len(_zeta_zeros) and n <= 100000: _load_zeta_zeros(url) if n > len(_zeta_zeros): raise NotImplementedError("n too large for zetazeros") return ctx.mpc(0.5, ctx.findroot(ctx.siegelz, _zeta_zeros[n-1])) @defun_wrapped def riemannr(ctx, x): if x == 0: return ctx.zero # Check if a simple asymptotic estimate is accurate enough if abs(x) > 1000: a = ctx.li(x) b = 0.5*ctx.li(ctx.sqrt(x)) if abs(b) < abs(a)*ctx.eps: return a if abs(x) < 0.01: # XXX ctx.prec += int(-ctx.log(abs(x),2)) # Sum Gram's series s = t = ctx.one u = ctx.ln(x) k = 1 while abs(t) > abs(s)*ctx.eps: t = t * u / k s += t / (k * ctx._zeta_int(k+1)) k += 1 return s @defun_static def primepi(ctx, x): x = int(x) if x < 2: return 0 return len(ctx.list_primes(x)) # TODO: fix the interface wrt contexts @defun_wrapped def primepi2(ctx, x): x = int(x) if x < 2: return ctx._iv.zero if x < 2657: return ctx._iv.mpf(ctx.primepi(x)) mid = ctx.li(x) # Schoenfeld's estimate for x >= 2657, assuming RH err = ctx.sqrt(x,rounding='u')*ctx.ln(x,rounding='u')/8/ctx.pi(rounding='d') a = ctx.floor((ctx._iv.mpf(mid)-err).a, rounding='d') b = ctx.ceil((ctx._iv.mpf(mid)+err).b, rounding='u') return ctx._iv.mpf([a,b]) @defun_wrapped def primezeta(ctx, s): if ctx.isnan(s): return s if ctx.re(s) <= 0: raise ValueError("prime zeta function defined only for re(s) > 0") if s == 1: return ctx.inf if s == 0.5: return ctx.mpc(ctx.ninf, ctx.pi) r = ctx.re(s) if r > ctx.prec: return 0.5**s else: wp = ctx.prec + int(r) def terms(): orig = ctx.prec # zeta ~ 1+eps; need to set precision # to get logarithm accurately k = 0 while 1: k += 1 u = ctx.moebius(k) if not u: continue ctx.prec = wp t = u*ctx.ln(ctx.zeta(k*s))/k if not t: return #print ctx.prec, ctx.nstr(t) ctx.prec = orig yield t return ctx.sum_accurately(terms) # TODO: for bernpoly and eulerpoly, ensure that all exact zeros are covered @defun_wrapped def bernpoly(ctx, n, z): # Slow implementation: #return sum(ctx.binomial(n,k)*ctx.bernoulli(k)*z**(n-k) for k in xrange(0,n+1)) n = int(n) if n < 0: raise ValueError("Bernoulli polynomials only defined for n >= 0") if z == 0 or (z == 1 and n > 1): return ctx.bernoulli(n) if z == 0.5: return (ctx.ldexp(1,1-n)-1)*ctx.bernoulli(n) if n <= 3: if n == 0: return z ** 0 if n == 1: return z - 0.5 if n == 2: return (6*z*(z-1)+1)/6 if n == 3: return z*(z*(z-1.5)+0.5) if ctx.isinf(z): return z ** n if ctx.isnan(z): return z if abs(z) > 2: def terms(): t = ctx.one yield t r = ctx.one/z k = 1 while k <= n: t = t*(n+1-k)/k*r if not (k > 2 and k & 1): yield t*ctx.bernoulli(k) k += 1 return ctx.sum_accurately(terms) * z**n else: def terms(): yield ctx.bernoulli(n) t = ctx.one k = 1 while k <= n: t = t*(n+1-k)/k * z m = n-k if not (m > 2 and m & 1): yield t*ctx.bernoulli(m) k += 1 return ctx.sum_accurately(terms) @defun_wrapped def eulerpoly(ctx, n, z): n = int(n) if n < 0: raise ValueError("Euler polynomials only defined for n >= 0") if n <= 2: if n == 0: return z ** 0 if n == 1: return z - 0.5 if n == 2: return z*(z-1) if ctx.isinf(z): return z**n if ctx.isnan(z): return z m = n+1 if z == 0: return -2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 if z == 1: return 2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 if z == 0.5: if n % 2: return ctx.zero # Use exact code for Euler numbers if n < 100 or n*ctx.mag(0.46839865*n) < ctx.prec*0.25: return ctx.ldexp(ctx._eulernum(n), -n) # http://functions.wolfram.com/Polynomials/EulerE2/06/01/02/01/0002/ def terms(): t = ctx.one k = 0 w = ctx.ldexp(1,n+2) while 1: v = n-k+1 if not (v > 2 and v & 1): yield (2-w)*ctx.bernoulli(v)*t k += 1 if k > n: break t = t*z*(n-k+2)/k w *= 0.5 return ctx.sum_accurately(terms) / m @defun def eulernum(ctx, n, exact=False): n = int(n) if exact: return int(ctx._eulernum(n)) if n < 100: return ctx.mpf(ctx._eulernum(n)) if n % 2: return ctx.zero return ctx.ldexp(ctx.eulerpoly(n,0.5), n) # TODO: this should be implemented low-level def polylog_series(ctx, s, z): tol = +ctx.eps l = ctx.zero k = 1 zk = z while 1: term = zk / k**s l += term if abs(term) < tol: break zk *= z k += 1 return l def polylog_continuation(ctx, n, z): if n < 0: return z*0 twopij = 2j * ctx.pi a = -twopij**n/ctx.fac(n) * ctx.bernpoly(n, ctx.ln(z)/twopij) if ctx._is_real_type(z) and z < 0: a = ctx._re(a) if ctx._im(z) < 0 or (ctx._im(z) == 0 and ctx._re(z) >= 1): a -= twopij*ctx.ln(z)**(n-1)/ctx.fac(n-1) return a def polylog_unitcircle(ctx, n, z): tol = +ctx.eps if n > 1: l = ctx.zero logz = ctx.ln(z) logmz = ctx.one m = 0 while 1: if (n-m) != 1: term = ctx.zeta(n-m) * logmz / ctx.fac(m) if term and abs(term) < tol: break l += term logmz *= logz m += 1 l += ctx.ln(z)**(n-1)/ctx.fac(n-1)*(ctx.harmonic(n-1)-ctx.ln(-ctx.ln(z))) elif n < 1: # else l = ctx.fac(-n)*(-ctx.ln(z))**(n-1) logz = ctx.ln(z) logkz = ctx.one k = 0 while 1: b = ctx.bernoulli(k-n+1) if b: term = b*logkz/(ctx.fac(k)*(k-n+1)) if abs(term) < tol: break l -= term logkz *= logz k += 1 else: raise ValueError if ctx._is_real_type(z) and z < 0: l = ctx._re(l) return l def polylog_general(ctx, s, z): v = ctx.zero u = ctx.ln(z) if not abs(u) < 5: # theoretically |u| < 2*pi raise NotImplementedError("polylog for arbitrary s and z") t = 1 k = 0 while 1: term = ctx.zeta(s-k) * t if abs(term) < ctx.eps: break v += term k += 1 t *= u t /= k return ctx.gamma(1-s)*(-u)**(s-1) + v @defun_wrapped def polylog(ctx, s, z): s = ctx.convert(s) z = ctx.convert(z) if z == 1: return ctx.zeta(s) if z == -1: return -ctx.altzeta(s) if s == 0: return z/(1-z) if s == 1: return -ctx.ln(1-z) if s == -1: return z/(1-z)**2 if abs(z) <= 0.75 or (not ctx.isint(s) and abs(z) < 0.9): return polylog_series(ctx, s, z) if abs(z) >= 1.4 and ctx.isint(s): return (-1)**(s+1)*polylog_series(ctx, s, 1/z) + polylog_continuation(ctx, s, z) if ctx.isint(s): return polylog_unitcircle(ctx, int(s), z) return polylog_general(ctx, s, z) #raise NotImplementedError("polylog for arbitrary s and z") # This could perhaps be used in some cases #from quadrature import quad #return quad(lambda t: t**(s-1)/(exp(t)/z-1),[0,inf])/gamma(s) @defun_wrapped def clsin(ctx, s, z, pi=False): if ctx.isint(s) and s < 0 and int(s) % 2 == 1: return z*0 if pi: a = ctx.expjpi(z) else: a = ctx.expj(z) if ctx._is_real_type(z) and ctx._is_real_type(s): return ctx.im(ctx.polylog(s,a)) b = 1/a return (-0.5j)*(ctx.polylog(s,a) - ctx.polylog(s,b)) @defun_wrapped def clcos(ctx, s, z, pi=False): if ctx.isint(s) and s < 0 and int(s) % 2 == 0: return z*0 if pi: a = ctx.expjpi(z) else: a = ctx.expj(z) if ctx._is_real_type(z) and ctx._is_real_type(s): return ctx.re(ctx.polylog(s,a)) b = 1/a return 0.5*(ctx.polylog(s,a) + ctx.polylog(s,b)) @defun def altzeta(ctx, s, **kwargs): try: return ctx._altzeta(s, **kwargs) except NotImplementedError: return ctx._altzeta_generic(s) @defun_wrapped def _altzeta_generic(ctx, s): if s == 1: return ctx.ln2 + 0*s return -ctx.powm1(2, 1-s) * ctx.zeta(s) @defun def zeta(ctx, s, a=1, derivative=0, method=None, **kwargs): d = int(derivative) if a == 1 and not (d or method): try: return ctx._zeta(s, **kwargs) except NotImplementedError: pass s = ctx.convert(s) prec = ctx.prec method = kwargs.get('method') verbose = kwargs.get('verbose') if a == 1 and method != 'euler-maclaurin': im = abs(ctx._im(s)) re = abs(ctx._re(s)) #if (im < prec or method == 'borwein') and not derivative: # try: # if verbose: # print "zeta: Attempting to use the Borwein algorithm" # return ctx._zeta(s, **kwargs) # except NotImplementedError: # if verbose: # print "zeta: Could not use the Borwein algorithm" # pass if abs(im) > 500*prec and 10*re < prec and derivative <= 4 or \ method == 'riemann-siegel': try: # py2.4 compatible try block try: if verbose: print("zeta: Attempting to use the Riemann-Siegel algorithm") return ctx.rs_zeta(s, derivative, **kwargs) except NotImplementedError: if verbose: print("zeta: Could not use the Riemann-Siegel algorithm") pass finally: ctx.prec = prec if s == 1: return ctx.inf abss = abs(s) if abss == ctx.inf: if ctx.re(s) == ctx.inf: if d == 0: return ctx.one return ctx.zero return s*0 elif ctx.isnan(abss): return 1/s if ctx.re(s) > 2*ctx.prec and a == 1 and not derivative: return ctx.one + ctx.power(2, -s) return +ctx._hurwitz(s, a, d, **kwargs) @defun def _hurwitz(ctx, s, a=1, d=0, **kwargs): prec = ctx.prec verbose = kwargs.get('verbose') try: extraprec = 10 ctx.prec += extraprec # We strongly want to special-case rational a a, atype = ctx._convert_param(a) if ctx.re(s) < 0: if verbose: print("zeta: Attempting reflection formula") try: return _hurwitz_reflection(ctx, s, a, d, atype) except NotImplementedError: pass if verbose: print("zeta: Reflection formula failed") if verbose: print("zeta: Using the Euler-Maclaurin algorithm") while 1: ctx.prec = prec + extraprec T1, T2 = _hurwitz_em(ctx, s, a, d, prec+10, verbose) cancellation = ctx.mag(T1) - ctx.mag(T1+T2) if verbose: print("Term 1:", T1) print("Term 2:", T2) print("Cancellation:", cancellation, "bits") if cancellation < extraprec: return T1 + T2 else: extraprec = max(2*extraprec, min(cancellation + 5, 100*prec)) if extraprec > kwargs.get('maxprec', 100*prec): raise ctx.NoConvergence("zeta: too much cancellation") finally: ctx.prec = prec def _hurwitz_reflection(ctx, s, a, d, atype): # TODO: implement for derivatives if d != 0: raise NotImplementedError res = ctx.re(s) negs = -s # Integer reflection formula if ctx.isnpint(s): n = int(res) if n <= 0: return ctx.bernpoly(1-n, a) / (n-1) t = 1-s # We now require a to be standardized v = 0 shift = 0 b = a while ctx.re(b) > 1: b -= 1 v -= b**negs shift -= 1 while ctx.re(b) <= 0: v += b**negs b += 1 shift += 1 # Rational reflection formula if atype == 'Q' or atype == 'Z': try: p, q = a._mpq_ except: assert a == int(a) p = int(a) q = 1 p += shift*q assert 1 <= p <= q g = ctx.fsum(ctx.cospi(t/2-2*k*b)*ctx._hurwitz(t,(k,q)) \ for k in range(1,q+1)) g *= 2*ctx.gamma(t)/(2*ctx.pi*q)**t v += g return v # General reflection formula # Note: clcos/clsin can raise NotImplementedError else: C1, C2 = ctx.cospi_sinpi(0.5*t) # Clausen functions; could maybe use polylog directly if C1: C1 *= ctx.clcos(t, 2*a, pi=True) if C2: C2 *= ctx.clsin(t, 2*a, pi=True) v += 2*ctx.gamma(t)/(2*ctx.pi)**t*(C1+C2) return v def _hurwitz_em(ctx, s, a, d, prec, verbose): # May not be converted at this point a = ctx.convert(a) tol = -prec # Estimate number of terms for Euler-Maclaurin summation; could be improved M1 = 0 M2 = prec // 3 N = M2 lsum = 0 # This speeds up the recurrence for derivatives if ctx.isint(s): s = int(ctx._re(s)) s1 = s-1 while 1: # Truncated L-series l = ctx._zetasum(s, M1+a, M2-M1-1, [d])[0][0] #if d: # l = ctx.fsum((-ctx.ln(n+a))**d * (n+a)**negs for n in range(M1,M2)) #else: # l = ctx.fsum((n+a)**negs for n in range(M1,M2)) lsum += l M2a = M2+a logM2a = ctx.ln(M2a) logM2ad = logM2a**d logs = [logM2ad] logr = 1/logM2a rM2a = 1/M2a M2as = rM2a**s if d: tailsum = ctx.gammainc(d+1, s1*logM2a) / s1**(d+1) else: tailsum = 1/((s1)*(M2a)**s1) tailsum += 0.5 * logM2ad * M2as U = [1] r = M2as fact = 2 for j in range(1, N+1): # TODO: the following could perhaps be tidied a bit j2 = 2*j if j == 1: upds = [1] else: upds = [j2-2, j2-1] for m in upds: D = min(m,d+1) if m <= d: logs.append(logs[-1] * logr) Un = [0]*(D+1) for i in xrange(D): Un[i] = (1-m-s)*U[i] for i in xrange(1,D+1): Un[i] += (d-(i-1))*U[i-1] U = Un r *= rM2a t = ctx.fdot(U, logs) * r * ctx.bernoulli(j2)/(-fact) tailsum += t if ctx.mag(t) < tol: return lsum, (-1)**d * tailsum fact *= (j2+1)*(j2+2) if verbose: print("Sum range:", M1, M2, "term magnitude", ctx.mag(t), "tolerance", tol) M1, M2 = M2, M2*2 if ctx.re(s) < 0: N += N//2 @defun def _zetasum(ctx, s, a, n, derivatives=[0], reflect=False): """ Returns [xd0,xd1,...,xdr], [yd0,yd1,...ydr] where xdk = D^k ( 1/a^s + 1/(a+1)^s + ... + 1/(a+n)^s ) ydk = D^k conj( 1/a^(1-s) + 1/(a+1)^(1-s) + ... + 1/(a+n)^(1-s) ) D^k = kth derivative with respect to s, k ranges over the given list of derivatives (which should consist of either a single element or a range 0,1,...r). If reflect=False, the ydks are not computed. """ #print "zetasum", s, a, n try: return ctx._zetasum_fast(s, a, n, derivatives, reflect) except NotImplementedError: pass negs = ctx.fneg(s, exact=True) have_derivatives = derivatives != [0] have_one_derivative = len(derivatives) == 1 if not reflect: if not have_derivatives: return [ctx.fsum((a+k)**negs for k in xrange(n+1))], [] if have_one_derivative: d = derivatives[0] x = ctx.fsum(ctx.ln(a+k)**d * (a+k)**negs for k in xrange(n+1)) return [(-1)**d * x], [] maxd = max(derivatives) if not have_one_derivative: derivatives = range(maxd+1) xs = [ctx.zero for d in derivatives] if reflect: ys = [ctx.zero for d in derivatives] else: ys = [] for k in xrange(n+1): w = a + k xterm = w ** negs if reflect: yterm = ctx.conj(ctx.one / (w * xterm)) if have_derivatives: logw = -ctx.ln(w) if have_one_derivative: logw = logw ** maxd xs[0] += xterm * logw if reflect: ys[0] += yterm * logw else: t = ctx.one for d in derivatives: xs[d] += xterm * t if reflect: ys[d] += yterm * t t *= logw else: xs[0] += xterm if reflect: ys[0] += yterm return xs, ys @defun def dirichlet(ctx, s, chi=[1], derivative=0): s = ctx.convert(s) q = len(chi) d = int(derivative) if d > 2: raise NotImplementedError("arbitrary order derivatives") prec = ctx.prec try: ctx.prec += 10 if s == 1: have_pole = True for x in chi: if x and x != 1: have_pole = False h = +ctx.eps ctx.prec *= 2*(d+1) s += h if have_pole: return +ctx.inf z = ctx.zero for p in range(1,q+1): if chi[p%q]: if d == 1: z += chi[p%q] * (ctx.zeta(s, (p,q), 1) - \ ctx.zeta(s, (p,q))*ctx.log(q)) else: z += chi[p%q] * ctx.zeta(s, (p,q)) z /= q**s finally: ctx.prec = prec return +z def secondzeta_main_term(ctx, s, a, **kwargs): tol = ctx.eps f = lambda n: ctx.gammainc(0.5*s, a*gamm**2, regularized=True)*gamm**(-s) totsum = term = ctx.zero mg = ctx.inf n = 0 while mg > tol: totsum += term n += 1 gamm = ctx.im(ctx.zetazero_memoized(n)) term = f(n) mg = abs(term) err = 0 if kwargs.get("error"): sg = ctx.re(s) err = 0.5*ctx.pi**(-1)*max(1,sg)*a**(sg-0.5)*ctx.log(gamm/(2*ctx.pi))*\ ctx.gammainc(-0.5, a*gamm**2)/abs(ctx.gamma(s/2)) err = abs(err) return +totsum, err, n def secondzeta_prime_term(ctx, s, a, **kwargs): tol = ctx.eps f = lambda n: ctx.gammainc(0.5*(1-s),0.25*ctx.log(n)**2 * a**(-1))*\ ((0.5*ctx.log(n))**(s-1))*ctx.mangoldt(n)/ctx.sqrt(n)/\ (2*ctx.gamma(0.5*s)*ctx.sqrt(ctx.pi)) totsum = term = ctx.zero mg = ctx.inf n = 1 while mg > tol or n < 9: totsum += term n += 1 term = f(n) if term == 0: mg = ctx.inf else: mg = abs(term) if kwargs.get("error"): err = mg return +totsum, err, n def secondzeta_exp_term(ctx, s, a): if ctx.isint(s) and ctx.re(s) <= 0: m = int(round(ctx.re(s))) if not m & 1: return ctx.mpf('-0.25')**(-m//2) tol = ctx.eps f = lambda n: (0.25*a)**n/((n+0.5*s)*ctx.fac(n)) totsum = ctx.zero term = f(0) mg = ctx.inf n = 0 while mg > tol: totsum += term n += 1 term = f(n) mg = abs(term) v = a**(0.5*s)*totsum/ctx.gamma(0.5*s) return v def secondzeta_singular_term(ctx, s, a, **kwargs): factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s)) extraprec = ctx.mag(factor) ctx.prec += extraprec factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s)) tol = ctx.eps f = lambda n: ctx.bernpoly(n,0.75)*(4*ctx.sqrt(a))**n*\ ctx.gamma(0.5*n)/((s+n-1)*ctx.fac(n)) totsum = ctx.zero mg1 = ctx.inf n = 1 term = f(n) mg2 = abs(term) while mg2 > tol and mg2 <= mg1: totsum += term n += 1 term = f(n) totsum += term n +=1 term = f(n) mg1 = mg2 mg2 = abs(term) totsum += term pole = -2*(s-1)**(-2)+(ctx.euler+ctx.log(16*ctx.pi**2*a))*(s-1)**(-1) st = factor*(pole+totsum) err = 0 if kwargs.get("error"): if not ((mg2 > tol) and (mg2 <= mg1)): if mg2 <= tol: err = ctx.mpf(10)**int(ctx.log(abs(factor*tol),10)) if mg2 > mg1: err = ctx.mpf(10)**int(ctx.log(abs(factor*mg1),10)) err = max(err, ctx.eps*1.) ctx.prec -= extraprec return +st, err @defun def secondzeta(ctx, s, a = 0.015, **kwargs): r""" Evaluates the secondary zeta function `Z(s)`, defined for `\mathrm{Re}(s)>1` by .. math :: Z(s) = \sum_{n=1}^{\infty} \frac{1}{\tau_n^s} where `\frac12+i\tau_n` runs through the zeros of `\zeta(s)` with imaginary part positive. `Z(s)` extends to a meromorphic function on `\mathbb{C}` with a double pole at `s=1` and simple poles at the points `-2n` for `n=0`, 1, 2, ... **Examples** >>> from mpmath import * >>> mp.pretty = True; mp.dps = 15 >>> secondzeta(2) 0.023104993115419 >>> xi = lambda s: 0.5*s*(s-1)*pi**(-0.5*s)*gamma(0.5*s)*zeta(s) >>> Xi = lambda t: xi(0.5+t*j) >>> -0.5*diff(Xi,0,n=2)/Xi(0) (0.023104993115419 + 0.0j) We may ask for an approximate error value:: >>> secondzeta(0.5+100j, error=True) ((-0.216272011276718 - 0.844952708937228j), 2.22044604925031e-16) The function has poles at the negative odd integers, and dyadic rational values at the negative even integers:: >>> mp.dps = 30 >>> secondzeta(-8) -0.67236328125 >>> secondzeta(-7) +inf **Implementation notes** The function is computed as sum of four terms `Z(s)=A(s)-P(s)+E(s)-S(s)` respectively main, prime, exponential and singular terms. The main term `A(s)` is computed from the zeros of zeta. The prime term depends on the von Mangoldt function. The singular term is responsible for the poles of the function. The four terms depends on a small parameter `a`. We may change the value of `a`. Theoretically this has no effect on the sum of the four terms, but in practice may be important. A smaller value of the parameter `a` makes `A(s)` depend on a smaller number of zeros of zeta, but `P(s)` uses more values of von Mangoldt function. We may also add a verbose option to obtain data about the values of the four terms. >>> mp.dps = 10 >>> secondzeta(0.5 + 40j, error=True, verbose=True) main term = (-30190318549.138656312556 - 13964804384.624622876523j) computed using 19 zeros of zeta prime term = (132717176.89212754625045 + 188980555.17563978290601j) computed using 9 values of the von Mangoldt function exponential term = (542447428666.07179812536 + 362434922978.80192435203j) singular term = (512124392939.98154322355 + 348281138038.65531023921j) ((0.059471043 + 0.3463514534j), 1.455191523e-11) >>> secondzeta(0.5 + 40j, a=0.04, error=True, verbose=True) main term = (-151962888.19606243907725 - 217930683.90210294051982j) computed using 9 zeros of zeta prime term = (2476659342.3038722372461 + 28711581821.921627163136j) computed using 37 values of the von Mangoldt function exponential term = (178506047114.7838188264 + 819674143244.45677330576j) singular term = (175877424884.22441310708 + 790744630738.28669174871j) ((0.059471043 + 0.3463514534j), 1.455191523e-11) Notice the great cancellation between the four terms. Changing `a`, the four terms are very different numbers but the cancellation gives the good value of Z(s). **References** A. Voros, Zeta functions for the Riemann zeros, Ann. Institute Fourier, 53, (2003) 665--699. A. Voros, Zeta functions over Zeros of Zeta Functions, Lecture Notes of the Unione Matematica Italiana, Springer, 2009. """ s = ctx.convert(s) a = ctx.convert(a) tol = ctx.eps if ctx.isint(s) and ctx.re(s) <= 1: if abs(s-1) < tol*1000: return ctx.inf m = int(round(ctx.re(s))) if m & 1: return ctx.inf else: return ((-1)**(-m//2)*\ ctx.fraction(8-ctx.eulernum(-m,exact=True),2**(-m+3))) prec = ctx.prec try: t3 = secondzeta_exp_term(ctx, s, a) extraprec = max(ctx.mag(t3),0) ctx.prec += extraprec + 3 t1, r1, gt = secondzeta_main_term(ctx,s,a,error='True', verbose='True') t2, r2, pt = secondzeta_prime_term(ctx,s,a,error='True', verbose='True') t4, r4 = secondzeta_singular_term(ctx,s,a,error='True') t3 = secondzeta_exp_term(ctx, s, a) err = r1+r2+r4 t = t1-t2+t3-t4 if kwargs.get("verbose"): print('main term =', t1) print(' computed using', gt, 'zeros of zeta') print('prime term =', t2) print(' computed using', pt, 'values of the von Mangoldt function') print('exponential term =', t3) print('singular term =', t4) finally: ctx.prec = prec if kwargs.get("error"): w = max(ctx.mag(abs(t)),0) err = max(err*2**w, ctx.eps*1.*2**w) return +t, err return +t @defun_wrapped def lerchphi(ctx, z, s, a): r""" Gives the Lerch transcendent, defined for `|z| < 1` and `\Re{a} > 0` by .. math :: \Phi(z,s,a) = \sum_{k=0}^{\infty} \frac{z^k}{(a+k)^s} and generally by the recurrence `\Phi(z,s,a) = z \Phi(z,s,a+1) + a^{-s}` along with the integral representation valid for `\Re{a} > 0` .. math :: \Phi(z,s,a) = \frac{1}{2 a^s} + \int_0^{\infty} \frac{z^t}{(a+t)^s} dt - 2 \int_0^{\infty} \frac{\sin(t \log z - s \operatorname{arctan}(t/a)}{(a^2 + t^2)^{s/2} (e^{2 \pi t}-1)} dt. The Lerch transcendent generalizes the Hurwitz zeta function :func:`zeta` (`z = 1`) and the polylogarithm :func:`polylog` (`a = 1`). **Examples** Several evaluations in terms of simpler functions:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> lerchphi(-1,2,0.5); 4*catalan 3.663862376708876060218414 3.663862376708876060218414 >>> diff(lerchphi, (-1,-2,1), (0,1,0)); 7*zeta(3)/(4*pi**2) 0.2131391994087528954617607 0.2131391994087528954617607 >>> lerchphi(-4,1,1); log(5)/4 0.4023594781085250936501898 0.4023594781085250936501898 >>> lerchphi(-3+2j,1,0.5); 2*atanh(sqrt(-3+2j))/sqrt(-3+2j) (1.142423447120257137774002 + 0.2118232380980201350495795j) (1.142423447120257137774002 + 0.2118232380980201350495795j) Evaluation works for complex arguments and `|z| \ge 1`:: >>> lerchphi(1+2j, 3-j, 4+2j) (0.002025009957009908600539469 + 0.003327897536813558807438089j) >>> lerchphi(-2,2,-2.5) -12.28676272353094275265944 >>> lerchphi(10,10,10) (-4.462130727102185701817349e-11 + 1.575172198981096218823481e-12j) >>> lerchphi(10,10,-10.5) (112658784011940.5605789002 + 498113185.5756221777743631j) Some degenerate cases:: >>> lerchphi(0,1,2) 0.5 >>> lerchphi(0,1,-2) -0.5 **References** 1. [DLMF]_ section 25.14 """ if z == 0: return a ** (-s) """ # Faster, but these cases are useful for testing right now if z == 1: return ctx.zeta(s, a) if a == 1: return z * ctx.polylog(s, z) """ if ctx.re(a) < 1: if ctx.isnpint(a): raise ValueError("Lerch transcendent complex infinity") m = int(ctx.ceil(1-ctx.re(a))) v = ctx.zero zpow = ctx.one for n in xrange(m): v += zpow / (a+n)**s zpow *= z return zpow * ctx.lerchphi(z,s, a+m) + v g = ctx.ln(z) v = 1/(2*a**s) + ctx.gammainc(1-s, -a*g) * (-g)**(s-1) / z**a h = s / 2 r = 2*ctx.pi f = lambda t: ctx.sin(s*ctx.atan(t/a)-t*g) / \ ((a**2+t**2)**h * ctx.expm1(r*t)) v += 2*ctx.quad(f, [0, ctx.inf]) if not ctx.im(z) and not ctx.im(s) and not ctx.im(a) and ctx.re(z) < 1: v = ctx.chop(v) return v
// Accord Math Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // // The source code presented in this file has been adapted from LibSVM - // A Library for Support Vector Machines, created by Chih-Chung Chang and // Chih-Jen Lin. Original license is given below. // // Copyright (c) 2000-2014 Chih-Chung Chang and Chih-Jen Lin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither name of copyright holders nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // namespace Accord.Math.Optimization { using System; using System.Diagnostics; /// <summary> /// General Sequential Minimal Optimization algorithm for Quadratic Programming problems. /// </summary> /// /// <remarks> /// <para> /// This class implements the same optimization method found in LibSVM. It can be used /// to solve quadratic programming problems where the quadratic matrix Q may be too large /// to fit in memory.</para> /// /// <para> /// The method is described in Fan et al., JMLR 6(2005), p. 1889--1918. It solves the /// minimization problem:</para> /// /// <code> /// min 0.5(\alpha^T Q \alpha) + p^T \alpha /// /// y^T \alpha = \delta /// y_i = +1 or -1 /// 0 &lt;= alpha_i &lt;= C_i /// </code> /// /// <para> /// Given Q, p, y, C, and an initial feasible point \alpha, where l is /// the size of vectors and matrices and eps is the stopping tolerance. /// </para> /// </remarks> /// public class FanChenLinQuadraticOptimization : IOptimizationMethod { const double TAU = 1e-12; int active_size; int[] y; double[] G; // gradient of objective function enum Status { LOWER_BOUND, UPPER_BOUND, FREE }; Status[] alpha_status; double[] alpha; Func<int, int, double> Q; double[] QD; // diagonal double eps = 0.001; double[] C; double[] p; int[] active_set; int[] indices; double[] G_bar; // gradient, if we treat free variables as 0 int l; bool unshrink; bool shrinking; double rho; double obj; /// <summary> /// Gets the number of variables (free parameters) in the optimization /// problem. In a SVM learning problem, this is the number of samples in /// the learning dataset. /// </summary> /// /// <value> /// The number of parameters for the optimization problem. /// </value> /// public int NumberOfVariables { get { return l; } } /// <summary> /// Gets the current solution found, the values of /// the parameters which optimizes the function. /// </summary> /// public double[] Solution { get { return alpha; } set { alpha = value; } } /// <summary> /// Gets the output of the function at the current <see cref="Solution" />. /// </summary> /// public double Value { get { return obj; } } /// <summary> /// Gets the threshold (bias) value for a SVM trained using this method. /// </summary> /// public double Rho { get { return rho; } } /// <summary> /// Gets or sets the precision tolerance before /// the method stops. Default is 0.001. /// </summary> /// public double Tolerance { get { return eps; } set { eps = value; } } /// <summary> /// Gets or sets a value indicating whether shrinking /// heuristics should be used. /// </summary> /// /// <value> /// <c>true</c> to use shrinking heuristics; otherwise, <c>false</c>. /// </value> /// public bool Shrinking { get { return shrinking; } set { shrinking = value; } } /// <summary> /// Gets the upper bounds for the optimization problem. In /// a SVM learning problem, this would be the capacity limit /// for each Lagrange multiplier (alpha) in the machine. The /// default is to use a vector filled with 1's. /// </summary> /// public double[] UpperBounds { get { return C; } } /// <summary> /// Initializes a new instance of the <see cref="FanChenLinQuadraticOptimization"/> class. /// </summary> /// /// <param name="numberOfVariables">The number of free parameters in the optimization problem.</param> /// <param name="Q"> /// The quadratic matrix Q. It should be specified as a lambda /// function so Q doesn't need to be always kept in memory.</param> /// public FanChenLinQuadraticOptimization(int numberOfVariables, Func<int, int, double> Q) { var zeros = new double[numberOfVariables]; var ones = new int[numberOfVariables]; for (int i = 0; i < ones.Length; i++) ones[i] = 1; initialize(numberOfVariables, Q, zeros, ones); } /// <summary> /// Initializes a new instance of the <see cref="FanChenLinQuadraticOptimization"/> class. /// </summary> /// /// <param name="numberOfVariables">The number of free parameters in the optimization problem.</param> /// <param name="Q"> /// The quadratic matrix Q. It should be specified as a lambda /// function so Q doesn't need to be always kept in memory.</param> /// <param name="p">The vector of linear terms p. Default is a zero vector.</param> /// <param name="y">The class labels y. Default is a unit vector.</param> /// public FanChenLinQuadraticOptimization(int numberOfVariables, Func<int, int, double> Q, double[] p, int[] y) { initialize(numberOfVariables, Q, p, y); } private void initialize(int numberOfVariables, Func<int, int, double> Q, double[] p, int[] y) { this.l = numberOfVariables; this.Q = Q; this.C = new double[l]; this.indices = new int[l]; this.alpha_status = new Status[l]; this.active_set = new int[l]; this.G = new double[l]; this.G_bar = new double[l]; this.p = p; this.y = y; this.alpha = new double[l]; for (int i = 0; i < C.Length; i++) C[i] = 1.0; } /// <summary> /// Finds the minimum value of a function. The solution vector /// will be made available at the <see cref="Solution" /> property. /// </summary> /// /// <returns> /// Returns <c>true</c> if the method converged to a <see cref="Solution" />. /// In this case, the found value will also be available at the <see cref="Value" /> /// property. /// </returns> /// public bool Minimize() { QD = new double[l]; for (int k = 0; k < QD.Length; k++) QD[k] = Q(k, k); unshrink = false; double[] Q_i = new double[l]; double[] Q_j = new double[l]; // initialize alpha_status { for (int i = 0; i < l; i++) update_alpha_status(i); } // initialize active set (for shrinking) { for (int i = 0; i < l; i++) active_set[i] = i; active_size = l; } // initialize index lookup vector { for (int i = 0; i < indices.Length; i++) indices[i] = i; } // initialize gradient { for (int i = 0; i < l; i++) { G[i] = p[i]; G_bar[i] = 0; } for (int i = 0; i < l; i++) { if (!is_lower_bound(i)) { row(i, l, Q_i); double alpha_i = alpha[i]; for (int j = 0; j < l; j++) G[j] += alpha_i * Q_i[j]; if (is_upper_bound(i)) { for (int j = 0; j < l; j++) G_bar[j] += C[i] * Q_i[j]; } } } } // optimization step int iter = 0; int max_iter = Math.Max(10000000, l > int.MaxValue / 100 ? int.MaxValue : 100 * l); int counter = Math.Min(l, 1000) + 1; while (iter < max_iter) { // show progress and do shrinking if (--counter == 0) { counter = Math.Min(l, 1000); if (shrinking) do_shrinking(); Trace.WriteLine("."); } int i = 0, j = 0; if (select_working_set(ref i, ref j) != 0) { // reconstruct the whole gradient reconstruct_gradient(); // reset active set size and check active_size = l; Trace.WriteLine("*"); if (select_working_set(ref i, ref j) != 0) { break; } else { counter = 1; // do shrinking next iteration } } ++iter; // update alpha[i] and alpha[j], handle bounds carefully row(i, active_size, Q_i); row(j, active_size, Q_j); double C_i = C[i]; double C_j = C[j]; double old_alpha_i = alpha[i]; double old_alpha_j = alpha[j]; if (y[i] != y[j]) { double quad_coef = QD[i] + QD[j] + 2 * Q_i[j]; if (quad_coef <= 0) quad_coef = TAU; double delta = (-G[i] - G[j]) / quad_coef; double diff = alpha[i] - alpha[j]; alpha[i] += delta; alpha[j] += delta; if (diff > 0) { if (alpha[j] < 0) { alpha[j] = 0; alpha[i] = diff; } } else { if (alpha[i] < 0) { alpha[i] = 0; alpha[j] = -diff; } } if (diff > C_i - C_j) { if (alpha[i] > C_i) { alpha[i] = C_i; alpha[j] = C_i - diff; } } else { if (alpha[j] > C_j) { alpha[j] = C_j; alpha[i] = C_j + diff; } } } else { double quad_coef = QD[i] + QD[j] - 2 * Q_i[j]; if (quad_coef <= 0) quad_coef = TAU; double delta = (G[i] - G[j]) / quad_coef; double sum = alpha[i] + alpha[j]; alpha[i] -= delta; alpha[j] += delta; if (sum > C_i) { if (alpha[i] > C_i) { alpha[i] = C_i; alpha[j] = sum - C_i; } } else { if (alpha[j] < 0) { alpha[j] = 0; alpha[i] = sum; } } if (sum > C_j) { if (alpha[j] > C_j) { alpha[j] = C_j; alpha[i] = sum - C_j; } } else { if (alpha[i] < 0) { alpha[i] = 0; alpha[j] = sum; } } } // update G double delta_alpha_i = alpha[i] - old_alpha_i; double delta_alpha_j = alpha[j] - old_alpha_j; for (int k = 0; k < active_size; k++) { G[k] += Q_i[k] * delta_alpha_i + Q_j[k] * delta_alpha_j; } // update alpha_status and G_bar { bool ui = is_upper_bound(i); bool uj = is_upper_bound(j); update_alpha_status(i); update_alpha_status(j); if (ui != is_upper_bound(i)) { row(i, l, Q_i); if (ui) { for (int k = 0; k < l; k++) G_bar[k] -= C_i * Q_i[k]; } else { for (int k = 0; k < l; k++) G_bar[k] += C_i * Q_i[k]; } } if (uj != is_upper_bound(j)) { row(j, l, Q_j); if (uj) { for (int k = 0; k < l; k++) G_bar[k] -= C_j * Q_j[k]; } else { for (int k = 0; k < l; k++) G_bar[k] += C_j * Q_j[k]; } } } } if (iter >= max_iter) { if (active_size < l) { // reconstruct the whole gradient to calculate objective value reconstruct_gradient(); active_size = l; Trace.WriteLine("*"); } Trace.WriteLine("WARNING: reaching max number of iterations"); } // calculate rho rho = calculate_rho(); // calculate objective value { double v = 0; for (int i = 0; i < l; i++) v += alpha[i] * (G[i] + p[i]); obj = v / 2; } // put back the solution { var solution = (double[])alpha.Clone(); Array.Clear(alpha, 0, alpha.Length); for (int i = 0; i < l; i++) alpha[active_set[i]] = solution[i]; } // juggle everything back /*{ for(int i=0;i<l;i++) while(active_set[i] != i) swap_index(i,active_set[i]); // or Q.swap_index(i,active_set[i]); }*/ Trace.WriteLine("optimization finished, #iter = " + iter); return (iter < max_iter); } /// <summary> /// Not supported. /// </summary> /// public bool Maximize() { throw new NotSupportedException(); } void update_alpha_status(int i) { if (alpha[i] >= C[i]) alpha_status[i] = Status.UPPER_BOUND; else if (alpha[i] <= 0) alpha_status[i] = Status.LOWER_BOUND; else alpha_status[i] = Status.FREE; } bool is_upper_bound(int i) { return alpha_status[i] == Status.UPPER_BOUND; } bool is_lower_bound(int i) { return alpha_status[i] == Status.LOWER_BOUND; } bool is_free(int i) { return alpha_status[i] == Status.FREE; } void reconstruct_gradient() { // reconstruct inactive elements of G from G_bar and free variables if (active_size == l) return; int nr_free = 0; for (int j = active_size; j < l; j++) G[j] = G_bar[j] + p[j]; for (int j = 0; j < active_size; j++) if (is_free(j)) nr_free++; if (2 * nr_free < active_size) Trace.WriteLine("WARNING: using -h 0 may be faster"); if (nr_free * l > 2 * active_size * (l - active_size)) { for (int i = active_size; i < l; i++) { int ii = indices[i]; for (int j = 0; j < active_size; j++) { if (is_free(j)) G[i] += alpha[j] * Q(ii, indices[j]); } } } else { for (int i = 0; i < active_size; i++) { if (is_free(i)) { int ii = indices[i]; double alpha_i = alpha[i]; for (int j = active_size; j < l; j++) G[j] += alpha_i * Q(ii, indices[j]); } } } } // return 1 if already optimal, return 0 otherwise int select_working_set(ref int out_i, ref int out_j) { // return i,j such that // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha) // j: minimizes the decrease of obj value // (if quadratic coefficient <= 0, replace it with tau) // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha) double Gmax = Double.NegativeInfinity; double Gmax2 = Double.NegativeInfinity; int Gmax_idx = -1; int Gmin_idx = -1; double obj_diff_min = Double.PositiveInfinity; for (int t = 0; t < active_size; t++) { if (y[t] == +1) { if (!is_upper_bound(t)) { if (-G[t] >= Gmax) { Gmax = -G[t]; Gmax_idx = t; } } } else { if (!is_lower_bound(t)) { if (G[t] >= Gmax) { Gmax = G[t]; Gmax_idx = t; } } } } int i = Gmax_idx; double[] Q_i = null; if (i != -1) { Q_i = new double[active_size]; row(i, active_size, Q_i); // NULL Q_i not accessed: Gmax=-INF if i=-1 } for (int j = 0; j < active_size; j++) { if (y[j] == +1) { if (!is_lower_bound(j)) { double grad_diff = Gmax + G[j]; if (G[j] >= Gmax2) Gmax2 = G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[i] + QD[j] - 2.0 * y[i] * Q_i[j]; if (quad_coef > 0) obj_diff = -(grad_diff * grad_diff) / quad_coef; else obj_diff = -(grad_diff * grad_diff) / TAU; if (obj_diff <= obj_diff_min) { Gmin_idx = j; obj_diff_min = obj_diff; } } } } else { if (!is_upper_bound(j)) { double grad_diff = Gmax - G[j]; if (-G[j] >= Gmax2) Gmax2 = -G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[i] + QD[j] + 2.0 * y[i] * Q_i[j]; if (quad_coef > 0) obj_diff = -(grad_diff * grad_diff) / quad_coef; else obj_diff = -(grad_diff * grad_diff) / TAU; if (obj_diff <= obj_diff_min) { Gmin_idx = j; obj_diff_min = obj_diff; } } } } } if (Gmax + Gmax2 < eps) return 1; out_i = Gmax_idx; out_j = Gmin_idx; return 0; } double calculate_rho() { double r; int nr_free = 0; double ub = Double.PositiveInfinity; double lb = Double.NegativeInfinity; double sum_free = 0; for (int i = 0; i < active_size; i++) { double yG = y[i] * G[i]; if (is_upper_bound(i)) { if (y[i] == -1) ub = Math.Min(ub, yG); else lb = Math.Max(lb, yG); } else if (is_lower_bound(i)) { if (y[i] == +1) ub = Math.Min(ub, yG); else lb = Math.Max(lb, yG); } else { ++nr_free; sum_free += yG; } } if (nr_free > 0) r = sum_free / nr_free; else r = (ub + lb) / 2; return r; } void do_shrinking() { double Gmax1 = Double.NegativeInfinity; // max { -y_i * grad(f)_i | i in I_up(\alpha) } double Gmax2 = Double.NegativeInfinity; // max { y_i * grad(f)_i | i in I_low(\alpha) } // find maximal violating pair first for (int i = 0; i < active_size; i++) { if (y[i] == +1) { if (!is_upper_bound(i)) { if (-G[i] >= Gmax1) Gmax1 = -G[i]; } if (!is_lower_bound(i)) { if (G[i] >= Gmax2) Gmax2 = G[i]; } } else { if (!is_upper_bound(i)) { if (-G[i] >= Gmax2) Gmax2 = -G[i]; } if (!is_lower_bound(i)) { if (G[i] >= Gmax1) Gmax1 = G[i]; } } } if (unshrink == false && Gmax1 + Gmax2 <= eps * 10) { unshrink = true; reconstruct_gradient(); active_size = l; Trace.WriteLine("*"); } for (int i = 0; i < active_size; i++) { if (be_shrunk(i, Gmax1, Gmax2)) { active_size--; while (active_size > i) { if (!be_shrunk(active_size, Gmax1, Gmax2)) { swap_index(i, active_size); break; } active_size--; } } } } bool be_shrunk(int i, double Gmax1, double Gmax2) { if (is_upper_bound(i)) { if (y[i] == +1) return (-G[i] > Gmax1); return (-G[i] > Gmax2); } else if (is_lower_bound(i)) { if (y[i] == +1) return (G[i] > Gmax2); return (G[i] > Gmax1); } return false; } void row(int i, int length, double[] row) { int ii = indices[i]; for (int j = 0; j < length; j++) row[j] = Q(ii, indices[j]); } void swap_index(int i, int j) { swap(ref indices[i], ref indices[j]); swap(ref y[i], ref y[j]); swap(ref G[i], ref G[j]); swap(ref alpha_status[i], ref alpha_status[j]); swap(ref alpha[i], ref alpha[j]); swap(ref p[i], ref p[j]); swap(ref active_set[i], ref active_set[j]); swap(ref G_bar[i], ref G_bar[j]); } static void swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; } } }
<div class="row"> <div class="col-sm-6"> <dl ng-if="pvc"> <dt translate>Name</dt> <dd>{{ pvc.metadata.name }}</dd> <dt translate>Namespace</dt> <dd>{{ pvc.metadata.namespace }}</dd> <dt ng-if="pvc.spec.accessModes" translate>Access Modes</dt> <dd ng-if="pvc.spec.accessModes"> <span ng-repeat="mode in pvc.spec.accessModes">{{ mode | accessModeLabel }}<span ng-if="!$last">, </span></span> </dd> <dt ng-if="pvc.spec.resources.requests" translate>Requests</dt> <dd ng-if="pvc.spec.resources.requests"> <dl> <dt ng-repeat-start="(key, value) in pvc.spec.resources.requests">{{ key | formatCapacityName }}</dt> <dd ng-repeat-end>{{ value | formatCapacityValue:key }}</dd> </dl> <dd> </dl> <dl class="full-width" ng-if="!pvc"> <dd translate>This volume has not been claimed</dd> </dl> </div> <div class="col-sm-6"> <dl ng-if="pvc" class="full-width"> <dt ng-if="target" translate>Status</dt> <dd ng-if="target && pvc.status.phase">{{ pvc.status.phase }}</dd> <dd ng-if="target && !pvc.status.phase" translate>Unknown</dd> <dt ng-if="pvc.status.message" translate>Message</dt> <dd ng-if="pvc.status.message">{{ pvc.status.message }}</dd> </dl> <dl class="full-width" ng-if="pvc"> <dt translate>Pods</dt> <dd ng-repeat="pod in pods">{{ pod.metadata.namespace }} / {{ pod.metadata.name }}</dd> <dd ng-if="!pods.length" translate>No Pods are using this claim</dd> </dl> </div> </div>
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Core * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Custom variable model * * @method Mage_Core_Model_Resource_Variable _getResource() * @method Mage_Core_Model_Resource_Variable getResource() * @method string getCode() * @method Mage_Core_Model_Variable setCode(string $value) * @method string getName() * @method Mage_Core_Model_Variable setName(string $value) * * @category Mage * @package Mage_Core * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Core_Model_Variable extends Mage_Core_Model_Abstract { const TYPE_TEXT = 'text'; const TYPE_HTML = 'html'; protected $_storeId = 0; /** * Internal Constructor */ protected function _construct() { parent::_construct(); $this->_init('core/variable'); } /** * Setter * * @param integer $storeId * @return Mage_Core_Model_Variable */ public function setStoreId($storeId) { $this->_storeId = $storeId; return $this; } /** * Getter * * @return integer */ public function getStoreId() { return $this->_storeId; } /** * Load variable by code * * @param string $code * @return Mage_Core_Model_Variable */ public function loadByCode($code) { $this->getResource()->loadByCode($this, $code); return $this; } /** * Return variable value depend on given type * * @param string $type * @return string */ public function getValue($type = null) { if ($type === null) { $type = self::TYPE_HTML; } if ($type == self::TYPE_TEXT || !(strlen((string)$this->getData('html_value')))) { $value = $this->getData('plain_value'); //escape html if type is html, but html value is not defined if ($type == self::TYPE_HTML) { $value = nl2br(Mage::helper('core')->escapeHtml($value)); } return $value; } return $this->getData('html_value'); } /** * Validation of object data. Checking for unique variable code * * @return boolean | string */ public function validate() { if ($this->getCode() && $this->getName()) { $variable = $this->getResource()->getVariableByCode($this->getCode()); if (!empty($variable) && $variable['variable_id'] != $this->getId()) { return Mage::helper('core')->__('Variable Code must be unique.'); } return true; } return Mage::helper('core')->__('Validation has failed.'); } /** * Retrieve variables option array * * @param boolean $withValues * @return array */ public function getVariablesOptionArray($withGroup = false) { /* @var $collection Mage_Core_Model_Mysql4_Variable_Collection */ $collection = $this->getCollection(); $variables = array(); foreach ($collection->toOptionArray() as $variable) { $variables[] = array( 'value' => '{{customVar code=' . $variable['value'] . '}}', 'label' => Mage::helper('core')->__('%s', $variable['label']) ); } if ($withGroup && $variables) { $variables = array( 'label' => Mage::helper('core')->__('Custom Variables'), 'value' => $variables ); } return $variables; } }
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Reports * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Report Reviews collection * * @category Mage * @package Mage_Reports * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Reports_Model_Resource_Report_Collection { /** * From value * * @var string */ protected $_from; /** * To value * * @var string */ protected $_to; /** * Report period * * @var int */ protected $_period; /** * Model object * * @var string */ protected $_model; /** * Intervals * * @var int */ protected $_intervals; /** * Page size * * @var int */ protected $_pageSize; /** * Array of store ids * * @var array */ protected $_storeIds; /** * Resource initialization * */ protected function _construct() { } /** * Set period * * @param int $period * @return Mage_Reports_Model_Resource_Report_Collection */ public function setPeriod($period) { $this->_period = $period; return $this; } /** * Set interval * * @param int $from * @param int $to * @return Mage_Reports_Model_Resource_Report_Collection */ public function setInterval($from, $to) { $this->_from = $from; $this->_to = $to; return $this; } /** * Get intervals * * @return unknown */ public function getIntervals() { if (!$this->_intervals) { $this->_intervals = array(); if (!$this->_from && !$this->_to) { return $this->_intervals; } $dateStart = new Zend_Date($this->_from); $dateEnd = new Zend_Date($this->_to); $t = array(); $firstInterval = true; while ($dateStart->compare($dateEnd) <= 0) { switch ($this->_period) { case 'day': $t['title'] = $dateStart->toString(Mage::app()->getLocale()->getDateFormat()); $t['start'] = $dateStart->toString('yyyy-MM-dd HH:mm:ss'); $t['end'] = $dateStart->toString('yyyy-MM-dd 23:59:59'); $dateStart->addDay(1); break; case 'month': $t['title'] = $dateStart->toString('MM/yyyy'); $t['start'] = ($firstInterval) ? $dateStart->toString('yyyy-MM-dd 00:00:00') : $dateStart->toString('yyyy-MM-01 00:00:00'); $lastInterval = ($dateStart->compareMonth($dateEnd->getMonth()) == 0); $t['end'] = ($lastInterval) ? $dateStart->setDay($dateEnd->getDay()) ->toString('yyyy-MM-dd 23:59:59') : $dateStart->toString('yyyy-MM-'.date('t', $dateStart->getTimestamp()).' 23:59:59'); $dateStart->addMonth(1); if ($dateStart->compareMonth($dateEnd->getMonth()) == 0) { $dateStart->setDay(1); } $firstInterval = false; break; case 'year': $t['title'] = $dateStart->toString('yyyy'); $t['start'] = ($firstInterval) ? $dateStart->toString('yyyy-MM-dd 00:00:00') : $dateStart->toString('yyyy-01-01 00:00:00'); $lastInterval = ($dateStart->compareYear($dateEnd->getYear()) == 0); $t['end'] = ($lastInterval) ? $dateStart->setMonth($dateEnd->getMonth()) ->setDay($dateEnd->getDay())->toString('yyyy-MM-dd 23:59:59') : $dateStart->toString('yyyy-12-31 23:59:59'); $dateStart->addYear(1); if ($dateStart->compareYear($dateEnd->getYear()) == 0) { $dateStart->setMonth(1)->setDay(1); } $firstInterval = false; break; } $this->_intervals[$t['title']] = $t; } } return $this->_intervals; } /** * Return date periods * * @return array */ public function getPeriods() { return array( 'day' => Mage::helper('reports')->__('Day'), 'month' => Mage::helper('reports')->__('Month'), 'year' => Mage::helper('reports')->__('Year') ); } /** * Set store ids * * @param array $storeIds * @return Mage_Reports_Model_Resource_Report_Collection */ public function setStoreIds($storeIds) { $this->_storeIds = $storeIds; return $this; } /** * Get store ids * * @return arrays */ public function getStoreIds() { return $this->_storeIds; } /** * Get size * * @return int */ public function getSize() { return count($this->getIntervals()); } /** * Set page size * * @param int $size * @return Mage_Reports_Model_Resource_Report_Collection */ public function setPageSize($size) { $this->_pageSize = $size; return $this; } /** * Get page size * * @return int */ public function getPageSize() { return $this->_pageSize; } /** * Init report * * @param string $modelClass * @return Mage_Reports_Model_Resource_Report_Collection */ public function initReport($modelClass) { $this->_model = Mage::getModel('reports/report') ->setPageSize($this->getPageSize()) ->setStoreIds($this->getStoreIds()) ->initCollection($modelClass); return $this; } /** * get report full * * @param int $from * @param int $to * @return unknown */ public function getReportFull($from, $to) { return $this->_model->getReportFull($this->timeShift($from), $this->timeShift($to)); } /** * Get report * * @param int $from * @param int $to * @return Varien_Object */ public function getReport($from, $to) { return $this->_model->getReport($this->timeShift($from), $this->timeShift($to)); } /** * Retreive time shift * * @param string $datetime * @return string */ public function timeShift($datetime) { return Mage::app()->getLocale() ->utcDate(null, $datetime, true, Varien_Date::DATETIME_INTERNAL_FORMAT) ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT); } }
// RUN: %clang_cc1 -triple sparc-unknown-unknown -emit-llvm %s -o - | FileCheck %s // CHECK-LABEL: define { float, float } @p({ float, float }* byval align 4 %a, { float, float }* byval align 4 %b) #0 { float __complex__ p (float __complex__ a, float __complex__ b) { } // CHECK-LABEL: define { double, double } @q({ double, double }* byval align 8 %a, { double, double }* byval align 8 %b) #0 { double __complex__ q (double __complex__ a, double __complex__ b) { } // CHECK-LABEL: define { i64, i64 } @r({ i64, i64 }* byval align 8 %a, { i64, i64 }* byval align 8 %b) #0 { long long __complex__ r (long long __complex__ a, long long __complex__ b) { }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package discovery; import org.codehaus.jackson.map.annotate.JsonRootName; /** * In a real application, the Service payload will most likely * be more detailed than this. But, this gives a good example. */ @JsonRootName("details") public class InstanceDetails { private String description; public InstanceDetails() { this(""); } public InstanceDetails(String description) { this.description = description; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.distribution.monitor.impl; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import org.apache.sling.distribution.agent.DistributionAgent; import org.apache.sling.distribution.agent.DistributionAgentState; import org.junit.Test; /** * Test case for {@link ForwardDistributionAgentMBean} */ public class ForwardDistributionAgentMBeanTest { @Test public void verifyMBeanExposedValues() { DistributionAgent agent = mock(DistributionAgent.class); when(agent.getState()).thenReturn(DistributionAgentState.RUNNING); Map<String, Object> osgiConfiguration = new HashMap<String, Object>(); osgiConfiguration.put("name", "#distributionagent"); osgiConfiguration.put("title", "Just a test title"); osgiConfiguration.put("details", "Just test details"); osgiConfiguration.put("enabled", true); osgiConfiguration.put("serviceName", "@distributionagent"); osgiConfiguration.put("log.level", "error"); osgiConfiguration.put("allowed.roots", "admin"); osgiConfiguration.put("queue.processing.enabled", true); osgiConfiguration.put("packageImporter.endpoints", "endpoints"); osgiConfiguration.put("passiveQueues", "passiveQueues"); osgiConfiguration.put("priorityQueues", "priorityQueues"); osgiConfiguration.put("retry.strategy", "none"); osgiConfiguration.put("retry.attempts", 30); osgiConfiguration.put("queue.provider", "jobsProvider"); osgiConfiguration.put("async.delivery", true); ForwardDistributionAgentMBean mBean = new ForwardDistributionAgentMBeanImpl(agent, osgiConfiguration); assertEquals(osgiConfiguration.get("name"), mBean.getName()); assertEquals(osgiConfiguration.get("title"), mBean.getTitle()); assertEquals(osgiConfiguration.get("details"), mBean.getDetails()); assertEquals(osgiConfiguration.get("enabled"), mBean.isEnabled()); assertEquals(osgiConfiguration.get("serviceName"), mBean.getServiceName()); assertEquals(osgiConfiguration.get("log.level"), mBean.getLogLevel()); assertEquals(osgiConfiguration.get("allowed.roots"), mBean.getAllowedRoots()); assertEquals(osgiConfiguration.get("queue.processing.enabled"), mBean.isQueueProcessingEnabled()); assertEquals(osgiConfiguration.get("packageImporter.endpoints"), mBean.getPackageImporterEndpoints()); assertEquals(osgiConfiguration.get("passiveQueues"), mBean.getPassiveQueues()); assertEquals(osgiConfiguration.get("priorityQueues"), mBean.getPriorityQueues()); assertEquals(osgiConfiguration.get("retry.strategy"), mBean.getRetryStrategy()); assertEquals(osgiConfiguration.get("retry.attempts"), mBean.getRetryAttempts()); assertEquals(osgiConfiguration.get("queue.provider"), mBean.getQueueProvider()); assertEquals(osgiConfiguration.get("async.delivery"), mBean.isAsyncDelivery()); assertEquals(agent.getState().name().toLowerCase(), mBean.getStatus()); } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.JavaExtensions { using System.Collections.Generic; using System.Linq; using IDictionary = System.Collections.IDictionary; using ObsoleteAttribute = System.ObsoleteAttribute; public static class DictionaryExtensions { [Obsolete] public static bool containsKey( this IDictionary map, object key ) { return map.Contains( key ); } [Obsolete] public static object get( this IDictionary map, object key ) { return map[key]; } public static TValue get<TKey, TValue>( this IDictionary<TKey, TValue> map, TKey key ) { TValue value; if ( map.TryGetValue( key, out value ) ) return value; if ( typeof( TValue ).IsValueType ) throw new KeyNotFoundException(); return default( TValue ); } // disambiguates public static TValue get<TKey, TValue>( this Dictionary<TKey, TValue> map, TKey key ) { TValue value; if ( map.TryGetValue( key, out value ) ) return value; if ( typeof( TValue ).IsValueType ) throw new KeyNotFoundException(); return default( TValue ); } public static TValue get<TKey, TValue>( this SortedList<TKey, TValue> map, TKey key ) { TValue value; if ( map.TryGetValue( key, out value ) ) return value; if ( typeof( TValue ).IsValueType ) throw new KeyNotFoundException(); return default( TValue ); } [Obsolete] public static void put( this IDictionary map, object key, object value ) { map[key] = value; } [Obsolete] public static void put<TKey, TValue>( this IDictionary<TKey, TValue> map, TKey key, TValue value ) { map[key] = value; } [Obsolete] public static void put<TKey, TValue>( this Dictionary<TKey, TValue> map, TKey key, TValue value ) { map[key] = value; } [Obsolete] public static HashSet<object> keySet( this IDictionary map ) { return new HashSet<object>( map.Keys.Cast<object>() ); } [Obsolete] public static HashSet<TKey> keySet<TKey, TValue>( this IDictionary<TKey, TValue> map ) { return new HashSet<TKey>( map.Keys ); } // disambiguates for Dictionary, which implements both IDictionary<T,K> and IDictionary [Obsolete] public static HashSet<TKey> keySet<TKey, TValue>( this Dictionary<TKey, TValue> map ) { return new HashSet<TKey>( map.Keys ); } [Obsolete] public static HashSet<object> keySet<TKey, TValue>( this SortedList<TKey, TValue> map ) { return new HashSet<object>( map.Keys.Cast<object>() ); } } }
// Copyright 2015 go-swagger maintainers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package loads import ( "bytes" "encoding/json" "fmt" "net/url" "path/filepath" "github.com/go-openapi/analysis" "github.com/go-openapi/loads/fmts" "github.com/go-openapi/spec" "github.com/go-openapi/swag" ) // JSONDoc loads a json document from either a file or a remote url func JSONDoc(path string) (json.RawMessage, error) { data, err := swag.LoadFromFileOrHTTP(path) if err != nil { return nil, err } return json.RawMessage(data), nil } // DocLoader represents a doc loader type type DocLoader func(string) (json.RawMessage, error) // DocMatcher represents a predicate to check if a loader matches type DocMatcher func(string) bool var ( loaders *loader defaultLoader *loader ) func init() { defaultLoader = &loader{Match: func(_ string) bool { return true }, Fn: JSONDoc} loaders = defaultLoader spec.PathLoader = loaders.Fn AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc) } // AddLoader for a document func AddLoader(predicate DocMatcher, load DocLoader) { prev := loaders loaders = &loader{ Match: predicate, Fn: load, Next: prev, } spec.PathLoader = loaders.Fn } type loader struct { Fn DocLoader Match DocMatcher Next *loader } // JSONSpec loads a spec from a json document func JSONSpec(path string) (*Document, error) { data, err := JSONDoc(path) if err != nil { return nil, err } // convert to json return Analyzed(json.RawMessage(data), "") } // Document represents a swagger spec document type Document struct { // specAnalyzer Analyzer *analysis.Spec spec *spec.Swagger specFilePath string origSpec *spec.Swagger schema *spec.Schema raw json.RawMessage } // Spec loads a new spec document func Spec(path string) (*Document, error) { specURL, err := url.Parse(path) if err != nil { return nil, err } var lastErr error for l := loaders.Next; l != nil; l = l.Next { if loaders.Match(specURL.Path) { b, err2 := loaders.Fn(path) if err2 != nil { lastErr = err2 continue } doc, err := Analyzed(b, "") if err != nil { return nil, err } if doc != nil { doc.specFilePath = path } return doc, nil } } if lastErr != nil { return nil, lastErr } b, err := defaultLoader.Fn(path) if err != nil { return nil, err } document, err := Analyzed(b, "") if document != nil { document.specFilePath = path } return document, err } // Analyzed creates a new analyzed spec document func Analyzed(data json.RawMessage, version string) (*Document, error) { if version == "" { version = "2.0" } if version != "2.0" { return nil, fmt.Errorf("spec version %q is not supported", version) } raw := data trimmed := bytes.TrimSpace(data) if len(trimmed) > 0 { if trimmed[0] != '{' && trimmed[0] != '[' { yml, err := fmts.BytesToYAMLDoc(trimmed) if err != nil { return nil, fmt.Errorf("analyzed: %v", err) } d, err := fmts.YAMLToJSON(yml) if err != nil { return nil, fmt.Errorf("analyzed: %v", err) } raw = d } } swspec := new(spec.Swagger) if err := json.Unmarshal(raw, swspec); err != nil { return nil, err } origsqspec := new(spec.Swagger) if err := json.Unmarshal(raw, origsqspec); err != nil { return nil, err } d := &Document{ Analyzer: analysis.New(swspec), schema: spec.MustLoadSwagger20Schema(), spec: swspec, raw: raw, origSpec: origsqspec, } return d, nil } // Expanded expands the ref fields in the spec document and returns a new spec document func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { swspec := new(spec.Swagger) if err := json.Unmarshal(d.raw, swspec); err != nil { return nil, err } var expandOptions *spec.ExpandOptions if len(options) > 0 { expandOptions = options[1] } else { expandOptions = &spec.ExpandOptions{ RelativeBase: filepath.Dir(d.specFilePath), } } if err := spec.ExpandSpec(swspec, expandOptions); err != nil { return nil, err } dd := &Document{ Analyzer: analysis.New(swspec), spec: swspec, schema: spec.MustLoadSwagger20Schema(), raw: d.raw, origSpec: d.origSpec, } return dd, nil } // BasePath the base path for this spec func (d *Document) BasePath() string { return d.spec.BasePath } // Version returns the version of this spec func (d *Document) Version() string { return d.spec.Swagger } // Schema returns the swagger 2.0 schema func (d *Document) Schema() *spec.Schema { return d.schema } // Spec returns the swagger spec object model func (d *Document) Spec() *spec.Swagger { return d.spec } // Host returns the host for the API func (d *Document) Host() string { return d.spec.Host } // Raw returns the raw swagger spec as json bytes func (d *Document) Raw() json.RawMessage { return d.raw } func (d *Document) OrigSpec() *spec.Swagger { return d.origSpec } // ResetDefinitions gives a shallow copy with the models reset func (d *Document) ResetDefinitions() *Document { defs := make(map[string]spec.Schema, len(d.origSpec.Definitions)) for k, v := range d.origSpec.Definitions { defs[k] = v } d.spec.Definitions = defs return d } // Pristine creates a new pristine document instance based on the input data func (d *Document) Pristine() *Document { dd, _ := Analyzed(d.Raw(), d.Version()) return dd } // SpecFilePath returns the file path of the spec if one is defined func (d *Document) SpecFilePath() string { return d.specFilePath }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.util; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; /** Tests for the {@link ArrayUtils}. */ public class ArrayUtilsTest extends TestLogger { @Test public void concatWithEmptyArray() { String[] emptyArray = new String[] {}; String[] nonEmptyArray = new String[] {"some value"}; assertThat( "Should return the non empty array", ArrayUtils.concat(emptyArray, nonEmptyArray), sameInstance(nonEmptyArray)); assertThat( "Should return the non empty array", ArrayUtils.concat(nonEmptyArray, emptyArray), sameInstance(nonEmptyArray)); } @Test public void concatArrays() { String[] array1 = new String[] {"A", "B", "C", "D", "E", "F", "G"}; String[] array2 = new String[] {"1", "2", "3"}; assertThat( ArrayUtils.concat(array1, array2), is(new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3"})); assertThat( ArrayUtils.concat(array2, array1), is(new String[] {"1", "2", "3", "A", "B", "C", "D", "E", "F", "G"})); } }
// aux-build:derive-foo.rs // pp-exact // Testing that both the inner item and next outer item are // preserved, and that the first outer item parsed in main is not // accidentally carried over to each inner function #[macro_use] extern crate derive_foo; #[derive(Foo)] struct X; #[derive(Foo)] #[Bar] struct Y; #[derive(Foo)] struct WithRef { x: X, #[Bar] y: Y, } #[derive(Foo)] enum Enum { #[Bar] Asdf, Qwerty, } fn main() { }
#ifndef TESTS_ARC4_H #define TESTS_ARC4_H #include <stddef.h> #include <stdint.h> /* Alleged RC4 algorithm encryption state. */ struct arc4 { uint8_t s[256]; uint8_t i, j; }; void arc4_init (struct arc4 *, const void *, size_t); void arc4_crypt (struct arc4 *, void *, size_t); #endif /* tests/arc4.h */
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.components.runtime; import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.common.PropertyTypeConstants; import com.google.appinventor.components.common.YaVersion; import com.google.appinventor.components.runtime.util.ErrorMessages; import com.google.appinventor.components.runtime.util.FileUtil; import android.media.MediaRecorder; import android.media.MediaRecorder.OnErrorListener; import android.media.MediaRecorder.OnInfoListener; import android.os.Environment; import android.util.Log; import java.io.IOException; /** * Multimedia component that records audio using * {@link android.media.MediaRecorder}. * */ @DesignerComponent(version = YaVersion.SOUND_RECORDER_COMPONENT_VERSION, description = "<p>Multimedia component that records audio.</p>", category = ComponentCategory.MEDIA, nonVisible = true, iconName = "images/soundRecorder.png") @SimpleObject @UsesPermissions(permissionNames = "android.permission.RECORD_AUDIO") public final class SoundRecorder extends AndroidNonvisibleComponent implements Component, OnErrorListener, OnInfoListener { private static final String TAG = "SoundRecorder"; // the path to the savedRecording // if it is the null string, the recorder will generate a path // note that this is also initialized to "" in the designer private String savedRecording = ""; /** * This class encapsulates the required state during recording. */ private class RecordingController { final MediaRecorder recorder; // file is the same as savedRecording, but we'll keep it local to the // RecordingController for future flexibility final String file; RecordingController(String savedRecording) throws IOException { // pick a pathname if none was specified file = (savedRecording.equals("")) ? FileUtil.getRecordingFile("3gp").getAbsolutePath() : savedRecording; recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); Log.i(TAG, "Setting output file to " + file); recorder.setOutputFile(file); Log.i(TAG, "preparing"); recorder.prepare(); recorder.setOnErrorListener(SoundRecorder.this); recorder.setOnInfoListener(SoundRecorder.this); } void start() throws IllegalStateException { Log.i(TAG, "starting"); try { recorder.start(); } catch (IllegalStateException e) { // This is the error produced when there are two recorders running. // There might be other causes, but we don't know them. // Using Log.e will log a stack trace, so we can investigate Log.e(TAG, "got IllegalStateException. Are there two recorders running?", e); // Pass back a message detail for dispatchErrorOccurred to // show at user level throw (new IllegalStateException("Is there another recording running?")); } } void stop() { recorder.setOnErrorListener(null); recorder.setOnInfoListener(null); recorder.stop(); recorder.reset(); recorder.release(); } } /* * This is null when not recording, and contains the active RecordingState * when recording. */ private RecordingController controller; public SoundRecorder(final ComponentContainer container) { super(container.$form()); } /** * Returns the path to the saved recording * * @return savedRecording path to recording */ @SimpleProperty( description = "Specifies the path to the file where the recording is stored. " + "If this proprety is the empty string, then starting a recording will create a file in " + "an appropriate location.", category = PropertyCategory.BEHAVIOR) public String SavedRecording() { return savedRecording; } /** * Specifies the path to the saved recording displayed by the label. * * @param pathName path to saved recording */ @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "") @SimpleProperty public void SavedRecording(String pathName) { savedRecording = pathName; } /** * Starts recording. */ @SimpleFunction public void Start() { if (controller != null) { Log.i(TAG, "Start() called, but already recording to " + controller.file); return; } Log.i(TAG, "Start() called"); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { form.dispatchErrorOccurredEvent( this, "Start", ErrorMessages.ERROR_MEDIA_EXTERNAL_STORAGE_NOT_AVAILABLE); return; } try { controller = new RecordingController(savedRecording); } catch (Throwable t) { form.dispatchErrorOccurredEvent( this, "Start", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } try { controller.start(); } catch (Throwable t) { // I'm commenting the next line out because stop can throw an error, and // it's not clear to me how to handle that. // controller.stop(); controller = null; form.dispatchErrorOccurredEvent( this, "Start", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } StartedRecording(); } @Override public void onError(MediaRecorder affectedRecorder, int what, int extra) { if (controller == null || affectedRecorder != controller.recorder) { Log.w(TAG, "onError called with wrong recorder. Ignoring."); return; } form.dispatchErrorOccurredEvent(this, "onError", ErrorMessages.ERROR_SOUND_RECORDER); try { controller.stop(); } catch (Throwable e) { Log.w(TAG, e.getMessage()); } finally { controller = null; StoppedRecording(); } } @Override public void onInfo(MediaRecorder affectedRecorder, int what, int extra) { if (controller == null || affectedRecorder != controller.recorder) { Log.w(TAG, "onInfo called with wrong recorder. Ignoring."); return; } Log.i(TAG, "Recoverable condition while recording. Will attempt to stop normally."); controller.recorder.stop(); } /** * Stops recording. */ @SimpleFunction public void Stop() { if (controller == null) { Log.i(TAG, "Stop() called, but already stopped."); return; } try { Log.i(TAG, "Stop() called"); Log.i(TAG, "stopping"); controller.stop(); Log.i(TAG, "Firing AfterSoundRecorded with " + controller.file); AfterSoundRecorded(controller.file); } catch (Throwable t) { form.dispatchErrorOccurredEvent(this, "Stop", ErrorMessages.ERROR_SOUND_RECORDER); } finally { controller = null; StoppedRecording(); } } @SimpleEvent(description = "Provides the location of the newly created sound.") public void AfterSoundRecorded(final String sound) { EventDispatcher.dispatchEvent(this, "AfterSoundRecorded", sound); } @SimpleEvent(description = "Indicates that the recorder has started, and can be stopped.") public void StartedRecording() { EventDispatcher.dispatchEvent(this, "StartedRecording"); } @SimpleEvent(description = "Indicates that the recorder has stopped, and can be started again.") public void StoppedRecording() { EventDispatcher.dispatchEvent(this, "StoppedRecording"); } }
using NUnit.Framework; using Nest.Tests.MockData.Domain; namespace Nest.Tests.Unit.Search.Query.Singles { [TestFixture] public class HasChildQueryJson { [Test] public void HasChildThisQuery() { var s = new SearchDescriptor<ElasticsearchProject>() .From(0) .Size(10) .Query(q => q .HasChild<Person>(fz => fz .Name("named_query") .Query(qq=>qq.Term(f=>f.FirstName, "john")) .Score(ChildScoreType.Average) ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { has_child: { _name: ""named_query"", type: ""person"", score_type: ""avg"", query: { term: { firstName: { value: ""john"" } } } }}}"; Assert.True(json.JsonEquals(expected), json); } [Test] public void HasChildOverrideTypeQuery() { var s = new SearchDescriptor<ElasticsearchProject>() .From(0) .Size(10) .Query(q => q .HasChild<Person>(fz => fz .Query(qq => qq.Term(f => f.FirstName, "john")) .Type("sillypeople") ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { has_child: { type: ""sillypeople"", query: { term: { firstName: { value: ""john"" } } } }}}"; Assert.True(json.JsonEquals(expected), json); } } }
// +build !providerless /* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package storageaccountclient import ( "context" "fmt" "net/http" "time" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/to" "k8s.io/client-go/util/flowcontrol" "k8s.io/klog/v2" azclients "k8s.io/legacy-cloud-providers/azure/clients" "k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/retry" ) var _ Interface = &Client{} // Client implements StorageAccount client Interface. type Client struct { armClient armclient.Interface subscriptionID string // Rate limiting configures. rateLimiterReader flowcontrol.RateLimiter rateLimiterWriter flowcontrol.RateLimiter // ARM throttling configures. RetryAfterReader time.Time RetryAfterWriter time.Time } // New creates a new StorageAccount client with ratelimiting. func New(config *azclients.ClientConfig) *Client { baseURI := config.ResourceManagerEndpoint authorizer := config.Authorizer armClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff) rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) klog.V(2).Infof("Azure StorageAccountClient (read ops) using rate limit config: QPS=%g, bucket=%d", config.RateLimitConfig.CloudProviderRateLimitQPS, config.RateLimitConfig.CloudProviderRateLimitBucket) klog.V(2).Infof("Azure StorageAccountClient (write ops) using rate limit config: QPS=%g, bucket=%d", config.RateLimitConfig.CloudProviderRateLimitQPSWrite, config.RateLimitConfig.CloudProviderRateLimitBucketWrite) client := &Client{ armClient: armClient, rateLimiterReader: rateLimiterReader, rateLimiterWriter: rateLimiterWriter, subscriptionID: config.SubscriptionID, } return client } // GetProperties gets properties of the StorageAccount. func (c *Client) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error) { mc := metrics.NewMetricContext("storage_account", "get", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterReader.TryAccept() { mc.RateLimitedCount() return storage.Account{}, retry.GetRateLimitError(false, "StorageAccountGet") } // Report errors if the client is throttled. if c.RetryAfterReader.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountGet", "client throttled", c.RetryAfterReader) return storage.Account{}, rerr } result, rerr := c.getStorageAccount(ctx, resourceGroupName, accountName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterReader = rerr.RetryAfter } return result, rerr } return result, nil } // getStorageAccount gets properties of the StorageAccount. func (c *Client) getStorageAccount(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error) { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) result := storage.Account{} response, rerr := c.armClient.GetResource(ctx, resourceID, "") defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.get.request", resourceID, rerr.Error()) return result, rerr } err := autorest.Respond( response, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result)) if err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.get.respond", resourceID, err) return result, retry.GetError(response, err) } result.Response = autorest.Response{Response: response} return result, nil } // ListKeys get a list of storage account keys. func (c *Client) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error) { mc := metrics.NewMetricContext("storage_account", "list_keys", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterReader.TryAccept() { mc.RateLimitedCount() return storage.AccountListKeysResult{}, retry.GetRateLimitError(false, "StorageAccountListKeys") } // Report errors if the client is throttled. if c.RetryAfterReader.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountListKeys", "client throttled", c.RetryAfterReader) return storage.AccountListKeysResult{}, rerr } result, rerr := c.listStorageAccountKeys(ctx, resourceGroupName, accountName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterReader = rerr.RetryAfter } return result, rerr } return result, nil } // listStorageAccountKeys get a list of storage account keys. func (c *Client) listStorageAccountKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error) { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) result := storage.AccountListKeysResult{} response, rerr := c.armClient.PostResource(ctx, resourceID, "listKeys", struct{}{}) defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.listkeys.request", resourceID, rerr.Error()) return result, rerr } err := autorest.Respond( response, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result)) if err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.listkeys.respond", resourceID, err) return result, retry.GetError(response, err) } result.Response = autorest.Response{Response: response} return result, nil } // Create creates a StorageAccount. func (c *Client) Create(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error { mc := metrics.NewMetricContext("storage_account", "create", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterWriter.TryAccept() { mc.RateLimitedCount() return retry.GetRateLimitError(true, "StorageAccountCreate") } // Report errors if the client is throttled. if c.RetryAfterWriter.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountCreate", "client throttled", c.RetryAfterWriter) return rerr } rerr := c.createStorageAccount(ctx, resourceGroupName, accountName, parameters) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterWriter = rerr.RetryAfter } return rerr } return nil } // createStorageAccount creates or updates a StorageAccount. func (c *Client) createStorageAccount(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) response, rerr := c.armClient.PutResource(ctx, resourceID, parameters) defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.put.request", resourceID, rerr.Error()) return rerr } if response != nil && response.StatusCode != http.StatusNoContent { _, rerr = c.createResponder(response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.put.respond", resourceID, rerr.Error()) return rerr } } return nil } func (c *Client) createResponder(resp *http.Response) (*storage.Account, *retry.Error) { result := &storage.Account{} err := autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result)) result.Response = autorest.Response{Response: resp} return result, retry.GetError(resp, err) } // Delete deletes a StorageAccount by name. func (c *Client) Delete(ctx context.Context, resourceGroupName string, accountName string) *retry.Error { mc := metrics.NewMetricContext("storage_account", "delete", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterWriter.TryAccept() { mc.RateLimitedCount() return retry.GetRateLimitError(true, "StorageAccountDelete") } // Report errors if the client is throttled. if c.RetryAfterWriter.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountDelete", "client throttled", c.RetryAfterWriter) return rerr } rerr := c.deleteStorageAccount(ctx, resourceGroupName, accountName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterWriter = rerr.RetryAfter } return rerr } return nil } // deleteStorageAccount deletes a PublicIPAddress by name. func (c *Client) deleteStorageAccount(ctx context.Context, resourceGroupName string, accountName string) *retry.Error { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) return c.armClient.DeleteResource(ctx, resourceID, "") } // ListByResourceGroup get a list storage accounts by resourceGroup. func (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) { mc := metrics.NewMetricContext("storage_account", "list_by_resource_group", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterReader.TryAccept() { mc.RateLimitedCount() return nil, retry.GetRateLimitError(false, "StorageAccountListByResourceGroup") } // Report errors if the client is throttled. if c.RetryAfterReader.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountListByResourceGroup", "client throttled", c.RetryAfterReader) return nil, rerr } result, rerr := c.ListStorageAccountByResourceGroup(ctx, resourceGroupName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterReader = rerr.RetryAfter } return result, rerr } return result, nil } // ListStorageAccountByResourceGroup get a list storage accounts by resourceGroup. func (c *Client) ListStorageAccountByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) { resourceID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts", autorest.Encode("path", c.subscriptionID), autorest.Encode("path", resourceGroupName)) result := make([]storage.Account, 0) page := &AccountListResultPage{} page.fn = c.listNextResults resp, rerr := c.armClient.GetResource(ctx, resourceID, "") defer c.armClient.CloseResponse(ctx, resp) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.list.request", resourceID, rerr.Error()) return result, rerr } var err error page.alr, err = c.listResponder(resp) if err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.list.respond", resourceID, err) return result, retry.GetError(resp, err) } for page.NotDone() { result = append(result, *page.Response().Value...) if err = page.NextWithContext(ctx); err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.list.next", resourceID, err) return result, retry.GetError(page.Response().Response.Response, err) } } return result, nil } func (c *Client) listResponder(resp *http.Response) (result storage.AccountListResult, err error) { err = autorest.Respond( resp, autorest.ByIgnoring(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result)) result.Response = autorest.Response{Response: resp} return } // StorageAccountResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (c *Client) StorageAccountResultPreparer(ctx context.Context, lr storage.AccountListResult) (*http.Request, error) { if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { return nil, nil } decorators := []autorest.PrepareDecorator{ autorest.WithBaseURL(to.String(lr.NextLink)), } return c.armClient.PrepareGetRequest(ctx, decorators...) } // listNextResults retrieves the next set of results, if any. func (c *Client) listNextResults(ctx context.Context, lastResults storage.AccountListResult) (result storage.AccountListResult, err error) { req, err := c.StorageAccountResultPreparer(ctx, lastResults) if err != nil { return result, autorest.NewErrorWithError(err, "storageaccount", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, rerr := c.armClient.Send(ctx, req) defer c.armClient.CloseResponse(ctx, resp) if rerr != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(rerr.Error(), "storageaccount", "listNextResults", resp, "Failure sending next results request") } result, err = c.listResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "storageaccount", "listNextResults", resp, "Failure responding to next results request") } return } // AccountListResultPage contains a page of Account values. type AccountListResultPage struct { fn func(context.Context, storage.AccountListResult) (storage.AccountListResult, error) alr storage.AccountListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *AccountListResultPage) NextWithContext(ctx context.Context) (err error) { next, err := page.fn(ctx, page.alr) if err != nil { return err } page.alr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *AccountListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page AccountListResultPage) NotDone() bool { return !page.alr.IsEmpty() } // Response returns the raw server response from the last page request. func (page AccountListResultPage) Response() storage.AccountListResult { return page.alr } // Values returns the slice of values for the current page or nil if there are no values. func (page AccountListResultPage) Values() []storage.Account { if page.alr.IsEmpty() { return nil } return *page.alr.Value }
/* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.appserver.sample.chad.data; /** * POJO representing a poll result */ public class ChadPollResult { private int totalNumberOfVotes; private String pollId; private String pollTitle; private String pollDescription; private boolean isPollStopped; private boolean isSingleVote; private ChadChoice[] orderedChoices; public ChadPollResult() { } public ChadChoice[] getOrderedChoices() { return orderedChoices; } public void setOrderedChoices(ChadChoice[] orderedChoices) { this.orderedChoices = orderedChoices; } public String getPollDescription() { return pollDescription; } public void setPollDescription(String pollDescription) { this.pollDescription = pollDescription; } public String getPollId() { return pollId; } public void setPollId(String pollId) { this.pollId = pollId; } public String getPollTitle() { return pollTitle; } public void setPollTitle(String pollTitle) { this.pollTitle = pollTitle; } public int getTotalNumberOfVotes() { return totalNumberOfVotes; } public void setTotalNumberOfVotes(int totalNumberOfVotes) { this.totalNumberOfVotes = totalNumberOfVotes; } public boolean isPollStopped() { return isPollStopped; } public void setPollStopped(boolean pollStopped) { isPollStopped = pollStopped; } public boolean isSingleVote() { return isSingleVote; } public void setSingleVote(boolean singleVote) { isSingleVote = singleVote; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.testsuites; import junit.framework.TestSuite; import org.apache.ignite.internal.processors.query.h2.H2IndexingGeoSelfTest; import org.apache.ignite.internal.processors.query.h2.H2IndexingSegmentedGeoSelfTest; /** * Geospatial indexing tests. */ public class GeoSpatialIndexingTestSuite extends TestSuite { /** * @return Test suite. * @throws Exception Thrown in case of the failure. */ public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite("H2 Geospatial Indexing Test Suite"); suite.addTestSuite(H2IndexingGeoSelfTest.class); suite.addTestSuite(H2IndexingSegmentedGeoSelfTest.class); return suite; } }
package org.zstack.test.storage.backup; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.zstack.core.Platform; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.componentloader.ComponentLoader; import org.zstack.core.db.DatabaseFacade; import org.zstack.header.message.MessageReply; import org.zstack.header.storage.backup.*; import org.zstack.test.Api; import org.zstack.test.ApiSenderException; import org.zstack.test.DBUtil; import org.zstack.test.WebBeanConstructor; import org.zstack.test.deployer.Deployer; import org.zstack.utils.Utils; import org.zstack.utils.data.SizeUnit; import org.zstack.utils.logging.CLogger; import java.util.concurrent.TimeUnit; /* * 1. add backup storage with 1G available capacity * 2. allocate 500M with faked uuid * * confirm: * failed */ public class TestAllocateBackupStorage3 { CLogger logger = Utils.getLogger(TestAllocateBackupStorage3.class); Deployer deployer; Api api; ComponentLoader loader; CloudBus bus; DatabaseFacade dbf; @Before public void setUp() throws Exception { DBUtil.reDeployDB(); WebBeanConstructor con = new WebBeanConstructor(); deployer = new Deployer("deployerXml/backupStorage/TestAllocateBackupStorage.xml", con); deployer.build(); api = deployer.getApi(); loader = deployer.getComponentLoader(); bus = loader.getComponent(CloudBus.class); dbf = loader.getComponent(DatabaseFacade.class); } @Test public void test() throws ApiSenderException, InterruptedException { BackupStorageInventory bsinv = deployer.backupStorages.get("backup1"); long size = SizeUnit.MEGABYTE.toByte(500); AllocateBackupStorageMsg msg = new AllocateBackupStorageMsg(); msg.setBackupStorageUuid(Platform.getUuid()); msg.setSize(size); bus.makeTargetServiceIdByResourceUuid(msg, BackupStorageConstant.SERVICE_ID, bsinv.getUuid()); msg.setTimeout(TimeUnit.SECONDS.toMillis(15)); MessageReply reply = bus.call(msg); Assert.assertFalse(reply.isSuccess()); Assert.assertEquals(BackupStorageErrors.ALLOCATE_ERROR.toString(), reply.getError().getCode()); BackupStorageVO vo = dbf.findByUuid(bsinv.getUuid(), BackupStorageVO.class); Assert.assertEquals(bsinv.getAvailableCapacity(), vo.getAvailableCapacity()); } }
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy; import com.google.inject.AbstractModule; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.template.soy.SoyFileSet.SoyFileSetFactory; import com.google.template.soy.basicdirectives.BasicDirectivesModule; import com.google.template.soy.basicfunctions.BasicFunctionsModule; import com.google.template.soy.bididirectives.BidiDirectivesModule; import com.google.template.soy.bidifunctions.BidiFunctionsModule; import com.google.template.soy.i18ndirectives.I18nDirectivesModule; import com.google.template.soy.javasrc.internal.JavaSrcModule; import com.google.template.soy.jssrc.internal.JsSrcModule; import com.google.template.soy.parsepasses.CheckFunctionCallsVisitor; import com.google.template.soy.parsepasses.PerformAutoescapeVisitor; import com.google.template.soy.parsepasses.contextautoesc.ContextualAutoescaper; import com.google.template.soy.shared.internal.SharedModule; import com.google.template.soy.tofu.internal.TofuModule; /** * Guice module for Soy's programmatic interface. * * @author Kai Huang */ public class SoyModule extends AbstractModule { @Override protected void configure() { // Install requisite modules. install(new SharedModule()); install(new TofuModule()); install(new JsSrcModule()); install(new JavaSrcModule()); // Bindings for when explicit dependencies are required. bind(CheckFunctionCallsVisitor.class); bind(ContextualAutoescaper.class); bind(PerformAutoescapeVisitor.class); // Install default directive and function modules. install(new BasicDirectivesModule()); install(new BidiDirectivesModule()); install(new BasicFunctionsModule()); install(new BidiFunctionsModule()); install(new I18nDirectivesModule()); // Bind providers of factories (created via assisted inject). install(new FactoryModuleBuilder().build(SoyFileSetFactory.class)); // The static injection of SoyFileSetFactory into SoyFileSet.Builder is what allows the Soy // compiler to use Guice even if the user of the Soy API does not use Guice. requestStaticInjection(SoyFileSet.Builder.class); // Mark the fact that Guice has been initialized. requestStaticInjection(GuiceInitializer.class); } }
# Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common utilities for tests of the Cython layer of gRPC Python.""" import collections import threading from grpc._cython import cygrpc RPC_COUNT = 4000 EMPTY_FLAGS = 0 INVOCATION_METADATA = ( ('client-md-key', 'client-md-key'), ('client-md-key-bin', b'\x00\x01' * 3000), ) INITIAL_METADATA = ( ('server-initial-md-key', 'server-initial-md-value'), ('server-initial-md-key-bin', b'\x00\x02' * 3000), ) TRAILING_METADATA = ( ('server-trailing-md-key', 'server-trailing-md-value'), ('server-trailing-md-key-bin', b'\x00\x03' * 3000), ) class QueueDriver(object): def __init__(self, condition, completion_queue): self._condition = condition self._completion_queue = completion_queue self._due = collections.defaultdict(int) self._events = collections.defaultdict(list) def add_due(self, tags): if not self._due: def in_thread(): while True: event = self._completion_queue.poll() with self._condition: self._events[event.tag].append(event) self._due[event.tag] -= 1 self._condition.notify_all() if self._due[event.tag] <= 0: self._due.pop(event.tag) if not self._due: return thread = threading.Thread(target=in_thread) thread.start() for tag in tags: self._due[tag] += 1 def event_with_tag(self, tag): with self._condition: while True: if self._events[tag]: return self._events[tag].pop(0) else: self._condition.wait() def execute_many_times(behavior): return tuple(behavior() for _ in range(RPC_COUNT)) class OperationResult( collections.namedtuple('OperationResult', ( 'start_batch_result', 'completion_type', 'success', ))): pass SUCCESSFUL_OPERATION_RESULT = OperationResult( cygrpc.CallError.ok, cygrpc.CompletionType.operation_complete, True) class RpcTest(object): def setUp(self): self.server_completion_queue = cygrpc.CompletionQueue() self.server = cygrpc.Server([(b'grpc.so_reuseport', 0)]) self.server.register_completion_queue(self.server_completion_queue) port = self.server.add_http2_port(b'[::]:0') self.server.start() self.channel = cygrpc.Channel('localhost:{}'.format(port).encode(), [], None) self._server_shutdown_tag = 'server_shutdown_tag' self.server_condition = threading.Condition() self.server_driver = QueueDriver(self.server_condition, self.server_completion_queue) with self.server_condition: self.server_driver.add_due({ self._server_shutdown_tag, }) self.client_condition = threading.Condition() self.client_completion_queue = cygrpc.CompletionQueue() self.client_driver = QueueDriver(self.client_condition, self.client_completion_queue) def tearDown(self): self.server.shutdown(self.server_completion_queue, self._server_shutdown_tag) self.server.cancel_all_calls()
/*============================================================================= Copyright (c) 2011 Eric Niebler Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_SEGMENTED_END_IMPL_HPP_INCLUDED) #define BOOST_FUSION_SEGMENTED_END_IMPL_HPP_INCLUDED #include <boost/fusion/support/config.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/fusion/sequence/intrinsic_fwd.hpp> #include <boost/fusion/container/list/cons_fwd.hpp> #include <boost/fusion/support/is_segmented.hpp> namespace boost { namespace fusion { template <typename First, typename Last> struct iterator_range; }} namespace boost { namespace fusion { namespace detail { //auto segmented_end_impl( seq, stack ) //{ // assert(is_segmented(seq)); // auto it = end(segments(seq)); // return cons(iterator_range(it, it), stack); //} template <typename Sequence, typename Stack> struct segmented_end_impl { BOOST_MPL_ASSERT((traits::is_segmented<Sequence>)); typedef typename result_of::end< typename remove_reference< typename add_const< typename result_of::segments<Sequence>::type >::type >::type >::type end_type; typedef iterator_range<end_type, end_type> pair_type; typedef cons<pair_type, Stack> type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static pair_type make_pair(end_type end) { return pair_type(end, end); } BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(Sequence & seq, Stack stack) { return type( make_pair(fusion::end(fusion::segments(seq))), stack); } }; }}} #endif