code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
/**
* File containing the Content class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version 2014.11.1
*/
namespace eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\Parser;
use eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\AbstractParser;
use eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\SiteAccessAware\ContextualizerInterface;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
/**
* Configuration parser handling content related config
*/
class Content extends AbstractParser
{
/**
* Adds semantic configuration definition.
*
* @param \Symfony\Component\Config\Definition\Builder\NodeBuilder $nodeBuilder Node just under ezpublish.system.<siteaccess>
*
* @return void
*/
public function addSemanticConfig( NodeBuilder $nodeBuilder )
{
$nodeBuilder
->arrayNode( 'content' )
->info( 'Content related configuration' )
->children()
->booleanNode( 'view_cache' )->defaultValue( true )->end()
->booleanNode( 'ttl_cache' )->defaultValue( true )->end()
->scalarNode( 'default_ttl' )->info( 'Default value for TTL cache, in seconds' )->defaultValue( 60 )->end()
->arrayNode( 'tree_root' )
->canBeUnset()
->children()
->integerNode( 'location_id' )
->info( "Root locationId for routing and link generation.\nUseful for multisite apps with one repository." )
->isRequired()
->end()
->arrayNode( 'excluded_uri_prefixes' )
->info( "URI prefixes that are allowed to be outside the content tree\n(useful for content sharing between multiple sites).\nPrefixes are not case sensitive" )
->example( array( '/media/images', '/products' ) )
->prototype( 'scalar' )->end()
->end()
->end()
->end()
->end()
->end();
}
public function mapConfig( array &$scopeSettings, $currentScope, ContextualizerInterface $contextualizer )
{
if ( !empty( $scopeSettings['content'] ) )
{
$contextualizer->setContextualParameter( 'content.view_cache', $currentScope, $scopeSettings['content']['view_cache'] );
$contextualizer->setContextualParameter( 'content.ttl_cache', $currentScope, $scopeSettings['content']['ttl_cache'] );
$contextualizer->setContextualParameter( 'content.default_ttl', $currentScope, $scopeSettings['content']['default_ttl'] );
if ( isset( $scopeSettings['content']['tree_root'] ) )
{
$contextualizer->setContextualParameter(
'content.tree_root.location_id',
$currentScope,
$scopeSettings['content']['tree_root']['location_id']
);
if ( isset( $scopeSettings['content']['tree_root']['excluded_uri_prefixes'] ) )
{
$contextualizer->setContextualParameter(
'content.tree_root.excluded_uri_prefixes',
$currentScope,
$scopeSettings['content']['tree_root']['excluded_uri_prefixes']
);
}
}
}
}
}
| wnsonsa/destin-foot | vendor/ezsystems/ezpublish-kernel/eZ/Bundle/EzPublishCoreBundle/DependencyInjection/Configuration/Parser/Content.php | PHP | gpl-2.0 | 3,718 |
package org.checkerframework.common.aliasing;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import org.checkerframework.common.aliasing.qual.LeakedToResult;
import org.checkerframework.common.aliasing.qual.MaybeAliased;
import org.checkerframework.common.aliasing.qual.MaybeLeaked;
import org.checkerframework.common.aliasing.qual.NonLeaked;
import org.checkerframework.common.aliasing.qual.Unique;
import org.checkerframework.common.basetype.BaseAnnotatedTypeFactory;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.framework.flow.CFAbstractAnalysis;
import org.checkerframework.framework.flow.CFStore;
import org.checkerframework.framework.flow.CFTransfer;
import org.checkerframework.framework.flow.CFValue;
import org.checkerframework.framework.qual.TypeQualifiers;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.QualifierHierarchy;
import org.checkerframework.framework.type.treeannotator.ImplicitsTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.PropagationTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.TreeAnnotator;
import org.checkerframework.framework.util.MultiGraphQualifierHierarchy;
import org.checkerframework.framework.util.MultiGraphQualifierHierarchy.MultiGraphFactory;
import org.checkerframework.javacutil.AnnotationUtils;
import com.sun.source.tree.NewClassTree;
// @NonLeaked and @LeakedToResult are type qualifiers because of a checker
// framework limitation (Issue 383). Once the stub parser gets updated to read
// non-type-qualifers annotations on stub files, this annotation won't be a
// type qualifier anymore.
@TypeQualifiers({ Unique.class, MaybeAliased.class, NonLeaked.class,
LeakedToResult.class, MaybeLeaked.class })
public class AliasingAnnotatedTypeFactory extends BaseAnnotatedTypeFactory {
private final AnnotationMirror MAYBE_ALIASED, NON_LEAKED, UNIQUE,
MAYBE_LEAKED;
public AliasingAnnotatedTypeFactory(BaseTypeChecker checker) {
super(checker);
MAYBE_ALIASED = AnnotationUtils.fromClass(elements, MaybeAliased.class);
NON_LEAKED = AnnotationUtils.fromClass(elements, NonLeaked.class);
UNIQUE = AnnotationUtils.fromClass(elements, Unique.class);
MAYBE_LEAKED = AnnotationUtils.fromClass(elements, MaybeLeaked.class);
if (this.getClass().equals(AliasingAnnotatedTypeFactory.class)) {
this.postInit();
}
}
@Override
public CFTransfer createFlowTransferFunction(
CFAbstractAnalysis<CFValue, CFStore, CFTransfer> analysis) {
CFTransfer ret = new AliasingTransfer(analysis);
return ret;
}
protected class AliasingTreeAnnotator extends TreeAnnotator {
public AliasingTreeAnnotator(AliasingAnnotatedTypeFactory atypeFactory) {
super(atypeFactory);
}
@Override
public Void visitNewClass(NewClassTree node, AnnotatedTypeMirror p) {
// Copied hack below from SPARTA:
// This is a horrible hack around the implementation of constructor
// results (CF treats annotations on constructor results in stub
// files as if it were a default and therefore ignores it.)
// This hack ignores any annotation written in the following location:
// new @A SomeClass();
AnnotatedTypeMirror defaulted = atypeFactory
.constructorFromUse(node).first.getReturnType();
Set<AnnotationMirror> defaultedSet = defaulted.getAnnotations();
p.replaceAnnotations(defaultedSet);
return null;
}
}
@Override
protected ListTreeAnnotator createTreeAnnotator() {
return new ListTreeAnnotator(new AliasingTreeAnnotator(this),
new PropagationTreeAnnotator(this), new ImplicitsTreeAnnotator(
this));
}
@Override
protected MultiGraphQualifierHierarchy.MultiGraphFactory createQualifierHierarchyFactory() {
return new MultiGraphQualifierHierarchy.MultiGraphFactory(this);
}
@Override
public QualifierHierarchy createQualifierHierarchy(MultiGraphFactory factory) {
return new AliasingQualifierHierarchy(factory);
}
protected class AliasingQualifierHierarchy extends
MultiGraphQualifierHierarchy {
protected AliasingQualifierHierarchy(MultiGraphFactory f) {
super(f);
}
@Override
protected Set<AnnotationMirror> findBottoms(
Map<AnnotationMirror, Set<AnnotationMirror>> supertypes) {
Set<AnnotationMirror> newbottoms = AnnotationUtils
.createAnnotationSet();
newbottoms.add(UNIQUE);
newbottoms.add(MAYBE_LEAKED);
return newbottoms;
}
@Override
protected Set<AnnotationMirror> findTops(
Map<AnnotationMirror, Set<AnnotationMirror>> supertypes) {
Set<AnnotationMirror> newtops = AnnotationUtils
.createAnnotationSet();
newtops.add(MAYBE_ALIASED);
newtops.add(NON_LEAKED);
return newtops;
}
private boolean isLeakedQualifier(AnnotationMirror anno) {
return AnnotationUtils.areSameByClass(anno, MaybeLeaked.class)
|| AnnotationUtils.areSameByClass(anno, NonLeaked.class)
|| AnnotationUtils.areSameByClass(anno, LeakedToResult.class);
}
@Override
public boolean isSubtype(AnnotationMirror rhs, AnnotationMirror lhs) {
if (isLeakedQualifier(lhs) && isLeakedQualifier(rhs)) {
// @LeakedToResult and @NonLeaked were supposed to be
// non-type-qualifiers annotations.
// Currently the stub parser does not support non-type-qualifier
// annotations on receiver parameters (Issue 383), therefore these
// annotations are implemented as type qualifiers but the
// warnings related to the hierarchy are ignored.
return true;
}
return super.isSubtype(rhs, lhs);
}
}
}
| renatoathaydes/checker-framework | framework/src/org/checkerframework/common/aliasing/AliasingAnnotatedTypeFactory.java | Java | gpl-2.0 | 6,385 |
/* Kernel module to match ESP parameters. */
/* (C) 2001-2002 Andras Kis-Szabo <kisza@sch.bme.hu>
*
* 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/module.h>
#include <linux/skbuff.h>
#include <linux/ipv6.h>
#include <linux/types.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter_ipv6/ip6t_esp.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("IPv6 ESP match");
MODULE_AUTHOR("Andras Kis-Szabo <kisza@sch.bme.hu>");
#if 0
#define DEBUGP printk
#else
#define DEBUGP(format, args...)
#endif
/* Returns 1 if the spi is matched by the range, 0 otherwise */
static inline int
spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, int invert)
{
int r=0;
DEBUGP("esp spi_match:%c 0x%x <= 0x%x <= 0x%x",invert? '!':' ',
min,spi,max);
r=(spi >= min && spi <= max) ^ invert;
DEBUGP(" result %s\n",r? "PASS\n" : "FAILED\n");
return r;
}
static int
match(const struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
const void *matchinfo,
int offset,
unsigned int protoff,
int *hotdrop)
{
struct ip_esp_hdr _esp, *eh;
const struct ip6t_esp *espinfo = matchinfo;
unsigned int ptr;
/* Make sure this isn't an evil packet */
/*DEBUGP("ipv6_esp entered \n");*/
if (ipv6_find_hdr(skb, &ptr, NEXTHDR_ESP) < 0)
return 0;
eh = skb_header_pointer(skb, ptr, sizeof(_esp), &_esp);
if (eh == NULL) {
*hotdrop = 1;
return 0;
}
DEBUGP("IPv6 ESP SPI %u %08X\n", ntohl(eh->spi), ntohl(eh->spi));
return (eh != NULL)
&& spi_match(espinfo->spis[0], espinfo->spis[1],
ntohl(eh->spi),
!!(espinfo->invflags & IP6T_ESP_INV_SPI));
}
/* Called when user tries to insert an entry of this type. */
static int
checkentry(const char *tablename,
const struct ip6t_ip6 *ip,
void *matchinfo,
unsigned int matchinfosize,
unsigned int hook_mask)
{
const struct ip6t_esp *espinfo = matchinfo;
if (matchinfosize != IP6T_ALIGN(sizeof(struct ip6t_esp))) {
DEBUGP("ip6t_esp: matchsize %u != %u\n",
matchinfosize, IP6T_ALIGN(sizeof(struct ip6t_esp)));
return 0;
}
if (espinfo->invflags & ~IP6T_ESP_INV_MASK) {
DEBUGP("ip6t_esp: unknown flags %X\n",
espinfo->invflags);
return 0;
}
return 1;
}
static struct ip6t_match esp_match = {
.name = "esp",
.match = &match,
.checkentry = &checkentry,
.me = THIS_MODULE,
};
static int __init init(void)
{
return ip6t_register_match(&esp_match);
}
static void __exit cleanup(void)
{
ip6t_unregister_match(&esp_match);
}
module_init(init);
module_exit(cleanup);
| gerboland/linux-2.6.15-neuros-eabi | net/ipv6/netfilter/ip6t_esp.c | C | gpl-2.0 | 2,753 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.4 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2013 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2013
* $Id$
*
*/
/**
* This class generates form components for Error Handling and Debugging
*
*/
class CRM_Admin_Form_Setting_UpdateConfigBackend extends CRM_Admin_Form_Setting {
protected $_oldBaseDir;
protected $_oldBaseURL;
protected $_oldSiteName;
/**
* Function to build the form
*
* @return None
* @access public
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Settings - Cleanup Caches and Update Paths'));
list(
$this->_oldBaseURL,
$this->_oldBaseDir,
$this->_oldSiteName
) = CRM_Core_BAO_ConfigSetting::getConfigSettings();
$this->assign('oldBaseURL', $this->_oldBaseURL);
$this->assign('oldBaseDir', $this->_oldBaseDir);
$this->assign('oldSiteName', $this->_oldSiteName);
$this->addElement(
'submit', $this->getButtonName('next', 'cleanup'), 'Cleanup Caches',
array('class' => 'form-submit', 'id' => 'cleanup-cache')
);
$this->add('text', 'newBaseURL', ts('New Base URL'), NULL, TRUE);
$this->add('text', 'newBaseDir', ts('New Base Directory'), NULL, TRUE);
if ($this->_oldSiteName) {
$this->add('text', 'newSiteName', ts('New Site Name'), NULL, TRUE);
}
$this->addFormRule(array('CRM_Admin_Form_Setting_UpdateConfigBackend', 'formRule'));
parent::buildQuickForm();
}
function setDefaultValues() {
if (!$this->_defaults) {
parent::setDefaultValues();
$config = CRM_Core_Config::singleton();
list(
$this->_defaults['newBaseURL'],
$this->_defaults['newBaseDir'],
$this->_defaults['newSiteName']
) = CRM_Core_BAO_ConfigSetting::getBestGuessSettings();
}
return $this->_defaults;
}
static function formRule($fields) {
$tmpDir = trim($fields['newBaseDir']);
$errors = array();
if (!is_writeable($tmpDir)) {
$errors['newBaseDir'] = ts('%1 directory does not exist or cannot be written by webserver',
array(1 => $tmpDir)
);
}
return $errors;
}
function postProcess() {
if (CRM_Utils_Array::value('_qf_UpdateConfigBackend_next_cleanup', $_POST)) {
$config = CRM_Core_Config::singleton();
// cleanup templates_c directory
$config->cleanup(1, FALSE);
// clear db caching
CRM_Core_Config::clearDBCache();
parent::rebuildMenu();
CRM_Core_BAO_WordReplacement::rebuild();
CRM_Core_Session::setStatus(ts('Cache has been cleared and menu has been rebuilt successfully.'), ts("Success"), "success");
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend', 'reset=1'));
}
// redirect to admin page after saving
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin'));
$params = $this->controller->exportValues($this->_name);
//CRM-5679
foreach ($params as $name => & $val) {
if ($val && in_array($name, array(
'newBaseURL', 'newBaseDir', 'newSiteName'))) {
$val = CRM_Utils_File::addTrailingSlash($val);
}
}
$from = array($this->_oldBaseURL, $this->_oldBaseDir);
$to = array(trim($params['newBaseURL']),
trim($params['newBaseDir']),
);
if ($this->_oldSiteName &&
$params['newSiteName']
) {
$from[] = $this->_oldSiteName;
$to[] = $params['newSiteName'];
}
$newValues = str_replace($from,
$to,
$this->_defaults
);
parent::commonProcess($newValues);
parent::rebuildMenu();
}
}
| lizmestres/bf | sites/all/modules/civicrm/CRM/Admin/Form/Setting/UpdateConfigBackend.php | PHP | gpl-2.0 | 5,269 |
/*
* Copyright (C) 2015 Ewoud Smeur <ewoud.smeur@gmail.com>
*
* This file is part of paparazzi.
*
* paparazzi 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, or (at your option)
* any later version.
*
* paparazzi 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 paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* @file firmwares/rotorcraft/guidance/guidance_indi.h
*
* A guidance mode based on Incremental Nonlinear Dynamic Inversion
* Come to ICRA2016 to learn more!
*
*/
#ifndef GUIDANCE_INDI_H
#define GUIDANCE_INDI_H
#include "std.h"
#include "math/pprz_algebra_int.h"
#include "math/pprz_algebra_float.h"
extern void guidance_indi_enter(void);
extern void guidance_indi_run(bool in_flight, int32_t heading);
extern void stabilization_attitude_set_setpoint_rp_quat_f(struct FloatEulers* indi_rp_cmd, bool in_flight, int32_t heading);
extern float guidance_indi_thrust_specific_force_gain;
extern struct FloatVect3 euler_cmd;
#endif /* GUIDANCE_INDI_H */
| RickHutten/paparazzi | sw/airborne/firmwares/rotorcraft/guidance/guidance_indi.h | C | gpl-2.0 | 1,479 |
--
-- Created by SQL::Translator::Producer::SQLite
-- Created on Mon Mar 2 20:07:22 2015
--
;
BEGIN TRANSACTION;
--
-- Table: dbix_class_deploymenthandler_versions
--
CREATE TABLE dbix_class_deploymenthandler_versions (
id INTEGER PRIMARY KEY NOT NULL,
version varchar(50) NOT NULL,
ddl text,
upgrade_sql text
);
CREATE UNIQUE INDEX dbix_class_deploymenthandler_versions_version ON dbix_class_deploymenthandler_versions (version);
COMMIT;
| garretraziel/openQA | dbicdh/SQLite/deploy/26/001-auto-__VERSION.sql | SQL | gpl-2.0 | 451 |
#!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: puppet
short_description: Runs puppet
description:
- Runs I(puppet) agent or apply in a reliable manner
version_added: "2.0"
options:
timeout:
description:
- How long to wait for I(puppet) to finish.
required: false
default: 30m
puppetmaster:
description:
- The hostname of the puppetmaster to contact.
required: false
default: None
modulepath:
description:
- Path to an alternate location for puppet modules
required: false
default: None
version_added: "2.4"
manifest:
description:
- Path to the manifest file to run puppet apply on.
required: false
default: None
facts:
description:
- A dict of values to pass in as persistent external facter facts
required: false
default: None
facter_basename:
description:
- Basename of the facter output file
required: false
default: ansible
environment:
description:
- Puppet environment to be used.
required: false
default: None
logdest:
description:
- Where the puppet logs should go, if puppet apply is being used
required: false
default: stdout
choices: [ 'stdout', 'syslog' ]
version_added: "2.1"
certname:
description:
- The name to use when handling certificates.
required: false
default: None
version_added: "2.1"
tags:
description:
- A comma-separated list of puppet tags to be used.
required: false
default: None
version_added: "2.1"
execute:
description:
- Execute a specific piece of Puppet code. It has no effect with
a puppetmaster.
required: false
default: None
version_added: "2.1"
requirements: [ puppet ]
author: "Monty Taylor (@emonty)"
'''
EXAMPLES = '''
# Run puppet agent and fail if anything goes wrong
- puppet
# Run puppet and timeout in 5 minutes
- puppet:
timeout: 5m
# Run puppet using a different environment
- puppet:
environment: testing
# Run puppet using a specific certname
- puppet:
certname: agent01.example.com
# Run puppet using a specific piece of Puppet code. Has no effect with a
# puppetmaster.
- puppet:
execute: 'include ::mymodule'
# Run puppet using a specific tags
- puppet:
tags: update,nginx
'''
import os
import pipes
import stat
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
def _get_facter_dir():
if os.getuid() == 0:
return '/etc/facter/facts.d'
else:
return os.path.expanduser('~/.facter/facts.d')
def _write_structured_data(basedir, basename, data):
if not os.path.exists(basedir):
os.makedirs(basedir)
file_path = os.path.join(basedir, "{0}.json".format(basename))
# This is more complex than you might normally expect because we want to
# open the file with only u+rw set. Also, we use the stat constants
# because ansible still supports python 2.4 and the octal syntax changed
out_file = os.fdopen(
os.open(
file_path, os.O_CREAT | os.O_WRONLY,
stat.S_IRUSR | stat.S_IWUSR), 'w')
out_file.write(json.dumps(data).encode('utf8'))
out_file.close()
def main():
module = AnsibleModule(
argument_spec=dict(
timeout=dict(default="30m"),
puppetmaster=dict(required=False, default=None),
modulepath=dict(required=False, default=None),
manifest=dict(required=False, default=None),
logdest=dict(
required=False, default='stdout',
choices=['stdout', 'syslog']),
show_diff=dict(
# internal code to work with --diff, do not use
default=False, aliases=['show-diff'], type='bool'),
facts=dict(default=None),
facter_basename=dict(default='ansible'),
environment=dict(required=False, default=None),
certname=dict(required=False, default=None),
tags=dict(required=False, default=None, type='list'),
execute=dict(required=False, default=None),
),
supports_check_mode=True,
mutually_exclusive=[
('puppetmaster', 'manifest'),
('puppetmaster', 'manifest', 'execute'),
('puppetmaster', 'modulepath')
],
)
p = module.params
global PUPPET_CMD
PUPPET_CMD = module.get_bin_path("puppet", False, ['/opt/puppetlabs/bin'])
if not PUPPET_CMD:
module.fail_json(
msg="Could not find puppet. Please ensure it is installed.")
global TIMEOUT_CMD
TIMEOUT_CMD = module.get_bin_path("timeout", False)
if p['manifest']:
if not os.path.exists(p['manifest']):
module.fail_json(
msg="Manifest file %(manifest)s not found." % dict(
manifest=p['manifest']))
# Check if puppet is disabled here
if not p['manifest']:
rc, stdout, stderr = module.run_command(
PUPPET_CMD + " config print agent_disabled_lockfile")
if os.path.exists(stdout.strip()):
module.fail_json(
msg="Puppet agent is administratively disabled.",
disabled=True)
elif rc != 0:
module.fail_json(
msg="Puppet agent state could not be determined.")
if module.params['facts'] and not module.check_mode:
_write_structured_data(
_get_facter_dir(),
module.params['facter_basename'],
module.params['facts'])
if TIMEOUT_CMD:
base_cmd = "%(timeout_cmd)s -s 9 %(timeout)s %(puppet_cmd)s" % dict(
timeout_cmd=TIMEOUT_CMD,
timeout=pipes.quote(p['timeout']),
puppet_cmd=PUPPET_CMD)
else:
base_cmd = PUPPET_CMD
if not p['manifest']:
cmd = ("%(base_cmd)s agent --onetime"
" --ignorecache --no-daemonize --no-usecacheonfailure --no-splay"
" --detailed-exitcodes --verbose --color 0") % dict(
base_cmd=base_cmd,
)
if p['puppetmaster']:
cmd += " --server %s" % pipes.quote(p['puppetmaster'])
if p['show_diff']:
cmd += " --show_diff"
if p['environment']:
cmd += " --environment '%s'" % p['environment']
if p['tags']:
cmd += " --tags '%s'" % ','.join(p['tags'])
if p['certname']:
cmd += " --certname='%s'" % p['certname']
if module.check_mode:
cmd += " --noop"
else:
cmd += " --no-noop"
else:
cmd = "%s apply --detailed-exitcodes " % base_cmd
if p['logdest'] == 'syslog':
cmd += "--logdest syslog "
if p['modulepath']:
cmd += "--modulepath='%s'" % p['modulepath']
if p['environment']:
cmd += "--environment '%s' " % p['environment']
if p['certname']:
cmd += " --certname='%s'" % p['certname']
if p['execute']:
cmd += " --execute '%s'" % p['execute']
if p['tags']:
cmd += " --tags '%s'" % ','.join(p['tags'])
if module.check_mode:
cmd += "--noop "
else:
cmd += "--no-noop "
cmd += pipes.quote(p['manifest'])
rc, stdout, stderr = module.run_command(cmd)
if rc == 0:
# success
module.exit_json(rc=rc, changed=False, stdout=stdout, stderr=stderr)
elif rc == 1:
# rc==1 could be because it's disabled
# rc==1 could also mean there was a compilation failure
disabled = "administratively disabled" in stdout
if disabled:
msg = "puppet is disabled"
else:
msg = "puppet did not run"
module.exit_json(
rc=rc, disabled=disabled, msg=msg,
error=True, stdout=stdout, stderr=stderr)
elif rc == 2:
# success with changes
module.exit_json(rc=0, changed=True, stdout=stdout, stderr=stderr)
elif rc == 124:
# timeout
module.exit_json(
rc=rc, msg="%s timed out" % cmd, stdout=stdout, stderr=stderr)
else:
# failure
module.fail_json(
rc=rc, msg="%s failed with return code: %d" % (cmd, rc),
stdout=stdout, stderr=stderr)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
| mensler/ansible | lib/ansible/modules/system/puppet.py | Python | gpl-3.0 | 9,396 |
<html lang="en">
<head>
<title>M68K-Chars - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="M68K_002dopcodes.html#M68K_002dopcodes" title="M68K-opcodes">
<link rel="prev" href="M68K_002dBranch.html#M68K_002dBranch" title="M68K-Branch">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="M68K-Chars"></a>
<a name="M68K_002dChars"></a>
Previous: <a rel="previous" accesskey="p" href="M68K_002dBranch.html#M68K_002dBranch">M68K-Branch</a>,
Up: <a rel="up" accesskey="u" href="M68K_002dopcodes.html#M68K_002dopcodes">M68K-opcodes</a>
<hr>
</div>
<h5 class="subsubsection">9.23.6.2 Special Characters</h5>
<p><a name="index-special-characters_002c-M680x0-1384"></a>
<a name="index-M680x0-line-comment-character-1385"></a><a name="index-line-comment-character_002c-M680x0-1386"></a><a name="index-comments_002c-M680x0-1387"></a>Line comments are introduced by the `<samp><span class="samp">|</span></samp>' character appearing
anywhere on a line, unless the <samp><span class="option">--bitwise-or</span></samp> command line option
has been specified.
<p>An asterisk (`<samp><span class="samp">*</span></samp>') as the first character on a line marks the
start of a line comment as well.
<p><a name="index-M680x0-immediate-character-1388"></a><a name="index-immediate-character_002c-M680x0-1389"></a>
A hash character (`<samp><span class="samp">#</span></samp>') as the first character on a line also
marks the start of a line comment, but in this case it could also be a
logical line number directive (see <a href="Comments.html#Comments">Comments</a>) or a preprocessor
control command (see <a href="Preprocessing.html#Preprocessing">Preprocessing</a>). If the hash character
appears elsewhere on a line it is used to introduce an immediate
value. (This is for compatibility with Sun's assembler).
<p><a name="index-M680x0-line-separator-1390"></a><a name="index-line-separator_002c-M680x0-1391"></a>
Multiple statements on the same line can appear if they are separated
by the `<samp><span class="samp">;</span></samp>' character.
<!-- Copyright (C) 1991-2015 Free Software Foundation, Inc. -->
<!-- This is part of the GAS manual. -->
<!-- For copying conditions, see the file as.texinfo. -->
</body></html>
| seemoo-lab/nexmon | buildtools/gcc-arm-none-eabi-5_4-2016q2-osx/share/doc/gcc-arm-none-eabi/html/as.html/M68K_002dChars.html | HTML | gpl-3.0 | 3,551 |
# If needed, first run: Set-ExecutionPolicy Unrestricted
$allFiles = (Get-ChildItem -Path ..\..\ -Include *.js,*.css,*.bat,*.html -Recurse)
$allFiles | %{
# Read file, remove trailing spaces/tabs, output back to file in CP1252 format (default for Git on Windows)
# This will also ensure the file has a trailing linebreak
Write-Host "Processing $_..."
$fileContent = (Get-Content $_) -replace "[ \t]+$", ""
[System.IO.File]::WriteAllLines($_, $fileContent, [System.Text.Encoding]::GetEncoding(1252))
} | cbezzy/openemr | public/assets/knockout-2-2-1/build/tools/normaliseAllFiles.ps1 | PowerShell | gpl-3.0 | 522 |
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "platform.h"
#if defined(USE_MSP_OVER_TELEMETRY)
#include "build/build_config.h"
#include "common/utils.h"
#include "fc/fc_msp.h"
#include "msp/msp.h"
#include "telemetry/crsf.h"
#include "telemetry/msp_shared.h"
#include "telemetry/smartport.h"
#define TELEMETRY_MSP_VERSION 1
#define TELEMETRY_MSP_VER_SHIFT 5
#define TELEMETRY_MSP_VER_MASK (0x7 << TELEMETRY_MSP_VER_SHIFT)
#define TELEMETRY_MSP_ERROR_FLAG (1 << 5)
#define TELEMETRY_MSP_START_FLAG (1 << 4)
#define TELEMETRY_MSP_SEQ_MASK 0x0F
#define TELEMETRY_MSP_RES_ERROR (-10)
enum {
TELEMETRY_MSP_VER_MISMATCH=0,
TELEMETRY_MSP_CRC_ERROR=1,
TELEMETRY_MSP_ERROR=2
};
STATIC_UNIT_TESTED uint8_t checksum = 0;
STATIC_UNIT_TESTED mspPackage_t mspPackage;
static mspRxBuffer_t mspRxBuffer;
static mspTxBuffer_t mspTxBuffer;
static mspPacket_t mspRxPacket;
static mspPacket_t mspTxPacket;
void initSharedMsp(void)
{
mspPackage.requestBuffer = (uint8_t *)&mspRxBuffer;
mspPackage.requestPacket = &mspRxPacket;
mspPackage.requestPacket->buf.ptr = mspPackage.requestBuffer;
mspPackage.requestPacket->buf.end = mspPackage.requestBuffer;
mspPackage.responseBuffer = (uint8_t *)&mspTxBuffer;
mspPackage.responsePacket = &mspTxPacket;
mspPackage.responsePacket->buf.ptr = mspPackage.responseBuffer;
mspPackage.responsePacket->buf.end = mspPackage.responseBuffer;
}
static void processMspPacket(void)
{
mspPackage.responsePacket->cmd = 0;
mspPackage.responsePacket->result = 0;
mspPackage.responsePacket->buf.end = mspPackage.responseBuffer;
mspPostProcessFnPtr mspPostProcessFn = NULL;
if (mspFcProcessCommand(mspPackage.requestPacket, mspPackage.responsePacket, &mspPostProcessFn) == MSP_RESULT_ERROR) {
sbufWriteU8(&mspPackage.responsePacket->buf, TELEMETRY_MSP_ERROR);
}
if (mspPostProcessFn) {
mspPostProcessFn(NULL);
}
sbufSwitchToReader(&mspPackage.responsePacket->buf, mspPackage.responseBuffer);
}
void sendMspErrorResponse(uint8_t error, int16_t cmd)
{
mspPackage.responsePacket->cmd = cmd;
mspPackage.responsePacket->result = 0;
mspPackage.responsePacket->buf.end = mspPackage.responseBuffer;
sbufWriteU8(&mspPackage.responsePacket->buf, error);
mspPackage.responsePacket->result = TELEMETRY_MSP_RES_ERROR;
sbufSwitchToReader(&mspPackage.responsePacket->buf, mspPackage.responseBuffer);
}
bool handleMspFrame(uint8_t *frameStart, int frameLength)
{
static uint8_t mspStarted = 0;
static uint8_t lastSeq = 0;
if (sbufBytesRemaining(&mspPackage.responsePacket->buf) > 0) {
mspStarted = 0;
}
if (mspStarted == 0) {
initSharedMsp();
}
mspPacket_t *packet = mspPackage.requestPacket;
sbuf_t *frameBuf = sbufInit(&mspPackage.requestFrame, frameStart, frameStart + (uint8_t)frameLength);
sbuf_t *rxBuf = &mspPackage.requestPacket->buf;
const uint8_t header = sbufReadU8(frameBuf);
const uint8_t seqNumber = header & TELEMETRY_MSP_SEQ_MASK;
const uint8_t version = (header & TELEMETRY_MSP_VER_MASK) >> TELEMETRY_MSP_VER_SHIFT;
if (version != TELEMETRY_MSP_VERSION) {
sendMspErrorResponse(TELEMETRY_MSP_VER_MISMATCH, 0);
return true;
}
if (header & TELEMETRY_MSP_START_FLAG) {
// first packet in sequence
uint8_t mspPayloadSize = sbufReadU8(frameBuf);
packet->cmd = sbufReadU8(frameBuf);
packet->result = 0;
packet->buf.ptr = mspPackage.requestBuffer;
packet->buf.end = mspPackage.requestBuffer + mspPayloadSize;
checksum = mspPayloadSize ^ packet->cmd;
mspStarted = 1;
} else if (!mspStarted) {
// no start packet yet, throw this one away
return false;
} else if (((lastSeq + 1) & TELEMETRY_MSP_SEQ_MASK) != seqNumber) {
// packet loss detected!
mspStarted = 0;
return false;
}
const uint8_t bufferBytesRemaining = sbufBytesRemaining(rxBuf);
const uint8_t frameBytesRemaining = sbufBytesRemaining(frameBuf);
uint8_t payload[frameBytesRemaining];
if (bufferBytesRemaining >= frameBytesRemaining) {
sbufReadData(frameBuf, payload, frameBytesRemaining);
sbufAdvance(frameBuf, frameBytesRemaining);
sbufWriteData(rxBuf, payload, frameBytesRemaining);
lastSeq = seqNumber;
return false;
} else {
sbufReadData(frameBuf, payload, bufferBytesRemaining);
sbufAdvance(frameBuf, bufferBytesRemaining);
sbufWriteData(rxBuf, payload, bufferBytesRemaining);
sbufSwitchToReader(rxBuf, mspPackage.requestBuffer);
while (sbufBytesRemaining(rxBuf)) {
checksum ^= sbufReadU8(rxBuf);
}
if (checksum != *frameBuf->ptr) {
mspStarted = 0;
sendMspErrorResponse(TELEMETRY_MSP_CRC_ERROR, packet->cmd);
return true;
}
}
mspStarted = 0;
sbufSwitchToReader(rxBuf, mspPackage.requestBuffer);
processMspPacket();
return true;
}
bool sendMspReply(uint8_t payloadSize, mspResponseFnPtr responseFn)
{
static uint8_t checksum = 0;
static uint8_t seq = 0;
uint8_t payloadOut[payloadSize];
sbuf_t payload;
sbuf_t *payloadBuf = sbufInit(&payload, payloadOut, payloadOut + payloadSize);
sbuf_t *txBuf = &mspPackage.responsePacket->buf;
// detect first reply packet
if (txBuf->ptr == mspPackage.responseBuffer) {
// header
uint8_t head = TELEMETRY_MSP_START_FLAG | (seq++ & TELEMETRY_MSP_SEQ_MASK);
if (mspPackage.responsePacket->result < 0) {
head |= TELEMETRY_MSP_ERROR_FLAG;
}
sbufWriteU8(payloadBuf, head);
uint8_t size = sbufBytesRemaining(txBuf);
sbufWriteU8(payloadBuf, size);
} else {
// header
sbufWriteU8(payloadBuf, (seq++ & TELEMETRY_MSP_SEQ_MASK));
}
const uint8_t bufferBytesRemaining = sbufBytesRemaining(txBuf);
const uint8_t payloadBytesRemaining = sbufBytesRemaining(payloadBuf);
uint8_t frame[payloadBytesRemaining];
if (bufferBytesRemaining >= payloadBytesRemaining) {
sbufReadData(txBuf, frame, payloadBytesRemaining);
sbufAdvance(txBuf, payloadBytesRemaining);
sbufWriteData(payloadBuf, frame, payloadBytesRemaining);
responseFn(payloadOut);
return true;
} else {
sbufReadData(txBuf, frame, bufferBytesRemaining);
sbufAdvance(txBuf, bufferBytesRemaining);
sbufWriteData(payloadBuf, frame, bufferBytesRemaining);
sbufSwitchToReader(txBuf, mspPackage.responseBuffer);
checksum = sbufBytesRemaining(txBuf) ^ mspPackage.responsePacket->cmd;
while (sbufBytesRemaining(txBuf)) {
checksum ^= sbufReadU8(txBuf);
}
sbufWriteU8(payloadBuf, checksum);
while (sbufBytesRemaining(payloadBuf)>1) {
sbufWriteU8(payloadBuf, 0);
}
}
responseFn(payloadOut);
return false;
}
#endif
| digitalentity/cleanflight | src/main/telemetry/msp_shared.c | C | gpl-3.0 | 7,036 |
/*
* linux/drivers/video/mmp/fb/vsync_notify.c
* vsync driver support
*
* Copyright (C) 2013 Marvell Technology Group Ltd.
* Authors: Yu Xu <yuxu@marvell.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 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, see <http://www.gnu.org/licenses/>.
*
*/
#include "mmpfb.h"
#include <video/mmp_trace.h>
void mmpfb_wait_vsync(struct mmpfb_info *fbi)
{
dev_dbg(fbi->dev, "wait vsync: vcnt %d, irq_en_ref: %d\n",
atomic_read(&fbi->vsync.vcnt), atomic_read(&fbi->path->irq_en_ref));
/*
* for N buffer cases,
* #1- (N-2) buffers passed in one frame:
* no need to wait vsync
* #N-1 buffer need to wait vsync
* e.g, for two buffer case, always wait
* for three buffer, only 2nd buffer need wait
*
* If vcnt is 0, we can't decrease it.
*/
if (atomic_read(&fbi->vsync.vcnt))
if (!atomic_dec_and_test(&fbi->vsync.vcnt))
return;
mmp_wait_vsync(&fbi->path->vsync);
}
static void mmpfb_vcnt_clean(struct mmpfb_info *fbi)
{
atomic_set(&fbi->vsync.vcnt, fbi->buffer_num - 1);
}
/* Get time stamp of vsync */
static ssize_t mmpfb_vsync_ts_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmpfb_info *fbi = dev_get_drvdata(dev);
return sprintf(buf, "%llx\n", fbi->vsync.ts_nano);
}
DEVICE_ATTR(vsync_ts, S_IRUGO, mmpfb_vsync_ts_show, NULL);
static ssize_t mmpfb_vsync_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmpfb_info *fbi = dev_get_drvdata(dev);
int s = 0;
s += sprintf(buf + s, "%s vsync uevent report\n",
fbi->vsync.en ? "enable" : "disable");
return s;
}
static ssize_t mmpfb_vsync_store(
struct device *dev, struct device_attribute *attr,
const char *buf, size_t size)
{
struct mmpfb_info *fbi = dev_get_drvdata(dev);
if (sysfs_streq(buf, "u1")) {
fbi->vsync.en = 1;
mmp_path_set_irq(fbi->path, 1);
} else if (sysfs_streq(buf, "u0")) {
fbi->vsync.en = 0;
mmp_path_set_irq(fbi->path, 0);
} else {
dev_dbg(fbi->dev, "invalid input, please echo as follow:\n");
dev_dbg(fbi->dev, "\tu1: enable vsync uevent\n");
dev_dbg(fbi->dev, "\tu0: disable vsync uevent\n");
}
trace_vsync(fbi->vsync.en);
dev_dbg(fbi->dev, "vsync_en = %d\n", fbi->vsync.en);
return size;
}
DEVICE_ATTR(vsync, S_IRUGO | S_IWUSR, mmpfb_vsync_show, mmpfb_vsync_store);
static void mmpfb_overlay_vsync_cb(void *data)
{
struct mmpfb_info *fbi = (struct mmpfb_info *)data;
if (fbi)
queue_work(fbi->vsync.wq, &fbi->vsync.fence_work);
}
static void mmpfb_vsync_cb(void *data)
{
struct timespec vsync_time;
struct mmpfb_info *fbi = (struct mmpfb_info *)data;
/* in vsync callback */
mmpfb_vcnt_clean(fbi);
/* Get time stamp of vsync */
ktime_get_ts(&vsync_time);
fbi->vsync.ts_nano = ((uint64_t)vsync_time.tv_sec)
* 1000 * 1000 * 1000 +
((uint64_t)vsync_time.tv_nsec);
if (atomic_read(&fbi->op_count)) {
queue_work(fbi->vsync.wq, &fbi->vsync.work);
queue_work(fbi->vsync.wq, &fbi->vsync.fence_work);
}
}
static void mmpfb_vsync_notify_work(struct work_struct *work)
{
struct mmpfb_vsync *vsync =
container_of(work, struct mmpfb_vsync, work);
struct mmpfb_info *fbi =
container_of(vsync, struct mmpfb_info, vsync);
sysfs_notify(&fbi->dev->kobj, NULL, "vsync_ts");
}
int mmpfb_overlay_vsync_notify_init(struct mmpfb_info *fbi)
{
int ret = 0;
struct mmp_vsync_notifier_node *notifier_node;
notifier_node = &fbi->vsync.notifier_node;
fbi->vsync.wq =
alloc_workqueue(fbi->name, WQ_HIGHPRI |
WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
if (!fbi->vsync.wq) {
dev_err(fbi->dev, "alloc_workqueue failed\n");
return ret;
}
INIT_WORK(&fbi->vsync.fence_work, mmpfb_overlay_fence_work);
notifier_node->cb_notify = mmpfb_overlay_vsync_cb;
notifier_node->cb_data = (void *)fbi;
mmp_register_vsync_cb(&fbi->path->vsync,
notifier_node);
return ret;
}
int mmpfb_vsync_notify_init(struct mmpfb_info *fbi)
{
int ret = 0;
struct mmp_vsync_notifier_node *notifier_node;
notifier_node = &fbi->vsync.notifier_node;
ret = device_create_file(fbi->dev, &dev_attr_vsync);
if (ret < 0) {
dev_err(fbi->dev, "device attr create fail: %d\n", ret);
return ret;
}
ret = device_create_file(fbi->dev, &dev_attr_vsync_ts);
if (ret < 0) {
dev_err(fbi->dev, "device attr create fail: %d\n", ret);
return ret;
}
fbi->vsync.wq =
alloc_workqueue(fbi->name, WQ_HIGHPRI |
WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
if (!fbi->vsync.wq) {
dev_err(fbi->dev, "alloc_workqueue failed\n");
return ret;
}
INIT_WORK(&fbi->vsync.work, mmpfb_vsync_notify_work);
INIT_WORK(&fbi->vsync.fence_work, mmpfb_overlay_fence_work);
notifier_node->cb_notify = mmpfb_vsync_cb;
notifier_node->cb_data = (void *)fbi;
mmp_register_vsync_cb(&fbi->path->vsync,
notifier_node);
mmpfb_vcnt_clean(fbi);
return ret;
}
void mmpfb_vsync_notify_deinit(struct mmpfb_info *fbi)
{
mmp_unregister_vsync_cb(&fbi->vsync.notifier_node);
device_remove_file(fbi->dev, &dev_attr_vsync_ts);
destroy_workqueue(fbi->vsync.wq);
}
| AKuHAK/xcover3ltexx_custom_kernel | drivers/video/mmp/fb/vsync_notify.c | C | gpl-3.0 | 5,488 |
/**
* Copyright (C) 2011 Whisper Systems
*
* 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 <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog.Calls;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
import org.thoughtcrime.securesms.contacts.ContactAccessor;
import org.thoughtcrime.securesms.contacts.ContactAccessor.ContactData;
import org.thoughtcrime.securesms.contacts.ContactAccessor.NumberData;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.RedPhoneCallTypes;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* Displays a list of recently used contacts for multi-select. Displayed
* by the ContactSelectionActivity in a tab frame, and ultimately used by
* ComposeMessageActivity for selecting destination message contacts.
*
* @author Moxie Marlinspike
*
*/
public class ContactSelectionRecentFragment extends SherlockListFragment
implements LoaderManager.LoaderCallbacks<Cursor>
{
private final HashMap<Long, ContactData> selectedContacts = new HashMap<Long, ContactData>();
@Override
public void onActivityCreated(Bundle icicle) {
super.onActivityCreated(icicle);
initializeResources();
initializeCursor();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.contact_selection_recent_activity, container, false);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
((CallItemView)v).selected();
}
private void initializeCursor() {
setListAdapter(new ContactSelectionListAdapter(getActivity(), null));
this.getLoaderManager().initLoader(0, null, this);
}
public List<ContactData> getSelectedContacts() {
List<ContactData> contacts = new LinkedList<ContactData>();
contacts.addAll(selectedContacts.values());
return contacts;
}
private void addSingleNumberContact(ContactData contactData) {
selectedContacts.put(contactData.id, contactData);
}
private void removeContact(ContactData contactData) {
selectedContacts.remove(contactData.id);
}
private void initializeResources() {
this.getListView().setFocusable(true);
}
private class ContactSelectionListAdapter extends CursorAdapter {
public ContactSelectionListAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
CallItemView view = new CallItemView(context);
bindView(view, context, cursor);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(Calls._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(Calls.CACHED_NAME));
String label = cursor.getString(cursor.getColumnIndexOrThrow(Calls.CACHED_NUMBER_LABEL));
String number = cursor.getString(cursor.getColumnIndexOrThrow(Calls.NUMBER));
int type = cursor.getInt(cursor.getColumnIndexOrThrow(Calls.TYPE));
long date = cursor.getLong(cursor.getColumnIndexOrThrow(Calls.DATE));
((CallItemView)view).set(id, name, label, number, type, date);
}
}
private class CallItemView extends RelativeLayout {
private ContactData contactData;
private Context context;
private ImageView callTypeIcon;
private TextView date;
private TextView label;
private TextView number;
private CheckedTextView line1;
public CallItemView(Context context) {
super(context);
LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
li.inflate(R.layout.recent_call_item_selectable, this, true);
this.context = context;
this.callTypeIcon = (ImageView) findViewById(R.id.call_type_icon);
this.date = (TextView) findViewById(R.id.date);
this.label = (TextView) findViewById(R.id.label);
this.number = (TextView) findViewById(R.id.number);
this.line1 = (CheckedTextView) findViewById(R.id.line1);
}
public void selected() {
line1.toggle();
if (line1.isChecked()) {
addSingleNumberContact(contactData);
} else {
removeContact(contactData);
}
}
public void set(long id, String name, String label, String number, int type, long date) {
if( name == null ) {
name = ContactAccessor.getInstance().getNameForNumber(getActivity(), number);
}
this.line1.setText((name == null || name.equals("")) ? number : name);
this.number.setText((name == null || name.equals("")) ? "" : number);
this.label.setText(label);
this.date.setText(DateUtils.getRelativeDateTimeString(context, date, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE));
if (type == Calls.INCOMING_TYPE || type == RedPhoneCallTypes.INCOMING) callTypeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_call_log_list_incoming_call));
else if (type == Calls.OUTGOING_TYPE || type == RedPhoneCallTypes.OUTGOING) callTypeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_call_log_list_outgoing_call));
else if (type == Calls.MISSED_TYPE || type == RedPhoneCallTypes.MISSED) callTypeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_call_log_list_missed_call));
this.contactData = new ContactData(id, name);
this.contactData.numbers.add(new NumberData(null, number));
if (selectedContacts.containsKey(id))
this.line1.setChecked(true);
else
this.line1.setChecked(false);
}
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(getActivity(), Calls.CONTENT_URI,
null, null, null,
Calls.DEFAULT_SORT_ORDER);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
((CursorAdapter)getListAdapter()).changeCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
((CursorAdapter)getListAdapter()).changeCursor(null);
}
}
| natuan241/TextSecure | src/org/thoughtcrime/securesms/ContactSelectionRecentFragment.java | Java | gpl-3.0 | 7,560 |
/*
* Copyright (C) 2010-2011 Kamil Dudka <kdudka@redhat.com>
*
* This file is part of predator.
*
* predator 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.
*
* predator 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 predator. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "plotenum.hh"
#include <cl/cl_msg.hh>
#include <iomanip>
// /////////////////////////////////////////////////////////////////////////////
// implementation of PlotEnumerator
PlotEnumerator *PlotEnumerator::inst_ = 0;
std::string PlotEnumerator::decorate(std::string name)
{
// obtain a unique ID for the given name
const int id = map_[name] ++;
#if SYMPLOT_STOP_AFTER_N_STATES
if (SYMPLOT_STOP_AFTER_N_STATES < id) {
CL_ERROR("SYMPLOT_STOP_AFTER_N_STATES (" << SYMPLOT_STOP_AFTER_N_STATES
<< ") exceeded, now stopping per user's request...");
CL_TRAP;
}
#endif
// convert the ID to string
std::ostringstream str;
str << std::fixed
<< std::setfill('0')
<< std::setw(/* width of the ID suffix */ 4)
<< id;
// merge name with ID
name += "-";
name += str.str();
#ifdef SYMPLOT_STOP_CONDITION
if (SYMPLOT_STOP_CONDITION(name))
CL_TRAP;
#endif
return name;
}
| martinhruska/forester | sl/plotenum.cc | C++ | gpl-3.0 | 1,726 |
/*
* Copyright (C) 2010 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.
*/
package dot.junit.opcodes.iget_wide.d;
public class T_iget_wide_7 {
public long run() {
return -99;
}
}
| s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/iget_wide/d/T_iget_wide_7.java | Java | gpl-3.0 | 743 |
/*-------------------------------------------------------------------------
*
* parse_oper.c
* handle operator things for parser
*
* Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/parser/parse_oper.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "lib/stringinfo.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
/*
* The lookup key for the operator lookaside hash table. Unused bits must be
* zeroes to ensure hashing works consistently --- in particular, oprname
* must be zero-padded and any unused entries in search_path must be zero.
*
* search_path contains the actual search_path with which the entry was
* derived (minus temp namespace if any), or else the single specified
* schema OID if we are looking up an explicitly-qualified operator name.
*
* search_path has to be fixed-length since the hashtable code insists on
* fixed-size keys. If your search path is longer than that, we just punt
* and don't cache anything.
*/
/* If your search_path is longer than this, sucks to be you ... */
#define MAX_CACHED_PATH_LEN 16
typedef struct OprCacheKey
{
char oprname[NAMEDATALEN];
Oid left_arg; /* Left input OID, or 0 if prefix op */
Oid right_arg; /* Right input OID, or 0 if postfix op */
Oid search_path[MAX_CACHED_PATH_LEN];
} OprCacheKey;
typedef struct OprCacheEntry
{
/* the hash lookup key MUST BE FIRST */
OprCacheKey key;
Oid opr_oid; /* OID of the resolved operator */
} OprCacheEntry;
static Oid binary_oper_exact(List *opname, Oid arg1, Oid arg2);
static FuncDetailCode oper_select_candidate(int nargs,
Oid *input_typeids,
FuncCandidateList candidates,
Oid *operOid);
static const char *op_signature_string(List *op, char oprkind,
Oid arg1, Oid arg2);
static void op_error(ParseState *pstate, List *op, char oprkind,
Oid arg1, Oid arg2,
FuncDetailCode fdresult, int location);
static bool make_oper_cache_key(ParseState *pstate, OprCacheKey *key,
List *opname, Oid ltypeId, Oid rtypeId,
int location);
static Oid find_oper_cache_entry(OprCacheKey *key);
static void make_oper_cache_entry(OprCacheKey *key, Oid opr_oid);
static void InvalidateOprCacheCallBack(Datum arg, int cacheid, uint32 hashvalue);
/*
* LookupOperName
* Given a possibly-qualified operator name and exact input datatypes,
* look up the operator.
*
* Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
* a postfix op.
*
* If the operator name is not schema-qualified, it is sought in the current
* namespace search path.
*
* If the operator is not found, we return InvalidOid if noError is true,
* else raise an error. pstate and location are used only to report the
* error position; pass NULL/-1 if not available.
*/
Oid
LookupOperName(ParseState *pstate, List *opername, Oid oprleft, Oid oprright,
bool noError, int location)
{
Oid result;
result = OpernameGetOprid(opername, oprleft, oprright);
if (OidIsValid(result))
return result;
/* we don't use op_error here because only an exact match is wanted */
if (!noError)
{
char oprkind;
if (!OidIsValid(oprleft))
oprkind = 'l';
else if (!OidIsValid(oprright))
oprkind = 'r';
else
oprkind = 'b';
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("operator does not exist: %s",
op_signature_string(opername, oprkind,
oprleft, oprright)),
parser_errposition(pstate, location)));
}
return InvalidOid;
}
/*
* LookupOperNameTypeNames
* Like LookupOperName, but the argument types are specified by
* TypeName nodes.
*
* Pass oprleft = NULL for a prefix op, oprright = NULL for a postfix op.
*/
Oid
LookupOperNameTypeNames(ParseState *pstate, List *opername,
TypeName *oprleft, TypeName *oprright,
bool noError, int location)
{
Oid leftoid,
rightoid;
if (oprleft == NULL)
leftoid = InvalidOid;
else
leftoid = LookupTypeNameOid(pstate, oprleft, noError);
if (oprright == NULL)
rightoid = InvalidOid;
else
rightoid = LookupTypeNameOid(pstate, oprright, noError);
return LookupOperName(pstate, opername, leftoid, rightoid,
noError, location);
}
/*
* get_sort_group_operators - get default sorting/grouping operators for type
*
* We fetch the "<", "=", and ">" operators all at once to reduce lookup
* overhead (knowing that most callers will be interested in at least two).
* However, a given datatype might have only an "=" operator, if it is
* hashable but not sortable. (Other combinations of present and missing
* operators shouldn't happen, unless the system catalogs are messed up.)
*
* If an operator is missing and the corresponding needXX flag is true,
* throw a standard error message, else return InvalidOid.
*
* In addition to the operator OIDs themselves, this function can identify
* whether the "=" operator is hashable.
*
* Callers can pass NULL pointers for any results they don't care to get.
*
* Note: the results are guaranteed to be exact or binary-compatible matches,
* since most callers are not prepared to cope with adding any run-time type
* coercion steps.
*/
void
get_sort_group_operators(Oid argtype,
bool needLT, bool needEQ, bool needGT,
Oid *ltOpr, Oid *eqOpr, Oid *gtOpr,
bool *isHashable)
{
TypeCacheEntry *typentry;
int cache_flags;
Oid lt_opr;
Oid eq_opr;
Oid gt_opr;
bool hashable;
/*
* Look up the operators using the type cache.
*
* Note: the search algorithm used by typcache.c ensures that the results
* are consistent, ie all from matching opclasses.
*/
if (isHashable != NULL)
cache_flags = TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR | TYPECACHE_GT_OPR |
TYPECACHE_HASH_PROC;
else
cache_flags = TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR | TYPECACHE_GT_OPR;
typentry = lookup_type_cache(argtype, cache_flags);
lt_opr = typentry->lt_opr;
eq_opr = typentry->eq_opr;
gt_opr = typentry->gt_opr;
hashable = OidIsValid(typentry->hash_proc);
/* Report errors if needed */
if ((needLT && !OidIsValid(lt_opr)) ||
(needGT && !OidIsValid(gt_opr)))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("could not identify an ordering operator for type %s",
format_type_be(argtype)),
errhint("Use an explicit ordering operator or modify the query.")));
if (needEQ && !OidIsValid(eq_opr))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("could not identify an equality operator for type %s",
format_type_be(argtype))));
/* Return results as needed */
if (ltOpr)
*ltOpr = lt_opr;
if (eqOpr)
*eqOpr = eq_opr;
if (gtOpr)
*gtOpr = gt_opr;
if (isHashable)
*isHashable = hashable;
}
/* given operator tuple, return the operator OID */
Oid
oprid(Operator op)
{
return HeapTupleGetOid(op);
}
/* given operator tuple, return the underlying function's OID */
Oid
oprfuncid(Operator op)
{
Form_pg_operator pgopform = (Form_pg_operator) GETSTRUCT(op);
return pgopform->oprcode;
}
/* binary_oper_exact()
* Check for an "exact" match to the specified operand types.
*
* If one operand is an unknown literal, assume it should be taken to be
* the same type as the other operand for this purpose. Also, consider
* the possibility that the other operand is a domain type that needs to
* be reduced to its base type to find an "exact" match.
*/
static Oid
binary_oper_exact(List *opname, Oid arg1, Oid arg2)
{
Oid result;
bool was_unknown = false;
/* Unspecified type for one of the arguments? then use the other */
if ((arg1 == UNKNOWNOID) && (arg2 != InvalidOid))
{
arg1 = arg2;
was_unknown = true;
}
else if ((arg2 == UNKNOWNOID) && (arg1 != InvalidOid))
{
arg2 = arg1;
was_unknown = true;
}
result = OpernameGetOprid(opname, arg1, arg2);
if (OidIsValid(result))
return result;
if (was_unknown)
{
/* arg1 and arg2 are the same here, need only look at arg1 */
Oid basetype = getBaseType(arg1);
if (basetype != arg1)
{
result = OpernameGetOprid(opname, basetype, basetype);
if (OidIsValid(result))
return result;
}
}
return InvalidOid;
}
/* oper_select_candidate()
* Given the input argtype array and one or more candidates
* for the operator, attempt to resolve the conflict.
*
* Returns FUNCDETAIL_NOTFOUND, FUNCDETAIL_MULTIPLE, or FUNCDETAIL_NORMAL.
* In the success case the Oid of the best candidate is stored in *operOid.
*
* Note that the caller has already determined that there is no candidate
* exactly matching the input argtype(s). Incompatible candidates are not yet
* pruned away, however.
*/
static FuncDetailCode
oper_select_candidate(int nargs,
Oid *input_typeids,
FuncCandidateList candidates,
Oid *operOid) /* output argument */
{
int ncandidates;
/*
* Delete any candidates that cannot actually accept the given input
* types, whether directly or by coercion.
*/
ncandidates = func_match_argtypes(nargs, input_typeids,
candidates, &candidates);
/* Done if no candidate or only one candidate survives */
if (ncandidates == 0)
{
*operOid = InvalidOid;
return FUNCDETAIL_NOTFOUND;
}
if (ncandidates == 1)
{
*operOid = candidates->oid;
return FUNCDETAIL_NORMAL;
}
/*
* Use the same heuristics as for ambiguous functions to resolve the
* conflict.
*/
candidates = func_select_candidate(nargs, input_typeids, candidates);
if (candidates)
{
*operOid = candidates->oid;
return FUNCDETAIL_NORMAL;
}
*operOid = InvalidOid;
return FUNCDETAIL_MULTIPLE; /* failed to select a best candidate */
}
/* oper() -- search for a binary operator
* Given operator name, types of arg1 and arg2, return oper struct.
*
* IMPORTANT: the returned operator (if any) is only promised to be
* coercion-compatible with the input datatypes. Do not use this if
* you need an exact- or binary-compatible match; see compatible_oper.
*
* If no matching operator found, return NULL if noError is true,
* raise an error if it is false. pstate and location are used only to report
* the error position; pass NULL/-1 if not available.
*
* NOTE: on success, the returned object is a syscache entry. The caller
* must ReleaseSysCache() the entry when done with it.
*/
Operator
oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId,
bool noError, int location)
{
Oid operOid;
OprCacheKey key;
bool key_ok;
FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
HeapTuple tup = NULL;
/*
* Try to find the mapping in the lookaside cache.
*/
key_ok = make_oper_cache_key(pstate, &key, opname, ltypeId, rtypeId, location);
if (key_ok)
{
operOid = find_oper_cache_entry(&key);
if (OidIsValid(operOid))
{
tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
if (HeapTupleIsValid(tup))
return (Operator) tup;
}
}
/*
* First try for an "exact" match.
*/
operOid = binary_oper_exact(opname, ltypeId, rtypeId);
if (!OidIsValid(operOid))
{
/*
* Otherwise, search for the most suitable candidate.
*/
FuncCandidateList clist;
/* Get binary operators of given name */
clist = OpernameGetCandidates(opname, 'b', false);
/* No operators found? Then fail... */
if (clist != NULL)
{
/*
* Unspecified type for one of the arguments? then use the other
* (XXX this is probably dead code?)
*/
Oid inputOids[2];
if (rtypeId == InvalidOid)
rtypeId = ltypeId;
else if (ltypeId == InvalidOid)
ltypeId = rtypeId;
inputOids[0] = ltypeId;
inputOids[1] = rtypeId;
fdresult = oper_select_candidate(2, inputOids, clist, &operOid);
}
}
if (OidIsValid(operOid))
tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
if (HeapTupleIsValid(tup))
{
if (key_ok)
make_oper_cache_entry(&key, operOid);
}
else if (!noError)
op_error(pstate, opname, 'b', ltypeId, rtypeId, fdresult, location);
return (Operator) tup;
}
/* compatible_oper()
* given an opname and input datatypes, find a compatible binary operator
*
* This is tighter than oper() because it will not return an operator that
* requires coercion of the input datatypes (but binary-compatible operators
* are accepted). Otherwise, the semantics are the same.
*/
Operator
compatible_oper(ParseState *pstate, List *op, Oid arg1, Oid arg2,
bool noError, int location)
{
Operator optup;
Form_pg_operator opform;
/* oper() will find the best available match */
optup = oper(pstate, op, arg1, arg2, noError, location);
if (optup == (Operator) NULL)
return (Operator) NULL; /* must be noError case */
/* but is it good enough? */
opform = (Form_pg_operator) GETSTRUCT(optup);
if (IsBinaryCoercible(arg1, opform->oprleft) &&
IsBinaryCoercible(arg2, opform->oprright))
return optup;
/* nope... */
ReleaseSysCache(optup);
if (!noError)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("operator requires run-time type coercion: %s",
op_signature_string(op, 'b', arg1, arg2)),
parser_errposition(pstate, location)));
return (Operator) NULL;
}
/* compatible_oper_opid() -- get OID of a binary operator
*
* This is a convenience routine that extracts only the operator OID
* from the result of compatible_oper(). InvalidOid is returned if the
* lookup fails and noError is true.
*/
Oid
compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
{
Operator optup;
Oid result;
optup = compatible_oper(NULL, op, arg1, arg2, noError, -1);
if (optup != NULL)
{
result = oprid(optup);
ReleaseSysCache(optup);
return result;
}
return InvalidOid;
}
/* right_oper() -- search for a unary right operator (postfix operator)
* Given operator name and type of arg, return oper struct.
*
* IMPORTANT: the returned operator (if any) is only promised to be
* coercion-compatible with the input datatype. Do not use this if
* you need an exact- or binary-compatible match.
*
* If no matching operator found, return NULL if noError is true,
* raise an error if it is false. pstate and location are used only to report
* the error position; pass NULL/-1 if not available.
*
* NOTE: on success, the returned object is a syscache entry. The caller
* must ReleaseSysCache() the entry when done with it.
*/
Operator
right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
{
Oid operOid;
OprCacheKey key;
bool key_ok;
FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
HeapTuple tup = NULL;
/*
* Try to find the mapping in the lookaside cache.
*/
key_ok = make_oper_cache_key(pstate, &key, op, arg, InvalidOid, location);
if (key_ok)
{
operOid = find_oper_cache_entry(&key);
if (OidIsValid(operOid))
{
tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
if (HeapTupleIsValid(tup))
return (Operator) tup;
}
}
/*
* First try for an "exact" match.
*/
operOid = OpernameGetOprid(op, arg, InvalidOid);
if (!OidIsValid(operOid))
{
/*
* Otherwise, search for the most suitable candidate.
*/
FuncCandidateList clist;
/* Get postfix operators of given name */
clist = OpernameGetCandidates(op, 'r', false);
/* No operators found? Then fail... */
if (clist != NULL)
{
/*
* We must run oper_select_candidate even if only one candidate,
* otherwise we may falsely return a non-type-compatible operator.
*/
fdresult = oper_select_candidate(1, &arg, clist, &operOid);
}
}
if (OidIsValid(operOid))
tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
if (HeapTupleIsValid(tup))
{
if (key_ok)
make_oper_cache_entry(&key, operOid);
}
else if (!noError)
op_error(pstate, op, 'r', arg, InvalidOid, fdresult, location);
return (Operator) tup;
}
/* left_oper() -- search for a unary left operator (prefix operator)
* Given operator name and type of arg, return oper struct.
*
* IMPORTANT: the returned operator (if any) is only promised to be
* coercion-compatible with the input datatype. Do not use this if
* you need an exact- or binary-compatible match.
*
* If no matching operator found, return NULL if noError is true,
* raise an error if it is false. pstate and location are used only to report
* the error position; pass NULL/-1 if not available.
*
* NOTE: on success, the returned object is a syscache entry. The caller
* must ReleaseSysCache() the entry when done with it.
*/
Operator
left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
{
Oid operOid;
OprCacheKey key;
bool key_ok;
FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
HeapTuple tup = NULL;
/*
* Try to find the mapping in the lookaside cache.
*/
key_ok = make_oper_cache_key(pstate, &key, op, InvalidOid, arg, location);
if (key_ok)
{
operOid = find_oper_cache_entry(&key);
if (OidIsValid(operOid))
{
tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
if (HeapTupleIsValid(tup))
return (Operator) tup;
}
}
/*
* First try for an "exact" match.
*/
operOid = OpernameGetOprid(op, InvalidOid, arg);
if (!OidIsValid(operOid))
{
/*
* Otherwise, search for the most suitable candidate.
*/
FuncCandidateList clist;
/* Get prefix operators of given name */
clist = OpernameGetCandidates(op, 'l', false);
/* No operators found? Then fail... */
if (clist != NULL)
{
/*
* The returned list has args in the form (0, oprright). Move the
* useful data into args[0] to keep oper_select_candidate simple.
* XXX we are assuming here that we may scribble on the list!
*/
FuncCandidateList clisti;
for (clisti = clist; clisti != NULL; clisti = clisti->next)
{
clisti->args[0] = clisti->args[1];
}
/*
* We must run oper_select_candidate even if only one candidate,
* otherwise we may falsely return a non-type-compatible operator.
*/
fdresult = oper_select_candidate(1, &arg, clist, &operOid);
}
}
if (OidIsValid(operOid))
tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
if (HeapTupleIsValid(tup))
{
if (key_ok)
make_oper_cache_entry(&key, operOid);
}
else if (!noError)
op_error(pstate, op, 'l', InvalidOid, arg, fdresult, location);
return (Operator) tup;
}
/*
* op_signature_string
* Build a string representing an operator name, including arg type(s).
* The result is something like "integer + integer".
*
* This is typically used in the construction of operator-not-found error
* messages.
*/
static const char *
op_signature_string(List *op, char oprkind, Oid arg1, Oid arg2)
{
StringInfoData argbuf;
initStringInfo(&argbuf);
if (oprkind != 'l')
appendStringInfo(&argbuf, "%s ", format_type_be(arg1));
appendStringInfoString(&argbuf, NameListToString(op));
if (oprkind != 'r')
appendStringInfo(&argbuf, " %s", format_type_be(arg2));
return argbuf.data; /* return palloc'd string buffer */
}
/*
* op_error - utility routine to complain about an unresolvable operator
*/
static void
op_error(ParseState *pstate, List *op, char oprkind,
Oid arg1, Oid arg2,
FuncDetailCode fdresult, int location)
{
if (fdresult == FUNCDETAIL_MULTIPLE)
ereport(ERROR,
(errcode(ERRCODE_AMBIGUOUS_FUNCTION),
errmsg("operator is not unique: %s",
op_signature_string(op, oprkind, arg1, arg2)),
errhint("Could not choose a best candidate operator. "
"You might need to add explicit type casts."),
parser_errposition(pstate, location)));
else
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("operator does not exist: %s",
op_signature_string(op, oprkind, arg1, arg2)),
errhint("No operator matches the given name and argument type(s). "
"You might need to add explicit type casts."),
parser_errposition(pstate, location)));
}
/*
* make_op()
* Operator expression construction.
*
* Transform operator expression ensuring type compatibility.
* This is where some type conversion happens.
*
* As with coerce_type, pstate may be NULL if no special unknown-Param
* processing is wanted.
*/
Expr *
make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
int location)
{
Oid ltypeId,
rtypeId;
Operator tup;
Form_pg_operator opform;
Oid actual_arg_types[2];
Oid declared_arg_types[2];
int nargs;
List *args;
Oid rettype;
OpExpr *result;
/* Select the operator */
if (rtree == NULL)
{
/* right operator */
ltypeId = exprType(ltree);
rtypeId = InvalidOid;
tup = right_oper(pstate, opname, ltypeId, false, location);
}
else if (ltree == NULL)
{
/* left operator */
rtypeId = exprType(rtree);
ltypeId = InvalidOid;
tup = left_oper(pstate, opname, rtypeId, false, location);
}
else
{
/* otherwise, binary operator */
ltypeId = exprType(ltree);
rtypeId = exprType(rtree);
tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
}
opform = (Form_pg_operator) GETSTRUCT(tup);
/* Check it's not a shell */
if (!RegProcedureIsValid(opform->oprcode))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("operator is only a shell: %s",
op_signature_string(opname,
opform->oprkind,
opform->oprleft,
opform->oprright)),
parser_errposition(pstate, location)));
/* Do typecasting and build the expression tree */
if (rtree == NULL)
{
/* right operator */
args = list_make1(ltree);
actual_arg_types[0] = ltypeId;
declared_arg_types[0] = opform->oprleft;
nargs = 1;
}
else if (ltree == NULL)
{
/* left operator */
args = list_make1(rtree);
actual_arg_types[0] = rtypeId;
declared_arg_types[0] = opform->oprright;
nargs = 1;
}
else
{
/* otherwise, binary operator */
args = list_make2(ltree, rtree);
actual_arg_types[0] = ltypeId;
actual_arg_types[1] = rtypeId;
declared_arg_types[0] = opform->oprleft;
declared_arg_types[1] = opform->oprright;
nargs = 2;
}
/*
* enforce consistency with polymorphic argument and return types,
* possibly adjusting return type or declared_arg_types (which will be
* used as the cast destination by make_fn_arguments)
*/
rettype = enforce_generic_type_consistency(actual_arg_types,
declared_arg_types,
nargs,
opform->oprresult,
false);
/* perform the necessary typecasting of arguments */
make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
/* and build the expression node */
result = makeNode(OpExpr);
result->opno = oprid(tup);
result->opfuncid = opform->oprcode;
result->opresulttype = rettype;
result->opretset = get_func_retset(opform->oprcode);
/* opcollid and inputcollid will be set by parse_collate.c */
result->args = args;
result->location = location;
ReleaseSysCache(tup);
return (Expr *) result;
}
/*
* make_scalar_array_op()
* Build expression tree for "scalar op ANY/ALL (array)" construct.
*/
Expr *
make_scalar_array_op(ParseState *pstate, List *opname,
bool useOr,
Node *ltree, Node *rtree,
int location)
{
Oid ltypeId,
rtypeId,
atypeId,
res_atypeId;
Operator tup;
Form_pg_operator opform;
Oid actual_arg_types[2];
Oid declared_arg_types[2];
List *args;
Oid rettype;
ScalarArrayOpExpr *result;
ltypeId = exprType(ltree);
atypeId = exprType(rtree);
/*
* The right-hand input of the operator will be the element type of the
* array. However, if we currently have just an untyped literal on the
* right, stay with that and hope we can resolve the operator.
*/
if (atypeId == UNKNOWNOID)
rtypeId = UNKNOWNOID;
else
{
rtypeId = get_base_element_type(atypeId);
if (!OidIsValid(rtypeId))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("op ANY/ALL (array) requires array on right side"),
parser_errposition(pstate, location)));
}
/* Now resolve the operator */
tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
opform = (Form_pg_operator) GETSTRUCT(tup);
/* Check it's not a shell */
if (!RegProcedureIsValid(opform->oprcode))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("operator is only a shell: %s",
op_signature_string(opname,
opform->oprkind,
opform->oprleft,
opform->oprright)),
parser_errposition(pstate, location)));
args = list_make2(ltree, rtree);
actual_arg_types[0] = ltypeId;
actual_arg_types[1] = rtypeId;
declared_arg_types[0] = opform->oprleft;
declared_arg_types[1] = opform->oprright;
/*
* enforce consistency with polymorphic argument and return types,
* possibly adjusting return type or declared_arg_types (which will be
* used as the cast destination by make_fn_arguments)
*/
rettype = enforce_generic_type_consistency(actual_arg_types,
declared_arg_types,
2,
opform->oprresult,
false);
/*
* Check that operator result is boolean
*/
if (rettype != BOOLOID)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("op ANY/ALL (array) requires operator to yield boolean"),
parser_errposition(pstate, location)));
if (get_func_retset(opform->oprcode))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("op ANY/ALL (array) requires operator not to return a set"),
parser_errposition(pstate, location)));
/*
* Now switch back to the array type on the right, arranging for any
* needed cast to be applied. Beware of polymorphic operators here;
* enforce_generic_type_consistency may or may not have replaced a
* polymorphic type with a real one.
*/
if (IsPolymorphicType(declared_arg_types[1]))
{
/* assume the actual array type is OK */
res_atypeId = atypeId;
}
else
{
res_atypeId = get_array_type(declared_arg_types[1]);
if (!OidIsValid(res_atypeId))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("could not find array type for data type %s",
format_type_be(declared_arg_types[1])),
parser_errposition(pstate, location)));
}
actual_arg_types[1] = atypeId;
declared_arg_types[1] = res_atypeId;
/* perform the necessary typecasting of arguments */
make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
/* and build the expression node */
result = makeNode(ScalarArrayOpExpr);
result->opno = oprid(tup);
result->opfuncid = opform->oprcode;
result->useOr = useOr;
/* inputcollid will be set by parse_collate.c */
result->args = args;
result->location = location;
ReleaseSysCache(tup);
return (Expr *) result;
}
/*
* Lookaside cache to speed operator lookup. Possibly this should be in
* a separate module under utils/cache/ ?
*
* The idea here is that the mapping from operator name and given argument
* types is constant for a given search path (or single specified schema OID)
* so long as the contents of pg_operator and pg_cast don't change. And that
* mapping is pretty expensive to compute, especially for ambiguous operators;
* this is mainly because there are a *lot* of instances of popular operator
* names such as "=", and we have to check each one to see which is the
* best match. So once we have identified the correct mapping, we save it
* in a cache that need only be flushed on pg_operator or pg_cast change.
* (pg_cast must be considered because changes in the set of implicit casts
* affect the set of applicable operators for any given input datatype.)
*
* XXX in principle, ALTER TABLE ... INHERIT could affect the mapping as
* well, but we disregard that since there's no convenient way to find out
* about it, and it seems a pretty far-fetched corner-case anyway.
*
* Note: at some point it might be worth doing a similar cache for function
* lookups. However, the potential gain is a lot less since (a) function
* names are generally not overloaded as heavily as operator names, and
* (b) we'd have to flush on pg_proc updates, which are probably a good
* deal more common than pg_operator updates.
*/
/* The operator cache hashtable */
static HTAB *OprCacheHash = NULL;
/*
* make_oper_cache_key
* Fill the lookup key struct given operator name and arg types.
*
* Returns TRUE if successful, FALSE if the search_path overflowed
* (hence no caching is possible).
*
* pstate/location are used only to report the error position; pass NULL/-1
* if not available.
*/
static bool
make_oper_cache_key(ParseState *pstate, OprCacheKey *key, List *opname,
Oid ltypeId, Oid rtypeId, int location)
{
char *schemaname;
char *opername;
/* deconstruct the name list */
DeconstructQualifiedName(opname, &schemaname, &opername);
/* ensure zero-fill for stable hashing */
MemSet(key, 0, sizeof(OprCacheKey));
/* save operator name and input types into key */
strlcpy(key->oprname, opername, NAMEDATALEN);
key->left_arg = ltypeId;
key->right_arg = rtypeId;
if (schemaname)
{
ParseCallbackState pcbstate;
/* search only in exact schema given */
setup_parser_errposition_callback(&pcbstate, pstate, location);
key->search_path[0] = LookupExplicitNamespace(schemaname, false);
cancel_parser_errposition_callback(&pcbstate);
}
else
{
/* get the active search path */
if (fetch_search_path_array(key->search_path,
MAX_CACHED_PATH_LEN) > MAX_CACHED_PATH_LEN)
return false; /* oops, didn't fit */
}
return true;
}
/*
* find_oper_cache_entry
*
* Look for a cache entry matching the given key. If found, return the
* contained operator OID, else return InvalidOid.
*/
static Oid
find_oper_cache_entry(OprCacheKey *key)
{
OprCacheEntry *oprentry;
if (OprCacheHash == NULL)
{
/* First time through: initialize the hash table */
HASHCTL ctl;
MemSet(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(OprCacheKey);
ctl.entrysize = sizeof(OprCacheEntry);
OprCacheHash = hash_create("Operator lookup cache", 256,
&ctl, HASH_ELEM | HASH_BLOBS);
/* Arrange to flush cache on pg_operator and pg_cast changes */
CacheRegisterSyscacheCallback(OPERNAMENSP,
InvalidateOprCacheCallBack,
(Datum) 0);
CacheRegisterSyscacheCallback(CASTSOURCETARGET,
InvalidateOprCacheCallBack,
(Datum) 0);
}
/* Look for an existing entry */
oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
(void *) key,
HASH_FIND, NULL);
if (oprentry == NULL)
return InvalidOid;
return oprentry->opr_oid;
}
/*
* make_oper_cache_entry
*
* Insert a cache entry for the given key.
*/
static void
make_oper_cache_entry(OprCacheKey *key, Oid opr_oid)
{
OprCacheEntry *oprentry;
Assert(OprCacheHash != NULL);
oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
(void *) key,
HASH_ENTER, NULL);
oprentry->opr_oid = opr_oid;
}
/*
* Callback for pg_operator and pg_cast inval events
*/
static void
InvalidateOprCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
{
HASH_SEQ_STATUS status;
OprCacheEntry *hentry;
Assert(OprCacheHash != NULL);
/* Currently we just flush all entries; hard to be smarter ... */
hash_seq_init(&status, OprCacheHash);
while ((hentry = (OprCacheEntry *) hash_seq_search(&status)) != NULL)
{
if (hash_search(OprCacheHash,
(void *) &hentry->key,
HASH_REMOVE, NULL) == NULL)
elog(ERROR, "hash table corrupted");
}
}
| oneeyeman1/dbhandler | libpg/src/backend/parser/parse_oper.c | C | gpl-3.0 | 31,718 |
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera 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.
*****************************************************************************/
/*****************************************************************************
T_2_3_1_5_neg.cpp --
Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#define MYNAME T_2_3_1_5
const int WIDTH = 8;
typedef sc_bv<WIDTH> my_vector;
typedef sc_signal<my_vector> signal_vector;
#include "T_2_3_1.h"
void
MYNAME::entry()
{
my_vector a;
my_vector b;
a = x;
b = y;
z = a | b;
wait();
a = x.read() | y.read();
b = x.read() ^ y.read();
z = a & b;
wait();
a = x.read() & y.read();
b = x.read() | y.read();
z = a ^ b;
wait();
a = ~ x.read();
b = ~ y.read();
z = a | b;
wait();
}
int
sc_main( int, char*[] )
{
return 0;
}
| vineodd/PIMSim | GEM5Simulation/gem5/src/systemc/tests/systemc/misc/semantic/2.3/T_2_3_1_5_neg/T_2_3_1_5_neg.cpp | C++ | gpl-3.0 | 2,096 |
# coding=utf-8
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Item",
"_doctype": "Item",
"color": "#f39c12",
"icon": "octicon octicon-package",
"type": "link",
"link": "List/Item"
},
{
"module_name": "Customer",
"_doctype": "Customer",
"color": "#1abc9c",
"icon": "octicon octicon-tag",
"type": "link",
"link": "List/Customer"
},
{
"module_name": "Supplier",
"_doctype": "Supplier",
"color": "#c0392b",
"icon": "octicon octicon-briefcase",
"type": "link",
"link": "List/Supplier"
},
{
"_doctype": "Employee",
"module_name": "Employee",
"color": "#2ecc71",
"icon": "octicon octicon-organization",
"type": "link",
"link": "List/Employee"
},
{
"module_name": "Project",
"_doctype": "Project",
"color": "#8e44ad",
"icon": "octicon octicon-rocket",
"type": "link",
"link": "List/Project"
},
{
"module_name": "Issue",
"color": "#2c3e50",
"icon": "octicon octicon-issue-opened",
"_doctype": "Issue",
"type": "link",
"link": "List/Issue"
},
{
"module_name": "Lead",
"icon": "octicon octicon-broadcast",
"_doctype": "Lead",
"type": "link",
"link": "List/Lead"
},
{
"module_name": "Profit and Loss Statement",
"_doctype": "Account",
"color": "#3498db",
"icon": "octicon octicon-repo",
"type": "link",
"link": "query-report/Profit and Loss Statement"
},
# old
{
"module_name": "Accounts",
"color": "#3498db",
"icon": "octicon octicon-repo",
"type": "module",
"hidden": 1
},
{
"module_name": "Stock",
"color": "#f39c12",
"icon": "octicon octicon-package",
"type": "module",
"hidden": 1
},
{
"module_name": "CRM",
"color": "#EF4DB6",
"icon": "octicon octicon-broadcast",
"type": "module",
"hidden": 1
},
{
"module_name": "Selling",
"color": "#1abc9c",
"icon": "octicon octicon-tag",
"type": "module",
"hidden": 1
},
{
"module_name": "Buying",
"color": "#c0392b",
"icon": "octicon octicon-briefcase",
"type": "module",
"hidden": 1
},
{
"module_name": "HR",
"color": "#2ecc71",
"icon": "octicon octicon-organization",
"label": _("Human Resources"),
"type": "module",
"hidden": 1
},
{
"module_name": "Manufacturing",
"color": "#7f8c8d",
"icon": "octicon octicon-tools",
"type": "module",
"hidden": 1
},
{
"module_name": "POS",
"color": "#589494",
"icon": "octicon octicon-credit-card",
"type": "page",
"link": "pos",
"label": _("POS")
},
{
"module_name": "Leaderboard",
"color": "#589494",
"icon": "octicon octicon-graph",
"type": "page",
"link": "leaderboard",
"label": _("Leaderboard")
},
{
"module_name": "Projects",
"color": "#8e44ad",
"icon": "octicon octicon-rocket",
"type": "module",
"hidden": 1
},
{
"module_name": "Support",
"color": "#2c3e50",
"icon": "octicon octicon-issue-opened",
"type": "module",
"hidden": 1
},
{
"module_name": "Learn",
"color": "#FF888B",
"icon": "octicon octicon-device-camera-video",
"type": "module",
"is_help": True,
"label": _("Learn"),
"hidden": 1
},
{
"module_name": "Maintenance",
"color": "#FF888B",
"icon": "octicon octicon-tools",
"type": "module",
"label": _("Maintenance"),
"hidden": 1
},
{
"module_name": "Student",
"color": "#c0392b",
"icon": "octicon octicon-person",
"label": _("Student"),
"link": "List/Student",
"_doctype": "Student",
"type": "list",
"hidden": 1
},
{
"module_name": "Student Group",
"color": "#d59919",
"icon": "octicon octicon-organization",
"label": _("Student Group"),
"link": "List/Student Group",
"_doctype": "Student Group",
"type": "list",
"hidden": 1
},
{
"module_name": "Course Schedule",
"color": "#fd784f",
"icon": "octicon octicon-calendar",
"label": _("Course Schedule"),
"link": "List/Course Schedule/Calendar",
"_doctype": "Course Schedule",
"type": "list",
"hidden": 1
},
{
"module_name": "Student Attendance Tool",
"color": "#C0392B",
"icon": "octicon octicon-checklist",
"label": _("Student Attendance Tool"),
"link": "List/Student Attendance Tool",
"_doctype": "Student Attendance Tool",
"type": "list",
"hidden": 1
},
{
"module_name": "Course",
"color": "#8e44ad",
"icon": "octicon octicon-book",
"label": _("Course"),
"link": "List/Course",
"_doctype": "Course",
"type": "list",
"hidden": 1
},
{
"module_name": "Program",
"color": "#9b59b6",
"icon": "octicon octicon-repo",
"label": _("Program"),
"link": "List/Program",
"_doctype": "Program",
"type": "list",
"hidden": 1
},
{
"module_name": "Student Applicant",
"color": "#4d927f",
"icon": "octicon octicon-clippy",
"label": _("Student Applicant"),
"link": "List/Student Applicant",
"_doctype": "Student Applicant",
"type": "list",
"hidden": 1
},
{
"module_name": "Fees",
"color": "#83C21E",
"icon": "fa fa-money",
"label": _("Fees"),
"link": "List/Fees",
"_doctype": "Fees",
"type": "list",
"hidden": 1
},
{
"module_name": "Instructor",
"color": "#a99e4c",
"icon": "octicon octicon-broadcast",
"label": _("Instructor"),
"link": "List/Instructor",
"_doctype": "Instructor",
"type": "list",
"hidden": 1
},
{
"module_name": "Room",
"color": "#f22683",
"icon": "fa fa-map-marker",
"label": _("Room"),
"link": "List/Room",
"_doctype": "Room",
"type": "list",
"hidden": 1
},
{
"module_name": "Education",
"color": "#428B46",
"icon": "octicon octicon-mortar-board",
"type": "module",
"label": _("Education"),
"hidden": 1
},
{
"module_name": "Healthcare",
"color": "#FF888B",
"icon": "fa fa-heartbeat",
"type": "module",
"label": _("Healthcare"),
"hidden": 1
},
{
"module_name": "Patient",
"color": "#6BE273",
"icon": "fa fa-user",
"doctype": "Patient",
"type": "link",
"link": "List/Patient",
"label": _("Patient"),
"hidden": 1
},
{
"module_name": "Healthcare Practitioner",
"color": "#2ecc71",
"icon": "fa fa-user-md",
"doctype": "Healthcare Practitioner",
"type": "link",
"link": "List/Healthcare Practitioner",
"label": _("Healthcare Practitioner"),
"hidden": 1
},
{
"module_name": "Patient Appointment",
"color": "#934F92",
"icon": "fa fa-calendar-plus-o",
"doctype": "Patient Appointment",
"type": "link",
"link": "List/Patient Appointment",
"label": _("Patient Appointment"),
"hidden": 1
},
{
"module_name": "Patient Encounter",
"color": "#2ecc71",
"icon": "fa fa-stethoscope",
"doctype": "Patient Encounter",
"type": "link",
"link": "List/Patient Encounter",
"label": _("Patient Encounter"),
"hidden": 1
},
{
"module_name": "Lab Test",
"color": "#7578f6",
"icon": "octicon octicon-beaker",
"doctype": "Lab Test",
"type": "list",
"link": "List/Lab Test",
"label": _("Lab Test"),
"hidden": 1
},
{
"module_name": "Vital Signs",
"color": "#2ecc71",
"icon": "fa fa-thermometer-empty",
"doctype": "Vital Signs",
"type": "list",
"link": "List/Vital Signs",
"label": _("Vital Signs"),
"hidden": 1
},
{
"module_name": "Clinical Procedure",
"color": "#FF888B",
"icon": "fa fa-medkit",
"doctype": "Clinical Procedure",
"type": "list",
"link": "List/Clinical Procedure",
"label": _("Clinical Procedure"),
"hidden": 1
},
{
"module_name": "Inpatient Record",
"color": "#7578f6",
"icon": "fa fa-list-alt",
"doctype": "Inpatient Record",
"type": "list",
"link": "List/Inpatient Record",
"label": _("Inpatient Record"),
"hidden": 1
},
{
"module_name": "Hub",
"color": "#009248",
"icon": "/assets/erpnext/images/hub_logo.svg",
"type": "page",
"link": "Hub/Item",
"label": _("Hub")
},
{
"module_name": "Data Import",
"color": "#FFF168",
"reverse": 1,
"doctype": "Data Import",
"icon": "octicon octicon-cloud-upload",
"label": _("Data Import"),
"link": "List/Data Import",
"type": "list"
},
{
"module_name": "Restaurant",
"color": "#EA81E8",
"icon": "🍔",
"_doctype": "Restaurant",
"type": "module",
"link": "List/Restaurant",
"label": _("Restaurant"),
"hidden": 1
},
{
"module_name": "Hotels",
"color": "#EA81E8",
"icon": "fa fa-bed",
"type": "module",
"label": _("Hotels"),
"hidden": 1
},
{
"module_name": "Agriculture",
"color": "#8BC34A",
"icon": "octicon octicon-globe",
"type": "module",
"label": _("Agriculture"),
"hidden": 1
},
{
"module_name": "Crop",
"_doctype": "Crop",
"label": _("Crop"),
"color": "#8BC34A",
"icon": "fa fa-tree",
"type": "list",
"link": "List/Crop",
"hidden": 1
},
{
"module_name": "Crop Cycle",
"_doctype": "Crop Cycle",
"label": _("Crop Cycle"),
"color": "#8BC34A",
"icon": "fa fa-circle-o-notch",
"type": "list",
"link": "List/Crop Cycle",
"hidden": 1
},
{
"module_name": "Fertilizer",
"_doctype": "Fertilizer",
"label": _("Fertilizer"),
"color": "#8BC34A",
"icon": "fa fa-leaf",
"type": "list",
"link": "List/Fertilizer",
"hidden": 1
},
{
"module_name": "Location",
"_doctype": "Location",
"label": _("Location"),
"color": "#8BC34A",
"icon": "fa fa-map",
"type": "list",
"link": "List/Location",
"hidden": 1
},
{
"module_name": "Disease",
"_doctype": "Disease",
"label": _("Disease"),
"color": "#8BC34A",
"icon": "octicon octicon-bug",
"type": "list",
"link": "List/Disease",
"hidden": 1
},
{
"module_name": "Plant Analysis",
"_doctype": "Plant Analysis",
"label": _("Plant Analysis"),
"color": "#8BC34A",
"icon": "fa fa-pagelines",
"type": "list",
"link": "List/Plant Analysis",
"hidden": 1
},
{
"module_name": "Soil Analysis",
"_doctype": "Soil Analysis",
"label": _("Soil Analysis"),
"color": "#8BC34A",
"icon": "fa fa-flask",
"type": "list",
"link": "List/Soil Analysis",
"hidden": 1
},
{
"module_name": "Soil Texture",
"_doctype": "Soil Texture",
"label": _("Soil Texture"),
"color": "#8BC34A",
"icon": "octicon octicon-beaker",
"type": "list",
"link": "List/Soil Texture",
"hidden": 1
},
{
"module_name": "Water Analysis",
"_doctype": "Water Analysis",
"label": _("Water Analysis"),
"color": "#8BC34A",
"icon": "fa fa-tint",
"type": "list",
"link": "List/Water Analysis",
"hidden": 1
},
{
"module_name": "Weather",
"_doctype": "Weather",
"label": _("Weather"),
"color": "#8BC34A",
"icon": "fa fa-sun-o",
"type": "list",
"link": "List/Weather",
"hidden": 1
},
{
"module_name": "Assets",
"color": "#4286f4",
"icon": "octicon octicon-database",
"hidden": 1,
"label": _("Assets"),
"type": "module"
},
{
"module_name": "Grant Application",
"color": "#E9AB17",
"icon": "fa fa-gift",
"_doctype": "Grant Application",
"type": "list",
"link": "List/Grant Application",
"label": _("Grant Application"),
"hidden": 1
},
{
"module_name": "Donor",
"color": "#7F5A58",
"icon": "fa fa-tint",
"_doctype": "Donor",
"type": "list",
"link": "List/Donor",
"label": _("Donor"),
"hidden": 1
},
{
"module_name": "Volunteer",
"color": "#7E587E",
"icon": "fa fa-angellist",
"_doctype": "Volunteer",
"type": "list",
"link": "List/Volunteer",
"label": _("Volunteer"),
"hidden": 1
},
{
"module_name": "Member",
"color": "#79BAEC",
"icon": "fa fa-users",
"_doctype": "Member",
"type": "list",
"link": "List/Member",
"label": _("Member"),
"hidden": 1
},
{
"module_name": "Chapter",
"color": "#3B9C9C",
"icon": "fa fa-handshake-o",
"_doctype": "Chapter",
"type": "list",
"link": "List/Chapter",
"label": _("Chapter"),
"hidden": 1
},
{
"module_name": "Non Profit",
"color": "#DE2B37",
"icon": "octicon octicon-heart",
"type": "module",
"label": _("Non Profit"),
"hidden": 1
}
]
| ovresko/erpnext | erpnext/config/desktop.py | Python | gpl-3.0 | 12,428 |
-----------------------------------
-- Area: Batallia_Downs_[S]
-- NPC: Yilbegan
-----------------------------------
require("scripts/globals/titles");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
killer:addTitle(YILBEGAN_HIDEFLAYER);
end; | FFXIOrgins/FFXIOrgins | scripts/zones/Batallia_Downs_[S]/mobs/Yilbegan.lua | Lua | gpl-3.0 | 463 |
#Region "Microsoft.VisualBasic::3b77316b6c4bc3ac1e35e4fe005b81fd, Data_science\MachineLearning\Bootstrapping\Monte-Carlo\Example.vb"
' Author:
'
' asuka (amethyst.asuka@gcmodeller.org)
' xie (genetics@smrucc.org)
' xieguigang (xie.guigang@live.com)
'
' Copyright (c) 2018 GPL3 Licensed
'
'
' GNU GENERAL PUBLIC LICENSE (GPL3)
'
'
' 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 <http://www.gnu.org/licenses/>.
' /********************************************************************************/
' Summaries:
' Class Example
'
' Function: eigenvector, params, yinit
'
' Sub: func
'
' Class TestObservation
'
' Function: Compares, y0
'
' Sub: func
'
'
' /********************************************************************************/
#End Region
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel
Imports Microsoft.VisualBasic.Math
Imports Microsoft.VisualBasic.Math.LinearAlgebra
Imports Microsoft.VisualBasic.Math.Calculus
Namespace MonteCarlo.Example
''' <summary>
''' 计算步骤
'''
''' 1. 继承<see cref="Model"/>对象并实现具体的过程
''' 2. 设置好大概的参数的变化区间
''' 3. 设置好大概的函数初始值的变化区间
''' </summary>
Public Class Example : Inherits Model
Dim sin As var
Dim a As Double
Dim f As Double
Protected Overrides Sub func(dx As Double, ByRef dy As Vector)
dy(index:=sin) = a * Math.Sin(dx) + f
End Sub
Public Overrides Function params() As ValueRange()
Return {
New ValueRange(-1000, 1000) With {.Name = NameOf(a)},
New ValueRange(-1000, 1000) With {.Name = NameOf(f)}
}
End Function
Public Overrides Function yinit() As ValueRange()
Return {
New ValueRange(-1000, 1000) With {.Name = NameOf(sin)}
}
End Function
Public Overrides Function eigenvector() As Dictionary(Of String, Eigenvector)
Return Nothing
End Function
End Class
Public Class TestObservation : Inherits ODEs
Dim sin As var
Dim a As Double = 10
Dim f As Double = -9.3
Dim compare As Boolean = False
Protected Overrides Sub func(dx As Double, ByRef dy As Vector)
dy(index:=sin) = a * Math.Sin(dx) + f
End Sub
Protected Overrides Function y0() As var()
If compare Then
Return {sin}
Else
Return {sin = f}
End If
End Function
Public Shared Iterator Function Compares(n As Integer, a As Integer, b As Integer, parms As Dictionary(Of String, Double)) As IEnumerable(Of ODEsOut)
Yield New TestObservation().Solve(n, a, b)
Yield New TestObservation With {
.a = parms(NameOf(a)),
.compare = True,
.f = parms(NameOf(f)),
.sin = New var With {
.Name = NameOf(sin),
.value = parms(NameOf(sin))
}
}.Solve(n, a, b)
End Function
End Class
End Namespace
| xieguigang/GCModeller | src/runtime/sciBASIC#/Data_science/MachineLearning/Bootstrapping/Monte-Carlo/Example.vb | Visual Basic | gpl-3.0 | 3,955 |
#ifndef ASEMANAUDIORECORDER_H
#define ASEMANAUDIORECORDER_H
#include <QObject>
#include <QUrl>
#include <QMediaRecorder>
#include <QStringList>
class AsemanAudioEncoderSettings;
class AsemanAudioRecorderPrivate;
class AsemanAudioRecorder : public QObject
{
Q_OBJECT
Q_ENUMS(State)
Q_ENUMS(Status)
Q_PROPERTY(AsemanAudioEncoderSettings* encoderSettings READ encoderSettings WRITE setEncoderSettings NOTIFY encoderSettingsChanged)
Q_PROPERTY(QUrl output READ output WRITE setOutput NOTIFY outputChanged)
Q_PROPERTY(bool mute READ mute WRITE setMute NOTIFY muteChanged)
Q_PROPERTY(bool available READ available NOTIFY availableChanged)
Q_PROPERTY(int availability READ availability NOTIFY availabilityChanged)
Q_PROPERTY(int state READ state NOTIFY stateChanged)
Q_PROPERTY(int status READ status NOTIFY statusChanged)
Q_PROPERTY(qreal volume READ volume WRITE setVolume NOTIFY volumeChanged)
Q_PROPERTY(QString audioInput READ audioInput WRITE setAudioInput NOTIFY audioInputChanged)
Q_PROPERTY(QStringList audioInputs READ audioInputs NOTIFY audioInputsChanged)
public:
enum State
{
StoppedState = QMediaRecorder::StoppedState,
RecordingState = QMediaRecorder::RecordingState,
PausedState = QMediaRecorder::PausedState
};
enum Status {
UnavailableStatus = QMediaRecorder::UnavailableStatus,
UnloadedStatus = QMediaRecorder::UnloadedStatus,
LoadingStatus = QMediaRecorder::LoadingStatus,
LoadedStatus = QMediaRecorder::LoadedStatus,
StartingStatus = QMediaRecorder::StartingStatus,
RecordingStatus = QMediaRecorder::RecordingStatus,
PausedStatus = QMediaRecorder::PausedStatus,
FinalizingStatus = QMediaRecorder::FinalizingStatus
};
AsemanAudioRecorder(QObject *parent = 0);
~AsemanAudioRecorder();
AsemanAudioEncoderSettings *encoderSettings() const;
void setEncoderSettings(AsemanAudioEncoderSettings *settings);
void setOutput(const QUrl &url);
QUrl output() const;
bool mute() const;
void setMute(bool stt);
qreal volume() const;
void setVolume(qreal vol);
void setAudioInput(const QString &input);
QString audioInput() const;
QStringList audioInputs() const;
bool available() const;
int availability() const;
int state() const;
int status() const;
public slots:
void stop();
void pause();
void record();
signals:
void encoderSettingsChanged();
void outputChanged();
void muteChanged();
void volumeChanged();
void availableChanged();
void availabilityChanged();
void stateChanged();
void statusChanged();
void audioInputChanged();
void audioInputsChanged();
private:
AsemanAudioRecorderPrivate *p;
};
#endif // ASEMANAUDIORECORDER_H
| NileGroup/JamiatApp | asemantools/asemanaudiorecorder.h | C | gpl-3.0 | 2,835 |
/**
* Copyright (c) 2006-2011 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* 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. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_GRAPHICS_COLOR_H
#define LOVE_GRAPHICS_COLOR_H
namespace love
{
namespace graphics
{
template <typename T>
struct ColorT
{
T r;
T g;
T b;
T a;
ColorT() : r(0), g(0), b(0), a(0) {}
ColorT(T r_, T g_, T b_, T a_) : r(r_), g(g_), b(b_), a(a_) {}
void set(T r_, T g_, T b_, T a_)
{
r = r_;
g = g_;
b = b_;
a = a_;
}
ColorT<T> operator+=(const ColorT<T> &other);
ColorT<T> operator*=(T s);
ColorT<T> operator/=(T s);
};
template <typename T>
ColorT<T> ColorT<T>::operator+=(const ColorT<T> &other)
{
r += other.r;
g += other.g;
b += other.b;
a += other.a;
return *this;
}
template <typename T>
ColorT<T> ColorT<T>::operator*=(T s)
{
r *= s;
g *= s;
b *= s;
a *= s;
return *this;
}
template <typename T>
ColorT<T> ColorT<T>::operator/=(T s)
{
r /= s;
g /= s;
b /= s;
a /= s;
return *this;
}
template <typename T>
ColorT<T> operator+(const ColorT<T> &a, const ColorT<T> &b)
{
ColorT<T> tmp(a);
return tmp += b;
}
template <typename T>
ColorT<T> operator*(const ColorT<T> &a, T s)
{
ColorT<T> tmp(a);
return tmp *= s;
}
template <typename T>
ColorT<T> operator/(const ColorT<T> &a, T s)
{
ColorT<T> tmp(a);
return tmp /= s;
}
typedef ColorT<unsigned char> Color;
typedef ColorT<float> Colorf;
} // graphics
} // love
#endif // LOVE_GRAPHICS_COLOR_H
| joedrago/love | src/modules/graphics/Color.h | C | gpl-3.0 | 2,232 |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose: Defines a group of app systems that all have the same lifetime
// that need to be connected/initialized, etc. in a well-defined order
//
// $Revision: $
// $NoKeywords: $
//=============================================================================
#ifndef IAPPSYSTEMGROUP_H
#define IAPPSYSTEMGROUP_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/interface.h"
#include "tier1/utlvector.h"
#include "tier1/utldict.h"
#include "IAppSystem.h"
//-----------------------------------------------------------------------------
// forward declarations
//-----------------------------------------------------------------------------
class IAppSystem;
class CSysModule;
class IBaseInterface;
class IFileSystem;
//-----------------------------------------------------------------------------
// Handle to a DLL
//-----------------------------------------------------------------------------
typedef int AppModule_t;
enum
{
APP_MODULE_INVALID = (AppModule_t)~0
};
//-----------------------------------------------------------------------------
// NOTE: The following methods must be implemented in your application
// although they can be empty implementations if you like...
//-----------------------------------------------------------------------------
abstract_class IAppSystemGroup
{
public:
// An installed application creation function, you should tell the group
// the DLLs and the singleton interfaces you want to instantiate.
// Return false if there's any problems and the app will abort
virtual bool Create( ) = 0;
// Allow the application to do some work after AppSystems are connected but
// they are all Initialized.
// Return false if there's any problems and the app will abort
virtual bool PreInit() = 0;
// Main loop implemented by the application
virtual int Main( ) = 0;
// Allow the application to do some work after all AppSystems are shut down
virtual void PostShutdown() = 0;
// Call an installed application destroy function, occurring after all modules
// are unloaded
virtual void Destroy() = 0;
};
//-----------------------------------------------------------------------------
// Specifies a module + interface name for initialization
//-----------------------------------------------------------------------------
struct AppSystemInfo_t
{
const char *m_pModuleName;
const char *m_pInterfaceName;
};
//-----------------------------------------------------------------------------
// This class represents a group of app systems that all have the same lifetime
// that need to be connected/initialized, etc. in a well-defined order
//-----------------------------------------------------------------------------
class CAppSystemGroup : public IAppSystemGroup
{
public:
// Used to determine where we exited out from the system
enum AppSystemGroupStage_t
{
CREATION = 0,
CONNECTION,
PREINITIALIZATION,
INITIALIZATION,
SHUTDOWN,
POSTSHUTDOWN,
DISCONNECTION,
DESTRUCTION,
NONE, // This means no error
};
public:
// constructor
CAppSystemGroup( CAppSystemGroup *pParentAppSystem = NULL );
// Runs the app system group.
// First, modules are loaded, next they are connected, followed by initialization
// Then Main() is run
// Then modules are shut down, disconnected, and unloaded
int Run( );
// Use this version in cases where you can't control the main loop and
// expect to be ticked
virtual int Startup();
virtual void Shutdown();
// Returns the stage at which the app system group ran into an error
AppSystemGroupStage_t GetErrorStage() const;
protected:
// These methods are meant to be called by derived classes of CAppSystemGroup
// Methods to load + unload DLLs
AppModule_t LoadModule( const char *pDLLName );
AppModule_t LoadModule( CreateInterfaceFn factory );
// Method to add various global singleton systems
IAppSystem *AddSystem( AppModule_t module, const char *pInterfaceName );
void AddSystem( IAppSystem *pAppSystem, const char *pInterfaceName );
// Simpler method of doing the LoadModule/AddSystem thing.
// Make sure the last AppSystemInfo has a NULL module name
bool AddSystems( AppSystemInfo_t *pSystems );
// Method to look up a particular named system...
void *FindSystem( const char *pInterfaceName );
// Gets at a class factory for the topmost appsystem group in an appsystem stack
static CreateInterfaceFn GetFactory();
private:
int OnStartup();
void OnShutdown();
void UnloadAllModules( );
void RemoveAllSystems();
// Method to connect/disconnect all systems
bool ConnectSystems( );
void DisconnectSystems();
// Method to initialize/shutdown all systems
InitReturnVal_t InitSystems();
void ShutdownSystems();
// Gets at the parent appsystem group
CAppSystemGroup *GetParent();
// Loads a module the standard way
virtual CSysModule *LoadModuleDLL( const char *pDLLName );
void ReportStartupFailure( int nErrorStage, int nSysIndex );
struct Module_t
{
CSysModule *m_pModule;
CreateInterfaceFn m_Factory;
char *m_pModuleName;
};
CUtlVector<Module_t> m_Modules;
CUtlVector<IAppSystem*> m_Systems;
CUtlDict<int, unsigned short> m_SystemDict;
CAppSystemGroup *m_pParentAppSystem;
AppSystemGroupStage_t m_nErrorStage;
friend void *AppSystemCreateInterfaceFn(const char *pName, int *pReturnCode);
friend class CSteamAppSystemGroup;
};
//-----------------------------------------------------------------------------
// This class represents a group of app systems that are loaded through steam
//-----------------------------------------------------------------------------
class CSteamAppSystemGroup : public CAppSystemGroup
{
public:
CSteamAppSystemGroup( IFileSystem *pFileSystem = NULL, CAppSystemGroup *pParentAppSystem = NULL );
// Used by CSteamApplication to set up necessary pointers if we can't do it in the constructor
void Setup( IFileSystem *pFileSystem, CAppSystemGroup *pParentAppSystem );
protected:
// Sets up the search paths
bool SetupSearchPaths( const char *pStartingDir, bool bOnlyUseStartingDir, bool bIsTool );
// Returns the game info path. Only works if you've called SetupSearchPaths first
const char *GetGameInfoPath() const;
private:
virtual CSysModule *LoadModuleDLL( const char *pDLLName );
IFileSystem *m_pFileSystem;
char m_pGameInfoPath[ MAX_PATH ];
};
//-----------------------------------------------------------------------------
// Helper empty decorator implementation of an IAppSystemGroup
//-----------------------------------------------------------------------------
template< class CBaseClass >
class CDefaultAppSystemGroup : public CBaseClass
{
public:
virtual bool Create( ) { return true; }
virtual bool PreInit() { return true; }
virtual void PostShutdown() {}
virtual void Destroy() {}
};
//-----------------------------------------------------------------------------
// Special helper for game info directory suggestion
//-----------------------------------------------------------------------------
class CFSSteamSetupInfo; // Forward declaration
//
// SuggestGameInfoDirFn_t
// Game info suggestion function.
// Provided by the application to possibly detect the suggested game info
// directory and initialize all the game-info-related systems appropriately.
// Parameters:
// pFsSteamSetupInfo steam file system setup information if available.
// pchPathBuffer buffer to hold game info directory path on return.
// nBufferLength length of the provided buffer to hold game info directory path.
// pbBubbleDirectories should contain "true" on return to bubble the directories up searching for game info file.
// Return values:
// Returns "true" if the game info directory path suggestion is available and
// was successfully copied into the provided buffer.
// Returns "false" otherwise, interpreted that no suggestion will be used.
//
typedef bool ( * SuggestGameInfoDirFn_t ) ( CFSSteamSetupInfo const *pFsSteamSetupInfo, char *pchPathBuffer, int nBufferLength, bool *pbBubbleDirectories );
//
// SetSuggestGameInfoDirFn
// Installs the supplied game info directory suggestion function.
// Parameters:
// pfnNewFn the new game info directory suggestion function.
// Returns:
// The previously installed suggestion function or NULL if none was installed before.
// This function never fails.
//
SuggestGameInfoDirFn_t SetSuggestGameInfoDirFn( SuggestGameInfoDirFn_t pfnNewFn );
#endif // APPSYSTEMGROUP_H
| OnePointSeven/onepointseven | src/public/appframework/IAppSystemGroup.h | C | gpl-3.0 | 8,787 |
package eu.excitementproject.eop.globalgraphoptimizer.graph;
public class SynonymEdge extends AbstractRuleEdge{
public SynonymEdge(RelationNode node1, RelationNode node2, double score) throws Exception {
if(node1.id()<node2.id()) {
m_from = node1;
m_to = node2;
}
else if(node2.id()<node1.id()) {
m_from = node2;
m_to = node1;
}
else
throw new Exception("Loops are not allowed in the graph");
m_score=score;
}
public String toString() {
return m_from.id()+SYMBOL+m_to.id();
}
public RelationNode from() {
return m_from;
}
public RelationNode to() {
return m_to;
}
/**
* The setter needs to make sure that the setting is legal
* @param from
* @throws Exception
*/
public void setFrom(RelationNode from) throws Exception {
if(from.id()>=m_to.id())
throw new Exception("The id of the from must be smaller than the id of the to");
m_from=from;
}
public void setTo(RelationNode to) throws Exception {
if(to.id()<=m_from.id())
throw new Exception("The id of the to must be larger than the id of the from");
m_to=to;
}
public boolean equals(Object other) {
if(!(other instanceof SynonymEdge))
return false;
SynonymEdge otherEdge = (SynonymEdge) other;
return m_from.equals(otherEdge.m_from) && m_to.equals(otherEdge.m_to);
}
public int hashCode() {
return toString().hashCode();
}
public double score() {
return m_score;
}
public String toDotString() {
return "\t"+m_from.id()+"--"+m_to.id()+"[fontsize=10.0,label=\"\"];";
}
@Override
public String symbol() {
return SYMBOL;
}
public static final String SYMBOL = "--";
}
| madhumita-git/Excitement-Open-Platform | globalgraphoptimizer/src/main/java/eu/excitementproject/eop/globalgraphoptimizer/graph/SynonymEdge.java | Java | gpl-3.0 | 1,646 |
// Berkeley Open Infrastructure for Network Computing
// http://boinc.berkeley.edu
// Copyright (C) 2005 University of California
//
// This 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 software 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.
//
// To view the GNU Lesser General Public License visit
// http://www.gnu.org/copyleft/lesser.html
// or write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#ifndef _CAHIDEBOINCMASTERPROFILE_H_
#define _CAHIDEBOINCMASTERPROFILE_H_
class CAHideBOINCMasterProfile : public BOINCCABase
{
public:
CAHideBOINCMasterProfile(MSIHANDLE hMSIHandle);
~CAHideBOINCMasterProfile();
virtual UINT OnExecution();
};
#endif
| freehal/boinc-freehal | win_build/installerv2/redist/Windows/src/boinccas/CAHideBOINCMasterProfile.h | C | gpl-3.0 | 1,169 |
// Copyright (c) 2016-2021 Antony Polukhin
//
// 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)
#ifndef BOOST_PFR_DETAIL_MAKE_FLAT_TUPLE_OF_REFERENCES_HPP
#define BOOST_PFR_DETAIL_MAKE_FLAT_TUPLE_OF_REFERENCES_HPP
#pragma once
#include <boost/pfr/detail/config.hpp>
#include <utility> // metaprogramming stuff
#include <boost/pfr/detail/sequence_tuple.hpp>
#include <boost/pfr/detail/rvalue_t.hpp>
#include <boost/pfr/detail/make_integer_sequence.hpp>
namespace boost { namespace pfr { namespace detail {
template <std::size_t Index>
using size_t_ = std::integral_constant<std::size_t, Index >;
// Helper: Make a "getter" object corresponding to built-in tuple::get
// For user-defined structures, the getter should be "offset_based_getter"
struct sequence_tuple_getter {
template <std::size_t idx, typename TupleOfReferences>
decltype(auto) get(TupleOfReferences&& t, size_t_<idx>) const noexcept {
return sequence_tuple::get<idx>(std::forward<TupleOfReferences>(t));
}
};
template <class TupleOrUserType, class Getter, std::size_t Begin, std::size_t Size>
constexpr auto make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<Size>) noexcept;
template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr sequence_tuple::tuple<> make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<0>) noexcept;
template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr auto make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<1>) noexcept;
template <class... T>
constexpr auto tie_as_tuple_with_references(T&... args) noexcept {
return sequence_tuple::tuple<T&...>{ args... };
}
template <class... T>
constexpr decltype(auto) tie_as_tuple_with_references(detail::sequence_tuple::tuple<T...>& t) noexcept {
return detail::make_flat_tuple_of_references(t, sequence_tuple_getter{}, size_t_<0>{}, size_t_<sequence_tuple::tuple<T...>::size_v>{});
}
template <class... T>
constexpr decltype(auto) tie_as_tuple_with_references(const detail::sequence_tuple::tuple<T...>& t) noexcept {
return detail::make_flat_tuple_of_references(t, sequence_tuple_getter{}, size_t_<0>{}, size_t_<sequence_tuple::tuple<T...>::size_v>{});
}
template <class Tuple1, std::size_t... I1, class Tuple2, std::size_t... I2>
constexpr auto my_tuple_cat_impl(const Tuple1& t1, std::index_sequence<I1...>, const Tuple2& t2, std::index_sequence<I2...>) noexcept {
return detail::tie_as_tuple_with_references(
sequence_tuple::get<I1>(t1)...,
sequence_tuple::get<I2>(t2)...
);
}
template <class Tuple1, class Tuple2>
constexpr auto my_tuple_cat(const Tuple1& t1, const Tuple2& t2) noexcept {
return detail::my_tuple_cat_impl(
t1, detail::make_index_sequence< Tuple1::size_v >{},
t2, detail::make_index_sequence< Tuple2::size_v >{}
);
}
template <class TupleOrUserType, class Getter, std::size_t Begin, std::size_t Size>
constexpr auto make_flat_tuple_of_references(TupleOrUserType& t, const Getter& g, size_t_<Begin>, size_t_<Size>) noexcept {
constexpr std::size_t next_size = Size / 2;
return detail::my_tuple_cat(
detail::make_flat_tuple_of_references(t, g, size_t_<Begin>{}, size_t_<next_size>{}),
detail::make_flat_tuple_of_references(t, g, size_t_<Begin + Size / 2>{}, size_t_<Size - next_size>{})
);
}
template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr sequence_tuple::tuple<> make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<0>) noexcept {
return {};
}
template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr auto make_flat_tuple_of_references(TupleOrUserType& t, const Getter& g, size_t_<Begin>, size_t_<1>) noexcept {
return detail::tie_as_tuple_with_references(
g.get(t, size_t_<Begin>{})
);
}
}}} // namespace boost::pfr::detail
#endif // BOOST_PFR_DETAIL_MAKE_FLAT_TUPLE_OF_REFERENCES_HPP
| rneiss/PocketTorah | ios/Pods/Flipper-Boost-iOSX/boost/pfr/detail/make_flat_tuple_of_references.hpp | C++ | gpl-3.0 | 4,113 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'message_jabber', language 'zh_tw', branch 'MOODLE_25_STABLE'
*
* @package message_jabber
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['configjabberhost'] = '發送jabber訊息的伺服器';
$string['configjabberpassword'] = '連接Jabber伺服器的密碼';
$string['configjabberport'] = '連接Jabber伺服器所要使用的埠';
$string['configjabberserver'] = 'XMPP主機ID(如果與Jabber主機相同,可以留空白)';
$string['configjabberusername'] = '連接Jabber伺服器的用戶名稱';
$string['jabberhost'] = 'Jabber 主機';
$string['jabberid'] = 'Jabber ID';
$string['jabberpassword'] = 'Jabber密碼';
$string['jabberport'] = 'Jabber連接埠';
$string['jabberserver'] = 'Jabber伺服器';
$string['jabberusername'] = 'Jabber用戶名稱';
$string['notconfigured'] = '這Jabber伺服器沒有被配置,因此Jabber的訊息無法送出';
$string['pluginname'] = 'Jabber訊息';
| jamesclickap/taiwanlife_web | lang/zh_tw/message_jabber.php | PHP | gpl-3.0 | 1,775 |
/**
* @file iqthread.c
* @brief thread to receive iq samples
* @author John Melton, G0ORX/N6LYT
* @version 0.1
* @date 2009-10-13
*/
/* Copyright (C)
* 2009 - John Melton, G0ORX/N6LYT
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "iqthread.h"
#define SMALL_PACKETS
static int iq_socket;
static struct sockaddr_in iq_addr;
static int iq_length;
static pthread_t iq_thread_id;
static void (*iq_callback)(void *);
void* iq_thread(void* arg);
void init_iq_thread(int rx) {
iq_length=sizeof(iq_addr);
iq_socket=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(iq_socket<0) {
perror("create iq socket failed");
exit(1);
}
memset(&iq_addr,0,iq_length);
iq_addr.sin_family=AF_INET;
iq_addr.sin_addr.s_addr=htonl(INADDR_ANY);
iq_addr.sin_port=htons(IQPORT+rx);
if(bind(iq_socket,(struct sockaddr*)&iq_addr,iq_length)<0) {
perror("bind socket failed for iq socket");
exit(1);
}
}
int get_iq_port() {
return ntohs(iq_addr.sin_port);
}
void start_iq_thread( void(*callback)(void *)) {
iq_callback=callback;
if(pthread_create(&iq_thread_id,NULL,iq_thread,NULL)<0) {
perror("pthread_create failed for iq_thread");
exit(1);
}
}
void* iq_thread(void* arg) {
struct sockaddr_in server_addr;
int server_length;
int bytes;
char buffer[1024*4*2];
BUFFER small_buffer;
unsigned long sequence=0L;
unsigned short offset=0;;
unsigned short length;
fprintf(stderr,"iq_thread: listening on port %d\n",ntohs(iq_addr.sin_port));
#ifdef SMALL_PACKETS
fprintf(stderr,"SMALL_PACKETS defined\n");
#endif
while(1) {
#ifdef SMALL_PACKETS
while(1) {
bytes=recvfrom(iq_socket,(char*)&small_buffer,sizeof(small_buffer),0,(struct sockaddr*)&server_addr,&server_length);
if(bytes<0) {
perror("recvfrom socket failed for spectrum buffer");
exit(1);
}
if(small_buffer.offset==0) {
offset=0;
sequence=small_buffer.sequence;
// start of a frame
memcpy((char *)&buffer[small_buffer.offset],(char *)&small_buffer.data[0],small_buffer.length);
offset+=small_buffer.length;
} else {
if((sequence==small_buffer.sequence) && (offset==small_buffer.offset)) {
memcpy((char *)&buffer[small_buffer.offset],(char *)&small_buffer.data[0],small_buffer.length);
offset+=small_buffer.length;
if(offset==sizeof(buffer)) {
offset=0;
break;
}
} else {
}
}
}
#else
bytes=recvfrom(iq_socket,(char*)buffer,sizeof(buffer),0,(struct sockaddr*)&server_addr,&server_length);
if(bytes<0) {
perror("recvfrom failed for iq buffer");
exit(1);
}
#endif
// process the I/Q samples
iq_callback(buffer);
}
}
| w3sz/ghpsdr3-w3sz | trunk/src/monitor/iqthread.c | C | gpl-3.0 | 3,872 |
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#if !defined( WRECTH )
#define WRECTH
typedef struct rect_s
{
int left, right, top, bottom;
} wrect_t;
#endif | RichardRohac/vulkan-halflife | cl_dll/wrect.h | C | gpl-3.0 | 313 |
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* (Shared logic for modifications)
* LICENSE: See LICENSE in the top level directory
* FILE: mods/shared_logic/CClientStreamElement.cpp
* PURPOSE: Streamed entity class
* DEVELOPERS: Christian Myhre Lundheim <>
* Jax <>
* Alberto Alonso <rydencillo@gmail.com>
*
*****************************************************************************/
#include "StdInc.h"
using std::list;
CClientStreamElement::CClientStreamElement ( CClientStreamer * pStreamer, ElementID ID ) : CClientEntity ( ID )
{
m_pStreamer = pStreamer;
m_pStreamRow = NULL;
m_pStreamSector = NULL;
m_fExpDistance = 0.0f;
m_bStreamedIn = false;
m_bAttemptingToStreamIn = false;
m_usStreamReferences = 0; m_usStreamReferencesScript = 0;
m_pStreamer->AddElement ( this );
}
CClientStreamElement::~CClientStreamElement ( void )
{
m_pStreamer->RemoveElement ( this );
}
void CClientStreamElement::UpdateStreamPosition ( const CVector & vecPosition )
{
m_vecStreamPosition = vecPosition;
m_pStreamer->OnUpdateStreamPosition ( this );
m_pManager->OnUpdateStreamPosition ( this );
// Update attached elements stream position
list < CClientEntity* >::iterator i = m_AttachedEntities.begin();
for (; i != m_AttachedEntities.end(); i++)
{
CClientStreamElement* attachedElement = dynamic_cast< CClientStreamElement* > (*i);
if ( attachedElement )
{
attachedElement->UpdateStreamPosition( vecPosition + attachedElement->m_vecAttachedPosition );
}
}
}
void CClientStreamElement::InternalStreamIn ( bool bInstantly )
{
if ( !m_bStreamedIn && !m_bAttemptingToStreamIn )
{
m_bAttemptingToStreamIn = true;
StreamIn ( bInstantly );
}
}
void CClientStreamElement::InternalStreamOut ( void )
{
if ( m_bStreamedIn )
{
StreamOut ();
m_bStreamedIn = false;
// Stream out attached elements
list < CClientEntity* >::iterator i = m_AttachedEntities.begin();
for (; i != m_AttachedEntities.end(); i++)
{
CClientStreamElement* attachedElement = dynamic_cast< CClientStreamElement* > (*i);
if ( attachedElement )
{
attachedElement->InternalStreamOut();
}
}
CLuaArguments Arguments;
CallEvent ( "onClientElementStreamOut", Arguments, true );
}
}
void CClientStreamElement::NotifyCreate ( void )
{
m_bStreamedIn = true;
m_bAttemptingToStreamIn = false;
CLuaArguments Arguments;
CallEvent ( "onClientElementStreamIn", Arguments, true );
}
void CClientStreamElement::NotifyUnableToCreate ( void )
{
m_bAttemptingToStreamIn = false;
}
void CClientStreamElement::AddStreamReference ( bool bScript )
{
unsigned short * pRefs = ( bScript ) ? &m_usStreamReferencesScript : &m_usStreamReferences;
if ( (*pRefs) < 0xFFFF ) (*pRefs)++;
// Have we added the first reference?
if ( ( m_usStreamReferences + m_usStreamReferencesScript ) == 1 )
{
m_pStreamer->OnElementForceStreamIn ( this );
}
}
void CClientStreamElement::RemoveStreamReference ( bool bScript )
{
unsigned short * pRefs = ( bScript ) ? &m_usStreamReferencesScript : &m_usStreamReferences;
if ( (*pRefs) > 0 )
{
(*pRefs)--;
}
// Have we removed the last reference?
if ( ( m_usStreamReferences + m_usStreamReferencesScript ) == 0 )
{
m_pStreamer->OnElementForceStreamOut ( this );
}
}
unsigned short CClientStreamElement::GetStreamReferences ( bool bScript )
{
unsigned short * pRefs = ( bScript ) ? &m_usStreamReferencesScript : &m_usStreamReferences;
return (*pRefs);
}
void CClientStreamElement::StreamOutForABit ( void )
{
// Remove asap, very messy
InternalStreamOut ();
}
void CClientStreamElement::SetDimension ( unsigned short usDimension )
{
// Different dimension than before?
if ( m_usDimension != usDimension )
{
// Set the new dimension
m_usDimension = usDimension;
m_pStreamer->OnElementDimension ( this );
}
} | google-code-export/multitheftauto | MTA10/mods/shared_logic/CClientStreamElement.cpp | C++ | gpl-3.0 | 4,236 |
/* tc-aarch64.c -- Assemble for the AArch64 ISA
Copyright (C) 2009-2015 Free Software Foundation, Inc.
Contributed by ARM Ltd.
This file is part of GAS.
GAS 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.
GAS 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; see the file COPYING3. If not,
see <http://www.gnu.org/licenses/>. */
#include "as.h"
#include <limits.h>
#include <stdarg.h>
#include "bfd_stdint.h"
#define NO_RELOC 0
#include "safe-ctype.h"
#include "subsegs.h"
#include "obstack.h"
#ifdef OBJ_ELF
#include "elf/aarch64.h"
#include "dw2gencfi.h"
#endif
#include "dwarf2dbg.h"
/* Types of processor to assemble for. */
#ifndef CPU_DEFAULT
#define CPU_DEFAULT AARCH64_ARCH_V8
#endif
#define streq(a, b) (strcmp (a, b) == 0)
#define END_OF_INSN '\0'
static aarch64_feature_set cpu_variant;
/* Variables that we set while parsing command-line options. Once all
options have been read we re-process these values to set the real
assembly flags. */
static const aarch64_feature_set *mcpu_cpu_opt = NULL;
static const aarch64_feature_set *march_cpu_opt = NULL;
/* Constants for known architecture features. */
static const aarch64_feature_set cpu_default = CPU_DEFAULT;
#ifdef OBJ_ELF
/* Pre-defined "_GLOBAL_OFFSET_TABLE_" */
static symbolS *GOT_symbol;
/* Which ABI to use. */
enum aarch64_abi_type
{
AARCH64_ABI_LP64 = 0,
AARCH64_ABI_ILP32 = 1
};
/* AArch64 ABI for the output file. */
static enum aarch64_abi_type aarch64_abi = AARCH64_ABI_LP64;
/* When non-zero, program to a 32-bit model, in which the C data types
int, long and all pointer types are 32-bit objects (ILP32); or to a
64-bit model, in which the C int type is 32-bits but the C long type
and all pointer types are 64-bit objects (LP64). */
#define ilp32_p (aarch64_abi == AARCH64_ABI_ILP32)
#endif
enum neon_el_type
{
NT_invtype = -1,
NT_b,
NT_h,
NT_s,
NT_d,
NT_q
};
/* Bits for DEFINED field in neon_type_el. */
#define NTA_HASTYPE 1
#define NTA_HASINDEX 2
struct neon_type_el
{
enum neon_el_type type;
unsigned char defined;
unsigned width;
int64_t index;
};
#define FIXUP_F_HAS_EXPLICIT_SHIFT 0x00000001
struct reloc
{
bfd_reloc_code_real_type type;
expressionS exp;
int pc_rel;
enum aarch64_opnd opnd;
uint32_t flags;
unsigned need_libopcodes_p : 1;
};
struct aarch64_instruction
{
/* libopcodes structure for instruction intermediate representation. */
aarch64_inst base;
/* Record assembly errors found during the parsing. */
struct
{
enum aarch64_operand_error_kind kind;
const char *error;
} parsing_error;
/* The condition that appears in the assembly line. */
int cond;
/* Relocation information (including the GAS internal fixup). */
struct reloc reloc;
/* Need to generate an immediate in the literal pool. */
unsigned gen_lit_pool : 1;
};
typedef struct aarch64_instruction aarch64_instruction;
static aarch64_instruction inst;
static bfd_boolean parse_operands (char *, const aarch64_opcode *);
static bfd_boolean programmer_friendly_fixup (aarch64_instruction *);
/* Diagnostics inline function utilites.
These are lightweight utlities which should only be called by parse_operands
and other parsers. GAS processes each assembly line by parsing it against
instruction template(s), in the case of multiple templates (for the same
mnemonic name), those templates are tried one by one until one succeeds or
all fail. An assembly line may fail a few templates before being
successfully parsed; an error saved here in most cases is not a user error
but an error indicating the current template is not the right template.
Therefore it is very important that errors can be saved at a low cost during
the parsing; we don't want to slow down the whole parsing by recording
non-user errors in detail.
Remember that the objective is to help GAS pick up the most approapriate
error message in the case of multiple templates, e.g. FMOV which has 8
templates. */
static inline void
clear_error (void)
{
inst.parsing_error.kind = AARCH64_OPDE_NIL;
inst.parsing_error.error = NULL;
}
static inline bfd_boolean
error_p (void)
{
return inst.parsing_error.kind != AARCH64_OPDE_NIL;
}
static inline const char *
get_error_message (void)
{
return inst.parsing_error.error;
}
static inline enum aarch64_operand_error_kind
get_error_kind (void)
{
return inst.parsing_error.kind;
}
static inline void
set_error (enum aarch64_operand_error_kind kind, const char *error)
{
inst.parsing_error.kind = kind;
inst.parsing_error.error = error;
}
static inline void
set_recoverable_error (const char *error)
{
set_error (AARCH64_OPDE_RECOVERABLE, error);
}
/* Use the DESC field of the corresponding aarch64_operand entry to compose
the error message. */
static inline void
set_default_error (void)
{
set_error (AARCH64_OPDE_SYNTAX_ERROR, NULL);
}
static inline void
set_syntax_error (const char *error)
{
set_error (AARCH64_OPDE_SYNTAX_ERROR, error);
}
static inline void
set_first_syntax_error (const char *error)
{
if (! error_p ())
set_error (AARCH64_OPDE_SYNTAX_ERROR, error);
}
static inline void
set_fatal_syntax_error (const char *error)
{
set_error (AARCH64_OPDE_FATAL_SYNTAX_ERROR, error);
}
/* Number of littlenums required to hold an extended precision number. */
#define MAX_LITTLENUMS 6
/* Return value for certain parsers when the parsing fails; those parsers
return the information of the parsed result, e.g. register number, on
success. */
#define PARSE_FAIL -1
/* This is an invalid condition code that means no conditional field is
present. */
#define COND_ALWAYS 0x10
typedef struct
{
const char *template;
unsigned long value;
} asm_barrier_opt;
typedef struct
{
const char *template;
uint32_t value;
} asm_nzcv;
struct reloc_entry
{
char *name;
bfd_reloc_code_real_type reloc;
};
/* Structure for a hash table entry for a register. */
typedef struct
{
const char *name;
unsigned char number;
unsigned char type;
unsigned char builtin;
} reg_entry;
/* Macros to define the register types and masks for the purpose
of parsing. */
#undef AARCH64_REG_TYPES
#define AARCH64_REG_TYPES \
BASIC_REG_TYPE(R_32) /* w[0-30] */ \
BASIC_REG_TYPE(R_64) /* x[0-30] */ \
BASIC_REG_TYPE(SP_32) /* wsp */ \
BASIC_REG_TYPE(SP_64) /* sp */ \
BASIC_REG_TYPE(Z_32) /* wzr */ \
BASIC_REG_TYPE(Z_64) /* xzr */ \
BASIC_REG_TYPE(FP_B) /* b[0-31] *//* NOTE: keep FP_[BHSDQ] consecutive! */\
BASIC_REG_TYPE(FP_H) /* h[0-31] */ \
BASIC_REG_TYPE(FP_S) /* s[0-31] */ \
BASIC_REG_TYPE(FP_D) /* d[0-31] */ \
BASIC_REG_TYPE(FP_Q) /* q[0-31] */ \
BASIC_REG_TYPE(CN) /* c[0-7] */ \
BASIC_REG_TYPE(VN) /* v[0-31] */ \
/* Typecheck: any 64-bit int reg (inc SP exc XZR) */ \
MULTI_REG_TYPE(R64_SP, REG_TYPE(R_64) | REG_TYPE(SP_64)) \
/* Typecheck: any int (inc {W}SP inc [WX]ZR) */ \
MULTI_REG_TYPE(R_Z_SP, REG_TYPE(R_32) | REG_TYPE(R_64) \
| REG_TYPE(SP_32) | REG_TYPE(SP_64) \
| REG_TYPE(Z_32) | REG_TYPE(Z_64)) \
/* Typecheck: any [BHSDQ]P FP. */ \
MULTI_REG_TYPE(BHSDQ, REG_TYPE(FP_B) | REG_TYPE(FP_H) \
| REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q)) \
/* Typecheck: any int or [BHSDQ]P FP or V reg (exc SP inc [WX]ZR) */ \
MULTI_REG_TYPE(R_Z_BHSDQ_V, REG_TYPE(R_32) | REG_TYPE(R_64) \
| REG_TYPE(Z_32) | REG_TYPE(Z_64) | REG_TYPE(VN) \
| REG_TYPE(FP_B) | REG_TYPE(FP_H) \
| REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q)) \
/* Any integer register; used for error messages only. */ \
MULTI_REG_TYPE(R_N, REG_TYPE(R_32) | REG_TYPE(R_64) \
| REG_TYPE(SP_32) | REG_TYPE(SP_64) \
| REG_TYPE(Z_32) | REG_TYPE(Z_64)) \
/* Pseudo type to mark the end of the enumerator sequence. */ \
BASIC_REG_TYPE(MAX)
#undef BASIC_REG_TYPE
#define BASIC_REG_TYPE(T) REG_TYPE_##T,
#undef MULTI_REG_TYPE
#define MULTI_REG_TYPE(T,V) BASIC_REG_TYPE(T)
/* Register type enumerators. */
typedef enum
{
/* A list of REG_TYPE_*. */
AARCH64_REG_TYPES
} aarch64_reg_type;
#undef BASIC_REG_TYPE
#define BASIC_REG_TYPE(T) 1 << REG_TYPE_##T,
#undef REG_TYPE
#define REG_TYPE(T) (1 << REG_TYPE_##T)
#undef MULTI_REG_TYPE
#define MULTI_REG_TYPE(T,V) V,
/* Values indexed by aarch64_reg_type to assist the type checking. */
static const unsigned reg_type_masks[] =
{
AARCH64_REG_TYPES
};
#undef BASIC_REG_TYPE
#undef REG_TYPE
#undef MULTI_REG_TYPE
#undef AARCH64_REG_TYPES
/* Diagnostics used when we don't get a register of the expected type.
Note: this has to synchronized with aarch64_reg_type definitions
above. */
static const char *
get_reg_expected_msg (aarch64_reg_type reg_type)
{
const char *msg;
switch (reg_type)
{
case REG_TYPE_R_32:
msg = N_("integer 32-bit register expected");
break;
case REG_TYPE_R_64:
msg = N_("integer 64-bit register expected");
break;
case REG_TYPE_R_N:
msg = N_("integer register expected");
break;
case REG_TYPE_R_Z_SP:
msg = N_("integer, zero or SP register expected");
break;
case REG_TYPE_FP_B:
msg = N_("8-bit SIMD scalar register expected");
break;
case REG_TYPE_FP_H:
msg = N_("16-bit SIMD scalar or floating-point half precision "
"register expected");
break;
case REG_TYPE_FP_S:
msg = N_("32-bit SIMD scalar or floating-point single precision "
"register expected");
break;
case REG_TYPE_FP_D:
msg = N_("64-bit SIMD scalar or floating-point double precision "
"register expected");
break;
case REG_TYPE_FP_Q:
msg = N_("128-bit SIMD scalar or floating-point quad precision "
"register expected");
break;
case REG_TYPE_CN:
msg = N_("C0 - C15 expected");
break;
case REG_TYPE_R_Z_BHSDQ_V:
msg = N_("register expected");
break;
case REG_TYPE_BHSDQ: /* any [BHSDQ]P FP */
msg = N_("SIMD scalar or floating-point register expected");
break;
case REG_TYPE_VN: /* any V reg */
msg = N_("vector register expected");
break;
default:
as_fatal (_("invalid register type %d"), reg_type);
}
return msg;
}
/* Some well known registers that we refer to directly elsewhere. */
#define REG_SP 31
/* Instructions take 4 bytes in the object file. */
#define INSN_SIZE 4
/* Define some common error messages. */
#define BAD_SP _("SP not allowed here")
static struct hash_control *aarch64_ops_hsh;
static struct hash_control *aarch64_cond_hsh;
static struct hash_control *aarch64_shift_hsh;
static struct hash_control *aarch64_sys_regs_hsh;
static struct hash_control *aarch64_pstatefield_hsh;
static struct hash_control *aarch64_sys_regs_ic_hsh;
static struct hash_control *aarch64_sys_regs_dc_hsh;
static struct hash_control *aarch64_sys_regs_at_hsh;
static struct hash_control *aarch64_sys_regs_tlbi_hsh;
static struct hash_control *aarch64_reg_hsh;
static struct hash_control *aarch64_barrier_opt_hsh;
static struct hash_control *aarch64_nzcv_hsh;
static struct hash_control *aarch64_pldop_hsh;
static struct hash_control *aarch64_hint_opt_hsh;
/* Stuff needed to resolve the label ambiguity
As:
...
label: <insn>
may differ from:
...
label:
<insn> */
static symbolS *last_label_seen;
/* Literal pool structure. Held on a per-section
and per-sub-section basis. */
#define MAX_LITERAL_POOL_SIZE 1024
typedef struct literal_expression
{
expressionS exp;
/* If exp.op == O_big then this bignum holds a copy of the global bignum value. */
LITTLENUM_TYPE * bignum;
} literal_expression;
typedef struct literal_pool
{
literal_expression literals[MAX_LITERAL_POOL_SIZE];
unsigned int next_free_entry;
unsigned int id;
symbolS *symbol;
segT section;
subsegT sub_section;
int size;
struct literal_pool *next;
} literal_pool;
/* Pointer to a linked list of literal pools. */
static literal_pool *list_of_pools = NULL;
/* Pure syntax. */
/* This array holds the chars that always start a comment. If the
pre-processor is disabled, these aren't very useful. */
const char comment_chars[] = "";
/* This array holds the chars that only start a comment at the beginning of
a line. If the line seems to have the form '# 123 filename'
.line and .file directives will appear in the pre-processed output. */
/* Note that input_file.c hand checks for '#' at the beginning of the
first line of the input file. This is because the compiler outputs
#NO_APP at the beginning of its output. */
/* Also note that comments like this one will always work. */
const char line_comment_chars[] = "#";
const char line_separator_chars[] = ";";
/* Chars that can be used to separate mant
from exp in floating point numbers. */
const char EXP_CHARS[] = "eE";
/* Chars that mean this number is a floating point constant. */
/* As in 0f12.456 */
/* or 0d1.2345e12 */
const char FLT_CHARS[] = "rRsSfFdDxXeEpP";
/* Prefix character that indicates the start of an immediate value. */
#define is_immediate_prefix(C) ((C) == '#')
/* Separator character handling. */
#define skip_whitespace(str) do { if (*(str) == ' ') ++(str); } while (0)
static inline bfd_boolean
skip_past_char (char **str, char c)
{
if (**str == c)
{
(*str)++;
return TRUE;
}
else
return FALSE;
}
#define skip_past_comma(str) skip_past_char (str, ',')
/* Arithmetic expressions (possibly involving symbols). */
static bfd_boolean in_my_get_expression_p = FALSE;
/* Third argument to my_get_expression. */
#define GE_NO_PREFIX 0
#define GE_OPT_PREFIX 1
/* Return TRUE if the string pointed by *STR is successfully parsed
as an valid expression; *EP will be filled with the information of
such an expression. Otherwise return FALSE. */
static bfd_boolean
my_get_expression (expressionS * ep, char **str, int prefix_mode,
int reject_absent)
{
char *save_in;
segT seg;
int prefix_present_p = 0;
switch (prefix_mode)
{
case GE_NO_PREFIX:
break;
case GE_OPT_PREFIX:
if (is_immediate_prefix (**str))
{
(*str)++;
prefix_present_p = 1;
}
break;
default:
abort ();
}
memset (ep, 0, sizeof (expressionS));
save_in = input_line_pointer;
input_line_pointer = *str;
in_my_get_expression_p = TRUE;
seg = expression (ep);
in_my_get_expression_p = FALSE;
if (ep->X_op == O_illegal || (reject_absent && ep->X_op == O_absent))
{
/* We found a bad expression in md_operand(). */
*str = input_line_pointer;
input_line_pointer = save_in;
if (prefix_present_p && ! error_p ())
set_fatal_syntax_error (_("bad expression"));
else
set_first_syntax_error (_("bad expression"));
return FALSE;
}
#ifdef OBJ_AOUT
if (seg != absolute_section
&& seg != text_section
&& seg != data_section
&& seg != bss_section && seg != undefined_section)
{
set_syntax_error (_("bad segment"));
*str = input_line_pointer;
input_line_pointer = save_in;
return FALSE;
}
#else
(void) seg;
#endif
*str = input_line_pointer;
input_line_pointer = save_in;
return TRUE;
}
/* Turn a string in input_line_pointer into a floating point constant
of type TYPE, and store the appropriate bytes in *LITP. The number
of LITTLENUMS emitted is stored in *SIZEP. An error message is
returned, or NULL on OK. */
char *
md_atof (int type, char *litP, int *sizeP)
{
return ieee_md_atof (type, litP, sizeP, target_big_endian);
}
/* We handle all bad expressions here, so that we can report the faulty
instruction in the error message. */
void
md_operand (expressionS * exp)
{
if (in_my_get_expression_p)
exp->X_op = O_illegal;
}
/* Immediate values. */
/* Errors may be set multiple times during parsing or bit encoding
(particularly in the Neon bits), but usually the earliest error which is set
will be the most meaningful. Avoid overwriting it with later (cascading)
errors by calling this function. */
static void
first_error (const char *error)
{
if (! error_p ())
set_syntax_error (error);
}
/* Similiar to first_error, but this function accepts formatted error
message. */
static void
first_error_fmt (const char *format, ...)
{
va_list args;
enum
{ size = 100 };
/* N.B. this single buffer will not cause error messages for different
instructions to pollute each other; this is because at the end of
processing of each assembly line, error message if any will be
collected by as_bad. */
static char buffer[size];
if (! error_p ())
{
int ret ATTRIBUTE_UNUSED;
va_start (args, format);
ret = vsnprintf (buffer, size, format, args);
know (ret <= size - 1 && ret >= 0);
va_end (args);
set_syntax_error (buffer);
}
}
/* Register parsing. */
/* Generic register parser which is called by other specialized
register parsers.
CCP points to what should be the beginning of a register name.
If it is indeed a valid register name, advance CCP over it and
return the reg_entry structure; otherwise return NULL.
It does not issue diagnostics. */
static reg_entry *
parse_reg (char **ccp)
{
char *start = *ccp;
char *p;
reg_entry *reg;
#ifdef REGISTER_PREFIX
if (*start != REGISTER_PREFIX)
return NULL;
start++;
#endif
p = start;
if (!ISALPHA (*p) || !is_name_beginner (*p))
return NULL;
do
p++;
while (ISALPHA (*p) || ISDIGIT (*p) || *p == '_');
reg = (reg_entry *) hash_find_n (aarch64_reg_hsh, start, p - start);
if (!reg)
return NULL;
*ccp = p;
return reg;
}
/* Return TRUE if REG->TYPE is a valid type of TYPE; otherwise
return FALSE. */
static bfd_boolean
aarch64_check_reg_type (const reg_entry *reg, aarch64_reg_type type)
{
if (reg->type == type)
return TRUE;
switch (type)
{
case REG_TYPE_R64_SP: /* 64-bit integer reg (inc SP exc XZR). */
case REG_TYPE_R_Z_SP: /* Integer reg (inc {X}SP inc [WX]ZR). */
case REG_TYPE_R_Z_BHSDQ_V: /* Any register apart from Cn. */
case REG_TYPE_BHSDQ: /* Any [BHSDQ]P FP or SIMD scalar register. */
case REG_TYPE_VN: /* Vector register. */
gas_assert (reg->type < REG_TYPE_MAX && type < REG_TYPE_MAX);
return ((reg_type_masks[reg->type] & reg_type_masks[type])
== reg_type_masks[reg->type]);
default:
as_fatal ("unhandled type %d", type);
abort ();
}
}
/* Parse a register and return PARSE_FAIL if the register is not of type R_Z_SP.
Return the register number otherwise. *ISREG32 is set to one if the
register is 32-bit wide; *ISREGZERO is set to one if the register is
of type Z_32 or Z_64.
Note that this function does not issue any diagnostics. */
static int
aarch64_reg_parse_32_64 (char **ccp, int reject_sp, int reject_rz,
int *isreg32, int *isregzero)
{
char *str = *ccp;
const reg_entry *reg = parse_reg (&str);
if (reg == NULL)
return PARSE_FAIL;
if (! aarch64_check_reg_type (reg, REG_TYPE_R_Z_SP))
return PARSE_FAIL;
switch (reg->type)
{
case REG_TYPE_SP_32:
case REG_TYPE_SP_64:
if (reject_sp)
return PARSE_FAIL;
*isreg32 = reg->type == REG_TYPE_SP_32;
*isregzero = 0;
break;
case REG_TYPE_R_32:
case REG_TYPE_R_64:
*isreg32 = reg->type == REG_TYPE_R_32;
*isregzero = 0;
break;
case REG_TYPE_Z_32:
case REG_TYPE_Z_64:
if (reject_rz)
return PARSE_FAIL;
*isreg32 = reg->type == REG_TYPE_Z_32;
*isregzero = 1;
break;
default:
return PARSE_FAIL;
}
*ccp = str;
return reg->number;
}
/* Parse the qualifier of a SIMD vector register or a SIMD vector element.
Fill in *PARSED_TYPE and return TRUE if the parsing succeeds;
otherwise return FALSE.
Accept only one occurrence of:
8b 16b 2h 4h 8h 2s 4s 1d 2d
b h s d q */
static bfd_boolean
parse_neon_type_for_operand (struct neon_type_el *parsed_type, char **str)
{
char *ptr = *str;
unsigned width;
unsigned element_size;
enum neon_el_type type;
/* skip '.' */
ptr++;
if (!ISDIGIT (*ptr))
{
width = 0;
goto elt_size;
}
width = strtoul (ptr, &ptr, 10);
if (width != 1 && width != 2 && width != 4 && width != 8 && width != 16)
{
first_error_fmt (_("bad size %d in vector width specifier"), width);
return FALSE;
}
elt_size:
switch (TOLOWER (*ptr))
{
case 'b':
type = NT_b;
element_size = 8;
break;
case 'h':
type = NT_h;
element_size = 16;
break;
case 's':
type = NT_s;
element_size = 32;
break;
case 'd':
type = NT_d;
element_size = 64;
break;
case 'q':
if (width == 1)
{
type = NT_q;
element_size = 128;
break;
}
/* fall through. */
default:
if (*ptr != '\0')
first_error_fmt (_("unexpected character `%c' in element size"), *ptr);
else
first_error (_("missing element size"));
return FALSE;
}
if (width != 0 && width * element_size != 64 && width * element_size != 128
&& !(width == 2 && element_size == 16))
{
first_error_fmt (_
("invalid element size %d and vector size combination %c"),
width, *ptr);
return FALSE;
}
ptr++;
parsed_type->type = type;
parsed_type->width = width;
*str = ptr;
return TRUE;
}
/* Parse a single type, e.g. ".8b", leading period included.
Only applicable to Vn registers.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_neon_operand_type (struct neon_type_el *vectype, char **ccp)
{
char *str = *ccp;
if (*str == '.')
{
if (! parse_neon_type_for_operand (vectype, &str))
{
first_error (_("vector type expected"));
return FALSE;
}
}
else
return FALSE;
*ccp = str;
return TRUE;
}
/* Parse a register of the type TYPE.
Return PARSE_FAIL if the string pointed by *CCP is not a valid register
name or the parsed register is not of TYPE.
Otherwise return the register number, and optionally fill in the actual
type of the register in *RTYPE when multiple alternatives were given, and
return the register shape and element index information in *TYPEINFO.
IN_REG_LIST should be set with TRUE if the caller is parsing a register
list. */
static int
parse_typed_reg (char **ccp, aarch64_reg_type type, aarch64_reg_type *rtype,
struct neon_type_el *typeinfo, bfd_boolean in_reg_list)
{
char *str = *ccp;
const reg_entry *reg = parse_reg (&str);
struct neon_type_el atype;
struct neon_type_el parsetype;
bfd_boolean is_typed_vecreg = FALSE;
atype.defined = 0;
atype.type = NT_invtype;
atype.width = -1;
atype.index = 0;
if (reg == NULL)
{
if (typeinfo)
*typeinfo = atype;
set_default_error ();
return PARSE_FAIL;
}
if (! aarch64_check_reg_type (reg, type))
{
DEBUG_TRACE ("reg type check failed");
set_default_error ();
return PARSE_FAIL;
}
type = reg->type;
if (type == REG_TYPE_VN
&& parse_neon_operand_type (&parsetype, &str))
{
/* Register if of the form Vn.[bhsdq]. */
is_typed_vecreg = TRUE;
if (parsetype.width == 0)
/* Expect index. In the new scheme we cannot have
Vn.[bhsdq] represent a scalar. Therefore any
Vn.[bhsdq] should have an index following it.
Except in reglists ofcourse. */
atype.defined |= NTA_HASINDEX;
else
atype.defined |= NTA_HASTYPE;
atype.type = parsetype.type;
atype.width = parsetype.width;
}
if (skip_past_char (&str, '['))
{
expressionS exp;
/* Reject Sn[index] syntax. */
if (!is_typed_vecreg)
{
first_error (_("this type of register can't be indexed"));
return PARSE_FAIL;
}
if (in_reg_list == TRUE)
{
first_error (_("index not allowed inside register list"));
return PARSE_FAIL;
}
atype.defined |= NTA_HASINDEX;
my_get_expression (&exp, &str, GE_NO_PREFIX, 1);
if (exp.X_op != O_constant)
{
first_error (_("constant expression required"));
return PARSE_FAIL;
}
if (! skip_past_char (&str, ']'))
return PARSE_FAIL;
atype.index = exp.X_add_number;
}
else if (!in_reg_list && (atype.defined & NTA_HASINDEX) != 0)
{
/* Indexed vector register expected. */
first_error (_("indexed vector register expected"));
return PARSE_FAIL;
}
/* A vector reg Vn should be typed or indexed. */
if (type == REG_TYPE_VN && atype.defined == 0)
{
first_error (_("invalid use of vector register"));
}
if (typeinfo)
*typeinfo = atype;
if (rtype)
*rtype = type;
*ccp = str;
return reg->number;
}
/* Parse register.
Return the register number on success; return PARSE_FAIL otherwise.
If RTYPE is not NULL, return in *RTYPE the (possibly restricted) type of
the register (e.g. NEON double or quad reg when either has been requested).
If this is a NEON vector register with additional type information, fill
in the struct pointed to by VECTYPE (if non-NULL).
This parser does not handle register list. */
static int
aarch64_reg_parse (char **ccp, aarch64_reg_type type,
aarch64_reg_type *rtype, struct neon_type_el *vectype)
{
struct neon_type_el atype;
char *str = *ccp;
int reg = parse_typed_reg (&str, type, rtype, &atype,
/*in_reg_list= */ FALSE);
if (reg == PARSE_FAIL)
return PARSE_FAIL;
if (vectype)
*vectype = atype;
*ccp = str;
return reg;
}
static inline bfd_boolean
eq_neon_type_el (struct neon_type_el e1, struct neon_type_el e2)
{
return
e1.type == e2.type
&& e1.defined == e2.defined
&& e1.width == e2.width && e1.index == e2.index;
}
/* This function parses the NEON register list. On success, it returns
the parsed register list information in the following encoded format:
bit 18-22 | 13-17 | 7-11 | 2-6 | 0-1
4th regno | 3rd regno | 2nd regno | 1st regno | num_of_reg
The information of the register shape and/or index is returned in
*VECTYPE.
It returns PARSE_FAIL if the register list is invalid.
The list contains one to four registers.
Each register can be one of:
<Vt>.<T>[<index>]
<Vt>.<T>
All <T> should be identical.
All <index> should be identical.
There are restrictions on <Vt> numbers which are checked later
(by reg_list_valid_p). */
static int
parse_neon_reg_list (char **ccp, struct neon_type_el *vectype)
{
char *str = *ccp;
int nb_regs;
struct neon_type_el typeinfo, typeinfo_first;
int val, val_range;
int in_range;
int ret_val;
int i;
bfd_boolean error = FALSE;
bfd_boolean expect_index = FALSE;
if (*str != '{')
{
set_syntax_error (_("expecting {"));
return PARSE_FAIL;
}
str++;
nb_regs = 0;
typeinfo_first.defined = 0;
typeinfo_first.type = NT_invtype;
typeinfo_first.width = -1;
typeinfo_first.index = 0;
ret_val = 0;
val = -1;
val_range = -1;
in_range = 0;
do
{
if (in_range)
{
str++; /* skip over '-' */
val_range = val;
}
val = parse_typed_reg (&str, REG_TYPE_VN, NULL, &typeinfo,
/*in_reg_list= */ TRUE);
if (val == PARSE_FAIL)
{
set_first_syntax_error (_("invalid vector register in list"));
error = TRUE;
continue;
}
/* reject [bhsd]n */
if (typeinfo.defined == 0)
{
set_first_syntax_error (_("invalid scalar register in list"));
error = TRUE;
continue;
}
if (typeinfo.defined & NTA_HASINDEX)
expect_index = TRUE;
if (in_range)
{
if (val < val_range)
{
set_first_syntax_error
(_("invalid range in vector register list"));
error = TRUE;
}
val_range++;
}
else
{
val_range = val;
if (nb_regs == 0)
typeinfo_first = typeinfo;
else if (! eq_neon_type_el (typeinfo_first, typeinfo))
{
set_first_syntax_error
(_("type mismatch in vector register list"));
error = TRUE;
}
}
if (! error)
for (i = val_range; i <= val; i++)
{
ret_val |= i << (5 * nb_regs);
nb_regs++;
}
in_range = 0;
}
while (skip_past_comma (&str) || (in_range = 1, *str == '-'));
skip_whitespace (str);
if (*str != '}')
{
set_first_syntax_error (_("end of vector register list not found"));
error = TRUE;
}
str++;
skip_whitespace (str);
if (expect_index)
{
if (skip_past_char (&str, '['))
{
expressionS exp;
my_get_expression (&exp, &str, GE_NO_PREFIX, 1);
if (exp.X_op != O_constant)
{
set_first_syntax_error (_("constant expression required."));
error = TRUE;
}
if (! skip_past_char (&str, ']'))
error = TRUE;
else
typeinfo_first.index = exp.X_add_number;
}
else
{
set_first_syntax_error (_("expected index"));
error = TRUE;
}
}
if (nb_regs > 4)
{
set_first_syntax_error (_("too many registers in vector register list"));
error = TRUE;
}
else if (nb_regs == 0)
{
set_first_syntax_error (_("empty vector register list"));
error = TRUE;
}
*ccp = str;
if (! error)
*vectype = typeinfo_first;
return error ? PARSE_FAIL : (ret_val << 2) | (nb_regs - 1);
}
/* Directives: register aliases. */
static reg_entry *
insert_reg_alias (char *str, int number, aarch64_reg_type type)
{
reg_entry *new;
const char *name;
if ((new = hash_find (aarch64_reg_hsh, str)) != 0)
{
if (new->builtin)
as_warn (_("ignoring attempt to redefine built-in register '%s'"),
str);
/* Only warn about a redefinition if it's not defined as the
same register. */
else if (new->number != number || new->type != type)
as_warn (_("ignoring redefinition of register alias '%s'"), str);
return NULL;
}
name = xstrdup (str);
new = xmalloc (sizeof (reg_entry));
new->name = name;
new->number = number;
new->type = type;
new->builtin = FALSE;
if (hash_insert (aarch64_reg_hsh, name, (void *) new))
abort ();
return new;
}
/* Look for the .req directive. This is of the form:
new_register_name .req existing_register_name
If we find one, or if it looks sufficiently like one that we want to
handle any error here, return TRUE. Otherwise return FALSE. */
static bfd_boolean
create_register_alias (char *newname, char *p)
{
const reg_entry *old;
char *oldname, *nbuf;
size_t nlen;
/* The input scrubber ensures that whitespace after the mnemonic is
collapsed to single spaces. */
oldname = p;
if (strncmp (oldname, " .req ", 6) != 0)
return FALSE;
oldname += 6;
if (*oldname == '\0')
return FALSE;
old = hash_find (aarch64_reg_hsh, oldname);
if (!old)
{
as_warn (_("unknown register '%s' -- .req ignored"), oldname);
return TRUE;
}
/* If TC_CASE_SENSITIVE is defined, then newname already points to
the desired alias name, and p points to its end. If not, then
the desired alias name is in the global original_case_string. */
#ifdef TC_CASE_SENSITIVE
nlen = p - newname;
#else
newname = original_case_string;
nlen = strlen (newname);
#endif
nbuf = alloca (nlen + 1);
memcpy (nbuf, newname, nlen);
nbuf[nlen] = '\0';
/* Create aliases under the new name as stated; an all-lowercase
version of the new name; and an all-uppercase version of the new
name. */
if (insert_reg_alias (nbuf, old->number, old->type) != NULL)
{
for (p = nbuf; *p; p++)
*p = TOUPPER (*p);
if (strncmp (nbuf, newname, nlen))
{
/* If this attempt to create an additional alias fails, do not bother
trying to create the all-lower case alias. We will fail and issue
a second, duplicate error message. This situation arises when the
programmer does something like:
foo .req r0
Foo .req r1
The second .req creates the "Foo" alias but then fails to create
the artificial FOO alias because it has already been created by the
first .req. */
if (insert_reg_alias (nbuf, old->number, old->type) == NULL)
return TRUE;
}
for (p = nbuf; *p; p++)
*p = TOLOWER (*p);
if (strncmp (nbuf, newname, nlen))
insert_reg_alias (nbuf, old->number, old->type);
}
return TRUE;
}
/* Should never be called, as .req goes between the alias and the
register name, not at the beginning of the line. */
static void
s_req (int a ATTRIBUTE_UNUSED)
{
as_bad (_("invalid syntax for .req directive"));
}
/* The .unreq directive deletes an alias which was previously defined
by .req. For example:
my_alias .req r11
.unreq my_alias */
static void
s_unreq (int a ATTRIBUTE_UNUSED)
{
char *name;
char saved_char;
name = input_line_pointer;
while (*input_line_pointer != 0
&& *input_line_pointer != ' ' && *input_line_pointer != '\n')
++input_line_pointer;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
if (!*name)
as_bad (_("invalid syntax for .unreq directive"));
else
{
reg_entry *reg = hash_find (aarch64_reg_hsh, name);
if (!reg)
as_bad (_("unknown register alias '%s'"), name);
else if (reg->builtin)
as_warn (_("ignoring attempt to undefine built-in register '%s'"),
name);
else
{
char *p;
char *nbuf;
hash_delete (aarch64_reg_hsh, name, FALSE);
free ((char *) reg->name);
free (reg);
/* Also locate the all upper case and all lower case versions.
Do not complain if we cannot find one or the other as it
was probably deleted above. */
nbuf = strdup (name);
for (p = nbuf; *p; p++)
*p = TOUPPER (*p);
reg = hash_find (aarch64_reg_hsh, nbuf);
if (reg)
{
hash_delete (aarch64_reg_hsh, nbuf, FALSE);
free ((char *) reg->name);
free (reg);
}
for (p = nbuf; *p; p++)
*p = TOLOWER (*p);
reg = hash_find (aarch64_reg_hsh, nbuf);
if (reg)
{
hash_delete (aarch64_reg_hsh, nbuf, FALSE);
free ((char *) reg->name);
free (reg);
}
free (nbuf);
}
}
*input_line_pointer = saved_char;
demand_empty_rest_of_line ();
}
/* Directives: Instruction set selection. */
#ifdef OBJ_ELF
/* This code is to handle mapping symbols as defined in the ARM AArch64 ELF
spec. (See "Mapping symbols", section 4.5.4, ARM AAELF64 version 0.05).
Note that previously, $a and $t has type STT_FUNC (BSF_OBJECT flag),
and $d has type STT_OBJECT (BSF_OBJECT flag). Now all three are untyped. */
/* Create a new mapping symbol for the transition to STATE. */
static void
make_mapping_symbol (enum mstate state, valueT value, fragS * frag)
{
symbolS *symbolP;
const char *symname;
int type;
switch (state)
{
case MAP_DATA:
symname = "$d";
type = BSF_NO_FLAGS;
break;
case MAP_INSN:
symname = "$x";
type = BSF_NO_FLAGS;
break;
default:
abort ();
}
symbolP = symbol_new (symname, now_seg, value, frag);
symbol_get_bfdsym (symbolP)->flags |= type | BSF_LOCAL;
/* Save the mapping symbols for future reference. Also check that
we do not place two mapping symbols at the same offset within a
frag. We'll handle overlap between frags in
check_mapping_symbols.
If .fill or other data filling directive generates zero sized data,
the mapping symbol for the following code will have the same value
as the one generated for the data filling directive. In this case,
we replace the old symbol with the new one at the same address. */
if (value == 0)
{
if (frag->tc_frag_data.first_map != NULL)
{
know (S_GET_VALUE (frag->tc_frag_data.first_map) == 0);
symbol_remove (frag->tc_frag_data.first_map, &symbol_rootP,
&symbol_lastP);
}
frag->tc_frag_data.first_map = symbolP;
}
if (frag->tc_frag_data.last_map != NULL)
{
know (S_GET_VALUE (frag->tc_frag_data.last_map) <=
S_GET_VALUE (symbolP));
if (S_GET_VALUE (frag->tc_frag_data.last_map) == S_GET_VALUE (symbolP))
symbol_remove (frag->tc_frag_data.last_map, &symbol_rootP,
&symbol_lastP);
}
frag->tc_frag_data.last_map = symbolP;
}
/* We must sometimes convert a region marked as code to data during
code alignment, if an odd number of bytes have to be padded. The
code mapping symbol is pushed to an aligned address. */
static void
insert_data_mapping_symbol (enum mstate state,
valueT value, fragS * frag, offsetT bytes)
{
/* If there was already a mapping symbol, remove it. */
if (frag->tc_frag_data.last_map != NULL
&& S_GET_VALUE (frag->tc_frag_data.last_map) ==
frag->fr_address + value)
{
symbolS *symp = frag->tc_frag_data.last_map;
if (value == 0)
{
know (frag->tc_frag_data.first_map == symp);
frag->tc_frag_data.first_map = NULL;
}
frag->tc_frag_data.last_map = NULL;
symbol_remove (symp, &symbol_rootP, &symbol_lastP);
}
make_mapping_symbol (MAP_DATA, value, frag);
make_mapping_symbol (state, value + bytes, frag);
}
static void mapping_state_2 (enum mstate state, int max_chars);
/* Set the mapping state to STATE. Only call this when about to
emit some STATE bytes to the file. */
void
mapping_state (enum mstate state)
{
enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
if (state == MAP_INSN)
/* AArch64 instructions require 4-byte alignment. When emitting
instructions into any section, record the appropriate section
alignment. */
record_alignment (now_seg, 2);
if (mapstate == state)
/* The mapping symbol has already been emitted.
There is nothing else to do. */
return;
#define TRANSITION(from, to) (mapstate == (from) && state == (to))
if (TRANSITION (MAP_UNDEFINED, MAP_DATA) && !subseg_text_p (now_seg))
/* Emit MAP_DATA within executable section in order. Otherwise, it will be
evaluated later in the next else. */
return;
else if (TRANSITION (MAP_UNDEFINED, MAP_INSN))
{
/* Only add the symbol if the offset is > 0:
if we're at the first frag, check it's size > 0;
if we're not at the first frag, then for sure
the offset is > 0. */
struct frag *const frag_first = seg_info (now_seg)->frchainP->frch_root;
const int add_symbol = (frag_now != frag_first)
|| (frag_now_fix () > 0);
if (add_symbol)
make_mapping_symbol (MAP_DATA, (valueT) 0, frag_first);
}
#undef TRANSITION
mapping_state_2 (state, 0);
}
/* Same as mapping_state, but MAX_CHARS bytes have already been
allocated. Put the mapping symbol that far back. */
static void
mapping_state_2 (enum mstate state, int max_chars)
{
enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
if (!SEG_NORMAL (now_seg))
return;
if (mapstate == state)
/* The mapping symbol has already been emitted.
There is nothing else to do. */
return;
seg_info (now_seg)->tc_segment_info_data.mapstate = state;
make_mapping_symbol (state, (valueT) frag_now_fix () - max_chars, frag_now);
}
#else
#define mapping_state(x) /* nothing */
#define mapping_state_2(x, y) /* nothing */
#endif
/* Directives: sectioning and alignment. */
static void
s_bss (int ignore ATTRIBUTE_UNUSED)
{
/* We don't support putting frags in the BSS segment, we fake it by
marking in_bss, then looking at s_skip for clues. */
subseg_set (bss_section, 0);
demand_empty_rest_of_line ();
mapping_state (MAP_DATA);
}
static void
s_even (int ignore ATTRIBUTE_UNUSED)
{
/* Never make frag if expect extra pass. */
if (!need_pass_2)
frag_align (1, 0, 0);
record_alignment (now_seg, 1);
demand_empty_rest_of_line ();
}
/* Directives: Literal pools. */
static literal_pool *
find_literal_pool (int size)
{
literal_pool *pool;
for (pool = list_of_pools; pool != NULL; pool = pool->next)
{
if (pool->section == now_seg
&& pool->sub_section == now_subseg && pool->size == size)
break;
}
return pool;
}
static literal_pool *
find_or_make_literal_pool (int size)
{
/* Next literal pool ID number. */
static unsigned int latest_pool_num = 1;
literal_pool *pool;
pool = find_literal_pool (size);
if (pool == NULL)
{
/* Create a new pool. */
pool = xmalloc (sizeof (*pool));
if (!pool)
return NULL;
/* Currently we always put the literal pool in the current text
section. If we were generating "small" model code where we
knew that all code and initialised data was within 1MB then
we could output literals to mergeable, read-only data
sections. */
pool->next_free_entry = 0;
pool->section = now_seg;
pool->sub_section = now_subseg;
pool->size = size;
pool->next = list_of_pools;
pool->symbol = NULL;
/* Add it to the list. */
list_of_pools = pool;
}
/* New pools, and emptied pools, will have a NULL symbol. */
if (pool->symbol == NULL)
{
pool->symbol = symbol_create (FAKE_LABEL_NAME, undefined_section,
(valueT) 0, &zero_address_frag);
pool->id = latest_pool_num++;
}
/* Done. */
return pool;
}
/* Add the literal of size SIZE in *EXP to the relevant literal pool.
Return TRUE on success, otherwise return FALSE. */
static bfd_boolean
add_to_lit_pool (expressionS *exp, int size)
{
literal_pool *pool;
unsigned int entry;
pool = find_or_make_literal_pool (size);
/* Check if this literal value is already in the pool. */
for (entry = 0; entry < pool->next_free_entry; entry++)
{
expressionS * litexp = & pool->literals[entry].exp;
if ((litexp->X_op == exp->X_op)
&& (exp->X_op == O_constant)
&& (litexp->X_add_number == exp->X_add_number)
&& (litexp->X_unsigned == exp->X_unsigned))
break;
if ((litexp->X_op == exp->X_op)
&& (exp->X_op == O_symbol)
&& (litexp->X_add_number == exp->X_add_number)
&& (litexp->X_add_symbol == exp->X_add_symbol)
&& (litexp->X_op_symbol == exp->X_op_symbol))
break;
}
/* Do we need to create a new entry? */
if (entry == pool->next_free_entry)
{
if (entry >= MAX_LITERAL_POOL_SIZE)
{
set_syntax_error (_("literal pool overflow"));
return FALSE;
}
pool->literals[entry].exp = *exp;
pool->next_free_entry += 1;
if (exp->X_op == O_big)
{
/* PR 16688: Bignums are held in a single global array. We must
copy and preserve that value now, before it is overwritten. */
pool->literals[entry].bignum = xmalloc (CHARS_PER_LITTLENUM * exp->X_add_number);
memcpy (pool->literals[entry].bignum, generic_bignum,
CHARS_PER_LITTLENUM * exp->X_add_number);
}
else
pool->literals[entry].bignum = NULL;
}
exp->X_op = O_symbol;
exp->X_add_number = ((int) entry) * size;
exp->X_add_symbol = pool->symbol;
return TRUE;
}
/* Can't use symbol_new here, so have to create a symbol and then at
a later date assign it a value. Thats what these functions do. */
static void
symbol_locate (symbolS * symbolP,
const char *name,/* It is copied, the caller can modify. */
segT segment, /* Segment identifier (SEG_<something>). */
valueT valu, /* Symbol value. */
fragS * frag) /* Associated fragment. */
{
size_t name_length;
char *preserved_copy_of_name;
name_length = strlen (name) + 1; /* +1 for \0. */
obstack_grow (¬es, name, name_length);
preserved_copy_of_name = obstack_finish (¬es);
#ifdef tc_canonicalize_symbol_name
preserved_copy_of_name =
tc_canonicalize_symbol_name (preserved_copy_of_name);
#endif
S_SET_NAME (symbolP, preserved_copy_of_name);
S_SET_SEGMENT (symbolP, segment);
S_SET_VALUE (symbolP, valu);
symbol_clear_list_pointers (symbolP);
symbol_set_frag (symbolP, frag);
/* Link to end of symbol chain. */
{
extern int symbol_table_frozen;
if (symbol_table_frozen)
abort ();
}
symbol_append (symbolP, symbol_lastP, &symbol_rootP, &symbol_lastP);
obj_symbol_new_hook (symbolP);
#ifdef tc_symbol_new_hook
tc_symbol_new_hook (symbolP);
#endif
#ifdef DEBUG_SYMS
verify_symbol_chain (symbol_rootP, symbol_lastP);
#endif /* DEBUG_SYMS */
}
static void
s_ltorg (int ignored ATTRIBUTE_UNUSED)
{
unsigned int entry;
literal_pool *pool;
char sym_name[20];
int align;
for (align = 2; align <= 4; align++)
{
int size = 1 << align;
pool = find_literal_pool (size);
if (pool == NULL || pool->symbol == NULL || pool->next_free_entry == 0)
continue;
mapping_state (MAP_DATA);
/* Align pool as you have word accesses.
Only make a frag if we have to. */
if (!need_pass_2)
frag_align (align, 0, 0);
record_alignment (now_seg, align);
sprintf (sym_name, "$$lit_\002%x", pool->id);
symbol_locate (pool->symbol, sym_name, now_seg,
(valueT) frag_now_fix (), frag_now);
symbol_table_insert (pool->symbol);
for (entry = 0; entry < pool->next_free_entry; entry++)
{
expressionS * exp = & pool->literals[entry].exp;
if (exp->X_op == O_big)
{
/* PR 16688: Restore the global bignum value. */
gas_assert (pool->literals[entry].bignum != NULL);
memcpy (generic_bignum, pool->literals[entry].bignum,
CHARS_PER_LITTLENUM * exp->X_add_number);
}
/* First output the expression in the instruction to the pool. */
emit_expr (exp, size); /* .word|.xword */
if (exp->X_op == O_big)
{
free (pool->literals[entry].bignum);
pool->literals[entry].bignum = NULL;
}
}
/* Mark the pool as empty. */
pool->next_free_entry = 0;
pool->symbol = NULL;
}
}
#ifdef OBJ_ELF
/* Forward declarations for functions below, in the MD interface
section. */
static fixS *fix_new_aarch64 (fragS *, int, short, expressionS *, int, int);
static struct reloc_table_entry * find_reloc_table_entry (char **);
/* Directives: Data. */
/* N.B. the support for relocation suffix in this directive needs to be
implemented properly. */
static void
s_aarch64_elf_cons (int nbytes)
{
expressionS exp;
#ifdef md_flush_pending_output
md_flush_pending_output ();
#endif
if (is_it_end_of_statement ())
{
demand_empty_rest_of_line ();
return;
}
#ifdef md_cons_align
md_cons_align (nbytes);
#endif
mapping_state (MAP_DATA);
do
{
struct reloc_table_entry *reloc;
expression (&exp);
if (exp.X_op != O_symbol)
emit_expr (&exp, (unsigned int) nbytes);
else
{
skip_past_char (&input_line_pointer, '#');
if (skip_past_char (&input_line_pointer, ':'))
{
reloc = find_reloc_table_entry (&input_line_pointer);
if (reloc == NULL)
as_bad (_("unrecognized relocation suffix"));
else
as_bad (_("unimplemented relocation suffix"));
ignore_rest_of_line ();
return;
}
else
emit_expr (&exp, (unsigned int) nbytes);
}
}
while (*input_line_pointer++ == ',');
/* Put terminator back into stream. */
input_line_pointer--;
demand_empty_rest_of_line ();
}
#endif /* OBJ_ELF */
/* Output a 32-bit word, but mark as an instruction. */
static void
s_aarch64_inst (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
#ifdef md_flush_pending_output
md_flush_pending_output ();
#endif
if (is_it_end_of_statement ())
{
demand_empty_rest_of_line ();
return;
}
/* Sections are assumed to start aligned. In executable section, there is no
MAP_DATA symbol pending. So we only align the address during
MAP_DATA --> MAP_INSN transition.
For other sections, this is not guaranteed. */
enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
if (!need_pass_2 && subseg_text_p (now_seg) && mapstate == MAP_DATA)
frag_align_code (2, 0);
#ifdef OBJ_ELF
mapping_state (MAP_INSN);
#endif
do
{
expression (&exp);
if (exp.X_op != O_constant)
{
as_bad (_("constant expression required"));
ignore_rest_of_line ();
return;
}
if (target_big_endian)
{
unsigned int val = exp.X_add_number;
exp.X_add_number = SWAP_32 (val);
}
emit_expr (&exp, 4);
}
while (*input_line_pointer++ == ',');
/* Put terminator back into stream. */
input_line_pointer--;
demand_empty_rest_of_line ();
}
#ifdef OBJ_ELF
/* Emit BFD_RELOC_AARCH64_TLSDESC_ADD on the next ADD instruction. */
static void
s_tlsdescadd (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
expression (&exp);
frag_grow (4);
fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
BFD_RELOC_AARCH64_TLSDESC_ADD);
demand_empty_rest_of_line ();
}
/* Emit BFD_RELOC_AARCH64_TLSDESC_CALL on the next BLR instruction. */
static void
s_tlsdesccall (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
/* Since we're just labelling the code, there's no need to define a
mapping symbol. */
expression (&exp);
/* Make sure there is enough room in this frag for the following
blr. This trick only works if the blr follows immediately after
the .tlsdesc directive. */
frag_grow (4);
fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
BFD_RELOC_AARCH64_TLSDESC_CALL);
demand_empty_rest_of_line ();
}
/* Emit BFD_RELOC_AARCH64_TLSDESC_LDR on the next LDR instruction. */
static void
s_tlsdescldr (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
expression (&exp);
frag_grow (4);
fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
BFD_RELOC_AARCH64_TLSDESC_LDR);
demand_empty_rest_of_line ();
}
#endif /* OBJ_ELF */
static void s_aarch64_arch (int);
static void s_aarch64_cpu (int);
static void s_aarch64_arch_extension (int);
/* This table describes all the machine specific pseudo-ops the assembler
has to support. The fields are:
pseudo-op name without dot
function to call to execute this pseudo-op
Integer arg to pass to the function. */
const pseudo_typeS md_pseudo_table[] = {
/* Never called because '.req' does not start a line. */
{"req", s_req, 0},
{"unreq", s_unreq, 0},
{"bss", s_bss, 0},
{"even", s_even, 0},
{"ltorg", s_ltorg, 0},
{"pool", s_ltorg, 0},
{"cpu", s_aarch64_cpu, 0},
{"arch", s_aarch64_arch, 0},
{"arch_extension", s_aarch64_arch_extension, 0},
{"inst", s_aarch64_inst, 0},
#ifdef OBJ_ELF
{"tlsdescadd", s_tlsdescadd, 0},
{"tlsdesccall", s_tlsdesccall, 0},
{"tlsdescldr", s_tlsdescldr, 0},
{"word", s_aarch64_elf_cons, 4},
{"long", s_aarch64_elf_cons, 4},
{"xword", s_aarch64_elf_cons, 8},
{"dword", s_aarch64_elf_cons, 8},
#endif
{0, 0, 0}
};
/* Check whether STR points to a register name followed by a comma or the
end of line; REG_TYPE indicates which register types are checked
against. Return TRUE if STR is such a register name; otherwise return
FALSE. The function does not intend to produce any diagnostics, but since
the register parser aarch64_reg_parse, which is called by this function,
does produce diagnostics, we call clear_error to clear any diagnostics
that may be generated by aarch64_reg_parse.
Also, the function returns FALSE directly if there is any user error
present at the function entry. This prevents the existing diagnostics
state from being spoiled.
The function currently serves parse_constant_immediate and
parse_big_immediate only. */
static bfd_boolean
reg_name_p (char *str, aarch64_reg_type reg_type)
{
int reg;
/* Prevent the diagnostics state from being spoiled. */
if (error_p ())
return FALSE;
reg = aarch64_reg_parse (&str, reg_type, NULL, NULL);
/* Clear the parsing error that may be set by the reg parser. */
clear_error ();
if (reg == PARSE_FAIL)
return FALSE;
skip_whitespace (str);
if (*str == ',' || is_end_of_line[(unsigned int) *str])
return TRUE;
return FALSE;
}
/* Parser functions used exclusively in instruction operands. */
/* Parse an immediate expression which may not be constant.
To prevent the expression parser from pushing a register name
into the symbol table as an undefined symbol, firstly a check is
done to find out whether STR is a valid register name followed
by a comma or the end of line. Return FALSE if STR is such a
string. */
static bfd_boolean
parse_immediate_expression (char **str, expressionS *exp)
{
if (reg_name_p (*str, REG_TYPE_R_Z_BHSDQ_V))
{
set_recoverable_error (_("immediate operand required"));
return FALSE;
}
my_get_expression (exp, str, GE_OPT_PREFIX, 1);
if (exp->X_op == O_absent)
{
set_fatal_syntax_error (_("missing immediate expression"));
return FALSE;
}
return TRUE;
}
/* Constant immediate-value read function for use in insn parsing.
STR points to the beginning of the immediate (with the optional
leading #); *VAL receives the value.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_constant_immediate (char **str, int64_t * val)
{
expressionS exp;
if (! parse_immediate_expression (str, &exp))
return FALSE;
if (exp.X_op != O_constant)
{
set_syntax_error (_("constant expression required"));
return FALSE;
}
*val = exp.X_add_number;
return TRUE;
}
static uint32_t
encode_imm_float_bits (uint32_t imm)
{
return ((imm >> 19) & 0x7f) /* b[25:19] -> b[6:0] */
| ((imm >> (31 - 7)) & 0x80); /* b[31] -> b[7] */
}
/* Return TRUE if the single-precision floating-point value encoded in IMM
can be expressed in the AArch64 8-bit signed floating-point format with
3-bit exponent and normalized 4 bits of precision; in other words, the
floating-point value must be expressable as
(+/-) n / 16 * power (2, r)
where n and r are integers such that 16 <= n <=31 and -3 <= r <= 4. */
static bfd_boolean
aarch64_imm_float_p (uint32_t imm)
{
/* If a single-precision floating-point value has the following bit
pattern, it can be expressed in the AArch64 8-bit floating-point
format:
3 32222222 2221111111111
1 09876543 21098765432109876543210
n Eeeeeexx xxxx0000000000000000000
where n, e and each x are either 0 or 1 independently, with
E == ~ e. */
uint32_t pattern;
/* Prepare the pattern for 'Eeeeee'. */
if (((imm >> 30) & 0x1) == 0)
pattern = 0x3e000000;
else
pattern = 0x40000000;
return (imm & 0x7ffff) == 0 /* lower 19 bits are 0. */
&& ((imm & 0x7e000000) == pattern); /* bits 25 - 29 == ~ bit 30. */
}
/* Like aarch64_imm_float_p but for a double-precision floating-point value.
Return TRUE if the value encoded in IMM can be expressed in the AArch64
8-bit signed floating-point format with 3-bit exponent and normalized 4
bits of precision (i.e. can be used in an FMOV instruction); return the
equivalent single-precision encoding in *FPWORD.
Otherwise return FALSE. */
static bfd_boolean
aarch64_double_precision_fmovable (uint64_t imm, uint32_t *fpword)
{
/* If a double-precision floating-point value has the following bit
pattern, it can be expressed in the AArch64 8-bit floating-point
format:
6 66655555555 554444444...21111111111
3 21098765432 109876543...098765432109876543210
n Eeeeeeeeexx xxxx00000...000000000000000000000
where n, e and each x are either 0 or 1 independently, with
E == ~ e. */
uint32_t pattern;
uint32_t high32 = imm >> 32;
/* Lower 32 bits need to be 0s. */
if ((imm & 0xffffffff) != 0)
return FALSE;
/* Prepare the pattern for 'Eeeeeeeee'. */
if (((high32 >> 30) & 0x1) == 0)
pattern = 0x3fc00000;
else
pattern = 0x40000000;
if ((high32 & 0xffff) == 0 /* bits 32 - 47 are 0. */
&& (high32 & 0x7fc00000) == pattern) /* bits 54 - 61 == ~ bit 62. */
{
/* Convert to the single-precision encoding.
i.e. convert
n Eeeeeeeeexx xxxx00000...000000000000000000000
to
n Eeeeeexx xxxx0000000000000000000. */
*fpword = ((high32 & 0xfe000000) /* nEeeeee. */
| (((high32 >> 16) & 0x3f) << 19)); /* xxxxxx. */
return TRUE;
}
else
return FALSE;
}
/* Parse a floating-point immediate. Return TRUE on success and return the
value in *IMMED in the format of IEEE754 single-precision encoding.
*CCP points to the start of the string; DP_P is TRUE when the immediate
is expected to be in double-precision (N.B. this only matters when
hexadecimal representation is involved).
N.B. 0.0 is accepted by this function. */
static bfd_boolean
parse_aarch64_imm_float (char **ccp, int *immed, bfd_boolean dp_p)
{
char *str = *ccp;
char *fpnum;
LITTLENUM_TYPE words[MAX_LITTLENUMS];
int found_fpchar = 0;
int64_t val = 0;
unsigned fpword = 0;
bfd_boolean hex_p = FALSE;
skip_past_char (&str, '#');
fpnum = str;
skip_whitespace (fpnum);
if (strncmp (fpnum, "0x", 2) == 0)
{
/* Support the hexadecimal representation of the IEEE754 encoding.
Double-precision is expected when DP_P is TRUE, otherwise the
representation should be in single-precision. */
if (! parse_constant_immediate (&str, &val))
goto invalid_fp;
if (dp_p)
{
if (! aarch64_double_precision_fmovable (val, &fpword))
goto invalid_fp;
}
else if ((uint64_t) val > 0xffffffff)
goto invalid_fp;
else
fpword = val;
hex_p = TRUE;
}
else
{
/* We must not accidentally parse an integer as a floating-point number.
Make sure that the value we parse is not an integer by checking for
special characters '.' or 'e'. */
for (; *fpnum != '\0' && *fpnum != ' ' && *fpnum != '\n'; fpnum++)
if (*fpnum == '.' || *fpnum == 'e' || *fpnum == 'E')
{
found_fpchar = 1;
break;
}
if (!found_fpchar)
return FALSE;
}
if (! hex_p)
{
int i;
if ((str = atof_ieee (str, 's', words)) == NULL)
goto invalid_fp;
/* Our FP word must be 32 bits (single-precision FP). */
for (i = 0; i < 32 / LITTLENUM_NUMBER_OF_BITS; i++)
{
fpword <<= LITTLENUM_NUMBER_OF_BITS;
fpword |= words[i];
}
}
if (aarch64_imm_float_p (fpword) || (fpword & 0x7fffffff) == 0)
{
*immed = fpword;
*ccp = str;
return TRUE;
}
invalid_fp:
set_fatal_syntax_error (_("invalid floating-point constant"));
return FALSE;
}
/* Less-generic immediate-value read function with the possibility of loading
a big (64-bit) immediate, as required by AdvSIMD Modified immediate
instructions.
To prevent the expression parser from pushing a register name into the
symbol table as an undefined symbol, a check is firstly done to find
out whether STR is a valid register name followed by a comma or the end
of line. Return FALSE if STR is such a register. */
static bfd_boolean
parse_big_immediate (char **str, int64_t *imm)
{
char *ptr = *str;
if (reg_name_p (ptr, REG_TYPE_R_Z_BHSDQ_V))
{
set_syntax_error (_("immediate operand required"));
return FALSE;
}
my_get_expression (&inst.reloc.exp, &ptr, GE_OPT_PREFIX, 1);
if (inst.reloc.exp.X_op == O_constant)
*imm = inst.reloc.exp.X_add_number;
*str = ptr;
return TRUE;
}
/* Set operand IDX of the *INSTR that needs a GAS internal fixup.
if NEED_LIBOPCODES is non-zero, the fixup will need
assistance from the libopcodes. */
static inline void
aarch64_set_gas_internal_fixup (struct reloc *reloc,
const aarch64_opnd_info *operand,
int need_libopcodes_p)
{
reloc->type = BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP;
reloc->opnd = operand->type;
if (need_libopcodes_p)
reloc->need_libopcodes_p = 1;
};
/* Return TRUE if the instruction needs to be fixed up later internally by
the GAS; otherwise return FALSE. */
static inline bfd_boolean
aarch64_gas_internal_fixup_p (void)
{
return inst.reloc.type == BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP;
}
/* Assign the immediate value to the relavant field in *OPERAND if
RELOC->EXP is a constant expression; otherwise, flag that *OPERAND
needs an internal fixup in a later stage.
ADDR_OFF_P determines whether it is the field ADDR.OFFSET.IMM or
IMM.VALUE that may get assigned with the constant. */
static inline void
assign_imm_if_const_or_fixup_later (struct reloc *reloc,
aarch64_opnd_info *operand,
int addr_off_p,
int need_libopcodes_p,
int skip_p)
{
if (reloc->exp.X_op == O_constant)
{
if (addr_off_p)
operand->addr.offset.imm = reloc->exp.X_add_number;
else
operand->imm.value = reloc->exp.X_add_number;
reloc->type = BFD_RELOC_UNUSED;
}
else
{
aarch64_set_gas_internal_fixup (reloc, operand, need_libopcodes_p);
/* Tell libopcodes to ignore this operand or not. This is helpful
when one of the operands needs to be fixed up later but we need
libopcodes to check the other operands. */
operand->skip = skip_p;
}
}
/* Relocation modifiers. Each entry in the table contains the textual
name for the relocation which may be placed before a symbol used as
a load/store offset, or add immediate. It must be surrounded by a
leading and trailing colon, for example:
ldr x0, [x1, #:rello:varsym]
add x0, x1, #:rello:varsym */
struct reloc_table_entry
{
const char *name;
int pc_rel;
bfd_reloc_code_real_type adr_type;
bfd_reloc_code_real_type adrp_type;
bfd_reloc_code_real_type movw_type;
bfd_reloc_code_real_type add_type;
bfd_reloc_code_real_type ldst_type;
bfd_reloc_code_real_type ld_literal_type;
};
static struct reloc_table_entry reloc_table[] = {
/* Low 12 bits of absolute address: ADD/i and LDR/STR */
{"lo12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_ADD_LO12,
BFD_RELOC_AARCH64_LDST_LO12,
0},
/* Higher 21 bits of pc-relative page offset: ADRP */
{"pg_hi21", 1,
0, /* adr_type */
BFD_RELOC_AARCH64_ADR_HI21_PCREL,
0,
0,
0,
0},
/* Higher 21 bits of pc-relative page offset: ADRP, no check */
{"pg_hi21_nc", 1,
0, /* adr_type */
BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL,
0,
0,
0,
0},
/* Most significant bits 0-15 of unsigned address/value: MOVZ */
{"abs_g0", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G0,
0,
0,
0},
/* Most significant bits 0-15 of signed address/value: MOVN/Z */
{"abs_g0_s", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G0_S,
0,
0,
0},
/* Less significant bits 0-15 of address/value: MOVK, no check */
{"abs_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G0_NC,
0,
0,
0},
/* Most significant bits 16-31 of unsigned address/value: MOVZ */
{"abs_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G1,
0,
0,
0},
/* Most significant bits 16-31 of signed address/value: MOVN/Z */
{"abs_g1_s", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G1_S,
0,
0,
0},
/* Less significant bits 16-31 of address/value: MOVK, no check */
{"abs_g1_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G1_NC,
0,
0,
0},
/* Most significant bits 32-47 of unsigned address/value: MOVZ */
{"abs_g2", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G2,
0,
0,
0},
/* Most significant bits 32-47 of signed address/value: MOVN/Z */
{"abs_g2_s", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G2_S,
0,
0,
0},
/* Less significant bits 32-47 of address/value: MOVK, no check */
{"abs_g2_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G2_NC,
0,
0,
0},
/* Most significant bits 48-63 of signed/unsigned address/value: MOVZ */
{"abs_g3", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_G3,
0,
0,
0},
/* Get to the page containing GOT entry for a symbol. */
{"got", 1,
0, /* adr_type */
BFD_RELOC_AARCH64_ADR_GOT_PAGE,
0,
0,
0,
BFD_RELOC_AARCH64_GOT_LD_PREL19},
/* 12 bit offset into the page containing GOT entry for that symbol. */
{"got_lo12", 0,
0, /* adr_type */
0,
0,
0,
BFD_RELOC_AARCH64_LD_GOT_LO12_NC,
0},
/* 0-15 bits of address/value: MOVk, no check. */
{"gotoff_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC,
0,
0,
0},
/* Most significant bits 16-31 of address/value: MOVZ. */
{"gotoff_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_MOVW_GOTOFF_G1,
0,
0,
0},
/* 15 bit offset into the page containing GOT entry for that symbol. */
{"gotoff_lo15", 0,
0, /* adr_type */
0,
0,
0,
BFD_RELOC_AARCH64_LD64_GOTOFF_LO15,
0},
/* Get to the page containing GOT TLS entry for a symbol */
{"gottprel_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC,
0,
0,
0},
/* Get to the page containing GOT TLS entry for a symbol */
{"gottprel_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1,
0,
0,
0},
/* Get to the page containing GOT TLS entry for a symbol */
{"tlsgd", 0,
BFD_RELOC_AARCH64_TLSGD_ADR_PREL21, /* adr_type */
BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21,
0,
0,
0,
0},
/* 12 bit offset into the page containing GOT TLS entry for a symbol */
{"tlsgd_lo12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC,
0,
0},
/* Lower 16 bits address/value: MOVk. */
{"tlsgd_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC,
0,
0,
0},
/* Most significant bits 16-31 of address/value: MOVZ. */
{"tlsgd_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSGD_MOVW_G1,
0,
0,
0},
/* Get to the page containing GOT TLS entry for a symbol */
{"tlsdesc", 0,
BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21, /* adr_type */
BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21,
0,
0,
0,
BFD_RELOC_AARCH64_TLSDESC_LD_PREL19},
/* 12 bit offset into the page containing GOT TLS entry for a symbol */
{"tlsdesc_lo12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSDESC_ADD_LO12_NC,
BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC,
0},
/* Get to the page containing GOT TLS entry for a symbol.
The same as GD, we allocate two consecutive GOT slots
for module index and module offset, the only difference
with GD is the module offset should be intialized to
zero without any outstanding runtime relocation. */
{"tlsldm", 0,
BFD_RELOC_AARCH64_TLSLD_ADR_PREL21, /* adr_type */
BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21,
0,
0,
0,
0},
/* 12 bit offset into the page containing GOT TLS entry for a symbol */
{"tlsldm_lo12_nc", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC,
0,
0},
/* 12 bit offset into the module TLS base address. */
{"dtprel_lo12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12,
BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12,
0},
/* Same as dtprel_lo12, no overflow check. */
{"dtprel_lo12_nc", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC,
BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC,
0},
/* bits[23:12] of offset to the module TLS base address. */
{"dtprel_hi12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12,
0,
0},
/* bits[15:0] of offset to the module TLS base address. */
{"dtprel_g0", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0,
0,
0,
0},
/* No overflow check version of BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0. */
{"dtprel_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC,
0,
0,
0},
/* bits[31:16] of offset to the module TLS base address. */
{"dtprel_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1,
0,
0,
0},
/* No overflow check version of BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1. */
{"dtprel_g1_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC,
0,
0,
0},
/* bits[47:32] of offset to the module TLS base address. */
{"dtprel_g2", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2,
0,
0,
0},
/* Lower 16 bit offset into GOT entry for a symbol */
{"tlsdesc_off_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC,
0,
0,
0},
/* Higher 16 bit offset into GOT entry for a symbol */
{"tlsdesc_off_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSDESC_OFF_G1,
0,
0,
0},
/* Get to the page containing GOT TLS entry for a symbol */
{"gottprel", 0,
0, /* adr_type */
BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21,
0,
0,
0,
BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19},
/* 12 bit offset into the page containing GOT TLS entry for a symbol */
{"gottprel_lo12", 0,
0, /* adr_type */
0,
0,
0,
BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC,
0},
/* Get tp offset for a symbol. */
{"tprel", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12,
0,
0},
/* Get tp offset for a symbol. */
{"tprel_lo12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12,
0,
0},
/* Get tp offset for a symbol. */
{"tprel_hi12", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12,
0,
0},
/* Get tp offset for a symbol. */
{"tprel_lo12_nc", 0,
0, /* adr_type */
0,
0,
BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC,
0,
0},
/* Most significant bits 32-47 of address/value: MOVZ. */
{"tprel_g2", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2,
0,
0,
0},
/* Most significant bits 16-31 of address/value: MOVZ. */
{"tprel_g1", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1,
0,
0,
0},
/* Most significant bits 16-31 of address/value: MOVZ, no check. */
{"tprel_g1_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC,
0,
0,
0},
/* Most significant bits 0-15 of address/value: MOVZ. */
{"tprel_g0", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0,
0,
0,
0},
/* Most significant bits 0-15 of address/value: MOVZ, no check. */
{"tprel_g0_nc", 0,
0, /* adr_type */
0,
BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC,
0,
0,
0},
/* 15bit offset from got entry to base address of GOT table. */
{"gotpage_lo15", 0,
0,
0,
0,
0,
BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15,
0},
/* 14bit offset from got entry to base address of GOT table. */
{"gotpage_lo14", 0,
0,
0,
0,
0,
BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14,
0},
};
/* Given the address of a pointer pointing to the textual name of a
relocation as may appear in assembler source, attempt to find its
details in reloc_table. The pointer will be updated to the character
after the trailing colon. On failure, NULL will be returned;
otherwise return the reloc_table_entry. */
static struct reloc_table_entry *
find_reloc_table_entry (char **str)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE (reloc_table); i++)
{
int length = strlen (reloc_table[i].name);
if (strncasecmp (reloc_table[i].name, *str, length) == 0
&& (*str)[length] == ':')
{
*str += (length + 1);
return &reloc_table[i];
}
}
return NULL;
}
/* Mode argument to parse_shift and parser_shifter_operand. */
enum parse_shift_mode
{
SHIFTED_ARITH_IMM, /* "rn{,lsl|lsr|asl|asr|uxt|sxt #n}" or
"#imm{,lsl #n}" */
SHIFTED_LOGIC_IMM, /* "rn{,lsl|lsr|asl|asr|ror #n}" or
"#imm" */
SHIFTED_LSL, /* bare "lsl #n" */
SHIFTED_LSL_MSL, /* "lsl|msl #n" */
SHIFTED_REG_OFFSET /* [su]xtw|sxtx {#n} or lsl #n */
};
/* Parse a <shift> operator on an AArch64 data processing instruction.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_shift (char **str, aarch64_opnd_info *operand, enum parse_shift_mode mode)
{
const struct aarch64_name_value_pair *shift_op;
enum aarch64_modifier_kind kind;
expressionS exp;
int exp_has_prefix;
char *s = *str;
char *p = s;
for (p = *str; ISALPHA (*p); p++)
;
if (p == *str)
{
set_syntax_error (_("shift expression expected"));
return FALSE;
}
shift_op = hash_find_n (aarch64_shift_hsh, *str, p - *str);
if (shift_op == NULL)
{
set_syntax_error (_("shift operator expected"));
return FALSE;
}
kind = aarch64_get_operand_modifier (shift_op);
if (kind == AARCH64_MOD_MSL && mode != SHIFTED_LSL_MSL)
{
set_syntax_error (_("invalid use of 'MSL'"));
return FALSE;
}
switch (mode)
{
case SHIFTED_LOGIC_IMM:
if (aarch64_extend_operator_p (kind) == TRUE)
{
set_syntax_error (_("extending shift is not permitted"));
return FALSE;
}
break;
case SHIFTED_ARITH_IMM:
if (kind == AARCH64_MOD_ROR)
{
set_syntax_error (_("'ROR' shift is not permitted"));
return FALSE;
}
break;
case SHIFTED_LSL:
if (kind != AARCH64_MOD_LSL)
{
set_syntax_error (_("only 'LSL' shift is permitted"));
return FALSE;
}
break;
case SHIFTED_REG_OFFSET:
if (kind != AARCH64_MOD_UXTW && kind != AARCH64_MOD_LSL
&& kind != AARCH64_MOD_SXTW && kind != AARCH64_MOD_SXTX)
{
set_fatal_syntax_error
(_("invalid shift for the register offset addressing mode"));
return FALSE;
}
break;
case SHIFTED_LSL_MSL:
if (kind != AARCH64_MOD_LSL && kind != AARCH64_MOD_MSL)
{
set_syntax_error (_("invalid shift operator"));
return FALSE;
}
break;
default:
abort ();
}
/* Whitespace can appear here if the next thing is a bare digit. */
skip_whitespace (p);
/* Parse shift amount. */
exp_has_prefix = 0;
if (mode == SHIFTED_REG_OFFSET && *p == ']')
exp.X_op = O_absent;
else
{
if (is_immediate_prefix (*p))
{
p++;
exp_has_prefix = 1;
}
my_get_expression (&exp, &p, GE_NO_PREFIX, 0);
}
if (exp.X_op == O_absent)
{
if (aarch64_extend_operator_p (kind) == FALSE || exp_has_prefix)
{
set_syntax_error (_("missing shift amount"));
return FALSE;
}
operand->shifter.amount = 0;
}
else if (exp.X_op != O_constant)
{
set_syntax_error (_("constant shift amount required"));
return FALSE;
}
else if (exp.X_add_number < 0 || exp.X_add_number > 63)
{
set_fatal_syntax_error (_("shift amount out of range 0 to 63"));
return FALSE;
}
else
{
operand->shifter.amount = exp.X_add_number;
operand->shifter.amount_present = 1;
}
operand->shifter.operator_present = 1;
operand->shifter.kind = kind;
*str = p;
return TRUE;
}
/* Parse a <shifter_operand> for a data processing instruction:
#<immediate>
#<immediate>, LSL #imm
Validation of immediate operands is deferred to md_apply_fix.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_shifter_operand_imm (char **str, aarch64_opnd_info *operand,
enum parse_shift_mode mode)
{
char *p;
if (mode != SHIFTED_ARITH_IMM && mode != SHIFTED_LOGIC_IMM)
return FALSE;
p = *str;
/* Accept an immediate expression. */
if (! my_get_expression (&inst.reloc.exp, &p, GE_OPT_PREFIX, 1))
return FALSE;
/* Accept optional LSL for arithmetic immediate values. */
if (mode == SHIFTED_ARITH_IMM && skip_past_comma (&p))
if (! parse_shift (&p, operand, SHIFTED_LSL))
return FALSE;
/* Not accept any shifter for logical immediate values. */
if (mode == SHIFTED_LOGIC_IMM && skip_past_comma (&p)
&& parse_shift (&p, operand, mode))
{
set_syntax_error (_("unexpected shift operator"));
return FALSE;
}
*str = p;
return TRUE;
}
/* Parse a <shifter_operand> for a data processing instruction:
<Rm>
<Rm>, <shift>
#<immediate>
#<immediate>, LSL #imm
where <shift> is handled by parse_shift above, and the last two
cases are handled by the function above.
Validation of immediate operands is deferred to md_apply_fix.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_shifter_operand (char **str, aarch64_opnd_info *operand,
enum parse_shift_mode mode)
{
int reg;
int isreg32, isregzero;
enum aarch64_operand_class opd_class
= aarch64_get_operand_class (operand->type);
if ((reg =
aarch64_reg_parse_32_64 (str, 0, 0, &isreg32, &isregzero)) != PARSE_FAIL)
{
if (opd_class == AARCH64_OPND_CLASS_IMMEDIATE)
{
set_syntax_error (_("unexpected register in the immediate operand"));
return FALSE;
}
if (!isregzero && reg == REG_SP)
{
set_syntax_error (BAD_SP);
return FALSE;
}
operand->reg.regno = reg;
operand->qualifier = isreg32 ? AARCH64_OPND_QLF_W : AARCH64_OPND_QLF_X;
/* Accept optional shift operation on register. */
if (! skip_past_comma (str))
return TRUE;
if (! parse_shift (str, operand, mode))
return FALSE;
return TRUE;
}
else if (opd_class == AARCH64_OPND_CLASS_MODIFIED_REG)
{
set_syntax_error
(_("integer register expected in the extended/shifted operand "
"register"));
return FALSE;
}
/* We have a shifted immediate variable. */
return parse_shifter_operand_imm (str, operand, mode);
}
/* Return TRUE on success; return FALSE otherwise. */
static bfd_boolean
parse_shifter_operand_reloc (char **str, aarch64_opnd_info *operand,
enum parse_shift_mode mode)
{
char *p = *str;
/* Determine if we have the sequence of characters #: or just :
coming next. If we do, then we check for a :rello: relocation
modifier. If we don't, punt the whole lot to
parse_shifter_operand. */
if ((p[0] == '#' && p[1] == ':') || p[0] == ':')
{
struct reloc_table_entry *entry;
if (p[0] == '#')
p += 2;
else
p++;
*str = p;
/* Try to parse a relocation. Anything else is an error. */
if (!(entry = find_reloc_table_entry (str)))
{
set_syntax_error (_("unknown relocation modifier"));
return FALSE;
}
if (entry->add_type == 0)
{
set_syntax_error
(_("this relocation modifier is not allowed on this instruction"));
return FALSE;
}
/* Save str before we decompose it. */
p = *str;
/* Next, we parse the expression. */
if (! my_get_expression (&inst.reloc.exp, str, GE_NO_PREFIX, 1))
return FALSE;
/* Record the relocation type (use the ADD variant here). */
inst.reloc.type = entry->add_type;
inst.reloc.pc_rel = entry->pc_rel;
/* If str is empty, we've reached the end, stop here. */
if (**str == '\0')
return TRUE;
/* Otherwise, we have a shifted reloc modifier, so rewind to
recover the variable name and continue parsing for the shifter. */
*str = p;
return parse_shifter_operand_imm (str, operand, mode);
}
return parse_shifter_operand (str, operand, mode);
}
/* Parse all forms of an address expression. Information is written
to *OPERAND and/or inst.reloc.
The A64 instruction set has the following addressing modes:
Offset
[base] // in SIMD ld/st structure
[base{,#0}] // in ld/st exclusive
[base{,#imm}]
[base,Xm{,LSL #imm}]
[base,Xm,SXTX {#imm}]
[base,Wm,(S|U)XTW {#imm}]
Pre-indexed
[base,#imm]!
Post-indexed
[base],#imm
[base],Xm // in SIMD ld/st structure
PC-relative (literal)
label
=immediate
(As a convenience, the notation "=immediate" is permitted in conjunction
with the pc-relative literal load instructions to automatically place an
immediate value or symbolic address in a nearby literal pool and generate
a hidden label which references it.)
Upon a successful parsing, the address structure in *OPERAND will be
filled in the following way:
.base_regno = <base>
.offset.is_reg // 1 if the offset is a register
.offset.imm = <imm>
.offset.regno = <Rm>
For different addressing modes defined in the A64 ISA:
Offset
.pcrel=0; .preind=1; .postind=0; .writeback=0
Pre-indexed
.pcrel=0; .preind=1; .postind=0; .writeback=1
Post-indexed
.pcrel=0; .preind=0; .postind=1; .writeback=1
PC-relative (literal)
.pcrel=1; .preind=1; .postind=0; .writeback=0
The shift/extension information, if any, will be stored in .shifter.
It is the caller's responsibility to check for addressing modes not
supported by the instruction, and to set inst.reloc.type. */
static bfd_boolean
parse_address_main (char **str, aarch64_opnd_info *operand, int reloc,
int accept_reg_post_index)
{
char *p = *str;
int reg;
int isreg32, isregzero;
expressionS *exp = &inst.reloc.exp;
if (! skip_past_char (&p, '['))
{
/* =immediate or label. */
operand->addr.pcrel = 1;
operand->addr.preind = 1;
/* #:<reloc_op>:<symbol> */
skip_past_char (&p, '#');
if (reloc && skip_past_char (&p, ':'))
{
bfd_reloc_code_real_type ty;
struct reloc_table_entry *entry;
/* Try to parse a relocation modifier. Anything else is
an error. */
entry = find_reloc_table_entry (&p);
if (! entry)
{
set_syntax_error (_("unknown relocation modifier"));
return FALSE;
}
switch (operand->type)
{
case AARCH64_OPND_ADDR_PCREL21:
/* adr */
ty = entry->adr_type;
break;
default:
ty = entry->ld_literal_type;
break;
}
if (ty == 0)
{
set_syntax_error
(_("this relocation modifier is not allowed on this "
"instruction"));
return FALSE;
}
/* #:<reloc_op>: */
if (! my_get_expression (exp, &p, GE_NO_PREFIX, 1))
{
set_syntax_error (_("invalid relocation expression"));
return FALSE;
}
/* #:<reloc_op>:<expr> */
/* Record the relocation type. */
inst.reloc.type = ty;
inst.reloc.pc_rel = entry->pc_rel;
}
else
{
if (skip_past_char (&p, '='))
/* =immediate; need to generate the literal in the literal pool. */
inst.gen_lit_pool = 1;
if (!my_get_expression (exp, &p, GE_NO_PREFIX, 1))
{
set_syntax_error (_("invalid address"));
return FALSE;
}
}
*str = p;
return TRUE;
}
/* [ */
/* Accept SP and reject ZR */
reg = aarch64_reg_parse_32_64 (&p, 0, 1, &isreg32, &isregzero);
if (reg == PARSE_FAIL || isreg32)
{
set_syntax_error (_(get_reg_expected_msg (REG_TYPE_R_64)));
return FALSE;
}
operand->addr.base_regno = reg;
/* [Xn */
if (skip_past_comma (&p))
{
/* [Xn, */
operand->addr.preind = 1;
/* Reject SP and accept ZR */
reg = aarch64_reg_parse_32_64 (&p, 1, 0, &isreg32, &isregzero);
if (reg != PARSE_FAIL)
{
/* [Xn,Rm */
operand->addr.offset.regno = reg;
operand->addr.offset.is_reg = 1;
/* Shifted index. */
if (skip_past_comma (&p))
{
/* [Xn,Rm, */
if (! parse_shift (&p, operand, SHIFTED_REG_OFFSET))
/* Use the diagnostics set in parse_shift, so not set new
error message here. */
return FALSE;
}
/* We only accept:
[base,Xm{,LSL #imm}]
[base,Xm,SXTX {#imm}]
[base,Wm,(S|U)XTW {#imm}] */
if (operand->shifter.kind == AARCH64_MOD_NONE
|| operand->shifter.kind == AARCH64_MOD_LSL
|| operand->shifter.kind == AARCH64_MOD_SXTX)
{
if (isreg32)
{
set_syntax_error (_("invalid use of 32-bit register offset"));
return FALSE;
}
}
else if (!isreg32)
{
set_syntax_error (_("invalid use of 64-bit register offset"));
return FALSE;
}
}
else
{
/* [Xn,#:<reloc_op>:<symbol> */
skip_past_char (&p, '#');
if (reloc && skip_past_char (&p, ':'))
{
struct reloc_table_entry *entry;
/* Try to parse a relocation modifier. Anything else is
an error. */
if (!(entry = find_reloc_table_entry (&p)))
{
set_syntax_error (_("unknown relocation modifier"));
return FALSE;
}
if (entry->ldst_type == 0)
{
set_syntax_error
(_("this relocation modifier is not allowed on this "
"instruction"));
return FALSE;
}
/* [Xn,#:<reloc_op>: */
/* We now have the group relocation table entry corresponding to
the name in the assembler source. Next, we parse the
expression. */
if (! my_get_expression (exp, &p, GE_NO_PREFIX, 1))
{
set_syntax_error (_("invalid relocation expression"));
return FALSE;
}
/* [Xn,#:<reloc_op>:<expr> */
/* Record the load/store relocation type. */
inst.reloc.type = entry->ldst_type;
inst.reloc.pc_rel = entry->pc_rel;
}
else if (! my_get_expression (exp, &p, GE_OPT_PREFIX, 1))
{
set_syntax_error (_("invalid expression in the address"));
return FALSE;
}
/* [Xn,<expr> */
}
}
if (! skip_past_char (&p, ']'))
{
set_syntax_error (_("']' expected"));
return FALSE;
}
if (skip_past_char (&p, '!'))
{
if (operand->addr.preind && operand->addr.offset.is_reg)
{
set_syntax_error (_("register offset not allowed in pre-indexed "
"addressing mode"));
return FALSE;
}
/* [Xn]! */
operand->addr.writeback = 1;
}
else if (skip_past_comma (&p))
{
/* [Xn], */
operand->addr.postind = 1;
operand->addr.writeback = 1;
if (operand->addr.preind)
{
set_syntax_error (_("cannot combine pre- and post-indexing"));
return FALSE;
}
if (accept_reg_post_index
&& (reg = aarch64_reg_parse_32_64 (&p, 1, 1, &isreg32,
&isregzero)) != PARSE_FAIL)
{
/* [Xn],Xm */
if (isreg32)
{
set_syntax_error (_("invalid 32-bit register offset"));
return FALSE;
}
operand->addr.offset.regno = reg;
operand->addr.offset.is_reg = 1;
}
else if (! my_get_expression (exp, &p, GE_OPT_PREFIX, 1))
{
/* [Xn],#expr */
set_syntax_error (_("invalid expression in the address"));
return FALSE;
}
}
/* If at this point neither .preind nor .postind is set, we have a
bare [Rn]{!}; reject [Rn]! but accept [Rn] as a shorthand for [Rn,#0]. */
if (operand->addr.preind == 0 && operand->addr.postind == 0)
{
if (operand->addr.writeback)
{
/* Reject [Rn]! */
set_syntax_error (_("missing offset in the pre-indexed address"));
return FALSE;
}
operand->addr.preind = 1;
inst.reloc.exp.X_op = O_constant;
inst.reloc.exp.X_add_number = 0;
}
*str = p;
return TRUE;
}
/* Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_address (char **str, aarch64_opnd_info *operand,
int accept_reg_post_index)
{
return parse_address_main (str, operand, 0, accept_reg_post_index);
}
/* Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_address_reloc (char **str, aarch64_opnd_info *operand)
{
return parse_address_main (str, operand, 1, 0);
}
/* Parse an operand for a MOVZ, MOVN or MOVK instruction.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_half (char **str, int *internal_fixup_p)
{
char *p, *saved;
int dummy;
p = *str;
skip_past_char (&p, '#');
gas_assert (internal_fixup_p);
*internal_fixup_p = 0;
if (*p == ':')
{
struct reloc_table_entry *entry;
/* Try to parse a relocation. Anything else is an error. */
++p;
if (!(entry = find_reloc_table_entry (&p)))
{
set_syntax_error (_("unknown relocation modifier"));
return FALSE;
}
if (entry->movw_type == 0)
{
set_syntax_error
(_("this relocation modifier is not allowed on this instruction"));
return FALSE;
}
inst.reloc.type = entry->movw_type;
}
else
*internal_fixup_p = 1;
/* Avoid parsing a register as a general symbol. */
saved = p;
if (aarch64_reg_parse_32_64 (&p, 0, 0, &dummy, &dummy) != PARSE_FAIL)
return FALSE;
p = saved;
if (! my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX, 1))
return FALSE;
*str = p;
return TRUE;
}
/* Parse an operand for an ADRP instruction:
ADRP <Xd>, <label>
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
parse_adrp (char **str)
{
char *p;
p = *str;
if (*p == ':')
{
struct reloc_table_entry *entry;
/* Try to parse a relocation. Anything else is an error. */
++p;
if (!(entry = find_reloc_table_entry (&p)))
{
set_syntax_error (_("unknown relocation modifier"));
return FALSE;
}
if (entry->adrp_type == 0)
{
set_syntax_error
(_("this relocation modifier is not allowed on this instruction"));
return FALSE;
}
inst.reloc.type = entry->adrp_type;
}
else
inst.reloc.type = BFD_RELOC_AARCH64_ADR_HI21_PCREL;
inst.reloc.pc_rel = 1;
if (! my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX, 1))
return FALSE;
*str = p;
return TRUE;
}
/* Miscellaneous. */
/* Parse an option for a preload instruction. Returns the encoding for the
option, or PARSE_FAIL. */
static int
parse_pldop (char **str)
{
char *p, *q;
const struct aarch64_name_value_pair *o;
p = q = *str;
while (ISALNUM (*q))
q++;
o = hash_find_n (aarch64_pldop_hsh, p, q - p);
if (!o)
return PARSE_FAIL;
*str = q;
return o->value;
}
/* Parse an option for a barrier instruction. Returns the encoding for the
option, or PARSE_FAIL. */
static int
parse_barrier (char **str)
{
char *p, *q;
const asm_barrier_opt *o;
p = q = *str;
while (ISALPHA (*q))
q++;
o = hash_find_n (aarch64_barrier_opt_hsh, p, q - p);
if (!o)
return PARSE_FAIL;
*str = q;
return o->value;
}
/* Parse an operand for a PSB barrier. Set *HINT_OPT to the hint-option record
return 0 if successful. Otherwise return PARSE_FAIL. */
static int
parse_barrier_psb (char **str,
const struct aarch64_name_value_pair ** hint_opt)
{
char *p, *q;
const struct aarch64_name_value_pair *o;
p = q = *str;
while (ISALPHA (*q))
q++;
o = hash_find_n (aarch64_hint_opt_hsh, p, q - p);
if (!o)
{
set_fatal_syntax_error
( _("unknown or missing option to PSB"));
return PARSE_FAIL;
}
if (o->value != 0x11)
{
/* PSB only accepts option name 'CSYNC'. */
set_syntax_error
(_("the specified option is not accepted for PSB"));
return PARSE_FAIL;
}
*str = q;
*hint_opt = o;
return 0;
}
/* Parse a system register or a PSTATE field name for an MSR/MRS instruction.
Returns the encoding for the option, or PARSE_FAIL.
If IMPLE_DEFINED_P is non-zero, the function will also try to parse the
implementation defined system register name S<op0>_<op1>_<Cn>_<Cm>_<op2>.
If PSTATEFIELD_P is non-zero, the function will parse the name as a PSTATE
field, otherwise as a system register.
*/
static int
parse_sys_reg (char **str, struct hash_control *sys_regs,
int imple_defined_p, int pstatefield_p)
{
char *p, *q;
char buf[32];
const aarch64_sys_reg *o;
int value;
p = buf;
for (q = *str; ISALNUM (*q) || *q == '_'; q++)
if (p < buf + 31)
*p++ = TOLOWER (*q);
*p = '\0';
/* Assert that BUF be large enough. */
gas_assert (p - buf == q - *str);
o = hash_find (sys_regs, buf);
if (!o)
{
if (!imple_defined_p)
return PARSE_FAIL;
else
{
/* Parse S<op0>_<op1>_<Cn>_<Cm>_<op2>. */
unsigned int op0, op1, cn, cm, op2;
if (sscanf (buf, "s%u_%u_c%u_c%u_%u", &op0, &op1, &cn, &cm, &op2)
!= 5)
return PARSE_FAIL;
if (op0 > 3 || op1 > 7 || cn > 15 || cm > 15 || op2 > 7)
return PARSE_FAIL;
value = (op0 << 14) | (op1 << 11) | (cn << 7) | (cm << 3) | op2;
}
}
else
{
if (pstatefield_p && !aarch64_pstatefield_supported_p (cpu_variant, o))
as_bad (_("selected processor does not support PSTATE field "
"name '%s'"), buf);
if (!pstatefield_p && !aarch64_sys_reg_supported_p (cpu_variant, o))
as_bad (_("selected processor does not support system register "
"name '%s'"), buf);
if (aarch64_sys_reg_deprecated_p (o))
as_warn (_("system register name '%s' is deprecated and may be "
"removed in a future release"), buf);
value = o->value;
}
*str = q;
return value;
}
/* Parse a system reg for ic/dc/at/tlbi instructions. Returns the table entry
for the option, or NULL. */
static const aarch64_sys_ins_reg *
parse_sys_ins_reg (char **str, struct hash_control *sys_ins_regs)
{
char *p, *q;
char buf[32];
const aarch64_sys_ins_reg *o;
p = buf;
for (q = *str; ISALNUM (*q) || *q == '_'; q++)
if (p < buf + 31)
*p++ = TOLOWER (*q);
*p = '\0';
o = hash_find (sys_ins_regs, buf);
if (!o)
return NULL;
if (!aarch64_sys_ins_reg_supported_p (cpu_variant, o))
as_bad (_("selected processor does not support system register "
"name '%s'"), buf);
*str = q;
return o;
}
#define po_char_or_fail(chr) do { \
if (! skip_past_char (&str, chr)) \
goto failure; \
} while (0)
#define po_reg_or_fail(regtype) do { \
val = aarch64_reg_parse (&str, regtype, &rtype, NULL); \
if (val == PARSE_FAIL) \
{ \
set_default_error (); \
goto failure; \
} \
} while (0)
#define po_int_reg_or_fail(reject_sp, reject_rz) do { \
val = aarch64_reg_parse_32_64 (&str, reject_sp, reject_rz, \
&isreg32, &isregzero); \
if (val == PARSE_FAIL) \
{ \
set_default_error (); \
goto failure; \
} \
info->reg.regno = val; \
if (isreg32) \
info->qualifier = AARCH64_OPND_QLF_W; \
else \
info->qualifier = AARCH64_OPND_QLF_X; \
} while (0)
#define po_imm_nc_or_fail() do { \
if (! parse_constant_immediate (&str, &val)) \
goto failure; \
} while (0)
#define po_imm_or_fail(min, max) do { \
if (! parse_constant_immediate (&str, &val)) \
goto failure; \
if (val < min || val > max) \
{ \
set_fatal_syntax_error (_("immediate value out of range "\
#min " to "#max)); \
goto failure; \
} \
} while (0)
#define po_misc_or_fail(expr) do { \
if (!expr) \
goto failure; \
} while (0)
/* encode the 12-bit imm field of Add/sub immediate */
static inline uint32_t
encode_addsub_imm (uint32_t imm)
{
return imm << 10;
}
/* encode the shift amount field of Add/sub immediate */
static inline uint32_t
encode_addsub_imm_shift_amount (uint32_t cnt)
{
return cnt << 22;
}
/* encode the imm field of Adr instruction */
static inline uint32_t
encode_adr_imm (uint32_t imm)
{
return (((imm & 0x3) << 29) /* [1:0] -> [30:29] */
| ((imm & (0x7ffff << 2)) << 3)); /* [20:2] -> [23:5] */
}
/* encode the immediate field of Move wide immediate */
static inline uint32_t
encode_movw_imm (uint32_t imm)
{
return imm << 5;
}
/* encode the 26-bit offset of unconditional branch */
static inline uint32_t
encode_branch_ofs_26 (uint32_t ofs)
{
return ofs & ((1 << 26) - 1);
}
/* encode the 19-bit offset of conditional branch and compare & branch */
static inline uint32_t
encode_cond_branch_ofs_19 (uint32_t ofs)
{
return (ofs & ((1 << 19) - 1)) << 5;
}
/* encode the 19-bit offset of ld literal */
static inline uint32_t
encode_ld_lit_ofs_19 (uint32_t ofs)
{
return (ofs & ((1 << 19) - 1)) << 5;
}
/* Encode the 14-bit offset of test & branch. */
static inline uint32_t
encode_tst_branch_ofs_14 (uint32_t ofs)
{
return (ofs & ((1 << 14) - 1)) << 5;
}
/* Encode the 16-bit imm field of svc/hvc/smc. */
static inline uint32_t
encode_svc_imm (uint32_t imm)
{
return imm << 5;
}
/* Reencode add(s) to sub(s), or sub(s) to add(s). */
static inline uint32_t
reencode_addsub_switch_add_sub (uint32_t opcode)
{
return opcode ^ (1 << 30);
}
static inline uint32_t
reencode_movzn_to_movz (uint32_t opcode)
{
return opcode | (1 << 30);
}
static inline uint32_t
reencode_movzn_to_movn (uint32_t opcode)
{
return opcode & ~(1 << 30);
}
/* Overall per-instruction processing. */
/* We need to be able to fix up arbitrary expressions in some statements.
This is so that we can handle symbols that are an arbitrary distance from
the pc. The most common cases are of the form ((+/-sym -/+ . - 8) & mask),
which returns part of an address in a form which will be valid for
a data instruction. We do this by pushing the expression into a symbol
in the expr_section, and creating a fix for that. */
static fixS *
fix_new_aarch64 (fragS * frag,
int where,
short int size, expressionS * exp, int pc_rel, int reloc)
{
fixS *new_fix;
switch (exp->X_op)
{
case O_constant:
case O_symbol:
case O_add:
case O_subtract:
new_fix = fix_new_exp (frag, where, size, exp, pc_rel, reloc);
break;
default:
new_fix = fix_new (frag, where, size, make_expr_symbol (exp), 0,
pc_rel, reloc);
break;
}
return new_fix;
}
/* Diagnostics on operands errors. */
/* By default, output verbose error message.
Disable the verbose error message by -mno-verbose-error. */
static int verbose_error_p = 1;
#ifdef DEBUG_AARCH64
/* N.B. this is only for the purpose of debugging. */
const char* operand_mismatch_kind_names[] =
{
"AARCH64_OPDE_NIL",
"AARCH64_OPDE_RECOVERABLE",
"AARCH64_OPDE_SYNTAX_ERROR",
"AARCH64_OPDE_FATAL_SYNTAX_ERROR",
"AARCH64_OPDE_INVALID_VARIANT",
"AARCH64_OPDE_OUT_OF_RANGE",
"AARCH64_OPDE_UNALIGNED",
"AARCH64_OPDE_REG_LIST",
"AARCH64_OPDE_OTHER_ERROR",
};
#endif /* DEBUG_AARCH64 */
/* Return TRUE if LHS is of higher severity than RHS, otherwise return FALSE.
When multiple errors of different kinds are found in the same assembly
line, only the error of the highest severity will be picked up for
issuing the diagnostics. */
static inline bfd_boolean
operand_error_higher_severity_p (enum aarch64_operand_error_kind lhs,
enum aarch64_operand_error_kind rhs)
{
gas_assert (AARCH64_OPDE_RECOVERABLE > AARCH64_OPDE_NIL);
gas_assert (AARCH64_OPDE_SYNTAX_ERROR > AARCH64_OPDE_RECOVERABLE);
gas_assert (AARCH64_OPDE_FATAL_SYNTAX_ERROR > AARCH64_OPDE_SYNTAX_ERROR);
gas_assert (AARCH64_OPDE_INVALID_VARIANT > AARCH64_OPDE_FATAL_SYNTAX_ERROR);
gas_assert (AARCH64_OPDE_OUT_OF_RANGE > AARCH64_OPDE_INVALID_VARIANT);
gas_assert (AARCH64_OPDE_UNALIGNED > AARCH64_OPDE_OUT_OF_RANGE);
gas_assert (AARCH64_OPDE_REG_LIST > AARCH64_OPDE_UNALIGNED);
gas_assert (AARCH64_OPDE_OTHER_ERROR > AARCH64_OPDE_REG_LIST);
return lhs > rhs;
}
/* Helper routine to get the mnemonic name from the assembly instruction
line; should only be called for the diagnosis purpose, as there is
string copy operation involved, which may affect the runtime
performance if used in elsewhere. */
static const char*
get_mnemonic_name (const char *str)
{
static char mnemonic[32];
char *ptr;
/* Get the first 15 bytes and assume that the full name is included. */
strncpy (mnemonic, str, 31);
mnemonic[31] = '\0';
/* Scan up to the end of the mnemonic, which must end in white space,
'.', or end of string. */
for (ptr = mnemonic; is_part_of_name(*ptr); ++ptr)
;
*ptr = '\0';
/* Append '...' to the truncated long name. */
if (ptr - mnemonic == 31)
mnemonic[28] = mnemonic[29] = mnemonic[30] = '.';
return mnemonic;
}
static void
reset_aarch64_instruction (aarch64_instruction *instruction)
{
memset (instruction, '\0', sizeof (aarch64_instruction));
instruction->reloc.type = BFD_RELOC_UNUSED;
}
/* Data strutures storing one user error in the assembly code related to
operands. */
struct operand_error_record
{
const aarch64_opcode *opcode;
aarch64_operand_error detail;
struct operand_error_record *next;
};
typedef struct operand_error_record operand_error_record;
struct operand_errors
{
operand_error_record *head;
operand_error_record *tail;
};
typedef struct operand_errors operand_errors;
/* Top-level data structure reporting user errors for the current line of
the assembly code.
The way md_assemble works is that all opcodes sharing the same mnemonic
name are iterated to find a match to the assembly line. In this data
structure, each of the such opcodes will have one operand_error_record
allocated and inserted. In other words, excessive errors related with
a single opcode are disregarded. */
operand_errors operand_error_report;
/* Free record nodes. */
static operand_error_record *free_opnd_error_record_nodes = NULL;
/* Initialize the data structure that stores the operand mismatch
information on assembling one line of the assembly code. */
static void
init_operand_error_report (void)
{
if (operand_error_report.head != NULL)
{
gas_assert (operand_error_report.tail != NULL);
operand_error_report.tail->next = free_opnd_error_record_nodes;
free_opnd_error_record_nodes = operand_error_report.head;
operand_error_report.head = NULL;
operand_error_report.tail = NULL;
return;
}
gas_assert (operand_error_report.tail == NULL);
}
/* Return TRUE if some operand error has been recorded during the
parsing of the current assembly line using the opcode *OPCODE;
otherwise return FALSE. */
static inline bfd_boolean
opcode_has_operand_error_p (const aarch64_opcode *opcode)
{
operand_error_record *record = operand_error_report.head;
return record && record->opcode == opcode;
}
/* Add the error record *NEW_RECORD to operand_error_report. The record's
OPCODE field is initialized with OPCODE.
N.B. only one record for each opcode, i.e. the maximum of one error is
recorded for each instruction template. */
static void
add_operand_error_record (const operand_error_record* new_record)
{
const aarch64_opcode *opcode = new_record->opcode;
operand_error_record* record = operand_error_report.head;
/* The record may have been created for this opcode. If not, we need
to prepare one. */
if (! opcode_has_operand_error_p (opcode))
{
/* Get one empty record. */
if (free_opnd_error_record_nodes == NULL)
{
record = xmalloc (sizeof (operand_error_record));
if (record == NULL)
abort ();
}
else
{
record = free_opnd_error_record_nodes;
free_opnd_error_record_nodes = record->next;
}
record->opcode = opcode;
/* Insert at the head. */
record->next = operand_error_report.head;
operand_error_report.head = record;
if (operand_error_report.tail == NULL)
operand_error_report.tail = record;
}
else if (record->detail.kind != AARCH64_OPDE_NIL
&& record->detail.index <= new_record->detail.index
&& operand_error_higher_severity_p (record->detail.kind,
new_record->detail.kind))
{
/* In the case of multiple errors found on operands related with a
single opcode, only record the error of the leftmost operand and
only if the error is of higher severity. */
DEBUG_TRACE ("error %s on operand %d not added to the report due to"
" the existing error %s on operand %d",
operand_mismatch_kind_names[new_record->detail.kind],
new_record->detail.index,
operand_mismatch_kind_names[record->detail.kind],
record->detail.index);
return;
}
record->detail = new_record->detail;
}
static inline void
record_operand_error_info (const aarch64_opcode *opcode,
aarch64_operand_error *error_info)
{
operand_error_record record;
record.opcode = opcode;
record.detail = *error_info;
add_operand_error_record (&record);
}
/* Record an error of kind KIND and, if ERROR is not NULL, of the detailed
error message *ERROR, for operand IDX (count from 0). */
static void
record_operand_error (const aarch64_opcode *opcode, int idx,
enum aarch64_operand_error_kind kind,
const char* error)
{
aarch64_operand_error info;
memset(&info, 0, sizeof (info));
info.index = idx;
info.kind = kind;
info.error = error;
record_operand_error_info (opcode, &info);
}
static void
record_operand_error_with_data (const aarch64_opcode *opcode, int idx,
enum aarch64_operand_error_kind kind,
const char* error, const int *extra_data)
{
aarch64_operand_error info;
info.index = idx;
info.kind = kind;
info.error = error;
info.data[0] = extra_data[0];
info.data[1] = extra_data[1];
info.data[2] = extra_data[2];
record_operand_error_info (opcode, &info);
}
static void
record_operand_out_of_range_error (const aarch64_opcode *opcode, int idx,
const char* error, int lower_bound,
int upper_bound)
{
int data[3] = {lower_bound, upper_bound, 0};
record_operand_error_with_data (opcode, idx, AARCH64_OPDE_OUT_OF_RANGE,
error, data);
}
/* Remove the operand error record for *OPCODE. */
static void ATTRIBUTE_UNUSED
remove_operand_error_record (const aarch64_opcode *opcode)
{
if (opcode_has_operand_error_p (opcode))
{
operand_error_record* record = operand_error_report.head;
gas_assert (record != NULL && operand_error_report.tail != NULL);
operand_error_report.head = record->next;
record->next = free_opnd_error_record_nodes;
free_opnd_error_record_nodes = record;
if (operand_error_report.head == NULL)
{
gas_assert (operand_error_report.tail == record);
operand_error_report.tail = NULL;
}
}
}
/* Given the instruction in *INSTR, return the index of the best matched
qualifier sequence in the list (an array) headed by QUALIFIERS_LIST.
Return -1 if there is no qualifier sequence; return the first match
if there is multiple matches found. */
static int
find_best_match (const aarch64_inst *instr,
const aarch64_opnd_qualifier_seq_t *qualifiers_list)
{
int i, num_opnds, max_num_matched, idx;
num_opnds = aarch64_num_of_operands (instr->opcode);
if (num_opnds == 0)
{
DEBUG_TRACE ("no operand");
return -1;
}
max_num_matched = 0;
idx = -1;
/* For each pattern. */
for (i = 0; i < AARCH64_MAX_QLF_SEQ_NUM; ++i, ++qualifiers_list)
{
int j, num_matched;
const aarch64_opnd_qualifier_t *qualifiers = *qualifiers_list;
/* Most opcodes has much fewer patterns in the list. */
if (empty_qualifier_sequence_p (qualifiers) == TRUE)
{
DEBUG_TRACE_IF (i == 0, "empty list of qualifier sequence");
if (i != 0 && idx == -1)
/* If nothing has been matched, return the 1st sequence. */
idx = 0;
break;
}
for (j = 0, num_matched = 0; j < num_opnds; ++j, ++qualifiers)
if (*qualifiers == instr->operands[j].qualifier)
++num_matched;
if (num_matched > max_num_matched)
{
max_num_matched = num_matched;
idx = i;
}
}
DEBUG_TRACE ("return with %d", idx);
return idx;
}
/* Assign qualifiers in the qualifier seqence (headed by QUALIFIERS) to the
corresponding operands in *INSTR. */
static inline void
assign_qualifier_sequence (aarch64_inst *instr,
const aarch64_opnd_qualifier_t *qualifiers)
{
int i = 0;
int num_opnds = aarch64_num_of_operands (instr->opcode);
gas_assert (num_opnds);
for (i = 0; i < num_opnds; ++i, ++qualifiers)
instr->operands[i].qualifier = *qualifiers;
}
/* Print operands for the diagnosis purpose. */
static void
print_operands (char *buf, const aarch64_opcode *opcode,
const aarch64_opnd_info *opnds)
{
int i;
for (i = 0; i < AARCH64_MAX_OPND_NUM; ++i)
{
const size_t size = 128;
char str[size];
/* We regard the opcode operand info more, however we also look into
the inst->operands to support the disassembling of the optional
operand.
The two operand code should be the same in all cases, apart from
when the operand can be optional. */
if (opcode->operands[i] == AARCH64_OPND_NIL
|| opnds[i].type == AARCH64_OPND_NIL)
break;
/* Generate the operand string in STR. */
aarch64_print_operand (str, size, 0, opcode, opnds, i, NULL, NULL);
/* Delimiter. */
if (str[0] != '\0')
strcat (buf, i == 0 ? " " : ",");
/* Append the operand string. */
strcat (buf, str);
}
}
/* Send to stderr a string as information. */
static void
output_info (const char *format, ...)
{
char *file;
unsigned int line;
va_list args;
as_where (&file, &line);
if (file)
{
if (line != 0)
fprintf (stderr, "%s:%u: ", file, line);
else
fprintf (stderr, "%s: ", file);
}
fprintf (stderr, _("Info: "));
va_start (args, format);
vfprintf (stderr, format, args);
va_end (args);
(void) putc ('\n', stderr);
}
/* Output one operand error record. */
static void
output_operand_error_record (const operand_error_record *record, char *str)
{
const aarch64_operand_error *detail = &record->detail;
int idx = detail->index;
const aarch64_opcode *opcode = record->opcode;
enum aarch64_opnd opd_code = (idx >= 0 ? opcode->operands[idx]
: AARCH64_OPND_NIL);
switch (detail->kind)
{
case AARCH64_OPDE_NIL:
gas_assert (0);
break;
case AARCH64_OPDE_SYNTAX_ERROR:
case AARCH64_OPDE_RECOVERABLE:
case AARCH64_OPDE_FATAL_SYNTAX_ERROR:
case AARCH64_OPDE_OTHER_ERROR:
/* Use the prepared error message if there is, otherwise use the
operand description string to describe the error. */
if (detail->error != NULL)
{
if (idx < 0)
as_bad (_("%s -- `%s'"), detail->error, str);
else
as_bad (_("%s at operand %d -- `%s'"),
detail->error, idx + 1, str);
}
else
{
gas_assert (idx >= 0);
as_bad (_("operand %d should be %s -- `%s'"), idx + 1,
aarch64_get_operand_desc (opd_code), str);
}
break;
case AARCH64_OPDE_INVALID_VARIANT:
as_bad (_("operand mismatch -- `%s'"), str);
if (verbose_error_p)
{
/* We will try to correct the erroneous instruction and also provide
more information e.g. all other valid variants.
The string representation of the corrected instruction and other
valid variants are generated by
1) obtaining the intermediate representation of the erroneous
instruction;
2) manipulating the IR, e.g. replacing the operand qualifier;
3) printing out the instruction by calling the printer functions
shared with the disassembler.
The limitation of this method is that the exact input assembly
line cannot be accurately reproduced in some cases, for example an
optional operand present in the actual assembly line will be
omitted in the output; likewise for the optional syntax rules,
e.g. the # before the immediate. Another limitation is that the
assembly symbols and relocation operations in the assembly line
currently cannot be printed out in the error report. Last but not
least, when there is other error(s) co-exist with this error, the
'corrected' instruction may be still incorrect, e.g. given
'ldnp h0,h1,[x0,#6]!'
this diagnosis will provide the version:
'ldnp s0,s1,[x0,#6]!'
which is still not right. */
size_t len = strlen (get_mnemonic_name (str));
int i, qlf_idx;
bfd_boolean result;
const size_t size = 2048;
char buf[size];
aarch64_inst *inst_base = &inst.base;
const aarch64_opnd_qualifier_seq_t *qualifiers_list;
/* Init inst. */
reset_aarch64_instruction (&inst);
inst_base->opcode = opcode;
/* Reset the error report so that there is no side effect on the
following operand parsing. */
init_operand_error_report ();
/* Fill inst. */
result = parse_operands (str + len, opcode)
&& programmer_friendly_fixup (&inst);
gas_assert (result);
result = aarch64_opcode_encode (opcode, inst_base, &inst_base->value,
NULL, NULL);
gas_assert (!result);
/* Find the most matched qualifier sequence. */
qlf_idx = find_best_match (inst_base, opcode->qualifiers_list);
gas_assert (qlf_idx > -1);
/* Assign the qualifiers. */
assign_qualifier_sequence (inst_base,
opcode->qualifiers_list[qlf_idx]);
/* Print the hint. */
output_info (_(" did you mean this?"));
snprintf (buf, size, "\t%s", get_mnemonic_name (str));
print_operands (buf, opcode, inst_base->operands);
output_info (_(" %s"), buf);
/* Print out other variant(s) if there is any. */
if (qlf_idx != 0 ||
!empty_qualifier_sequence_p (opcode->qualifiers_list[1]))
output_info (_(" other valid variant(s):"));
/* For each pattern. */
qualifiers_list = opcode->qualifiers_list;
for (i = 0; i < AARCH64_MAX_QLF_SEQ_NUM; ++i, ++qualifiers_list)
{
/* Most opcodes has much fewer patterns in the list.
First NIL qualifier indicates the end in the list. */
if (empty_qualifier_sequence_p (*qualifiers_list) == TRUE)
break;
if (i != qlf_idx)
{
/* Mnemonics name. */
snprintf (buf, size, "\t%s", get_mnemonic_name (str));
/* Assign the qualifiers. */
assign_qualifier_sequence (inst_base, *qualifiers_list);
/* Print instruction. */
print_operands (buf, opcode, inst_base->operands);
output_info (_(" %s"), buf);
}
}
}
break;
case AARCH64_OPDE_OUT_OF_RANGE:
if (detail->data[0] != detail->data[1])
as_bad (_("%s out of range %d to %d at operand %d -- `%s'"),
detail->error ? detail->error : _("immediate value"),
detail->data[0], detail->data[1], idx + 1, str);
else
as_bad (_("%s expected to be %d at operand %d -- `%s'"),
detail->error ? detail->error : _("immediate value"),
detail->data[0], idx + 1, str);
break;
case AARCH64_OPDE_REG_LIST:
if (detail->data[0] == 1)
as_bad (_("invalid number of registers in the list; "
"only 1 register is expected at operand %d -- `%s'"),
idx + 1, str);
else
as_bad (_("invalid number of registers in the list; "
"%d registers are expected at operand %d -- `%s'"),
detail->data[0], idx + 1, str);
break;
case AARCH64_OPDE_UNALIGNED:
as_bad (_("immediate value should be a multiple of "
"%d at operand %d -- `%s'"),
detail->data[0], idx + 1, str);
break;
default:
gas_assert (0);
break;
}
}
/* Process and output the error message about the operand mismatching.
When this function is called, the operand error information had
been collected for an assembly line and there will be multiple
errors in the case of mulitple instruction templates; output the
error message that most closely describes the problem. */
static void
output_operand_error_report (char *str)
{
int largest_error_pos;
const char *msg = NULL;
enum aarch64_operand_error_kind kind;
operand_error_record *curr;
operand_error_record *head = operand_error_report.head;
operand_error_record *record = NULL;
/* No error to report. */
if (head == NULL)
return;
gas_assert (head != NULL && operand_error_report.tail != NULL);
/* Only one error. */
if (head == operand_error_report.tail)
{
DEBUG_TRACE ("single opcode entry with error kind: %s",
operand_mismatch_kind_names[head->detail.kind]);
output_operand_error_record (head, str);
return;
}
/* Find the error kind of the highest severity. */
DEBUG_TRACE ("multiple opcode entres with error kind");
kind = AARCH64_OPDE_NIL;
for (curr = head; curr != NULL; curr = curr->next)
{
gas_assert (curr->detail.kind != AARCH64_OPDE_NIL);
DEBUG_TRACE ("\t%s", operand_mismatch_kind_names[curr->detail.kind]);
if (operand_error_higher_severity_p (curr->detail.kind, kind))
kind = curr->detail.kind;
}
gas_assert (kind != AARCH64_OPDE_NIL);
/* Pick up one of errors of KIND to report. */
largest_error_pos = -2; /* Index can be -1 which means unknown index. */
for (curr = head; curr != NULL; curr = curr->next)
{
if (curr->detail.kind != kind)
continue;
/* If there are multiple errors, pick up the one with the highest
mismatching operand index. In the case of multiple errors with
the equally highest operand index, pick up the first one or the
first one with non-NULL error message. */
if (curr->detail.index > largest_error_pos
|| (curr->detail.index == largest_error_pos && msg == NULL
&& curr->detail.error != NULL))
{
largest_error_pos = curr->detail.index;
record = curr;
msg = record->detail.error;
}
}
gas_assert (largest_error_pos != -2 && record != NULL);
DEBUG_TRACE ("Pick up error kind %s to report",
operand_mismatch_kind_names[record->detail.kind]);
/* Output. */
output_operand_error_record (record, str);
}
/* Write an AARCH64 instruction to buf - always little-endian. */
static void
put_aarch64_insn (char *buf, uint32_t insn)
{
unsigned char *where = (unsigned char *) buf;
where[0] = insn;
where[1] = insn >> 8;
where[2] = insn >> 16;
where[3] = insn >> 24;
}
static uint32_t
get_aarch64_insn (char *buf)
{
unsigned char *where = (unsigned char *) buf;
uint32_t result;
result = (where[0] | (where[1] << 8) | (where[2] << 16) | (where[3] << 24));
return result;
}
static void
output_inst (struct aarch64_inst *new_inst)
{
char *to = NULL;
to = frag_more (INSN_SIZE);
frag_now->tc_frag_data.recorded = 1;
put_aarch64_insn (to, inst.base.value);
if (inst.reloc.type != BFD_RELOC_UNUSED)
{
fixS *fixp = fix_new_aarch64 (frag_now, to - frag_now->fr_literal,
INSN_SIZE, &inst.reloc.exp,
inst.reloc.pc_rel,
inst.reloc.type);
DEBUG_TRACE ("Prepared relocation fix up");
/* Don't check the addend value against the instruction size,
that's the job of our code in md_apply_fix(). */
fixp->fx_no_overflow = 1;
if (new_inst != NULL)
fixp->tc_fix_data.inst = new_inst;
if (aarch64_gas_internal_fixup_p ())
{
gas_assert (inst.reloc.opnd != AARCH64_OPND_NIL);
fixp->tc_fix_data.opnd = inst.reloc.opnd;
fixp->fx_addnumber = inst.reloc.flags;
}
}
dwarf2_emit_insn (INSN_SIZE);
}
/* Link together opcodes of the same name. */
struct templates
{
aarch64_opcode *opcode;
struct templates *next;
};
typedef struct templates templates;
static templates *
lookup_mnemonic (const char *start, int len)
{
templates *templ = NULL;
templ = hash_find_n (aarch64_ops_hsh, start, len);
return templ;
}
/* Subroutine of md_assemble, responsible for looking up the primary
opcode from the mnemonic the user wrote. STR points to the
beginning of the mnemonic. */
static templates *
opcode_lookup (char **str)
{
char *end, *base;
const aarch64_cond *cond;
char condname[16];
int len;
/* Scan up to the end of the mnemonic, which must end in white space,
'.', or end of string. */
for (base = end = *str; is_part_of_name(*end); end++)
if (*end == '.')
break;
if (end == base)
return 0;
inst.cond = COND_ALWAYS;
/* Handle a possible condition. */
if (end[0] == '.')
{
cond = hash_find_n (aarch64_cond_hsh, end + 1, 2);
if (cond)
{
inst.cond = cond->value;
*str = end + 3;
}
else
{
*str = end;
return 0;
}
}
else
*str = end;
len = end - base;
if (inst.cond == COND_ALWAYS)
{
/* Look for unaffixed mnemonic. */
return lookup_mnemonic (base, len);
}
else if (len <= 13)
{
/* append ".c" to mnemonic if conditional */
memcpy (condname, base, len);
memcpy (condname + len, ".c", 2);
base = condname;
len += 2;
return lookup_mnemonic (base, len);
}
return NULL;
}
/* Internal helper routine converting a vector neon_type_el structure
*VECTYPE to a corresponding operand qualifier. */
static inline aarch64_opnd_qualifier_t
vectype_to_qualifier (const struct neon_type_el *vectype)
{
/* Element size in bytes indexed by neon_el_type. */
const unsigned char ele_size[5]
= {1, 2, 4, 8, 16};
const unsigned int ele_base [5] =
{
AARCH64_OPND_QLF_V_8B,
AARCH64_OPND_QLF_V_2H,
AARCH64_OPND_QLF_V_2S,
AARCH64_OPND_QLF_V_1D,
AARCH64_OPND_QLF_V_1Q
};
if (!vectype->defined || vectype->type == NT_invtype)
goto vectype_conversion_fail;
gas_assert (vectype->type >= NT_b && vectype->type <= NT_q);
if (vectype->defined & NTA_HASINDEX)
/* Vector element register. */
return AARCH64_OPND_QLF_S_B + vectype->type;
else
{
/* Vector register. */
int reg_size = ele_size[vectype->type] * vectype->width;
unsigned offset;
unsigned shift;
if (reg_size != 16 && reg_size != 8 && reg_size != 4)
goto vectype_conversion_fail;
/* The conversion is by calculating the offset from the base operand
qualifier for the vector type. The operand qualifiers are regular
enough that the offset can established by shifting the vector width by
a vector-type dependent amount. */
shift = 0;
if (vectype->type == NT_b)
shift = 4;
else if (vectype->type == NT_h || vectype->type == NT_s)
shift = 2;
else if (vectype->type >= NT_d)
shift = 1;
else
gas_assert (0);
offset = ele_base [vectype->type] + (vectype->width >> shift);
gas_assert (AARCH64_OPND_QLF_V_8B <= offset
&& offset <= AARCH64_OPND_QLF_V_1Q);
return offset;
}
vectype_conversion_fail:
first_error (_("bad vector arrangement type"));
return AARCH64_OPND_QLF_NIL;
}
/* Process an optional operand that is found omitted from the assembly line.
Fill *OPERAND for such an operand of type TYPE. OPCODE points to the
instruction's opcode entry while IDX is the index of this omitted operand.
*/
static void
process_omitted_operand (enum aarch64_opnd type, const aarch64_opcode *opcode,
int idx, aarch64_opnd_info *operand)
{
aarch64_insn default_value = get_optional_operand_default_value (opcode);
gas_assert (optional_operand_p (opcode, idx));
gas_assert (!operand->present);
switch (type)
{
case AARCH64_OPND_Rd:
case AARCH64_OPND_Rn:
case AARCH64_OPND_Rm:
case AARCH64_OPND_Rt:
case AARCH64_OPND_Rt2:
case AARCH64_OPND_Rs:
case AARCH64_OPND_Ra:
case AARCH64_OPND_Rt_SYS:
case AARCH64_OPND_Rd_SP:
case AARCH64_OPND_Rn_SP:
case AARCH64_OPND_Fd:
case AARCH64_OPND_Fn:
case AARCH64_OPND_Fm:
case AARCH64_OPND_Fa:
case AARCH64_OPND_Ft:
case AARCH64_OPND_Ft2:
case AARCH64_OPND_Sd:
case AARCH64_OPND_Sn:
case AARCH64_OPND_Sm:
case AARCH64_OPND_Vd:
case AARCH64_OPND_Vn:
case AARCH64_OPND_Vm:
case AARCH64_OPND_VdD1:
case AARCH64_OPND_VnD1:
operand->reg.regno = default_value;
break;
case AARCH64_OPND_Ed:
case AARCH64_OPND_En:
case AARCH64_OPND_Em:
operand->reglane.regno = default_value;
break;
case AARCH64_OPND_IDX:
case AARCH64_OPND_BIT_NUM:
case AARCH64_OPND_IMMR:
case AARCH64_OPND_IMMS:
case AARCH64_OPND_SHLL_IMM:
case AARCH64_OPND_IMM_VLSL:
case AARCH64_OPND_IMM_VLSR:
case AARCH64_OPND_CCMP_IMM:
case AARCH64_OPND_FBITS:
case AARCH64_OPND_UIMM4:
case AARCH64_OPND_UIMM3_OP1:
case AARCH64_OPND_UIMM3_OP2:
case AARCH64_OPND_IMM:
case AARCH64_OPND_WIDTH:
case AARCH64_OPND_UIMM7:
case AARCH64_OPND_NZCV:
operand->imm.value = default_value;
break;
case AARCH64_OPND_EXCEPTION:
inst.reloc.type = BFD_RELOC_UNUSED;
break;
case AARCH64_OPND_BARRIER_ISB:
operand->barrier = aarch64_barrier_options + default_value;
default:
break;
}
}
/* Process the relocation type for move wide instructions.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
process_movw_reloc_info (void)
{
int is32;
unsigned shift;
is32 = inst.base.operands[0].qualifier == AARCH64_OPND_QLF_W ? 1 : 0;
if (inst.base.opcode->op == OP_MOVK)
switch (inst.reloc.type)
{
case BFD_RELOC_AARCH64_MOVW_G0_S:
case BFD_RELOC_AARCH64_MOVW_G1_S:
case BFD_RELOC_AARCH64_MOVW_G2_S:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
set_syntax_error
(_("the specified relocation type is not allowed for MOVK"));
return FALSE;
default:
break;
}
switch (inst.reloc.type)
{
case BFD_RELOC_AARCH64_MOVW_G0:
case BFD_RELOC_AARCH64_MOVW_G0_NC:
case BFD_RELOC_AARCH64_MOVW_G0_S:
case BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC:
case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
shift = 0;
break;
case BFD_RELOC_AARCH64_MOVW_G1:
case BFD_RELOC_AARCH64_MOVW_G1_NC:
case BFD_RELOC_AARCH64_MOVW_G1_S:
case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
shift = 16;
break;
case BFD_RELOC_AARCH64_MOVW_G2:
case BFD_RELOC_AARCH64_MOVW_G2_NC:
case BFD_RELOC_AARCH64_MOVW_G2_S:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
if (is32)
{
set_fatal_syntax_error
(_("the specified relocation type is not allowed for 32-bit "
"register"));
return FALSE;
}
shift = 32;
break;
case BFD_RELOC_AARCH64_MOVW_G3:
if (is32)
{
set_fatal_syntax_error
(_("the specified relocation type is not allowed for 32-bit "
"register"));
return FALSE;
}
shift = 48;
break;
default:
/* More cases should be added when more MOVW-related relocation types
are supported in GAS. */
gas_assert (aarch64_gas_internal_fixup_p ());
/* The shift amount should have already been set by the parser. */
return TRUE;
}
inst.base.operands[1].shifter.amount = shift;
return TRUE;
}
/* A primitive log caculator. */
static inline unsigned int
get_logsz (unsigned int size)
{
const unsigned char ls[16] =
{0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4};
if (size > 16)
{
gas_assert (0);
return -1;
}
gas_assert (ls[size - 1] != (unsigned char)-1);
return ls[size - 1];
}
/* Determine and return the real reloc type code for an instruction
with the pseudo reloc type code BFD_RELOC_AARCH64_LDST_LO12. */
static inline bfd_reloc_code_real_type
ldst_lo12_determine_real_reloc_type (void)
{
unsigned logsz;
enum aarch64_opnd_qualifier opd0_qlf = inst.base.operands[0].qualifier;
enum aarch64_opnd_qualifier opd1_qlf = inst.base.operands[1].qualifier;
const bfd_reloc_code_real_type reloc_ldst_lo12[3][5] = {
{
BFD_RELOC_AARCH64_LDST8_LO12,
BFD_RELOC_AARCH64_LDST16_LO12,
BFD_RELOC_AARCH64_LDST32_LO12,
BFD_RELOC_AARCH64_LDST64_LO12,
BFD_RELOC_AARCH64_LDST128_LO12
},
{
BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12,
BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12,
BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12,
BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12,
BFD_RELOC_AARCH64_NONE
},
{
BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC,
BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC,
BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC,
BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC,
BFD_RELOC_AARCH64_NONE
}
};
gas_assert (inst.reloc.type == BFD_RELOC_AARCH64_LDST_LO12
|| inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12
|| (inst.reloc.type
== BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC));
gas_assert (inst.base.opcode->operands[1] == AARCH64_OPND_ADDR_UIMM12);
if (opd1_qlf == AARCH64_OPND_QLF_NIL)
opd1_qlf =
aarch64_get_expected_qualifier (inst.base.opcode->qualifiers_list,
1, opd0_qlf, 0);
gas_assert (opd1_qlf != AARCH64_OPND_QLF_NIL);
logsz = get_logsz (aarch64_get_qualifier_esize (opd1_qlf));
if (inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12
|| inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC)
gas_assert (logsz <= 3);
else
gas_assert (logsz <= 4);
/* In reloc.c, these pseudo relocation types should be defined in similar
order as above reloc_ldst_lo12 array. Because the array index calcuation
below relies on this. */
return reloc_ldst_lo12[inst.reloc.type - BFD_RELOC_AARCH64_LDST_LO12][logsz];
}
/* Check whether a register list REGINFO is valid. The registers must be
numbered in increasing order (modulo 32), in increments of one or two.
If ACCEPT_ALTERNATE is non-zero, the register numbers should be in
increments of two.
Return FALSE if such a register list is invalid, otherwise return TRUE. */
static bfd_boolean
reg_list_valid_p (uint32_t reginfo, int accept_alternate)
{
uint32_t i, nb_regs, prev_regno, incr;
nb_regs = 1 + (reginfo & 0x3);
reginfo >>= 2;
prev_regno = reginfo & 0x1f;
incr = accept_alternate ? 2 : 1;
for (i = 1; i < nb_regs; ++i)
{
uint32_t curr_regno;
reginfo >>= 5;
curr_regno = reginfo & 0x1f;
if (curr_regno != ((prev_regno + incr) & 0x1f))
return FALSE;
prev_regno = curr_regno;
}
return TRUE;
}
/* Generic instruction operand parser. This does no encoding and no
semantic validation; it merely squirrels values away in the inst
structure. Returns TRUE or FALSE depending on whether the
specified grammar matched. */
static bfd_boolean
parse_operands (char *str, const aarch64_opcode *opcode)
{
int i;
char *backtrack_pos = 0;
const enum aarch64_opnd *operands = opcode->operands;
clear_error ();
skip_whitespace (str);
for (i = 0; operands[i] != AARCH64_OPND_NIL; i++)
{
int64_t val;
int isreg32, isregzero;
int comma_skipped_p = 0;
aarch64_reg_type rtype;
struct neon_type_el vectype;
aarch64_opnd_info *info = &inst.base.operands[i];
DEBUG_TRACE ("parse operand %d", i);
/* Assign the operand code. */
info->type = operands[i];
if (optional_operand_p (opcode, i))
{
/* Remember where we are in case we need to backtrack. */
gas_assert (!backtrack_pos);
backtrack_pos = str;
}
/* Expect comma between operands; the backtrack mechanizm will take
care of cases of omitted optional operand. */
if (i > 0 && ! skip_past_char (&str, ','))
{
set_syntax_error (_("comma expected between operands"));
goto failure;
}
else
comma_skipped_p = 1;
switch (operands[i])
{
case AARCH64_OPND_Rd:
case AARCH64_OPND_Rn:
case AARCH64_OPND_Rm:
case AARCH64_OPND_Rt:
case AARCH64_OPND_Rt2:
case AARCH64_OPND_Rs:
case AARCH64_OPND_Ra:
case AARCH64_OPND_Rt_SYS:
case AARCH64_OPND_PAIRREG:
po_int_reg_or_fail (1, 0);
break;
case AARCH64_OPND_Rd_SP:
case AARCH64_OPND_Rn_SP:
po_int_reg_or_fail (0, 1);
break;
case AARCH64_OPND_Rm_EXT:
case AARCH64_OPND_Rm_SFT:
po_misc_or_fail (parse_shifter_operand
(&str, info, (operands[i] == AARCH64_OPND_Rm_EXT
? SHIFTED_ARITH_IMM
: SHIFTED_LOGIC_IMM)));
if (!info->shifter.operator_present)
{
/* Default to LSL if not present. Libopcodes prefers shifter
kind to be explicit. */
gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
info->shifter.kind = AARCH64_MOD_LSL;
/* For Rm_EXT, libopcodes will carry out further check on whether
or not stack pointer is used in the instruction (Recall that
"the extend operator is not optional unless at least one of
"Rd" or "Rn" is '11111' (i.e. WSP)"). */
}
break;
case AARCH64_OPND_Fd:
case AARCH64_OPND_Fn:
case AARCH64_OPND_Fm:
case AARCH64_OPND_Fa:
case AARCH64_OPND_Ft:
case AARCH64_OPND_Ft2:
case AARCH64_OPND_Sd:
case AARCH64_OPND_Sn:
case AARCH64_OPND_Sm:
val = aarch64_reg_parse (&str, REG_TYPE_BHSDQ, &rtype, NULL);
if (val == PARSE_FAIL)
{
first_error (_(get_reg_expected_msg (REG_TYPE_BHSDQ)));
goto failure;
}
gas_assert (rtype >= REG_TYPE_FP_B && rtype <= REG_TYPE_FP_Q);
info->reg.regno = val;
info->qualifier = AARCH64_OPND_QLF_S_B + (rtype - REG_TYPE_FP_B);
break;
case AARCH64_OPND_Vd:
case AARCH64_OPND_Vn:
case AARCH64_OPND_Vm:
val = aarch64_reg_parse (&str, REG_TYPE_VN, NULL, &vectype);
if (val == PARSE_FAIL)
{
first_error (_(get_reg_expected_msg (REG_TYPE_VN)));
goto failure;
}
if (vectype.defined & NTA_HASINDEX)
goto failure;
info->reg.regno = val;
info->qualifier = vectype_to_qualifier (&vectype);
if (info->qualifier == AARCH64_OPND_QLF_NIL)
goto failure;
break;
case AARCH64_OPND_VdD1:
case AARCH64_OPND_VnD1:
val = aarch64_reg_parse (&str, REG_TYPE_VN, NULL, &vectype);
if (val == PARSE_FAIL)
{
set_first_syntax_error (_(get_reg_expected_msg (REG_TYPE_VN)));
goto failure;
}
if (vectype.type != NT_d || vectype.index != 1)
{
set_fatal_syntax_error
(_("the top half of a 128-bit FP/SIMD register is expected"));
goto failure;
}
info->reg.regno = val;
/* N.B: VdD1 and VnD1 are treated as an fp or advsimd scalar register
here; it is correct for the purpose of encoding/decoding since
only the register number is explicitly encoded in the related
instructions, although this appears a bit hacky. */
info->qualifier = AARCH64_OPND_QLF_S_D;
break;
case AARCH64_OPND_Ed:
case AARCH64_OPND_En:
case AARCH64_OPND_Em:
val = aarch64_reg_parse (&str, REG_TYPE_VN, NULL, &vectype);
if (val == PARSE_FAIL)
{
first_error (_(get_reg_expected_msg (REG_TYPE_VN)));
goto failure;
}
if (vectype.type == NT_invtype || !(vectype.defined & NTA_HASINDEX))
goto failure;
info->reglane.regno = val;
info->reglane.index = vectype.index;
info->qualifier = vectype_to_qualifier (&vectype);
if (info->qualifier == AARCH64_OPND_QLF_NIL)
goto failure;
break;
case AARCH64_OPND_LVn:
case AARCH64_OPND_LVt:
case AARCH64_OPND_LVt_AL:
case AARCH64_OPND_LEt:
if ((val = parse_neon_reg_list (&str, &vectype)) == PARSE_FAIL)
goto failure;
if (! reg_list_valid_p (val, /* accept_alternate */ 0))
{
set_fatal_syntax_error (_("invalid register list"));
goto failure;
}
info->reglist.first_regno = (val >> 2) & 0x1f;
info->reglist.num_regs = (val & 0x3) + 1;
if (operands[i] == AARCH64_OPND_LEt)
{
if (!(vectype.defined & NTA_HASINDEX))
goto failure;
info->reglist.has_index = 1;
info->reglist.index = vectype.index;
}
else if (!(vectype.defined & NTA_HASTYPE))
goto failure;
info->qualifier = vectype_to_qualifier (&vectype);
if (info->qualifier == AARCH64_OPND_QLF_NIL)
goto failure;
break;
case AARCH64_OPND_Cn:
case AARCH64_OPND_Cm:
po_reg_or_fail (REG_TYPE_CN);
if (val > 15)
{
set_fatal_syntax_error (_(get_reg_expected_msg (REG_TYPE_CN)));
goto failure;
}
inst.base.operands[i].reg.regno = val;
break;
case AARCH64_OPND_SHLL_IMM:
case AARCH64_OPND_IMM_VLSR:
po_imm_or_fail (1, 64);
info->imm.value = val;
break;
case AARCH64_OPND_CCMP_IMM:
case AARCH64_OPND_FBITS:
case AARCH64_OPND_UIMM4:
case AARCH64_OPND_UIMM3_OP1:
case AARCH64_OPND_UIMM3_OP2:
case AARCH64_OPND_IMM_VLSL:
case AARCH64_OPND_IMM:
case AARCH64_OPND_WIDTH:
po_imm_nc_or_fail ();
info->imm.value = val;
break;
case AARCH64_OPND_UIMM7:
po_imm_or_fail (0, 127);
info->imm.value = val;
break;
case AARCH64_OPND_IDX:
case AARCH64_OPND_BIT_NUM:
case AARCH64_OPND_IMMR:
case AARCH64_OPND_IMMS:
po_imm_or_fail (0, 63);
info->imm.value = val;
break;
case AARCH64_OPND_IMM0:
po_imm_nc_or_fail ();
if (val != 0)
{
set_fatal_syntax_error (_("immediate zero expected"));
goto failure;
}
info->imm.value = 0;
break;
case AARCH64_OPND_FPIMM0:
{
int qfloat;
bfd_boolean res1 = FALSE, res2 = FALSE;
/* N.B. -0.0 will be rejected; although -0.0 shouldn't be rejected,
it is probably not worth the effort to support it. */
if (!(res1 = parse_aarch64_imm_float (&str, &qfloat, FALSE))
&& !(res2 = parse_constant_immediate (&str, &val)))
goto failure;
if ((res1 && qfloat == 0) || (res2 && val == 0))
{
info->imm.value = 0;
info->imm.is_fp = 1;
break;
}
set_fatal_syntax_error (_("immediate zero expected"));
goto failure;
}
case AARCH64_OPND_IMM_MOV:
{
char *saved = str;
if (reg_name_p (str, REG_TYPE_R_Z_SP) ||
reg_name_p (str, REG_TYPE_VN))
goto failure;
str = saved;
po_misc_or_fail (my_get_expression (&inst.reloc.exp, &str,
GE_OPT_PREFIX, 1));
/* The MOV immediate alias will be fixed up by fix_mov_imm_insn
later. fix_mov_imm_insn will try to determine a machine
instruction (MOVZ, MOVN or ORR) for it and will issue an error
message if the immediate cannot be moved by a single
instruction. */
aarch64_set_gas_internal_fixup (&inst.reloc, info, 1);
inst.base.operands[i].skip = 1;
}
break;
case AARCH64_OPND_SIMD_IMM:
case AARCH64_OPND_SIMD_IMM_SFT:
if (! parse_big_immediate (&str, &val))
goto failure;
assign_imm_if_const_or_fixup_later (&inst.reloc, info,
/* addr_off_p */ 0,
/* need_libopcodes_p */ 1,
/* skip_p */ 1);
/* Parse shift.
N.B. although AARCH64_OPND_SIMD_IMM doesn't permit any
shift, we don't check it here; we leave the checking to
the libopcodes (operand_general_constraint_met_p). By
doing this, we achieve better diagnostics. */
if (skip_past_comma (&str)
&& ! parse_shift (&str, info, SHIFTED_LSL_MSL))
goto failure;
if (!info->shifter.operator_present
&& info->type == AARCH64_OPND_SIMD_IMM_SFT)
{
/* Default to LSL if not present. Libopcodes prefers shifter
kind to be explicit. */
gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
info->shifter.kind = AARCH64_MOD_LSL;
}
break;
case AARCH64_OPND_FPIMM:
case AARCH64_OPND_SIMD_FPIMM:
{
int qfloat;
bfd_boolean dp_p
= (aarch64_get_qualifier_esize (inst.base.operands[0].qualifier)
== 8);
if (! parse_aarch64_imm_float (&str, &qfloat, dp_p))
goto failure;
if (qfloat == 0)
{
set_fatal_syntax_error (_("invalid floating-point constant"));
goto failure;
}
inst.base.operands[i].imm.value = encode_imm_float_bits (qfloat);
inst.base.operands[i].imm.is_fp = 1;
}
break;
case AARCH64_OPND_LIMM:
po_misc_or_fail (parse_shifter_operand (&str, info,
SHIFTED_LOGIC_IMM));
if (info->shifter.operator_present)
{
set_fatal_syntax_error
(_("shift not allowed for bitmask immediate"));
goto failure;
}
assign_imm_if_const_or_fixup_later (&inst.reloc, info,
/* addr_off_p */ 0,
/* need_libopcodes_p */ 1,
/* skip_p */ 1);
break;
case AARCH64_OPND_AIMM:
if (opcode->op == OP_ADD)
/* ADD may have relocation types. */
po_misc_or_fail (parse_shifter_operand_reloc (&str, info,
SHIFTED_ARITH_IMM));
else
po_misc_or_fail (parse_shifter_operand (&str, info,
SHIFTED_ARITH_IMM));
switch (inst.reloc.type)
{
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
info->shifter.amount = 12;
break;
case BFD_RELOC_UNUSED:
aarch64_set_gas_internal_fixup (&inst.reloc, info, 0);
if (info->shifter.kind != AARCH64_MOD_NONE)
inst.reloc.flags = FIXUP_F_HAS_EXPLICIT_SHIFT;
inst.reloc.pc_rel = 0;
break;
default:
break;
}
info->imm.value = 0;
if (!info->shifter.operator_present)
{
/* Default to LSL if not present. Libopcodes prefers shifter
kind to be explicit. */
gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
info->shifter.kind = AARCH64_MOD_LSL;
}
break;
case AARCH64_OPND_HALF:
{
/* #<imm16> or relocation. */
int internal_fixup_p;
po_misc_or_fail (parse_half (&str, &internal_fixup_p));
if (internal_fixup_p)
aarch64_set_gas_internal_fixup (&inst.reloc, info, 0);
skip_whitespace (str);
if (skip_past_comma (&str))
{
/* {, LSL #<shift>} */
if (! aarch64_gas_internal_fixup_p ())
{
set_fatal_syntax_error (_("can't mix relocation modifier "
"with explicit shift"));
goto failure;
}
po_misc_or_fail (parse_shift (&str, info, SHIFTED_LSL));
}
else
inst.base.operands[i].shifter.amount = 0;
inst.base.operands[i].shifter.kind = AARCH64_MOD_LSL;
inst.base.operands[i].imm.value = 0;
if (! process_movw_reloc_info ())
goto failure;
}
break;
case AARCH64_OPND_EXCEPTION:
po_misc_or_fail (parse_immediate_expression (&str, &inst.reloc.exp));
assign_imm_if_const_or_fixup_later (&inst.reloc, info,
/* addr_off_p */ 0,
/* need_libopcodes_p */ 0,
/* skip_p */ 1);
break;
case AARCH64_OPND_NZCV:
{
const asm_nzcv *nzcv = hash_find_n (aarch64_nzcv_hsh, str, 4);
if (nzcv != NULL)
{
str += 4;
info->imm.value = nzcv->value;
break;
}
po_imm_or_fail (0, 15);
info->imm.value = val;
}
break;
case AARCH64_OPND_COND:
case AARCH64_OPND_COND1:
info->cond = hash_find_n (aarch64_cond_hsh, str, 2);
str += 2;
if (info->cond == NULL)
{
set_syntax_error (_("invalid condition"));
goto failure;
}
else if (operands[i] == AARCH64_OPND_COND1
&& (info->cond->value & 0xe) == 0xe)
{
/* Not allow AL or NV. */
set_default_error ();
goto failure;
}
break;
case AARCH64_OPND_ADDR_ADRP:
po_misc_or_fail (parse_adrp (&str));
/* Clear the value as operand needs to be relocated. */
info->imm.value = 0;
break;
case AARCH64_OPND_ADDR_PCREL14:
case AARCH64_OPND_ADDR_PCREL19:
case AARCH64_OPND_ADDR_PCREL21:
case AARCH64_OPND_ADDR_PCREL26:
po_misc_or_fail (parse_address_reloc (&str, info));
if (!info->addr.pcrel)
{
set_syntax_error (_("invalid pc-relative address"));
goto failure;
}
if (inst.gen_lit_pool
&& (opcode->iclass != loadlit || opcode->op == OP_PRFM_LIT))
{
/* Only permit "=value" in the literal load instructions.
The literal will be generated by programmer_friendly_fixup. */
set_syntax_error (_("invalid use of \"=immediate\""));
goto failure;
}
if (inst.reloc.exp.X_op == O_symbol && find_reloc_table_entry (&str))
{
set_syntax_error (_("unrecognized relocation suffix"));
goto failure;
}
if (inst.reloc.exp.X_op == O_constant && !inst.gen_lit_pool)
{
info->imm.value = inst.reloc.exp.X_add_number;
inst.reloc.type = BFD_RELOC_UNUSED;
}
else
{
info->imm.value = 0;
if (inst.reloc.type == BFD_RELOC_UNUSED)
switch (opcode->iclass)
{
case compbranch:
case condbranch:
/* e.g. CBZ or B.COND */
gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL19);
inst.reloc.type = BFD_RELOC_AARCH64_BRANCH19;
break;
case testbranch:
/* e.g. TBZ */
gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL14);
inst.reloc.type = BFD_RELOC_AARCH64_TSTBR14;
break;
case branch_imm:
/* e.g. B or BL */
gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL26);
inst.reloc.type =
(opcode->op == OP_BL) ? BFD_RELOC_AARCH64_CALL26
: BFD_RELOC_AARCH64_JUMP26;
break;
case loadlit:
gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL19);
inst.reloc.type = BFD_RELOC_AARCH64_LD_LO19_PCREL;
break;
case pcreladdr:
gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL21);
inst.reloc.type = BFD_RELOC_AARCH64_ADR_LO21_PCREL;
break;
default:
gas_assert (0);
abort ();
}
inst.reloc.pc_rel = 1;
}
break;
case AARCH64_OPND_ADDR_SIMPLE:
case AARCH64_OPND_SIMD_ADDR_SIMPLE:
/* [<Xn|SP>{, #<simm>}] */
po_char_or_fail ('[');
po_reg_or_fail (REG_TYPE_R64_SP);
/* Accept optional ", #0". */
if (operands[i] == AARCH64_OPND_ADDR_SIMPLE
&& skip_past_char (&str, ','))
{
skip_past_char (&str, '#');
if (! skip_past_char (&str, '0'))
{
set_fatal_syntax_error
(_("the optional immediate offset can only be 0"));
goto failure;
}
}
po_char_or_fail (']');
info->addr.base_regno = val;
break;
case AARCH64_OPND_ADDR_REGOFF:
/* [<Xn|SP>, <R><m>{, <extend> {<amount>}}] */
po_misc_or_fail (parse_address (&str, info, 0));
if (info->addr.pcrel || !info->addr.offset.is_reg
|| !info->addr.preind || info->addr.postind
|| info->addr.writeback)
{
set_syntax_error (_("invalid addressing mode"));
goto failure;
}
if (!info->shifter.operator_present)
{
/* Default to LSL if not present. Libopcodes prefers shifter
kind to be explicit. */
gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
info->shifter.kind = AARCH64_MOD_LSL;
}
/* Qualifier to be deduced by libopcodes. */
break;
case AARCH64_OPND_ADDR_SIMM7:
po_misc_or_fail (parse_address (&str, info, 0));
if (info->addr.pcrel || info->addr.offset.is_reg
|| (!info->addr.preind && !info->addr.postind))
{
set_syntax_error (_("invalid addressing mode"));
goto failure;
}
assign_imm_if_const_or_fixup_later (&inst.reloc, info,
/* addr_off_p */ 1,
/* need_libopcodes_p */ 1,
/* skip_p */ 0);
break;
case AARCH64_OPND_ADDR_SIMM9:
case AARCH64_OPND_ADDR_SIMM9_2:
po_misc_or_fail (parse_address_reloc (&str, info));
if (info->addr.pcrel || info->addr.offset.is_reg
|| (!info->addr.preind && !info->addr.postind)
|| (operands[i] == AARCH64_OPND_ADDR_SIMM9_2
&& info->addr.writeback))
{
set_syntax_error (_("invalid addressing mode"));
goto failure;
}
if (inst.reloc.type != BFD_RELOC_UNUSED)
{
set_syntax_error (_("relocation not allowed"));
goto failure;
}
assign_imm_if_const_or_fixup_later (&inst.reloc, info,
/* addr_off_p */ 1,
/* need_libopcodes_p */ 1,
/* skip_p */ 0);
break;
case AARCH64_OPND_ADDR_UIMM12:
po_misc_or_fail (parse_address_reloc (&str, info));
if (info->addr.pcrel || info->addr.offset.is_reg
|| !info->addr.preind || info->addr.writeback)
{
set_syntax_error (_("invalid addressing mode"));
goto failure;
}
if (inst.reloc.type == BFD_RELOC_UNUSED)
aarch64_set_gas_internal_fixup (&inst.reloc, info, 1);
else if (inst.reloc.type == BFD_RELOC_AARCH64_LDST_LO12
|| (inst.reloc.type
== BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12)
|| (inst.reloc.type
== BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC))
inst.reloc.type = ldst_lo12_determine_real_reloc_type ();
/* Leave qualifier to be determined by libopcodes. */
break;
case AARCH64_OPND_SIMD_ADDR_POST:
/* [<Xn|SP>], <Xm|#<amount>> */
po_misc_or_fail (parse_address (&str, info, 1));
if (!info->addr.postind || !info->addr.writeback)
{
set_syntax_error (_("invalid addressing mode"));
goto failure;
}
if (!info->addr.offset.is_reg)
{
if (inst.reloc.exp.X_op == O_constant)
info->addr.offset.imm = inst.reloc.exp.X_add_number;
else
{
set_fatal_syntax_error
(_("writeback value should be an immediate constant"));
goto failure;
}
}
/* No qualifier. */
break;
case AARCH64_OPND_SYSREG:
if ((val = parse_sys_reg (&str, aarch64_sys_regs_hsh, 1, 0))
== PARSE_FAIL)
{
set_syntax_error (_("unknown or missing system register name"));
goto failure;
}
inst.base.operands[i].sysreg = val;
break;
case AARCH64_OPND_PSTATEFIELD:
if ((val = parse_sys_reg (&str, aarch64_pstatefield_hsh, 0, 1))
== PARSE_FAIL)
{
set_syntax_error (_("unknown or missing PSTATE field name"));
goto failure;
}
inst.base.operands[i].pstatefield = val;
break;
case AARCH64_OPND_SYSREG_IC:
inst.base.operands[i].sysins_op =
parse_sys_ins_reg (&str, aarch64_sys_regs_ic_hsh);
goto sys_reg_ins;
case AARCH64_OPND_SYSREG_DC:
inst.base.operands[i].sysins_op =
parse_sys_ins_reg (&str, aarch64_sys_regs_dc_hsh);
goto sys_reg_ins;
case AARCH64_OPND_SYSREG_AT:
inst.base.operands[i].sysins_op =
parse_sys_ins_reg (&str, aarch64_sys_regs_at_hsh);
goto sys_reg_ins;
case AARCH64_OPND_SYSREG_TLBI:
inst.base.operands[i].sysins_op =
parse_sys_ins_reg (&str, aarch64_sys_regs_tlbi_hsh);
sys_reg_ins:
if (inst.base.operands[i].sysins_op == NULL)
{
set_fatal_syntax_error ( _("unknown or missing operation name"));
goto failure;
}
break;
case AARCH64_OPND_BARRIER:
case AARCH64_OPND_BARRIER_ISB:
val = parse_barrier (&str);
if (val != PARSE_FAIL
&& operands[i] == AARCH64_OPND_BARRIER_ISB && val != 0xf)
{
/* ISB only accepts options name 'sy'. */
set_syntax_error
(_("the specified option is not accepted in ISB"));
/* Turn off backtrack as this optional operand is present. */
backtrack_pos = 0;
goto failure;
}
/* This is an extension to accept a 0..15 immediate. */
if (val == PARSE_FAIL)
po_imm_or_fail (0, 15);
info->barrier = aarch64_barrier_options + val;
break;
case AARCH64_OPND_PRFOP:
val = parse_pldop (&str);
/* This is an extension to accept a 0..31 immediate. */
if (val == PARSE_FAIL)
po_imm_or_fail (0, 31);
inst.base.operands[i].prfop = aarch64_prfops + val;
break;
case AARCH64_OPND_BARRIER_PSB:
val = parse_barrier_psb (&str, &(info->hint_option));
if (val == PARSE_FAIL)
goto failure;
break;
default:
as_fatal (_("unhandled operand code %d"), operands[i]);
}
/* If we get here, this operand was successfully parsed. */
inst.base.operands[i].present = 1;
continue;
failure:
/* The parse routine should already have set the error, but in case
not, set a default one here. */
if (! error_p ())
set_default_error ();
if (! backtrack_pos)
goto parse_operands_return;
{
/* We reach here because this operand is marked as optional, and
either no operand was supplied or the operand was supplied but it
was syntactically incorrect. In the latter case we report an
error. In the former case we perform a few more checks before
dropping through to the code to insert the default operand. */
char *tmp = backtrack_pos;
char endchar = END_OF_INSN;
if (i != (aarch64_num_of_operands (opcode) - 1))
endchar = ',';
skip_past_char (&tmp, ',');
if (*tmp != endchar)
/* The user has supplied an operand in the wrong format. */
goto parse_operands_return;
/* Make sure there is not a comma before the optional operand.
For example the fifth operand of 'sys' is optional:
sys #0,c0,c0,#0, <--- wrong
sys #0,c0,c0,#0 <--- correct. */
if (comma_skipped_p && i && endchar == END_OF_INSN)
{
set_fatal_syntax_error
(_("unexpected comma before the omitted optional operand"));
goto parse_operands_return;
}
}
/* Reaching here means we are dealing with an optional operand that is
omitted from the assembly line. */
gas_assert (optional_operand_p (opcode, i));
info->present = 0;
process_omitted_operand (operands[i], opcode, i, info);
/* Try again, skipping the optional operand at backtrack_pos. */
str = backtrack_pos;
backtrack_pos = 0;
/* Clear any error record after the omitted optional operand has been
successfully handled. */
clear_error ();
}
/* Check if we have parsed all the operands. */
if (*str != '\0' && ! error_p ())
{
/* Set I to the index of the last present operand; this is
for the purpose of diagnostics. */
for (i -= 1; i >= 0 && !inst.base.operands[i].present; --i)
;
set_fatal_syntax_error
(_("unexpected characters following instruction"));
}
parse_operands_return:
if (error_p ())
{
DEBUG_TRACE ("parsing FAIL: %s - %s",
operand_mismatch_kind_names[get_error_kind ()],
get_error_message ());
/* Record the operand error properly; this is useful when there
are multiple instruction templates for a mnemonic name, so that
later on, we can select the error that most closely describes
the problem. */
record_operand_error (opcode, i, get_error_kind (),
get_error_message ());
return FALSE;
}
else
{
DEBUG_TRACE ("parsing SUCCESS");
return TRUE;
}
}
/* It does some fix-up to provide some programmer friendly feature while
keeping the libopcodes happy, i.e. libopcodes only accepts
the preferred architectural syntax.
Return FALSE if there is any failure; otherwise return TRUE. */
static bfd_boolean
programmer_friendly_fixup (aarch64_instruction *instr)
{
aarch64_inst *base = &instr->base;
const aarch64_opcode *opcode = base->opcode;
enum aarch64_op op = opcode->op;
aarch64_opnd_info *operands = base->operands;
DEBUG_TRACE ("enter");
switch (opcode->iclass)
{
case testbranch:
/* TBNZ Xn|Wn, #uimm6, label
Test and Branch Not Zero: conditionally jumps to label if bit number
uimm6 in register Xn is not zero. The bit number implies the width of
the register, which may be written and should be disassembled as Wn if
uimm is less than 32. */
if (operands[0].qualifier == AARCH64_OPND_QLF_W)
{
if (operands[1].imm.value >= 32)
{
record_operand_out_of_range_error (opcode, 1, _("immediate value"),
0, 31);
return FALSE;
}
operands[0].qualifier = AARCH64_OPND_QLF_X;
}
break;
case loadlit:
/* LDR Wt, label | =value
As a convenience assemblers will typically permit the notation
"=value" in conjunction with the pc-relative literal load instructions
to automatically place an immediate value or symbolic address in a
nearby literal pool and generate a hidden label which references it.
ISREG has been set to 0 in the case of =value. */
if (instr->gen_lit_pool
&& (op == OP_LDR_LIT || op == OP_LDRV_LIT || op == OP_LDRSW_LIT))
{
int size = aarch64_get_qualifier_esize (operands[0].qualifier);
if (op == OP_LDRSW_LIT)
size = 4;
if (instr->reloc.exp.X_op != O_constant
&& instr->reloc.exp.X_op != O_big
&& instr->reloc.exp.X_op != O_symbol)
{
record_operand_error (opcode, 1,
AARCH64_OPDE_FATAL_SYNTAX_ERROR,
_("constant expression expected"));
return FALSE;
}
if (! add_to_lit_pool (&instr->reloc.exp, size))
{
record_operand_error (opcode, 1,
AARCH64_OPDE_OTHER_ERROR,
_("literal pool insertion failed"));
return FALSE;
}
}
break;
case log_shift:
case bitfield:
/* UXT[BHW] Wd, Wn
Unsigned Extend Byte|Halfword|Word: UXT[BH] is architectural alias
for UBFM Wd,Wn,#0,#7|15, while UXTW is pseudo instruction which is
encoded using ORR Wd, WZR, Wn (MOV Wd,Wn).
A programmer-friendly assembler should accept a destination Xd in
place of Wd, however that is not the preferred form for disassembly.
*/
if ((op == OP_UXTB || op == OP_UXTH || op == OP_UXTW)
&& operands[1].qualifier == AARCH64_OPND_QLF_W
&& operands[0].qualifier == AARCH64_OPND_QLF_X)
operands[0].qualifier = AARCH64_OPND_QLF_W;
break;
case addsub_ext:
{
/* In the 64-bit form, the final register operand is written as Wm
for all but the (possibly omitted) UXTX/LSL and SXTX
operators.
As a programmer-friendly assembler, we accept e.g.
ADDS <Xd>, <Xn|SP>, <Xm>{, UXTB {#<amount>}} and change it to
ADDS <Xd>, <Xn|SP>, <Wm>{, UXTB {#<amount>}}. */
int idx = aarch64_operand_index (opcode->operands,
AARCH64_OPND_Rm_EXT);
gas_assert (idx == 1 || idx == 2);
if (operands[0].qualifier == AARCH64_OPND_QLF_X
&& operands[idx].qualifier == AARCH64_OPND_QLF_X
&& operands[idx].shifter.kind != AARCH64_MOD_LSL
&& operands[idx].shifter.kind != AARCH64_MOD_UXTX
&& operands[idx].shifter.kind != AARCH64_MOD_SXTX)
operands[idx].qualifier = AARCH64_OPND_QLF_W;
}
break;
default:
break;
}
DEBUG_TRACE ("exit with SUCCESS");
return TRUE;
}
/* Check for loads and stores that will cause unpredictable behavior. */
static void
warn_unpredictable_ldst (aarch64_instruction *instr, char *str)
{
aarch64_inst *base = &instr->base;
const aarch64_opcode *opcode = base->opcode;
const aarch64_opnd_info *opnds = base->operands;
switch (opcode->iclass)
{
case ldst_pos:
case ldst_imm9:
case ldst_unscaled:
case ldst_unpriv:
/* Loading/storing the base register is unpredictable if writeback. */
if ((aarch64_get_operand_class (opnds[0].type)
== AARCH64_OPND_CLASS_INT_REG)
&& opnds[0].reg.regno == opnds[1].addr.base_regno
&& opnds[1].addr.base_regno != REG_SP
&& opnds[1].addr.writeback)
as_warn (_("unpredictable transfer with writeback -- `%s'"), str);
break;
case ldstpair_off:
case ldstnapair_offs:
case ldstpair_indexed:
/* Loading/storing the base register is unpredictable if writeback. */
if ((aarch64_get_operand_class (opnds[0].type)
== AARCH64_OPND_CLASS_INT_REG)
&& (opnds[0].reg.regno == opnds[2].addr.base_regno
|| opnds[1].reg.regno == opnds[2].addr.base_regno)
&& opnds[2].addr.base_regno != REG_SP
&& opnds[2].addr.writeback)
as_warn (_("unpredictable transfer with writeback -- `%s'"), str);
/* Load operations must load different registers. */
if ((opcode->opcode & (1 << 22))
&& opnds[0].reg.regno == opnds[1].reg.regno)
as_warn (_("unpredictable load of register pair -- `%s'"), str);
break;
default:
break;
}
}
/* A wrapper function to interface with libopcodes on encoding and
record the error message if there is any.
Return TRUE on success; otherwise return FALSE. */
static bfd_boolean
do_encode (const aarch64_opcode *opcode, aarch64_inst *instr,
aarch64_insn *code)
{
aarch64_operand_error error_info;
error_info.kind = AARCH64_OPDE_NIL;
if (aarch64_opcode_encode (opcode, instr, code, NULL, &error_info))
return TRUE;
else
{
gas_assert (error_info.kind != AARCH64_OPDE_NIL);
record_operand_error_info (opcode, &error_info);
return FALSE;
}
}
#ifdef DEBUG_AARCH64
static inline void
dump_opcode_operands (const aarch64_opcode *opcode)
{
int i = 0;
while (opcode->operands[i] != AARCH64_OPND_NIL)
{
aarch64_verbose ("\t\t opnd%d: %s", i,
aarch64_get_operand_name (opcode->operands[i])[0] != '\0'
? aarch64_get_operand_name (opcode->operands[i])
: aarch64_get_operand_desc (opcode->operands[i]));
++i;
}
}
#endif /* DEBUG_AARCH64 */
/* This is the guts of the machine-dependent assembler. STR points to a
machine dependent instruction. This function is supposed to emit
the frags/bytes it assembles to. */
void
md_assemble (char *str)
{
char *p = str;
templates *template;
aarch64_opcode *opcode;
aarch64_inst *inst_base;
unsigned saved_cond;
/* Align the previous label if needed. */
if (last_label_seen != NULL)
{
symbol_set_frag (last_label_seen, frag_now);
S_SET_VALUE (last_label_seen, (valueT) frag_now_fix ());
S_SET_SEGMENT (last_label_seen, now_seg);
}
inst.reloc.type = BFD_RELOC_UNUSED;
DEBUG_TRACE ("\n\n");
DEBUG_TRACE ("==============================");
DEBUG_TRACE ("Enter md_assemble with %s", str);
template = opcode_lookup (&p);
if (!template)
{
/* It wasn't an instruction, but it might be a register alias of
the form alias .req reg directive. */
if (!create_register_alias (str, p))
as_bad (_("unknown mnemonic `%s' -- `%s'"), get_mnemonic_name (str),
str);
return;
}
skip_whitespace (p);
if (*p == ',')
{
as_bad (_("unexpected comma after the mnemonic name `%s' -- `%s'"),
get_mnemonic_name (str), str);
return;
}
init_operand_error_report ();
/* Sections are assumed to start aligned. In executable section, there is no
MAP_DATA symbol pending. So we only align the address during
MAP_DATA --> MAP_INSN transition.
For other sections, this is not guaranteed. */
enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
if (!need_pass_2 && subseg_text_p (now_seg) && mapstate == MAP_DATA)
frag_align_code (2, 0);
saved_cond = inst.cond;
reset_aarch64_instruction (&inst);
inst.cond = saved_cond;
/* Iterate through all opcode entries with the same mnemonic name. */
do
{
opcode = template->opcode;
DEBUG_TRACE ("opcode %s found", opcode->name);
#ifdef DEBUG_AARCH64
if (debug_dump)
dump_opcode_operands (opcode);
#endif /* DEBUG_AARCH64 */
mapping_state (MAP_INSN);
inst_base = &inst.base;
inst_base->opcode = opcode;
/* Truly conditionally executed instructions, e.g. b.cond. */
if (opcode->flags & F_COND)
{
gas_assert (inst.cond != COND_ALWAYS);
inst_base->cond = get_cond_from_value (inst.cond);
DEBUG_TRACE ("condition found %s", inst_base->cond->names[0]);
}
else if (inst.cond != COND_ALWAYS)
{
/* It shouldn't arrive here, where the assembly looks like a
conditional instruction but the found opcode is unconditional. */
gas_assert (0);
continue;
}
if (parse_operands (p, opcode)
&& programmer_friendly_fixup (&inst)
&& do_encode (inst_base->opcode, &inst.base, &inst_base->value))
{
/* Check that this instruction is supported for this CPU. */
if (!opcode->avariant
|| !AARCH64_CPU_HAS_FEATURE (cpu_variant, *opcode->avariant))
{
as_bad (_("selected processor does not support `%s'"), str);
return;
}
warn_unpredictable_ldst (&inst, str);
if (inst.reloc.type == BFD_RELOC_UNUSED
|| !inst.reloc.need_libopcodes_p)
output_inst (NULL);
else
{
/* If there is relocation generated for the instruction,
store the instruction information for the future fix-up. */
struct aarch64_inst *copy;
gas_assert (inst.reloc.type != BFD_RELOC_UNUSED);
if ((copy = xmalloc (sizeof (struct aarch64_inst))) == NULL)
abort ();
memcpy (copy, &inst.base, sizeof (struct aarch64_inst));
output_inst (copy);
}
return;
}
template = template->next;
if (template != NULL)
{
reset_aarch64_instruction (&inst);
inst.cond = saved_cond;
}
}
while (template != NULL);
/* Issue the error messages if any. */
output_operand_error_report (str);
}
/* Various frobbings of labels and their addresses. */
void
aarch64_start_line_hook (void)
{
last_label_seen = NULL;
}
void
aarch64_frob_label (symbolS * sym)
{
last_label_seen = sym;
dwarf2_emit_label (sym);
}
int
aarch64_data_in_code (void)
{
if (!strncmp (input_line_pointer + 1, "data:", 5))
{
*input_line_pointer = '/';
input_line_pointer += 5;
*input_line_pointer = 0;
return 1;
}
return 0;
}
char *
aarch64_canonicalize_symbol_name (char *name)
{
int len;
if ((len = strlen (name)) > 5 && streq (name + len - 5, "/data"))
*(name + len - 5) = 0;
return name;
}
/* Table of all register names defined by default. The user can
define additional names with .req. Note that all register names
should appear in both upper and lowercase variants. Some registers
also have mixed-case names. */
#define REGDEF(s,n,t) { #s, n, REG_TYPE_##t, TRUE }
#define REGNUM(p,n,t) REGDEF(p##n, n, t)
#define REGSET31(p,t) \
REGNUM(p, 0,t), REGNUM(p, 1,t), REGNUM(p, 2,t), REGNUM(p, 3,t), \
REGNUM(p, 4,t), REGNUM(p, 5,t), REGNUM(p, 6,t), REGNUM(p, 7,t), \
REGNUM(p, 8,t), REGNUM(p, 9,t), REGNUM(p,10,t), REGNUM(p,11,t), \
REGNUM(p,12,t), REGNUM(p,13,t), REGNUM(p,14,t), REGNUM(p,15,t), \
REGNUM(p,16,t), REGNUM(p,17,t), REGNUM(p,18,t), REGNUM(p,19,t), \
REGNUM(p,20,t), REGNUM(p,21,t), REGNUM(p,22,t), REGNUM(p,23,t), \
REGNUM(p,24,t), REGNUM(p,25,t), REGNUM(p,26,t), REGNUM(p,27,t), \
REGNUM(p,28,t), REGNUM(p,29,t), REGNUM(p,30,t)
#define REGSET(p,t) \
REGSET31(p,t), REGNUM(p,31,t)
/* These go into aarch64_reg_hsh hash-table. */
static const reg_entry reg_names[] = {
/* Integer registers. */
REGSET31 (x, R_64), REGSET31 (X, R_64),
REGSET31 (w, R_32), REGSET31 (W, R_32),
REGDEF (wsp, 31, SP_32), REGDEF (WSP, 31, SP_32),
REGDEF (sp, 31, SP_64), REGDEF (SP, 31, SP_64),
REGDEF (wzr, 31, Z_32), REGDEF (WZR, 31, Z_32),
REGDEF (xzr, 31, Z_64), REGDEF (XZR, 31, Z_64),
/* Coprocessor register numbers. */
REGSET (c, CN), REGSET (C, CN),
/* Floating-point single precision registers. */
REGSET (s, FP_S), REGSET (S, FP_S),
/* Floating-point double precision registers. */
REGSET (d, FP_D), REGSET (D, FP_D),
/* Floating-point half precision registers. */
REGSET (h, FP_H), REGSET (H, FP_H),
/* Floating-point byte precision registers. */
REGSET (b, FP_B), REGSET (B, FP_B),
/* Floating-point quad precision registers. */
REGSET (q, FP_Q), REGSET (Q, FP_Q),
/* FP/SIMD registers. */
REGSET (v, VN), REGSET (V, VN),
};
#undef REGDEF
#undef REGNUM
#undef REGSET
#define N 1
#define n 0
#define Z 1
#define z 0
#define C 1
#define c 0
#define V 1
#define v 0
#define B(a,b,c,d) (((a) << 3) | ((b) << 2) | ((c) << 1) | (d))
static const asm_nzcv nzcv_names[] = {
{"nzcv", B (n, z, c, v)},
{"nzcV", B (n, z, c, V)},
{"nzCv", B (n, z, C, v)},
{"nzCV", B (n, z, C, V)},
{"nZcv", B (n, Z, c, v)},
{"nZcV", B (n, Z, c, V)},
{"nZCv", B (n, Z, C, v)},
{"nZCV", B (n, Z, C, V)},
{"Nzcv", B (N, z, c, v)},
{"NzcV", B (N, z, c, V)},
{"NzCv", B (N, z, C, v)},
{"NzCV", B (N, z, C, V)},
{"NZcv", B (N, Z, c, v)},
{"NZcV", B (N, Z, c, V)},
{"NZCv", B (N, Z, C, v)},
{"NZCV", B (N, Z, C, V)}
};
#undef N
#undef n
#undef Z
#undef z
#undef C
#undef c
#undef V
#undef v
#undef B
/* MD interface: bits in the object file. */
/* Turn an integer of n bytes (in val) into a stream of bytes appropriate
for use in the a.out file, and stores them in the array pointed to by buf.
This knows about the endian-ness of the target machine and does
THE RIGHT THING, whatever it is. Possible values for n are 1 (byte)
2 (short) and 4 (long) Floating numbers are put out as a series of
LITTLENUMS (shorts, here at least). */
void
md_number_to_chars (char *buf, valueT val, int n)
{
if (target_big_endian)
number_to_chars_bigendian (buf, val, n);
else
number_to_chars_littleendian (buf, val, n);
}
/* MD interface: Sections. */
/* Estimate the size of a frag before relaxing. Assume everything fits in
4 bytes. */
int
md_estimate_size_before_relax (fragS * fragp, segT segtype ATTRIBUTE_UNUSED)
{
fragp->fr_var = 4;
return 4;
}
/* Round up a section size to the appropriate boundary. */
valueT
md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
{
return size;
}
/* This is called from HANDLE_ALIGN in write.c. Fill in the contents
of an rs_align_code fragment.
Here we fill the frag with the appropriate info for padding the
output stream. The resulting frag will consist of a fixed (fr_fix)
and of a repeating (fr_var) part.
The fixed content is always emitted before the repeating content and
these two parts are used as follows in constructing the output:
- the fixed part will be used to align to a valid instruction word
boundary, in case that we start at a misaligned address; as no
executable instruction can live at the misaligned location, we
simply fill with zeros;
- the variable part will be used to cover the remaining padding and
we fill using the AArch64 NOP instruction.
Note that the size of a RS_ALIGN_CODE fragment is always 7 to provide
enough storage space for up to 3 bytes for padding the back to a valid
instruction alignment and exactly 4 bytes to store the NOP pattern. */
void
aarch64_handle_align (fragS * fragP)
{
/* NOP = d503201f */
/* AArch64 instructions are always little-endian. */
static char const aarch64_noop[4] = { 0x1f, 0x20, 0x03, 0xd5 };
int bytes, fix, noop_size;
char *p;
if (fragP->fr_type != rs_align_code)
return;
bytes = fragP->fr_next->fr_address - fragP->fr_address - fragP->fr_fix;
p = fragP->fr_literal + fragP->fr_fix;
#ifdef OBJ_ELF
gas_assert (fragP->tc_frag_data.recorded);
#endif
noop_size = sizeof (aarch64_noop);
fix = bytes & (noop_size - 1);
if (fix)
{
#ifdef OBJ_ELF
insert_data_mapping_symbol (MAP_INSN, fragP->fr_fix, fragP, fix);
#endif
memset (p, 0, fix);
p += fix;
fragP->fr_fix += fix;
}
if (noop_size)
memcpy (p, aarch64_noop, noop_size);
fragP->fr_var = noop_size;
}
/* Perform target specific initialisation of a frag.
Note - despite the name this initialisation is not done when the frag
is created, but only when its type is assigned. A frag can be created
and used a long time before its type is set, so beware of assuming that
this initialisationis performed first. */
#ifndef OBJ_ELF
void
aarch64_init_frag (fragS * fragP ATTRIBUTE_UNUSED,
int max_chars ATTRIBUTE_UNUSED)
{
}
#else /* OBJ_ELF is defined. */
void
aarch64_init_frag (fragS * fragP, int max_chars)
{
/* Record a mapping symbol for alignment frags. We will delete this
later if the alignment ends up empty. */
if (!fragP->tc_frag_data.recorded)
fragP->tc_frag_data.recorded = 1;
switch (fragP->fr_type)
{
case rs_align:
case rs_align_test:
case rs_fill:
mapping_state_2 (MAP_DATA, max_chars);
break;
case rs_align_code:
mapping_state_2 (MAP_INSN, max_chars);
break;
default:
break;
}
}
/* Initialize the DWARF-2 unwind information for this procedure. */
void
tc_aarch64_frame_initial_instructions (void)
{
cfi_add_CFA_def_cfa (REG_SP, 0);
}
#endif /* OBJ_ELF */
/* Convert REGNAME to a DWARF-2 register number. */
int
tc_aarch64_regname_to_dw2regnum (char *regname)
{
const reg_entry *reg = parse_reg (®name);
if (reg == NULL)
return -1;
switch (reg->type)
{
case REG_TYPE_SP_32:
case REG_TYPE_SP_64:
case REG_TYPE_R_32:
case REG_TYPE_R_64:
return reg->number;
case REG_TYPE_FP_B:
case REG_TYPE_FP_H:
case REG_TYPE_FP_S:
case REG_TYPE_FP_D:
case REG_TYPE_FP_Q:
return reg->number + 64;
default:
break;
}
return -1;
}
/* Implement DWARF2_ADDR_SIZE. */
int
aarch64_dwarf2_addr_size (void)
{
#if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
if (ilp32_p)
return 4;
#endif
return bfd_arch_bits_per_address (stdoutput) / 8;
}
/* MD interface: Symbol and relocation handling. */
/* Return the address within the segment that a PC-relative fixup is
relative to. For AArch64 PC-relative fixups applied to instructions
are generally relative to the location plus AARCH64_PCREL_OFFSET bytes. */
long
md_pcrel_from_section (fixS * fixP, segT seg)
{
offsetT base = fixP->fx_where + fixP->fx_frag->fr_address;
/* If this is pc-relative and we are going to emit a relocation
then we just want to put out any pipeline compensation that the linker
will need. Otherwise we want to use the calculated base. */
if (fixP->fx_pcrel
&& ((fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != seg)
|| aarch64_force_relocation (fixP)))
base = 0;
/* AArch64 should be consistent for all pc-relative relocations. */
return base + AARCH64_PCREL_OFFSET;
}
/* Under ELF we need to default _GLOBAL_OFFSET_TABLE.
Otherwise we have no need to default values of symbols. */
symbolS *
md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
{
#ifdef OBJ_ELF
if (name[0] == '_' && name[1] == 'G'
&& streq (name, GLOBAL_OFFSET_TABLE_NAME))
{
if (!GOT_symbol)
{
if (symbol_find (name))
as_bad (_("GOT already in the symbol table"));
GOT_symbol = symbol_new (name, undefined_section,
(valueT) 0, &zero_address_frag);
}
return GOT_symbol;
}
#endif
return 0;
}
/* Return non-zero if the indicated VALUE has overflowed the maximum
range expressible by a unsigned number with the indicated number of
BITS. */
static bfd_boolean
unsigned_overflow (valueT value, unsigned bits)
{
valueT lim;
if (bits >= sizeof (valueT) * 8)
return FALSE;
lim = (valueT) 1 << bits;
return (value >= lim);
}
/* Return non-zero if the indicated VALUE has overflowed the maximum
range expressible by an signed number with the indicated number of
BITS. */
static bfd_boolean
signed_overflow (offsetT value, unsigned bits)
{
offsetT lim;
if (bits >= sizeof (offsetT) * 8)
return FALSE;
lim = (offsetT) 1 << (bits - 1);
return (value < -lim || value >= lim);
}
/* Given an instruction in *INST, which is expected to be a scaled, 12-bit,
unsigned immediate offset load/store instruction, try to encode it as
an unscaled, 9-bit, signed immediate offset load/store instruction.
Return TRUE if it is successful; otherwise return FALSE.
As a programmer-friendly assembler, LDUR/STUR instructions can be generated
in response to the standard LDR/STR mnemonics when the immediate offset is
unambiguous, i.e. when it is negative or unaligned. */
static bfd_boolean
try_to_encode_as_unscaled_ldst (aarch64_inst *instr)
{
int idx;
enum aarch64_op new_op;
const aarch64_opcode *new_opcode;
gas_assert (instr->opcode->iclass == ldst_pos);
switch (instr->opcode->op)
{
case OP_LDRB_POS:new_op = OP_LDURB; break;
case OP_STRB_POS: new_op = OP_STURB; break;
case OP_LDRSB_POS: new_op = OP_LDURSB; break;
case OP_LDRH_POS: new_op = OP_LDURH; break;
case OP_STRH_POS: new_op = OP_STURH; break;
case OP_LDRSH_POS: new_op = OP_LDURSH; break;
case OP_LDR_POS: new_op = OP_LDUR; break;
case OP_STR_POS: new_op = OP_STUR; break;
case OP_LDRF_POS: new_op = OP_LDURV; break;
case OP_STRF_POS: new_op = OP_STURV; break;
case OP_LDRSW_POS: new_op = OP_LDURSW; break;
case OP_PRFM_POS: new_op = OP_PRFUM; break;
default: new_op = OP_NIL; break;
}
if (new_op == OP_NIL)
return FALSE;
new_opcode = aarch64_get_opcode (new_op);
gas_assert (new_opcode != NULL);
DEBUG_TRACE ("Check programmer-friendly STURB/LDURB -> STRB/LDRB: %d == %d",
instr->opcode->op, new_opcode->op);
aarch64_replace_opcode (instr, new_opcode);
/* Clear up the ADDR_SIMM9's qualifier; otherwise the
qualifier matching may fail because the out-of-date qualifier will
prevent the operand being updated with a new and correct qualifier. */
idx = aarch64_operand_index (instr->opcode->operands,
AARCH64_OPND_ADDR_SIMM9);
gas_assert (idx == 1);
instr->operands[idx].qualifier = AARCH64_OPND_QLF_NIL;
DEBUG_TRACE ("Found LDURB entry to encode programmer-friendly LDRB");
if (!aarch64_opcode_encode (instr->opcode, instr, &instr->value, NULL, NULL))
return FALSE;
return TRUE;
}
/* Called by fix_insn to fix a MOV immediate alias instruction.
Operand for a generic move immediate instruction, which is an alias
instruction that generates a single MOVZ, MOVN or ORR instruction to loads
a 32-bit/64-bit immediate value into general register. An assembler error
shall result if the immediate cannot be created by a single one of these
instructions. If there is a choice, then to ensure reversability an
assembler must prefer a MOVZ to MOVN, and MOVZ or MOVN to ORR. */
static void
fix_mov_imm_insn (fixS *fixP, char *buf, aarch64_inst *instr, offsetT value)
{
const aarch64_opcode *opcode;
/* Need to check if the destination is SP/ZR. The check has to be done
before any aarch64_replace_opcode. */
int try_mov_wide_p = !aarch64_stack_pointer_p (&instr->operands[0]);
int try_mov_bitmask_p = !aarch64_zero_register_p (&instr->operands[0]);
instr->operands[1].imm.value = value;
instr->operands[1].skip = 0;
if (try_mov_wide_p)
{
/* Try the MOVZ alias. */
opcode = aarch64_get_opcode (OP_MOV_IMM_WIDE);
aarch64_replace_opcode (instr, opcode);
if (aarch64_opcode_encode (instr->opcode, instr,
&instr->value, NULL, NULL))
{
put_aarch64_insn (buf, instr->value);
return;
}
/* Try the MOVK alias. */
opcode = aarch64_get_opcode (OP_MOV_IMM_WIDEN);
aarch64_replace_opcode (instr, opcode);
if (aarch64_opcode_encode (instr->opcode, instr,
&instr->value, NULL, NULL))
{
put_aarch64_insn (buf, instr->value);
return;
}
}
if (try_mov_bitmask_p)
{
/* Try the ORR alias. */
opcode = aarch64_get_opcode (OP_MOV_IMM_LOG);
aarch64_replace_opcode (instr, opcode);
if (aarch64_opcode_encode (instr->opcode, instr,
&instr->value, NULL, NULL))
{
put_aarch64_insn (buf, instr->value);
return;
}
}
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate cannot be moved by a single instruction"));
}
/* An instruction operand which is immediate related may have symbol used
in the assembly, e.g.
mov w0, u32
.set u32, 0x00ffff00
At the time when the assembly instruction is parsed, a referenced symbol,
like 'u32' in the above example may not have been seen; a fixS is created
in such a case and is handled here after symbols have been resolved.
Instruction is fixed up with VALUE using the information in *FIXP plus
extra information in FLAGS.
This function is called by md_apply_fix to fix up instructions that need
a fix-up described above but does not involve any linker-time relocation. */
static void
fix_insn (fixS *fixP, uint32_t flags, offsetT value)
{
int idx;
uint32_t insn;
char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
enum aarch64_opnd opnd = fixP->tc_fix_data.opnd;
aarch64_inst *new_inst = fixP->tc_fix_data.inst;
if (new_inst)
{
/* Now the instruction is about to be fixed-up, so the operand that
was previously marked as 'ignored' needs to be unmarked in order
to get the encoding done properly. */
idx = aarch64_operand_index (new_inst->opcode->operands, opnd);
new_inst->operands[idx].skip = 0;
}
gas_assert (opnd != AARCH64_OPND_NIL);
switch (opnd)
{
case AARCH64_OPND_EXCEPTION:
if (unsigned_overflow (value, 16))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_svc_imm (value);
put_aarch64_insn (buf, insn);
break;
case AARCH64_OPND_AIMM:
/* ADD or SUB with immediate.
NOTE this assumes we come here with a add/sub shifted reg encoding
3 322|2222|2 2 2 21111 111111
1 098|7654|3 2 1 09876 543210 98765 43210
0b000000 sf 000|1011|shift 0 Rm imm6 Rn Rd ADD
2b000000 sf 010|1011|shift 0 Rm imm6 Rn Rd ADDS
4b000000 sf 100|1011|shift 0 Rm imm6 Rn Rd SUB
6b000000 sf 110|1011|shift 0 Rm imm6 Rn Rd SUBS
->
3 322|2222|2 2 221111111111
1 098|7654|3 2 109876543210 98765 43210
11000000 sf 001|0001|shift imm12 Rn Rd ADD
31000000 sf 011|0001|shift imm12 Rn Rd ADDS
51000000 sf 101|0001|shift imm12 Rn Rd SUB
71000000 sf 111|0001|shift imm12 Rn Rd SUBS
Fields sf Rn Rd are already set. */
insn = get_aarch64_insn (buf);
if (value < 0)
{
/* Add <-> sub. */
insn = reencode_addsub_switch_add_sub (insn);
value = -value;
}
if ((flags & FIXUP_F_HAS_EXPLICIT_SHIFT) == 0
&& unsigned_overflow (value, 12))
{
/* Try to shift the value by 12 to make it fit. */
if (((value >> 12) << 12) == value
&& ! unsigned_overflow (value, 12 + 12))
{
value >>= 12;
insn |= encode_addsub_imm_shift_amount (1);
}
}
if (unsigned_overflow (value, 12))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate out of range"));
insn |= encode_addsub_imm (value);
put_aarch64_insn (buf, insn);
break;
case AARCH64_OPND_SIMD_IMM:
case AARCH64_OPND_SIMD_IMM_SFT:
case AARCH64_OPND_LIMM:
/* Bit mask immediate. */
gas_assert (new_inst != NULL);
idx = aarch64_operand_index (new_inst->opcode->operands, opnd);
new_inst->operands[idx].imm.value = value;
if (aarch64_opcode_encode (new_inst->opcode, new_inst,
&new_inst->value, NULL, NULL))
put_aarch64_insn (buf, new_inst->value);
else
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid immediate"));
break;
case AARCH64_OPND_HALF:
/* 16-bit unsigned immediate. */
if (unsigned_overflow (value, 16))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_movw_imm (value & 0xffff);
put_aarch64_insn (buf, insn);
break;
case AARCH64_OPND_IMM_MOV:
/* Operand for a generic move immediate instruction, which is
an alias instruction that generates a single MOVZ, MOVN or ORR
instruction to loads a 32-bit/64-bit immediate value into general
register. An assembler error shall result if the immediate cannot be
created by a single one of these instructions. If there is a choice,
then to ensure reversability an assembler must prefer a MOVZ to MOVN,
and MOVZ or MOVN to ORR. */
gas_assert (new_inst != NULL);
fix_mov_imm_insn (fixP, buf, new_inst, value);
break;
case AARCH64_OPND_ADDR_SIMM7:
case AARCH64_OPND_ADDR_SIMM9:
case AARCH64_OPND_ADDR_SIMM9_2:
case AARCH64_OPND_ADDR_UIMM12:
/* Immediate offset in an address. */
insn = get_aarch64_insn (buf);
gas_assert (new_inst != NULL && new_inst->value == insn);
gas_assert (new_inst->opcode->operands[1] == opnd
|| new_inst->opcode->operands[2] == opnd);
/* Get the index of the address operand. */
if (new_inst->opcode->operands[1] == opnd)
/* e.g. STR <Xt>, [<Xn|SP>, <R><m>{, <extend> {<amount>}}]. */
idx = 1;
else
/* e.g. LDP <Qt1>, <Qt2>, [<Xn|SP>{, #<imm>}]. */
idx = 2;
/* Update the resolved offset value. */
new_inst->operands[idx].addr.offset.imm = value;
/* Encode/fix-up. */
if (aarch64_opcode_encode (new_inst->opcode, new_inst,
&new_inst->value, NULL, NULL))
{
put_aarch64_insn (buf, new_inst->value);
break;
}
else if (new_inst->opcode->iclass == ldst_pos
&& try_to_encode_as_unscaled_ldst (new_inst))
{
put_aarch64_insn (buf, new_inst->value);
break;
}
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate offset out of range"));
break;
default:
gas_assert (0);
as_fatal (_("unhandled operand code %d"), opnd);
}
}
/* Apply a fixup (fixP) to segment data, once it has been determined
by our caller that we have all the info we need to fix it up.
Parameter valP is the pointer to the value of the bits. */
void
md_apply_fix (fixS * fixP, valueT * valP, segT seg)
{
offsetT value = *valP;
uint32_t insn;
char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
int scale;
unsigned flags = fixP->fx_addnumber;
DEBUG_TRACE ("\n\n");
DEBUG_TRACE ("~~~~~~~~~~~~~~~~~~~~~~~~~");
DEBUG_TRACE ("Enter md_apply_fix");
gas_assert (fixP->fx_r_type <= BFD_RELOC_UNUSED);
/* Note whether this will delete the relocation. */
if (fixP->fx_addsy == 0 && !fixP->fx_pcrel)
fixP->fx_done = 1;
/* Process the relocations. */
switch (fixP->fx_r_type)
{
case BFD_RELOC_NONE:
/* This will need to go in the object file. */
fixP->fx_done = 0;
break;
case BFD_RELOC_8:
case BFD_RELOC_8_PCREL:
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, value, 1);
break;
case BFD_RELOC_16:
case BFD_RELOC_16_PCREL:
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, value, 2);
break;
case BFD_RELOC_32:
case BFD_RELOC_32_PCREL:
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, value, 4);
break;
case BFD_RELOC_64:
case BFD_RELOC_64_PCREL:
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, value, 8);
break;
case BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP:
/* We claim that these fixups have been processed here, even if
in fact we generate an error because we do not have a reloc
for them, so tc_gen_reloc() will reject them. */
fixP->fx_done = 1;
if (fixP->fx_addsy && !S_IS_DEFINED (fixP->fx_addsy))
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("undefined symbol %s used as an immediate value"),
S_GET_NAME (fixP->fx_addsy));
goto apply_fix_return;
}
fix_insn (fixP, flags, value);
break;
case BFD_RELOC_AARCH64_LD_LO19_PCREL:
if (fixP->fx_done || !seg->use_rela_p)
{
if (value & 3)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("pc-relative load offset not word aligned"));
if (signed_overflow (value, 21))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("pc-relative load offset out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_ld_lit_ofs_19 (value >> 2);
put_aarch64_insn (buf, insn);
}
break;
case BFD_RELOC_AARCH64_ADR_LO21_PCREL:
if (fixP->fx_done || !seg->use_rela_p)
{
if (signed_overflow (value, 21))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("pc-relative address offset out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_adr_imm (value);
put_aarch64_insn (buf, insn);
}
break;
case BFD_RELOC_AARCH64_BRANCH19:
if (fixP->fx_done || !seg->use_rela_p)
{
if (value & 3)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("conditional branch target not word aligned"));
if (signed_overflow (value, 21))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("conditional branch out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_cond_branch_ofs_19 (value >> 2);
put_aarch64_insn (buf, insn);
}
break;
case BFD_RELOC_AARCH64_TSTBR14:
if (fixP->fx_done || !seg->use_rela_p)
{
if (value & 3)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("conditional branch target not word aligned"));
if (signed_overflow (value, 16))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("conditional branch out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_tst_branch_ofs_14 (value >> 2);
put_aarch64_insn (buf, insn);
}
break;
case BFD_RELOC_AARCH64_CALL26:
case BFD_RELOC_AARCH64_JUMP26:
if (fixP->fx_done || !seg->use_rela_p)
{
if (value & 3)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("branch target not word aligned"));
if (signed_overflow (value, 28))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("branch out of range"));
insn = get_aarch64_insn (buf);
insn |= encode_branch_ofs_26 (value >> 2);
put_aarch64_insn (buf, insn);
}
break;
case BFD_RELOC_AARCH64_MOVW_G0:
case BFD_RELOC_AARCH64_MOVW_G0_NC:
case BFD_RELOC_AARCH64_MOVW_G0_S:
case BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC:
scale = 0;
goto movw_common;
case BFD_RELOC_AARCH64_MOVW_G1:
case BFD_RELOC_AARCH64_MOVW_G1_NC:
case BFD_RELOC_AARCH64_MOVW_G1_S:
case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
scale = 16;
goto movw_common;
case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
scale = 0;
S_SET_THREAD_LOCAL (fixP->fx_addsy);
/* Should always be exported to object file, see
aarch64_force_relocation(). */
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
goto movw_common;
case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
scale = 16;
S_SET_THREAD_LOCAL (fixP->fx_addsy);
/* Should always be exported to object file, see
aarch64_force_relocation(). */
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
goto movw_common;
case BFD_RELOC_AARCH64_MOVW_G2:
case BFD_RELOC_AARCH64_MOVW_G2_NC:
case BFD_RELOC_AARCH64_MOVW_G2_S:
scale = 32;
goto movw_common;
case BFD_RELOC_AARCH64_MOVW_G3:
scale = 48;
movw_common:
if (fixP->fx_done || !seg->use_rela_p)
{
insn = get_aarch64_insn (buf);
if (!fixP->fx_done)
{
/* REL signed addend must fit in 16 bits */
if (signed_overflow (value, 16))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
}
else
{
/* Check for overflow and scale. */
switch (fixP->fx_r_type)
{
case BFD_RELOC_AARCH64_MOVW_G0:
case BFD_RELOC_AARCH64_MOVW_G1:
case BFD_RELOC_AARCH64_MOVW_G2:
case BFD_RELOC_AARCH64_MOVW_G3:
case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
if (unsigned_overflow (value, scale + 16))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("unsigned value out of range"));
break;
case BFD_RELOC_AARCH64_MOVW_G0_S:
case BFD_RELOC_AARCH64_MOVW_G1_S:
case BFD_RELOC_AARCH64_MOVW_G2_S:
/* NOTE: We can only come here with movz or movn. */
if (signed_overflow (value, scale + 16))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("signed value out of range"));
if (value < 0)
{
/* Force use of MOVN. */
value = ~value;
insn = reencode_movzn_to_movn (insn);
}
else
{
/* Force use of MOVZ. */
insn = reencode_movzn_to_movz (insn);
}
break;
default:
/* Unchecked relocations. */
break;
}
value >>= scale;
}
/* Insert value into MOVN/MOVZ/MOVK instruction. */
insn |= encode_movw_imm (value & 0xffff);
put_aarch64_insn (buf, insn);
}
break;
case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC:
fixP->fx_r_type = (ilp32_p
? BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC
: BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC);
S_SET_THREAD_LOCAL (fixP->fx_addsy);
/* Should always be exported to object file, see
aarch64_force_relocation(). */
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
break;
case BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC:
fixP->fx_r_type = (ilp32_p
? BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC
: BFD_RELOC_AARCH64_TLSDESC_LD64_LO12_NC);
S_SET_THREAD_LOCAL (fixP->fx_addsy);
/* Should always be exported to object file, see
aarch64_force_relocation(). */
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
break;
case BFD_RELOC_AARCH64_TLSDESC_ADD_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21:
case BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21:
case BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_LD64_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_LD_PREL19:
case BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC:
case BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21:
case BFD_RELOC_AARCH64_TLSGD_ADR_PREL21:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
case BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
case BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12:
case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21:
case BFD_RELOC_AARCH64_TLSLD_ADR_PREL21:
case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12:
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
S_SET_THREAD_LOCAL (fixP->fx_addsy);
/* Should always be exported to object file, see
aarch64_force_relocation(). */
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
break;
case BFD_RELOC_AARCH64_LD_GOT_LO12_NC:
/* Should always be exported to object file, see
aarch64_force_relocation(). */
fixP->fx_r_type = (ilp32_p
? BFD_RELOC_AARCH64_LD32_GOT_LO12_NC
: BFD_RELOC_AARCH64_LD64_GOT_LO12_NC);
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
break;
case BFD_RELOC_AARCH64_ADD_LO12:
case BFD_RELOC_AARCH64_ADR_GOT_PAGE:
case BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL:
case BFD_RELOC_AARCH64_ADR_HI21_PCREL:
case BFD_RELOC_AARCH64_GOT_LD_PREL19:
case BFD_RELOC_AARCH64_LD32_GOT_LO12_NC:
case BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14:
case BFD_RELOC_AARCH64_LD64_GOTOFF_LO15:
case BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15:
case BFD_RELOC_AARCH64_LD64_GOT_LO12_NC:
case BFD_RELOC_AARCH64_LDST128_LO12:
case BFD_RELOC_AARCH64_LDST16_LO12:
case BFD_RELOC_AARCH64_LDST32_LO12:
case BFD_RELOC_AARCH64_LDST64_LO12:
case BFD_RELOC_AARCH64_LDST8_LO12:
/* Should always be exported to object file, see
aarch64_force_relocation(). */
gas_assert (!fixP->fx_done);
gas_assert (seg->use_rela_p);
break;
case BFD_RELOC_AARCH64_TLSDESC_ADD:
case BFD_RELOC_AARCH64_TLSDESC_CALL:
case BFD_RELOC_AARCH64_TLSDESC_LDR:
break;
case BFD_RELOC_UNUSED:
/* An error will already have been reported. */
break;
default:
as_bad_where (fixP->fx_file, fixP->fx_line,
_("unexpected %s fixup"),
bfd_get_reloc_code_name (fixP->fx_r_type));
break;
}
apply_fix_return:
/* Free the allocated the struct aarch64_inst.
N.B. currently there are very limited number of fix-up types actually use
this field, so the impact on the performance should be minimal . */
if (fixP->tc_fix_data.inst != NULL)
free (fixP->tc_fix_data.inst);
return;
}
/* Translate internal representation of relocation info to BFD target
format. */
arelent *
tc_gen_reloc (asection * section, fixS * fixp)
{
arelent *reloc;
bfd_reloc_code_real_type code;
reloc = xmalloc (sizeof (arelent));
reloc->sym_ptr_ptr = xmalloc (sizeof (asymbol *));
*reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
if (fixp->fx_pcrel)
{
if (section->use_rela_p)
fixp->fx_offset -= md_pcrel_from_section (fixp, section);
else
fixp->fx_offset = reloc->address;
}
reloc->addend = fixp->fx_offset;
code = fixp->fx_r_type;
switch (code)
{
case BFD_RELOC_16:
if (fixp->fx_pcrel)
code = BFD_RELOC_16_PCREL;
break;
case BFD_RELOC_32:
if (fixp->fx_pcrel)
code = BFD_RELOC_32_PCREL;
break;
case BFD_RELOC_64:
if (fixp->fx_pcrel)
code = BFD_RELOC_64_PCREL;
break;
default:
break;
}
reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
if (reloc->howto == NULL)
{
as_bad_where (fixp->fx_file, fixp->fx_line,
_
("cannot represent %s relocation in this object file format"),
bfd_get_reloc_code_name (code));
return NULL;
}
return reloc;
}
/* This fix_new is called by cons via TC_CONS_FIX_NEW. */
void
cons_fix_new_aarch64 (fragS * frag, int where, int size, expressionS * exp)
{
bfd_reloc_code_real_type type;
int pcrel = 0;
/* Pick a reloc.
FIXME: @@ Should look at CPU word size. */
switch (size)
{
case 1:
type = BFD_RELOC_8;
break;
case 2:
type = BFD_RELOC_16;
break;
case 4:
type = BFD_RELOC_32;
break;
case 8:
type = BFD_RELOC_64;
break;
default:
as_bad (_("cannot do %u-byte relocation"), size);
type = BFD_RELOC_UNUSED;
break;
}
fix_new_exp (frag, where, (int) size, exp, pcrel, type);
}
int
aarch64_force_relocation (struct fix *fixp)
{
switch (fixp->fx_r_type)
{
case BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP:
/* Perform these "immediate" internal relocations
even if the symbol is extern or weak. */
return 0;
case BFD_RELOC_AARCH64_LD_GOT_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC:
case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC:
/* Pseudo relocs that need to be fixed up according to
ilp32_p. */
return 0;
case BFD_RELOC_AARCH64_ADD_LO12:
case BFD_RELOC_AARCH64_ADR_GOT_PAGE:
case BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL:
case BFD_RELOC_AARCH64_ADR_HI21_PCREL:
case BFD_RELOC_AARCH64_GOT_LD_PREL19:
case BFD_RELOC_AARCH64_LD32_GOT_LO12_NC:
case BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14:
case BFD_RELOC_AARCH64_LD64_GOTOFF_LO15:
case BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15:
case BFD_RELOC_AARCH64_LD64_GOT_LO12_NC:
case BFD_RELOC_AARCH64_LDST128_LO12:
case BFD_RELOC_AARCH64_LDST16_LO12:
case BFD_RELOC_AARCH64_LDST32_LO12:
case BFD_RELOC_AARCH64_LDST64_LO12:
case BFD_RELOC_AARCH64_LDST8_LO12:
case BFD_RELOC_AARCH64_TLSDESC_ADD_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21:
case BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21:
case BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_LD64_LO12_NC:
case BFD_RELOC_AARCH64_TLSDESC_LD_PREL19:
case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
case BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC:
case BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21:
case BFD_RELOC_AARCH64_TLSGD_ADR_PREL21:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
case BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
case BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12:
case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21:
case BFD_RELOC_AARCH64_TLSLD_ADR_PREL21:
case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12:
case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12:
case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
/* Always leave these relocations for the linker. */
return 1;
default:
break;
}
return generic_force_reloc (fixp);
}
#ifdef OBJ_ELF
const char *
elf64_aarch64_target_format (void)
{
if (strcmp (TARGET_OS, "cloudabi") == 0)
{
/* FIXME: What to do for ilp32_p ? */
return target_big_endian ? "elf64-bigaarch64-cloudabi" : "elf64-littleaarch64-cloudabi";
}
if (target_big_endian)
return ilp32_p ? "elf32-bigaarch64" : "elf64-bigaarch64";
else
return ilp32_p ? "elf32-littleaarch64" : "elf64-littleaarch64";
}
void
aarch64elf_frob_symbol (symbolS * symp, int *puntp)
{
elf_frob_symbol (symp, puntp);
}
#endif
/* MD interface: Finalization. */
/* A good place to do this, although this was probably not intended
for this kind of use. We need to dump the literal pool before
references are made to a null symbol pointer. */
void
aarch64_cleanup (void)
{
literal_pool *pool;
for (pool = list_of_pools; pool; pool = pool->next)
{
/* Put it at the end of the relevant section. */
subseg_set (pool->section, pool->sub_section);
s_ltorg (0);
}
}
#ifdef OBJ_ELF
/* Remove any excess mapping symbols generated for alignment frags in
SEC. We may have created a mapping symbol before a zero byte
alignment; remove it if there's a mapping symbol after the
alignment. */
static void
check_mapping_symbols (bfd * abfd ATTRIBUTE_UNUSED, asection * sec,
void *dummy ATTRIBUTE_UNUSED)
{
segment_info_type *seginfo = seg_info (sec);
fragS *fragp;
if (seginfo == NULL || seginfo->frchainP == NULL)
return;
for (fragp = seginfo->frchainP->frch_root;
fragp != NULL; fragp = fragp->fr_next)
{
symbolS *sym = fragp->tc_frag_data.last_map;
fragS *next = fragp->fr_next;
/* Variable-sized frags have been converted to fixed size by
this point. But if this was variable-sized to start with,
there will be a fixed-size frag after it. So don't handle
next == NULL. */
if (sym == NULL || next == NULL)
continue;
if (S_GET_VALUE (sym) < next->fr_address)
/* Not at the end of this frag. */
continue;
know (S_GET_VALUE (sym) == next->fr_address);
do
{
if (next->tc_frag_data.first_map != NULL)
{
/* Next frag starts with a mapping symbol. Discard this
one. */
symbol_remove (sym, &symbol_rootP, &symbol_lastP);
break;
}
if (next->fr_next == NULL)
{
/* This mapping symbol is at the end of the section. Discard
it. */
know (next->fr_fix == 0 && next->fr_var == 0);
symbol_remove (sym, &symbol_rootP, &symbol_lastP);
break;
}
/* As long as we have empty frags without any mapping symbols,
keep looking. */
/* If the next frag is non-empty and does not start with a
mapping symbol, then this mapping symbol is required. */
if (next->fr_address != next->fr_next->fr_address)
break;
next = next->fr_next;
}
while (next != NULL);
}
}
#endif
/* Adjust the symbol table. */
void
aarch64_adjust_symtab (void)
{
#ifdef OBJ_ELF
/* Remove any overlapping mapping symbols generated by alignment frags. */
bfd_map_over_sections (stdoutput, check_mapping_symbols, (char *) 0);
/* Now do generic ELF adjustments. */
elf_adjust_symtab ();
#endif
}
static void
checked_hash_insert (struct hash_control *table, const char *key, void *value)
{
const char *hash_err;
hash_err = hash_insert (table, key, value);
if (hash_err)
printf ("Internal Error: Can't hash %s\n", key);
}
static void
fill_instruction_hash_table (void)
{
aarch64_opcode *opcode = aarch64_opcode_table;
while (opcode->name != NULL)
{
templates *templ, *new_templ;
templ = hash_find (aarch64_ops_hsh, opcode->name);
new_templ = (templates *) xmalloc (sizeof (templates));
new_templ->opcode = opcode;
new_templ->next = NULL;
if (!templ)
checked_hash_insert (aarch64_ops_hsh, opcode->name, (void *) new_templ);
else
{
new_templ->next = templ->next;
templ->next = new_templ;
}
++opcode;
}
}
static inline void
convert_to_upper (char *dst, const char *src, size_t num)
{
unsigned int i;
for (i = 0; i < num && *src != '\0'; ++i, ++dst, ++src)
*dst = TOUPPER (*src);
*dst = '\0';
}
/* Assume STR point to a lower-case string, allocate, convert and return
the corresponding upper-case string. */
static inline const char*
get_upper_str (const char *str)
{
char *ret;
size_t len = strlen (str);
if ((ret = xmalloc (len + 1)) == NULL)
abort ();
convert_to_upper (ret, str, len);
return ret;
}
/* MD interface: Initialization. */
void
md_begin (void)
{
unsigned mach;
unsigned int i;
if ((aarch64_ops_hsh = hash_new ()) == NULL
|| (aarch64_cond_hsh = hash_new ()) == NULL
|| (aarch64_shift_hsh = hash_new ()) == NULL
|| (aarch64_sys_regs_hsh = hash_new ()) == NULL
|| (aarch64_pstatefield_hsh = hash_new ()) == NULL
|| (aarch64_sys_regs_ic_hsh = hash_new ()) == NULL
|| (aarch64_sys_regs_dc_hsh = hash_new ()) == NULL
|| (aarch64_sys_regs_at_hsh = hash_new ()) == NULL
|| (aarch64_sys_regs_tlbi_hsh = hash_new ()) == NULL
|| (aarch64_reg_hsh = hash_new ()) == NULL
|| (aarch64_barrier_opt_hsh = hash_new ()) == NULL
|| (aarch64_nzcv_hsh = hash_new ()) == NULL
|| (aarch64_pldop_hsh = hash_new ()) == NULL
|| (aarch64_hint_opt_hsh = hash_new ()) == NULL)
as_fatal (_("virtual memory exhausted"));
fill_instruction_hash_table ();
for (i = 0; aarch64_sys_regs[i].name != NULL; ++i)
checked_hash_insert (aarch64_sys_regs_hsh, aarch64_sys_regs[i].name,
(void *) (aarch64_sys_regs + i));
for (i = 0; aarch64_pstatefields[i].name != NULL; ++i)
checked_hash_insert (aarch64_pstatefield_hsh,
aarch64_pstatefields[i].name,
(void *) (aarch64_pstatefields + i));
for (i = 0; aarch64_sys_regs_ic[i].name != NULL; i++)
checked_hash_insert (aarch64_sys_regs_ic_hsh,
aarch64_sys_regs_ic[i].name,
(void *) (aarch64_sys_regs_ic + i));
for (i = 0; aarch64_sys_regs_dc[i].name != NULL; i++)
checked_hash_insert (aarch64_sys_regs_dc_hsh,
aarch64_sys_regs_dc[i].name,
(void *) (aarch64_sys_regs_dc + i));
for (i = 0; aarch64_sys_regs_at[i].name != NULL; i++)
checked_hash_insert (aarch64_sys_regs_at_hsh,
aarch64_sys_regs_at[i].name,
(void *) (aarch64_sys_regs_at + i));
for (i = 0; aarch64_sys_regs_tlbi[i].name != NULL; i++)
checked_hash_insert (aarch64_sys_regs_tlbi_hsh,
aarch64_sys_regs_tlbi[i].name,
(void *) (aarch64_sys_regs_tlbi + i));
for (i = 0; i < ARRAY_SIZE (reg_names); i++)
checked_hash_insert (aarch64_reg_hsh, reg_names[i].name,
(void *) (reg_names + i));
for (i = 0; i < ARRAY_SIZE (nzcv_names); i++)
checked_hash_insert (aarch64_nzcv_hsh, nzcv_names[i].template,
(void *) (nzcv_names + i));
for (i = 0; aarch64_operand_modifiers[i].name != NULL; i++)
{
const char *name = aarch64_operand_modifiers[i].name;
checked_hash_insert (aarch64_shift_hsh, name,
(void *) (aarch64_operand_modifiers + i));
/* Also hash the name in the upper case. */
checked_hash_insert (aarch64_shift_hsh, get_upper_str (name),
(void *) (aarch64_operand_modifiers + i));
}
for (i = 0; i < ARRAY_SIZE (aarch64_conds); i++)
{
unsigned int j;
/* A condition code may have alias(es), e.g. "cc", "lo" and "ul" are
the same condition code. */
for (j = 0; j < ARRAY_SIZE (aarch64_conds[i].names); ++j)
{
const char *name = aarch64_conds[i].names[j];
if (name == NULL)
break;
checked_hash_insert (aarch64_cond_hsh, name,
(void *) (aarch64_conds + i));
/* Also hash the name in the upper case. */
checked_hash_insert (aarch64_cond_hsh, get_upper_str (name),
(void *) (aarch64_conds + i));
}
}
for (i = 0; i < ARRAY_SIZE (aarch64_barrier_options); i++)
{
const char *name = aarch64_barrier_options[i].name;
/* Skip xx00 - the unallocated values of option. */
if ((i & 0x3) == 0)
continue;
checked_hash_insert (aarch64_barrier_opt_hsh, name,
(void *) (aarch64_barrier_options + i));
/* Also hash the name in the upper case. */
checked_hash_insert (aarch64_barrier_opt_hsh, get_upper_str (name),
(void *) (aarch64_barrier_options + i));
}
for (i = 0; i < ARRAY_SIZE (aarch64_prfops); i++)
{
const char* name = aarch64_prfops[i].name;
/* Skip the unallocated hint encodings. */
if (name == NULL)
continue;
checked_hash_insert (aarch64_pldop_hsh, name,
(void *) (aarch64_prfops + i));
/* Also hash the name in the upper case. */
checked_hash_insert (aarch64_pldop_hsh, get_upper_str (name),
(void *) (aarch64_prfops + i));
}
for (i = 0; aarch64_hint_options[i].name != NULL; i++)
{
const char* name = aarch64_hint_options[i].name;
checked_hash_insert (aarch64_hint_opt_hsh, name,
(void *) (aarch64_hint_options + i));
/* Also hash the name in the upper case. */
checked_hash_insert (aarch64_pldop_hsh, get_upper_str (name),
(void *) (aarch64_hint_options + i));
}
/* Set the cpu variant based on the command-line options. */
if (!mcpu_cpu_opt)
mcpu_cpu_opt = march_cpu_opt;
if (!mcpu_cpu_opt)
mcpu_cpu_opt = &cpu_default;
cpu_variant = *mcpu_cpu_opt;
/* Record the CPU type. */
mach = ilp32_p ? bfd_mach_aarch64_ilp32 : bfd_mach_aarch64;
bfd_set_arch_mach (stdoutput, TARGET_ARCH, mach);
}
/* Command line processing. */
const char *md_shortopts = "m:";
#ifdef AARCH64_BI_ENDIAN
#define OPTION_EB (OPTION_MD_BASE + 0)
#define OPTION_EL (OPTION_MD_BASE + 1)
#else
#if TARGET_BYTES_BIG_ENDIAN
#define OPTION_EB (OPTION_MD_BASE + 0)
#else
#define OPTION_EL (OPTION_MD_BASE + 1)
#endif
#endif
struct option md_longopts[] = {
#ifdef OPTION_EB
{"EB", no_argument, NULL, OPTION_EB},
#endif
#ifdef OPTION_EL
{"EL", no_argument, NULL, OPTION_EL},
#endif
{NULL, no_argument, NULL, 0}
};
size_t md_longopts_size = sizeof (md_longopts);
struct aarch64_option_table
{
char *option; /* Option name to match. */
char *help; /* Help information. */
int *var; /* Variable to change. */
int value; /* What to change it to. */
char *deprecated; /* If non-null, print this message. */
};
static struct aarch64_option_table aarch64_opts[] = {
{"mbig-endian", N_("assemble for big-endian"), &target_big_endian, 1, NULL},
{"mlittle-endian", N_("assemble for little-endian"), &target_big_endian, 0,
NULL},
#ifdef DEBUG_AARCH64
{"mdebug-dump", N_("temporary switch for dumping"), &debug_dump, 1, NULL},
#endif /* DEBUG_AARCH64 */
{"mverbose-error", N_("output verbose error messages"), &verbose_error_p, 1,
NULL},
{"mno-verbose-error", N_("do not output verbose error messages"),
&verbose_error_p, 0, NULL},
{NULL, NULL, NULL, 0, NULL}
};
struct aarch64_cpu_option_table
{
char *name;
const aarch64_feature_set value;
/* The canonical name of the CPU, or NULL to use NAME converted to upper
case. */
const char *canonical_name;
};
/* This list should, at a minimum, contain all the cpu names
recognized by GCC. */
static const struct aarch64_cpu_option_table aarch64_cpus[] = {
{"all", AARCH64_ANY, NULL},
{"cortex-a35", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC), "Cortex-A35"},
{"cortex-a53", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC), "Cortex-A53"},
{"cortex-a57", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC), "Cortex-A57"},
{"cortex-a72", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC), "Cortex-A72"},
{"exynos-m1", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
"Samsung Exynos M1"},
{"qdf24xx", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
"Qualcomm QDF24XX"},
{"thunderx", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
"Cavium ThunderX"},
/* The 'xgene-1' name is an older name for 'xgene1', which was used
in earlier releases and is superseded by 'xgene1' in all
tools. */
{"xgene-1", AARCH64_ARCH_V8, "APM X-Gene 1"},
{"xgene1", AARCH64_ARCH_V8, "APM X-Gene 1"},
{"xgene2", AARCH64_FEATURE (AARCH64_ARCH_V8,
AARCH64_FEATURE_CRC), "APM X-Gene 2"},
{"generic", AARCH64_ARCH_V8, NULL},
{NULL, AARCH64_ARCH_NONE, NULL}
};
struct aarch64_arch_option_table
{
char *name;
const aarch64_feature_set value;
};
/* This list should, at a minimum, contain all the architecture names
recognized by GCC. */
static const struct aarch64_arch_option_table aarch64_archs[] = {
{"all", AARCH64_ANY},
{"armv8-a", AARCH64_ARCH_V8},
{"armv8.1-a", AARCH64_ARCH_V8_1},
{"armv8.2-a", AARCH64_ARCH_V8_2},
{NULL, AARCH64_ARCH_NONE}
};
/* ISA extensions. */
struct aarch64_option_cpu_value_table
{
char *name;
const aarch64_feature_set value;
};
static const struct aarch64_option_cpu_value_table aarch64_features[] = {
{"crc", AARCH64_FEATURE (AARCH64_FEATURE_CRC, 0)},
{"crypto", AARCH64_FEATURE (AARCH64_FEATURE_CRYPTO, 0)},
{"fp", AARCH64_FEATURE (AARCH64_FEATURE_FP, 0)},
{"lse", AARCH64_FEATURE (AARCH64_FEATURE_LSE, 0)},
{"simd", AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0)},
{"pan", AARCH64_FEATURE (AARCH64_FEATURE_PAN, 0)},
{"lor", AARCH64_FEATURE (AARCH64_FEATURE_LOR, 0)},
{"rdma", AARCH64_FEATURE (AARCH64_FEATURE_SIMD
| AARCH64_FEATURE_RDMA, 0)},
{"fp16", AARCH64_FEATURE (AARCH64_FEATURE_F16
| AARCH64_FEATURE_FP, 0)},
{"profile", AARCH64_FEATURE (AARCH64_FEATURE_PROFILE, 0)},
{NULL, AARCH64_ARCH_NONE}
};
struct aarch64_long_option_table
{
char *option; /* Substring to match. */
char *help; /* Help information. */
int (*func) (char *subopt); /* Function to decode sub-option. */
char *deprecated; /* If non-null, print this message. */
};
static int
aarch64_parse_features (char *str, const aarch64_feature_set **opt_p,
bfd_boolean ext_only)
{
/* We insist on extensions being added before being removed. We achieve
this by using the ADDING_VALUE variable to indicate whether we are
adding an extension (1) or removing it (0) and only allowing it to
change in the order -1 -> 1 -> 0. */
int adding_value = -1;
aarch64_feature_set *ext_set = xmalloc (sizeof (aarch64_feature_set));
/* Copy the feature set, so that we can modify it. */
*ext_set = **opt_p;
*opt_p = ext_set;
while (str != NULL && *str != 0)
{
const struct aarch64_option_cpu_value_table *opt;
char *ext = NULL;
int optlen;
if (!ext_only)
{
if (*str != '+')
{
as_bad (_("invalid architectural extension"));
return 0;
}
ext = strchr (++str, '+');
}
if (ext != NULL)
optlen = ext - str;
else
optlen = strlen (str);
if (optlen >= 2 && strncmp (str, "no", 2) == 0)
{
if (adding_value != 0)
adding_value = 0;
optlen -= 2;
str += 2;
}
else if (optlen > 0)
{
if (adding_value == -1)
adding_value = 1;
else if (adding_value != 1)
{
as_bad (_("must specify extensions to add before specifying "
"those to remove"));
return FALSE;
}
}
if (optlen == 0)
{
as_bad (_("missing architectural extension"));
return 0;
}
gas_assert (adding_value != -1);
for (opt = aarch64_features; opt->name != NULL; opt++)
if (strncmp (opt->name, str, optlen) == 0)
{
/* Add or remove the extension. */
if (adding_value)
AARCH64_MERGE_FEATURE_SETS (*ext_set, *ext_set, opt->value);
else
AARCH64_CLEAR_FEATURE (*ext_set, *ext_set, opt->value);
break;
}
if (opt->name == NULL)
{
as_bad (_("unknown architectural extension `%s'"), str);
return 0;
}
str = ext;
};
return 1;
}
static int
aarch64_parse_cpu (char *str)
{
const struct aarch64_cpu_option_table *opt;
char *ext = strchr (str, '+');
size_t optlen;
if (ext != NULL)
optlen = ext - str;
else
optlen = strlen (str);
if (optlen == 0)
{
as_bad (_("missing cpu name `%s'"), str);
return 0;
}
for (opt = aarch64_cpus; opt->name != NULL; opt++)
if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
{
mcpu_cpu_opt = &opt->value;
if (ext != NULL)
return aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE);
return 1;
}
as_bad (_("unknown cpu `%s'"), str);
return 0;
}
static int
aarch64_parse_arch (char *str)
{
const struct aarch64_arch_option_table *opt;
char *ext = strchr (str, '+');
size_t optlen;
if (ext != NULL)
optlen = ext - str;
else
optlen = strlen (str);
if (optlen == 0)
{
as_bad (_("missing architecture name `%s'"), str);
return 0;
}
for (opt = aarch64_archs; opt->name != NULL; opt++)
if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
{
march_cpu_opt = &opt->value;
if (ext != NULL)
return aarch64_parse_features (ext, &march_cpu_opt, FALSE);
return 1;
}
as_bad (_("unknown architecture `%s'\n"), str);
return 0;
}
/* ABIs. */
struct aarch64_option_abi_value_table
{
char *name;
enum aarch64_abi_type value;
};
static const struct aarch64_option_abi_value_table aarch64_abis[] = {
{"ilp32", AARCH64_ABI_ILP32},
{"lp64", AARCH64_ABI_LP64},
{NULL, 0}
};
static int
aarch64_parse_abi (char *str)
{
const struct aarch64_option_abi_value_table *opt;
size_t optlen = strlen (str);
if (optlen == 0)
{
as_bad (_("missing abi name `%s'"), str);
return 0;
}
for (opt = aarch64_abis; opt->name != NULL; opt++)
if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
{
aarch64_abi = opt->value;
return 1;
}
as_bad (_("unknown abi `%s'\n"), str);
return 0;
}
static struct aarch64_long_option_table aarch64_long_opts[] = {
#ifdef OBJ_ELF
{"mabi=", N_("<abi name>\t specify for ABI <abi name>"),
aarch64_parse_abi, NULL},
#endif /* OBJ_ELF */
{"mcpu=", N_("<cpu name>\t assemble for CPU <cpu name>"),
aarch64_parse_cpu, NULL},
{"march=", N_("<arch name>\t assemble for architecture <arch name>"),
aarch64_parse_arch, NULL},
{NULL, NULL, 0, NULL}
};
int
md_parse_option (int c, char *arg)
{
struct aarch64_option_table *opt;
struct aarch64_long_option_table *lopt;
switch (c)
{
#ifdef OPTION_EB
case OPTION_EB:
target_big_endian = 1;
break;
#endif
#ifdef OPTION_EL
case OPTION_EL:
target_big_endian = 0;
break;
#endif
case 'a':
/* Listing option. Just ignore these, we don't support additional
ones. */
return 0;
default:
for (opt = aarch64_opts; opt->option != NULL; opt++)
{
if (c == opt->option[0]
&& ((arg == NULL && opt->option[1] == 0)
|| streq (arg, opt->option + 1)))
{
/* If the option is deprecated, tell the user. */
if (opt->deprecated != NULL)
as_tsktsk (_("option `-%c%s' is deprecated: %s"), c,
arg ? arg : "", _(opt->deprecated));
if (opt->var != NULL)
*opt->var = opt->value;
return 1;
}
}
for (lopt = aarch64_long_opts; lopt->option != NULL; lopt++)
{
/* These options are expected to have an argument. */
if (c == lopt->option[0]
&& arg != NULL
&& strncmp (arg, lopt->option + 1,
strlen (lopt->option + 1)) == 0)
{
/* If the option is deprecated, tell the user. */
if (lopt->deprecated != NULL)
as_tsktsk (_("option `-%c%s' is deprecated: %s"), c, arg,
_(lopt->deprecated));
/* Call the sup-option parser. */
return lopt->func (arg + strlen (lopt->option) - 1);
}
}
return 0;
}
return 1;
}
void
md_show_usage (FILE * fp)
{
struct aarch64_option_table *opt;
struct aarch64_long_option_table *lopt;
fprintf (fp, _(" AArch64-specific assembler options:\n"));
for (opt = aarch64_opts; opt->option != NULL; opt++)
if (opt->help != NULL)
fprintf (fp, " -%-23s%s\n", opt->option, _(opt->help));
for (lopt = aarch64_long_opts; lopt->option != NULL; lopt++)
if (lopt->help != NULL)
fprintf (fp, " -%s%s\n", lopt->option, _(lopt->help));
#ifdef OPTION_EB
fprintf (fp, _("\
-EB assemble code for a big-endian cpu\n"));
#endif
#ifdef OPTION_EL
fprintf (fp, _("\
-EL assemble code for a little-endian cpu\n"));
#endif
}
/* Parse a .cpu directive. */
static void
s_aarch64_cpu (int ignored ATTRIBUTE_UNUSED)
{
const struct aarch64_cpu_option_table *opt;
char saved_char;
char *name;
char *ext;
size_t optlen;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
ext = strchr (name, '+');
if (ext != NULL)
optlen = ext - name;
else
optlen = strlen (name);
/* Skip the first "all" entry. */
for (opt = aarch64_cpus + 1; opt->name != NULL; opt++)
if (strlen (opt->name) == optlen
&& strncmp (name, opt->name, optlen) == 0)
{
mcpu_cpu_opt = &opt->value;
if (ext != NULL)
if (!aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE))
return;
cpu_variant = *mcpu_cpu_opt;
*input_line_pointer = saved_char;
demand_empty_rest_of_line ();
return;
}
as_bad (_("unknown cpu `%s'"), name);
*input_line_pointer = saved_char;
ignore_rest_of_line ();
}
/* Parse a .arch directive. */
static void
s_aarch64_arch (int ignored ATTRIBUTE_UNUSED)
{
const struct aarch64_arch_option_table *opt;
char saved_char;
char *name;
char *ext;
size_t optlen;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
ext = strchr (name, '+');
if (ext != NULL)
optlen = ext - name;
else
optlen = strlen (name);
/* Skip the first "all" entry. */
for (opt = aarch64_archs + 1; opt->name != NULL; opt++)
if (strlen (opt->name) == optlen
&& strncmp (name, opt->name, optlen) == 0)
{
mcpu_cpu_opt = &opt->value;
if (ext != NULL)
if (!aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE))
return;
cpu_variant = *mcpu_cpu_opt;
*input_line_pointer = saved_char;
demand_empty_rest_of_line ();
return;
}
as_bad (_("unknown architecture `%s'\n"), name);
*input_line_pointer = saved_char;
ignore_rest_of_line ();
}
/* Parse a .arch_extension directive. */
static void
s_aarch64_arch_extension (int ignored ATTRIBUTE_UNUSED)
{
char saved_char;
char *ext = input_line_pointer;;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
if (!aarch64_parse_features (ext, &mcpu_cpu_opt, TRUE))
return;
cpu_variant = *mcpu_cpu_opt;
*input_line_pointer = saved_char;
demand_empty_rest_of_line ();
}
/* Copy symbol information. */
void
aarch64_copy_symbol_attributes (symbolS * dest, symbolS * src)
{
AARCH64_GET_FLAG (dest) = AARCH64_GET_FLAG (src);
}
| selmentdev/selment-toolchain | source/binutils-latest/gas/config/tc-aarch64.c | C | gpl-3.0 | 225,864 |
/* Soot - a J*va Optimization Framework
* Copyright (C) 2003 Ondrej Lhotak
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/* THIS FILE IS AUTO-GENERATED FROM soot_options.xml. DO NOT MODIFY. */
package soot.options;
import java.util.*;
/** Option parser for Lazy Code Motion. */
public class LCMOptions
{
private Map<String, String> options;
public LCMOptions( Map<String, String> options ) {
this.options = options;
}
/** Enabled --
* .
*
*/
public boolean enabled() {
return soot.PhaseOptions.getBoolean( options, "enabled" );
}
/** Unroll --
* .
* If true, perform loop inversion before doing the
* transformation.
*/
public boolean unroll() {
return soot.PhaseOptions.getBoolean( options, "unroll" );
}
/** Naive Side Effect Tester --
* Use a naive side effect analysis even if interprocedural
* information is available.
* If Naive Side Effect Tester is set to true, Lazy Code Motion
* uses the conservative side effect information provided by the
* NaiveSideEffectTester class, even if interprocedural information
* about side effects is available. The naive side effect analysis
* is based solely on the information available locally about a
* statement. It assumes, for example, that any method call has the
* potential to write and read all instance and static fields in
* the program. If Naive Side Effect Tester is set to false and
* Soot is in whole program mode, then Lazy Code Motion uses the
* side effect information provided by the PASideEffectTester
* class. PASideEffectTester uses a points-to analysis to determine
* which fields and statics may be written or read by a given
* statement. If whole program analysis is not performed, naive
* side effect information is used regardless of the setting of
* Naive Side Effect Tester.
*/
public boolean naive_side_effect() {
return soot.PhaseOptions.getBoolean( options, "naive-side-effect" );
}
public static final int safety_safe = 1;
public static final int safety_medium = 2;
public static final int safety_unsafe = 3;
/** Safety --
* .
* This option controls which fields and statements are candidates
* for code motion.
*/
public int safety() {
String s = soot.PhaseOptions.getString( options, "safety" );
if( s.equalsIgnoreCase( "safe" ) )
return safety_safe;
if( s.equalsIgnoreCase( "medium" ) )
return safety_medium;
if( s.equalsIgnoreCase( "unsafe" ) )
return safety_unsafe;
throw new RuntimeException( "Invalid value "+s+" of phase option safety" );
}
}
| flankerhqd/JAADAS | soot/generated/options/soot/options/LCMOptions.java | Java | gpl-3.0 | 3,591 |
#include <algorithm>
#include <fstream>
#include <iterator>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <zlib.h>
#include "elf.h"
#pragma pack(push, 1)
struct RplLibsDef
{
be_val<uint32_t> name;
be_val<uint32_t> stubStart;
be_val<uint32_t> stubEnd;
};
#pragma pack(pop)
static const uint32_t LoadAddress = 0x01000000u;
static const uint32_t CodeAddress = 0x02000000u;
static const uint32_t DataAddress = 0x10000000u;
static const uint32_t WiiuLoadAddress = 0xC0000000u;
struct ElfFile
{
struct Symbol
{
std::string name;
uint32_t address;
uint32_t size;
elf::SymbolType type;
elf::SymbolBinding binding;
uint32_t outNamePos;
};
struct Relocation
{
uint32_t target;
elf::RelocationType type;
Symbol *symbol;
uint32_t addend;
};
struct DataSection
{
std::string name;
uint32_t address;
elf::SectionType type;
elf::SectionFlags flags;
/* Data used if type == SHT_PROGBITS */
std::vector<char> data;
/* Size used if type == SHT_NOBITS */
uint32_t size;
};
struct RplImport
{
Symbol *trampSymbol;
Symbol *stubSymbol;
uint32_t stubAddr;
uint32_t trampAddr;
};
struct RplImportLibrary
{
std::string name;
std::vector<std::unique_ptr<RplImport>> imports;
};
uint32_t entryPoint;
std::vector<std::unique_ptr<DataSection>> dataSections;
std::vector<std::unique_ptr<Symbol>> symbols;
std::vector<std::unique_ptr<Relocation>> relocations;
std::vector<std::unique_ptr<RplImportLibrary>> rplImports;
};
struct InputSection
{
elf::SectionHeader header;
std::vector<char> data;
};
static ElfFile::Symbol *
findSymbol(ElfFile &file, uint32_t address)
{
for (auto &symbol : file.symbols) {
if (symbol->address == address && symbol->type != elf::STT_NOTYPE) {
return symbol.get();
}
}
for (auto &symbol : file.symbols) {
if (symbol->address == address) {
return symbol.get();
}
}
return nullptr;
}
static ElfFile::RplImport *
findImport(ElfFile &file, uint32_t address)
{
for (auto &lib : file.rplImports) {
for (auto &import : lib->imports) {
if (import->stubAddr == address || import->trampAddr == address) {
return import.get();
}
}
}
return nullptr;
}
template<typename Type>
static Type *
getLoaderDataPtr(std::vector<InputSection> &inSections, uint32_t address)
{
for (auto §ion : inSections) {
auto start = section.header.addr;
auto end = start + section.data.size();
if (start <= address && end > address) {
auto offset = address - start;
return reinterpret_cast<Type *>(section.data.data() + offset);
}
}
return nullptr;
}
static elf::Symbol *
getSectionSymbol(InputSection §ion, size_t index)
{
auto symbols = reinterpret_cast<elf::Symbol *>(section.data.data());
return &symbols[index];
};
static bool
read(ElfFile &file, const std::string &filename)
{
std::ifstream in { filename, std::ifstream::binary };
std::vector<InputSection> inSections;
if (!in.is_open()) {
std::cout << "Could not open " << filename << " for reading" << std::endl;
return false;
}
/* Read header */
elf::Header header;
in.read(reinterpret_cast<char *>(&header), sizeof(elf::Header));
if (header.magic != elf::HeaderMagic) {
std::cout << "Invalid ELF magic header" << std::endl;
return false;
}
if (header.fileClass != elf::ELFCLASS32) {
std::cout << "Unexpected ELF file class" << std::endl;
return false;
}
if (header.encoding != elf::ELFDATA2MSB) {
std::cout << "Unexpected ELF encoding" << std::endl;
return false;
}
if (header.machine != elf::EM_PPC) {
std::cout << "Unexpected ELF machine type" << std::endl;
return false;
}
if (header.elfVersion != elf::EV_CURRENT) {
std::cout << "Unexpected ELF version" << std::endl;
return false;
}
file.entryPoint = header.entry;
/* Read section headers and data */
in.seekg(static_cast<size_t>(header.shoff));
inSections.resize(header.shnum);
for (auto §ion : inSections) {
in.read(reinterpret_cast<char *>(§ion.header), sizeof(elf::SectionHeader));
if (!section.header.size || section.header.type == elf::SHT_NOBITS) {
continue;
}
auto pos = in.tellg();
in.seekg(static_cast<size_t>(section.header.offset));
section.data.resize(section.header.size);
in.read(section.data.data(), section.data.size());
in.seekg(pos);
}
auto shStrTab = inSections[header.shstrndx].data.data();
/* Process any loader relocations */
for (auto §ion : inSections) {
if (section.header.type != elf::SHT_RELA) {
continue;
}
auto name = std::string { shStrTab + section.header.name };
if (name.compare(".rela.dyn") != 0) {
continue;
}
auto symSection = inSections[section.header.link];
auto relas = reinterpret_cast<elf::Rela *>(section.data.data());
auto count = section.data.size() / sizeof(elf::Rela);
for (auto i = 0u; i < count; ++i) {
auto &rela = relas[i];
auto index = rela.info >> 8;
auto symbol = getSectionSymbol(symSection, index);
auto addr = symbol->value + rela.addend;
auto type = rela.info & 0xff;
auto ptr = getLoaderDataPtr<uint32_t>(inSections, rela.offset);
if (!ptr) {
std::cout << "Unexpected relocation offset in .rela.dyn section" << std::endl;
return false;
}
switch (type) {
case elf::R_PPC_RELATIVE:
*ptr = byte_swap(addr);
break;
case elf::R_PPC_NONE:
/* ignore padding */
break;
default:
std::cout << "Unexpected relocation type in .rela.dyn section" << std::endl;
return false;
}
}
}
/* Read text/data sections */
for (auto §ion : inSections) {
if (section.header.addr >= LoadAddress && section.header.addr < CodeAddress) {
/* Skip any load sections */
continue;
}
auto name = std::string { shStrTab + section.header.name };
if (section.header.type == elf::SHT_PROGBITS) {
auto data = new ElfFile::DataSection();
data->type = elf::SHT_PROGBITS;
data->flags = static_cast<elf::SectionFlags>(section.header.flags.value());
data->name = shStrTab + section.header.name;
data->address = section.header.addr;
data->data = section.data;
file.dataSections.emplace_back(data);
} else if (section.header.type == elf::SHT_NOBITS) {
auto bss = new ElfFile::DataSection();
bss->type = elf::SHT_NOBITS;
bss->flags = static_cast<elf::SectionFlags>(section.header.flags.value());
bss->name = shStrTab + section.header.name;
bss->address = section.header.addr;
bss->size = section.header.size;
file.dataSections.emplace_back(bss);
}
}
/* Default symbols */
auto symNull = new ElfFile::Symbol();
symNull->address = 0;
symNull->size = 0;
symNull->type = elf::STT_NOTYPE;
symNull->binding = elf::STB_LOCAL;
file.symbols.emplace_back(symNull);
auto symText = new ElfFile::Symbol();
symText->name = "$TEXT";
symText->address = CodeAddress;
symText->size = 0;
symText->type = elf::STT_SECTION;
symText->binding = elf::STB_LOCAL;
file.symbols.emplace_back(symText);
auto symData = new ElfFile::Symbol();
symData->name = "$DATA";
symData->address = DataAddress;
symData->size = 0;
symData->type = elf::STT_SECTION;
symData->binding = elf::STB_LOCAL;
file.symbols.emplace_back(symData);
auto symUndef = new ElfFile::Symbol();
symUndef->name = "$UNDEF";
symUndef->address = 0;
symUndef->size = 0;
symUndef->type = elf::STT_OBJECT;
symUndef->binding = elf::STB_GLOBAL;
file.symbols.emplace_back(symUndef);
/* Read symbols */
for (auto §ion : inSections) {
if (section.header.type != elf::SHT_SYMTAB) {
continue;
}
auto name = std::string { shStrTab + section.header.name };
if (name.compare(".symtab") != 0) {
std::cout << "Unexpected symbol section " << name << std::endl;
return false;
}
auto strTab = inSections[section.header.link].data.data();
auto symTab = reinterpret_cast<elf::Symbol *>(section.data.data());
auto count = section.data.size() / sizeof(elf::Symbol);
for (auto i = 0u; i < count; ++i) {
auto &sym = symTab[i];
if (sym.value >= LoadAddress && sym.value < CodeAddress) {
/* Skip any load symbols */
continue;
}
auto type = static_cast<elf::SymbolType>(sym.info & 0xF);
auto binding = static_cast<elf::SymbolBinding>((sym.info >> 4) & 0xF);
if (type == elf::STT_NOTYPE && sym.value == 0) {
/* Skip null symbol */
continue;
}
if (type == elf::STT_FILE || type == elf::STT_SECTION) {
/* Skip file, section symbols */
continue;
}
auto symbol = new ElfFile::Symbol();
symbol->name = strTab + sym.name;
symbol->address = sym.value;
symbol->size = sym.size;
symbol->type = type;
symbol->binding = binding;
file.symbols.emplace_back(symbol);
}
}
/* Read RPL imports */
for (auto §ion : inSections) {
auto name = std::string { shStrTab + section.header.name };
if (name.compare(".lib.rplLibs") != 0) {
continue;
}
auto rplTab = reinterpret_cast<RplLibsDef *>(section.data.data());
auto count = section.data.size() / sizeof(RplLibsDef);
for (auto i = 0u; i < count; ++i) {
auto &rpl = rplTab[i];
auto lib = new ElfFile::RplImportLibrary();
lib->name = getLoaderDataPtr<char>(inSections, rpl.name);
for (auto stubAddr = rpl.stubStart; stubAddr < rpl.stubEnd; stubAddr += 4) {
auto import = new ElfFile::RplImport();
import->trampAddr = byte_swap(*getLoaderDataPtr<uint32_t>(inSections, stubAddr));
import->stubAddr = stubAddr;
/* Get the tramp symbol */
import->trampSymbol = findSymbol(file, import->trampAddr);
/* Create a new symbol to use for the import */
auto stubSymbol = new ElfFile::Symbol();
import->stubSymbol = stubSymbol;
stubSymbol->name = import->trampSymbol->name;
stubSymbol->address = 0;
stubSymbol->size = 0;
stubSymbol->binding = elf::STB_GLOBAL;
stubSymbol->type = elf::STT_FUNC;
file.symbols.emplace_back(stubSymbol);
/* Rename tramp symbol */
import->trampSymbol->name += "_tramp";
lib->imports.emplace_back(import);
}
file.rplImports.emplace_back(lib);
}
}
/* Read relocations */
for (auto §ion : inSections) {
if (section.header.type != elf::SHT_RELA) {
continue;
}
auto name = std::string { shStrTab + section.header.name };
if (name.compare(".rela.dyn") == 0) {
/* Skip dyn relocations */
continue;
}
auto symTab = reinterpret_cast<elf::Symbol *>(inSections[section.header.link].data.data());
auto relTab = reinterpret_cast<elf::Rela *>(section.data.data());
auto count = section.data.size() / sizeof(elf::Rela);
for (auto i = 0u; i < count; ++i) {
auto relocation = new ElfFile::Relocation();
auto &rela = relTab[i];
auto type = rela.info & 0xff;
auto index = rela.info >> 8;
auto &sym = symTab[index];
auto symType = sym.info & 0xf;
if (symType == elf::STT_SECTION && sym.value == CodeAddress) {
if (rela.offset < CodeAddress || rela.offset >= DataAddress) {
std::cout << "Unexpected symbol referenced in relocation section " << name << std::endl;
return false;
}
}
auto addend = static_cast<uint32_t>(rela.addend);
if (auto import = findImport(file, addend)) {
relocation->symbol = import->stubSymbol;
relocation->addend = 0;
} else if (auto symbol = findSymbol(file, addend)) {
relocation->symbol = symbol;
relocation->addend = 0;
} else if (addend >= DataAddress && addend < WiiuLoadAddress) {
relocation->symbol = findSymbol(file, DataAddress);
relocation->addend = addend - DataAddress;
} else if (addend >= CodeAddress && addend < DataAddress) {
relocation->symbol = findSymbol(file, CodeAddress);
relocation->addend = addend - CodeAddress;
} else {
/* If we can't find a proper symbol, write the addend in and hope for the best */
auto ptr = getLoaderDataPtr<uint32_t>(inSections, rela.offset);
*ptr = addend;
std::cout << "Unexpected addend " << std::hex << addend << " referenced in relocation section " << name << ", continuing." << std::endl;
continue;
}
relocation->target = rela.offset;
relocation->type = static_cast<elf::RelocationType>(type);
file.relocations.emplace_back(relocation);
}
}
/* Read dyn relocations */
for (auto §ion : inSections) {
if (section.header.type != elf::SHT_RELA) {
continue;
}
auto name = std::string { shStrTab + section.header.name };
if (name.compare(".rela.dyn") != 0) {
continue;
}
auto symSection = inSections[section.header.link];
auto relas = reinterpret_cast<elf::Rela *>(section.data.data());
auto count = section.data.size() / sizeof(elf::Rela);
for (auto i = 0u; i < count; ++i) {
auto relocation = new ElfFile::Relocation();
auto &rela = relas[i];
auto type = rela.info & 0xff;
auto index = rela.info >> 8;
auto symbol = getSectionSymbol(symSection, index);
auto addr = symbol->value + rela.addend;
if(type == elf::R_PPC_NONE)
{
/* ignore padding */
continue;
}
if(index == 0)
{
auto addend = static_cast<uint32_t>(rela.addend);
if (auto import = findImport(file, addend)) {
relocation->symbol = import->stubSymbol;
relocation->addend = 0;
} else if (auto symbol = findSymbol(file, addend)) {
relocation->symbol = symbol;
relocation->addend = 0;
} else if (addr >= CodeAddress && addr < DataAddress) {
index = 1;
relocation->symbol = findSymbol(file, CodeAddress);
relocation->addend = rela.addend - CodeAddress;
} else if (addr >= DataAddress && addr < WiiuLoadAddress) {
index = 2;
relocation->symbol = findSymbol(file, DataAddress);
relocation->addend = rela.addend - DataAddress;
} else {
std::cout << "Unexpected symbol address in .rela.dyn section" << std::endl;
return false;
}
}
switch (type) {
case elf::R_PPC_RELATIVE:
type = elf::R_PPC_ADDR32;
break;
default:
std::cout << "Unexpected relocation type in .rela.dyn section" << std::endl;
return false;
}
relocation->target = rela.offset;
relocation->type = static_cast<elf::RelocationType>(type);
/* Scrap any compiler/linker garbage */
if(relocation->target >= CodeAddress && relocation->target < WiiuLoadAddress)
file.relocations.emplace_back(relocation);
}
}
return true;
}
struct OutputSection
{
std::string name;
elf::SectionHeader header;
std::vector<char> data;
OutputSection *relocationSection = nullptr;
ElfFile::Symbol *sectionSymbol = nullptr;
};
template<typename SymbolIterator>
SymbolIterator addSection(ElfFile &file, std::vector<OutputSection *> &outSections, SymbolIterator symbolIterator, OutputSection *section)
{
auto sectionSymbol = new ElfFile::Symbol();
sectionSymbol->name = section->name;
sectionSymbol->address = section->header.addr;
sectionSymbol->size = -1;
sectionSymbol->type = elf::STT_SECTION;
sectionSymbol->binding = elf::STB_LOCAL;
section->sectionSymbol = sectionSymbol;
outSections.push_back(section);
return file.symbols.insert(symbolIterator, std::unique_ptr<ElfFile::Symbol> { sectionSymbol }) + 1;
};
static uint32_t
getSectionIndex(std::vector<OutputSection *> &outSections, uint32_t address)
{
for (auto i = 0u; i < outSections.size(); ++i) {
auto §ion = outSections[i];
auto start = section->header.addr;
auto end = start + section->header.size;
if (address >= start && address < end) {
return i;
}
}
return -1;
}
static uint32_t
getSectionIndex(std::vector<OutputSection *> &outSections, const std::string &name)
{
for (auto i = 0u; i < outSections.size(); ++i) {
auto §ion = outSections[i];
if (section->name.compare(name) == 0) {
return i;
}
}
return -1;
}
static bool
write(ElfFile &file, const std::string &filename)
{
std::vector<OutputSection *> outSections;
auto sectionSymbolItr = file.symbols.begin() + 4;
/* Create NULL section */
auto nullSection = new OutputSection();
memset(&nullSection->header, 0, sizeof(elf::SectionHeader));
outSections.push_back(nullSection);
/* Create text/data sections */
for (auto §ion : file.dataSections) {
auto out = new OutputSection();
out->header.name = -1;
out->header.type = section->type;
out->header.flags = section->flags;
out->header.addr = section->address;
out->header.offset = -1;
if (section->type == elf::SHT_NOBITS) {
out->header.size = section->size;
} else {
out->header.size = section->data.size();
}
out->header.link = 0;
out->header.info = 0;
if (section->address == DataAddress) {
out->header.addralign = 4096;
out->header.flags |= elf::SHF_WRITE; /* .rodata needs to be writable? */
} else {
out->header.addralign = 256;
}
out->header.entsize = 0;
/* Add section */
out->name = section->name;
out->data = section->data;
sectionSymbolItr = addSection(file, outSections, sectionSymbolItr, out);
}
/* Create relocation sections */
for (auto &relocation : file.relocations) {
OutputSection *targetSection = nullptr;
for (auto §ion : outSections) {
auto start = section->header.addr;
auto end = start + section->header.size;
if (relocation->target >= start && relocation->target < end) {
targetSection = section;
break;
}
}
if (!targetSection) {
std::cout << "Error could not find section for relocation" << std::endl;
return false;
}
if (!targetSection->relocationSection) {
/* Create new relocation section */
auto out = new OutputSection();
out->header.name = -1;
out->header.type = elf::SHT_RELA;
out->header.flags = 0;
out->header.addr = 0;
out->header.offset = -1;
out->header.size = -1;
out->header.link = -1;
out->header.info = getSectionIndex(outSections, targetSection->header.addr);
out->header.addralign = 4;
out->header.entsize = sizeof(elf::Rela);
/* Add section */
out->name = ".rela" + targetSection->name;
sectionSymbolItr = addSection(file, outSections, sectionSymbolItr, out);
targetSection->relocationSection = out;
}
}
/* Calculate sizes of symbol/string tables so RPL imports are placed after them */
auto loadAddress = 0xC0000000;
auto predictStrTabSize = 1;
auto predictSymTabSize = 1;
auto predictShstrTabSize = 1;
for (auto &symbol : file.symbols) {
predictStrTabSize += symbol->name.size() + 1;
predictSymTabSize += sizeof(elf::Symbol);
}
for (auto §ion : outSections) {
predictShstrTabSize += section->name.size() + 1;
}
predictStrTabSize = align_up(predictStrTabSize, 0x10);
predictSymTabSize = align_up(predictSymTabSize, 0x10);
predictShstrTabSize = align_up(predictShstrTabSize, 0x10);
loadAddress += predictStrTabSize + predictSymTabSize + predictShstrTabSize;
/* Create RPL import sections, .fimport_*, .dimport_* */
for (auto &lib : file.rplImports) {
auto out = new OutputSection();
out->header.name = -1;
out->header.type = elf::SHT_RPL_IMPORTS;
out->header.flags = elf::SHF_ALLOC | elf::SHF_EXECINSTR;
out->header.addr = loadAddress;
out->header.offset = -1;
out->header.link = 0;
out->header.info = 0;
out->header.addralign = 4;
out->header.entsize = 0;
out->name = ".fimport_" + lib->name;
/* Calculate size */
auto nameSize = align_up(8 + lib->name.size(), 8);
auto stubSize = 8 + 8 * lib->imports.size();
out->header.size = std::max(nameSize, stubSize);
out->data.resize(out->header.size);
/* Setup data */
auto imports = reinterpret_cast<elf::RplImport*>(out->data.data());
imports->count = lib->imports.size();
imports->signature = crc32(0, Z_NULL, 0);
memcpy(imports->name, lib->name.data(), lib->name.size());
imports->name[lib->name.size()] = 0;
/* Update address of import symbols */
for (auto i = 0u; i < lib->imports.size(); ++i) {
lib->imports[i]->stubSymbol->address = loadAddress + 8 + i * 8;
}
loadAddress = align_up(loadAddress + out->header.size, 4);
/* Add section */
sectionSymbolItr = addSection(file, outSections, sectionSymbolItr, out);
}
/* Prune out unneeded symbols */
for (auto i = 0u; i < file.symbols.size(); ++i) {
if (!file.symbols[i]->name.empty() && file.symbols[i]->type == elf::STT_NOTYPE && file.symbols[i]->size == 0) {
file.symbols.erase(file.symbols.begin() + i);
i--;
}
}
/* NOTICE: FROM NOW ON DO NOT MODIFY mSymbols */
/* Convert relocations */
for (auto &relocation : file.relocations) {
OutputSection *targetSection = nullptr;
for (auto §ion : outSections) {
auto start = section->header.addr;
auto end = start + section->header.size;
if (relocation->target >= start && relocation->target < end) {
targetSection = section;
break;
}
}
if (!targetSection || !targetSection->relocationSection) {
std::cout << "Error could not find section for relocation" << std::endl;
return false;
}
/* Get address of relocation->target */
auto relocationSection = targetSection->relocationSection;
/* Find symbol this relocation points to */
auto itr = std::find_if(file.symbols.begin(), file.symbols.end(), [&relocation](auto &val) {
return val.get() == relocation->symbol;
});
auto idx = itr - file.symbols.begin();
/* If the symbol doesn't exist but it is within DATA or TEXT, use those symbols + an addend */
if (itr == file.symbols.end()) {
if (relocation->symbol->address >= CodeAddress && relocation->symbol->address < DataAddress) {
idx = 1;
relocation->addend = relocation->symbol->address - CodeAddress;
relocation->symbol = findSymbol(file, CodeAddress);
} else if (relocation->symbol->address >= DataAddress && relocation->symbol->address < WiiuLoadAddress) {
idx = 2;
relocation->addend = relocation->symbol->address - DataAddress;
relocation->symbol = findSymbol(file, DataAddress);
} else {
std::cout << "Could not find matching symbol for relocation" << std::endl;
return false;
}
}
/* Create relocation */
elf::Rela rela;
rela.info = relocation->type | idx << 8;
if(relocation->type == elf::R_PPC_RELATIVE) {
rela.info = elf::R_PPC_ADDR32 | idx << 8;
}
rela.addend = relocation->addend;
rela.offset = relocation->target;
/* Append to relocation section data */
char *relaData = reinterpret_cast<char *>(&rela);
relocationSection->data.insert(relocationSection->data.end(), relaData, relaData + sizeof(elf::Rela));
}
/* String + Symbol sections */
auto symTabSection = new OutputSection();
auto strTabSection = new OutputSection();
auto shStrTabSection = new OutputSection();
symTabSection->name = ".symtab";
strTabSection->name = ".strtab";
shStrTabSection->name = ".shstrtab";
auto symTabIndex = outSections.size();
outSections.push_back(symTabSection);
auto strTabIndex = outSections.size();
outSections.push_back(strTabSection);
auto shStrTabIndex = outSections.size();
outSections.push_back(shStrTabSection);
/* Update relocation sections to link to symtab */
for (auto §ion : outSections) {
if (section->header.type == elf::SHT_RELA) {
section->header.link = symTabIndex;
}
if (section->header.type != elf::SHT_NOBITS) {
section->header.size = section->data.size();
}
if (section->sectionSymbol) {
section->sectionSymbol->address = section->header.addr;
section->sectionSymbol->size = section->header.size;
}
}
/* Create .strtab */
strTabSection->header.name = 0;
strTabSection->header.type = elf::SHT_STRTAB;
strTabSection->header.flags = elf::SHF_ALLOC;
strTabSection->header.addr = 0;
strTabSection->header.offset = -1;
strTabSection->header.size = -1;
strTabSection->header.link = 0;
strTabSection->header.info = 0;
strTabSection->header.addralign = 1;
strTabSection->header.entsize = 0;
/* Add all symbol names to data, update symbol->outNamePos */
strTabSection->data.push_back(0);
for (auto &symbol : file.symbols) {
if (symbol->name.empty()) {
symbol->outNamePos = 0;
} else {
symbol->outNamePos = static_cast<uint32_t>(strTabSection->data.size());
std::copy(symbol->name.begin(), symbol->name.end(), std::back_inserter(strTabSection->data));
strTabSection->data.push_back(0);
}
}
/* Create .symtab */
symTabSection->header.name = 0;
symTabSection->header.type = elf::SHT_SYMTAB;
symTabSection->header.flags = elf::SHF_ALLOC;
symTabSection->header.addr = 0;
symTabSection->header.offset = -1;
symTabSection->header.size = -1;
symTabSection->header.link = strTabIndex;
symTabSection->header.info = 0;
symTabSection->header.addralign = 4;
symTabSection->header.entsize = sizeof(elf::Symbol);
for (auto &symbol : file.symbols) {
elf::Symbol sym;
auto shndx = getSectionIndex(outSections, symbol->address);
if (symbol->type == elf::STT_SECTION && symbol->address == 0) {
shndx = getSectionIndex(outSections, symbol->name);
}
if (shndx == (uint32_t)-1) {
std::cout << "Could not find section for symbol" << std::endl;
return false;
}
sym.name = symbol->outNamePos;
sym.value = symbol->address;
sym.size = symbol->size;
sym.info = symbol->type | (symbol->binding << 4);
sym.other = 0;
sym.shndx = shndx;
/* Compound symbol crc into section crc */
auto crcSection = outSections[shndx];
if(crcSection->header.type == elf::SHT_RPL_IMPORTS && symbol->type != elf::STT_SECTION) {
auto rplImport = reinterpret_cast<elf::RplImport*>(crcSection->data.data());
rplImport->signature = crc32(rplImport->signature, reinterpret_cast<Bytef *>(strTabSection->data.data() + sym.name),strlen(strTabSection->data.data() + sym.name)+1);
}
/* Append to symtab data */
char *symData = reinterpret_cast<char *>(&sym);
symTabSection->data.insert(symTabSection->data.end(), symData, symData + sizeof(elf::Symbol));
}
/* Finish SHT_RPL_IMPORTS signatures */
Bytef *zero_buffer = reinterpret_cast<Bytef *>(calloc(0x10, 1));
for (auto §ion : outSections) {
if(section->header.type == elf::SHT_RPL_IMPORTS) {
auto rplImport = reinterpret_cast<elf::RplImport*>(section->data.data());
rplImport->signature = crc32(rplImport->signature, zero_buffer, 0xE);
}
}
free(zero_buffer);
/* Create .shstrtab */
shStrTabSection->header.name = 0;
shStrTabSection->header.type = elf::SHT_STRTAB;
shStrTabSection->header.flags = elf::SHF_ALLOC;
shStrTabSection->header.addr = 0;
shStrTabSection->header.offset = -1;
shStrTabSection->header.size = -1;
shStrTabSection->header.link = 0;
shStrTabSection->header.info = 0;
shStrTabSection->header.addralign = 1;
shStrTabSection->header.entsize = 0;
/* Add all section header names to data, update section->header.name */
shStrTabSection->data.push_back(0);
for (auto §ion : outSections) {
if (section->name.empty()) {
section->header.name = 0;
} else {
section->header.name = shStrTabSection->data.size();
std::copy(section->name.begin(), section->name.end(), std::back_inserter(shStrTabSection->data));
shStrTabSection->data.push_back(0);
}
}
loadAddress = 0xC0000000;
/* Update symtab, strtab, shstrtab section addresses */
symTabSection->header.addr = loadAddress;
symTabSection->header.size = symTabSection->data.size();
loadAddress = align_up(symTabSection->header.addr + predictSymTabSize, 16);
strTabSection->header.addr = loadAddress;
strTabSection->header.size = strTabSection->data.size();
loadAddress = align_up(strTabSection->header.addr + predictStrTabSize, 16);
shStrTabSection->header.addr = loadAddress;
shStrTabSection->header.size = shStrTabSection->data.size();
/* Create SHT_RPL_FILEINFO section */
auto fileInfoSection = new OutputSection();
fileInfoSection->header.name = 0;
fileInfoSection->header.type = elf::SHT_RPL_FILEINFO;
fileInfoSection->header.flags = 0;
fileInfoSection->header.addr = 0;
fileInfoSection->header.offset = -1;
fileInfoSection->header.size = -1;
fileInfoSection->header.link = 0;
fileInfoSection->header.info = 0;
fileInfoSection->header.addralign = 4;
fileInfoSection->header.entsize = 0;
elf::RplFileInfo fileInfo;
fileInfo.version = 0xCAFE0402;
fileInfo.textSize = 0;
fileInfo.textAlign = 32;
fileInfo.dataSize = 0;
fileInfo.dataAlign = 4096;
fileInfo.loadSize = 0;
fileInfo.loadAlign = 4;
fileInfo.tempSize = 0;
fileInfo.trampAdjust = 0;
fileInfo.trampAddition = 0;
fileInfo.sdaBase = 0;
fileInfo.sda2Base = 0;
fileInfo.stackSize = 0x10000;
fileInfo.heapSize = 0x8000;
fileInfo.filename = 0;
fileInfo.flags = elf::RPL_IS_RPX;
fileInfo.minVersion = 0x5078;
fileInfo.compressionLevel = -1;
fileInfo.fileInfoPad = 0;
fileInfo.cafeSdkVersion = 0x51BA;
fileInfo.cafeSdkRevision = 0xCCD1;
fileInfo.tlsAlignShift = 0;
fileInfo.tlsModuleIndex = 0;
fileInfo.runtimeFileInfoSize = 0;
fileInfo.tagOffset = 0;
/* Count file info textSize, dataSize, loadSize */
for (auto §ion : outSections) {
auto size = section->data.size();
if (section->header.type == elf::SHT_NOBITS) {
size = section->header.size;
}
if (section->header.addr >= CodeAddress && section->header.addr < DataAddress) {
auto val = section->header.addr.value() + section->header.size.value() - CodeAddress;
if(val > fileInfo.textSize) {
fileInfo.textSize = val;
}
} else if (section->header.addr >= DataAddress && section->header.addr < WiiuLoadAddress) {
auto val = section->header.addr.value() + section->header.size.value() - DataAddress;
if(val > fileInfo.dataSize) {
fileInfo.dataSize = val;
}
} else if (section->header.addr >= WiiuLoadAddress) {
auto val = section->header.addr.value() + section->header.size.value() - WiiuLoadAddress;
if(val > fileInfo.loadSize) {
fileInfo.loadSize = val;
}
} else if (section->header.addr == 0 && section->header.type != elf::SHT_RPL_CRCS && section->header.type != elf::SHT_RPL_FILEINFO) {
fileInfo.tempSize += (size + 128);
}
}
/* TODO: These were calculated based on observation, however some games differ. */
fileInfo.sdaBase = align_up(DataAddress + fileInfo.dataSize + fileInfo.heapSize, 64);
fileInfo.sda2Base = align_up(DataAddress + fileInfo.heapSize, 64);
char *fileInfoData = reinterpret_cast<char *>(&fileInfo);
fileInfoSection->data.insert(fileInfoSection->data.end(), fileInfoData, fileInfoData + sizeof(elf::RplFileInfo));
/* Create SHT_RPL_CRCS section */
auto crcSection = new OutputSection();
crcSection->header.name = 0;
crcSection->header.type = elf::SHT_RPL_CRCS;
crcSection->header.flags = 0;
crcSection->header.addr = 0;
crcSection->header.offset = -1;
crcSection->header.size = -1;
crcSection->header.link = 0;
crcSection->header.info = 0;
crcSection->header.addralign = 4;
crcSection->header.entsize = 4;
outSections.push_back(crcSection);
outSections.push_back(fileInfoSection);
std::vector<uint32_t> sectionCRCs;
for (auto §ion : outSections) {
auto crc = 0u;
if (!section->data.empty()) {
crc = crc32(0, Z_NULL, 0);
crc = crc32(crc, reinterpret_cast<Bytef *>(section->data.data()), section->data.size());
}
sectionCRCs.push_back(byte_swap(crc));
}
char *crcData = reinterpret_cast<char *>(sectionCRCs.data());
crcSection->data.insert(crcSection->data.end(), crcData, crcData + sizeof(uint32_t) * sectionCRCs.size());
/* Update section sizes and offsets */
auto shoff = align_up(sizeof(elf::Header), 64);
auto dataOffset = align_up(shoff + outSections.size() * sizeof(elf::SectionHeader), 64);
/* Add CRC and FileInfo sections first */
for (auto §ion : outSections) {
if (section->header.type != elf::SHT_RPL_CRCS && section->header.type != elf::SHT_RPL_FILEINFO) {
continue;
}
if (section->header.type != elf::SHT_NOBITS) {
section->header.size = section->data.size();
}
if (!section->data.empty()) {
section->header.offset = dataOffset;
dataOffset = align_up(section->header.offset + section->data.size(), 64);
} else {
section->header.offset = 0;
}
}
/* Add data sections next */
for (auto §ion : outSections) {
if(section->header.offset != -1) {
continue;
}
if (section->header.addr < DataAddress || section->header.addr >= WiiuLoadAddress) {
continue;
}
if (section->header.type != elf::SHT_NOBITS) {
section->header.size = section->data.size();
}
if (!section->data.empty()) {
section->header.offset = dataOffset;
dataOffset = align_up(section->header.offset + section->data.size(), 64);
} else {
section->header.offset = 0;
}
}
/* Add load sections next */
for (auto §ion : outSections) {
if(section->header.offset != -1) {
continue;
}
if (section->header.addr < WiiuLoadAddress) {
continue;
}
if (section->header.type != elf::SHT_NOBITS) {
section->header.size = section->data.size();
}
if (!section->data.empty()) {
section->header.offset = dataOffset;
dataOffset = align_up(section->header.offset + section->data.size(), 64);
} else {
section->header.offset = 0;
}
}
/* Everything else */
for (auto §ion : outSections) {
if(section->header.offset != -1) {
continue;
}
if (section->header.type != elf::SHT_NOBITS) {
section->header.size = section->data.size();
}
if (!section->data.empty()) {
section->header.offset = dataOffset;
dataOffset = align_up(section->header.offset + section->data.size(), 64);
} else {
section->header.offset = 0;
}
}
/* Write to file */
std::ofstream out { filename, std::ofstream::binary };
std::vector<char> padding;
if (!out.is_open()) {
std::cout << "Could not open " << filename << " for writing" << std::endl;
return false;
}
elf::Header header;
header.magic = elf::HeaderMagic;
header.fileClass = 1;
header.encoding = elf::ELFDATA2MSB;
header.elfVersion = elf::EV_CURRENT;
header.abi = elf::EABI_CAFE;
memset(&header.pad, 0, 7);
header.type = 0xFE01;
header.machine = elf::EM_PPC;
header.version = 1;
header.entry = file.entryPoint;
header.phoff = 0;
header.phentsize = 0;
header.phnum = 0;
header.shoff = shoff;
header.shnum = outSections.size();
header.shentsize = sizeof(elf::SectionHeader);
header.flags = 0;
header.ehsize = sizeof(elf::Header);
header.shstrndx = shStrTabIndex;
out.write(reinterpret_cast<char *>(&header), sizeof(elf::Header));
/* Write section headers */
out.seekp(header.shoff.value());
for (auto §ion : outSections) {
out.write(reinterpret_cast<char *>(§ion->header), sizeof(elf::SectionHeader));
}
/* Write section data */
for (auto §ion : outSections) {
if (!section->data.empty()) {
out.seekp(section->header.offset.value());
out.write(section->data.data(), section->data.size());
}
}
return true;
}
int main(int argc, char **argv)
{
if (argc < 3) {
std::cout << "Usage: " << argv[0] << " <src> <dst>" << std::endl;
return -1;
}
ElfFile elf;
auto src = argv[1];
auto dst = argv[2];
if (!read(elf, src)) {
return -1;
}
if (!write(elf, dst)) {
return -1;
}
return 0;
}
| Monroe88/RetroArch | wiiu/wut/elf2rpl/main.cpp | C++ | gpl-3.0 | 38,595 |
<html lang="en">
<head>
<title>AVR-Modifiers - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="AVR-Syntax.html#AVR-Syntax" title="AVR Syntax">
<link rel="prev" href="AVR_002dRegs.html#AVR_002dRegs" title="AVR-Regs">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="AVR-Modifiers"></a>
<a name="AVR_002dModifiers"></a>
Previous: <a rel="previous" accesskey="p" href="AVR_002dRegs.html#AVR_002dRegs">AVR-Regs</a>,
Up: <a rel="up" accesskey="u" href="AVR-Syntax.html#AVR-Syntax">AVR Syntax</a>
<hr>
</div>
<h5 class="subsubsection">9.5.2.3 Relocatable Expression Modifiers</h5>
<p><a name="index-AVR-modifiers-799"></a><a name="index-syntax_002c-AVR-800"></a>
The assembler supports several modifiers when using relocatable addresses
in AVR instruction operands. The general syntax is the following:
<pre class="smallexample"> modifier(relocatable-expression)
</pre>
<a name="index-symbol-modifiers-801"></a>
<dl>
<dt><code>lo8</code><dd>
This modifier allows you to use bits 0 through 7 of
an address expression as 8 bit relocatable expression.
<br><dt><code>hi8</code><dd>
This modifier allows you to use bits 7 through 15 of an address expression
as 8 bit relocatable expression. This is useful with, for example, the
AVR ‘<samp><span class="samp">ldi</span></samp>’ instruction and ‘<samp><span class="samp">lo8</span></samp>’ modifier.
<p>For example
<pre class="smallexample"> ldi r26, lo8(sym+10)
ldi r27, hi8(sym+10)
</pre>
<br><dt><code>hh8</code><dd>
This modifier allows you to use bits 16 through 23 of
an address expression as 8 bit relocatable expression.
Also, can be useful for loading 32 bit constants.
<br><dt><code>hlo8</code><dd>
Synonym of ‘<samp><span class="samp">hh8</span></samp>’.
<br><dt><code>hhi8</code><dd>
This modifier allows you to use bits 24 through 31 of
an expression as 8 bit expression. This is useful with, for example, the
AVR ‘<samp><span class="samp">ldi</span></samp>’ instruction and ‘<samp><span class="samp">lo8</span></samp>’, ‘<samp><span class="samp">hi8</span></samp>’, ‘<samp><span class="samp">hlo8</span></samp>’,
‘<samp><span class="samp">hhi8</span></samp>’, modifier.
<p>For example
<pre class="smallexample"> ldi r26, lo8(285774925)
ldi r27, hi8(285774925)
ldi r28, hlo8(285774925)
ldi r29, hhi8(285774925)
; r29,r28,r27,r26 = 285774925
</pre>
<br><dt><code>pm_lo8</code><dd>
This modifier allows you to use bits 0 through 7 of
an address expression as 8 bit relocatable expression.
This modifier useful for addressing data or code from
Flash/Program memory. The using of ‘<samp><span class="samp">pm_lo8</span></samp>’ similar
to ‘<samp><span class="samp">lo8</span></samp>’.
<br><dt><code>pm_hi8</code><dd>
This modifier allows you to use bits 8 through 15 of
an address expression as 8 bit relocatable expression.
This modifier useful for addressing data or code from
Flash/Program memory.
<br><dt><code>pm_hh8</code><dd>
This modifier allows you to use bits 15 through 23 of
an address expression as 8 bit relocatable expression.
This modifier useful for addressing data or code from
Flash/Program memory.
</dl>
</body></html>
| FabianKnapp/nexmon | buildtools/gcc-arm-none-eabi-5_4-2016q2-linux-x86/share/doc/gcc-arm-none-eabi/html/as.html/AVR_002dModifiers.html | HTML | gpl-3.0 | 4,696 |
#ifdef _MSC_VER
#pragma warning (disable : 4786 4114 4018 4267 4244 4702 4710)
#endif
#include <math.h>
#include "lcomb.hpp"
#include <vector>
using namespace std;
vector<double> p_fact;
vector<vector<double> > p_comb;
vector<vector<double> > p_stirling2;
vector<double> p_bell;
vector<double> p_logfact;
vector<vector<double> > p_logcomb;
bool init_p() {
p_fact.push_back(1);
p_logfact.push_back(0);
p_stirling2.push_back(vector<double>());
p_stirling2.back().push_back(0);
return 0;
}
bool to_init = init_p();
double fact(const int &n)
{
int sze = p_fact.size();
if (sze <= n) {
p_fact.reserve(n+1);
float bk = p_fact.back();
for(; sze <= n; sze++)
p_fact.push_back(bk *= float(sze));
}
return p_fact[n];
}
double comb(const int &n, const int &k)
{ if ((int(p_comb.size())>n) && (int(p_comb[n].size())>k)) {
double &res = p_comb[n][k];
if (res<0)
res = fact(n)/fact(k)/fact(n-k);
return res;
}
p_comb.reserve(n+1);
{ for(int i = n-p_comb.size()+1; i--; )
p_comb.push_back(vector<double>());
}
vector<double> &line = p_comb[n];
line.reserve(k+1);
{ for(int i = k-line.size()+1; i--; )
line.push_back(-1);
}
line[k] = fact(n)/fact(k)/fact(n-k);
return line[k];
}
double stirling2(const int &n, const int &k)
{ if ((k<1) || (k>n))
return 0.0;
if ((k==1) || (k==n))
return 1.0;
if ((n<int(p_stirling2.size())) && (k<int(p_stirling2[n].size()))) {
double &res = p_stirling2[n][k];
if (res<0)
res = k*stirling2(n-1,k) + stirling2(n-1,k-1);
return res;
}
if (n >= int(p_stirling2.size())) {
p_stirling2.reserve(n+1);
{ for(int i = n-p_stirling2.size()+1; i--; )
p_stirling2.push_back(vector<double>());
}
}
vector<double> &line = p_stirling2[n];
if (k >= int(line.size())) {
line.reserve(k+1);
{ for(int i = k-line.size()+1; i--; )
line.push_back(-1);
}
}
line[k] = k*stirling2(n-1,k) + stirling2(n-1,k-1);
return line[k];
}
double bell(const int &n)
{ double res = 0.0;
for(int i = 1; i <= n; res += (stirling2(n, i++)));
return res;
}
double log(double);
const float log_of_2 = log(2.0);
double logfact(const int &n)
{
if (int(p_logfact.size()) <= n) {
p_logfact.reserve(n+1);
float bk = p_logfact.back();
for(int sze = p_logfact.size(); sze<=n; sze++)
p_logfact.push_back(bk += log(float(sze))/log_of_2);
}
return p_logfact[n];
}
double logcomb(const int &n, const int &k)
{ if ((int(p_logcomb.size())>n) && (int(p_logcomb[n].size())>k)) {
double &res = p_logcomb[n][k];
if (res==-99.0)
res = logfact(n)-logfact(k)-logfact(n-k);
return res;
}
p_comb.reserve(n+1);
{ for(int i = n-p_logcomb.size()+1; i--; )
p_logcomb.push_back(vector<double>());
}
vector<double> &line = p_logcomb[n];
line.reserve(k+1);
{ for(int i = k-line.size()+1; i--; )
line.push_back(-99.0);
}
line[k] = logfact(n)-logfact(k)-logfact(n-k);
return line[k];
}
| jlegendary/orange | source/include/lcomb.cpp | C++ | gpl-3.0 | 3,016 |
<?php
/**
* This file is the entry point for ResourceLoader.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @author Roan Kattouw
* @author Trevor Parscal
*/
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MediaWikiServices;
// This endpoint is supposed to be independent of request cookies and other
// details of the session. Enforce this constraint with respect to session use.
define( 'MW_NO_SESSION', 1 );
require __DIR__ . '/includes/WebStart.php';
// URL safety checks
if ( !$wgRequest->checkUrlExtension() ) {
return;
}
// Don't initialise ChronologyProtector from object cache, and
// don't wait for unrelated MediaWiki writes when querying ResourceLoader.
MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
'ChronologyProtection' => 'false',
] );
// Set up ResourceLoader
$resourceLoader = new ResourceLoader(
ConfigFactory::getDefaultInstance()->makeConfig( 'main' ),
LoggerFactory::getInstance( 'resourceloader' )
);
$context = new ResourceLoaderContext( $resourceLoader, $wgRequest );
// Respond to ResourceLoader request
$resourceLoader->respond( $context );
Profiler::instance()->setTemplated( true );
$mediawiki = new MediaWiki();
$mediawiki->doPostOutputShutdown( 'fast' );
| micaelbatista/neeist_wiki | wiki/load.php | PHP | gpl-3.0 | 1,965 |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# 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 <http://www.gnu.org/licenses/>.
#
#########################################################################
import logging
from importlib import import_module
from django.apps import AppConfig
from django.conf import settings
from django.db.models import signals
from geonode.tasks.tasks import send_queued_notifications
E = getattr(settings, 'NOTIFICATION_ENABLED', False)
M = getattr(settings, 'NOTIFICATIONS_MODULE', None)
notifications = None
has_notifications = E and M and M in settings.INSTALLED_APPS
if has_notifications:
notifications = import_module(M)
class NotificationsAppConfigBase(AppConfig):
"""
Base class for AppConfig notifications setup
You should subclass it and provide list of notifications
in NOTIFICATIONS attribute to automatically register to
post_migrate signal.
"""
# override in subclass
NOTIFICATIONS = tuple()
def _get_logger(self):
return logging.getLogger(self.__class__.__module__)
def _register_notifications(self, *args, **kwargs):
if has_notifications and notifications:
self._get_logger().debug("Creating notifications")
for label, display, description in self.NOTIFICATIONS:
notifications.models.NoticeType.create(
label, display, description)
def ready(self):
signals.post_migrate.connect(self._register_notifications, sender=self)
def call_celery(func):
def wrap(*args, **kwargs):
ret = func(*args, **kwargs)
if settings.PINAX_NOTIFICATIONS_QUEUE_ALL:
send_queued_notifications.delay()
return ret
return wrap
def send_now_notification(*args, **kwargs):
"""
Simple wrapper around notifications.model send().
This can be called safely if notifications are not installed.
"""
if has_notifications:
return notifications.models.send_now(*args, **kwargs)
@call_celery
def send_notification(*args, **kwargs):
"""
Simple wrapper around notifications.model send().
This can be called safely if notifications are not installed.
"""
if has_notifications:
# queue for further processing if required
if settings.PINAX_NOTIFICATIONS_QUEUE_ALL:
return queue_notification(*args, **kwargs)
try:
return notifications.models.send(*args, **kwargs)
except Exception:
logging.exception("Could not send notifications.")
return False
def queue_notification(*args, **kwargs):
if has_notifications:
return notifications.models.queue(*args, **kwargs)
def get_notification_recipients(notice_type_label, exclude_user=None):
""" Get notification recipients
"""
if not has_notifications:
return []
recipients_ids = notifications.models.NoticeSetting.objects \
.filter(notice_type__label=notice_type_label) \
.values('user')
from geonode.people.models import Profile
profiles = Profile.objects.filter(id__in=recipients_ids)
if exclude_user:
profiles.exclude(username=exclude_user.username)
return profiles
| kartoza/geonode | geonode/notifications_helper.py | Python | gpl-3.0 | 3,847 |
# Copyright (C) 2013 Claudio "nex" Guarnieri (@botherder)
#
# 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 <http://www.gnu.org/licenses/>.
from lib.cuckoo.common.abstracts import Signature
class NetworkIRC(Signature):
name = "network_irc"
description = "Connects to an IRC server, possibly part of a botnet"
severity = 3
categories = ["irc"]
authors = ["nex"]
minimum = "0.6"
def run(self):
if "irc" in self.results["network"]:
if len(self.results["network"]["irc"]) > 0:
return True
return False
| 0x00ach/zer0m0n | signatures/network_irc.py | Python | gpl-3.0 | 1,128 |
-----------------------------------
-- Area: Windurst Waters
-- NPC: Gordias
-- Working 100%
-----------------------------------
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x258);
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;
| hooksta4/darkstar | scripts/zones/zones/Windurst_Waters/npcs/Gordias.lua | Lua | gpl-3.0 | 855 |
<?php
/*
* Copyright 2014 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.
*/
class Google_Service_Compute_NetworkEndpointGroupAppEngine extends Google_Model
{
public $service;
public $urlMask;
public $version;
public function setService($service)
{
$this->service = $service;
}
public function getService()
{
return $this->service;
}
public function setUrlMask($urlMask)
{
$this->urlMask = $urlMask;
}
public function getUrlMask()
{
return $this->urlMask;
}
public function setVersion($version)
{
$this->version = $version;
}
public function getVersion()
{
return $this->version;
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/Compute/NetworkEndpointGroupAppEngine.php | PHP | gpl-3.0 | 1,172 |
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// 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.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RECTANGLESHAPE_HPP
#define SFML_RECTANGLESHAPE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Shape.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Specialized shape representing a rectangle
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RectangleShape : public Shape
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// \param size Size of the rectangle
///
////////////////////////////////////////////////////////////
explicit RectangleShape(const Vector2f& size = Vector2f(0, 0));
////////////////////////////////////////////////////////////
/// \brief Set the size of the rectangle
///
/// \param size New size of the rectangle
///
/// \see getSize
///
////////////////////////////////////////////////////////////
void setSize(const Vector2f& size);
////////////////////////////////////////////////////////////
/// \brief Get the size of the rectangle
///
/// \return Size of the rectangle
///
/// \see setSize
///
////////////////////////////////////////////////////////////
const Vector2f& getSize() const;
////////////////////////////////////////////////////////////
/// \brief Get the number of points defining the shape
///
/// \return Number of points of the shape
///
////////////////////////////////////////////////////////////
virtual unsigned int getPointCount() const;
////////////////////////////////////////////////////////////
/// \brief Get a point of the shape
///
/// The result is undefined if \a index is out of the valid range.
///
/// \param index Index of the point to get, in range [0 .. getPointCount() - 1]
///
/// \return Index-th point of the shape
///
////////////////////////////////////////////////////////////
virtual Vector2f getPoint(unsigned int index) const;
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vector2f m_size; ///< Size of the rectangle
};
} // namespace sf
#endif // SFML_RECTANGLESHAPE_HPP
////////////////////////////////////////////////////////////
/// \class sf::RectangleShape
/// \ingroup graphics
///
/// This class inherits all the functions of sf::Transformable
/// (position, rotation, scale, bounds, ...) as well as the
/// functions of sf::Shape (outline, color, texture, ...).
///
/// Usage example:
/// \code
/// sf::RectangleShape rectangle;
/// rectangle.setSize(sf::Vector2f(100, 50));
/// rectangle.setOutlineColor(sf::Color::Red);
/// rectangle.setOutlineThickness(5);
/// rectangle.setPosition(10, 20);
/// ...
/// window.draw(rectangle);
/// \endcode
///
/// \see sf::Shape, sf::CircleShape, sf::ConvexShape
///
////////////////////////////////////////////////////////////
| N00byEdge/ProjectDurr | lib/SFML/include/SFML/Graphics/RectangleShape.hpp | C++ | gpl-3.0 | 4,392 |
source: Installation/Installation-Ubuntu-1604-Apache.md
> NOTE: These instructions assume you are the root user. If you are not, prepend `sudo` to the shell commands (the ones that aren't at `mysql>` prompts) or temporarily become a user with root privileges with `sudo -s` or `sudo -i`.
### DB Server ###
> NOTE: Whilst we are working on ensuring LibreNMS is compatible with MySQL strict mode, for now, please disable this after mysql is installed.
#### Install / Configure MySQL
```bash
apt-get install mariadb-server mariadb-client
systemctl restart mysql
mysql -uroot -p
```
```sql
CREATE DATABASE librenms CHARACTER SET utf8 COLLATE utf8_unicode_ci;
CREATE USER 'librenms'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON librenms.* TO 'librenms'@'localhost';
FLUSH PRIVILEGES;
exit
```
`vim /etc/mysql/mariadb.conf.d/50-server.cnf`
Within the [mysqld] section please add:
```bash
innodb_file_per_table=1
sql-mode=""
```
```systemctl restart mysql```
### Web Server ###
#### Install / Configure Apache
`apt-get install libapache2-mod-php7.0 php7.0-cli php7.0-mysql php7.0-gd php7.0-snmp php-pear php7.0-curl snmp graphviz php7.0-mcrypt php7.0-json apache2 fping imagemagick whois mtr-tiny nmap python-mysqldb snmpd php-net-ipv4 php-net-ipv6 rrdtool git`
In `/etc/php/7.0/apache2/php.ini` and `/etc/php/7.0/cli/php.ini`, ensure date.timezone is set to your preferred time zone. See http://php.net/manual/en/timezones.php for a list of supported timezones. Valid examples are: "America/New_York", "Australia/Brisbane", "Etc/UTC".
```bash
a2enmod php7.0
a2dismod mpm_event
a2enmod mpm_prefork
phpenmod mcrypt
```
#### Add librenms user
```bash
useradd librenms -d /opt/librenms -M -r
usermod -a -G librenms www-data
```
#### Clone repo
```bash
cd /opt
git clone https://github.com/librenms/librenms.git librenms
```
#### Web interface
```bash
cd /opt/librenms
mkdir rrd logs
chmod 775 rrd
vim /etc/apache2/sites-available/librenms.conf
```
Add the following config:
```apache
<VirtualHost *:80>
DocumentRoot /opt/librenms/html/
ServerName librenms.example.com
CustomLog /opt/librenms/logs/access_log combined
ErrorLog /opt/librenms/logs/error_log
AllowEncodedSlashes NoDecode
<Directory "/opt/librenms/html/">
Require all granted
AllowOverride All
Options FollowSymLinks MultiViews
</Directory>
</VirtualHost>
```
```bash
a2ensite librenms.conf
a2enmod rewrite
systemctl restart apache2
```
> NOTE: If this is the only site you are hosting on this server (it should be :)) then you will need to disable the default site.
`a2dissite 000-default`
#### Web installer
Now head to: http://librenms.example.com/install.php and follow the on-screen instructions.
#### Configure snmpd
```bash
cp /opt/librenms/snmpd.conf.example /etc/snmp/snmpd.conf
vim /etc/snmp/snmpd.conf
```
Edit the text which says `RANDOMSTRINGGOESHERE` and set your own community string.
```bash
curl -o /usr/bin/distro https://raw.githubusercontent.com/librenms/librenms-agent/master/snmp/distro
chmod +x /usr/bin/distro
systemctl restart snmpd
```
#### Cron job
`cp librenms.nonroot.cron /etc/cron.d/librenms`
#### Copy logrotate config
LibreNMS keeps logs in `/opt/librenms/logs`. Over time these can become large and be rotated out. To rotate out the old logs you can use the provided logrotate config file:
cp misc/librenms.logrotate /etc/logrotate.d/librenms
#### Final steps
```bash
chown -R librenms:librenms /opt/librenms
```
Run validate.php as root in the librenms directory:
```bash
cd /opt/librenms
./validate.php
```
That's it! You now should be able to log in to http://librenms.example.com/. Please note that we have not covered HTTPS setup in this example, so your LibreNMS install is not secure by default. Please do not expose it to the public Internet unless you have configured HTTPS and taken appropriate web server hardening steps.
#### Add first device
We now suggest that you add localhost as your first device from within the WebUI.
#### What next?
Now that you've installed LibreNMS, we'd suggest that you have a read of a few other docs to get you going:
- [Performance tuning](http://docs.librenms.org/Support/Performance)
- [Alerting](http://docs.librenms.org/Extensions/Alerting/)
- [Device Groups](http://docs.librenms.org/Extensions/Device-Groups/)
- [Auto discovery](http://docs.librenms.org/Extensions/Auto-Discovery/)
#### Closing
We hope you enjoy using LibreNMS. If you do, it would be great if you would consider opting into the stats system we have, please see [this page](http://docs.librenms.org/General/Callback-Stats-and-Privacy/) on what it is and how to enable it.
| worton/librenms | doc/Installation/Installation-Ubuntu-1604-Apache.md | Markdown | gpl-3.0 | 4,681 |
/*
* Copyright (C) 2010 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.
*/
package dot.junit.opcodes.invoke_virtual.d;
public class T_invoke_virtual_19 extends TSuper {
public int run() {
return 0;
}
}
| s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_virtual/d/T_invoke_virtual_19.java | Java | gpl-3.0 | 765 |
<html lang="en">
<head>
<title>In-Process Agent - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="JIT-Interface.html#JIT-Interface" title="JIT Interface">
<link rel="next" href="GDB-Bugs.html#GDB-Bugs" title="GDB Bugs">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="In-Process-Agent"></a>
<a name="In_002dProcess-Agent"></a>
Next: <a rel="next" accesskey="n" href="GDB-Bugs.html#GDB-Bugs">GDB Bugs</a>,
Previous: <a rel="previous" accesskey="p" href="JIT-Interface.html#JIT-Interface">JIT Interface</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr>
</div>
<h2 class="chapter">30 In-Process Agent</h2>
<p><a name="index-debugging-agent-3049"></a>The traditional debugging model is conceptually low-speed, but works fine,
because most bugs can be reproduced in debugging-mode execution. However,
as multi-core or many-core processors are becoming mainstream, and
multi-threaded programs become more and more popular, there should be more
and more bugs that only manifest themselves at normal-mode execution, for
example, thread races, because debugger's interference with the program's
timing may conceal the bugs. On the other hand, in some applications,
it is not feasible for the debugger to interrupt the program's execution
long enough for the developer to learn anything helpful about its behavior.
If the program's correctness depends on its real-time behavior, delays
introduced by a debugger might cause the program to fail, even when the
code itself is correct. It is useful to be able to observe the program's
behavior without interrupting it.
<p>Therefore, traditional debugging model is too intrusive to reproduce
some bugs. In order to reduce the interference with the program, we can
reduce the number of operations performed by debugger. The
<dfn>In-Process Agent</dfn>, a shared library, is running within the same
process with inferior, and is able to perform some debugging operations
itself. As a result, debugger is only involved when necessary, and
performance of debugging can be improved accordingly. Note that
interference with program can be reduced but can't be removed completely,
because the in-process agent will still stop or slow down the program.
<p>The in-process agent can interpret and execute Agent Expressions
(see <a href="Agent-Expressions.html#Agent-Expressions">Agent Expressions</a>) during performing debugging operations. The
agent expressions can be used for different purposes, such as collecting
data in tracepoints, and condition evaluation in breakpoints.
<p><a name="Control-Agent"></a>You can control whether the in-process agent is used as an aid for
debugging with the following commands:
<a name="index-set-agent-on-3050"></a>
<dl><dt><code>set agent on</code><dd>Causes the in-process agent to perform some operations on behalf of the
debugger. Just which operations requested by the user will be done
by the in-process agent depends on the its capabilities. For example,
if you request to evaluate breakpoint conditions in the in-process agent,
and the in-process agent has such capability as well, then breakpoint
conditions will be evaluated in the in-process agent.
<p><a name="index-set-agent-off-3051"></a><br><dt><code>set agent off</code><dd>Disables execution of debugging operations by the in-process agent. All
of the operations will be performed by <span class="sc">gdb</span>.
<p><a name="index-show-agent-3052"></a><br><dt><code>show agent</code><dd>Display the current setting of execution of debugging operations by
the in-process agent.
</dl>
<ul class="menu">
<li><a accesskey="1" href="In_002dProcess-Agent-Protocol.html#In_002dProcess-Agent-Protocol">In-Process Agent Protocol</a>
</ul>
</body></html>
| FabianKnapp/nexmon | buildtools/gcc-arm-none-eabi-5_4-2016q2-linux-x86/share/doc/gcc-arm-none-eabi/html/gdb/In_002dProcess-Agent.html | HTML | gpl-3.0 | 5,265 |
-----------------------------------------
-- ID: 4128
-- Item: Ether
-- Item Effect: Restores 10 MP
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/msg");
function onItemCheck(target)
if (target:getMP() == target:getMaxMP()) then
return msgBasic.ITEM_UNABLE_TO_USE;
end
return 0;
end;
function onItemUse(target)
target:messageBasic(msgBasic.RECOVERS_MP,0,target:addMP(10*ITEM_POWER));
end;
| Whitechaser/darkstar | scripts/globals/items/bottle_of_mulsum.lua | Lua | gpl-3.0 | 472 |
# Worker WPT tests
These are the workers (`Worker`, `SharedWorker`) tests for the
[Web workers chapter of the HTML Standard](https://html.spec.whatwg.org/multipage/workers.html).
See also
[testharness.js API > Web Workers](https://web-platform-tests.org/writing-tests/testharness-api.html#web-workers).
## Writing `*.any.js`
The easiest and most recommended way to write tests for workers
is to create .any.js-style tests.
Official doc:
[WPT > File Name Flags > Test Features](https://web-platform-tests.org/writing-tests/file-names.html#test-features).
- Standard `testharness.js`-style can be used (and is enforced).
- The same test can be run on window and many types of workers.
- All glue code are automatically generated.
- No need to care about how to create and communicate with each type of workers,
thanks to `fetch_tests_from_worker` in `testharness.js`.
Converting existing tests into `.any.js`-style also has benefits:
- Multiple tests can be merged into one.
- Tests written for window can be run on workers
with a very low development cost.
### How to write tests
If you write `testharness.js`-based tests in `foo.any.js` and
specify types of workers to be tested,
the test can run on any of dedicated, shared and service workers.
See `examples/general.any.js` for example.
Even for testing specific features in a specific type of workers
(e.g. shared worker's `onconnect`), `.any.js`-style tests can be used.
See `examples/onconnect.any.js` for example.
### How to debug tests
Whether each individual test passed or failed,
and its assertion failures (if any) are all reported in the final results.
`console.log()` might not appear in the test results and
thus might not be useful for printf debugging.
For example, in Chromium, this message
- Appears (in stderr) on a window or a dedicated worker, but
- Does NOT appear on a shared worker or a service worker.
### How it works
`.any.js`-style tests use
`fetch_tests_from_worker` functionality of `testharness.js`.
The WPT test server generates necessary glue code
(including generated Document HTML and worker top-level scripts).
See
[serve.py](https://github.com/web-platform-tests/wpt/blob/master/tools/serve/serve.py)
for the actual glue code.
Note that `.any.js` file is not the worker top-level script,
and currently we cannot set response headers to the worker top-level script,
e.g. to set Referrer Policy of the workers.
## Writing `*.worker.js`
Similar to `.any.js`, you can also write `.worker.js`
for tests only for dedicated workers.
Almost the same as `.any.js`, except for the things listed below.
Official doc:
[WPT > File Name Flags > Test Features](https://web-platform-tests.org/writing-tests/file-names.html#test-features).
### How to write tests
You have to write two things manually (which is generated in `.any.js` tests):
- `importScripts("/resources/testharness.js");` at the beginning.
- `done();` at the bottom.
Note: Even if you write `async_test()` or `promise_test()`,
this global `done()` is always needed
(this is different from async_test's `done()`)
for dedicated workers and shared workers.
See official doc:
[testharness.js API > Determining when all tests are complete](https://web-platform-tests.org/writing-tests/testharness-api.html#determining-when-all-tests-are-complete).
See `examples/general.worker.js` for example.
### How it works
`.worker.js`-style tests also use
`fetch_tests_from_worker` functionality of `testharness.js`.
The WPT test server generates glue code in Document HTML-side,
but not for worker top-level scripts.
This is why you have to manually write `importScripts()` etc.
See
[serve.py](https://github.com/web-platform-tests/wpt/blob/master/tools/serve/serve.py)
for the actual glue code.
Unlike `*.any.js` cases, the `*.worker.js` is the worker top-level script.
## Using `fetch_tests_from_worker`
If you need more flexibility,
writing tests using `fetch_tests_from_worker` is the way to go.
For example, when
- Additional processing is needed on the parent Document.
- Workers should be created in a specific way.
- You are writing non-WPT tests using `testharness.js`.
You have to write the main HTMLs and the worker scripts,
but most of the glue code needed for running tests on workers
are provided by `fetch_tests_from_worker`.
### How to write tests
See
- `examples/fetch_tests_from_worker.html` and
`examples/fetch_tests_from_worker.js`.
## Writing the whole tests manually
If `fetch_tests_from_worker` isn't suitable for your specific case
(which should be rare but might be still possible),
you have to write the whole tests,
including the main Document HTML, worker scripts,
and message passing code between them.
TODO: Supply the templates for writing this kind of tests.
| peterjoel/servo | tests/wpt/web-platform-tests/workers/README.md | Markdown | mpl-2.0 | 4,763 |
/*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.objects.accounts.loan;
/**
* Created by nellyk on 2/21/2016.
*/
public class DaysInMonthType {
int id;
int code;
int value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
| coderaashir/android-client | mifosng-android/src/main/java/com/mifos/objects/accounts/loan/DaysInMonthType.java | Java | mpl-2.0 | 661 |
package copystructure
import (
"reflect"
"sync"
"github.com/mitchellh/reflectwalk"
)
// Copy returns a deep copy of v.
func Copy(v interface{}) (interface{}, error) {
return Config{}.Copy(v)
}
// CopierFunc is a function that knows how to deep copy a specific type.
// Register these globally with the Copiers variable.
type CopierFunc func(interface{}) (interface{}, error)
// Copiers is a map of types that behave specially when they are copied.
// If a type is found in this map while deep copying, this function
// will be called to copy it instead of attempting to copy all fields.
//
// The key should be the type, obtained using: reflect.TypeOf(value with type).
//
// It is unsafe to write to this map after Copies have started. If you
// are writing to this map while also copying, wrap all modifications to
// this map as well as to Copy in a mutex.
var Copiers map[reflect.Type]CopierFunc = make(map[reflect.Type]CopierFunc)
type Config struct {
// Lock any types that are a sync.Locker and are not a mutex while copying.
// If there is an RLocker method, use that to get the sync.Locker.
Lock bool
// Copiers is a map of types associated with a CopierFunc. Use the global
// Copiers map if this is nil.
Copiers map[reflect.Type]CopierFunc
}
func (c Config) Copy(v interface{}) (interface{}, error) {
w := new(walker)
if c.Lock {
w.useLocks = true
}
if c.Copiers == nil {
c.Copiers = Copiers
}
err := reflectwalk.Walk(v, w)
if err != nil {
return nil, err
}
// Get the result. If the result is nil, then we want to turn it
// into a typed nil if we can.
result := w.Result
if result == nil {
val := reflect.ValueOf(v)
result = reflect.Indirect(reflect.New(val.Type())).Interface()
}
return result, nil
}
type walker struct {
Result interface{}
depth int
ignoreDepth int
vals []reflect.Value
cs []reflect.Value
ps []bool
// any locks we've taken, indexed by depth
locks []sync.Locker
// take locks while walking the structure
useLocks bool
}
func (w *walker) Enter(l reflectwalk.Location) error {
w.depth++
// ensure we have enough elements to index via w.depth
for w.depth >= len(w.locks) {
w.locks = append(w.locks, nil)
}
return nil
}
func (w *walker) Exit(l reflectwalk.Location) error {
locker := w.locks[w.depth]
w.locks[w.depth] = nil
if locker != nil {
defer locker.Unlock()
}
w.depth--
if w.ignoreDepth > w.depth {
w.ignoreDepth = 0
}
if w.ignoring() {
return nil
}
switch l {
case reflectwalk.Map:
fallthrough
case reflectwalk.Slice:
// Pop map off our container
w.cs = w.cs[:len(w.cs)-1]
case reflectwalk.MapValue:
// Pop off the key and value
mv := w.valPop()
mk := w.valPop()
m := w.cs[len(w.cs)-1]
// If mv is the zero value, SetMapIndex deletes the key form the map,
// or in this case never adds it. We need to create a properly typed
// zero value so that this key can be set.
if !mv.IsValid() {
mv = reflect.Zero(m.Type().Elem())
}
m.SetMapIndex(mk, mv)
case reflectwalk.SliceElem:
// Pop off the value and the index and set it on the slice
v := w.valPop()
if v.IsValid() {
i := w.valPop().Interface().(int)
s := w.cs[len(w.cs)-1]
se := s.Index(i)
if se.CanSet() {
se.Set(v)
}
}
case reflectwalk.Struct:
w.replacePointerMaybe()
// Remove the struct from the container stack
w.cs = w.cs[:len(w.cs)-1]
case reflectwalk.StructField:
// Pop off the value and the field
v := w.valPop()
f := w.valPop().Interface().(reflect.StructField)
if v.IsValid() {
s := w.cs[len(w.cs)-1]
sf := reflect.Indirect(s).FieldByName(f.Name)
if sf.CanSet() {
sf.Set(v)
}
}
case reflectwalk.WalkLoc:
// Clear out the slices for GC
w.cs = nil
w.vals = nil
}
return nil
}
func (w *walker) Map(m reflect.Value) error {
if w.ignoring() {
return nil
}
w.lock(m)
// Create the map. If the map itself is nil, then just make a nil map
var newMap reflect.Value
if m.IsNil() {
newMap = reflect.Indirect(reflect.New(m.Type()))
} else {
newMap = reflect.MakeMap(m.Type())
}
w.cs = append(w.cs, newMap)
w.valPush(newMap)
return nil
}
func (w *walker) MapElem(m, k, v reflect.Value) error {
return nil
}
func (w *walker) PointerEnter(v bool) error {
if w.ignoring() {
return nil
}
w.ps = append(w.ps, v)
return nil
}
func (w *walker) PointerExit(bool) error {
if w.ignoring() {
return nil
}
w.ps = w.ps[:len(w.ps)-1]
return nil
}
func (w *walker) Primitive(v reflect.Value) error {
if w.ignoring() {
return nil
}
w.lock(v)
// IsValid verifies the v is non-zero and CanInterface verifies
// that we're allowed to read this value (unexported fields).
var newV reflect.Value
if v.IsValid() && v.CanInterface() {
newV = reflect.New(v.Type())
reflect.Indirect(newV).Set(v)
}
w.valPush(newV)
w.replacePointerMaybe()
return nil
}
func (w *walker) Slice(s reflect.Value) error {
if w.ignoring() {
return nil
}
w.lock(s)
var newS reflect.Value
if s.IsNil() {
newS = reflect.Indirect(reflect.New(s.Type()))
} else {
newS = reflect.MakeSlice(s.Type(), s.Len(), s.Cap())
}
w.cs = append(w.cs, newS)
w.valPush(newS)
return nil
}
func (w *walker) SliceElem(i int, elem reflect.Value) error {
if w.ignoring() {
return nil
}
// We don't write the slice here because elem might still be
// arbitrarily complex. Just record the index and continue on.
w.valPush(reflect.ValueOf(i))
return nil
}
func (w *walker) Struct(s reflect.Value) error {
if w.ignoring() {
return nil
}
w.lock(s)
var v reflect.Value
if c, ok := Copiers[s.Type()]; ok {
// We have a Copier for this struct, so we use that copier to
// get the copy, and we ignore anything deeper than this.
w.ignoreDepth = w.depth
dup, err := c(s.Interface())
if err != nil {
return err
}
v = reflect.ValueOf(dup)
} else {
// No copier, we copy ourselves and allow reflectwalk to guide
// us deeper into the structure for copying.
v = reflect.New(s.Type())
}
// Push the value onto the value stack for setting the struct field,
// and add the struct itself to the containers stack in case we walk
// deeper so that its own fields can be modified.
w.valPush(v)
w.cs = append(w.cs, v)
return nil
}
func (w *walker) StructField(f reflect.StructField, v reflect.Value) error {
if w.ignoring() {
return nil
}
// Push the field onto the stack, we'll handle it when we exit
// the struct field in Exit...
w.valPush(reflect.ValueOf(f))
return nil
}
func (w *walker) ignoring() bool {
return w.ignoreDepth > 0 && w.depth >= w.ignoreDepth
}
func (w *walker) pointerPeek() bool {
return w.ps[len(w.ps)-1]
}
func (w *walker) valPop() reflect.Value {
result := w.vals[len(w.vals)-1]
w.vals = w.vals[:len(w.vals)-1]
// If we're out of values, that means we popped everything off. In
// this case, we reset the result so the next pushed value becomes
// the result.
if len(w.vals) == 0 {
w.Result = nil
}
return result
}
func (w *walker) valPush(v reflect.Value) {
w.vals = append(w.vals, v)
// If we haven't set the result yet, then this is the result since
// it is the first (outermost) value we're seeing.
if w.Result == nil && v.IsValid() {
w.Result = v.Interface()
}
}
func (w *walker) replacePointerMaybe() {
// Determine the last pointer value. If it is NOT a pointer, then
// we need to push that onto the stack.
if !w.pointerPeek() {
w.valPush(reflect.Indirect(w.valPop()))
}
}
// if this value is a Locker, lock it and add it to the locks slice
func (w *walker) lock(v reflect.Value) {
if !w.useLocks {
return
}
if !v.IsValid() || !v.CanInterface() {
return
}
type rlocker interface {
RLocker() sync.Locker
}
var locker sync.Locker
// first check if we can get a locker from the value
switch l := v.Interface().(type) {
case rlocker:
// don't lock a mutex directly
if _, ok := l.(*sync.RWMutex); !ok {
locker = l.RLocker()
}
case sync.Locker:
locker = l
}
// the value itself isn't a locker, so check the method on a pointer too
if locker == nil && v.CanAddr() {
switch l := v.Addr().Interface().(type) {
case rlocker:
// don't lock a mutex directly
if _, ok := l.(*sync.RWMutex); !ok {
locker = l.RLocker()
}
case sync.Locker:
locker = l
}
}
// still no callable locker
if locker == nil {
return
}
// don't lock a mutex directly
switch locker.(type) {
case *sync.Mutex, *sync.RWMutex:
return
}
locker.Lock()
w.locks[w.depth] = locker
}
| optimisticanshul/terraform | vendor/github.com/mitchellh/copystructure/copystructure.go | GO | mpl-2.0 | 8,535 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.nursing.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseHospitalReportImpl extends DomainImpl implements ims.nursing.domain.HospitalReport, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatelistHospitalReports(ims.core.vo.LocMostVo voWard, ims.framework.utils.DateTime fromDateTime, ims.framework.utils.DateTime toDateTime)
{
}
@SuppressWarnings("unused")
public void validatelistLocations(ims.core.vo.LocMostVo locationFilterVo)
{
}
@SuppressWarnings("unused")
public void validatelistHospitalReportsByHospital(ims.core.vo.LocMostVo voHospital, ims.framework.utils.DateTime fromDateTime, ims.framework.utils.DateTime toDateTime)
{
}
@SuppressWarnings("unused")
public void validategetReportAndTemplate(Integer nReportId, Integer nTemplateId)
{
}
@SuppressWarnings("unused")
public void validategetPatientFromCareContext(ims.core.admin.vo.CareContextRefVo voRef)
{
}
}
| open-health-hub/openMAXIMS | openmaxims_workspace/Nursing/src/ims/nursing/domain/base/impl/BaseHospitalReportImpl.java | Java | agpl-3.0 | 2,691 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Florin Blindu using IMS Development Environment (version 1.80 build 4785.23502)
// Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved.
package ims.emergency.domain.impl;
import ims.core.admin.vo.CareContextRefVo;
import ims.core.admin.vo.EpisodeOfCareRefVo;
import ims.core.patient.vo.PatientRefVo;
import ims.core.resource.people.vo.HcpRefVo;
import ims.core.vo.CareContextShortVoCollection;
import ims.core.vo.lookups.HcpDisType;
import ims.core.vo.lookups.Specialty;
import ims.domain.DomainFactory;
import ims.emergency.domain.base.impl.BaseAttendanceNotesCcImpl;
import ims.emergency.helper.EmergencyHelper;
import ims.emergency.helper.IEmergencyHelper;
import ims.emergency.vo.AttendanceClinicalNotesRefVo;
import ims.emergency.vo.AttendanceClinicalNotesVoCollection;
import ims.emergency.vo.domain.AttendanceClinicalNotesVoAssembler;
import ims.emergency.vo.lookups.AttendanceClinicalNoteType;
import ims.framework.exceptions.CodingRuntimeException;
import java.util.ArrayList;
import java.util.List;
public class AttendanceNotesCcImpl extends BaseAttendanceNotesCcImpl
{
private static final long serialVersionUID = 1L;
public AttendanceClinicalNotesVoCollection listNotes(PatientRefVo patient, EpisodeOfCareRefVo episodeOfCare, CareContextRefVo careContext, AttendanceClinicalNoteType noteType, HcpDisType discipline, Specialty specialty, Boolean orderType)
{
if(patient == null)
throw new CodingRuntimeException("Cannot list AttendanceClinicalNotes for a null Patient Id.");
String hql = "from AttendanceClinicalNotes as attClinicalNotes ";
StringBuffer hqlConditions = new StringBuffer();
ArrayList<String> markers = new ArrayList<String>();
ArrayList<Object> values = new ArrayList<Object>();
String andStr = "";
if (patient !=null)
{
hqlConditions.append(andStr);
hqlConditions.append("attClinicalNotes.patient.id = :PatientId ");
markers.add("PatientId");
values.add(patient.getID_Patient());
andStr = " and ";
}
if(careContext != null)
{
hqlConditions.append(andStr);
hqlConditions.append(" attClinicalNotes.attendance.id = :CareContextId ");
markers.add("CareContextId");
values.add(careContext.getID_CareContext());
andStr = " and ";
}
/*
if(episodeOfCare != null)
{
hqlConditions.append(andStr);
hqlConditions.append(" attClinicalNotes.episode.id = :EpisodeOfCareId ");
markers.add("EpisodeOfCareId");
values.add(episodeOfCare.getID_EpisodeOfCare());
andStr = " and ";
}
*/
if (noteType!=null)
{
hqlConditions.append(andStr);
hqlConditions.append("attClinicalNotes.noteType.id = :noteTypeId ");
markers.add("noteTypeId");
values.add(noteType.getID());
andStr = " and ";
}
if (discipline!=null)
{
hqlConditions.append(andStr);
hqlConditions.append("attClinicalNotes.discipline.id = :disciplineId ");
markers.add("disciplineId");
values.add(discipline.getID());
andStr = " and ";
}
if (specialty!=null)
{
hqlConditions.append(andStr);
hqlConditions.append("attClinicalNotes.specialty.id = :specialtyId ");
markers.add("specialtyId");
values.add(specialty.getID());
andStr = " and ";
}
if (hqlConditions.length() > 0)
{
hqlConditions.insert(0, " where (");
hqlConditions.append(" ) ");
}
DomainFactory factory = getDomainFactory();
if (Boolean.TRUE.equals(orderType))
{
hql=hql + hqlConditions.toString() + " order by attClinicalNotes.authoringInformation.authoringDateTime desc";
}
else
{
hql=hql + hqlConditions.toString() + " order by attClinicalNotes.authoringInformation.authoringDateTime asc";
}
List<?> list = factory.find(hql, markers, values);
return AttendanceClinicalNotesVoAssembler.createAttendanceClinicalNotesVoCollectionFromAttendanceClinicalNotes(list);
}
public Specialty getSpecialtyForHCP(HcpRefVo hcpRef, HcpDisType hcpDisType)
{
IEmergencyHelper impl = (IEmergencyHelper)getDomainImpl(EmergencyHelper.class);
return impl.getSpecialtyForHCP(hcpRef, hcpDisType);
}
public CareContextShortVoCollection getCareContextsByPatient(PatientRefVo patientRef)
{
IEmergencyHelper impl = (IEmergencyHelper)getDomainImpl(EmergencyHelper.class);
return impl.getCareContextsByPatient(patientRef);
}
public Boolean isStale(AttendanceClinicalNotesRefVo attendanceClinicalNoteRef)
{
if(attendanceClinicalNoteRef == null)
return false;
DomainFactory factory = getDomainFactory();
List<?> appts = factory.find("select a.id from AttendanceClinicalNotes as a where a.id = :attClinNoteId and a.version > :attClinNoteVersion", new String[] {"attClinNoteId", "attClinNoteVersion"}, new Object[] {attendanceClinicalNoteRef.getID_AttendanceClinicalNotes(), attendanceClinicalNoteRef.getVersion_AttendanceClinicalNotes()});
if(appts != null && appts.size() > 0)
return true;
return false;
}
}
| open-health-hub/openMAXIMS | openmaxims_workspace/Emergency/src/ims/emergency/domain/impl/AttendanceNotesCcImpl.java | Java | agpl-3.0 | 6,359 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2015 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2015. All rights reserved".
********************************************************************************/
/**
* Base class for working with model values and what type they are. Typicall the type would be a zurmo model id,
* another system id, or the name of the model.
*/
abstract class ValueTypeMappingRuleForm extends ModelAttributeMappingRuleForm
{
public $type;
public function rules()
{
return array(array('type', 'required'));
}
public function attributeLabels()
{
return array('type' => Zurmo::t('ImportModule', 'Type of Value'));
}
public static function getAttributeName()
{
return 'type';
}
}
?> | raymondlamwu/zurmotest | app/protected/modules/import/forms/ValueTypeMappingRuleForm.php | PHP | agpl-3.0 | 2,776 |
<?php
return Affinity\Action::create(['core'], function($app, $broker) {
$root_directory = $app['engine']->fetch('view', 'root_directory', 'user/templates');
$broker->define('Inkwell\View', [
':root_directory' => $app->getDirectory($root_directory)
]);
});
| dotink/inkwell-view | plugin/boot/default/view.php | PHP | agpl-3.0 | 270 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Cornel Ventuneac using IMS Development Environment (version 1.80 build 4696.13908)
// Copyright (C) 1995-2012 IMS MAXIMS. All rights reserved.
package ims.clinical.forms.dementiaassessmentamtscomponent;
import ims.clinical.forms.dementiaassessmentamtscomponent.GenForm.GroupMedicationEnumeration;
import ims.clinical.forms.dementiaassessmentamtscomponent.GenForm.GroupPRotocolEnumeration;
import ims.clinical.vo.DementiaAssessAndInvestigateVo;
import ims.clinical.vo.DementiaAssessInvestigateNoteVo;
import ims.clinical.vo.DementiaVo;
import ims.clinical.vo.DementiaWorklistStatusVo;
import ims.clinical.vo.enums.DementiaEventEnumeration;
import ims.clinicaladmin.vo.DementiaTermConfigVo;
import ims.clinicaladmin.vo.lookups.DementiaTermConfig;
import ims.configuration.AppRight;
import ims.configuration.gen.ConfigFlag;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.lookups.DementiaWorklistStatus;
import ims.core.vo.lookups.YesNo;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.DateTime;
public class Logic extends BaseLogic
{
private static final long serialVersionUID = 1L;
protected void onBtnEditClick() throws ims.framework.exceptions.PresentationLogicException
{
edit();
}
private void edit()
{
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.EDIT);
form.fireCustomControlValueChanged();
form.setMode(FormMode.EDIT);
open();
updateControlState();
}
protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
{
if (save())
{
open();
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.RELOAD_AMTS_BROWSER);
else
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.SAVE);
form.fireCustomControlValueChanged();
}
}
private void open()
{
populateScreenFromData();
}
private boolean save()
{
if ( ! validateData(true))
return false;
int nThreshold = 8;//Default as per specification
if (form.getGlobalContext().Admin.getDementiaConfigurationIsNotNull()
&& form.getGlobalContext().Admin.getDementiaConfiguration().getAMTSThresholdScoreIsNotNull())
nThreshold = form.getGlobalContext().Admin.getDementiaConfiguration().getAMTSThresholdScore();
form.getGlobalContext().Clinical.setAMTSRecordToView(null);
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
{
DementiaAssessAndInvestigateVo voAMTSFollowUp = populateDataFromScreen();
if (voAMTSFollowUp.getID_DementiaAssessAndInvestigateIsNotNull())
{
form.getLocalContext().getSelectedRecord().getFollowUpAssessments().set(form.getLocalContext().getSelectedRecord().getFollowUpAssessments().indexOf(voAMTSFollowUp), voAMTSFollowUp);
form.getGlobalContext().Clinical.setAMTSRecordToView(voAMTSFollowUp);
}
else
{
form.getLocalContext().getSelectedRecord().getFollowUpAssessments().add(voAMTSFollowUp);
form.getGlobalContext().Clinical.setAMTSRecordToView(null);
}
}
else
{
form.getLocalContext().getSelectedRecord().setStepTwoAssess(populateDataFromScreen());
form.getLocalContext().getSelectedRecord().setAMTSScore(form.txtTotalScore().getValue() != null ? new Integer(form.txtTotalScore().getValue()) : null);
}
//Create worklist status entry
if ((form.getLocalContext().getinFollowUpMode() == null
|| (form.getLocalContext().getinFollowUpModeIsNotNull()
&& !form.getLocalContext().getinFollowUpMode()) )
&& (form.getLocalContext().getSelectedRecord().getCurrentWorklistStatus().getStatus().equals(DementiaWorklistStatus.STEP_TWO_ASSESS_INVESTIGATE_OUTSTANDING)
|| form.getLocalContext().getSelectedRecord().getCurrentWorklistStatus().getStatus().equals(DementiaWorklistStatus.COMPLETED)
|| form.getLocalContext().getSelectedRecord().getCurrentWorklistStatus().getStatus().equals(DementiaWorklistStatus.FOR_REFERRAL)) )
{
DementiaWorklistStatusVo voStat = new DementiaWorklistStatusVo();
AuthoringInformationVo voAuthor = new AuthoringInformationVo();
voAuthor.setAuthoringDateTime(new DateTime());
if(domain.getHcpUser() != null)
voAuthor.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
voStat.setAuthoringInformation(voAuthor);
if ((new Integer(form.txtTotalScore().getValue()) > nThreshold))
voStat.setStatus(DementiaWorklistStatus.COMPLETED);
else if ((new Integer(form.txtTotalScore().getValue()) == nThreshold))
voStat.setStatus(DementiaWorklistStatus.FOR_REFERRAL);
else if ((new Integer(form.txtTotalScore().getValue()) < nThreshold))
voStat.setStatus(DementiaWorklistStatus.FOR_REFERRAL);
form.getLocalContext().getSelectedRecord().setCurrentWorklistStatus(voStat);
form.getLocalContext().getSelectedRecord().getHistoricalWorklistStatus().add(voStat);
}
String[] str = form.getLocalContext().getSelectedRecord().validate();
if (str != null && str.length > 0)
{
engine.showErrors(str);
return false;
}
try
{
form.getLocalContext().setSelectedRecord(domain.saveDementia(form.getLocalContext().getSelectedRecord()));
}
catch (DomainInterfaceException e)
{
engine.showMessage(e.getMessage());
form.getLocalContext().setSelectedRecord(domain.getDementia(form.getLocalContext().getSelectedRecord()));
open();
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.RELOAD_AMTS_BROWSER);
else
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.SAVE);
form.fireCustomControlValueChanged();
form.setMode(FormMode.VIEW);
return false;
}
catch (StaleObjectException e)
{
engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
form.getLocalContext().setSelectedRecord(domain.getDementia(form.getLocalContext().getSelectedRecord()));
open();
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.SOE); //wdev-16368
else
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.SOE);
form.fireCustomControlValueChanged();
form.setMode(FormMode.VIEW);
return false;
}
form.setMode(FormMode.VIEW);
return true;
}
private boolean validateData(boolean bShowMessage)
{
StringBuffer sb = new StringBuffer();
if (form.lblConfirmMedication().isVisible()
&& form.GroupMedication().getValue().equals(GroupMedicationEnumeration.None))
sb.append(form.lblConfirmMedication().getValue() + " is mandatory.");
if (form.lblConfirmTrust().isVisible()
&& form.GroupPRotocol().getValue().equals(GroupPRotocolEnumeration.None))
{
if (sb.toString().length() >0)
sb.append("\n\n");
sb.append(form.lblConfirmTrust().getValue() + " is mandatory.");
}
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
sb = new StringBuffer();
if (form.txtTotalScore().getValue() == null
|| form.txtTotalScore().getValue().equals(""))
sb.append("Score has not yet been calculated. Finish the assessment and Save again.");
if (sb.toString().length() >0)
{
if (bShowMessage)
engine.showMessage(sb.toString());
return false;
}
return true;
}
private void updateControlState()
{
form.btnEdit().setVisible(false);
form.btnNewFollowUp().setVisible(false);
form.btnEditFollowUp().setVisible(false);
if (form.getMode().equals(FormMode.VIEW))
{
if( form.getLocalContext().getSelectedRecordIsNotNull()
&& form.getLocalContext().getSelectedRecord().getStepTwoAssessIsNotNull()
&& form.getLocalContext().getSelectedRecord().getStepTwoAssess().getID_DementiaAssessAndInvestigateIsNotNull()
&& form.getLocalContext().getSelectedRecord().getStepTwoAssess().getAuthoringInformationIsNotNull()
&& form.getLocalContext().getSelectedRecord().getStepTwoAssess().getAuthoringInformation().getAuthoringHcpIsNotNull()
&& domain.getHcpLiteUser() != null)
{
if ( ((HcpLiteVo) domain.getHcpLiteUser()).equals(form.getLocalContext().getSelectedRecord().getStepTwoAssess().getAuthoringInformation().getAuthoringHcp())
|| (engine.hasRight(AppRight.CAN_EDIT_AND_RIE_DEMENTIA)) )
form.btnEdit().setVisible(true);
}
else if (domain.getHcpLiteUser() != null)
form.btnEdit().setVisible(true);
}
if (form.getMode().equals(FormMode.VIEW)
&& form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
{
if( form.getLocalContext().getSelectedAMTSRecordIsNotNull()
&& form.getLocalContext().getSelectedAMTSRecord().getID_DementiaAssessAndInvestigateIsNotNull()
&& domain.getHcpLiteUser() != null)
{
if( ((HcpLiteVo) domain.getHcpLiteUser()).equals(form.getLocalContext().getSelectedAMTSRecord().getAuthoringInformation().getAuthoringHcp())
|| ( domain.getHcpLiteUser() != null && engine.hasRight(AppRight.CAN_EDIT_AND_RIE_DEMENTIA)) )
form.btnEditFollowUp().setVisible(true);
if (domain.getHcpLiteUser() != null)
form.btnNewFollowUp().setVisible(true);
}
else if (domain.getHcpLiteUser() != null)
form.btnNewFollowUp().setVisible(true);
}
form.btnRIE().setVisible(form.getMode().equals(FormMode.VIEW)
&& form.getLocalContext().getSelectedRecord() != null
&& form.getLocalContext().getSelectedRecord().getStepTwoAssess() !=null
&& ! form.getLocalContext().getinFollowUpMode()
&& engine.hasRight(AppRight.CAN_EDIT_AND_RIE_DEMENTIA) );
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
{
form.txtComment().setVisible(false);
form.btnEdit().setVisible(false);
}
else
form.txtComment().setEnabled(form.getMode().equals(FormMode.EDIT));
form.btnSave().setEnabled(false);
if ( validateData(false))
form.btnSave().setEnabled(form.getMode().equals(FormMode.EDIT));
form.btnSave().setVisible(form.getMode().equals(FormMode.EDIT));
form.btnCancel().setVisible(form.getMode().equals(FormMode.EDIT));
hideShowBottomQuestionsBasedOnThreshold(false);
}
private void populateQuestions()
{
DementiaTermConfig lkpHint = new DementiaTermConfig();
lkpHint.setId(DementiaTermConfig.AMTS_AGE.getID());
DementiaTermConfigVo voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblAge().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_DOB.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblDOB().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_QUESTION.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblRepeat42().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_CURRENT_YEAR.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblCurrentYear().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_CURRENT_TIME.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblCurrentTime().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_HOSP_NAME.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblNameOfHospital().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_TWO_PEOPLE.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblRecognizetwopeople().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_WW_TWO.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblYearOfWW2().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_MONARCH.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblWhoIsMonarch().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_COUNT.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblCountbackwards().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_RECALL_QUESTION.getID());
voHint = domain.getHintByLookupID(lkpHint);
if (voHint != null )
form.lblRecall42().setValue(voHint.getHelpText());
lkpHint.setId(DementiaTermConfig.AMTS_TRUST_PROTOCOL.getID());
voHint = domain.getHintByLookupID(lkpHint);
if ( voHint != null )
{
form.imbConfirmTrustProtocol().setTooltip(voHint.getHelpText());
}
lkpHint.setId(DementiaTermConfig.AMTS_TRUST_PROTOCOL_TEXT.getID());
voHint = domain.getHintByLookupID(lkpHint);
if ( voHint != null )
{
form.lblConfirmTrust().setValue(voHint.getHelpText());
}
lkpHint.setId(DementiaTermConfig.AMTS_MED_REVIEW.getID());
voHint = domain.getHintByLookupID(lkpHint);
if ( voHint != null )
{
form.imbConfirmMedication().setTooltip(voHint.getHelpText());
}
lkpHint.setId(DementiaTermConfig.AMTS_MED_REVIEW_LABEL_TEXT.getID());
voHint = domain.getHintByLookupID(lkpHint);
if ( voHint != null )
{
form.lblConfirmMedication().setValue(voHint.getHelpText());
}
lkpHint.setId(DementiaTermConfig.AMTS_FORM_HELP.getID());
voHint = domain.getHintByLookupID(lkpHint);
if ( voHint != null )
{
form.imbAMTSForm().setTooltip(voHint.getHelpText());
}
}
public void setModeForm(FormMode modeform)
{
form.setMode(modeform);
}
public void initialize()
{
}
private void clearTenQuestions()
{
form.chkAgeYes().setValue(null);
form.chkAgeNo().setValue(null);
form.chkDBYes().setValue(null);
form.chkDBNo().setValue(null);
form.chkCurrentYearYes().setValue(null);
form.chkCurrentYearNo().setValue(null);
form.chkCurrentTimeYes().setValue(null);
form.chkCurrentTimeNo().setValue(null);
form.chkNameHospitalYes().setValue(null);
form.chkNameHospitalNo().setValue(null);
form.chkRecogniseYes().setValue(null);
form.chkRecogniseNo().setValue(null);
form.chkYearWW2Yes().setValue(null);
form.chkYearWW2No().setValue(null);
form.chkMonarchNo().setValue(null);
form.chkMonarchYes().setValue(null);
form.chkCountYes().setValue(null);
form.chkCountNo().setValue(null);
form.chkRecallYes().setValue(null);
form.chkRecallNo().setValue(null);
}
private void clearLastTwoQuestions()
{
form.GroupMedication().setValue(GroupMedicationEnumeration.None);
form.GroupPRotocol().setValue(GroupPRotocolEnumeration.None);
}
private void clearAllControls()
{
clearTenQuestions();
form.txtTotalScore().setValue(null);
form.txtComment().setValue(null);
clearLastTwoQuestions();
}
protected void onFormModeChanged()
{
updateControlState();
}
public DementiaEventEnumeration getSelectedEvent()
{
return form.getLocalContext().getSelectedEvent();
}
protected void onBtnCancelClick() throws PresentationLogicException
{
hideShowBottomQuestionsBasedOnThreshold(false);
open();
form.setMode(FormMode.VIEW);
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.RELOAD_AMTS_BROWSER);
else
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.CANCEL);
form.fireCustomControlValueChanged();
}
@Override
protected void onChkRecallYesValueChanged() throws PresentationLogicException
{
form.chkRecallNo().setValue(false);
calculateAndDisplayScore();
}
private void hideShowBottomQuestionsBasedOnThreshold(Boolean hideshow)
{
int nThreshold = 8;//Default as per specification
boolean bThresholdExceeded = false;
boolean bDelerium = false;
boolean bAllCompleted = false;
if (form.getGlobalContext().Admin.getDementiaConfigurationIsNotNull()
&& form.getGlobalContext().Admin.getDementiaConfiguration().getAMTSThresholdScoreIsNotNull())
nThreshold = form.getGlobalContext().Admin.getDementiaConfiguration().getAMTSThresholdScore();
if (form.txtTotalScore().getValue() != ""
&& form.txtTotalScore().getValue() != null)
bAllCompleted = true;
if (form.txtTotalScore().getValue() != ""
&& form.txtTotalScore().getValue() != null ? new Integer(form.txtTotalScore().getValue()) <= nThreshold : false)
{
hideshow = true;
bThresholdExceeded = true;
}
else
hideshow = false;
if (form.getLocalContext().getSelectedRecordIsNotNull()
&& form.getLocalContext().getSelectedRecord().getDeliriumConfirmedIsNotNull()
&& form.getLocalContext().getSelectedRecord().getDeliriumConfirmed())
{
hideshow = true;
bDelerium = true;
}
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
{
form.txtComment().setVisible(false);
form.lblComment().setVisible(false);
form.lblComment1().setVisible(false); //wdev-16421
hideshow = false;
}
form.imbConfirmTrustProtocol().setVisible(hideshow);
if (hideshow)
form.imbConfirmTrustProtocol().setEnabled(false);
form.lblConfirmTrust().setVisible(hideshow);
form.GroupPRotocol().setVisible(hideshow);
form.GroupPRotocol().setEnabled(form.getMode().equals(FormMode.EDIT) && (bThresholdExceeded || (bAllCompleted && bDelerium)) );
form.imbConfirmMedication().setVisible(hideshow);
if (hideshow)
form.imbConfirmMedication().setEnabled(false);
form.lblConfirmMedication().setVisible(hideshow);
form.GroupMedication().setVisible(hideshow);
form.GroupMedication().setEnabled(form.getMode().equals(FormMode.EDIT) && (bThresholdExceeded || (bAllCompleted && bDelerium)) );
form.hzl34().setVisible(hideshow);
form.hzl35().setVisible(hideshow);
}
private void calculateAndDisplayScore()
{
int nScore =0;
form.txtTotalScore().setValue("");
if (form.chkAgeYes().getValue())
nScore++;
if (form.chkDBYes().getValue())
nScore++;
if (form.chkCurrentYearYes().getValue())
nScore++;
if (form.chkCurrentTimeYes().getValue())
nScore++;
if (form.chkNameHospitalYes().getValue())
nScore++;
if (form.chkRecogniseYes().getValue())
nScore++;
if (form.chkYearWW2Yes().getValue())
nScore++;
if (form.chkMonarchYes().getValue())
nScore++;
if (form.chkCountYes().getValue())
nScore++;
if (form.chkRecallYes().getValue())
nScore++;
form.btnSave().setEnabled(false);
if ( (form.chkAgeYes().getValue() || form.chkAgeNo().getValue())
&& (form.chkDBYes().getValue() || form.chkDBNo().getValue())
&& (form.chkCurrentYearYes().getValue() || form.chkCurrentYearNo().getValue())
&& (form.chkCurrentTimeYes().getValue() || form.chkCurrentTimeNo().getValue())
&& (form.chkNameHospitalYes().getValue() || form.chkNameHospitalNo().getValue())
&& (form.chkRecogniseYes().getValue() || form.chkRecogniseNo().getValue())
&& (form.chkYearWW2Yes().getValue() || form.chkYearWW2No().getValue())
&& (form.chkMonarchYes().getValue() || form.chkMonarchNo().getValue())
&& (form.chkCountYes().getValue() || form.chkCountNo().getValue())
&& (form.chkRecallYes().getValue() || form.chkRecallNo().getValue())
)
{
form.txtTotalScore().setValue( new Integer(nScore).toString());
hideShowBottomQuestionsBasedOnThreshold(true);
if ( validateData(false))
form.btnSave().setEnabled(form.getMode().equals(FormMode.EDIT));
}
}
@Override
protected void onChkCountYesValueChanged() throws PresentationLogicException
{
form.chkCountNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkMonarchYesValueChanged() throws PresentationLogicException
{
form.chkMonarchNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkYearWW2YesValueChanged() throws PresentationLogicException
{
form.chkYearWW2No().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkRecogniseYesValueChanged() throws PresentationLogicException
{
form.chkRecogniseNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkNameHospitalYesValueChanged() throws PresentationLogicException
{
form.chkNameHospitalNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkCurrentTimeYesValueChanged() throws PresentationLogicException
{
form.chkCurrentTimeNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkCurrentYearYesValueChanged() throws PresentationLogicException
{
form.chkCurrentYearNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkDBYesValueChanged() throws PresentationLogicException
{
form.chkDBNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkAgeYesValueChanged() throws PresentationLogicException
{
form.chkAgeNo().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkRecallNoValueChanged() throws PresentationLogicException
{
form.chkRecallYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkCountNoValueChanged() throws PresentationLogicException
{
form.chkCountYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkMonarchNoValueChanged() throws PresentationLogicException
{
form.chkMonarchYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkYearWW2NoValueChanged() throws PresentationLogicException
{
form.chkYearWW2Yes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkRecogniseNoValueChanged() throws PresentationLogicException
{
form.chkRecogniseYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkNameHospitalNoValueChanged() throws PresentationLogicException
{
form.chkNameHospitalYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkCurrentTimeNoValueChanged() throws PresentationLogicException
{
form.chkCurrentTimeYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkCurrentYearNoValueChanged() throws PresentationLogicException
{
form.chkCurrentYearYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkDBNoValueChanged() throws PresentationLogicException
{
form.chkDBYes().setValue(false);
calculateAndDisplayScore();
}
@Override
protected void onChkAgeNoValueChanged() throws PresentationLogicException
{
form.chkAgeYes().setValue(false);
calculateAndDisplayScore();
}
public void initialize(DementiaVo voDementia, FormMode formMode, DementiaAssessAndInvestigateVo voAMTS)
{
form.getLocalContext().setSelectedRecord(voDementia);
form.getLocalContext().setinFollowUpMode(false);
form.getLocalContext().setSelectedAMTSRecord(null);
if (voAMTS != null)
{
form.getLocalContext().setSelectedAMTSRecord(voAMTS);
form.getLocalContext().setinFollowUpMode(true);
}
populateQuestions();
hideShowBottomQuestionsBasedOnThreshold(false);
initializeAuthoringControls(null);
form.setMode(formMode);
open();
}
private void initializeAuthoringControls(AuthoringInformationVo voAuthoring)
{
if (voAuthoring == null)
{
voAuthoring = new AuthoringInformationVo();
voAuthoring.setAuthoringDateTime(new DateTime());
voAuthoring.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
}
form.lblAuthoringDateTime().setValue(voAuthoring.getAuthoringDateTime().toString());
if (voAuthoring.getAuthoringHcpIsNotNull())
{
if (voAuthoring.getAuthoringHcp().getIHcpName().length() > 65)
{
form.lblAuthoringHCP().setTooltip(voAuthoring.getAuthoringHcp().getIHcpName());
form.lblAuthoringHCP().setValue(voAuthoring.getAuthoringHcp().getIHcpName().substring(0, 65));
}
else
form.lblAuthoringHCP().setValue(voAuthoring.getAuthoringHcp().getIHcpName());
}
}
private void populateScreenFromData()
{
clearAllControls();
DementiaAssessAndInvestigateVo voAMTS = null;
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode()
&& form.getLocalContext().getSelectedAMTSRecordIsNotNull())
voAMTS = form.getLocalContext().getSelectedAMTSRecord();
else if (form.getLocalContext().getSelectedRecordIsNotNull())
voAMTS = form.getLocalContext().getSelectedRecord().getStepTwoAssess();
if (voAMTS == null || voAMTS.getID_DementiaAssessAndInvestigate() == null)
return;
if (voAMTS != null)
{
initializeAuthoringControls(voAMTS.getAuthoringInformation());
//Age
if (voAMTS.getQ1Age().equals(YesNo.YES))
form.chkAgeYes().setValue(true);
else
form.chkAgeNo().setValue(true);
//DOB
if (voAMTS.getQ2DOB().equals(YesNo.YES))
form.chkDBYes().setValue(true);
else
form.chkDBNo().setValue(true);
//Current Year
if(voAMTS.getQ3CurrentYear().equals(YesNo.YES))
form.chkCurrentYearYes().setValue(true);
else
form.chkCurrentYearNo().setValue(true);
//Current Time
if (voAMTS.getQ4CurrentTime().equals(YesNo.YES))
form.chkCurrentTimeYes().setValue(true);
else
form.chkCurrentTimeNo().setValue(true);
//name of hospital
if (voAMTS.getQ5NameOfHospital().equals(YesNo.YES))
form.chkNameHospitalYes().setValue(true);
else
form.chkNameHospitalNo().setValue(true);
//recognise
if (voAMTS.getQ6RecognisePeople().equals(YesNo.YES))
form.chkRecogniseYes().setValue(true);
else
form.chkRecogniseNo().setValue(true);
//ww2
if (voAMTS.getQ7YearWW2Ended().equals(YesNo.YES))
form.chkYearWW2Yes().setValue(true);
else
form.chkYearWW2No().setValue(true);
//Monach
if (voAMTS.getQ8Monarch().equals(YesNo.YES))
form.chkMonarchYes().setValue(true);
else
form.chkMonarchNo().setValue(true);
//Backwards from 20
if (voAMTS.getQ9CountBackwards().equals(YesNo.YES))
form.chkCountYes().setValue(true);
else
form.chkCountNo().setValue(true);
//Recall
if (voAMTS.getQ10Recall().equals(YesNo.YES))
form.chkRecallYes().setValue(true);
else
form.chkRecallNo().setValue(true);
calculateAndDisplayScore();
if(voAMTS.getConfirmMedicationReviewIsNotNull())
form.GroupMedication().setValue(voAMTS.getConfirmMedicationReview().equals(YesNo.YES) ? GroupMedicationEnumeration.rdoMedicationYES : GroupMedicationEnumeration.rdoMedicationNO);
if(voAMTS.getConfirmTrustsProtocolIsNotNull())
form.GroupPRotocol().setValue(voAMTS.getConfirmTrustsProtocol().equals(YesNo.YES) ? GroupPRotocolEnumeration.rdoTrustProtocolYES : GroupPRotocolEnumeration.rdoTrustProtocolNO);
form.txtComment().setValue(voAMTS.getStepTwoAssessNoteIsNotNull() ? voAMTS.getStepTwoAssessNote().getNote() : "");
if ( validateData(false))
form.btnSave().setEnabled(form.getMode().equals(FormMode.EDIT));
}
}
private DementiaAssessAndInvestigateVo populateDataFromScreen()
{
DementiaAssessAndInvestigateVo voAMTS = form.getLocalContext().getSelectedRecord().getStepTwoAssess();
if (form.getLocalContext().getinFollowUpModeIsNotNull()
&& form.getLocalContext().getinFollowUpMode())
voAMTS = form.getLocalContext().getSelectedAMTSRecord();
if (voAMTS == null)
voAMTS = new DementiaAssessAndInvestigateVo();
AuthoringInformationVo voAuthor = new AuthoringInformationVo();
if (voAMTS.getAuthoringInformation() == null)
{
voAuthor.setAuthoringDateTime(new DateTime());
if(domain.getHcpUser() != null)
voAuthor.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
voAMTS.setAuthoringInformation(voAuthor);
}
voAMTS.setAMTSScore(form.txtTotalScore().getValue() != null ? new Integer(form.txtTotalScore().getValue()) : null);
//Age
if(form.chkAgeYes().getValue())
voAMTS.setQ1Age(YesNo.YES);
else
voAMTS.setQ1Age(YesNo.NO);
//DOB
if(form.chkDBYes().getValue())
voAMTS.setQ2DOB(YesNo.YES);
else
voAMTS.setQ2DOB(YesNo.NO);
//Current Year
if(form.chkCurrentYearYes().getValue())
voAMTS.setQ3CurrentYear(YesNo.YES);
else
voAMTS.setQ3CurrentYear(YesNo.NO);
//Current Time
if(form.chkCurrentTimeYes().getValue())
voAMTS.setQ4CurrentTime(YesNo.YES);
else
voAMTS.setQ4CurrentTime(YesNo.NO);
//name of hospital
if(form.chkNameHospitalYes().getValue())
voAMTS.setQ5NameOfHospital(YesNo.YES);
else
voAMTS.setQ5NameOfHospital(YesNo.NO);
//recognise
if(form.chkRecogniseYes().getValue())
voAMTS.setQ6RecognisePeople(YesNo.YES);
else
voAMTS.setQ6RecognisePeople(YesNo.NO);
//ww2
if(form.chkYearWW2Yes().getValue())
voAMTS.setQ7YearWW2Ended(YesNo.YES);
else
voAMTS.setQ7YearWW2Ended(YesNo.NO);
//Monach
if(form.chkMonarchYes().getValue())
voAMTS.setQ8Monarch(YesNo.YES);
else
voAMTS.setQ8Monarch(YesNo.NO);
//Backwards from 20
if(form.chkCountYes().getValue())
voAMTS.setQ9CountBackwards(YesNo.YES);
else
voAMTS.setQ9CountBackwards(YesNo.NO);
//Recall
if(form.chkRecallYes().getValue())
voAMTS.setQ10Recall(YesNo.YES);
else
voAMTS.setQ10Recall(YesNo.NO);
voAMTS.setConfirmMedicationReview(null);
if(form.lblConfirmMedication().isVisible())
voAMTS.setConfirmMedicationReview(form.GroupMedication().getValue().equals(GroupMedicationEnumeration.rdoMedicationYES) ? YesNo.YES : YesNo.NO);
else
voAMTS.setConfirmMedicationReview(null);
voAMTS.setConfirmTrustsProtocol(null);
if(form.lblConfirmTrust().isVisible())
voAMTS.setConfirmTrustsProtocol(form.GroupPRotocol().getValue().equals(GroupPRotocolEnumeration.rdoTrustProtocolYES) ? YesNo.YES : YesNo.NO);
else
voAMTS.setConfirmTrustsProtocol(null);
if (form.txtComment().isVisible()
&& form.txtComment().getValue() != null
&& form.txtComment().getValue().length() >0)
{
if (voAMTS.getStepTwoAssessNote() == null)
voAMTS.setStepTwoAssessNote(new DementiaAssessInvestigateNoteVo());
if (voAuthor.getAuthoringDateTime() == null) // i.e. was this initialised above, if not then do the domain calls to populate
{
voAuthor.setAuthoringDateTime(new DateTime());
if(domain.getHcpUser() != null)
voAuthor.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
}
voAMTS.getStepTwoAssessNote().setAuthoringInformation(voAuthor);
voAMTS.getStepTwoAssessNote().setNote(form.txtComment().getValue());
}
else
{
voAMTS.setStepTwoAssessNote(null); // WDEV-16373
}
return voAMTS;
}
public DementiaVo getValue()
{
return form.getLocalContext().getSelectedRecord();
}
public void resetSelectedEvent()
{
form.getLocalContext().setSelectedEvent(null);
}
@Override
protected void onBtnRIEClick() throws PresentationLogicException
{
engine.open(form.getForms().Core.RieConfirmationDialog);
}
@Override
protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
{
if (formName.equals(form.getForms().Core.RieConfirmationDialog) && DialogResult.OK.equals(result))
{
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.MARK_RIE);
form.fireCustomControlValueChanged();
open();
}
}
@Override
protected void onBtnEditFollowUpClick() throws PresentationLogicException
{
edit();
}
@Override
protected void onBtnNewFollowUpClick() throws PresentationLogicException
{
form.getLocalContext().setSelectedEvent(DementiaEventEnumeration.EDIT);
form.fireCustomControlValueChanged();
form.setMode(FormMode.EDIT);
form.getLocalContext().setSelectedAMTSRecord(null);
clearAllControls();
hideShowBottomQuestionsBasedOnThreshold(false);
initializeAuthoringControls(null);
updateControlState();
}
@Override
protected void onRadioButtonGroupMedicationValueChanged() throws PresentationLogicException
{
if ( validateData(false))
form.btnSave().setEnabled(form.getMode().equals(FormMode.EDIT));
}
@Override
protected void onRadioButtonGroupPRotocolValueChanged() throws PresentationLogicException
{
if ( validateData(false))
form.btnSave().setEnabled(form.getMode().equals(FormMode.EDIT));
}
}
| open-health-hub/openMAXIMS | openmaxims_workspace/Clinical/src/ims/clinical/forms/dementiaassessmentamtscomponent/Logic.java | Java | agpl-3.0 | 34,001 |
-- DB update 2020_09_29_00 -> 2020_09_30_00
DROP PROCEDURE IF EXISTS `updateDb`;
DELIMITER //
CREATE PROCEDURE updateDb ()
proc:BEGIN DECLARE OK VARCHAR(100) DEFAULT 'FALSE';
SELECT COUNT(*) INTO @COLEXISTS
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'version_db_world' AND COLUMN_NAME = '2020_09_29_00';
IF @COLEXISTS = 0 THEN LEAVE proc; END IF;
START TRANSACTION;
ALTER TABLE version_db_world CHANGE COLUMN 2020_09_29_00 2020_09_30_00 bit;
SELECT sql_rev INTO OK FROM version_db_world WHERE sql_rev = '1598878239120359200'; IF OK <> 'FALSE' THEN LEAVE proc; END IF;
--
-- START UPDATING QUERIES
--
INSERT INTO `version_db_world` (`sql_rev`) VALUES ('1598878239120359200');
/*
* Dungeon: Dire Maul (West)
* Update by Knindza | <www.azerothcore.org>
* Copyright (C) <www.shadowburn.net> & <www.lichbane.com>
*/
/* REGULAR */
UPDATE `creature_template` SET `mindmg` = 489, `maxdmg` = 673, `DamageModifier` = 1.03 WHERE `entry` = 11459;
UPDATE `creature_template` SET `mindmg` = 415, `maxdmg` = 625, `DamageModifier` = 1.03 WHERE `entry` = 14303;
UPDATE `creature_template` SET `mindmg` = 421, `maxdmg` = 637, `DamageModifier` = 1.03 WHERE `entry` = 11458;
UPDATE `creature_template` SET `mindmg` = 456, `maxdmg` = 629, `DamageModifier` = 1.03 WHERE `entry` = 11483;
UPDATE `creature_template` SET `mindmg` = 475, `maxdmg` = 641, `DamageModifier` = 1.03 WHERE `entry` = 11480;
UPDATE `creature_template` SET `mindmg` = 464, `maxdmg` = 629, `DamageModifier` = 1.03 WHERE `entry` = 11473;
UPDATE `creature_template` SET `mindmg` = 452, `maxdmg` = 619, `DamageModifier` = 1.03 WHERE `entry` = 11470;
UPDATE `creature_template` SET `mindmg` = 498, `maxdmg` = 559, `DamageModifier` = 1.03 WHERE `entry` = 11469;
UPDATE `creature_template` SET `mindmg` = 472, `maxdmg` = 612, `DamageModifier` = 1.03 WHERE `entry` = 11477;
UPDATE `creature_template` SET `mindmg` = 464, `maxdmg` = 629, `DamageModifier` = 1.03 WHERE `entry` = 14398;
UPDATE `creature_template` SET `mindmg` = 432, `maxdmg` = 605, `DamageModifier` = 1.03 WHERE `entry` = 11476;
UPDATE `creature_template` SET `mindmg` = 472, `maxdmg` = 647, `DamageModifier` = 1.03 WHERE `entry` = 11472;
UPDATE `creature_template` SET `mindmg` = 456, `maxdmg` = 615, `DamageModifier` = 1.03 WHERE `entry` = 11471;
UPDATE `creature_template` SET `mindmg` = 498, `maxdmg` = 663, `DamageModifier` = 1.03 WHERE `entry` = 11475;
UPDATE `creature_template` SET `mindmg` = 775, `maxdmg` = 1027, `DamageModifier` = 1.03 WHERE `entry` = 14308;
UPDATE `creature_template` SET `mindmg` = 410, `maxdmg` = 553, `DamageModifier` = 1.03 WHERE `entry` = 11484;
UPDATE `creature_template` SET `mindmg` = 337, `maxdmg` = 455, `DamageModifier` = 1.03 WHERE `entry` = 14397;
UPDATE `creature_template` SET `mindmg` = 412, `maxdmg` = 616, `DamageModifier` = 1.03 WHERE `entry` = 14399;
UPDATE `creature_template` SET `mindmg` = 305, `maxdmg` = 428, `DamageModifier` = 1.03 WHERE `entry` = 14400;
UPDATE `creature_template` SET `mindmg` = 266, `maxdmg` = 363, `DamageModifier` = 1.03 WHERE `entry` = 11466;
/* RARE */
UPDATE `creature_template` SET `rank` = 2, `mindmg` = 496, `maxdmg` = 692, `DamageModifier` = 1.02 WHERE `entry` = 11467;
/* BOSS */
UPDATE `creature_template` SET `type_flags`=`type_flags`|4, `mindmg` = 689, `maxdmg` = 771, `DamageModifier` = 1.01 WHERE `entry` = 11489;
UPDATE `creature_template` SET `type_flags`=`type_flags`|4, `mindmg` = 684, `maxdmg` = 741, `DamageModifier` = 1.01 WHERE `entry` = 11487;
UPDATE `creature_template` SET `type_flags`=`type_flags`|4, `mindmg` = 692, `maxdmg` = 757, `DamageModifier` = 1.01 WHERE `entry` = 11488;
UPDATE `creature_template` SET `type_flags`=`type_flags`|4, `mindmg` = 675, `maxdmg` = 714, `DamageModifier` = 1.01 WHERE `entry` = 11496;
UPDATE `creature_template` SET `type_flags`=`type_flags`|4, `mindmg` = 695, `maxdmg` = 723, `DamageModifier` = 1.01 WHERE `entry` = 11486;
UPDATE `creature_template` SET `type_flags`=`type_flags`|4, `mindmg` = 684, `maxdmg` = 776, `DamageModifier` = 1.01 WHERE `entry` = 14506;
--
-- END UPDATING QUERIES
--
COMMIT;
END //
DELIMITER ;
CALL updateDb();
DROP PROCEDURE IF EXISTS `updateDb`;
| ShinDarth/azerothcore-wotlk | data/sql/archive/db_world/3.x/2020_09_30_00.sql | SQL | agpl-3.0 | 4,162 |
<?php
namespace Aws\CodeBuild;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS CodeBuild** service.
* @method \Aws\Result batchDeleteBuilds(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchDeleteBuildsAsync(array $args = [])
* @method \Aws\Result batchGetBuildBatches(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetBuildBatchesAsync(array $args = [])
* @method \Aws\Result batchGetBuilds(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetBuildsAsync(array $args = [])
* @method \Aws\Result batchGetProjects(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetProjectsAsync(array $args = [])
* @method \Aws\Result batchGetReportGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetReportGroupsAsync(array $args = [])
* @method \Aws\Result batchGetReports(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetReportsAsync(array $args = [])
* @method \Aws\Result createProject(array $args = [])
* @method \GuzzleHttp\Promise\Promise createProjectAsync(array $args = [])
* @method \Aws\Result createReportGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise createReportGroupAsync(array $args = [])
* @method \Aws\Result createWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise createWebhookAsync(array $args = [])
* @method \Aws\Result deleteBuildBatch(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBuildBatchAsync(array $args = [])
* @method \Aws\Result deleteProject(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteProjectAsync(array $args = [])
* @method \Aws\Result deleteReport(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteReportAsync(array $args = [])
* @method \Aws\Result deleteReportGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteReportGroupAsync(array $args = [])
* @method \Aws\Result deleteResourcePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteResourcePolicyAsync(array $args = [])
* @method \Aws\Result deleteSourceCredentials(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteSourceCredentialsAsync(array $args = [])
* @method \Aws\Result deleteWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteWebhookAsync(array $args = [])
* @method \Aws\Result describeCodeCoverages(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeCodeCoveragesAsync(array $args = [])
* @method \Aws\Result describeTestCases(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeTestCasesAsync(array $args = [])
* @method \Aws\Result getReportGroupTrend(array $args = [])
* @method \GuzzleHttp\Promise\Promise getReportGroupTrendAsync(array $args = [])
* @method \Aws\Result getResourcePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getResourcePolicyAsync(array $args = [])
* @method \Aws\Result importSourceCredentials(array $args = [])
* @method \GuzzleHttp\Promise\Promise importSourceCredentialsAsync(array $args = [])
* @method \Aws\Result invalidateProjectCache(array $args = [])
* @method \GuzzleHttp\Promise\Promise invalidateProjectCacheAsync(array $args = [])
* @method \Aws\Result listBuildBatches(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBuildBatchesAsync(array $args = [])
* @method \Aws\Result listBuildBatchesForProject(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBuildBatchesForProjectAsync(array $args = [])
* @method \Aws\Result listBuilds(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBuildsAsync(array $args = [])
* @method \Aws\Result listBuildsForProject(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBuildsForProjectAsync(array $args = [])
* @method \Aws\Result listCuratedEnvironmentImages(array $args = [])
* @method \GuzzleHttp\Promise\Promise listCuratedEnvironmentImagesAsync(array $args = [])
* @method \Aws\Result listProjects(array $args = [])
* @method \GuzzleHttp\Promise\Promise listProjectsAsync(array $args = [])
* @method \Aws\Result listReportGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise listReportGroupsAsync(array $args = [])
* @method \Aws\Result listReports(array $args = [])
* @method \GuzzleHttp\Promise\Promise listReportsAsync(array $args = [])
* @method \Aws\Result listReportsForReportGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise listReportsForReportGroupAsync(array $args = [])
* @method \Aws\Result listSharedProjects(array $args = [])
* @method \GuzzleHttp\Promise\Promise listSharedProjectsAsync(array $args = [])
* @method \Aws\Result listSharedReportGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise listSharedReportGroupsAsync(array $args = [])
* @method \Aws\Result listSourceCredentials(array $args = [])
* @method \GuzzleHttp\Promise\Promise listSourceCredentialsAsync(array $args = [])
* @method \Aws\Result putResourcePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putResourcePolicyAsync(array $args = [])
* @method \Aws\Result retryBuild(array $args = [])
* @method \GuzzleHttp\Promise\Promise retryBuildAsync(array $args = [])
* @method \Aws\Result retryBuildBatch(array $args = [])
* @method \GuzzleHttp\Promise\Promise retryBuildBatchAsync(array $args = [])
* @method \Aws\Result startBuild(array $args = [])
* @method \GuzzleHttp\Promise\Promise startBuildAsync(array $args = [])
* @method \Aws\Result startBuildBatch(array $args = [])
* @method \GuzzleHttp\Promise\Promise startBuildBatchAsync(array $args = [])
* @method \Aws\Result stopBuild(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopBuildAsync(array $args = [])
* @method \Aws\Result stopBuildBatch(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopBuildBatchAsync(array $args = [])
* @method \Aws\Result updateProject(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateProjectAsync(array $args = [])
* @method \Aws\Result updateProjectVisibility(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateProjectVisibilityAsync(array $args = [])
* @method \Aws\Result updateReportGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateReportGroupAsync(array $args = [])
* @method \Aws\Result updateWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateWebhookAsync(array $args = [])
*/
class CodeBuildClient extends AwsClient {}
| colosa/processmaker | vendor/aws/aws-sdk-php/src/CodeBuild/CodeBuildClient.php | PHP | agpl-3.0 | 6,417 |
-- DB update 2021_07_29_05 -> 2021_07_29_06
DROP PROCEDURE IF EXISTS `updateDb`;
DELIMITER //
CREATE PROCEDURE updateDb ()
proc:BEGIN DECLARE OK VARCHAR(100) DEFAULT 'FALSE';
SELECT COUNT(*) INTO @COLEXISTS
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'version_db_world' AND COLUMN_NAME = '2021_07_29_05';
IF @COLEXISTS = 0 THEN LEAVE proc; END IF;
START TRANSACTION;
ALTER TABLE version_db_world CHANGE COLUMN 2021_07_29_05 2021_07_29_06 bit;
SELECT sql_rev INTO OK FROM version_db_world WHERE sql_rev = '1627192822598309507'; IF OK <> 'FALSE' THEN LEAVE proc; END IF;
--
-- START UPDATING QUERIES
--
INSERT INTO `version_db_world` (`sql_rev`) VALUES ('1627192822598309507');
UPDATE `creature_template` SET `AIName` = 'SmartAI' WHERE `entry` = 7156;
DELETE FROM `smart_scripts` WHERE `entryorguid` = 7156 AND `source_type` = 0 AND `id` IN (0, 1);
INSERT INTO `smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `event_param5`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_param4`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES
(7156, 0, 0, 0, 0, 0, 100, 1, 0, 0, 5000, 5000, 0, 11, 13583, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 'Deadwood Den Watcher - In Combat - Cast \'Curse of the Deadwood\' (No Repeat)'),
(7156, 0, 1, 0, 2, 0, 100, 1, 0, 50, 0, 0, 0, 39, 20, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 'Deadwood Den Watcher - Between 0-50% Health - Call For Help (No Repeat)');
--
-- END UPDATING QUERIES
--
UPDATE version_db_world SET date = '2021_07_29_06' WHERE sql_rev = '1627192822598309507';
COMMIT;
END //
DELIMITER ;
CALL updateDb();
DROP PROCEDURE IF EXISTS `updateDb`;
| ShinDarth/azerothcore-wotlk | data/sql/archive/db_world/4.x/2021_07_29_06.sql | SQL | agpl-3.0 | 1,932 |
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('course_action_state.tests.test_rerun_manager', 'common.djangoapps.course_action_state.tests.test_rerun_manager')
from common.djangoapps.course_action_state.tests.test_rerun_manager import *
| eduNEXT/edunext-platform | import_shims/studio/course_action_state/tests/test_rerun_manager.py | Python | agpl-3.0 | 461 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.pathways.forms.createnewevent;
public abstract class BaseLogic extends Handlers
{
public final Class getDomainInterface() throws ClassNotFoundException
{
return ims.pathways.domain.CreateNewEvent.class;
}
public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.pathways.domain.CreateNewEvent domain)
{
setContext(engine, form);
this.domain = domain;
}
public final void free()
{
super.free();
domain = null;
}
protected ims.pathways.domain.CreateNewEvent domain;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/Pathways/src/ims/pathways/forms/createnewevent/BaseLogic.java | Java | agpl-3.0 | 2,194 |
# Copyright 2008-2015 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check http://launchpad.net/filesync-server
"""Add db_worker_unseen table to keep track of unseen items on the database
side.
"""
SQL = [
"""
CREATE TABLE txlog.db_worker_unseen (
id INTEGER NOT NULL,
worker_id TEXT NOT NULL,
created TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT \
timezone('UTC'::text, now())
)
""",
"""
GRANT SELECT, INSERT, UPDATE, DELETE
ON TABLE txlog.db_worker_unseen
TO storage, webapp
""",
"""
CREATE INDEX db_worker_unseen_idx
ON txlog.db_worker_unseen(worker_id, created, id)
"""
]
def apply(store):
"""Apply the patch"""
for statement in SQL:
store.execute(statement)
| zhsso/ubunto-one | src/backends/db/schemas/txlog/patch_4.py | Python | agpl-3.0 | 1,421 |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logging
from flask import current_app as app
from superdesk.errors import SuperdeskApiError
import superdesk
from .ldap import ADAuth, add_default_values, get_user_query
logger = logging.getLogger(__name__)
class ImportUserProfileFromADCommand(superdesk.Command):
"""
Responsible for importing a user profile from Active Directory (AD) to Mongo.
This command runs on assumption that the user executing this command and
the user whose profile need to be imported need not to be the same. Uses ad_username and ad_password to bind to AD
and then searches for a user identified by username_to_import and if found imports into Mongo.
"""
option_list = (
superdesk.Option('--ad_username', '-adu', dest='ad_username', required=True),
superdesk.Option('--ad_password', '-adp', dest='ad_password', required=True),
superdesk.Option('--username_to_import', '-u', dest='username', required=True),
superdesk.Option('--admin', '-a', dest='admin', required=False),
)
def run(self, ad_username, ad_password, username, admin='false'):
"""
Imports or Updates a User Profile from AD to Mongo.
:param ad_username: Active Directory Username
:param ad_password: Password of Active Directory Username
:param username: Username as in Active Directory whose profile needs to be imported to Superdesk.
:return: User Profile.
"""
# force type conversion to boolean
user_type = 'administrator' if admin is not None and admin.lower() == 'true' else 'user'
# Authenticate and fetch profile from AD
settings = app.settings
ad_auth = ADAuth(settings['LDAP_SERVER'], settings['LDAP_SERVER_PORT'], settings['LDAP_BASE_FILTER'],
settings['LDAP_USER_FILTER'], settings['LDAP_USER_ATTRIBUTES'], settings['LDAP_FQDN'])
user_data = ad_auth.authenticate_and_fetch_profile(ad_username, ad_password, username)
if len(user_data) == 0:
raise SuperdeskApiError.notFoundError('Username not found')
# Check if User Profile already exists in Mongo
user = superdesk.get_resource_service('users').find_one(req=None, **get_user_query(username))
if user:
superdesk.get_resource_service('users').patch(user.get('_id'), user_data)
else:
add_default_values(user_data, username, user_type=user_type)
superdesk.get_resource_service('users').post([user_data])
return user_data
superdesk.command('users:copyfromad', ImportUserProfileFromADCommand())
| sivakuna-aap/superdesk | server/apps/ldap/commands.py | Python | agpl-3.0 | 2,913 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.emergency.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseAddEditQuestionsToWhiteboardImpl extends DomainImpl implements ims.emergency.domain.AddEditQuestionsToWhiteboard, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/Emergency/src/ims/emergency/domain/base/impl/BaseAddEditQuestionsToWhiteboardImpl.java | Java | agpl-3.0 | 1,974 |
# -*- encoding : utf-8 -*-
# Rebuild the current xapian index
def rebuild_xapian_index(terms = true, values = true, texts = true, dropfirst = true)
if dropfirst
begin
ActsAsXapian.readable_init
FileUtils.rm_r(ActsAsXapian.db_path)
rescue RuntimeError
end
ActsAsXapian.writable_init
ActsAsXapian.writable_db.close
end
parse_all_incoming_messages
# safe_rebuild=true, which involves forking to avoid memory leaks, doesn't work well with rspec.
# unsafe is significantly faster, and we can afford possible memory leaks while testing.
models = [PublicBody, User, InfoRequestEvent]
ActsAsXapian.rebuild_index(models, verbose=false, terms, values, texts, safe_rebuild=false)
end
def update_xapian_index
ActsAsXapian.update_index(flush_to_disk=false, verbose=false)
end
# Copy the xapian index created in create_fixtures_xapian_index to a temporary
# copy at the same level and point xapian at the copy
def get_fixtures_xapian_index
# Create a base index for the fixtures if not already created
$existing_xapian_db ||= create_fixtures_xapian_index
# Store whatever the xapian db path is originally
$original_xapian_path ||= ActsAsXapian.db_path
path_array = $original_xapian_path.split(File::Separator)
path_array.pop
temp_path = File.join(path_array, 'test.temp')
FileUtils.remove_entry_secure(temp_path, force=true)
FileUtils.cp_r($original_xapian_path, temp_path)
ActsAsXapian.db_path = temp_path
end
# Create a clean xapian index based on the fixture files and the raw_email data.
def create_fixtures_xapian_index
load_raw_emails_data
rebuild_xapian_index
end
| Br3nda/alaveteli | spec/support/xapian_index.rb | Ruby | agpl-3.0 | 1,632 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.admin.vo.lookups;
import ims.framework.cn.data.TreeNode;
import java.util.ArrayList;
import ims.framework.utils.Image;
import ims.framework.utils.Color;
public class EDAttendenceControlType extends ims.vo.LookupInstVo implements TreeNode
{
private static final long serialVersionUID = 1L;
public EDAttendenceControlType()
{
super();
}
public EDAttendenceControlType(int id)
{
super(id, "", true);
}
public EDAttendenceControlType(int id, String text, boolean active)
{
super(id, text, active, null, null, null);
}
public EDAttendenceControlType(int id, String text, boolean active, EDAttendenceControlType parent, Image image)
{
super(id, text, active, parent, image);
}
public EDAttendenceControlType(int id, String text, boolean active, EDAttendenceControlType parent, Image image, Color color)
{
super(id, text, active, parent, image, color);
}
public EDAttendenceControlType(int id, String text, boolean active, EDAttendenceControlType parent, Image image, Color color, int order)
{
super(id, text, active, parent, image, color, order);
}
public static EDAttendenceControlType buildLookup(ims.vo.LookupInstanceBean bean)
{
return new EDAttendenceControlType(bean.getId(), bean.getText(), bean.isActive());
}
public String toString()
{
if(getText() != null)
return getText();
return "";
}
public TreeNode getParentNode()
{
return (EDAttendenceControlType)super.getParentInstance();
}
public EDAttendenceControlType getParent()
{
return (EDAttendenceControlType)super.getParentInstance();
}
public void setParent(EDAttendenceControlType parent)
{
super.setParentInstance(parent);
}
public TreeNode[] getChildren()
{
ArrayList children = super.getChildInstances();
EDAttendenceControlType[] typedChildren = new EDAttendenceControlType[children.size()];
for (int i = 0; i < children.size(); i++)
{
typedChildren[i] = (EDAttendenceControlType)children.get(i);
}
return typedChildren;
}
public int addChild(TreeNode child)
{
if (child instanceof EDAttendenceControlType)
{
super.addChild((EDAttendenceControlType)child);
}
return super.getChildInstances().size();
}
public int removeChild(TreeNode child)
{
if (child instanceof EDAttendenceControlType)
{
super.removeChild((EDAttendenceControlType)child);
}
return super.getChildInstances().size();
}
public Image getExpandedImage()
{
return super.getImage();
}
public Image getCollapsedImage()
{
return super.getImage();
}
public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection()
{
EDAttendenceControlTypeCollection result = new EDAttendenceControlTypeCollection();
result.add(ATTEND_CONTROLS);
result.add(CHART_CONTROLS);
result.add(INV_BILL_CONTROLS);
return result;
}
public static EDAttendenceControlType[] getNegativeInstances()
{
EDAttendenceControlType[] instances = new EDAttendenceControlType[3];
instances[0] = ATTEND_CONTROLS;
instances[1] = CHART_CONTROLS;
instances[2] = INV_BILL_CONTROLS;
return instances;
}
public static String[] getNegativeInstanceNames()
{
String[] negativeInstances = new String[3];
negativeInstances[0] = "ATTEND_CONTROLS";
negativeInstances[1] = "CHART_CONTROLS";
negativeInstances[2] = "INV_BILL_CONTROLS";
return negativeInstances;
}
public static EDAttendenceControlType getNegativeInstance(String name)
{
if(name == null)
return null;
String[] negativeInstances = getNegativeInstanceNames();
for (int i = 0; i < negativeInstances.length; i++)
{
if(negativeInstances[i].equals(name))
return getNegativeInstances()[i];
}
return null;
}
public static EDAttendenceControlType getNegativeInstance(Integer id)
{
if(id == null)
return null;
EDAttendenceControlType[] negativeInstances = getNegativeInstances();
for (int i = 0; i < negativeInstances.length; i++)
{
if(negativeInstances[i].getID() == id)
return negativeInstances[i];
}
return null;
}
public int getTypeId()
{
return TYPE_ID;
}
public static final int TYPE_ID = 1031027;
public static final EDAttendenceControlType ATTEND_CONTROLS = new EDAttendenceControlType(-2513, "ATTEND_CONTROLS", true, null, null, Color.Default);
public static final EDAttendenceControlType CHART_CONTROLS = new EDAttendenceControlType(-2514, "CHART_CONTROLS", true, null, null, Color.Default);
public static final EDAttendenceControlType INV_BILL_CONTROLS = new EDAttendenceControlType(-2515, "INV_BILL_CONTROLS", true, null, null, Color.Default);
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/admin/vo/lookups/EDAttendenceControlType.java | Java | agpl-3.0 | 6,202 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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 Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace ShopwarePlugin\PaymentMethods\Components;
use Doctrine\ORM\AbstractQuery;
/**
* Replacement class for legacy core/paymentmeans/debit.php class.
*
* Class DebitPaymentMethod
* Used to handle debit payment
*/
class DebitPaymentMethod extends GenericPaymentMethod
{
/**
* {@inheritdoc}
*/
public function validate($paymentData)
{
$sErrorFlag = [];
$fields = [
'sDebitAccount',
'sDebitBankcode',
'sDebitBankName',
'sDebitBankHolder',
];
foreach ($fields as $field) {
$value = $paymentData[$field] ?: '';
$value = trim($value);
if (empty($value)) {
$sErrorFlag[$field] = true;
}
}
if (count($sErrorFlag)) {
$sErrorMessages[] = Shopware()->Snippets()->getNamespace('frontend/account/internalMessages')
->get('ErrorFillIn', 'Please fill in all red fields');
return [
'sErrorFlag' => $sErrorFlag,
'sErrorMessages' => $sErrorMessages,
];
}
return [];
}
/**
* {@inheritdoc}
*/
public function savePaymentData($userId, \Enlight_Controller_Request_Request $request)
{
$lastPayment = $this->getCurrentPaymentDataAsArray($userId);
$paymentMean = Shopware()->Models()->getRepository('\Shopware\Models\Payment\Payment')->
getPaymentsQuery(['name' => 'debit'])->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
$data = [
'account_number' => $request->getParam('sDebitAccount'),
'bank_code' => $request->getParam('sDebitBankcode'),
'bankname' => $request->getParam('sDebitBankName'),
'account_holder' => $request->getParam('sDebitBankHolder'),
];
if (!$lastPayment) {
$date = new \DateTime();
$data['created_at'] = $date->format('Y-m-d');
$data['payment_mean_id'] = $paymentMean['id'];
$data['user_id'] = $userId;
Shopware()->Db()->insert('s_core_payment_data', $data);
} else {
$where = [
'payment_mean_id = ?' => $paymentMean['id'],
'user_id = ?' => $userId,
];
Shopware()->Db()->update('s_core_payment_data', $data, $where);
}
}
/**
* {@inheritdoc}
*/
public function getCurrentPaymentDataAsArray($userId)
{
$paymentData = Shopware()->Models()->getRepository('\Shopware\Models\Customer\PaymentData')
->getCurrentPaymentDataQueryBuilder($userId, 'debit')->getQuery()->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
if (isset($paymentData)) {
$arrayData = [
'sDebitAccount' => $paymentData['accountNumber'],
'sDebitBankcode' => $paymentData['bankCode'],
'sDebitBankName' => $paymentData['bankName'],
'sDebitBankHolder' => $paymentData['accountHolder'],
];
return $arrayData;
}
}
/**
* {@inheritdoc}
*/
public function createPaymentInstance($orderId, $userId, $paymentId)
{
$orderAmount = Shopware()->Models()->createQueryBuilder()
->select('orders.invoiceAmount')
->from('Shopware\Models\Order\Order', 'orders')
->where('orders.id = ?1')
->setParameter(1, $orderId)
->getQuery()
->getSingleScalarResult();
$addressData = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')
->find($userId)->getDefaultBillingAddress();
$debitData = $this->getCurrentPaymentDataAsArray($userId);
$date = new \DateTime();
$data = [
'payment_mean_id' => $paymentId,
'order_id' => $orderId,
'user_id' => $userId,
'firstname' => $addressData->getFirstname(),
'lastname' => $addressData->getLastname(),
'address' => $addressData->getStreet(),
'zipcode' => $addressData->getZipcode(),
'city' => $addressData->getCity(),
'account_number' => $debitData['sDebitAccount'],
'bank_code' => $debitData['sDebitBankcode'],
'bank_name' => $debitData['sDebitBankName'],
'account_holder' => $debitData['sDebitBankHolder'],
'amount' => $orderAmount,
'created_at' => $date->format('Y-m-d'),
];
Shopware()->Db()->insert('s_core_payment_instance', $data);
return true;
}
}
| simkli/shopware | engine/Shopware/Plugins/Default/Core/PaymentMethods/Components/DebitPaymentMethod.php | PHP | agpl-3.0 | 5,574 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RTriebeard(RPackage):
"""triebeard: 'Radix' Trees in 'Rcpp'"""
homepage = "https://github.com/Ironholds/triebeard/"
url = "https://cloud.r-project.org/src/contrib/triebeard_0.3.0.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/triebeard"
version('0.3.0', sha256='bf1dd6209cea1aab24e21a85375ca473ad11c2eff400d65c6202c0fb4ef91ec3')
depends_on('r-rcpp', type=('build', 'run'))
| LLNL/spack | var/spack/repos/builtin/packages/r-triebeard/package.py | Python | lgpl-2.1 | 652 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyEpydoc(PythonPackage):
"""Epydoc is a tool for generating API documentation documentation for
Python modules, based on their docstrings."""
pypi = "epydoc/epydoc-3.0.1.tar.gz"
version('3.0.1', sha256='c81469b853fab06ec42b39e35dd7cccbe9938dfddef324683d89c1e5176e48f2')
| LLNL/spack | var/spack/repos/builtin/packages/py-epydoc/package.py | Python | lgpl-2.1 | 516 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using N2.Edit.Installation;
using N2.Engine;
using N2.Web;
using N2.Definitions.Static;
using N2.Persistence;
using N2.Persistence.Serialization;
using N2.Persistence.NH;
using N2.Plugin;
using N2.Configuration;
using N2.Details;
using N2.Security;
namespace N2.Raven
{
[Service(typeof(InstallationManager), Replaces = typeof(InstallationManager))]
public class RavenInstallationManager : InstallationManager
{
private RavenConnectionProvider cp;
public RavenInstallationManager(IHost host, DefinitionMap map, ContentActivator activator, Importer importer, IPersister persister, ISessionProvider sessionProvider, IConfigurationBuilder configurationBuilder, IWebContext webContext, ConnectionMonitor connectionContext, DatabaseSection config, RavenConnectionProvider cp)
: base(connectionContext, importer, webContext, persister, activator)
{
this.cp = cp;
}
public Exception GetConnectionException()
{
//return base.GetConnectionException();
try
{
using (cp.OpenSession())
{
return null;
}
}
catch (Exception ex)
{
return ex;
}
}
protected void UpdateConnection(DatabaseStatus status)
{
//base.UpdateConnection(status);
if (GetConnectionException() == null)
{
status.IsConnected = true;
}
}
protected void UpdateVersion(DatabaseStatus status)
{
//base.UpdateVersion(status);
status.DatabaseVersion = DatabaseStatus.RequiredDatabaseVersion;
}
protected void UpdateSchema(DatabaseStatus status)
{
//base.UpdateSchema(status);
status.HasSchema = true;
}
protected void UpdateCount(DatabaseStatus status)
{
try
{
status.Items = cp.Session.Query<ContentItem>().Count();
status.Details = cp.Session.Query<ContentDetail>().Count();
status.DetailCollections = cp.Session.Query<DetailCollection>().Count();
status.AuthorizedRoles = cp.Session.Query<AuthorizedRole>().Count();
}
catch (Exception)
{
throw;
}
}
public override string CheckConnection(out string stackTrace)
{
throw new NotImplementedException();
}
public override string CheckDatabase()
{
throw new NotImplementedException();
}
public override string CheckRootItem()
{
throw new NotImplementedException();
}
public override string CheckStartPage()
{
throw new NotImplementedException();
}
public override DatabaseStatus GetStatus()
{
throw new NotImplementedException();
}
public override void Upgrade()
{
throw new NotImplementedException();
}
public override void Install()
{
throw new NotImplementedException();
}
public override IEnumerable<ContentItem> ExecuteQuery(string query)
{
throw new NotImplementedException();
}
public override string ExportSchema()
{
throw new NotImplementedException();
}
public override void ExportSchema(TextWriter output)
{
throw new NotImplementedException();
}
public override string ExportUpgradeSchema()
{
throw new NotImplementedException();
}
}
}
| DejanMilicic/n2cms | src/Framework/Raven/RavenInstallationManager.cs | C# | lgpl-2.1 | 3,124 |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.service.certificate;
import java.security.cert.*;
/**
* Service that creates dialog that is shown to the user when
* a certificate verification failed.
*
* @author Damian Minkov
*/
public interface VerifyCertificateDialogService
{
/**
* Creates the dialog.
*
* @param certs the certificates list
* @param title The title of the dialog; when null the resource
* <tt>service.gui.CERT_DIALOG_TITLE</tt> is loaded and used.
* @param message A text that describes why the verification failed.
*/
public VerifyCertificateDialog createDialog(
Certificate[] certs, String title, String message);
/**
* The dialog implementers should return <tt>VerifyCertificateDialog</tt>.
*/
public interface VerifyCertificateDialog
{
/**
* Shows or hides the dialog and waits for user response.
* @param isVisible whether we should show or hide the dialog.
*/
public void setVisible(boolean isVisible);
/**
* Whether the user has accepted the certificate or not.
* @return whether the user has accepted the certificate or not.
*/
public boolean isTrusted();
/**
* Whether the user has selected to note the certificate so we always
* trust it.
* @return whether the user has selected to note the certificate so
* we always trust it.
*/
public boolean isAlwaysTrustSelected();
}
}
| marclaporte/jitsi | src/net/java/sip/communicator/service/certificate/VerifyCertificateDialogService.java | Java | lgpl-2.1 | 1,673 |
v.setCursorPosition(1,19);
v.enter();
v.type("ok"); | hlamer/kate | tests/data/indent/cstyle/aplist10/input.js | JavaScript | lgpl-2.1 | 51 |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*
* ContactGroupSSHImpl.java
*
* SSH Suport in SIP Communicator - GSoC' 07 Project
*
*/
package net.java.sip.communicator.impl.protocol.ssh;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
/**
* A simple, straightforward implementation of a ssh ContactGroup. Since
* the SSH protocol is not a real one, we simply store all group details
* in class fields. You should know that when implementing a real protocol,
* the contact group implementation would rather encapsulate group objects from
* the protocol stack and group property values should be returned by
* consulting the encapsulated object.
*
* @author Shobhit Jindal
*/
public class ContactGroupSSHImpl
implements ContactGroup
{
/**
* The name of this SSH contact group.
*/
private String groupName = null;
/**
* The list of this group's members.
*/
private Vector<Contact> contacts = new Vector<Contact>();
/**
* The list of sub groups belonging to this group.
*/
private Vector<ContactGroup> subGroups = new Vector<ContactGroup>();
/**
* The group that this group belongs to (or null if this is the root group).
*/
private ContactGroupSSHImpl parentGroup = null;
/**
* Determines whether this group is really in the contact list or whether
* it is here only temporarily and will be gone next time we restart.
*/
private boolean isPersistent = true;
/**
* The protocol provider that created us.
*/
private ProtocolProviderServiceSSHImpl parentProvider = null;
/**
* Determines whether this group has been resolved on the server.
* Unresolved groups are groups that were available on previous runs and
* that the meta contact list has stored. During all next runs, when
* bootstrapping, the meta contact list would create these groups as
* unresolved. Once a protocol provider implementation confirms that the
* groups are still on the server, it would issue an event indicating that
* the groups are now resolved.
*/
private boolean isResolved = true;
/**
* An id uniquely identifying the group. For many protocols this could be
* the group name itself.
*/
private String uid = null;
private static final String UID_SUFFIX = ".uid";
/**
* Creates a ContactGroupSSHImpl with the specified name.
*
* @param groupName the name of the group.
* @param parentProvider the protocol provider that created this group.
*/
public ContactGroupSSHImpl(
String groupName,
ProtocolProviderServiceSSHImpl parentProvider)
{
this.groupName = groupName;
this.uid = groupName + UID_SUFFIX;
this.parentProvider = parentProvider;
}
/**
* Determines whether the group may contain subgroups or not.
*
* @return always true in this implementation.
*/
public boolean canContainSubgroups()
{
return true;
}
/**
* Returns the protocol provider that this group belongs to.
* @return a regerence to the ProtocolProviderService instance that this
* ContactGroup belongs to.
*/
public ProtocolProviderService getProtocolProvider()
{
return parentProvider;
}
/**
* Returns an Iterator over all contacts, member of this
* <tt>ContactGroup</tt>.
*
* @return a java.util.Iterator over all contacts inside this
* <tt>ContactGroup</tt>
*/
public Iterator<Contact> contacts()
{
return contacts.iterator();
}
/**
* Adds the specified contact to this group.
* @param contactToAdd the ContactSSHImpl to add to this group.
*/
public void addContact(ContactSSH contactToAdd)
{
this.contacts.add(contactToAdd);
contactToAdd.setParentGroup(this);
}
/**
* Returns the number of <tt>Contact</tt> members of this
* <tt>ContactGroup</tt>
*
* @return an int indicating the number of <tt>Contact</tt>s, members of
* this <tt>ContactGroup</tt>.
*/
public int countContacts()
{
return contacts.size();
}
/**
* Returns the number of subgroups contained by this
* <tt>ContactGroup</tt>.
*
* @return the number of subGroups currently added to this group.
*/
public int countSubgroups()
{
return subGroups.size();
}
/**
* Adds the specified contact group to the contained by this group.
* @param subgroup the ContactGroupSSHImpl to add as a subgroup to this
* group.
*/
public void addSubgroup(ContactGroupSSHImpl subgroup)
{
this.subGroups.add(subgroup);
subgroup.setParentGroup(this);
}
/**
* Sets the group that is the new parent of this group
* @param parent ContactGroupSSHImpl
*/
void setParentGroup(ContactGroupSSHImpl parent)
{
this.parentGroup = parent;
}
/**
* Returns the contact group that currently contains this group or null if
* this is the root contact group.
* @return the contact group that currently contains this group or null if
* this is the root contact group.
*/
public ContactGroup getParentContactGroup()
{
return this.parentGroup;
}
/**
* Removes the specified contact group from the this group's subgroups.
* @param subgroup the ContactGroupSSHImpl subgroup to remove.
*/
public void removeSubGroup(ContactGroupSSHImpl subgroup)
{
this.subGroups.remove(subgroup);
subgroup.setParentGroup(null);
}
/**
* Returns the group that is parent of the specified sshGroup or null
* if no parent was found.
* @param sshGroup the group whose parent we're looking for.
* @return the ContactGroupSSHImpl instance that sshGroup
* belongs to or null if no parent was found.
*/
public ContactGroupSSHImpl findGroupParent(
ContactGroupSSHImpl sshGroup)
{
if ( subGroups.contains(sshGroup) )
return this;
Iterator<ContactGroup> subGroupsIter = subgroups();
while (subGroupsIter.hasNext())
{
ContactGroupSSHImpl subgroup
= (ContactGroupSSHImpl) subGroupsIter.next();
ContactGroupSSHImpl parent
= subgroup.findGroupParent(sshGroup);
if(parent != null)
return parent;
}
return null;
}
/**
* Returns the group that is parent of the specified sshContact or
* null if no parent was found.
*
* @param sshContact the contact whose parent we're looking for.
* @return the ContactGroupSSHImpl instance that sshContact
* belongs to or <tt>null</tt> if no parent was found.
*/
public ContactGroupSSHImpl findContactParent(
ContactSSHImpl sshContact)
{
if ( contacts.contains(sshContact) )
return this;
Iterator<ContactGroup> subGroupsIter = subgroups();
while (subGroupsIter.hasNext())
{
ContactGroupSSHImpl subgroup
= (ContactGroupSSHImpl) subGroupsIter.next();
ContactGroupSSHImpl parent
= subgroup.findContactParent(sshContact);
if(parent != null)
return parent;
}
return null;
}
/**
* Returns the <tt>Contact</tt> with the specified address or identifier.
*
* @param id the addres or identifier of the <tt>Contact</tt> we are
* looking for.
* @return the <tt>Contact</tt> with the specified id or address.
*/
public Contact getContact(String id)
{
Iterator<Contact> contactsIter = contacts();
while (contactsIter.hasNext())
{
ContactSSHImpl contact = (ContactSSHImpl) contactsIter.next();
if (contact.getAddress().equals(id))
return contact;
}
return null;
}
/**
* Returns the subgroup with the specified index.
*
* @param index the index of the <tt>ContactGroup</tt> to retrieve.
* @return the <tt>ContactGroup</tt> with the specified index.
*/
public ContactGroup getGroup(int index)
{
return subGroups.get(index);
}
/**
* Returns the subgroup with the specified name.
*
* @param groupName the name of the <tt>ContactGroup</tt> to retrieve.
* @return the <tt>ContactGroup</tt> with the specified index.
*/
public ContactGroup getGroup(String groupName)
{
Iterator<ContactGroup> groupsIter = subgroups();
while (groupsIter.hasNext())
{
ContactGroupSSHImpl contactGroup
= (ContactGroupSSHImpl) groupsIter.next();
if (contactGroup.getGroupName().equals(groupName))
return contactGroup;
}
return null;
}
/**
* Returns the name of this group.
*
* @return a String containing the name of this group.
*/
public String getGroupName()
{
return this.groupName;
}
/**
* Sets this group a new name.
* @param newGrpName a String containing the new name of this group.
*/
public void setGroupName(String newGrpName)
{
this.groupName = newGrpName;
}
/**
* Returns an iterator over the sub groups that this
* <tt>ContactGroup</tt> contains.
*
* @return a java.util.Iterator over the <tt>ContactGroup</tt> children
* of this group (i.e. subgroups).
*/
public Iterator<ContactGroup> subgroups()
{
return subGroups.iterator();
}
/**
* Removes the specified contact from this group.
* @param contact the ContactSSHImpl to remove from this group
*/
public void removeContact(ContactSSHImpl contact)
{
this.contacts.remove(contact);
}
/**
* Returns the contact with the specified id or null if no such contact
* exists.
* @param id the id of the contact we're looking for.
* @return ContactSSHImpl
*/
public ContactSSHImpl findContactByID(String id)
{
//first go through the contacts that are direct children.
Iterator<Contact> contactsIter = contacts();
while(contactsIter.hasNext())
{
ContactSSHImpl mContact = (ContactSSHImpl)contactsIter.next();
if( mContact.getAddress().equals(id) )
return mContact;
}
//if we didn't find it here, let's try in the subougroups
Iterator<ContactGroup> groupsIter = subgroups();
while( groupsIter.hasNext() )
{
ContactGroupSSHImpl mGroup = (ContactGroupSSHImpl)groupsIter.next();
ContactSSHImpl mContact = mGroup.findContactByID(id);
if (mContact != null)
return mContact;
}
return null;
}
/**
* Returns a String representation of this group and the contacts it
* contains (may turn out to be a relatively long string).
* @return a String representing this group and its child contacts.
*/
@Override
public String toString()
{
StringBuffer buff = new StringBuffer(getGroupName());
buff.append(".subGroups=" + countSubgroups() + ":\n");
Iterator<ContactGroup> subGroups = subgroups();
while (subGroups.hasNext())
{
ContactGroup group = subGroups.next();
buff.append(group.toString());
if (subGroups.hasNext())
buff.append("\n");
}
buff.append("\nChildContacts="+countContacts()+":[");
Iterator<Contact> contacts = contacts();
while (contacts.hasNext())
{
Contact contact = contacts.next();
buff.append(contact.toString());
if(contacts.hasNext())
buff.append(", ");
}
return buff.append("]").toString();
}
/**
* Specifies whether or not this contact group is being stored by the
* server.
* Non persistent contact groups are common in the case of simple,
* non-persistent presence operation sets. They could however also be seen
* in persistent presence operation sets when for example we have received
* an event from someone not on our contact list and the contact that we
* associated with that user is placed in a non persistent group. Non
* persistent contact groups are volatile even when coming from a
* persistent presence op. set. They would only exist until the
* application is closed and will not be there next time it is loaded.
*
* @param isPersistent true if the contact group is to be persistent and
* false otherwise.
*/
public void setPersistent(boolean isPersistent)
{
this.isPersistent = isPersistent;
}
/**
* Determines whether or not this contact group is being stored by the
* server. Non persistent contact groups exist for the sole purpose of
* containing non persistent contacts.
* @return true if the contact group is persistent and false otherwise.
*/
public boolean isPersistent()
{
return isPersistent;
}
/**
* Returns null as no persistent data is required and the contact address is
* sufficient for restoring the contact.
* <p>
* @return null as no such data is needed.
*/
public String getPersistentData()
{
return null;
}
/**
* Determines whether or not this contact has been resolved against the
* server. Unresolved contacts are used when initially loading a contact
* list that has been stored in a local file until the presence operation
* set has managed to retrieve all the contact list from the server and has
* properly mapped contacts to their on-line buddies.
* @return true if the contact has been resolved (mapped against a buddy)
* and false otherwise.
*/
public boolean isResolved()
{
return isResolved;
}
/**
* Makes the group resolved or unresolved.
*
* @param resolved true to make the group resolved; false to
* make it unresolved
*/
public void setResolved(boolean resolved)
{
this.isResolved = resolved;
}
/**
* Returns a <tt>String</tt> that uniquely represnets the group inside
* the current protocol. The string MUST be persistent (it must not change
* across connections or runs of the application). In many cases (Jabber,
* ICQ) the string may match the name of the group as these protocols
* only allow a single level of contact groups and there is no danger of
* having the same name twice in the same contact list. Other protocols
* (no examples come to mind but that doesn't bother me ;) ) may be
* supporting mutilple levels of grooups so it might be possible for group
* A and group B to both contain groups named C. In such cases the
* implementation must find a way to return a unique identifier in this
* method and this UID should never change for a given group.
*
* @return a String representing this group in a unique and persistent
* way.
*/
public String getUID()
{
return uid;
}
/**
* Ugly but tricky conversion method.
* @param uid the uid we'd like to get a name from
* @return the name of the group with the specified <tt>uid</tt>.
*/
static String createNameFromUID(String uid)
{
return uid.substring(0, uid.length() - (UID_SUFFIX.length()));
}
/**
* Indicates whether some other object is "equal to" this one which in terms
* of contact groups translates to having the equal names and matching
* subgroups and child contacts. The resolved status of contactgroups and
* contacts is deliberately ignored so that groups and/or contacts would
* be assumed equal even if it differs.
* <p>
* @param obj the reference object with which to compare.
* @return <code>true</code> if this contact group has the equal child
* contacts and subgroups to those of the <code>obj</code> argument.
*/
@Override
public boolean equals(Object obj)
{
if(obj == null
|| !(obj instanceof ContactGroupSSHImpl))
return false;
ContactGroupSSHImpl sshGroup
= (ContactGroupSSHImpl)obj;
if( ! sshGroup.getGroupName().equals(getGroupName())
|| ! sshGroup.getUID().equals(getUID())
|| sshGroup.countContacts() != countContacts()
|| sshGroup.countSubgroups() != countSubgroups())
return false;
//traverse child contacts
Iterator<Contact> theirContacts = sshGroup.contacts();
while(theirContacts.hasNext())
{
Contact theirContact = theirContacts.next();
Contact ourContact = getContact(theirContact.getAddress());
if(ourContact == null
|| !ourContact.equals(theirContact))
return false;
}
//traverse subgroups
Iterator<ContactGroup> theirSubgroups = sshGroup.subgroups();
while(theirSubgroups.hasNext())
{
ContactGroup theirSubgroup = theirSubgroups.next();
ContactGroup ourSubgroup = getGroup(theirSubgroup.getGroupName());
if(ourSubgroup == null
|| !ourSubgroup.equals(theirSubgroup))
return false;
}
return true;
}
}
| marclaporte/jitsi | src/net/java/sip/communicator/impl/protocol/ssh/ContactGroupSSHImpl.java | Java | lgpl-2.1 | 17,908 |
package org.intermine.dataconversion;
/*
* Copyright (C) 2002-2017 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.File;
import org.intermine.metadata.Model;
/**
* Parent class for DataConverters that read from directories
* @author Julie Sullivan
*/
public abstract class DirectoryConverter extends DataConverter
{
/**
* Constructor
* @param writer the Writer used to output the resultant items
* @param model the data model
*/
public DirectoryConverter(ItemWriter writer, Model model) {
super(writer, model);
}
/**
* Perform the conversion files in the directory
* @param dataDir directory containing files to convert
* @throws Exception if an error occurs during processing
*/
public abstract void process(File dataDir) throws Exception;
/**
* Perform any necessary clean-up after post-conversion
* @throws Exception if an error occurs
*/
public void close() throws Exception {
// empty
}
}
| elsiklab/intermine | intermine/integrate/main/src/org/intermine/dataconversion/DirectoryConverter.java | Java | lgpl-2.1 | 1,241 |
/*
This software has been released under the MIT license:
Copyright (c) 2009 Jonas Krogsboell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
Using the JSON Path part of the JSON_EXT package
*/
set serveroutput on;
declare
obj json := json(
'{
"a" : true,
"b" : [1,2,"3"],
"c" : {
"d" : [["array of array"], null, { "e": 7913 }]
}
}');
begin
-- Having understood ex8.sql and ex9.sql, we now what to delete elements with
-- JSON Path. The JSON Path remove method does only remove an element if it
-- exists. Unlike put, it does not build up a structure but uses get to
-- investigate if the structure exists. The only time remove should fail, is
-- when you ask it to remove the entire structure.
-- (Which you could easily do yourself >> obj := json() << )
dbms_output.put_line('Example 1: remove a');
json_ext.remove(obj, 'a');
obj.print;
dbms_output.put_line('Example 2: remove third element of b');
json_ext.remove(obj, 'b[3]');
obj.print;
dbms_output.put_line('Example 3: remove first element of b');
json_ext.remove(obj, 'b[1]');
obj.print;
dbms_output.put_line('Example 4: remove e in d in c');
json_ext.remove(obj, 'c.d[3].e');
obj.print;
dbms_output.put_line('Example 5: remove array of array in d');
json_ext.remove(obj, 'c.d[1]');
obj.print;
dbms_output.put_line('Example 6: remove null element in d');
json_ext.remove(obj, 'c.d[1]');
obj.print;
dbms_output.put_line('Example 7: remove b and c');
json_ext.remove(obj, 'c');
json_ext.remove(obj, 'b');
obj.print;
-- thats it!
end;
/ | osalvador/dbax | source/types/json_v1_0_4/examples/ex10.sql | SQL | lgpl-3.0 | 2,595 |
//
// AssemblyInfo.cs
//
// Author:
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (C) 2003 Ximian, Inc. http://www.ximian.com
// (C) 2004 Novell (http://www.novell.com)
//
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion (Consts.FxVersion)]
/* TODO COMPLETE INFORMATION
[assembly: AssemblyTitle ("")]
[assembly: AssemblyDescription ("")]
[assembly: CLSCompliant (true)]
[assembly: AssemblyFileVersion ("0.0.0.1")]
[assembly: ComVisible (false)]
*/
[assembly: AssemblyDelaySign (true)]
[assembly: AssemblyKeyFile ("../mono.pub")]
| edwinspire/VSharp | class/PEAPI/Assembly/AssemblyInfo.cs | C# | lgpl-3.0 | 605 |
/**
* This program 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 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 <http://www.gnu.org/licenses/>.
*
**/
#pragma once
/**
* @file
* @author Jocelyn Meyron (\c jocelyn.meyron@liris.cnrs.fr )
* Laboratoire d'InfoRmatique en Image et Systemes d'information - LIRIS (CNRS, UMR 5205), CNRS, France
*
* @date 2020/12/15
*
* Header file for module MaximalSegmentSliceEstimation.cpp
*
* This file is part of the DGtal library.
*/
#if defined(MaximalSegmentSliceEstimation_RECURSES)
#error Recursive header files inclusion detected in MaximalSegmentSliceEstimation.h
#else // defined(MaximalSegmentSliceEstimation_RECURSES)
/** Prevents recursive inclusion of headers. */
#define MaximalSegmentSliceEstimation_RECURSES
#if !defined MaximalSegmentSliceEstimation_h
/** Prevents repeated inclusion of headers. */
#define MaximalSegmentSliceEstimation_h
//////////////////////////////////////////////////////////////////////////////
// Inclusions
#include <iostream>
#include <vector>
#include "DGtal/base/Common.h"
#include "DGtal/geometry/surfaces/ArithmeticalDSSComputerOnSurfels.h"
#include "DGtal/topology/DigitalSurface2DSlice.h"
#include "DGtal/topology/CDigitalSurfaceContainer.h"
//////////////////////////////////////////////////////////////////////////////
namespace DGtal
{
/////////////////////////////////////////////////////////////////////////////
// template class MaximalSegmentSliceEstimation
/**
* Description of template class 'MaximalSegmentSliceEstimation' <p>
* \brief Aim:
*
* @tparam TSurface the digital surface type.
*
* \b Models: A MaximalSegmentSliceEstimation is a model of concepts::CSurfelLocalEstimator and concepts::CDigitalSurfaceLocalEstimator.
*/
template <typename TSurface>
class MaximalSegmentSliceEstimation
{
BOOST_CONCEPT_ASSERT(( concepts::CDigitalSurfaceContainer<typename TSurface::DigitalSurfaceContainer> ));
// ----------------------- Public types ------------------------------
public:
using Surface = TSurface;
using Tracker = typename Surface::DigitalSurfaceTracker;
using SurfaceSlice = DigitalSurface2DSlice<Tracker>;
using Scalar = double;
// -------------------------------------- other types ----------------------------
using KSpace = typename Surface::KSpace;
using SCell = typename KSpace::SCell;
using Cell = typename KSpace::Cell;
using Point = typename Surface::Point;
using Vector = Point;
using Integer = typename Point::Coordinate;
using Space = typename KSpace::Space;
using RealPoint = typename Space::RealPoint;
using RealVector = RealPoint;
// ----------------------- model of CDigitalSurfaceLocalEstimator ----------------
using Surfel = typename Surface::Surfel;
using Quantity = RealVector;
// ----------------------- Private types ------------------------------
private:
using Point2 = PointVector<2, Integer>;
using RealPoint2 = PointVector<2, double>;
using Container = std::deque<SCell>;
using Iterator = typename Container::const_iterator;
using DSSComputer = ArithmeticalDSSComputerOnSurfels<KSpace, Circulator<Iterator>, Integer, 4>;
// ----------------------- Standard services ------------------------------
public:
/**
* Default constructor.
*/
MaximalSegmentSliceEstimation();
/**
* Constructor.
*
* @param aSurface a digiral surface.
*/
MaximalSegmentSliceEstimation(ConstAlias<Surface> aSurface);
/**
* Destructor.
*/
~MaximalSegmentSliceEstimation();
/**
* Copy constructor.
* @param other the object to clone.
*/
MaximalSegmentSliceEstimation ( const MaximalSegmentSliceEstimation & other );
/**
* Copy assignment operator.
* @param other the object to copy.
* @return a reference on 'this'.
*/
MaximalSegmentSliceEstimation & operator= ( const MaximalSegmentSliceEstimation & other );
// ----------------- model of CSurfelLocalEstimator -----------------------
public:
/**
* Initializes the estimator (in this case, do nothing apart from storing the gridstep).
*
* @param h the grdstep.
* @param itb an iterator on the start of the range of surfels.
* @param ite a past-the-end iterator of the range of surfels.
*/
template < typename SurfelConstIterator >
void init (Scalar const& h, SurfelConstIterator itb, SurfelConstIterator ite);
/**
* Estimates the quantity on a surfel.
*
* @param it an iterator whose value type is a Surfel.
* @return the estimated quantity.
*/
template < typename SurfelConstIterator >
Quantity eval (SurfelConstIterator it) const;
/**
* Estimates the quantity on a range of surfels.
*
* @param itb an iterator on the start of the range of surfels.
* @param ite a past-the-end iterator of the range of surfels.
* @param out an output iterator to store the results.
* @return the modified output iterator.
*/
template < typename SurfelConstIterator, typename OutputIterator >
OutputIterator eval (SurfelConstIterator itb, SurfelConstIterator ite, OutputIterator out) const;
/**
* @return the gridstep.
*/
Scalar h () const;
// --------------- model of CDigitalSurfaceLocalEstimator ------------------
public:
void attach (ConstAlias<Surface> aSurface);
// ----------------------- Interface --------------------------------------
public:
/**
* Writes/Displays the object on an output stream.
* @param out the output stream where the object is written.
*/
void selfDisplay ( std::ostream & out ) const;
/**
* Checks the validity/consistency of the object.
* @return 'true' if the object is valid, 'false' otherwise.
*/
bool isValid() const;
// ------------------------- Protected Datas ------------------------------
protected:
// ------------------------- Private Datas --------------------------------
private:
CountedConstPtrOrConstPtr<Surface> mySurface; /**< A pointer to the digital surface. */
Scalar myH; /**< The gridstep */
// ------------------------- Hidden services ------------------------------
protected:
// ------------------------- Internals ------------------------------------
private:
/**
* Khalimsky space associated to the digital surface.
*
* @return a const reference to the Khalimsky space.
*/
KSpace const& space () const;
/**
* Computes the extremal points of a set of 2D digital points using maximal segments.
*
* @param aSlice a slice of the digital surface.
* @param aProjectDir1 the first direction of projection.
* @param aProjectDir2 the second direction of projection.
* @return the two extremities of the maximal segment on the left and on the right.
*/
std::pair<Point2, Point2> getExtremalPoints (SurfaceSlice const& aSlice,
Dimension const& aProjectDir1, Dimension const& aProjectDir2) const;
/**
* @param aSurfel a surfel.
* @return the trivial normal vector of a surfel.
*/
Vector trivialNormal (Surfel const& aSurfel) const;
}; // end of class MaximalSegmentSliceEstimation
/**
* Overloads 'operator<<' for displaying objects of class 'MaximalSegmentSliceEstimation'.
* @param out the output stream where the object is written.
* @param object the object of class 'MaximalSegmentSliceEstimation' to write.
* @return the output stream after the writing.
*/
template <typename TSurface>
std::ostream&
operator<< ( std::ostream & out, const MaximalSegmentSliceEstimation<TSurface> & object );
} // namespace DGtal
///////////////////////////////////////////////////////////////////////////////
// Includes inline functions.
#include "DGtal/geometry/surfaces/estimation/MaximalSegmentSliceEstimation.ih"
// //
///////////////////////////////////////////////////////////////////////////////
#endif // !defined MaximalSegmentSliceEstimation_h
#undef MaximalSegmentSliceEstimation_RECURSES
#endif // else defined(MaximalSegmentSliceEstimation_RECURSES)
| JacquesOlivierLachaud/DGtal | src/DGtal/geometry/surfaces/estimation/MaximalSegmentSliceEstimation.h | C | lgpl-3.0 | 8,960 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Waikato Environment for Knowledge Analysis (WEKA)</title>
<!-- CSS Stylesheet -->
<style>body
{
background: #ededed;
color: #666666;
font: 14px Tahoma, Helvetica, sans-serif;;
margin: 5px 10px 5px 10px;
padding: 0px;
}
</style>
</head>
<body bgcolor="#ededed" text="#666666">
<table summary="Package isotonicRegression: summary">
<tr><td valign=top>Author:</td><td width=50></td><td>Eibe Frank</td></tr>
<tr><td valign=top>Category:</td><td width=50></td><td>Regression</td></tr>
<tr><td valign=top>Date:</td><td width=50></td><td>2009-09-10</td></tr>
<tr><td valign=top>Depends:</td><td width=50></td><td>weka (>=3.7.1)</td></tr>
<tr><td valign=top>Description:</td><td width=50></td><td>Learns an isotonic regression model. Picks the attribute that results in the lowest squared error. Missing values are not allowed. Can only deal with numeric attributes. Considers the monotonically increasing case as well as the monotonically decreasing case.</td></tr>
<tr><td valign=top>License:</td><td width=50></td><td>GPL 2.0</td></tr>
<tr><td valign=top>Maintainer:</td><td width=50></td><td>Weka team <wekalist{[at]}list.scms.waikato.ac.nz></td></tr>
<tr><td valign=top>PackageURL:</td><td width=50></td><td><a href="http://prdownloads.sourceforge.net/weka/isotonicRegression1.0.0.zip?download">http://prdownloads.sourceforge.net/weka/isotonicRegression1.0.0.zip?download</a></td></tr>
<tr><td valign=top>URL:</td><td width=50></td><td><a href="http://weka.sourceforge.net/doc.packages/isotonicRegression">http://weka.sourceforge.net/doc.packages/isotonicRegression</a></td></tr>
<tr><td valign=top>Version:</td><td width=50></td><td>1.0.0</td></tr>
</table>
</body>
</html>
| Mindtoeye/Hoop | wekafiles/repCache/isotonicRegression/Latest.html | HTML | lgpl-3.0 | 1,772 |
using UnityEngine;
using System.Collections;
using DentedPixel;
public class GeneralBasics2dCS : MonoBehaviour {
public Texture2D dudeTexture;
public GameObject prefabParticles;
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
void Start () {
// Setup
GameObject avatarRotate = createSpriteDude( "avatarRotate", new Vector3(-2.51208f,10.7119f,-14.37754f));
GameObject avatarScale = createSpriteDude( "avatarScale", new Vector3(2.51208f,10.2119f,-14.37754f));
GameObject avatarMove = createSpriteDude( "avatarMove", new Vector3(-3.1208f,7.100643f,-14.37754f));
// Rotate Example
LeanTween.rotateAround( avatarRotate, Vector3.forward, -360f, 5f);
// Scale Example
LeanTween.scale( avatarScale, new Vector3(1.7f, 1.7f, 1.7f), 5f).setEase(LeanTweenType.easeOutBounce);
LeanTween.moveX( avatarScale, avatarScale.transform.position.x + 1f, 5f).setEase(LeanTweenType.easeOutBounce); // Simultaneously target many different tweens on the same object
// Move Example
LeanTween.move( avatarMove, avatarMove.transform.position + new Vector3(1.7f, 0f, 0f), 2f).setEase(LeanTweenType.easeInQuad);
// Delay
LeanTween.move( avatarMove, avatarMove.transform.position + new Vector3(2f, -1f, 0f), 2f).setDelay(3f);
// Chain properties (delay, easing with a set repeating of type ping pong)
LeanTween.scale( avatarScale, new Vector3(0.2f, 0.2f, 0.2f), 1f).setDelay(7f).setEase(LeanTweenType.easeInOutCirc).setLoopPingPong(3);
// Call methods after a certain time period
LeanTween.delayedCall(gameObject, 0.2f, advancedExamples);
}
GameObject createSpriteDude( string name, Vector3 pos, bool hasParticles = true ){
GameObject go = new GameObject(name);
SpriteRenderer ren = go.AddComponent<SpriteRenderer>();
go.GetComponent<SpriteRenderer>().color = new Color(0f,181f/255f,1f);
ren.sprite = Sprite.Create( dudeTexture, new Rect(0.0f,0.0f,256.0f,256.0f), new Vector2(0.5f,0f), 256f);
go.transform.position = pos;
if(hasParticles){
GameObject particles = (GameObject)GameObject.Instantiate(prefabParticles, Vector3.zero, prefabParticles.transform.rotation );
particles.transform.parent = go.transform;
particles.transform.localPosition = prefabParticles.transform.position;
}
return go;
}
// Advanced Examples
// It might be best to master the basics first, but this is included to tease the many possibilies LeanTween provides.
void advancedExamples(){
LeanTween.delayedCall(gameObject, 14f, ()=>{
for(int i=0; i < 10; i++){
// Instantiate Container
GameObject rotator = new GameObject("rotator"+i);
rotator.transform.position = new Vector3(2.71208f,7.100643f,-12.37754f);
// Instantiate Avatar
GameObject dude = createSpriteDude( "dude"+i, new Vector3(-2.51208f,7.100643f,-14.37754f), false);//(GameObject)GameObject.Instantiate(prefabAvatar, Vector3.zero, prefabAvatar.transform.rotation );
dude.transform.parent = rotator.transform;
dude.transform.localPosition = new Vector3(0f,0.5f,0.5f*i);
// Scale, pop-in
dude.transform.localScale = new Vector3(0f,0f,0f);
LeanTween.scale(dude, new Vector3(0.65f,0.65f,0.65f), 1f).setDelay(i*0.2f).setEase(LeanTweenType.easeOutBack);
// Color like the rainbow
float period = LeanTween.tau/10*i;
float red = Mathf.Sin(period + LeanTween.tau*0f/3f) * 0.5f + 0.5f;
float green = Mathf.Sin(period + LeanTween.tau*1f/3f) * 0.5f + 0.5f;
float blue = Mathf.Sin(period + LeanTween.tau*2f/3f) * 0.5f + 0.5f;
Color rainbowColor = new Color(red, green, blue);
LeanTween.color(dude, rainbowColor, 0.3f).setDelay(1.2f + i*0.4f);
// Push into the wheel
LeanTween.moveLocalZ(dude, -2f, 0.3f).setDelay(1.2f + i*0.4f).setEase(LeanTweenType.easeSpring).setOnComplete(
()=>{
LeanTween.rotateAround(rotator, Vector3.forward, -1080f, 12f);
}
);
// Jump Up and back down
LeanTween.moveLocalY(dude,1.17f,1.2f).setDelay(5f + i*0.2f).setLoopPingPong(1).setEase(LeanTweenType.easeInOutQuad);
// Alpha Out, and destroy
LeanTween.alpha(dude, 0f, 0.6f).setDelay(9.2f + i*0.4f).setDestroyOnComplete(true).setOnComplete(
()=>{
Destroy( rotator ); // destroying parent as well
}
);
}
}).setOnCompleteOnStart(true).setRepeat(-1); // Have the OnComplete play in the beginning and have the whole group repeat endlessly
}
#endif
}
| paosalcedo/shooterexperiment | ShooterExperiment/ShooterExperiment/Assets/LeanTween/Examples/Scripts/GeneralBasics2dCS.cs | C# | unlicense | 4,391 |
angular.module('spartan.services', [])
/**
* A simple example service that returns some data.
*/
.factory('Friends', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var friends = [
{ id: 0, name: 'Scruff McGruff' },
{ id: 1, name: 'G.I. Joe' },
{ id: 2, name: 'Miss Frizzle' },
{ id: 3, name: 'Ash Ketchum' }
];
return {
all: function() {
return friends;
},
get: function(friendId) {
// Simple index lookup
return friends[friendId];
}
}
});
| carlosrojaso/urbangods | www/js/services.js | JavaScript | unlicense | 554 |
# coding: utf-8
from __future__ import unicode_literals
import hashlib
import math
import random
import time
import uuid
from .common import InfoExtractor
from ..compat import compat_urllib_parse
from ..utils import ExtractorError
class IqiyiIE(InfoExtractor):
IE_NAME = 'iqiyi'
IE_DESC = '爱奇艺'
_VALID_URL = r'http://(?:[^.]+\.)?iqiyi\.com/.+\.html'
_TESTS = [{
'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
'md5': '2cb594dc2781e6c941a110d8f358118b',
'info_dict': {
'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
'title': '美国德州空中惊现奇异云团 酷似UFO',
'ext': 'f4v',
}
}, {
'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb',
'title': '名侦探柯南第752集',
},
'playlist': [{
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part1',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part4',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part5',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part6',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part7',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}, {
'info_dict': {
'id': 'e3f585b550a280af23c98b6cb2be19fb_part8',
'ext': 'f4v',
'title': '名侦探柯南第752集',
},
}],
'params': {
'skip_download': True,
},
}, {
'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
'only_matching': True,
}, {
'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
'only_matching': True,
}, {
'url': 'http://yule.iqiyi.com/pcb.html',
'only_matching': True,
}]
_FORMATS_MAP = [
('1', 'h6'),
('2', 'h5'),
('3', 'h4'),
('4', 'h3'),
('5', 'h2'),
('10', 'h1'),
]
@staticmethod
def md5_text(text):
return hashlib.md5(text.encode('utf-8')).hexdigest()
def construct_video_urls(self, data, video_id, _uuid):
def do_xor(x, y):
a = y % 3
if a == 1:
return x ^ 121
if a == 2:
return x ^ 72
return x ^ 103
def get_encode_code(l):
a = 0
b = l.split('-')
c = len(b)
s = ''
for i in range(c - 1, -1, -1):
a = do_xor(int(b[c - i - 1], 16), i)
s += chr(a)
return s[::-1]
def get_path_key(x, format_id, segment_index):
mg = ')(*&^flash@#$%a'
tm = self._download_json(
'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
)['t']
t = str(int(math.floor(int(tm) / (600.0))))
return self.md5_text(t + mg + x)
video_urls_dict = {}
for format_item in data['vp']['tkl'][0]['vs']:
if 0 < int(format_item['bid']) <= 10:
format_id = self.get_format(format_item['bid'])
else:
continue
video_urls = []
video_urls_info = format_item['fs']
if not format_item['fs'][0]['l'].startswith('/'):
t = get_encode_code(format_item['fs'][0]['l'])
if t.endswith('mp4'):
video_urls_info = format_item['flvs']
for segment_index, segment in enumerate(video_urls_info):
vl = segment['l']
if not vl.startswith('/'):
vl = get_encode_code(vl)
key = get_path_key(
vl.split('/')[-1].split('.')[0], format_id, segment_index)
filesize = segment['b']
base_url = data['vp']['du'].split('/')
base_url.insert(-1, key)
base_url = '/'.join(base_url)
param = {
'su': _uuid,
'qyid': uuid.uuid4().hex,
'client': '',
'z': '',
'bt': '',
'ct': '',
'tn': str(int(time.time()))
}
api_video_url = base_url + vl + '?' + \
compat_urllib_parse.urlencode(param)
js = self._download_json(
api_video_url, video_id,
note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
video_url = js['l']
video_urls.append(
(video_url, filesize))
video_urls_dict[format_id] = video_urls
return video_urls_dict
def get_format(self, bid):
matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
return matched_format_ids[0] if len(matched_format_ids) else None
def get_bid(self, format_id):
matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
return matched_bids[0] if len(matched_bids) else None
def get_raw_data(self, tvid, video_id, enc_key, _uuid):
tm = str(int(time.time()))
tail = tm + tvid
param = {
'key': 'fvip',
'src': self.md5_text('youtube-dl'),
'tvId': tvid,
'vid': video_id,
'vinfo': 1,
'tm': tm,
'enc': self.md5_text(enc_key + tail),
'qyid': _uuid,
'tn': random.random(),
'um': 0,
'authkey': self.md5_text(self.md5_text('') + tail),
}
api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
compat_urllib_parse.urlencode(param)
raw_data = self._download_json(api_url, video_id)
return raw_data
def get_enc_key(self, swf_url, video_id):
# TODO: automatic key extraction
# last update at 2015-12-18 for Zombie::bite
enc_key = '8b6b683780897eb8d9a48a02ccc4817d'[::-1]
return enc_key
def _real_extract(self, url):
webpage = self._download_webpage(
url, 'temp_id', note='download video page')
tvid = self._search_regex(
r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
video_id = self._search_regex(
r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
swf_url = self._search_regex(
r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL')
_uuid = uuid.uuid4().hex
enc_key = self.get_enc_key(swf_url, video_id)
raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
if raw_data['code'] != 'A000000':
raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
if not raw_data['data']['vp']['tkl']:
raise ExtractorError('No support iQiqy VIP video')
data = raw_data['data']
title = data['vi']['vn']
# generate video_urls_dict
video_urls_dict = self.construct_video_urls(
data, video_id, _uuid)
# construct info
entries = []
for format_id in video_urls_dict:
video_urls = video_urls_dict[format_id]
for i, video_url_info in enumerate(video_urls):
if len(entries) < i + 1:
entries.append({'formats': []})
entries[i]['formats'].append(
{
'url': video_url_info[0],
'filesize': video_url_info[-1],
'format_id': format_id,
'preference': int(self.get_bid(format_id))
}
)
for i in range(len(entries)):
self._sort_formats(entries[i]['formats'])
entries[i].update(
{
'id': '%s_part%d' % (video_id, i + 1),
'title': title,
}
)
if len(entries) > 1:
info = {
'_type': 'multi_video',
'id': video_id,
'title': title,
'entries': entries,
}
else:
info = entries[0]
info['id'] = video_id
info['title'] = title
return info
| atomic83/youtube-dl | youtube_dl/extractor/iqiyi.py | Python | unlicense | 9,558 |
"""Support for WeMo switches."""
import asyncio
import logging
from datetime import datetime, timedelta
import requests
import async_timeout
from homeassistant.components.switch import SwitchDevice
from homeassistant.exceptions import PlatformNotReady
from homeassistant.util import convert
from homeassistant.const import (
STATE_OFF, STATE_ON, STATE_STANDBY, STATE_UNKNOWN)
from . import SUBSCRIPTION_REGISTRY
SCAN_INTERVAL = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
ATTR_SENSOR_STATE = 'sensor_state'
ATTR_SWITCH_MODE = 'switch_mode'
ATTR_CURRENT_STATE_DETAIL = 'state_detail'
ATTR_COFFEMAKER_MODE = 'coffeemaker_mode'
MAKER_SWITCH_MOMENTARY = 'momentary'
MAKER_SWITCH_TOGGLE = 'toggle'
WEMO_ON = 1
WEMO_OFF = 0
WEMO_STANDBY = 8
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up discovered WeMo switches."""
from pywemo import discovery
if discovery_info is not None:
location = discovery_info['ssdp_description']
mac = discovery_info['mac_address']
try:
device = discovery.device_from_description(location, mac)
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout) as err:
_LOGGER.error("Unable to access %s (%s)", location, err)
raise PlatformNotReady
if device:
add_entities([WemoSwitch(device)])
class WemoSwitch(SwitchDevice):
"""Representation of a WeMo switch."""
def __init__(self, device):
"""Initialize the WeMo switch."""
self.wemo = device
self.insight_params = None
self.maker_params = None
self.coffeemaker_mode = None
self._state = None
self._mode_string = None
self._available = True
self._update_lock = None
self._model_name = self.wemo.model_name
self._name = self.wemo.name
self._serialnumber = self.wemo.serialnumber
def _subscription_callback(self, _device, _type, _params):
"""Update the state by the Wemo device."""
_LOGGER.info("Subscription update for %s", self.name)
updated = self.wemo.subscription_update(_type, _params)
self.hass.add_job(
self._async_locked_subscription_callback(not updated))
async def _async_locked_subscription_callback(self, force_update):
"""Handle an update from a subscription."""
# If an update is in progress, we don't do anything
if self._update_lock.locked():
return
await self._async_locked_update(force_update)
self.async_schedule_update_ha_state()
@property
def unique_id(self):
"""Return the ID of this WeMo switch."""
return self._serialnumber
@property
def name(self):
"""Return the name of the switch if any."""
return self._name
@property
def device_state_attributes(self):
"""Return the state attributes of the device."""
attr = {}
if self.maker_params:
# Is the maker sensor on or off.
if self.maker_params['hassensor']:
# Note a state of 1 matches the WeMo app 'not triggered'!
if self.maker_params['sensorstate']:
attr[ATTR_SENSOR_STATE] = STATE_OFF
else:
attr[ATTR_SENSOR_STATE] = STATE_ON
# Is the maker switch configured as toggle(0) or momentary (1).
if self.maker_params['switchmode']:
attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_MOMENTARY
else:
attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_TOGGLE
if self.insight_params or (self.coffeemaker_mode is not None):
attr[ATTR_CURRENT_STATE_DETAIL] = self.detail_state
if self.insight_params:
attr['on_latest_time'] = \
WemoSwitch.as_uptime(self.insight_params['onfor'])
attr['on_today_time'] = \
WemoSwitch.as_uptime(self.insight_params['ontoday'])
attr['on_total_time'] = \
WemoSwitch.as_uptime(self.insight_params['ontotal'])
attr['power_threshold_w'] = \
convert(
self.insight_params['powerthreshold'], float, 0.0
) / 1000.0
if self.coffeemaker_mode is not None:
attr[ATTR_COFFEMAKER_MODE] = self.coffeemaker_mode
return attr
@staticmethod
def as_uptime(_seconds):
"""Format seconds into uptime string in the format: 00d 00h 00m 00s."""
uptime = datetime(1, 1, 1) + timedelta(seconds=_seconds)
return "{:0>2d}d {:0>2d}h {:0>2d}m {:0>2d}s".format(
uptime.day-1, uptime.hour, uptime.minute, uptime.second)
@property
def current_power_w(self):
"""Return the current power usage in W."""
if self.insight_params:
return convert(
self.insight_params['currentpower'], float, 0.0
) / 1000.0
@property
def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
if self.insight_params:
miliwatts = convert(self.insight_params['todaymw'], float, 0.0)
return round(miliwatts / (1000.0 * 1000.0 * 60), 2)
@property
def detail_state(self):
"""Return the state of the device."""
if self.coffeemaker_mode is not None:
return self._mode_string
if self.insight_params:
standby_state = int(self.insight_params['state'])
if standby_state == WEMO_ON:
return STATE_ON
if standby_state == WEMO_OFF:
return STATE_OFF
if standby_state == WEMO_STANDBY:
return STATE_STANDBY
return STATE_UNKNOWN
@property
def is_on(self):
"""Return true if switch is on. Standby is on."""
return self._state
@property
def available(self):
"""Return true if switch is available."""
return self._available
@property
def icon(self):
"""Return the icon of device based on its type."""
if self._model_name == 'CoffeeMaker':
return 'mdi:coffee'
return None
def turn_on(self, **kwargs):
"""Turn the switch on."""
self.wemo.on()
def turn_off(self, **kwargs):
"""Turn the switch off."""
self.wemo.off()
async def async_added_to_hass(self):
"""Wemo switch added to HASS."""
# Define inside async context so we know our event loop
self._update_lock = asyncio.Lock()
registry = SUBSCRIPTION_REGISTRY
await self.hass.async_add_job(registry.register, self.wemo)
registry.on(self.wemo, None, self._subscription_callback)
async def async_update(self):
"""Update WeMo state.
Wemo has an aggressive retry logic that sometimes can take over a
minute to return. If we don't get a state after 5 seconds, assume the
Wemo switch is unreachable. If update goes through, it will be made
available again.
"""
# If an update is in progress, we don't do anything
if self._update_lock.locked():
return
try:
with async_timeout.timeout(5):
await asyncio.shield(self._async_locked_update(True))
except asyncio.TimeoutError:
_LOGGER.warning('Lost connection to %s', self.name)
self._available = False
async def _async_locked_update(self, force_update):
"""Try updating within an async lock."""
async with self._update_lock:
await self.hass.async_add_job(self._update, force_update)
def _update(self, force_update):
"""Update the device state."""
try:
self._state = self.wemo.get_state(force_update)
if self._model_name == 'Insight':
self.insight_params = self.wemo.insight_params
self.insight_params['standby_state'] = (
self.wemo.get_standby_state)
elif self._model_name == 'Maker':
self.maker_params = self.wemo.maker_params
elif self._model_name == 'CoffeeMaker':
self.coffeemaker_mode = self.wemo.mode
self._mode_string = self.wemo.mode_string
if not self._available:
_LOGGER.info('Reconnected to %s', self.name)
self._available = True
except AttributeError as err:
_LOGGER.warning("Could not update status for %s (%s)",
self.name, err)
self._available = False
| MartinHjelmare/home-assistant | homeassistant/components/wemo/switch.py | Python | apache-2.0 | 8,674 |
class AddAvatarsToUsers < ActiveRecord::Migration
def self.up
add_attachment :users, :avatar
end
def self.down
remove_attachment :users, :avatar
end
end
| neversion/comment_sufia | sufia-models/lib/generators/sufia/models/templates/migrations/add_avatars_to_users.rb | Ruby | apache-2.0 | 170 |
/*
* 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 io.trino.plugin.hive.rcfile;
import io.trino.plugin.hive.FileFormatDataSourceStats;
import io.trino.rcfile.RcFileDataSource;
import io.trino.rcfile.RcFileDataSourceId;
import org.apache.hadoop.fs.FSDataInputStream;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public class HdfsRcFileDataSource
implements RcFileDataSource
{
private final FSDataInputStream inputStream;
private final String path;
private final long size;
private final FileFormatDataSourceStats stats;
private long readTimeNanos;
private long readBytes;
public HdfsRcFileDataSource(String path, FSDataInputStream inputStream, long size, FileFormatDataSourceStats stats)
{
this.path = requireNonNull(path, "path is null");
this.inputStream = requireNonNull(inputStream, "inputStream is null");
this.size = size;
checkArgument(size >= 0, "size is negative");
this.stats = requireNonNull(stats, "stats is null");
}
@Override
public RcFileDataSourceId getId()
{
return new RcFileDataSourceId(path);
}
@Override
public void close()
throws IOException
{
inputStream.close();
}
@Override
public long getReadBytes()
{
return readBytes;
}
@Override
public long getReadTimeNanos()
{
return readTimeNanos;
}
@Override
public long getSize()
{
return size;
}
@Override
public void readFully(long position, byte[] buffer, int bufferOffset, int bufferLength)
throws IOException
{
long start = System.nanoTime();
inputStream.readFully(position, buffer, bufferOffset, bufferLength);
long readDuration = System.nanoTime() - start;
stats.readDataBytesPerSecond(bufferLength, readDuration);
readTimeNanos += readDuration;
readBytes += bufferLength;
}
@Override
public String toString()
{
return path;
}
}
| electrum/presto | plugin/trino-hive/src/main/java/io/trino/plugin/hive/rcfile/HdfsRcFileDataSource.java | Java | apache-2.0 | 2,649 |
import("util.lua")
local f, g, a, b, c, x = Consts("f, g, a, b, c, x")
local m1 = mk_metavar("m1")
local m2 = mk_metavar("m2")
local m3 = mk_metavar("m3")
local s = fo_unify(f(m1, g(m2, c)), f(g(m2, a), g(m3, m3)))
assert(s)
assert(#s == 3)
assert(s:find(m2) == c)
assert(s:apply(f(m1, g(m2, c))) == s:apply(f(g(m2, a), g(m3, m3))))
assert(not fo_unify(f(a), g(m2)))
function must_unify(t1, t2)
local s = fo_unify(t1, t2)
assert(s)
print(t1, t2, s:apply(t1))
assert(s:apply(t1) == s:apply(t2))
end
Bool = Const("Bool")
must_unify(Type(), m1)
must_unify(fun(x, Bool, x), fun(x, Bool, m1))
must_unify(Pi(x, Bool, x), Pi(x, Bool, m1))
must_unify(Var(0), m1)
must_unify(f(m1, m2, m3), f(m1, m1, m2))
must_unify(mk_let("x", f(b), Var(0)), mk_let("y", f(m1), Var(0)))
assert(not fo_unify(mk_let("x", Bool, f(b), Var(0)), mk_let("y", f(m1), Var(0))))
assert(not fo_unify(mk_let("x", f(b), Var(0)), mk_let("y", Bool, f(m1), Var(0))))
must_unify(mk_let("x", Bool, f(b), Var(0)), mk_let("y", Bool, f(m1), Var(0)))
assert(not fo_unify(mk_let("x", Bool, f(b), Var(0)), fun(x, Bool, x)))
must_unify(iVal(10), m1)
must_unify(iVal(10), iVal(10))
| codyroux/lean0.1 | tests/lua/unify1.lua | Lua | apache-2.0 | 1,144 |
package brooklyn.entity.nosql.mongodb.sharding;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.entity.Entity;
import brooklyn.entity.group.DynamicClusterImpl;
import brooklyn.entity.nosql.mongodb.MongoDBClientSupport;
import brooklyn.entity.nosql.mongodb.MongoDBReplicaSet;
import brooklyn.entity.nosql.mongodb.MongoDBServer;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.trait.Startable;
import brooklyn.event.SensorEvent;
import brooklyn.event.SensorEventListener;
import brooklyn.location.Location;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.text.Strings;
import com.google.common.collect.Sets;
public class MongoDBShardClusterImpl extends DynamicClusterImpl implements MongoDBShardCluster {
private static final Logger LOG = LoggerFactory.getLogger(MongoDBShardClusterImpl.class);
// TODO: Need to use attributes for this in order to support brooklyn restart
private Set<Entity> addedMembers = Sets.newConcurrentHashSet();
@Override
protected EntitySpec<?> getMemberSpec() {
EntitySpec<?> result = super.getMemberSpec();
if (result == null)
result = EntitySpec.create(MongoDBReplicaSet.class);
result.configure(DynamicClusterImpl.INITIAL_SIZE, getConfig(MongoDBShardedDeployment.SHARD_REPLICASET_SIZE));
return result;
}
@Override
public void start(Collection<? extends Location> locations) {
subscribeToMembers(this, Startable.SERVICE_UP, new SensorEventListener<Boolean>() {
public void onEvent(SensorEvent<Boolean> event) {
addShards();
}
});
super.start(locations);
MongoDBRouterCluster routers = getParent().getAttribute(MongoDBShardedDeployment.ROUTER_CLUSTER);
subscribe(routers, MongoDBRouterCluster.ANY_RUNNING_ROUTER, new SensorEventListener<MongoDBRouter>() {
public void onEvent(SensorEvent<MongoDBRouter> event) {
if (event.getValue() != null)
addShards();
}
});
}
protected void addShards() {
MongoDBRouter router = getParent().getAttribute(MongoDBShardedDeployment.ROUTER_CLUSTER).getAttribute(MongoDBRouterCluster.ANY_RUNNING_ROUTER);
if (router == null)
return;
MongoDBClientSupport client;
try {
client = MongoDBClientSupport.forServer(router);
} catch (UnknownHostException e) {
throw Exceptions.propagate(e);
}
for (Entity member : this.getMembers()) {
if (member.getAttribute(Startable.SERVICE_UP) && !addedMembers.contains(member)) {
MongoDBServer primary = member.getAttribute(MongoDBReplicaSet.PRIMARY_ENTITY);
String addr = Strings.removeFromStart(primary.getAttribute(MongoDBServer.MONGO_SERVER_ENDPOINT), "http://");
String replicaSetURL = ((MongoDBReplicaSet) member).getName() + "/" + addr;
LOG.info("Using {} to add shard URL {}...", router, replicaSetURL);
client.addShardToRouter(replicaSetURL);
addedMembers.add(member);
}
}
}
}
| azharhashmi/brooklyn | software/nosql/src/main/java/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardClusterImpl.java | Java | apache-2.0 | 3,318 |
/*
* Copyright 2010 JBoss 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 org.drools.core.reteoo;
import org.drools.core.common.BetaConstraints;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.reteoo.builder.BuildContext;
import org.drools.core.spi.PropagationContext;
/**
* <code>ExistsNode</code> extends <code>BetaNode</code> to perform tests for
* the existence of a Fact plus one or more conditions. Where existence
* is found the left ReteTuple is copied and propagated. Further to this it
* maintains the "truth" by canceling any
* <code>Activation<code>s that are no longer
* considered true by the retraction of ReteTuple's or FactHandleImpl.
* Tuples are considered to be asserted from the left input and facts from the right input.
* The <code>BetaNode</code> provides the BetaMemory to store asserted ReteTuples and
* <code>FactHandleImpl<code>s. Each fact handle is stored in the right
* memory.
*/
public class ExistsNode extends BetaNode {
private static final long serialVersionUID = 510l;
public ExistsNode() { }
public ExistsNode(final int id,
final LeftTupleSource leftInput,
final ObjectSource rightInput,
final BetaConstraints joinNodeBinder,
final BuildContext context) {
super( id,
leftInput,
rightInput,
joinNodeBinder,
context );
this.tupleMemoryEnabled = context.isTupleMemoryEnabled();
}
public String toString() {
ObjectSource source = this.rightInput;
while ( source != null && source.getClass() != ObjectTypeNode.class ) {
source = source.source;
}
return "[ExistsNode(" + this.getId() + ") - " + ((source != null) ? ((ObjectTypeNode) source).getObjectType() : "<source from a subnetwork>") + "]";
}
public short getType() {
return NodeTypeEnums.ExistsNode;
}
public LeftTuple createLeftTuple(InternalFactHandle factHandle,
LeftTupleSink sink,
boolean leftTupleMemoryEnabled) {
return new NotNodeLeftTuple(factHandle, sink, leftTupleMemoryEnabled );
}
public LeftTuple createLeftTuple(final InternalFactHandle factHandle,
final LeftTuple leftTuple,
final LeftTupleSink sink) {
return new NotNodeLeftTuple(factHandle,leftTuple, sink );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
LeftTupleSink sink,
PropagationContext pctx,
boolean leftTupleMemoryEnabled) {
return new NotNodeLeftTuple(leftTuple,sink, pctx, leftTupleMemoryEnabled );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
RightTuple rightTuple,
LeftTupleSink sink) {
return new NotNodeLeftTuple(leftTuple, rightTuple, sink );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
RightTuple rightTuple,
LeftTuple currentLeftChild,
LeftTuple currentRightChild,
LeftTupleSink sink,
boolean leftTupleMemoryEnabled) {
return new NotNodeLeftTuple(leftTuple, rightTuple, currentLeftChild, currentRightChild, sink, leftTupleMemoryEnabled );
}
public LeftTuple createPeer(LeftTuple original) {
NotNodeLeftTuple peer = new NotNodeLeftTuple();
peer.initPeer( (BaseLeftTuple) original, this );
original.setPeer( peer );
return peer;
}
@Override
public void assertRightTuple(RightTuple rightTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
public void retractRightTuple(final RightTuple rightTuple,
final PropagationContext pctx,
final InternalWorkingMemory workingMemory) {
final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this );
rightTuple.setPropagationContext( pctx );
doDeleteRightTuple( rightTuple,
workingMemory,
memory );
}
@Override
public void modifyRightTuple(RightTuple rightTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void assertLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void retractLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void modifyLeftTuple(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void modifyLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void updateSink(LeftTupleSink sink, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public boolean doRemove(RuleRemovalContext context, ReteooBuilder builder, InternalWorkingMemory[] workingMemories) {
if ( !isInUse() ) {
getLeftTupleSource().removeTupleSink( this );
getRightInput().removeObjectSink( this );
return true;
}
return false;
}
public boolean isLeftUpdateOptimizationAllowed() {
return getRawConstraints().isLeftUpdateOptimizationAllowed();
}
}
| amckee23/drools | drools-core/src/main/java/org/drools/core/reteoo/ExistsNode.java | Java | apache-2.0 | 6,823 |
// This file was generated by counterfeiter
package fakes
import (
. "github.com/cloudfoundry/cli/cf/actors/service_builder"
"github.com/cloudfoundry/cli/cf/models"
"sync"
)
type FakeServiceBuilder struct {
GetAllServicesStub func() ([]models.ServiceOffering, error)
getAllServicesMutex sync.RWMutex
getAllServicesArgsForCall []struct{}
getAllServicesReturns struct {
result1 []models.ServiceOffering
result2 error
}
GetAllServicesWithPlansStub func() ([]models.ServiceOffering, error)
getAllServicesWithPlansMutex sync.RWMutex
getAllServicesWithPlansArgsForCall []struct{}
getAllServicesWithPlansReturns struct {
result1 []models.ServiceOffering
result2 error
}
GetServiceByNameWithPlansStub func(string) (models.ServiceOffering, error)
getServiceByNameWithPlansMutex sync.RWMutex
getServiceByNameWithPlansArgsForCall []struct {
arg1 string
}
getServiceByNameWithPlansReturns struct {
result1 models.ServiceOffering
result2 error
}
GetServiceByNameWithPlansWithOrgNamesStub func(string) (models.ServiceOffering, error)
getServiceByNameWithPlansWithOrgNamesMutex sync.RWMutex
getServiceByNameWithPlansWithOrgNamesArgsForCall []struct {
arg1 string
}
getServiceByNameWithPlansWithOrgNamesReturns struct {
result1 models.ServiceOffering
result2 error
}
GetServiceByNameForSpaceStub func(string, string) (models.ServiceOffering, error)
getServiceByNameForSpaceMutex sync.RWMutex
getServiceByNameForSpaceArgsForCall []struct {
arg1 string
arg2 string
}
getServiceByNameForSpaceReturns struct {
result1 models.ServiceOffering
result2 error
}
GetServiceByNameForSpaceWithPlansStub func(string, string) (models.ServiceOffering, error)
getServiceByNameForSpaceWithPlansMutex sync.RWMutex
getServiceByNameForSpaceWithPlansArgsForCall []struct {
arg1 string
arg2 string
}
getServiceByNameForSpaceWithPlansReturns struct {
result1 models.ServiceOffering
result2 error
}
GetServicesByNameForSpaceWithPlansStub func(string, string) (models.ServiceOfferings, error)
getServicesByNameForSpaceWithPlansMutex sync.RWMutex
getServicesByNameForSpaceWithPlansArgsForCall []struct {
arg1 string
arg2 string
}
getServicesByNameForSpaceWithPlansReturns struct {
result1 models.ServiceOfferings
result2 error
}
GetServiceByNameForOrgStub func(string, string) (models.ServiceOffering, error)
getServiceByNameForOrgMutex sync.RWMutex
getServiceByNameForOrgArgsForCall []struct {
arg1 string
arg2 string
}
getServiceByNameForOrgReturns struct {
result1 models.ServiceOffering
result2 error
}
GetServicesForBrokerStub func(string) ([]models.ServiceOffering, error)
getServicesForBrokerMutex sync.RWMutex
getServicesForBrokerArgsForCall []struct {
arg1 string
}
getServicesForBrokerReturns struct {
result1 []models.ServiceOffering
result2 error
}
GetServicesForSpaceStub func(string) ([]models.ServiceOffering, error)
getServicesForSpaceMutex sync.RWMutex
getServicesForSpaceArgsForCall []struct {
arg1 string
}
getServicesForSpaceReturns struct {
result1 []models.ServiceOffering
result2 error
}
GetServicesForSpaceWithPlansStub func(string) ([]models.ServiceOffering, error)
getServicesForSpaceWithPlansMutex sync.RWMutex
getServicesForSpaceWithPlansArgsForCall []struct {
arg1 string
}
getServicesForSpaceWithPlansReturns struct {
result1 []models.ServiceOffering
result2 error
}
GetServiceVisibleToOrgStub func(string, string) (models.ServiceOffering, error)
getServiceVisibleToOrgMutex sync.RWMutex
getServiceVisibleToOrgArgsForCall []struct {
arg1 string
arg2 string
}
getServiceVisibleToOrgReturns struct {
result1 models.ServiceOffering
result2 error
}
GetServicesVisibleToOrgStub func(string) ([]models.ServiceOffering, error)
getServicesVisibleToOrgMutex sync.RWMutex
getServicesVisibleToOrgArgsForCall []struct {
arg1 string
}
getServicesVisibleToOrgReturns struct {
result1 []models.ServiceOffering
result2 error
}
}
func (fake *FakeServiceBuilder) GetAllServices() ([]models.ServiceOffering, error) {
fake.getAllServicesMutex.Lock()
defer fake.getAllServicesMutex.Unlock()
fake.getAllServicesArgsForCall = append(fake.getAllServicesArgsForCall, struct{}{})
if fake.GetAllServicesStub != nil {
return fake.GetAllServicesStub()
} else {
return fake.getAllServicesReturns.result1, fake.getAllServicesReturns.result2
}
}
func (fake *FakeServiceBuilder) GetAllServicesCallCount() int {
fake.getAllServicesMutex.RLock()
defer fake.getAllServicesMutex.RUnlock()
return len(fake.getAllServicesArgsForCall)
}
func (fake *FakeServiceBuilder) GetAllServicesReturns(result1 []models.ServiceOffering, result2 error) {
fake.getAllServicesReturns = struct {
result1 []models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetAllServicesWithPlans() ([]models.ServiceOffering, error) {
fake.getAllServicesWithPlansMutex.Lock()
defer fake.getAllServicesWithPlansMutex.Unlock()
fake.getAllServicesWithPlansArgsForCall = append(fake.getAllServicesWithPlansArgsForCall, struct{}{})
if fake.GetAllServicesWithPlansStub != nil {
return fake.GetAllServicesWithPlansStub()
} else {
return fake.getAllServicesWithPlansReturns.result1, fake.getAllServicesWithPlansReturns.result2
}
}
func (fake *FakeServiceBuilder) GetAllServicesWithPlansCallCount() int {
fake.getAllServicesWithPlansMutex.RLock()
defer fake.getAllServicesWithPlansMutex.RUnlock()
return len(fake.getAllServicesWithPlansArgsForCall)
}
func (fake *FakeServiceBuilder) GetAllServicesWithPlansReturns(result1 []models.ServiceOffering, result2 error) {
fake.getAllServicesWithPlansReturns = struct {
result1 []models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlans(arg1 string) (models.ServiceOffering, error) {
fake.getServiceByNameWithPlansMutex.Lock()
defer fake.getServiceByNameWithPlansMutex.Unlock()
fake.getServiceByNameWithPlansArgsForCall = append(fake.getServiceByNameWithPlansArgsForCall, struct {
arg1 string
}{arg1})
if fake.GetServiceByNameWithPlansStub != nil {
return fake.GetServiceByNameWithPlansStub(arg1)
} else {
return fake.getServiceByNameWithPlansReturns.result1, fake.getServiceByNameWithPlansReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansCallCount() int {
fake.getServiceByNameWithPlansMutex.RLock()
defer fake.getServiceByNameWithPlansMutex.RUnlock()
return len(fake.getServiceByNameWithPlansArgsForCall)
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansArgsForCall(i int) string {
fake.getServiceByNameWithPlansMutex.RLock()
defer fake.getServiceByNameWithPlansMutex.RUnlock()
return fake.getServiceByNameWithPlansArgsForCall[i].arg1
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansReturns(result1 models.ServiceOffering, result2 error) {
fake.getServiceByNameWithPlansReturns = struct {
result1 models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansWithOrgNames(arg1 string) (models.ServiceOffering, error) {
fake.getServiceByNameWithPlansWithOrgNamesMutex.Lock()
defer fake.getServiceByNameWithPlansWithOrgNamesMutex.Unlock()
fake.getServiceByNameWithPlansWithOrgNamesArgsForCall = append(fake.getServiceByNameWithPlansWithOrgNamesArgsForCall, struct {
arg1 string
}{arg1})
if fake.GetServiceByNameWithPlansWithOrgNamesStub != nil {
return fake.GetServiceByNameWithPlansWithOrgNamesStub(arg1)
} else {
return fake.getServiceByNameWithPlansWithOrgNamesReturns.result1, fake.getServiceByNameWithPlansWithOrgNamesReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansWithOrgNamesCallCount() int {
fake.getServiceByNameWithPlansWithOrgNamesMutex.RLock()
defer fake.getServiceByNameWithPlansWithOrgNamesMutex.RUnlock()
return len(fake.getServiceByNameWithPlansWithOrgNamesArgsForCall)
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansWithOrgNamesArgsForCall(i int) string {
fake.getServiceByNameWithPlansWithOrgNamesMutex.RLock()
defer fake.getServiceByNameWithPlansWithOrgNamesMutex.RUnlock()
return fake.getServiceByNameWithPlansWithOrgNamesArgsForCall[i].arg1
}
func (fake *FakeServiceBuilder) GetServiceByNameWithPlansWithOrgNamesReturns(result1 models.ServiceOffering, result2 error) {
fake.getServiceByNameWithPlansWithOrgNamesReturns = struct {
result1 models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpace(arg1 string, arg2 string) (models.ServiceOffering, error) {
fake.getServiceByNameForSpaceMutex.Lock()
defer fake.getServiceByNameForSpaceMutex.Unlock()
fake.getServiceByNameForSpaceArgsForCall = append(fake.getServiceByNameForSpaceArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
if fake.GetServiceByNameForSpaceStub != nil {
return fake.GetServiceByNameForSpaceStub(arg1, arg2)
} else {
return fake.getServiceByNameForSpaceReturns.result1, fake.getServiceByNameForSpaceReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceCallCount() int {
fake.getServiceByNameForSpaceMutex.RLock()
defer fake.getServiceByNameForSpaceMutex.RUnlock()
return len(fake.getServiceByNameForSpaceArgsForCall)
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceArgsForCall(i int) (string, string) {
fake.getServiceByNameForSpaceMutex.RLock()
defer fake.getServiceByNameForSpaceMutex.RUnlock()
return fake.getServiceByNameForSpaceArgsForCall[i].arg1, fake.getServiceByNameForSpaceArgsForCall[i].arg2
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceReturns(result1 models.ServiceOffering, result2 error) {
fake.getServiceByNameForSpaceReturns = struct {
result1 models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceWithPlans(arg1 string, arg2 string) (models.ServiceOffering, error) {
fake.getServiceByNameForSpaceWithPlansMutex.Lock()
defer fake.getServiceByNameForSpaceWithPlansMutex.Unlock()
fake.getServiceByNameForSpaceWithPlansArgsForCall = append(fake.getServiceByNameForSpaceWithPlansArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
if fake.GetServiceByNameForSpaceWithPlansStub != nil {
return fake.GetServiceByNameForSpaceWithPlansStub(arg1, arg2)
} else {
return fake.getServiceByNameForSpaceWithPlansReturns.result1, fake.getServiceByNameForSpaceWithPlansReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceWithPlansCallCount() int {
fake.getServiceByNameForSpaceWithPlansMutex.RLock()
defer fake.getServiceByNameForSpaceWithPlansMutex.RUnlock()
return len(fake.getServiceByNameForSpaceWithPlansArgsForCall)
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceWithPlansArgsForCall(i int) (string, string) {
fake.getServiceByNameForSpaceWithPlansMutex.RLock()
defer fake.getServiceByNameForSpaceWithPlansMutex.RUnlock()
return fake.getServiceByNameForSpaceWithPlansArgsForCall[i].arg1, fake.getServiceByNameForSpaceWithPlansArgsForCall[i].arg2
}
func (fake *FakeServiceBuilder) GetServiceByNameForSpaceWithPlansReturns(result1 models.ServiceOffering, result2 error) {
fake.getServiceByNameForSpaceWithPlansReturns = struct {
result1 models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServicesByNameForSpaceWithPlans(arg1 string, arg2 string) (models.ServiceOfferings, error) {
fake.getServicesByNameForSpaceWithPlansMutex.Lock()
defer fake.getServicesByNameForSpaceWithPlansMutex.Unlock()
fake.getServicesByNameForSpaceWithPlansArgsForCall = append(fake.getServicesByNameForSpaceWithPlansArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
if fake.GetServicesByNameForSpaceWithPlansStub != nil {
return fake.GetServicesByNameForSpaceWithPlansStub(arg1, arg2)
} else {
return fake.getServicesByNameForSpaceWithPlansReturns.result1, fake.getServicesByNameForSpaceWithPlansReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServicesByNameForSpaceWithPlansCallCount() int {
fake.getServicesByNameForSpaceWithPlansMutex.RLock()
defer fake.getServicesByNameForSpaceWithPlansMutex.RUnlock()
return len(fake.getServicesByNameForSpaceWithPlansArgsForCall)
}
func (fake *FakeServiceBuilder) GetServicesByNameForSpaceWithPlansArgsForCall(i int) (string, string) {
fake.getServicesByNameForSpaceWithPlansMutex.RLock()
defer fake.getServicesByNameForSpaceWithPlansMutex.RUnlock()
return fake.getServicesByNameForSpaceWithPlansArgsForCall[i].arg1, fake.getServicesByNameForSpaceWithPlansArgsForCall[i].arg2
}
func (fake *FakeServiceBuilder) GetServicesByNameForSpaceWithPlansReturns(result1 models.ServiceOfferings, result2 error) {
fake.getServicesByNameForSpaceWithPlansReturns = struct {
result1 models.ServiceOfferings
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServiceByNameForOrg(arg1 string, arg2 string) (models.ServiceOffering, error) {
fake.getServiceByNameForOrgMutex.Lock()
defer fake.getServiceByNameForOrgMutex.Unlock()
fake.getServiceByNameForOrgArgsForCall = append(fake.getServiceByNameForOrgArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
if fake.GetServiceByNameForOrgStub != nil {
return fake.GetServiceByNameForOrgStub(arg1, arg2)
} else {
return fake.getServiceByNameForOrgReturns.result1, fake.getServiceByNameForOrgReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServiceByNameForOrgCallCount() int {
fake.getServiceByNameForOrgMutex.RLock()
defer fake.getServiceByNameForOrgMutex.RUnlock()
return len(fake.getServiceByNameForOrgArgsForCall)
}
func (fake *FakeServiceBuilder) GetServiceByNameForOrgArgsForCall(i int) (string, string) {
fake.getServiceByNameForOrgMutex.RLock()
defer fake.getServiceByNameForOrgMutex.RUnlock()
return fake.getServiceByNameForOrgArgsForCall[i].arg1, fake.getServiceByNameForOrgArgsForCall[i].arg2
}
func (fake *FakeServiceBuilder) GetServiceByNameForOrgReturns(result1 models.ServiceOffering, result2 error) {
fake.getServiceByNameForOrgReturns = struct {
result1 models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServicesForBroker(arg1 string) ([]models.ServiceOffering, error) {
fake.getServicesForBrokerMutex.Lock()
defer fake.getServicesForBrokerMutex.Unlock()
fake.getServicesForBrokerArgsForCall = append(fake.getServicesForBrokerArgsForCall, struct {
arg1 string
}{arg1})
if fake.GetServicesForBrokerStub != nil {
return fake.GetServicesForBrokerStub(arg1)
} else {
return fake.getServicesForBrokerReturns.result1, fake.getServicesForBrokerReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServicesForBrokerCallCount() int {
fake.getServicesForBrokerMutex.RLock()
defer fake.getServicesForBrokerMutex.RUnlock()
return len(fake.getServicesForBrokerArgsForCall)
}
func (fake *FakeServiceBuilder) GetServicesForBrokerArgsForCall(i int) string {
fake.getServicesForBrokerMutex.RLock()
defer fake.getServicesForBrokerMutex.RUnlock()
return fake.getServicesForBrokerArgsForCall[i].arg1
}
func (fake *FakeServiceBuilder) GetServicesForBrokerReturns(result1 []models.ServiceOffering, result2 error) {
fake.getServicesForBrokerReturns = struct {
result1 []models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServicesForSpace(arg1 string) ([]models.ServiceOffering, error) {
fake.getServicesForSpaceMutex.Lock()
defer fake.getServicesForSpaceMutex.Unlock()
fake.getServicesForSpaceArgsForCall = append(fake.getServicesForSpaceArgsForCall, struct {
arg1 string
}{arg1})
if fake.GetServicesForSpaceStub != nil {
return fake.GetServicesForSpaceStub(arg1)
} else {
return fake.getServicesForSpaceReturns.result1, fake.getServicesForSpaceReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServicesForSpaceCallCount() int {
fake.getServicesForSpaceMutex.RLock()
defer fake.getServicesForSpaceMutex.RUnlock()
return len(fake.getServicesForSpaceArgsForCall)
}
func (fake *FakeServiceBuilder) GetServicesForSpaceArgsForCall(i int) string {
fake.getServicesForSpaceMutex.RLock()
defer fake.getServicesForSpaceMutex.RUnlock()
return fake.getServicesForSpaceArgsForCall[i].arg1
}
func (fake *FakeServiceBuilder) GetServicesForSpaceReturns(result1 []models.ServiceOffering, result2 error) {
fake.getServicesForSpaceReturns = struct {
result1 []models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServicesForSpaceWithPlans(arg1 string) ([]models.ServiceOffering, error) {
fake.getServicesForSpaceWithPlansMutex.Lock()
defer fake.getServicesForSpaceWithPlansMutex.Unlock()
fake.getServicesForSpaceWithPlansArgsForCall = append(fake.getServicesForSpaceWithPlansArgsForCall, struct {
arg1 string
}{arg1})
if fake.GetServicesForSpaceWithPlansStub != nil {
return fake.GetServicesForSpaceWithPlansStub(arg1)
} else {
return fake.getServicesForSpaceWithPlansReturns.result1, fake.getServicesForSpaceWithPlansReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServicesForSpaceWithPlansCallCount() int {
fake.getServicesForSpaceWithPlansMutex.RLock()
defer fake.getServicesForSpaceWithPlansMutex.RUnlock()
return len(fake.getServicesForSpaceWithPlansArgsForCall)
}
func (fake *FakeServiceBuilder) GetServicesForSpaceWithPlansArgsForCall(i int) string {
fake.getServicesForSpaceWithPlansMutex.RLock()
defer fake.getServicesForSpaceWithPlansMutex.RUnlock()
return fake.getServicesForSpaceWithPlansArgsForCall[i].arg1
}
func (fake *FakeServiceBuilder) GetServicesForSpaceWithPlansReturns(result1 []models.ServiceOffering, result2 error) {
fake.getServicesForSpaceWithPlansReturns = struct {
result1 []models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServiceVisibleToOrg(arg1 string, arg2 string) (models.ServiceOffering, error) {
fake.getServiceVisibleToOrgMutex.Lock()
defer fake.getServiceVisibleToOrgMutex.Unlock()
fake.getServiceVisibleToOrgArgsForCall = append(fake.getServiceVisibleToOrgArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
if fake.GetServiceVisibleToOrgStub != nil {
return fake.GetServiceVisibleToOrgStub(arg1, arg2)
} else {
return fake.getServiceVisibleToOrgReturns.result1, fake.getServiceVisibleToOrgReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServiceVisibleToOrgCallCount() int {
fake.getServiceVisibleToOrgMutex.RLock()
defer fake.getServiceVisibleToOrgMutex.RUnlock()
return len(fake.getServiceVisibleToOrgArgsForCall)
}
func (fake *FakeServiceBuilder) GetServiceVisibleToOrgArgsForCall(i int) (string, string) {
fake.getServiceVisibleToOrgMutex.RLock()
defer fake.getServiceVisibleToOrgMutex.RUnlock()
return fake.getServiceVisibleToOrgArgsForCall[i].arg1, fake.getServiceVisibleToOrgArgsForCall[i].arg2
}
func (fake *FakeServiceBuilder) GetServiceVisibleToOrgReturns(result1 models.ServiceOffering, result2 error) {
fake.getServiceVisibleToOrgReturns = struct {
result1 models.ServiceOffering
result2 error
}{result1, result2}
}
func (fake *FakeServiceBuilder) GetServicesVisibleToOrg(arg1 string) ([]models.ServiceOffering, error) {
fake.getServicesVisibleToOrgMutex.Lock()
defer fake.getServicesVisibleToOrgMutex.Unlock()
fake.getServicesVisibleToOrgArgsForCall = append(fake.getServicesVisibleToOrgArgsForCall, struct {
arg1 string
}{arg1})
if fake.GetServicesVisibleToOrgStub != nil {
return fake.GetServicesVisibleToOrgStub(arg1)
} else {
return fake.getServicesVisibleToOrgReturns.result1, fake.getServicesVisibleToOrgReturns.result2
}
}
func (fake *FakeServiceBuilder) GetServicesVisibleToOrgCallCount() int {
fake.getServicesVisibleToOrgMutex.RLock()
defer fake.getServicesVisibleToOrgMutex.RUnlock()
return len(fake.getServicesVisibleToOrgArgsForCall)
}
func (fake *FakeServiceBuilder) GetServicesVisibleToOrgArgsForCall(i int) string {
fake.getServicesVisibleToOrgMutex.RLock()
defer fake.getServicesVisibleToOrgMutex.RUnlock()
return fake.getServicesVisibleToOrgArgsForCall[i].arg1
}
func (fake *FakeServiceBuilder) GetServicesVisibleToOrgReturns(result1 []models.ServiceOffering, result2 error) {
fake.getServicesVisibleToOrgReturns = struct {
result1 []models.ServiceOffering
result2 error
}{result1, result2}
}
var _ ServiceBuilder = new(FakeServiceBuilder)
| zhang-hua/cli | cf/actors/service_builder/fakes/fake_service_builder.go | GO | apache-2.0 | 20,554 |
/**
* 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.nutch.protocol.ftp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;
//import java.util.LinkedList;
import org.apache.commons.net.MalformedServerReplyException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPCommand;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParser;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
/***********************************************
* Client.java encapsulates functionalities necessary for nutch to
* get dir list and retrieve file from an FTP server.
* This class takes care of all low level details of interacting
* with an FTP server and provides a convenient higher level interface.
*
* Modified from FtpClient.java in apache commons-net.
*
* Notes by John Xing:
* ftp server implementations are hardly uniform and none seems to follow
* RFCs whole-heartedly. We have no choice, but assume common denominator
* as following:
* (1) Use stream mode for data transfer. Block mode will be better for
* multiple file downloading and partial file downloading. However
* not every ftpd has block mode support.
* (2) Use passive mode for data connection.
* So Nutch will work if we run behind firewall.
* (3) Data connection is opened/closed per ftp command for the reasons
* listed in (1). There are ftp servers out there,
* when partial downloading is enforced by closing data channel
* socket on our client side, the server side immediately closes
* control channel (socket). Our codes deal with such a bad behavior.
* (4) LIST is used to obtain remote file attributes if possible.
* MDTM & SIZE would be nice, but not as ubiquitously implemented as LIST.
* (5) Avoid using ABOR in single thread? Do not use it at all.
*
* About exceptions:
* Some specific exceptions are re-thrown as one of FtpException*.java
* In fact, each function throws FtpException*.java or pass IOException.
*
* @author John Xing
***********************************************/
public class Client extends FTP
{
private int __dataTimeout;
private int __passivePort;
private String __passiveHost;
// private int __fileType, __fileFormat;
private boolean __remoteVerificationEnabled;
// private FTPFileEntryParser __entryParser;
private String __systemName;
/** Public default constructor */
public Client()
{
__initDefaults();
__dataTimeout = -1;
__remoteVerificationEnabled = true;
}
// defaults when initialize
private void __initDefaults()
{
__passiveHost = null;
__passivePort = -1;
__systemName = null;
// __fileType = FTP.ASCII_FILE_TYPE;
// __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
// __entryParser = null;
}
// parse reply for pass()
private void __parsePassiveModeReply(String reply)
throws MalformedServerReplyException
{
int i, index, lastIndex;
String octet1, octet2;
StringBuffer host;
reply = reply.substring(reply.indexOf('(') + 1,
reply.indexOf(')')).trim();
host = new StringBuffer(24);
lastIndex = 0;
index = reply.indexOf(',');
host.append(reply.substring(lastIndex, index));
for (i = 0; i < 3; i++)
{
host.append('.');
lastIndex = index + 1;
index = reply.indexOf(',', lastIndex);
host.append(reply.substring(lastIndex, index));
}
lastIndex = index + 1;
index = reply.indexOf(',', lastIndex);
octet1 = reply.substring(lastIndex, index);
octet2 = reply.substring(index + 1);
// index and lastIndex now used as temporaries
try
{
index = Integer.parseInt(octet1);
lastIndex = Integer.parseInt(octet2);
}
catch (NumberFormatException e)
{
throw new MalformedServerReplyException(
"Could not parse passive host information.\nServer Reply: " + reply);
}
index <<= 8;
index |= lastIndex;
__passiveHost = host.toString();
__passivePort = index;
}
/**
* open a passive data connection socket
* @param command
* @param arg
* @return
* @throws IOException
* @throws FtpExceptionCanNotHaveDataConnection
*/
protected Socket __openPassiveDataConnection(int command, String arg)
throws IOException, FtpExceptionCanNotHaveDataConnection {
Socket socket;
// // 20040317, xing, accommodate ill-behaved servers, see below
// int port_previous = __passivePort;
if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
throw new FtpExceptionCanNotHaveDataConnection(
"pasv() failed. " + getReplyString());
try {
__parsePassiveModeReply(getReplyStrings()[0]);
} catch (MalformedServerReplyException e) {
throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
}
// // 20040317, xing, accommodate ill-behaved servers, see above
// int count = 0;
// System.err.println("__passivePort "+__passivePort);
// System.err.println("port_previous "+port_previous);
// while (__passivePort == port_previous) {
// // just quit if too many tries. make it an exception here?
// if (count++ > 10)
// return null;
// // slow down further for each new try
// Thread.sleep(500*count);
// if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
// throw new FtpExceptionCanNotHaveDataConnection(
// "pasv() failed. " + getReplyString());
// //return null;
// try {
// __parsePassiveModeReply(getReplyStrings()[0]);
// } catch (MalformedServerReplyException e) {
// throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
// }
// }
socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
socket.close();
return null;
}
if (__remoteVerificationEnabled && !verifyRemote(socket))
{
InetAddress host1, host2;
host1 = socket.getInetAddress();
host2 = getRemoteAddress();
socket.close();
// our precaution
throw new FtpExceptionCanNotHaveDataConnection(
"Host attempting data connection " + host1.getHostAddress() +
" is not same as server " + host2.getHostAddress() +
" So we intentionally close it for security precaution."
);
}
if (__dataTimeout >= 0)
socket.setSoTimeout(__dataTimeout);
return socket;
}
/***
* Sets the timeout in milliseconds to use for data connection.
* set immediately after opening the data connection.
***/
public void setDataTimeout(int timeout)
{
__dataTimeout = timeout;
}
/***
* Closes the connection to the FTP server and restores
* connection parameters to the default values.
* <p>
* @exception IOException If an error occurs while disconnecting.
***/
public void disconnect() throws IOException
{
__initDefaults();
super.disconnect();
// no worry for data connection, since we always close it
// in every ftp command that invloves data connection
}
/***
* Enable or disable verification that the remote host taking part
* of a data connection is the same as the host to which the control
* connection is attached. The default is for verification to be
* enabled. You may set this value at any time, whether the
* FTPClient is currently connected or not.
* <p>
* @param enable True to enable verification, false to disable verification.
***/
public void setRemoteVerificationEnabled(boolean enable)
{
__remoteVerificationEnabled = enable;
}
/***
* Return whether or not verification of the remote host participating
* in data connections is enabled. The default behavior is for
* verification to be enabled.
* <p>
* @return True if verification is enabled, false if not.
***/
public boolean isRemoteVerificationEnabled()
{
return __remoteVerificationEnabled;
}
/***
* Login to the FTP server using the provided username and password.
* <p>
* @param username The username to login under.
* @param password The password to use.
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public boolean login(String username, String password) throws IOException
{
user(username);
if (FTPReply.isPositiveCompletion(getReplyCode()))
return true;
// If we get here, we either have an error code, or an intermmediate
// reply requesting password.
if (!FTPReply.isPositiveIntermediate(getReplyCode()))
return false;
return FTPReply.isPositiveCompletion(pass(password));
}
/***
* Logout of the FTP server by sending the QUIT command.
* <p>
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public boolean logout() throws IOException
{
return FTPReply.isPositiveCompletion(quit());
}
/**
* retrieve list reply for path
* @param path
* @param entries
* @param limit
* @param parser
* @throws IOException
* @throws FtpExceptionCanNotHaveDataConnection
* @throws FtpExceptionUnknownForcedDataClose
* @throws FtpExceptionControlClosedByForcedDataClose
*/
public void retrieveList(String path, List<FTPFile> entries, int limit,
FTPFileEntryParser parser)
throws IOException,
FtpExceptionCanNotHaveDataConnection,
FtpExceptionUnknownForcedDataClose,
FtpExceptionControlClosedByForcedDataClose {
Socket socket = __openPassiveDataConnection(FTPCommand.LIST, path);
if (socket == null)
throw new FtpExceptionCanNotHaveDataConnection("LIST "
+ ((path == null) ? "" : path));
BufferedReader reader =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
// force-close data channel socket, when download limit is reached
// boolean mandatory_close = false;
//List entries = new LinkedList();
int count = 0;
String line = parser.readNextEntry(reader);
while (line != null) {
FTPFile ftpFile = parser.parseFTPEntry(line);
// skip non-formatted lines
if (ftpFile == null) {
line = parser.readNextEntry(reader);
continue;
}
entries.add(ftpFile);
count += line.length();
// impose download limit if limit >= 0, otherwise no limit
// here, cut off is up to the line when total bytes is just over limit
if (limit >= 0 && count > limit) {
// mandatory_close = true;
break;
}
line = parser.readNextEntry(reader);
}
//if (mandatory_close)
// you always close here, no matter mandatory_close or not.
// however different ftp servers respond differently, see below.
socket.close();
// scenarios:
// (1) mandatory_close is false, download limit not reached
// no special care here
// (2) mandatory_close is true, download limit is reached
// different servers have different reply codes:
try {
int reply = getReply();
if (!_notBadReply(reply))
throw new FtpExceptionUnknownForcedDataClose(getReplyString());
} catch (FTPConnectionClosedException e) {
// some ftp servers will close control channel if data channel socket
// is closed by our end before all data has been read out. Check:
// tux414.q-tam.hp.com FTP server (hp.com version whp02)
// so must catch FTPConnectionClosedException thrown by getReply() above
//disconnect();
throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
}
}
/**
* retrieve file for path
* @param path
* @param os
* @param limit
* @throws IOException
* @throws FtpExceptionCanNotHaveDataConnection
* @throws FtpExceptionUnknownForcedDataClose
* @throws FtpExceptionControlClosedByForcedDataClose
*/
public void retrieveFile(String path, OutputStream os, int limit)
throws IOException,
FtpExceptionCanNotHaveDataConnection,
FtpExceptionUnknownForcedDataClose,
FtpExceptionControlClosedByForcedDataClose {
Socket socket = __openPassiveDataConnection(FTPCommand.RETR, path);
if (socket == null)
throw new FtpExceptionCanNotHaveDataConnection("RETR "
+ ((path == null) ? "" : path));
InputStream input = socket.getInputStream();
// 20040318, xing, treat everything as BINARY_FILE_TYPE for now
// do we ever need ASCII_FILE_TYPE?
//if (__fileType == ASCII_FILE_TYPE)
// input = new FromNetASCIIInputStream(input);
// fixme, should we instruct server here for binary file type?
// force-close data channel socket
// boolean mandatory_close = false;
int len; int count = 0;
byte[] buf =
new byte[org.apache.commons.net.io.Util.DEFAULT_COPY_BUFFER_SIZE];
while((len=input.read(buf,0,buf.length)) != -1){
count += len;
// impose download limit if limit >= 0, otherwise no limit
// here, cut off is exactly of limit bytes
if (limit >= 0 && count > limit) {
os.write(buf,0,len-(count-limit));
// mandatory_close = true;
break;
}
os.write(buf,0,len);
os.flush();
}
//if (mandatory_close)
// you always close here, no matter mandatory_close or not.
// however different ftp servers respond differently, see below.
socket.close();
// scenarios:
// (1) mandatory_close is false, download limit not reached
// no special care here
// (2) mandatory_close is true, download limit is reached
// different servers have different reply codes:
// do not need this
//sendCommand("ABOR");
try {
int reply = getReply();
if (!_notBadReply(reply))
throw new FtpExceptionUnknownForcedDataClose(getReplyString());
} catch (FTPConnectionClosedException e) {
// some ftp servers will close control channel if data channel socket
// is closed by our end before all data has been read out. Check:
// tux414.q-tam.hp.com FTP server (hp.com version whp02)
// so must catch FTPConnectionClosedException thrown by getReply() above
//disconnect();
throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
}
}
/**
* reply check after closing data connection
* @param reply
* @return
*/
private boolean _notBadReply(int reply) {
if (FTPReply.isPositiveCompletion(reply)) {
// do nothing
} else if (reply == 426) { // FTPReply.TRANSFER_ABORTED
// some ftp servers reply 426, e.g.,
// foggy FTP server (Version wu-2.6.2(2)
// there is second reply witing? no!
//getReply();
} else if (reply == 450) { // FTPReply.FILE_ACTION_NOT_TAKEN
// some ftp servers reply 450, e.g.,
// ProFTPD [ftp.kernel.org]
// there is second reply witing? no!
//getReply();
} else if (reply == 451) { // FTPReply.ACTION_ABORTED
// some ftp servers reply 451, e.g.,
// ProFTPD [ftp.kernel.org]
// there is second reply witing? no!
//getReply();
} else if (reply == 451) { // FTPReply.ACTION_ABORTED
} else {
// what other kind of ftp server out there?
return false;
}
return true;
}
/***
* Sets the file type to be transferred. This should be one of
* <code> FTP.ASCII_FILE_TYPE </code>, <code> FTP.IMAGE_FILE_TYPE </code>,
* etc. The file type only needs to be set when you want to change the
* type. After changing it, the new type stays in effect until you change
* it again. The default file type is <code> FTP.ASCII_FILE_TYPE </code>
* if this method is never called.
* <p>
* @param fileType The <code> _FILE_TYPE </code> constant indcating the
* type of file.
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public boolean setFileType(int fileType) throws IOException
{
if (FTPReply.isPositiveCompletion(type(fileType)))
{
/* __fileType = fileType;
__fileFormat = FTP.NON_PRINT_TEXT_FORMAT;*/
return true;
}
return false;
}
/***
* Fetches the system type name from the server and returns the string.
* This value is cached for the duration of the connection after the
* first call to this method. In other words, only the first time
* that you invoke this method will it issue a SYST command to the
* FTP server. FTPClient will remember the value and return the
* cached value until a call to disconnect.
* <p>
* @return The system type name obtained from the server. null if the
* information could not be obtained.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public String getSystemName()
throws IOException, FtpExceptionBadSystResponse
{
//if (syst() == FTPReply.NAME_SYSTEM_TYPE)
// Technically, we should expect a NAME_SYSTEM_TYPE response, but
// in practice FTP servers deviate, so we soften the condition to
// a positive completion.
if (__systemName == null && FTPReply.isPositiveCompletion(syst())) {
__systemName = (getReplyStrings()[0]).substring(4);
} else {
throw new FtpExceptionBadSystResponse(
"Bad response of SYST: " + getReplyString());
}
return __systemName;
}
/***
* Sends a NOOP command to the FTP server. This is useful for preventing
* server timeouts.
* <p>
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public boolean sendNoOp() throws IOException
{
return FTPReply.isPositiveCompletion(noop());
}
// client.stat(path);
// client.sendCommand("STAT");
// client.sendCommand("STAT",path);
// client.sendCommand("MDTM",path);
// client.sendCommand("SIZE",path);
// client.sendCommand("HELP","SITE");
// client.sendCommand("SYST");
// client.setRestartOffset(120);
}
| fogbeam/Heceta_nutch | src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java | Java | apache-2.0 | 22,349 |
/*
* Dynomite - A thin, distributed replication layer for multi non-distributed storages.
* Copyright (C) 2014 Netflix, Inc.
*/
/*
* twemproxy - A fast and lightweight proxy for memcached protocol.
* Copyright (C) 2011 Twitter, 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.
*/
/*
* By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
* code any way you wish, private, educational, or commercial. It's free.
* Use for hash table lookup, or anything where one collision in 2^^32 is
* acceptable. Do NOT use for cryptographic purposes.
* http://burtleburtle.net/bob/hash/index.html
*
* Modified by Brian Pontz for libmemcached
* TODO:
* Add big endian support
*/
#include <dyn_token.h>
#include <dyn_core.h>
#define hashsize(n) ((uint32_t)1<<(n))
#define hashmask(n) (hashsize(n)-1)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
#define mix(a,b,c) \
{ \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
#define final(a,b,c) \
{ \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
#define JENKINS_INITVAL 13
/*
* jenkins_hash() -- hash a variable-length key into a 32-bit value
* k : the key (the unaligned variable-length array of bytes)
* length : the length of the key, counting by bytes
* initval : can be any 4-byte value
* Returns a 32-bit value. Every bit of the key affects every bit of
* the return value. Two keys differing by one or two bits will have
* totally different hash values.
* The best hash table sizes are powers of 2. There is no need to do
* mod a prime (mod is sooo slow!). If you need less than 32 bits,
* use a bitmask. For example, if you need only 10 bits, do
* h = (h & hashmask(10));
* In which case, the hash table should have hashsize(10) elements.
*/
rstatus_t
hash_jenkins(const char *key, size_t length, struct dyn_token *token)
{
uint32_t a,b,c; /* internal state */
union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
/* Set up the internal state */
a = b = c = 0xdeadbeef + ((uint32_t)length) + JENKINS_INITVAL;
u.ptr = key;
#ifndef WORDS_BIGENDIAN
if ((u.i & 0x3) == 0)
{
const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
b += k[1];
c += k[2];
mix(a,b,c);
length -= 12;
k += 3;
}
/*----------------------------- handle the last (probably partial) block */
/*
* "k[2]&0xffffff" actually reads beyond the end of the string, but
* then masks off the part it's not allowed to read. Because the
* string is aligned, the masked-off tail is in the same word as the
* rest of the string. Every machine with memory protection I've seen
* does it on word boundaries, so is OK with this. But VALGRIND will
* still catch it and complain. The masking trick does make the hash
* noticably faster for short strings (like English words).
*/
switch(length)
{
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
case 6 : b+=k[1]&0xffff; a+=k[0]; break;
case 5 : b+=k[1]&0xff; a+=k[0]; break;
case 4 : a+=k[0]; break;
case 3 : a+=k[0]&0xffffff; break;
case 2 : a+=k[0]&0xffff; break;
case 1 : a+=k[0]&0xff; break;
case 0 : return c; /* zero length strings require no mixing */
default: return c;
}
}
else if ((u.i & 0x1) == 0)
{
const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
const uint8_t *k8;
/*--------------- all but last block: aligned reads and different mixing */
while (length > 12)
{
a += k[0] + (((uint32_t)k[1])<<16);
b += k[2] + (((uint32_t)k[3])<<16);
c += k[4] + (((uint32_t)k[5])<<16);
mix(a,b,c);
length -= 12;
k += 6;
}
/*----------------------------- handle the last (probably partial) block */
k8 = (const uint8_t *)k;
switch(length)
{
case 12: c+=k[4]+(((uint32_t)k[5])<<16);
b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=k[4];
b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=k[2];
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=k[0];
break;
case 1 : a+=k8[0];
break;
case 0 : return c; /* zero length requires no mixing */
default: return c;
}
}
else
{ /* need to read the key one byte at a time */
#endif /* little endian */
const uint8_t *k = (const uint8_t *)key;
/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
a += ((uint32_t)k[1])<<8;
a += ((uint32_t)k[2])<<16;
a += ((uint32_t)k[3])<<24;
b += k[4];
b += ((uint32_t)k[5])<<8;
b += ((uint32_t)k[6])<<16;
b += ((uint32_t)k[7])<<24;
c += k[8];
c += ((uint32_t)k[9])<<8;
c += ((uint32_t)k[10])<<16;
c += ((uint32_t)k[11])<<24;
mix(a,b,c);
length -= 12;
k += 12;
}
/*-------------------------------- last block: affect all 32 bits of (c) */
switch(length) /* all the case statements fall through */
{
case 12: c+=((uint32_t)k[11])<<24;
case 11: c+=((uint32_t)k[10])<<16;
case 10: c+=((uint32_t)k[9])<<8;
case 9 : c+=k[8];
case 8 : b+=((uint32_t)k[7])<<24;
case 7 : b+=((uint32_t)k[6])<<16;
case 6 : b+=((uint32_t)k[5])<<8;
case 5 : b+=k[4];
case 4 : a+=((uint32_t)k[3])<<24;
case 3 : a+=((uint32_t)k[2])<<16;
case 2 : a+=((uint32_t)k[1])<<8;
case 1 : a+=k[0];
break;
case 0 : return c;
default : return c;
}
#ifndef WORDS_BIGENDIAN
}
#endif
final(a,b,c);
size_dyn_token(token, 1);
set_int_dyn_token(token, c);
return DN_OK;
}
| philipz/dynomite | src/hashkit/dyn_jenkins.c | C | apache-2.0 | 7,652 |
include ../../_utils/cil/Makefile.common | bh107/benchpress | benchpress/benchmarks/shallow_water/csharp_numcil/Makefile | Makefile | apache-2.0 | 40 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* 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.zaproxy.addon.oast;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.commons.httpclient.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.parosproxy.paros.db.RecordHistory;
import org.parosproxy.paros.db.TableAlert;
import org.parosproxy.paros.db.TableHistory;
import org.parosproxy.paros.db.TableTag;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.testutils.TestUtils;
class OastRequestUnitTests extends TestUtils {
@BeforeEach
void setUp() throws Exception {
setUpZap();
}
@Test
void shouldCreateValidOastRequest() throws Exception {
// Given
String source = "192.0.2.0:12345";
String handler = "expected handler";
String referer = "expected referer";
HttpMessage httpMessage = new HttpMessage(new URI("https://example.com", true));
httpMessage.getRequestHeader().setHeader(HttpHeader.REFERER, referer);
TableHistory tableHistory = mock(TableHistory.class);
RecordHistory recordHistory = mock(RecordHistory.class);
HistoryReference.setTableHistory(tableHistory);
when(tableHistory.write(anyLong(), anyInt(), eq(httpMessage))).thenReturn(recordHistory);
when(tableHistory.read(anyInt())).thenReturn(recordHistory);
when(recordHistory.getHttpMessage()).thenReturn(httpMessage);
HistoryReference.setTableAlert(mock(TableAlert.class));
TableTag tableTag = mock(TableTag.class);
HistoryReference.setTableTag(tableTag);
when(tableTag.insert(anyLong(), any())).thenReturn(null);
// When
OastRequest oastRequest = OastRequest.create(httpMessage, source, handler);
// Then
assertThat(oastRequest.getSource(), is(source));
assertThat(oastRequest.getHandler(), is(handler));
assertThat(oastRequest.getReferer(), is(referer));
}
}
| thc202/zap-extensions | addOns/oast/src/test/java/org/zaproxy/addon/oast/OastRequestUnitTests.java | Java | apache-2.0 | 3,097 |
/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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 "cmsis.h"
#include "platform/mbed_semihost_api.h"
#include <stdint.h>
#include <string.h>
#if DEVICE_SEMIHOST
// ARM Semihosting Commands
#define SYS_OPEN (0x1)
#define SYS_CLOSE (0x2)
#define SYS_WRITE (0x5)
#define SYS_READ (0x6)
#define SYS_ISTTY (0x9)
#define SYS_SEEK (0xa)
#define SYS_ENSURE (0xb)
#define SYS_FLEN (0xc)
#define SYS_REMOVE (0xe)
#define SYS_RENAME (0xf)
#define SYS_EXIT (0x18)
// mbed Semihosting Commands
#define RESERVED_FOR_USER_APPLICATIONS (0x100) // 0x100 - 0x1ff
#define USR_XFFIND (RESERVED_FOR_USER_APPLICATIONS + 0)
#define USR_UID (RESERVED_FOR_USER_APPLICATIONS + 1)
#define USR_RESET (RESERVED_FOR_USER_APPLICATIONS + 2)
#define USR_VBUS (RESERVED_FOR_USER_APPLICATIONS + 3)
#define USR_POWERDOWN (RESERVED_FOR_USER_APPLICATIONS + 4)
#define USR_DISABLEDEBUG (RESERVED_FOR_USER_APPLICATIONS + 5)
#if DEVICE_LOCALFILESYSTEM
FILEHANDLE semihost_open(const char* name, int openmode) {
uint32_t args[3];
args[0] = (uint32_t)name;
args[1] = (uint32_t)openmode;
args[2] = (uint32_t)strlen(name);
return __semihost(SYS_OPEN, args);
}
int semihost_close(FILEHANDLE fh) {
return __semihost(SYS_CLOSE, &fh);
}
int semihost_write(FILEHANDLE fh, const unsigned char* buffer, unsigned int length, int mode) {
if (length == 0) return 0;
uint32_t args[3];
args[0] = (uint32_t)fh;
args[1] = (uint32_t)buffer;
args[2] = (uint32_t)length;
return __semihost(SYS_WRITE, args);
}
int semihost_read(FILEHANDLE fh, unsigned char* buffer, unsigned int length, int mode) {
uint32_t args[3];
args[0] = (uint32_t)fh;
args[1] = (uint32_t)buffer;
args[2] = (uint32_t)length;
return __semihost(SYS_READ, args);
}
int semihost_istty(FILEHANDLE fh) {
return __semihost(SYS_ISTTY, &fh);
}
int semihost_seek(FILEHANDLE fh, long position) {
uint32_t args[2];
args[0] = (uint32_t)fh;
args[1] = (uint32_t)position;
return __semihost(SYS_SEEK, args);
}
int semihost_ensure(FILEHANDLE fh) {
return __semihost(SYS_ENSURE, &fh);
}
long semihost_flen(FILEHANDLE fh) {
return __semihost(SYS_FLEN, &fh);
}
int semihost_remove(const char *name) {
uint32_t args[2];
args[0] = (uint32_t)name;
args[1] = (uint32_t)strlen(name);
return __semihost(SYS_REMOVE, args);
}
int semihost_rename(const char *old_name, const char *new_name) {
uint32_t args[4];
args[0] = (uint32_t)old_name;
args[1] = (uint32_t)strlen(old_name);
args[0] = (uint32_t)new_name;
args[1] = (uint32_t)strlen(new_name);
return __semihost(SYS_RENAME, args);
}
#endif
int semihost_exit(void) {
uint32_t args[4];
return __semihost(SYS_EXIT, args);
}
int semihost_uid(char *uid) {
uint32_t args[2];
args[0] = (uint32_t)uid;
args[1] = DEVICE_ID_LENGTH + 1;
return __semihost(USR_UID, &args);
}
int semihost_reset(void) {
// Does not normally return, however if used with older firmware versions
// that do not support this call it will return -1.
return __semihost(USR_RESET, NULL);
}
int semihost_vbus(void) {
return __semihost(USR_VBUS, NULL);
}
int semihost_powerdown(void) {
return __semihost(USR_POWERDOWN, NULL);
}
#if DEVICE_DEBUG_AWARENESS
int semihost_connected(void) {
return (CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) ? 1 : 0;
}
#else
// These processors cannot know if the interface is connect, assume so:
static int is_debugger_attached = 1;
int semihost_connected(void) {
return is_debugger_attached;
}
#endif
int semihost_disabledebug(void) {
#if !(DEVICE_DEBUG_AWARENESS)
is_debugger_attached = 0;
#endif
return __semihost(USR_DISABLEDEBUG, NULL);
}
#endif
| RonEld/mbed | platform/mbed_semihost_api.c | C | apache-2.0 | 4,332 |
/**
* 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.mahout.math.function;
/*
Copyright 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
/**
* Interface that represents a procedure object: a procedure that takes two arguments and does not return a value.
*
*/
public interface ByteCharProcedure {
/**
* Applies a procedure to two arguments. Optionally can return a boolean flag to inform the object calling the
* procedure.
*
* <p>Example: forEach() methods often use procedure objects. To signal to a forEach() method whether iteration should
* continue normally or terminate (because for example a matching element has been found), a procedure can return
* <tt>false</tt> to indicate termination and <tt>true</tt> to indicate continuation.
*
* @param first first argument passed to the procedure.
* @param second second argument passed to the procedure.
* @return a flag to inform the object calling the procedure.
*/
boolean apply(byte first, char second);
}
| genericDataCompany/hsandbox | common/mahout-distribution-0.7-hadoop1/math/target/generated-sources/org/apache/mahout/math/function/ByteCharProcedure.java | Java | apache-2.0 | 2,235 |
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: A importância da ordem padrão do DOM
{# wf_updated_on: 2016-10-04 #}
{# wf_published_on: 2016-10-04 #}
# A Ordem do DOM É Importante {: .page-title }
{% include "web/_shared/contributors/megginkearney.html" %}
{% include "web/_shared/contributors/dgash.html" %}
{% include "web/_shared/contributors/robdodson.html" %}
Trabalhar com elementos nativos é uma ótima forma de aprender sobre o comportamento de foco
porque eles são automaticamente inseridos na ordem na guia com base
em sua posição no DOM.
Por exemplo, você pode ter três elementos de botão, um após o outro no
DOM. Pressionar `Tab` foca cada botão na ordem. Tente clicar no bloco de código
abaixo para mover o ponto inicial do foco de navegação, depois pressione `Tab` para mover o foco
entre os botões.
<button>I Should</button>
<button>Be Focused</button>
<button>Last!</button>
{% framebox height="80px" %}
<button>I Should</button>
<button>Be Focused</button>
<button>Last!</button>
{% endframebox %}
No entanto, é importante observar que, ao utilizar CSS, é possível as coisas
existirem em uma ordem no DOM, mas aparecerem em uma ordem diferente na tela. Por exemplo,
se você usar uma propriedade CSS como `float` para mover um botão para a direita,
os botões aparecem numa ordem diferente na tela. Porém, como sua ordem no
DOM permanece a inalterada, o mesmo ocorre com sua ordem de guias. Quando o usuário percorre as
guias através a página, os botões são focados em uma ordem não intuitiva. Tente clicar no
bloco de código abaixo para mover o ponto inicial do foco de navegação, depois pressione `Tab` para
mover o foco entre os botões.
<button style="float: right">I Should</button>
<button>Be Focused</button>
<button>Last!</button>
{% framebox height="80px" %}
<button style="float: right;">I Should</button>
<button>Be Focused</button>
<button>Last!</button>
{% endframebox %}
Cuidado ao mudar a posição visual de elementos na tela usando CSS.
Isso pode fazer a ordem de guias para saltar ao redor, aparentemente de forma aleatória, confundindo
os usuários que usam o teclado. Por esta razão, a lista de verificação do Web AIM afirma,
[na seção 1.3.2] (http://webaim.org/standards/wcag/checklist#sc1.3.2){: .external }
que a ordem de leitura e de navegação, determinada pela ordem do código, deve ser
lógica e intuitiva.
Como regra geral, tente percorrer as guias de suas páginas de vez em quando, só
para ter certeza de que você não cancelou acidentalmente a ordem das guias. Este é um bom hábito a se adotar,
e não requer muito esforço.
## Conteúdo fora da tela
E se você tiver conteúdo que não está sendo exibido no momento, mas ainda precisa estar
no DOM, tal como uma navegação lateral responsiva? Quando se tem elementos como este, que
recebe foco quando estão fora da tela, pode parecer que o foco está
desaparecendo e reaparecendo conforme o usuário percorre as guias da página — obviamente
um efeito indesejável. Idealmente, devemos impedir que o painel seja
focado quando está fora da tela, e permitir que ele seja focado somente quando o usuário pode
interagir com ele.

Às vezes você precisa fazer um pouco de trabalho de detetive para descobrir
para onde foi o foco. Você pode usar `document.activeElement` a partir do console para descobrir qual
elemento está focado no momento.
Depois de saber que elemento fora da tela está sendo focado, você pode configurá-lo para
`display: none` ou `visibility: hidden` e, em seguida, configurá-lo de volta para `display:
block` ou `visibility: visible` antes de mostrá-lo para o usuário.


Em geral, incentivamos os desenvolvedores a percorrer as guias de seus sites antes
de cada publicação para ver se a ordem das guias não desaparece ou sai de uma
sequência lógica. Se isso acontecer, você deve certificar que está ocultando adequadamente
conteúdo fora da tela com `display: none` ou `visibility: hidden`, ou que
reorganiza as posições físicas dos elementos no DOM para que estejam em
uma ordem lógica.
{# wf_devsite_translation #}
| ebidel/WebFundamentals | src/content/pt-br/fundamentals/accessibility/focus/dom-order-matters.md | Markdown | apache-2.0 | 4,437 |
<div class="acl-switch-panel" style="">
<span class="acl-separator-vert"></span>
<div class="acl-badge-panel">
<span class="badge acl-badge-red"></span>
</div>
<div class="acl-toggle-panel" data-field="togglePanel"></div>
</div>
| karreiro/uberfire | uberfire-extensions/uberfire-security/uberfire-security-management/uberfire-widgets-security-management/src/main/java/org/uberfire/ext/security/management/client/widgets/management/editor/acl/node/PermissionSwitchView.html | HTML | apache-2.0 | 253 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
# -------------------------------------------------------------------------
import pygame
from Axon.Component import component
class BasicSprite(pygame.sprite.Sprite, component):
Inboxes=["translation", "imaging","inbox", "control"]
allsprites = []
def __init__(self, imagepath, name, pos = None,border=40):
pygame.sprite.Sprite.__init__(self)
component.__init__(self)
self.imagepath = imagepath
self.image = None
self.original = None
self.rect = None
self.pos = pos
if self.pos == None:
self.pos = [100,100]
self.dir = ""
self.name = name
self.update = self.sprite_logic().next
self.screensize = (924,658)
self.border = border
self.__class__.allsprites.append(self)
def allSprites(klass):
return klass.allsprites
allSprites = classmethod(allSprites)
def sprite_logic(self):
while 1:
yield 1
def main(self):
self.image = pygame.image.load(self.imagepath)
self.original = self.image
self.image = self.original
self.rect = self.image.get_rect()
self.rect.center = self.pos
center = list(self.rect.center)
current = self.image
pos = center
dx,dy = 0,0
d = 10 # Change me to change the velocity of the sprite
while 1:
self.image = current
if self.dataReady("imaging"):
self.image = self.recv("imaging")
current = self.image
if self.dataReady("translation"):
pos = self.recv("translation")
if self.dataReady("inbox"):
event = self.recv("inbox")
if event == "start_up": dy = dy + d
if event == "stop_up": dy = dy - d
if event == "start_down": dy = dy - d
if event == "stop_down": dy = dy + d
if event == "start_right": dx = dx + d
if event == "stop_right": dx = dx - d
if event == "start_left": dx = dx - d
if event == "stop_left": dx = dx + d
if dx !=0 or dy != 0:
self.pos[0] += dx
if self.pos[0] >self.screensize[0]-self.border: self.pos[0] =self.screensize[0]-self.border
if self.pos[1] >self.screensize[1]-self.border: self.pos[1] =self.screensize[1]-self.border
if self.pos[0] <self.border: self.pos[0] = self.border
if self.pos[1] < self.border: self.pos[1] = self.border
self.pos[1] -= dy
self.rect.center = (self.pos)
self.send(self.pos, "outbox")
yield 1
| sparkslabs/kamaelia_ | Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/Games4Kids/BasicSprite.py | Python | apache-2.0 | 3,562 |
/*
Copyright 2015 The Kubernetes 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.
*/
package generators
import (
"fmt"
"io"
"path/filepath"
"strings"
"k8s.io/kubernetes/cmd/libs/go2idl/args"
"k8s.io/kubernetes/cmd/libs/go2idl/generator"
"k8s.io/kubernetes/cmd/libs/go2idl/namer"
"k8s.io/kubernetes/cmd/libs/go2idl/types"
"k8s.io/kubernetes/pkg/util/sets"
"github.com/golang/glog"
)
// TODO: This is created only to reduce number of changes in a single PR.
// Remove it and use PublicNamer instead.
func deepCopyNamer() *namer.NameStrategy {
return &namer.NameStrategy{
Join: func(pre string, in []string, post string) string {
return strings.Join(in, "_")
},
PrependPackageNames: 1,
}
}
// NameSystems returns the name system used by the generators in this package.
func NameSystems() namer.NameSystems {
return namer.NameSystems{
"public": deepCopyNamer(),
"raw": namer.NewRawNamer("", nil),
}
}
// DefaultNameSystem returns the default name system for ordering the types to be
// processed by the generators in this package.
func DefaultNameSystem() string {
return "public"
}
func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
boilerplate, err := arguments.LoadGoBoilerplate()
if err != nil {
glog.Fatalf("Failed loading boilerplate: %v", err)
}
inputs := sets.NewString(arguments.InputDirs...)
packages := generator.Packages{}
header := append([]byte(
`// +build !ignore_autogenerated
`), boilerplate...)
header = append(header, []byte(
`
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
`)...)
for _, p := range context.Universe {
copyableType := false
for _, t := range p.Types {
if copyableWithinPackage(t) {
copyableType = true
}
}
if copyableType {
path := p.Path
packages = append(packages,
&generator.DefaultPackage{
PackageName: filepath.Base(path),
PackagePath: path,
HeaderText: header,
GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {
generators = []generator.Generator{}
generators = append(
generators, NewGenDeepCopy("deep_copy_generated", path, inputs.Has(path)))
return generators
},
FilterFunc: func(c *generator.Context, t *types.Type) bool {
return t.Name.Package == path
},
})
}
}
return packages
}
const (
apiPackagePath = "k8s.io/kubernetes/pkg/api"
conversionPackagePath = "k8s.io/kubernetes/pkg/conversion"
)
// genDeepCopy produces a file with autogenerated deep-copy functions.
type genDeepCopy struct {
generator.DefaultGen
targetPackage string
imports namer.ImportTracker
typesForInit []*types.Type
generateInitFunc bool
}
func NewGenDeepCopy(sanitizedName, targetPackage string, generateInitFunc bool) generator.Generator {
return &genDeepCopy{
DefaultGen: generator.DefaultGen{
OptionalName: sanitizedName,
},
targetPackage: targetPackage,
imports: generator.NewImportTracker(),
typesForInit: make([]*types.Type, 0),
generateInitFunc: generateInitFunc,
}
}
func (g *genDeepCopy) Namers(c *generator.Context) namer.NameSystems {
// Have the raw namer for this file track what it imports.
return namer.NameSystems{"raw": namer.NewRawNamer(g.targetPackage, g.imports)}
}
func (g *genDeepCopy) Filter(c *generator.Context, t *types.Type) bool {
// Filter out all types not copyable within the package.
copyable := copyableWithinPackage(t)
if copyable {
g.typesForInit = append(g.typesForInit, t)
}
return copyable
}
func copyableWithinPackage(t *types.Type) bool {
if !strings.HasPrefix(t.Name.Package, "k8s.io/kubernetes/") {
return false
}
if types.ExtractCommentTags("+", t.CommentLines)["gencopy"] == "false" {
return false
}
// TODO: Consider generating functions for other kinds too.
if t.Kind != types.Struct {
return false
}
// Also, filter out private types.
if namer.IsPrivateGoName(t.Name.Name) {
return false
}
return true
}
func (g *genDeepCopy) isOtherPackage(pkg string) bool {
if pkg == g.targetPackage {
return false
}
if strings.HasSuffix(pkg, "\""+g.targetPackage+"\"") {
return false
}
return true
}
func (g *genDeepCopy) Imports(c *generator.Context) (imports []string) {
importLines := []string{}
if g.isOtherPackage(apiPackagePath) && g.generateInitFunc {
importLines = append(importLines, "api \""+apiPackagePath+"\"")
}
if g.isOtherPackage(conversionPackagePath) {
importLines = append(importLines, "conversion \""+conversionPackagePath+"\"")
}
for _, singleImport := range g.imports.ImportLines() {
if g.isOtherPackage(singleImport) {
importLines = append(importLines, singleImport)
}
}
return importLines
}
func argsFromType(t *types.Type) interface{} {
return map[string]interface{}{
"type": t,
}
}
func (g *genDeepCopy) funcNameTmpl(t *types.Type) string {
tmpl := "DeepCopy_$.type|public$"
g.imports.AddType(t)
if t.Name.Package != g.targetPackage {
tmpl = g.imports.LocalNameOf(t.Name.Package) + "." + tmpl
}
return tmpl
}
func (g *genDeepCopy) Init(c *generator.Context, w io.Writer) error {
if !g.generateInitFunc {
// TODO: We should come up with a solution to register all generated
// deep-copy functions. However, for now, to avoid import cycles
// we register only those explicitly requested.
return nil
}
sw := generator.NewSnippetWriter(w, c, "$", "$")
sw.Do("func init() {\n", nil)
if g.targetPackage == apiPackagePath {
sw.Do("if err := Scheme.AddGeneratedDeepCopyFuncs(\n", nil)
} else {
sw.Do("if err := api.Scheme.AddGeneratedDeepCopyFuncs(\n", nil)
}
for _, t := range g.typesForInit {
sw.Do(fmt.Sprintf("%s,\n", g.funcNameTmpl(t)), argsFromType(t))
}
sw.Do("); err != nil {\n", nil)
sw.Do("// if one of the deep copy functions is malformed, detect it immediately.\n", nil)
sw.Do("panic(err)\n", nil)
sw.Do("}\n", nil)
sw.Do("}\n\n", nil)
return sw.Error()
}
func (g *genDeepCopy) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "$", "$")
funcName := g.funcNameTmpl(t)
if g.targetPackage == conversionPackagePath {
sw.Do(fmt.Sprintf("func %s(in $.type|raw$, out *$.type|raw$, c *Cloner) error {\n", funcName), argsFromType(t))
} else {
sw.Do(fmt.Sprintf("func %s(in $.type|raw$, out *$.type|raw$, c *conversion.Cloner) error {\n", funcName), argsFromType(t))
}
g.generateFor(t, sw)
sw.Do("return nil\n", nil)
sw.Do("}\n\n", nil)
return sw.Error()
}
// we use the system of shadowing 'in' and 'out' so that the same code is valid
// at any nesting level. This makes the autogenerator easy to understand, and
// the compiler shouldn't care.
func (g *genDeepCopy) generateFor(t *types.Type, sw *generator.SnippetWriter) {
var f func(*types.Type, *generator.SnippetWriter)
switch t.Kind {
case types.Builtin:
f = g.doBuiltin
case types.Map:
f = g.doMap
case types.Slice:
f = g.doSlice
case types.Struct:
f = g.doStruct
case types.Interface:
f = g.doInterface
case types.Pointer:
f = g.doPointer
case types.Alias:
f = g.doAlias
default:
f = g.doUnknown
}
f(t, sw)
}
func (g *genDeepCopy) doBuiltin(t *types.Type, sw *generator.SnippetWriter) {
sw.Do("*out = in\n", nil)
}
func (g *genDeepCopy) doMap(t *types.Type, sw *generator.SnippetWriter) {
sw.Do("*out = make($.|raw$)\n", t)
if t.Key.IsAssignable() {
sw.Do("for key, val := range in {\n", nil)
if t.Elem.IsAssignable() {
sw.Do("(*out)[key] = val\n", nil)
} else {
if copyableWithinPackage(t.Elem) {
sw.Do("newVal := new($.|raw$)\n", t.Elem)
funcName := g.funcNameTmpl(t.Elem)
sw.Do(fmt.Sprintf("if err := %s(val, newVal, c); err != nil {\n", funcName), argsFromType(t.Elem))
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
sw.Do("(*out)[key] = *newVal\n", nil)
} else {
sw.Do("if newVal, err := c.DeepCopy(val); err != nil {\n", nil)
sw.Do("return err\n", nil)
sw.Do("} else {\n", nil)
sw.Do("(*out)[key] = newVal.($.|raw$)\n", t.Elem)
sw.Do("}\n", nil)
}
}
} else {
// TODO: Implement it when necessary.
sw.Do("for range in {\n", nil)
sw.Do("// FIXME: Copying unassignable keys unsupported $.|raw$\n", t.Key)
}
sw.Do("}\n", nil)
}
func (g *genDeepCopy) doSlice(t *types.Type, sw *generator.SnippetWriter) {
sw.Do("*out = make($.|raw$, len(in))\n", t)
if t.Elem.Kind == types.Builtin {
sw.Do("copy(*out, in)\n", nil)
} else {
sw.Do("for i := range in {\n", nil)
if t.Elem.IsAssignable() {
sw.Do("(*out)[i] = in[i]\n", nil)
} else if copyableWithinPackage(t.Elem) {
funcName := g.funcNameTmpl(t.Elem)
sw.Do(fmt.Sprintf("if err := %s(in[i], &(*out)[i], c); err != nil {\n", funcName), argsFromType(t.Elem))
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
} else {
sw.Do("if newVal, err := c.DeepCopy(in[i]); err != nil {\n", nil)
sw.Do("return err\n", nil)
sw.Do("} else {\n", nil)
sw.Do("(*out)[i] = newVal.($.|raw$)\n", t.Elem)
sw.Do("}\n", nil)
}
sw.Do("}\n", nil)
}
}
func (g *genDeepCopy) doStruct(t *types.Type, sw *generator.SnippetWriter) {
for _, m := range t.Members {
args := map[string]interface{}{
"type": m.Type,
"name": m.Name,
}
switch m.Type.Kind {
case types.Builtin:
sw.Do("out.$.name$ = in.$.name$\n", args)
case types.Map, types.Slice, types.Pointer:
sw.Do("if in.$.name$ != nil {\n", args)
sw.Do("in, out := in.$.name$, &out.$.name$\n", args)
g.generateFor(m.Type, sw)
sw.Do("} else {\n", nil)
sw.Do("out.$.name$ = nil\n", args)
sw.Do("}\n", nil)
case types.Struct:
if copyableWithinPackage(m.Type) {
funcName := g.funcNameTmpl(m.Type)
sw.Do(fmt.Sprintf("if err := %s(in.$.name$, &out.$.name$, c); err != nil {\n", funcName), args)
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
} else {
sw.Do("if newVal, err := c.DeepCopy(in.$.name$); err != nil {\n", args)
sw.Do("return err\n", nil)
sw.Do("} else {\n", nil)
sw.Do("out.$.name$ = newVal.($.type|raw$)\n", args)
sw.Do("}\n", nil)
}
default:
if m.Type.Kind == types.Alias && m.Type.Underlying.Kind == types.Builtin {
sw.Do("out.$.name$ = in.$.name$\n", args)
} else {
sw.Do("if in.$.name$ == nil {\n", args)
sw.Do("out.$.name$ = nil\n", args)
sw.Do("} else if newVal, err := c.DeepCopy(in.$.name$); err != nil {\n", args)
sw.Do("return err\n", nil)
sw.Do("} else {\n", nil)
sw.Do("out.$.name$ = newVal.($.type|raw$)\n", args)
sw.Do("}\n", nil)
}
}
}
}
func (g *genDeepCopy) doInterface(t *types.Type, sw *generator.SnippetWriter) {
// TODO: Add support for interfaces.
g.doUnknown(t, sw)
}
func (g *genDeepCopy) doPointer(t *types.Type, sw *generator.SnippetWriter) {
sw.Do("*out = new($.Elem|raw$)\n", t)
if t.Elem.Kind == types.Builtin {
sw.Do("**out = *in", nil)
} else if copyableWithinPackage(t.Elem) {
funcName := g.funcNameTmpl(t.Elem)
sw.Do(fmt.Sprintf("if err := %s(*in, *out, c); err != nil {\n", funcName), argsFromType(t.Elem))
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
} else {
sw.Do("if newVal, err := c.DeepCopy(*in); err != nil {\n", nil)
sw.Do("return err\n", nil)
sw.Do("} else {\n", nil)
sw.Do("**out = newVal.($.|raw$)\n", t.Elem)
sw.Do("}\n", nil)
}
}
func (g *genDeepCopy) doAlias(t *types.Type, sw *generator.SnippetWriter) {
// TODO: Add support for aliases.
g.doUnknown(t, sw)
}
func (g *genDeepCopy) doUnknown(t *types.Type, sw *generator.SnippetWriter) {
sw.Do("// FIXME: Type $.|raw$ is unsupported.\n", t)
}
| Frostman/kubernetes | cmd/libs/go2idl/deepcopy-gen/generators/deepcopy.go | GO | apache-2.0 | 12,059 |
/* Copyright 2007-2015 QReal Research Group
*
* 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. */
#pragma once
#include <QtGui/QPainter>
#include "qrutils/utilsDeclSpec.h"
namespace qReal {
namespace ui {
/// An interface for object that implements some painting logic on PaintWidget.
/// @see qReal::ui::PaintWidget
class QRUTILS_EXPORT PainterInterface
{
public:
virtual ~PainterInterface() {}
/// Implements the painting process itself.
virtual void paint(QPainter *painter) = 0;
/// Clears all drawn stuff.
virtual void reset() = 0;
};
}
}
| anastasia143/qreal | qrutils/widgets/painterInterface.h | C | apache-2.0 | 1,064 |
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.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.pentaho.runtime.test.action;
/**
* Created by bryan on 9/8/15.
*/
public interface RuntimeTestActionHandler {
boolean canHandle( RuntimeTestAction runtimeTestAction );
void handle( RuntimeTestAction runtimeTestAction );
}
| bytekast/big-data-plugin | api/runtimeTest/src/main/java/org/pentaho/runtime/test/action/RuntimeTestActionHandler.java | Java | apache-2.0 | 1,138 |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// column_stats_collector_test.cpp
//
// Identification: test/optimizer/column_stats_collector_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include <vector>
#include "common/logger.h"
#include "optimizer/stats/column_stats_collector.h"
#include "type/type.h"
#include "type/value.h"
#include "type/value_factory.h"
#define private public
#define TEST_OID 0
namespace peloton {
namespace test {
using namespace optimizer;
class ColumnStatsCollectorTests : public PelotonTest {};
// Basic test with tiny dataset.
TEST_F(ColumnStatsCollectorTests, BasicTest) {
ColumnStatsCollector colstats{TEST_OID, TEST_OID, TEST_OID,
type::TypeId::INTEGER, ""};
// Edge case
EXPECT_EQ(colstats.GetFracNull(), 0); // Should also log error
EXPECT_EQ(colstats.GetCardinality(), 0);
EXPECT_EQ(colstats.GetHistogramBound().size(), 0);
EXPECT_EQ(colstats.GetCommonValueAndFrequency().size(), 0);
for (int i = 0; i < 10; i++) {
type::Value v = type::ValueFactory::GetIntegerValue(i);
colstats.AddValue(v);
}
EXPECT_EQ(colstats.GetCardinality(), 10);
EXPECT_EQ(colstats.GetFracNull(), 0);
EXPECT_GE(colstats.GetHistogramBound().size(), 0);
}
// Test categorical values. Categorical data refers to data that
// are not compariable but still hashable.
TEST_F(ColumnStatsCollectorTests, DistinctValueTest) {
ColumnStatsCollector colstats{TEST_OID, TEST_OID, TEST_OID,
type::TypeId::BOOLEAN, ""};
for (int i = 0; i < 1250; i++) {
type::Value v = type::ValueFactory::GetBooleanValue(i % 5 == 0);
colstats.AddValue(v);
}
EXPECT_EQ(colstats.GetCardinality(), 2);
EXPECT_EQ(colstats.GetFracNull(), 0);
EXPECT_EQ(colstats.GetHistogramBound().size(), 0); // No histogram dist
}
// Test dataset with extreme distribution.
// More specifically distribution with large amount of data at tail
// with single continuous value to the left of tail.
// This test is commented out because it's a performance test and takes long time.
// TEST_F(ColumnStatsCollectorTests, SkewedDistTest) {
// ColumnStatsCollector colstats{TEST_OID, TEST_OID, TEST_OID,
// type::TypeId::BIGINT, ""};
// int big_int = 1234567;
// int height = 100000;
// int n = 10;
// // Build up extreme tail distribution.
// for (int i = 1; i <= n; i++) {
// type::Value v = type::ValueFactory::GetBigIntValue(i * big_int);
// for (int j = 0; j < height; j++) {
// colstats.AddValue(v);
// }
// }
// EXPECT_EQ(colstats.GetFracNull(), 0);
// EXPECT_EQ(colstats.GetCardinality(), 10);
// EXPECT_GE(colstats.GetHistogramBound().size(), 0);
// EXPECT_LE(colstats.GetHistogramBound().size(), 255);
// // Add head distribution
// for (int i = 0; i < big_int; i++) {
// type::Value v = type::ValueFactory::GetBigIntValue(i);
// colstats.AddValue(v);
// }
// EXPECT_EQ(colstats.GetFracNull(), 0);
// uint64_t cardinality = colstats.GetCardinality();
// double error = colstats.GetCardinalityError();
// int buffer = 30000; // extreme case error buffer
// EXPECT_GE(cardinality, (big_int + 10) * (1 - error) - buffer);
// EXPECT_LE(cardinality, (big_int + 10) * (1 + error) + buffer);
// EXPECT_GE(colstats.GetHistogramBound().size(), 0);
// // test null
// type::Value null = type::ValueFactory::GetNullValueByType(type::TypeId::BIGINT);
// colstats.AddValue(null);
// EXPECT_GE(colstats.GetFracNull(), 0);
// }
// Test double values.
TEST_F(ColumnStatsCollectorTests, DecimalTest) {
ColumnStatsCollector colstats{0, 0, 0, type::TypeId::DECIMAL, ""};
for (int i = 0; i < 1000; i++) {
type::Value v = type::ValueFactory::GetDecimalValue(4.1525);
colstats.AddValue(v);
}
type::Value v1 = type::ValueFactory::GetDecimalValue(7.12);
type::Value v2 = type::ValueFactory::GetDecimalValue(10.25);
colstats.AddValue(v1);
colstats.AddValue(v2);
EXPECT_EQ(colstats.GetCardinality(), 3);
}
} // namespace test
} // namespace peloton
| AllisonWang/peloton | test/optimizer/column_stats_collector_test.cpp | C++ | apache-2.0 | 4,272 |
{% extends "horizon/common/_modal_form.html" %}
{% load i18n %}
{% load url from future %}
{% block form_id %}update_security_group_form{% endblock %}
{% block form_action %}{% url 'horizon:project:access_and_security:security_groups:update' security_group.id%}{% endblock %}
{% block modal-header %}{% trans "Edit Security Group" %}{% endblock %}
{% block modal_id %}update_security_group_modal{% endblock %}
{% block modal-body %}
<div class="left">
<fieldset>
{% include "horizon/common/_form_fields.html" %}
</fieldset>
</div>
<div class="right">
<h3>{% trans "Description" %}:</h3>
<p>{% trans "Security groups are sets of IP filter rules that are applied to the network settings for the VM. Edit the security group to add and change the rules." %}</p>
</div>
{% endblock %}
{% block modal-footer %}
<input class="btn btn-primary pull-right" type="submit" value="{% trans "Edit Security Group" %}" />
<a href="{% url 'horizon:project:access_and_security:index' %}" class="btn btn-default secondary cancel close">{% trans "Cancel" %}</a>
{% endblock %}
| zouyapeng/horizon-newtouch | openstack_dashboard/dashboards/project/access_and_security/templates/access_and_security/security_groups/_update.html | HTML | apache-2.0 | 1,085 |
#!/usr/bin/env python3
# Copyright 2015 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.
"""Generates the appropriate JSON data for LB interop test scenarios."""
import json
import os
import yaml
all_scenarios = []
# TODO(https://github.com/grpc/grpc-go/issues/2347): enable
# client_falls_back_because_no_backends_* scenarios for Java/Go.
# TODO(https://github.com/grpc/grpc-java/issues/4887): enable
# *short_stream* scenarios for Java.
# TODO(https://github.com/grpc/grpc-java/issues/4912): enable
# Java TLS tests involving TLS to the balancer.
def server_sec(transport_sec):
if transport_sec == 'google_default_credentials':
return 'alts', 'alts', 'tls'
return transport_sec, transport_sec, transport_sec
def generate_no_balancer_because_lb_a_record_returns_nx_domain():
all_configs = []
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
config = {
'name':
'no_balancer_because_lb_a_record_returns_nx_domain_%s' %
transport_sec,
'skip_langs': [],
'transport_sec':
transport_sec,
'balancer_configs': [],
'backend_configs': [],
'fallback_configs': [{
'transport_sec': fallback_sec,
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_no_balancer_because_lb_a_record_returns_nx_domain()
def generate_no_balancer_because_lb_a_record_returns_no_data():
all_configs = []
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
config = {
'name':
'no_balancer_because_lb_a_record_returns_no_data_%s' %
transport_sec,
'skip_langs': [],
'transport_sec':
transport_sec,
'balancer_configs': [],
'backend_configs': [],
'fallback_configs': [{
'transport_sec': fallback_sec,
}],
'cause_no_error_no_data_for_balancer_a_record':
True,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_no_balancer_because_lb_a_record_returns_no_data()
def generate_client_referred_to_backend():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_%s_short_stream_%s' %
(transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [{
'transport_sec': backend_sec,
}],
'fallback_configs': [],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend()
def generate_client_referred_to_backend_fallback_broken():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in ['alts', 'tls', 'google_default_credentials']:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_fallback_broken_%s_short_stream_%s'
% (transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [{
'transport_sec': backend_sec,
}],
'fallback_configs': [{
'transport_sec': 'insecure',
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend_fallback_broken()
def generate_client_referred_to_backend_multiple_backends():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_multiple_backends_%s_short_stream_%s'
% (transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [{
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}, {
'transport_sec': backend_sec,
}],
'fallback_configs': [],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend_multiple_backends()
def generate_client_falls_back_because_no_backends():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = ['go', 'java']
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_falls_back_because_no_backends_%s_short_stream_%s' %
(transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
}],
'backend_configs': [],
'fallback_configs': [{
'transport_sec': fallback_sec,
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_falls_back_because_no_backends()
def generate_client_falls_back_because_balancer_connection_broken():
all_configs = []
for transport_sec in ['alts', 'tls', 'google_default_credentials']:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs = ['java']
config = {
'name':
'client_falls_back_because_balancer_connection_broken_%s' %
transport_sec,
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [{
'transport_sec': 'insecure',
'short_stream': False,
}],
'backend_configs': [],
'fallback_configs': [{
'transport_sec': fallback_sec,
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_falls_back_because_balancer_connection_broken()
def generate_client_referred_to_backend_multiple_balancers():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts', 'tls', 'google_default_credentials'
]:
balancer_sec, backend_sec, fallback_sec = server_sec(transport_sec)
skip_langs = []
if transport_sec == 'tls':
skip_langs += ['java']
if balancer_short_stream:
skip_langs += ['java']
config = {
'name':
'client_referred_to_backend_multiple_balancers_%s_short_stream_%s'
% (transport_sec, balancer_short_stream),
'skip_langs':
skip_langs,
'transport_sec':
transport_sec,
'balancer_configs': [
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
{
'transport_sec': balancer_sec,
'short_stream': balancer_short_stream,
},
],
'backend_configs': [{
'transport_sec': backend_sec,
},],
'fallback_configs': [],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
all_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend_multiple_balancers()
print((yaml.dump({
'lb_interop_test_scenarios': all_scenarios,
})))
| ctiller/grpc | tools/run_tests/lb_interop_tests/gen_build_yaml.py | Python | apache-2.0 | 12,124 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_11) on Mon Jul 12 21:36:30 CEST 2010 -->
<TITLE>
Uses of Class org.apache.fop.pdf.ASCII85Filter (Apache FOP 1.0 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.apache.fop.pdf.ASCII85Filter (Apache FOP 1.0 API)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/pdf/ASCII85Filter.html" title="class in org.apache.fop.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.0</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="ASCII85Filter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.fop.pdf.ASCII85Filter</B></H2>
</CENTER>
No usage of org.apache.fop.pdf.ASCII85Filter
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/pdf/ASCII85Filter.html" title="class in org.apache.fop.pdf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.0</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="ASCII85Filter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| lewismc/yax | lib/fop-1.0/javadocs/org/apache/fop/pdf/class-use/ASCII85Filter.html | HTML | apache-2.0 | 5,738 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.