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
|
|---|---|---|---|---|---|
/*
Copyright (c) 2007-2011 Gordon Gremme <gremme@zbh.uni-hamburg.de>
Copyright (c) 2007-2008 Center for Bioinformatics, University of Hamburg
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef INTER_FEATURE_STREAM_API_H
#define INTER_FEATURE_STREAM_API_H
#include <stdio.h>
#include "extended/node_stream_api.h"
/* Implements the <GtNodeStream> interface. A <GtInterFeatureStream> inserts new
feature nodes between existing feature nodes of a certain type. */
typedef struct GtInterFeatureStream GtInterFeatureStream;
/* Create a <GtInterFeatureStream*> which inserts feature nodes of type
<inter_type> between the feature nodes of type <outside_type> it retrieves
from <in_stream> and returns them. */
GtNodeStream* gt_inter_feature_stream_new(GtNodeStream *in_stream,
const char *outside_type,
const char *inter_type);
#endif
|
bioh4x/NeatFreq
|
lib/genometools-1.4.1/src/extended/inter_feature_stream_api.h
|
C
|
gpl-2.0
| 1,605
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/** SQL Parser Functions for phpMyAdmin
*
* Copyright 2002 Robin Johnson <robbat2@users.sourceforge.net>
* http://www.orbis-terrarum.net/?l=people.robbat2
*
* These functions define an SQL parser system, capable of understanding and
* extracting data from a MySQL type SQL query.
*
* The basic procedure for using the new SQL parser:
* On any page that needs to extract data from a query or to pretty-print a
* query, you need code like this up at the top:
*
* ($sql contains the query)
* $parsed_sql = PMA_SQP_parse($sql);
*
* If you want to extract data from it then, you just need to run
* $sql_info = PMA_SQP_analyze($parsed_sql);
*
* lem9: See comments in PMA_SQP_analyze for the returned info
* from the analyzer.
*
* If you want a pretty-printed version of the query, do:
* $string = PMA_SQP_formatHtml($parsed_sql);
* (note that that you need to have syntax.css.php included somehow in your
* page for it to work, I recommend '<link rel="stylesheet" type="text/css"
* href="syntax.css.php" />' at the moment.)
*
* @version $Id: sqlparser.lib.php 11513 2008-08-28 16:17:53Z lem9 $
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Minimum inclusion? (i.e. for the stylesheet builder)
*/
if (! defined('PMA_MINIMUM_COMMON')) {
/**
* Include the string library as we use it heavily
*/
require_once './libraries/string.lib.php';
/**
* Include data for the SQL Parser
*/
require_once './libraries/sqlparser.data.php';
require_once './libraries/mysql_charsets.lib.php';
if (!isset($mysql_charsets)) {
$mysql_charsets = array();
$mysql_charsets_count = 0;
$mysql_collations_flat = array();
$mysql_collations_count = 0;
}
if (!defined('DEBUG_TIMING')) {
// currently we don't need the $pos (token position in query)
// for other purposes than LIMIT clause verification,
// so many calls to this function do not include the 4th parameter
function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0)
{
$arr[] = array('type' => $type, 'data' => $data, 'pos' => $pos);
$arrsize++;
} // end of the "PMA_SQP_arrayAdd()" function
} else {
function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0)
{
global $timer;
$t = $timer;
$arr[] = array('type' => $type, 'data' => $data, 'pos' => $pos, 'time' => $t);
$timer = microtime();
$arrsize++;
} // end of the "PMA_SQP_arrayAdd()" function
} // end if... else...
/**
* Reset the error variable for the SQL parser
*
* @access public
*/
// Added, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_resetError()
{
global $SQP_errorString;
$SQP_errorString = '';
unset($SQP_errorString);
}
/**
* Get the contents of the error variable for the SQL parser
*
* @return string Error string from SQL parser
*
* @access public
*/
// Added, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_getErrorString()
{
global $SQP_errorString;
return isset($SQP_errorString) ? $SQP_errorString : '';
}
/**
* Check if the SQL parser hit an error
*
* @return boolean error state
*
* @access public
*/
// Added, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_isError()
{
global $SQP_errorString;
return isset($SQP_errorString) && !empty($SQP_errorString);
}
/**
* Set an error message for the system
*
* @param string The error message
* @param string The failing SQL query
*
* @access private
* @scope SQL Parser internal
*/
// Revised, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_throwError($message, $sql)
{
global $SQP_errorString;
$SQP_errorString = '<p>'.$GLOBALS['strSQLParserUserError'] . '</p>' . "\n"
. '<pre>' . "\n"
. 'ERROR: ' . $message . "\n"
. 'SQL: ' . htmlspecialchars($sql) . "\n"
. '</pre>' . "\n";
} // end of the "PMA_SQP_throwError()" function
/**
* Do display the bug report
*
* @param string The error message
* @param string The failing SQL query
*
* @access public
*/
function PMA_SQP_bug($message, $sql)
{
global $SQP_errorString;
$debugstr = 'ERROR: ' . $message . "\n";
$debugstr .= 'SVN: $Id: sqlparser.lib.php 11513 2008-08-28 16:17:53Z lem9 $' . "\n";
$debugstr .= 'MySQL: '.PMA_MYSQL_STR_VERSION . "\n";
$debugstr .= 'USR OS, AGENT, VER: ' . PMA_USR_OS . ' ' . PMA_USR_BROWSER_AGENT . ' ' . PMA_USR_BROWSER_VER . "\n";
$debugstr .= 'PMA: ' . PMA_VERSION . "\n";
$debugstr .= 'PHP VER,OS: ' . PMA_PHP_STR_VERSION . ' ' . PHP_OS . "\n";
$debugstr .= 'LANG: ' . $GLOBALS['lang'] . "\n";
$debugstr .= 'SQL: ' . htmlspecialchars($sql);
$encodedstr = $debugstr;
if (@function_exists('gzcompress')) {
$encodedstr = gzcompress($debugstr, 9);
}
$encodedstr = preg_replace("/(\015\012)|(\015)|(\012)/", '<br />' . "\n", chunk_split(base64_encode($encodedstr)));
$SQP_errorString .= $GLOBALS['strSQLParserBugMessage'] . '<br />' . "\n"
. '----' . $GLOBALS['strBeginCut'] . '----' . '<br />' . "\n"
. $encodedstr . "\n"
. '----' . $GLOBALS['strEndCut'] . '----' . '<br />' . "\n";
$SQP_errorString .= '----' . $GLOBALS['strBeginRaw'] . '----<br />' . "\n"
. '<pre>' . "\n"
. $debugstr
. '</pre>' . "\n"
. '----' . $GLOBALS['strEndRaw'] . '----<br />' . "\n";
} // end of the "PMA_SQP_bug()" function
/**
* Parses the SQL queries
*
* @param string The SQL query list
*
* @return mixed Most of times, nothing...
*
* @global array The current PMA configuration
* @global array MySQL column attributes
* @global array MySQL reserved words
* @global array MySQL column types
* @global array MySQL function names
* @global integer MySQL column attributes count
* @global integer MySQL reserved words count
* @global integer MySQL column types count
* @global integer MySQL function names count
* @global array List of available character sets
* @global array List of available collations
* @global integer Character sets count
* @global integer Collations count
*
* @access public
*/
function PMA_SQP_parse($sql)
{
global $cfg;
global $PMA_SQPdata_column_attrib, $PMA_SQPdata_reserved_word, $PMA_SQPdata_column_type, $PMA_SQPdata_function_name,
$PMA_SQPdata_column_attrib_cnt, $PMA_SQPdata_reserved_word_cnt, $PMA_SQPdata_column_type_cnt, $PMA_SQPdata_function_name_cnt;
global $mysql_charsets, $mysql_collations_flat, $mysql_charsets_count, $mysql_collations_count;
global $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt;
// rabus: Convert all line feeds to Unix style
$sql = str_replace("\r\n", "\n", $sql);
$sql = str_replace("\r", "\n", $sql);
$len = PMA_strlen($sql);
if ($len == 0) {
return array();
}
$sql_array = array();
$sql_array['raw'] = $sql;
$count1 = 0;
$count2 = 0;
$punct_queryend = ';';
$punct_qualifier = '.';
$punct_listsep = ',';
$punct_level_plus = '(';
$punct_level_minus = ')';
$punct_user = '@';
$digit_floatdecimal = '.';
$digit_hexset = 'x';
$bracket_list = '()[]{}';
$allpunct_list = '-,;:!?/.^~\*&%+<=>|';
$allpunct_list_pair = array (
0 => '!=',
1 => '&&',
2 => ':=',
3 => '<<',
4 => '<=',
5 => '<=>',
6 => '<>',
7 => '>=',
8 => '>>',
9 => '||'
);
$allpunct_list_pair_size = 10; //count($allpunct_list_pair);
$quote_list = '\'"`';
$arraysize = 0;
$previous_was_space = false;
$this_was_space = false;
$previous_was_bracket = false;
$this_was_bracket = false;
$previous_was_punct = false;
$this_was_punct = false;
$previous_was_listsep = false;
$this_was_listsep = false;
$previous_was_quote = false;
$this_was_quote = false;
while ($count2 < $len) {
$c = PMA_substr($sql, $count2, 1);
$count1 = $count2;
$previous_was_space = $this_was_space;
$this_was_space = false;
$previous_was_bracket = $this_was_bracket;
$this_was_bracket = false;
$previous_was_punct = $this_was_punct;
$this_was_punct = false;
$previous_was_listsep = $this_was_listsep;
$this_was_listsep = false;
$previous_was_quote = $this_was_quote;
$this_was_quote = false;
if (($c == "\n")) {
$this_was_space = true;
$count2++;
PMA_SQP_arrayAdd($sql_array, 'white_newline', '', $arraysize);
continue;
}
// Checks for white space
if (PMA_STR_isSpace($c)) {
$this_was_space = true;
$count2++;
continue;
}
// Checks for comment lines.
// MySQL style #
// C style /* */
// ANSI style --
if (($c == '#')
|| (($count2 + 1 < $len) && ($c == '/') && (PMA_substr($sql, $count2 + 1, 1) == '*'))
|| (($count2 + 2 == $len) && ($c == '-') && (PMA_substr($sql, $count2 + 1, 1) == '-'))
|| (($count2 + 2 < $len) && ($c == '-') && (PMA_substr($sql, $count2 + 1, 1) == '-') && ((PMA_substr($sql, $count2 + 2, 1) <= ' ')))) {
$count2++;
$pos = 0;
$type = 'bad';
switch ($c) {
case '#':
$type = 'mysql';
case '-':
$type = 'ansi';
$pos = $GLOBALS['PMA_strpos']($sql, "\n", $count2);
break;
case '/':
$type = 'c';
$pos = $GLOBALS['PMA_strpos']($sql, '*/', $count2);
$pos += 2;
break;
default:
break;
} // end switch
$count2 = ($pos < $count2) ? $len : $pos;
$str = PMA_substr($sql, $count1, $count2 - $count1);
PMA_SQP_arrayAdd($sql_array, 'comment_' . $type, $str, $arraysize);
continue;
} // end if
// Checks for something inside quotation marks
if (PMA_STR_strInStr($c, $quote_list)) {
$startquotepos = $count2;
$quotetype = $c;
$count2++;
$escaped = FALSE;
$escaped_escaped = FALSE;
$pos = $count2;
$oldpos = 0;
do {
$oldpos = $pos;
$pos = $GLOBALS['PMA_strpos'](' ' . $sql, $quotetype, $oldpos + 1) - 1;
// ($pos === FALSE)
if ($pos < 0) {
$debugstr = $GLOBALS['strSQPBugUnclosedQuote'] . ' @ ' . $startquotepos. "\n"
. 'STR: ' . htmlspecialchars($quotetype);
PMA_SQP_throwError($debugstr, $sql);
return $sql;
}
// If the quote is the first character, it can't be
// escaped, so don't do the rest of the code
if ($pos == 0) {
break;
}
// Checks for MySQL escaping using a \
// And checks for ANSI escaping using the $quotetype character
if (($pos < $len) && PMA_STR_charIsEscaped($sql, $pos)) {
$pos ++;
continue;
} elseif (($pos + 1 < $len) && (PMA_substr($sql, $pos, 1) == $quotetype) && (PMA_substr($sql, $pos + 1, 1) == $quotetype)) {
$pos = $pos + 2;
continue;
} else {
break;
}
} while ($len > $pos); // end do
$count2 = $pos;
$count2++;
$type = 'quote_';
switch ($quotetype) {
case '\'':
$type .= 'single';
$this_was_quote = true;
break;
case '"':
$type .= 'double';
$this_was_quote = true;
break;
case '`':
$type .= 'backtick';
$this_was_quote = true;
break;
default:
break;
} // end switch
$data = PMA_substr($sql, $count1, $count2 - $count1);
PMA_SQP_arrayAdd($sql_array, $type, $data, $arraysize);
continue;
}
// Checks for brackets
if (PMA_STR_strInStr($c, $bracket_list)) {
// All bracket tokens are only one item long
$this_was_bracket = true;
$count2++;
$type_type = '';
if (PMA_STR_strInStr($c, '([{')) {
$type_type = 'open';
} else {
$type_type = 'close';
}
$type_style = '';
if (PMA_STR_strInStr($c, '()')) {
$type_style = 'round';
} elseif (PMA_STR_strInStr($c, '[]')) {
$type_style = 'square';
} else {
$type_style = 'curly';
}
$type = 'punct_bracket_' . $type_type . '_' . $type_style;
PMA_SQP_arrayAdd($sql_array, $type, $c, $arraysize);
continue;
}
/* DEBUG
echo '<pre>1';
var_dump(PMA_STR_isSqlIdentifier($c, false));
var_dump($c == '@');
var_dump($c == '.');
var_dump(PMA_STR_isDigit(PMA_substr($sql, $count2 + 1, 1)));
var_dump($previous_was_space);
var_dump($previous_was_bracket);
var_dump($previous_was_listsep);
echo '</pre>';
*/
// Checks for identifier (alpha or numeric)
if (PMA_STR_isSqlIdentifier($c, false)
|| $c == '@'
|| ($c == '.'
&& PMA_STR_isDigit(PMA_substr($sql, $count2 + 1, 1))
&& ($previous_was_space || $previous_was_bracket || $previous_was_listsep))) {
/* DEBUG
echo PMA_substr($sql, $count2);
echo '<hr />';
*/
$count2++;
/**
* @todo a @ can also be present in expressions like
* FROM 'user'@'%' or TO 'user'@'%'
* in this case, the @ is wrongly marked as alpha_variable
*/
$is_identifier = $previous_was_punct;
$is_sql_variable = $c == '@' && ! $previous_was_quote;
$is_user = $c == '@' && $previous_was_quote;
$is_digit = !$is_identifier && !$is_sql_variable && PMA_STR_isDigit($c);
$is_hex_digit = $is_digit && $c == '0' && $count2 < $len && PMA_substr($sql, $count2, 1) == 'x';
$is_float_digit = $c == '.';
$is_float_digit_exponent = FALSE;
/* DEBUG
echo '<pre>2';
var_dump($is_identifier);
var_dump($is_sql_variable);
var_dump($is_digit);
var_dump($is_float_digit);
echo '</pre>';
*/
// Nijel: Fast skip is especially needed for huge BLOB data, requires PHP at least 4.3.0:
if (PMA_PHP_INT_VERSION >= 40300) {
if ($is_hex_digit) {
$count2++;
$pos = strspn($sql, '0123456789abcdefABCDEF', $count2);
if ($pos > $count2) {
$count2 = $pos;
}
unset($pos);
} elseif ($is_digit) {
$pos = strspn($sql, '0123456789', $count2);
if ($pos > $count2) {
$count2 = $pos;
}
unset($pos);
}
}
while (($count2 < $len) && PMA_STR_isSqlIdentifier(PMA_substr($sql, $count2, 1), ($is_sql_variable || $is_digit))) {
$c2 = PMA_substr($sql, $count2, 1);
if ($is_sql_variable && ($c2 == '.')) {
$count2++;
continue;
}
if ($is_digit && (!$is_hex_digit) && ($c2 == '.')) {
$count2++;
if (!$is_float_digit) {
$is_float_digit = TRUE;
continue;
} else {
$debugstr = $GLOBALS['strSQPBugInvalidIdentifer'] . ' @ ' . ($count1+1) . "\n"
. 'STR: ' . htmlspecialchars(PMA_substr($sql, $count1, $count2 - $count1));
PMA_SQP_throwError($debugstr, $sql);
return $sql;
}
}
if ($is_digit && (!$is_hex_digit) && (($c2 == 'e') || ($c2 == 'E'))) {
if (!$is_float_digit_exponent) {
$is_float_digit_exponent = TRUE;
$is_float_digit = TRUE;
$count2++;
continue;
} else {
$is_digit = FALSE;
$is_float_digit = FALSE;
}
}
if (($is_hex_digit && PMA_STR_isHexDigit($c2)) || ($is_digit && PMA_STR_isDigit($c2))) {
$count2++;
continue;
} else {
$is_digit = FALSE;
$is_hex_digit = FALSE;
}
$count2++;
} // end while
$l = $count2 - $count1;
$str = PMA_substr($sql, $count1, $l);
$type = '';
if ($is_digit || $is_float_digit || $is_hex_digit) {
$type = 'digit';
if ($is_float_digit) {
$type .= '_float';
} elseif ($is_hex_digit) {
$type .= '_hex';
} else {
$type .= '_integer';
}
} elseif ($is_user) {
$type = 'punct_user';
} elseif ($is_sql_variable != FALSE) {
$type = 'alpha_variable';
} else {
$type = 'alpha';
} // end if... else....
PMA_SQP_arrayAdd($sql_array, $type, $str, $arraysize, $count2);
continue;
}
// Checks for punct
if (PMA_STR_strInStr($c, $allpunct_list)) {
while (($count2 < $len) && PMA_STR_strInStr(PMA_substr($sql, $count2, 1), $allpunct_list)) {
$count2++;
}
$l = $count2 - $count1;
if ($l == 1) {
$punct_data = $c;
} else {
$punct_data = PMA_substr($sql, $count1, $l);
}
// Special case, sometimes, althought two characters are
// adjectent directly, they ACTUALLY need to be seperate
/* DEBUG
echo '<pre>';
var_dump($l);
var_dump($punct_data);
echo '</pre>';
*/
if ($l == 1) {
$t_suffix = '';
switch ($punct_data) {
case $punct_queryend:
$t_suffix = '_queryend';
break;
case $punct_qualifier:
$t_suffix = '_qualifier';
$this_was_punct = true;
break;
case $punct_listsep:
$this_was_listsep = true;
$t_suffix = '_listsep';
break;
default:
break;
}
PMA_SQP_arrayAdd($sql_array, 'punct' . $t_suffix, $punct_data, $arraysize);
} elseif (PMA_STR_binarySearchInArr($punct_data, $allpunct_list_pair, $allpunct_list_pair_size)) {
// Ok, we have one of the valid combined punct expressions
PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize);
} else {
// Bad luck, lets split it up more
$first = $punct_data[0];
$first2 = $punct_data[0] . $punct_data[1];
$last2 = $punct_data[$l - 2] . $punct_data[$l - 1];
$last = $punct_data[$l - 1];
if (($first == ',') || ($first == ';') || ($first == '.') || ($first == '*')) {
$count2 = $count1 + 1;
$punct_data = $first;
} elseif (($last2 == '/*') || (($last2 == '--') && ($count2 == $len || PMA_substr($sql, $count2, 1) <= ' '))) {
$count2 -= 2;
$punct_data = PMA_substr($sql, $count1, $count2 - $count1);
} elseif (($last == '-') || ($last == '+') || ($last == '!')) {
$count2--;
$punct_data = PMA_substr($sql, $count1, $count2 - $count1);
/**
* @todo for negation operator, split in 2 tokens ?
* "select x&~1 from t"
* becomes "select x & ~ 1 from t" ?
*/
} elseif ($last != '~') {
$debugstr = $GLOBALS['strSQPBugUnknownPunctuation'] . ' @ ' . ($count1+1) . "\n"
. 'STR: ' . htmlspecialchars($punct_data);
PMA_SQP_throwError($debugstr, $sql);
return $sql;
}
PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize);
continue;
} // end if... elseif... else
continue;
}
// DEBUG
$count2++;
$debugstr = 'C1 C2 LEN: ' . $count1 . ' ' . $count2 . ' ' . $len . "\n"
. 'STR: ' . PMA_substr($sql, $count1, $count2 - $count1) . "\n";
PMA_SQP_bug($debugstr, $sql);
return $sql;
} // end while ($count2 < $len)
/*
echo '<pre>';
print_r($sql_array);
echo '</pre>';
*/
if ($arraysize > 0) {
$t_next = $sql_array[0]['type'];
$t_prev = '';
$t_bef_prev = '';
$t_cur = '';
$d_next = $sql_array[0]['data'];
$d_prev = '';
$d_bef_prev = '';
$d_cur = '';
$d_next_upper = $t_next == 'alpha' ? strtoupper($d_next) : $d_next;
$d_prev_upper = '';
$d_bef_prev_upper = '';
$d_cur_upper = '';
}
for ($i = 0; $i < $arraysize; $i++) {
$t_bef_prev = $t_prev;
$t_prev = $t_cur;
$t_cur = $t_next;
$d_bef_prev = $d_prev;
$d_prev = $d_cur;
$d_cur = $d_next;
$d_bef_prev_upper = $d_prev_upper;
$d_prev_upper = $d_cur_upper;
$d_cur_upper = $d_next_upper;
if (($i + 1) < $arraysize) {
$t_next = $sql_array[$i + 1]['type'];
$d_next = $sql_array[$i + 1]['data'];
$d_next_upper = $t_next == 'alpha' ? strtoupper($d_next) : $d_next;
} else {
$t_next = '';
$d_next = '';
$d_next_upper = '';
}
//DEBUG echo "[prev: <b>".$d_prev."</b> ".$t_prev."][cur: <b>".$d_cur."</b> ".$t_cur."][next: <b>".$d_next."</b> ".$t_next."]<br />";
if ($t_cur == 'alpha') {
$t_suffix = '_identifier';
if (($t_next == 'punct_qualifier') || ($t_prev == 'punct_qualifier')) {
$t_suffix = '_identifier';
} elseif (($t_next == 'punct_bracket_open_round')
&& PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_function_name, $PMA_SQPdata_function_name_cnt)) {
/**
* @todo 2005-10-16: in the case of a CREATE TABLE containing
* a TIMESTAMP, since TIMESTAMP() is also a function, it's
* found here and the token is wrongly marked as alpha_functionName.
* But we compensate for this when analysing for timestamp_not_null
* later in this script.
*
* Same applies to CHAR vs. CHAR() function.
*/
$t_suffix = '_functionName';
/* There are functions which might be as well column types */
if (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_column_type, $PMA_SQPdata_column_type_cnt)) {
}
} elseif (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_column_type, $PMA_SQPdata_column_type_cnt)) {
$t_suffix = '_columnType';
/**
* Temporary fix for BUG #621357
*
* @todo FIX PROPERLY NEEDS OVERHAUL OF SQL TOKENIZER
*/
if ($d_cur_upper == 'SET' && $t_next != 'punct_bracket_open_round') {
$t_suffix = '_reservedWord';
}
//END OF TEMPORARY FIX
// CHARACTER is a synonym for CHAR, but can also be meant as
// CHARACTER SET. In this case, we have a reserved word.
if ($d_cur_upper == 'CHARACTER' && $d_next_upper == 'SET') {
$t_suffix = '_reservedWord';
}
// experimental
// current is a column type, so previous must not be
// a reserved word but an identifier
// CREATE TABLE SG_Persons (first varchar(64))
//if ($sql_array[$i-1]['type'] =='alpha_reservedWord') {
// $sql_array[$i-1]['type'] = 'alpha_identifier';
//}
} elseif (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_reserved_word, $PMA_SQPdata_reserved_word_cnt)) {
$t_suffix = '_reservedWord';
} elseif (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_column_attrib, $PMA_SQPdata_column_attrib_cnt)) {
$t_suffix = '_columnAttrib';
// INNODB is a MySQL table type, but in "SHOW INNODB STATUS",
// it should be regarded as a reserved word.
if ($d_cur_upper == 'INNODB' && $d_prev_upper == 'SHOW' && $d_next_upper == 'STATUS') {
$t_suffix = '_reservedWord';
}
if ($d_cur_upper == 'DEFAULT' && $d_next_upper == 'CHARACTER') {
$t_suffix = '_reservedWord';
}
// Binary as character set
if ($d_cur_upper == 'BINARY' && (
($d_bef_prev_upper == 'CHARACTER' && $d_prev_upper == 'SET')
|| ($d_bef_prev_upper == 'SET' && $d_prev_upper == '=')
|| ($d_bef_prev_upper == 'CHARSET' && $d_prev_upper == '=')
|| $d_prev_upper == 'CHARSET'
) && PMA_STR_binarySearchInArr($d_cur, $mysql_charsets, count($mysql_charsets))) {
$t_suffix = '_charset';
}
} elseif (PMA_STR_binarySearchInArr($d_cur, $mysql_charsets, $mysql_charsets_count)
|| PMA_STR_binarySearchInArr($d_cur, $mysql_collations_flat, $mysql_collations_count)
|| ($d_cur{0} == '_' && PMA_STR_binarySearchInArr(substr($d_cur, 1), $mysql_charsets, $mysql_charsets_count))) {
$t_suffix = '_charset';
} else {
// Do nothing
}
// check if present in the list of forbidden words
if ($t_suffix == '_reservedWord' && PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
$sql_array[$i]['forbidden'] = TRUE;
} else {
$sql_array[$i]['forbidden'] = FALSE;
}
$sql_array[$i]['type'] .= $t_suffix;
}
} // end for
// Stores the size of the array inside the array, as count() is a slow
// operation.
$sql_array['len'] = $arraysize;
// DEBUG echo 'After parsing<pre>'; print_r($sql_array); echo '</pre>';
// Sends the data back
return $sql_array;
} // end of the "PMA_SQP_parse()" function
/**
* Checks for token types being what we want...
*
* @param string String of type that we have
* @param string String of type that we want
*
* @return boolean result of check
*
* @access private
*/
function PMA_SQP_typeCheck($toCheck, $whatWeWant)
{
$typeSeperator = '_';
if (strcmp($whatWeWant, $toCheck) == 0) {
return TRUE;
} else {
if (strpos($whatWeWant, $typeSeperator) === FALSE) {
return strncmp($whatWeWant, $toCheck, strpos($toCheck, $typeSeperator)) == 0;
} else {
return FALSE;
}
}
}
/**
* Analyzes SQL queries
*
* @param array The SQL queries
*
* @return array The analyzed SQL queries
*
* @access public
*/
function PMA_SQP_analyze($arr)
{
if ($arr == array()) {
return array();
}
$result = array();
$size = $arr['len'];
$subresult = array(
'querytype' => '',
'select_expr_clause'=> '', // the whole stuff between SELECT and FROM , except DISTINCT
'position_of_first_select' => '', // the array index
'from_clause'=> '',
'group_by_clause'=> '',
'order_by_clause'=> '',
'having_clause' => '',
'limit_clause' => '',
'where_clause' => '',
'where_clause_identifiers' => array(),
'unsorted_query' => '',
'queryflags' => array(),
'select_expr' => array(),
'table_ref' => array(),
'foreign_keys' => array(),
'create_table_fields' => array()
);
$subresult_empty = $subresult;
$seek_queryend = FALSE;
$seen_end_of_table_ref = FALSE;
$number_of_brackets_in_extract = 0;
$number_of_brackets_in_group_concat = 0;
$number_of_brackets = 0;
$in_subquery = false;
$seen_subquery = false;
$seen_from = false;
// for SELECT EXTRACT(YEAR_MONTH FROM CURDATE())
// we must not use CURDATE as a table_ref
// so we track wether we are in the EXTRACT()
$in_extract = FALSE;
// for GROUP_CONCAT(...)
$in_group_concat = FALSE;
/* Description of analyzer results by lem9
*
* db, table, column, alias
* ------------------------
*
* Inside the $subresult array, we create ['select_expr'] and ['table_ref'] arrays.
*
* The SELECT syntax (simplified) is
*
* SELECT
* select_expression,...
* [FROM [table_references]
*
*
* ['select_expr'] is filled with each expression, the key represents the
* expression position in the list (0-based) (so we don't lose track of
* multiple occurences of the same column).
*
* ['table_ref'] is filled with each table ref, same thing for the key.
*
* I create all sub-values empty, even if they are
* not present (for example no select_expression alias).
*
* There is a debug section at the end of loop #1, if you want to
* see the exact contents of select_expr and table_ref
*
* queryflags
* ----------
*
* In $subresult, array 'queryflags' is filled, according to what we
* find in the query.
*
* Currently, those are generated:
*
* ['queryflags']['need_confirm'] = 1; if the query needs confirmation
* ['queryflags']['select_from'] = 1; if this is a real SELECT...FROM
* ['queryflags']['distinct'] = 1; for a DISTINCT
* ['queryflags']['union'] = 1; for a UNION
* ['queryflags']['join'] = 1; for a JOIN
* ['queryflags']['offset'] = 1; for the presence of OFFSET
* ['queryflags']['procedure'] = 1; for the presence of PROCEDURE
*
* query clauses
* -------------
*
* The select is splitted in those clauses:
* ['select_expr_clause']
* ['from_clause']
* ['group_by_clause']
* ['order_by_clause']
* ['having_clause']
* ['where_clause']
* ['limit_clause']
*
* The identifiers of the WHERE clause are put into the array
* ['where_clause_identifier']
*
* For a SELECT, the whole query without the ORDER BY clause is put into
* ['unsorted_query']
*
* foreign keys
* ------------
* The CREATE TABLE may contain FOREIGN KEY clauses, so they get
* analyzed and ['foreign_keys'] is an array filled with
* the constraint name, the index list,
* the REFERENCES table name and REFERENCES index list,
* and ON UPDATE | ON DELETE clauses
*
* position_of_first_select
* ------------------------
*
* The array index of the first SELECT we find. Will be used to
* insert a SQL_CALC_FOUND_ROWS.
*
* create_table_fields
* -------------------
*
* For now, mostly used to detect the DEFAULT CURRENT_TIMESTAMP and
* ON UPDATE CURRENT_TIMESTAMP clauses of the CREATE TABLE query.
* An array, each element is the identifier name.
* Note that for now, the timestamp_not_null element is created
* even for non-TIMESTAMP fields.
*
* Sub-elements: ['type'] which contains the column type
* optional (currently they are never false but can be absent):
* ['default_current_timestamp'] boolean
* ['on_update_current_timestamp'] boolean
* ['timestamp_not_null'] boolean
*
* section_before_limit, section_after_limit
* -----------------------------------------
*
* Marks the point of the query where we can insert a LIMIT clause;
* so the section_before_limit will contain the left part before
* a possible LIMIT clause
*
*
* End of description of analyzer results
*/
// must be sorted
// TODO: current logic checks for only one word, so I put only the
// first word of the reserved expressions that end a table ref;
// maybe this is not ok (the first word might mean something else)
// $words_ending_table_ref = array(
// 'FOR UPDATE',
// 'GROUP BY',
// 'HAVING',
// 'LIMIT',
// 'LOCK IN SHARE MODE',
// 'ORDER BY',
// 'PROCEDURE',
// 'UNION',
// 'WHERE'
// );
$words_ending_table_ref = array(
'FOR',
'GROUP',
'HAVING',
'LIMIT',
'LOCK',
'ORDER',
'PROCEDURE',
'UNION',
'WHERE'
);
$words_ending_table_ref_cnt = 9; //count($words_ending_table_ref);
$words_ending_clauses = array(
'FOR',
'LIMIT',
'LOCK',
'PROCEDURE',
'UNION'
);
$words_ending_clauses_cnt = 5; //count($words_ending_clauses);
// must be sorted
$supported_query_types = array(
'SELECT'
/*
// Support for these additional query types will come later on.
'DELETE',
'INSERT',
'REPLACE',
'TRUNCATE',
'UPDATE'
'EXPLAIN',
'DESCRIBE',
'SHOW',
'CREATE',
'SET',
'ALTER'
*/
);
$supported_query_types_cnt = count($supported_query_types);
// loop #1 for each token: select_expr, table_ref for SELECT
for ($i = 0; $i < $size; $i++) {
//DEBUG echo "Loop1 <b>" . $arr[$i]['data'] . "</b> (" . $arr[$i]['type'] . ")<br />";
// High speed seek for locating the end of the current query
if ($seek_queryend == TRUE) {
if ($arr[$i]['type'] == 'punct_queryend') {
$seek_queryend = FALSE;
} else {
continue;
} // end if (type == punct_queryend)
} // end if ($seek_queryend)
/**
* Note: do not split if this is a punct_queryend for the first and only query
* @todo when we find a UNION, should we split in another subresult?
*/
if ($arr[$i]['type'] == 'punct_queryend' && ($i + 1 != $size)) {
$result[] = $subresult;
$subresult = $subresult_empty;
continue;
} // end if (type == punct_queryend)
// ==============================================================
if ($arr[$i]['type'] == 'punct_bracket_open_round') {
$number_of_brackets++;
if ($in_extract) {
$number_of_brackets_in_extract++;
}
if ($in_group_concat) {
$number_of_brackets_in_group_concat++;
}
}
// ==============================================================
if ($arr[$i]['type'] == 'punct_bracket_close_round') {
$number_of_brackets--;
if ($number_of_brackets == 0) {
$in_subquery = false;
}
if ($in_extract) {
$number_of_brackets_in_extract--;
if ($number_of_brackets_in_extract == 0) {
$in_extract = FALSE;
}
}
if ($in_group_concat) {
$number_of_brackets_in_group_concat--;
if ($number_of_brackets_in_group_concat == 0) {
$in_group_concat = FALSE;
}
}
}
if ($in_subquery) {
/**
* skip the subquery to avoid setting
* select_expr or table_ref with the contents
* of this subquery; this is to avoid a bug when
* trying to edit the results of
* select * from child where not exists (select id from
* parent where child.parent_id = parent.id);
*/
continue;
}
// ==============================================================
if ($arr[$i]['type'] == 'alpha_functionName') {
$upper_data = strtoupper($arr[$i]['data']);
if ($upper_data =='EXTRACT') {
$in_extract = TRUE;
$number_of_brackets_in_extract = 0;
}
if ($upper_data =='GROUP_CONCAT') {
$in_group_concat = TRUE;
$number_of_brackets_in_group_concat = 0;
}
}
// ==============================================================
if ($arr[$i]['type'] == 'alpha_reservedWord'
// && $arr[$i]['forbidden'] == FALSE) {
) {
// We don't know what type of query yet, so run this
if ($subresult['querytype'] == '') {
$subresult['querytype'] = strtoupper($arr[$i]['data']);
} // end if (querytype was empty)
// Check if we support this type of query
if (!PMA_STR_binarySearchInArr($subresult['querytype'], $supported_query_types, $supported_query_types_cnt)) {
// Skip ahead to the next one if we don't
$seek_queryend = TRUE;
continue;
} // end if (query not supported)
// upper once
$upper_data = strtoupper($arr[$i]['data']);
/**
* @todo reset for each query?
*/
if ($upper_data == 'SELECT') {
if ($number_of_brackets > 0) {
$in_subquery = true;
$seen_subquery = true;
// this is a subquery so do not analyze inside it
continue;
}
$seen_from = FALSE;
$previous_was_identifier = FALSE;
$current_select_expr = -1;
$seen_end_of_table_ref = FALSE;
} // end if (data == SELECT)
if ($upper_data =='FROM' && !$in_extract) {
$current_table_ref = -1;
$seen_from = TRUE;
$previous_was_identifier = FALSE;
$save_table_ref = TRUE;
} // end if (data == FROM)
// here, do not 'continue' the loop, as we have more work for
// reserved words below
} // end if (type == alpha_reservedWord)
// ==============================
if ($arr[$i]['type'] == 'quote_backtick'
|| $arr[$i]['type'] == 'quote_double'
|| $arr[$i]['type'] == 'quote_single'
|| $arr[$i]['type'] == 'alpha_identifier'
|| ($arr[$i]['type'] == 'alpha_reservedWord'
&& $arr[$i]['forbidden'] == FALSE)) {
switch ($arr[$i]['type']) {
case 'alpha_identifier':
case 'alpha_reservedWord':
/**
* this is not a real reservedWord, because it's not
* present in the list of forbidden words, for example
* "storage" which can be used as an identifier
*
* @todo avoid the pretty printing in color in this case
*/
$identifier = $arr[$i]['data'];
break;
case 'quote_backtick':
case 'quote_double':
case 'quote_single':
$identifier = PMA_unQuote($arr[$i]['data']);
break;
} // end switch
if ($subresult['querytype'] == 'SELECT'
&& ! $in_group_concat
&& ! ($seen_subquery && $arr[$i - 1]['type'] == 'punct_bracket_close_round')) {
if (!$seen_from) {
if ($previous_was_identifier && isset($chain)) {
// found alias for this select_expr, save it
// but only if we got something in $chain
// (for example, SELECT COUNT(*) AS cnt
// puts nothing in $chain, so we avoid
// setting the alias)
$alias_for_select_expr = $identifier;
} else {
$chain[] = $identifier;
$previous_was_identifier = TRUE;
} // end if !$previous_was_identifier
} else {
// ($seen_from)
if ($save_table_ref && !$seen_end_of_table_ref) {
if ($previous_was_identifier) {
// found alias for table ref
// save it for later
$alias_for_table_ref = $identifier;
} else {
$chain[] = $identifier;
$previous_was_identifier = TRUE;
} // end if ($previous_was_identifier)
} // end if ($save_table_ref &&!$seen_end_of_table_ref)
} // end if (!$seen_from)
} // end if (querytype SELECT)
} // end if (quote_backtick or double quote or alpha_identifier)
// ===================================
if ($arr[$i]['type'] == 'punct_qualifier') {
// to be able to detect an identifier following another
$previous_was_identifier = FALSE;
continue;
} // end if (punct_qualifier)
/**
* @todo check if 3 identifiers following one another -> error
*/
// s a v e a s e l e c t e x p r
// finding a list separator or FROM
// means that we must save the current chain of identifiers
// into a select expression
// for now, we only save a select expression if it contains
// at least one identifier, as we are interested in checking
// the columns and table names, so in "select * from persons",
// the "*" is not saved
if (isset($chain) && !$seen_end_of_table_ref
&& ((!$seen_from && $arr[$i]['type'] == 'punct_listsep')
|| ($arr[$i]['type'] == 'alpha_reservedWord' && $upper_data == 'FROM'))) {
$size_chain = count($chain);
$current_select_expr++;
$subresult['select_expr'][$current_select_expr] = array(
'expr' => '',
'alias' => '',
'db' => '',
'table_name' => '',
'table_true_name' => '',
'column' => ''
);
if (isset($alias_for_select_expr) && strlen($alias_for_select_expr)) {
// we had found an alias for this select expression
$subresult['select_expr'][$current_select_expr]['alias'] = $alias_for_select_expr;
unset($alias_for_select_expr);
}
// there is at least a column
$subresult['select_expr'][$current_select_expr]['column'] = $chain[$size_chain - 1];
$subresult['select_expr'][$current_select_expr]['expr'] = $chain[$size_chain - 1];
// maybe a table
if ($size_chain > 1) {
$subresult['select_expr'][$current_select_expr]['table_name'] = $chain[$size_chain - 2];
// we assume for now that this is also the true name
$subresult['select_expr'][$current_select_expr]['table_true_name'] = $chain[$size_chain - 2];
$subresult['select_expr'][$current_select_expr]['expr']
= $subresult['select_expr'][$current_select_expr]['table_name']
. '.' . $subresult['select_expr'][$current_select_expr]['expr'];
} // end if ($size_chain > 1)
// maybe a db
if ($size_chain > 2) {
$subresult['select_expr'][$current_select_expr]['db'] = $chain[$size_chain - 3];
$subresult['select_expr'][$current_select_expr]['expr']
= $subresult['select_expr'][$current_select_expr]['db']
. '.' . $subresult['select_expr'][$current_select_expr]['expr'];
} // end if ($size_chain > 2)
unset($chain);
/**
* @todo explain this:
*/
if (($arr[$i]['type'] == 'alpha_reservedWord')
&& ($upper_data != 'FROM')) {
$previous_was_identifier = TRUE;
}
} // end if (save a select expr)
//======================================
// s a v e a t a b l e r e f
//======================================
// maybe we just saw the end of table refs
// but the last table ref has to be saved
// or we are at the last token
// or we just got a reserved word
/**
* @todo there could be another query after this one
*/
if (isset($chain) && $seen_from && $save_table_ref
&& ($arr[$i]['type'] == 'punct_listsep'
|| ($arr[$i]['type'] == 'alpha_reservedWord' && $upper_data!="AS")
|| $seen_end_of_table_ref
|| $i==$size-1)) {
$size_chain = count($chain);
$current_table_ref++;
$subresult['table_ref'][$current_table_ref] = array(
'expr' => '',
'db' => '',
'table_name' => '',
'table_alias' => '',
'table_true_name' => ''
);
if (isset($alias_for_table_ref) && strlen($alias_for_table_ref)) {
$subresult['table_ref'][$current_table_ref]['table_alias'] = $alias_for_table_ref;
unset($alias_for_table_ref);
}
$subresult['table_ref'][$current_table_ref]['table_name'] = $chain[$size_chain - 1];
// we assume for now that this is also the true name
$subresult['table_ref'][$current_table_ref]['table_true_name'] = $chain[$size_chain - 1];
$subresult['table_ref'][$current_table_ref]['expr']
= $subresult['table_ref'][$current_table_ref]['table_name'];
// maybe a db
if ($size_chain > 1) {
$subresult['table_ref'][$current_table_ref]['db'] = $chain[$size_chain - 2];
$subresult['table_ref'][$current_table_ref]['expr']
= $subresult['table_ref'][$current_table_ref]['db']
. '.' . $subresult['table_ref'][$current_table_ref]['expr'];
} // end if ($size_chain > 1)
// add the table alias into the whole expression
$subresult['table_ref'][$current_table_ref]['expr']
.= ' ' . $subresult['table_ref'][$current_table_ref]['table_alias'];
unset($chain);
$previous_was_identifier = TRUE;
//continue;
} // end if (save a table ref)
// when we have found all table refs,
// for each table_ref alias, put the true name of the table
// in the corresponding select expressions
if (isset($current_table_ref) && ($seen_end_of_table_ref || $i == $size-1) && $subresult != $subresult_empty) {
for ($tr=0; $tr <= $current_table_ref; $tr++) {
$alias = $subresult['table_ref'][$tr]['table_alias'];
$truename = $subresult['table_ref'][$tr]['table_true_name'];
for ($se=0; $se <= $current_select_expr; $se++) {
if (isset($alias) && strlen($alias) && $subresult['select_expr'][$se]['table_true_name']
== $alias) {
$subresult['select_expr'][$se]['table_true_name']
= $truename;
} // end if (found the alias)
} // end for (select expressions)
} // end for (table refs)
} // end if (set the true names)
// e n d i n g l o o p #1
// set the $previous_was_identifier to FALSE if the current
// token is not an identifier
if (($arr[$i]['type'] != 'alpha_identifier')
&& ($arr[$i]['type'] != 'quote_double')
&& ($arr[$i]['type'] != 'quote_single')
&& ($arr[$i]['type'] != 'quote_backtick')) {
$previous_was_identifier = FALSE;
} // end if
// however, if we are on AS, we must keep the $previous_was_identifier
if (($arr[$i]['type'] == 'alpha_reservedWord')
&& ($upper_data == 'AS')) {
$previous_was_identifier = TRUE;
}
if (($arr[$i]['type'] == 'alpha_reservedWord')
&& ($upper_data =='ON' || $upper_data =='USING')) {
$save_table_ref = FALSE;
} // end if (data == ON)
if (($arr[$i]['type'] == 'alpha_reservedWord')
&& ($upper_data =='JOIN' || $upper_data =='FROM')) {
$save_table_ref = TRUE;
} // end if (data == JOIN)
/**
* no need to check the end of table ref if we already did
*
* @todo maybe add "&& $seen_from"
*/
if (!$seen_end_of_table_ref) {
// if this is the last token, it implies that we have
// seen the end of table references
// Check for the end of table references
//
// Note: if we are analyzing a GROUP_CONCAT clause,
// we might find a word that seems to indicate that
// we have found the end of table refs (like ORDER)
// but it's a modifier of the GROUP_CONCAT so
// it's not the real end of table refs
if (($i == $size-1)
|| ($arr[$i]['type'] == 'alpha_reservedWord'
&& !$in_group_concat
&& PMA_STR_binarySearchInArr($upper_data, $words_ending_table_ref, $words_ending_table_ref_cnt))) {
$seen_end_of_table_ref = TRUE;
// to be able to save the last table ref, but do not
// set it true if we found a word like "ON" that has
// already set it to false
if (isset($save_table_ref) && $save_table_ref != FALSE) {
$save_table_ref = TRUE;
} //end if
} // end if (check for end of table ref)
} //end if (!$seen_end_of_table_ref)
if ($seen_end_of_table_ref) {
$save_table_ref = FALSE;
} // end if
} // end for $i (loop #1)
//DEBUG
/*
if (isset($current_select_expr)) {
for ($trace=0; $trace<=$current_select_expr; $trace++) {
echo "<br />";
reset ($subresult['select_expr'][$trace]);
while (list ($key, $val) = each ($subresult['select_expr'][$trace]))
echo "sel expr $trace $key => $val<br />\n";
}
}
if (isset($current_table_ref)) {
echo "current_table_ref = " . $current_table_ref . "<br>";
for ($trace=0; $trace<=$current_table_ref; $trace++) {
echo "<br />";
reset ($subresult['table_ref'][$trace]);
while (list ($key, $val) = each ($subresult['table_ref'][$trace]))
echo "table ref $trace $key => $val<br />\n";
}
}
*/
// -------------------------------------------------------
// loop #2: - queryflags
// - querytype (for queries != 'SELECT')
// - section_before_limit, section_after_limit
//
// we will also need this queryflag in loop 2
// so set it here
if (isset($current_table_ref) && $current_table_ref > -1) {
$subresult['queryflags']['select_from'] = 1;
}
$section_before_limit = '';
$section_after_limit = ''; // truly the section after the limit clause
$seen_reserved_word = FALSE;
$seen_group = FALSE;
$seen_order = FALSE;
$seen_order_by = FALSE;
$in_group_by = FALSE; // true when we are inside the GROUP BY clause
$in_order_by = FALSE; // true when we are inside the ORDER BY clause
$in_having = FALSE; // true when we are inside the HAVING clause
$in_select_expr = FALSE; // true when we are inside the select expr clause
$in_where = FALSE; // true when we are inside the WHERE clause
$seen_limit = FALSE; // true if we have seen a LIMIT clause
$in_limit = FALSE; // true when we are inside the LIMIT clause
$after_limit = FALSE; // true when we are after the LIMIT clause
$in_from = FALSE; // true when we are in the FROM clause
$in_group_concat = FALSE;
$first_reserved_word = '';
$current_identifier = '';
$unsorted_query = $arr['raw']; // in case there is no ORDER BY
for ($i = 0; $i < $size; $i++) {
//DEBUG echo "Loop2 <b>" . $arr[$i]['data'] . "</b> (" . $arr[$i]['type'] . ")<br />";
// need_confirm
//
// check for reserved words that will have to generate
// a confirmation request later in sql.php
// the cases are:
// DROP TABLE
// DROP DATABASE
// ALTER TABLE... DROP
// DELETE FROM...
//
// this code is not used for confirmations coming from functions.js
if ($arr[$i]['type'] == 'alpha_reservedWord') {
$upper_data = strtoupper($arr[$i]['data']);
if (!$seen_reserved_word) {
$first_reserved_word = $upper_data;
$subresult['querytype'] = $upper_data;
$seen_reserved_word = TRUE;
// if the first reserved word is DROP or DELETE,
// we know this is a query that needs to be confirmed
if ($first_reserved_word=='DROP'
|| $first_reserved_word == 'DELETE'
|| $first_reserved_word == 'TRUNCATE') {
$subresult['queryflags']['need_confirm'] = 1;
}
if ($first_reserved_word=='SELECT'){
$position_of_first_select = $i;
}
} else {
if ($upper_data == 'DROP' && $first_reserved_word == 'ALTER') {
$subresult['queryflags']['need_confirm'] = 1;
}
}
if ($upper_data == 'LIMIT') {
$section_before_limit = substr($arr['raw'], 0, $arr[$i]['pos'] - 5);
$in_limit = TRUE;
$seen_limit = TRUE;
$limit_clause = '';
$in_order_by = FALSE; // @todo maybe others to set FALSE
}
if ($upper_data == 'PROCEDURE') {
$subresult['queryflags']['procedure'] = 1;
$in_limit = FALSE;
$after_limit = TRUE;
}
/**
* @todo set also to FALSE if we find FOR UPDATE or LOCK IN SHARE MODE
*/
if ($upper_data == 'SELECT') {
$in_select_expr = TRUE;
$select_expr_clause = '';
}
if ($upper_data == 'DISTINCT' && !$in_group_concat) {
$subresult['queryflags']['distinct'] = 1;
}
if ($upper_data == 'UNION') {
$subresult['queryflags']['union'] = 1;
}
if ($upper_data == 'JOIN') {
$subresult['queryflags']['join'] = 1;
}
if ($upper_data == 'OFFSET') {
$subresult['queryflags']['offset'] = 1;
}
// if this is a real SELECT...FROM
if ($upper_data == 'FROM' && isset($subresult['queryflags']['select_from']) && $subresult['queryflags']['select_from'] == 1) {
$in_from = TRUE;
$from_clause = '';
$in_select_expr = FALSE;
}
// (we could have less resetting of variables to FALSE
// if we trust that the query respects the standard
// MySQL order for clauses)
// we use $seen_group and $seen_order because we are looking
// for the BY
if ($upper_data == 'GROUP') {
$seen_group = TRUE;
$seen_order = FALSE;
$in_having = FALSE;
$in_order_by = FALSE;
$in_where = FALSE;
$in_select_expr = FALSE;
$in_from = FALSE;
}
if ($upper_data == 'ORDER' && !$in_group_concat) {
$seen_order = TRUE;
$seen_group = FALSE;
$in_having = FALSE;
$in_group_by = FALSE;
$in_where = FALSE;
$in_select_expr = FALSE;
$in_from = FALSE;
}
if ($upper_data == 'HAVING') {
$in_having = TRUE;
$having_clause = '';
$seen_group = FALSE;
$seen_order = FALSE;
$in_group_by = FALSE;
$in_order_by = FALSE;
$in_where = FALSE;
$in_select_expr = FALSE;
$in_from = FALSE;
}
if ($upper_data == 'WHERE') {
$in_where = TRUE;
$where_clause = '';
$where_clause_identifiers = array();
$seen_group = FALSE;
$seen_order = FALSE;
$in_group_by = FALSE;
$in_order_by = FALSE;
$in_having = FALSE;
$in_select_expr = FALSE;
$in_from = FALSE;
}
if ($upper_data == 'BY') {
if ($seen_group) {
$in_group_by = TRUE;
$group_by_clause = '';
}
if ($seen_order) {
$seen_order_by = TRUE;
// here we assume that the ORDER BY keywords took
// exactly 8 characters
$unsorted_query = substr($arr['raw'], 0, $arr[$i]['pos'] - 8);
$in_order_by = TRUE;
$order_by_clause = '';
}
}
// if we find one of the words that could end the clause
if (PMA_STR_binarySearchInArr($upper_data, $words_ending_clauses, $words_ending_clauses_cnt)) {
$in_group_by = FALSE;
$in_order_by = FALSE;
$in_having = FALSE;
$in_where = FALSE;
$in_select_expr = FALSE;
$in_from = FALSE;
}
} // endif (reservedWord)
// do not add a space after a function name
/**
* @todo can we combine loop 2 and loop 1? some code is repeated here...
*/
$sep = ' ';
if ($arr[$i]['type'] == 'alpha_functionName') {
$sep='';
$upper_data = strtoupper($arr[$i]['data']);
if ($upper_data =='GROUP_CONCAT') {
$in_group_concat = TRUE;
$number_of_brackets_in_group_concat = 0;
}
}
if ($arr[$i]['type'] == 'punct_bracket_open_round') {
if ($in_group_concat) {
$number_of_brackets_in_group_concat++;
}
}
if ($arr[$i]['type'] == 'punct_bracket_close_round') {
if ($in_group_concat) {
$number_of_brackets_in_group_concat--;
if ($number_of_brackets_in_group_concat == 0) {
$in_group_concat = FALSE;
}
}
}
// do not add a space after an identifier if followed by a dot
if ($arr[$i]['type'] == 'alpha_identifier' && $i < $size - 1 && $arr[$i + 1]['data'] == '.') {
$sep = '';
}
// do not add a space after a dot if followed by an identifier
if ($arr[$i]['data'] == '.' && $i < $size - 1 && $arr[$i + 1]['type'] == 'alpha_identifier') {
$sep = '';
}
if ($in_select_expr && $upper_data != 'SELECT' && $upper_data != 'DISTINCT') {
$select_expr_clause .= $arr[$i]['data'] . $sep;
}
if ($in_from && $upper_data != 'FROM') {
$from_clause .= $arr[$i]['data'] . $sep;
}
if ($in_group_by && $upper_data != 'GROUP' && $upper_data != 'BY') {
$group_by_clause .= $arr[$i]['data'] . $sep;
}
if ($in_order_by && $upper_data != 'ORDER' && $upper_data != 'BY') {
// add a space only before ASC or DESC
// not around the dot between dbname and tablename
if ($arr[$i]['type'] == 'alpha_reservedWord') {
$order_by_clause .= $sep;
}
$order_by_clause .= $arr[$i]['data'];
}
if ($in_having && $upper_data != 'HAVING') {
$having_clause .= $arr[$i]['data'] . $sep;
}
if ($in_where && $upper_data != 'WHERE') {
$where_clause .= $arr[$i]['data'] . $sep;
if (($arr[$i]['type'] == 'quote_backtick')
|| ($arr[$i]['type'] == 'alpha_identifier')) {
$where_clause_identifiers[] = $arr[$i]['data'];
}
}
// to grab the rest of the query after the ORDER BY clause
if (isset($subresult['queryflags']['select_from'])
&& $subresult['queryflags']['select_from'] == 1
&& ! $in_order_by
&& $seen_order_by
&& $upper_data != 'BY') {
$unsorted_query .= $arr[$i]['data'];
if ($arr[$i]['type'] != 'punct_bracket_open_round'
&& $arr[$i]['type'] != 'punct_bracket_close_round'
&& $arr[$i]['type'] != 'punct') {
$unsorted_query .= $sep;
}
}
if ($in_limit) {
if ($upper_data == 'OFFSET') {
$limit_clause .= $sep;
}
$limit_clause .= $arr[$i]['data'];
if ($upper_data == 'LIMIT' || $upper_data == 'OFFSET') {
$limit_clause .= $sep;
}
}
if ($after_limit && $seen_limit) {
$section_after_limit .= $arr[$i]['data'] . $sep;
}
// clear $upper_data for next iteration
$upper_data='';
} // end for $i (loop #2)
if (empty($section_before_limit)) {
$section_before_limit = $arr['raw'];
}
// -----------------------------------------------------
// loop #3: foreign keys and MySQL 4.1.2+ TIMESTAMP options
// (for now, check only the first query)
// (for now, identifiers are assumed to be backquoted)
// If we find that we are dealing with a CREATE TABLE query,
// we look for the next punct_bracket_open_round, which
// introduces the fields list. Then, when we find a
// quote_backtick, it must be a field, so we put it into
// the create_table_fields array. Even if this field is
// not a timestamp, it will be useful when logic has been
// added for complete field attributes analysis.
$seen_foreign = FALSE;
$seen_references = FALSE;
$seen_constraint = FALSE;
$foreign_key_number = -1;
$seen_create_table = FALSE;
$seen_create = FALSE;
$in_create_table_fields = FALSE;
$brackets_level = 0;
$in_timestamp_options = FALSE;
$seen_default = FALSE;
for ($i = 0; $i < $size; $i++) {
// DEBUG echo "Loop 3 <b>" . $arr[$i]['data'] . "</b> " . $arr[$i]['type'] . "<br />";
if ($arr[$i]['type'] == 'alpha_reservedWord') {
$upper_data = strtoupper($arr[$i]['data']);
if ($upper_data == 'NOT' && $in_timestamp_options) {
$create_table_fields[$current_identifier]['timestamp_not_null'] = TRUE;
}
if ($upper_data == 'CREATE') {
$seen_create = TRUE;
}
if ($upper_data == 'TABLE' && $seen_create) {
$seen_create_table = TRUE;
$create_table_fields = array();
}
if ($upper_data == 'CURRENT_TIMESTAMP') {
if ($in_timestamp_options) {
if ($seen_default) {
$create_table_fields[$current_identifier]['default_current_timestamp'] = TRUE;
}
}
}
if ($upper_data == 'CONSTRAINT') {
$foreign_key_number++;
$seen_foreign = FALSE;
$seen_references = FALSE;
$seen_constraint = TRUE;
}
if ($upper_data == 'FOREIGN') {
$seen_foreign = TRUE;
$seen_references = FALSE;
$seen_constraint = FALSE;
}
if ($upper_data == 'REFERENCES') {
$seen_foreign = FALSE;
$seen_references = TRUE;
$seen_constraint = FALSE;
}
// Cases covered:
// [ON DELETE {CASCADE | SET NULL | NO ACTION | RESTRICT}]
// [ON UPDATE {CASCADE | SET NULL | NO ACTION | RESTRICT}]
// but we set ['on_delete'] or ['on_cascade'] to
// CASCADE | SET_NULL | NO_ACTION | RESTRICT
// ON UPDATE CURRENT_TIMESTAMP
if ($upper_data == 'ON') {
if (isset($arr[$i+1]) && $arr[$i+1]['type'] == 'alpha_reservedWord') {
$second_upper_data = strtoupper($arr[$i+1]['data']);
if ($second_upper_data == 'DELETE') {
$clause = 'on_delete';
}
if ($second_upper_data == 'UPDATE') {
$clause = 'on_update';
}
if (isset($clause)
&& ($arr[$i+2]['type'] == 'alpha_reservedWord'
// ugly workaround because currently, NO is not
// in the list of reserved words in sqlparser.data
// (we got a bug report about not being able to use
// 'no' as an identifier)
|| ($arr[$i+2]['type'] == 'alpha_identifier'
&& strtoupper($arr[$i+2]['data'])=='NO'))
) {
$third_upper_data = strtoupper($arr[$i+2]['data']);
if ($third_upper_data == 'CASCADE'
|| $third_upper_data == 'RESTRICT') {
$value = $third_upper_data;
} elseif ($third_upper_data == 'SET'
|| $third_upper_data == 'NO') {
if ($arr[$i+3]['type'] == 'alpha_reservedWord') {
$value = $third_upper_data . '_' . strtoupper($arr[$i+3]['data']);
}
} elseif ($third_upper_data == 'CURRENT_TIMESTAMP') {
if ($clause == 'on_update'
&& $in_timestamp_options) {
$create_table_fields[$current_identifier]['on_update_current_timestamp'] = TRUE;
$seen_default = FALSE;
}
} else {
$value = '';
}
if (!empty($value)) {
$foreign[$foreign_key_number][$clause] = $value;
}
unset($clause);
} // endif (isset($clause))
}
}
} // end of reserved words analysis
if ($arr[$i]['type'] == 'punct_bracket_open_round') {
$brackets_level++;
if ($seen_create_table && $brackets_level == 1) {
$in_create_table_fields = TRUE;
}
}
if ($arr[$i]['type'] == 'punct_bracket_close_round') {
$brackets_level--;
if ($seen_references) {
$seen_references = FALSE;
}
if ($seen_create_table && $brackets_level == 0) {
$in_create_table_fields = FALSE;
}
}
if (($arr[$i]['type'] == 'alpha_columnAttrib')) {
$upper_data = strtoupper($arr[$i]['data']);
if ($seen_create_table && $in_create_table_fields) {
if ($upper_data == 'DEFAULT') {
$seen_default = TRUE;
}
}
}
/**
* @see @todo 2005-10-16 note: the "or" part here is a workaround for a bug
*/
if (($arr[$i]['type'] == 'alpha_columnType') || ($arr[$i]['type'] == 'alpha_functionName' && $seen_create_table)) {
$upper_data = strtoupper($arr[$i]['data']);
if ($seen_create_table && $in_create_table_fields && isset($current_identifier)) {
$create_table_fields[$current_identifier]['type'] = $upper_data;
if ($upper_data == 'TIMESTAMP') {
$arr[$i]['type'] = 'alpha_columnType';
$in_timestamp_options = TRUE;
} else {
$in_timestamp_options = FALSE;
if ($upper_data == 'CHAR') {
$arr[$i]['type'] = 'alpha_columnType';
}
}
}
}
if ($arr[$i]['type'] == 'quote_backtick' || $arr[$i]['type'] == 'alpha_identifier') {
if ($arr[$i]['type'] == 'quote_backtick') {
// remove backquotes
$identifier = PMA_unQuote($arr[$i]['data']);
} else {
$identifier = $arr[$i]['data'];
}
if ($seen_create_table && $in_create_table_fields) {
$current_identifier = $identifier;
// warning: we set this one even for non TIMESTAMP type
$create_table_fields[$current_identifier]['timestamp_not_null'] = FALSE;
}
if ($seen_constraint) {
$foreign[$foreign_key_number]['constraint'] = $identifier;
}
if ($seen_foreign && $brackets_level > 0) {
$foreign[$foreign_key_number]['index_list'][] = $identifier;
}
if ($seen_references) {
// here, the first bracket level corresponds to the
// bracket of CREATE TABLE
// so if we are on level 2, it must be the index list
// of the foreign key REFERENCES
if ($brackets_level > 1) {
$foreign[$foreign_key_number]['ref_index_list'][] = $identifier;
} else {
// for MySQL 4.0.18, identifier is
// `table` or `db`.`table`
// the first pass will pick the db name
// the next pass will execute the else and pick the
// db name in $db_table[0]
if ($arr[$i+1]['type'] == 'punct_qualifier') {
$foreign[$foreign_key_number]['ref_db_name'] = $identifier;
} else {
// for MySQL 4.0.16, identifier is
// `table` or `db.table`
$db_table = explode('.', $identifier);
if (isset($db_table[1])) {
$foreign[$foreign_key_number]['ref_db_name'] = $db_table[0];
$foreign[$foreign_key_number]['ref_table_name'] = $db_table[1];
} else {
$foreign[$foreign_key_number]['ref_table_name'] = $db_table[0];
}
}
}
}
}
} // end for $i (loop #3)
// Fill the $subresult array
if (isset($create_table_fields)) {
$subresult['create_table_fields'] = $create_table_fields;
}
if (isset($foreign)) {
$subresult['foreign_keys'] = $foreign;
}
if (isset($select_expr_clause)) {
$subresult['select_expr_clause'] = $select_expr_clause;
}
if (isset($from_clause)) {
$subresult['from_clause'] = $from_clause;
}
if (isset($group_by_clause)) {
$subresult['group_by_clause'] = $group_by_clause;
}
if (isset($order_by_clause)) {
$subresult['order_by_clause'] = $order_by_clause;
}
if (isset($having_clause)) {
$subresult['having_clause'] = $having_clause;
}
if (isset($limit_clause)) {
$subresult['limit_clause'] = $limit_clause;
}
if (isset($where_clause)) {
$subresult['where_clause'] = $where_clause;
}
if (isset($unsorted_query) && !empty($unsorted_query)) {
$subresult['unsorted_query'] = $unsorted_query;
}
if (isset($where_clause_identifiers)) {
$subresult['where_clause_identifiers'] = $where_clause_identifiers;
}
if (isset($position_of_first_select)) {
$subresult['position_of_first_select'] = $position_of_first_select;
$subresult['section_before_limit'] = $section_before_limit;
$subresult['section_after_limit'] = $section_after_limit;
}
// They are naughty and didn't have a trailing semi-colon,
// then still handle it properly
if ($subresult['querytype'] != '') {
$result[] = $subresult;
}
return $result;
} // end of the "PMA_SQP_analyze()" function
/**
* Colorizes SQL queries html formatted
*
* @todo check why adding a "\n" after the </span> would cause extra blanks
* to be displayed: SELECT p . person_name
* @param array The SQL queries html formatted
*
* @return array The colorized SQL queries
*
* @access public
*/
function PMA_SQP_formatHtml_colorize($arr)
{
$i = $GLOBALS['PMA_strpos']($arr['type'], '_');
$class = '';
if ($i > 0) {
$class = 'syntax_' . PMA_substr($arr['type'], 0, $i) . ' ';
}
$class .= 'syntax_' . $arr['type'];
return '<span class="' . $class . '">' . htmlspecialchars($arr['data']) . '</span>';
} // end of the "PMA_SQP_formatHtml_colorize()" function
/**
* Formats SQL queries to html
*
* @param array The SQL queries
* @param string mode
* @param integer starting token
* @param integer number of tokens to format, -1 = all
*
* @return string The formatted SQL queries
*
* @access public
*/
function PMA_SQP_formatHtml($arr, $mode='color', $start_token=0,
$number_of_tokens=-1)
{
//DEBUG echo 'in Format<pre>'; print_r($arr); echo '</pre>';
// then check for an array
if (!is_array($arr)) {
return htmlspecialchars($arr);
}
// first check for the SQL parser having hit an error
if (PMA_SQP_isError()) {
return htmlspecialchars($arr['raw']);
}
// else do it properly
switch ($mode) {
case 'color':
$str = '<span class="syntax">';
$html_line_break = '<br />';
break;
case 'query_only':
$str = '';
$html_line_break = "\n";
break;
case 'text':
$str = '';
$html_line_break = '<br />';
break;
} // end switch
$indent = 0;
$bracketlevel = 0;
$functionlevel = 0;
$infunction = FALSE;
$space_punct_listsep = ' ';
$space_punct_listsep_function_name = ' ';
// $space_alpha_reserved_word = '<br />'."\n";
$space_alpha_reserved_word = ' ';
$keywords_with_brackets_1before = array(
'INDEX',
'KEY',
'ON',
'USING'
);
$keywords_with_brackets_1before_cnt = 4;
$keywords_with_brackets_2before = array(
'IGNORE',
'INDEX',
'INTO',
'KEY',
'PRIMARY',
'PROCEDURE',
'REFERENCES',
'UNIQUE',
'USE'
);
// $keywords_with_brackets_2before_cnt = count($keywords_with_brackets_2before);
$keywords_with_brackets_2before_cnt = 9;
// These reserved words do NOT get a newline placed near them.
$keywords_no_newline = array(
'AS',
'ASC',
'DESC',
'DISTINCT',
'DUPLICATE',
'HOUR',
'INTERVAL',
'IS',
'LIKE',
'NOT',
'NULL',
'ON',
'REGEXP'
);
$keywords_no_newline_cnt = 12;
// These reserved words introduce a privilege list
$keywords_priv_list = array(
'GRANT',
'REVOKE'
);
$keywords_priv_list_cnt = 2;
if ($number_of_tokens == -1) {
$arraysize = $arr['len'];
} else {
$arraysize = $number_of_tokens;
}
$typearr = array();
if ($arraysize >= 0) {
$typearr[0] = '';
$typearr[1] = '';
$typearr[2] = '';
//$typearr[3] = $arr[0]['type'];
$typearr[3] = $arr[$start_token]['type'];
}
$in_priv_list = FALSE;
for ($i = $start_token; $i < $arraysize; $i++) {
// DEBUG echo "Loop format <b>" . $arr[$i]['data'] . "</b> " . $arr[$i]['type'] . "<br />";
$before = '';
$after = '';
$indent = 0;
// array_shift($typearr);
/*
0 prev2
1 prev
2 current
3 next
*/
if (($i + 1) < $arraysize) {
// array_push($typearr, $arr[$i + 1]['type']);
$typearr[4] = $arr[$i + 1]['type'];
} else {
//array_push($typearr, null);
$typearr[4] = '';
}
for ($j=0; $j<4; $j++) {
$typearr[$j] = $typearr[$j + 1];
}
switch ($typearr[2]) {
case 'white_newline':
$before = '';
break;
case 'punct_bracket_open_round':
$bracketlevel++;
$infunction = FALSE;
// Make sure this array is sorted!
if (($typearr[1] == 'alpha_functionName') || ($typearr[1] == 'alpha_columnType') || ($typearr[1] == 'punct')
|| ($typearr[3] == 'digit_integer') || ($typearr[3] == 'digit_hex') || ($typearr[3] == 'digit_float')
|| (($typearr[0] == 'alpha_reservedWord')
&& PMA_STR_binarySearchInArr(strtoupper($arr[$i - 2]['data']), $keywords_with_brackets_2before, $keywords_with_brackets_2before_cnt))
|| (($typearr[1] == 'alpha_reservedWord')
&& PMA_STR_binarySearchInArr(strtoupper($arr[$i - 1]['data']), $keywords_with_brackets_1before, $keywords_with_brackets_1before_cnt))
) {
$functionlevel++;
$infunction = TRUE;
$after .= ' ';
} else {
$indent++;
$after .= ($mode != 'query_only' ? '<div class="syntax_indent' . $indent . '">' : ' ');
}
break;
case 'alpha_identifier':
if (($typearr[1] == 'punct_qualifier') || ($typearr[3] == 'punct_qualifier')) {
$after = '';
$before = '';
}
if (($typearr[3] == 'alpha_columnType') || ($typearr[3] == 'alpha_identifier')) {
$after .= ' ';
}
break;
case 'punct_user':
case 'punct_qualifier':
$before = '';
$after = '';
break;
case 'punct_listsep':
if ($infunction == TRUE) {
$after .= $space_punct_listsep_function_name;
} else {
$after .= $space_punct_listsep;
}
break;
case 'punct_queryend':
if (($typearr[3] != 'comment_mysql') && ($typearr[3] != 'comment_ansi') && $typearr[3] != 'comment_c') {
$after .= $html_line_break;
$after .= $html_line_break;
}
$space_punct_listsep = ' ';
$space_punct_listsep_function_name = ' ';
$space_alpha_reserved_word = ' ';
$in_priv_list = FALSE;
break;
case 'comment_mysql':
case 'comment_ansi':
$after .= $html_line_break;
break;
case 'punct':
$before .= ' ';
// workaround for
// select * from mytable limit 0,-1
// (a side effect of this workaround is that
// select 20 - 9
// becomes
// select 20 -9
// )
if ($typearr[3] != 'digit_integer') {
$after .= ' ';
}
break;
case 'punct_bracket_close_round':
$bracketlevel--;
if ($infunction == TRUE) {
$functionlevel--;
$after .= ' ';
$before .= ' ';
} else {
$indent--;
$before .= ($mode != 'query_only' ? '</div>' : ' ');
}
$infunction = ($functionlevel > 0) ? TRUE : FALSE;
break;
case 'alpha_columnType':
if ($typearr[3] == 'alpha_columnAttrib') {
$after .= ' ';
}
if ($typearr[1] == 'alpha_columnType') {
$before .= ' ';
}
break;
case 'alpha_columnAttrib':
// ALTER TABLE tbl_name AUTO_INCREMENT = 1
// COLLATE LATIN1_GENERAL_CI DEFAULT
if ($typearr[1] == 'alpha_identifier' || $typearr[1] == 'alpha_charset') {
$before .= ' ';
}
if (($typearr[3] == 'alpha_columnAttrib') || ($typearr[3] == 'quote_single') || ($typearr[3] == 'digit_integer')) {
$after .= ' ';
}
// workaround for
// AUTO_INCREMENT = 31DEFAULT_CHARSET = utf-8
if ($typearr[2] == 'alpha_columnAttrib' && $typearr[3] == 'alpha_reservedWord') {
$before .= ' ';
}
// workaround for
// select * from mysql.user where binary user="root"
// binary is marked as alpha_columnAttrib
// but should be marked as a reserved word
if (strtoupper($arr[$i]['data']) == 'BINARY'
&& $typearr[3] == 'alpha_identifier') {
$after .= ' ';
}
break;
case 'alpha_reservedWord':
// do not uppercase the reserved word if we are calling
// this function in query_only mode, because we need
// the original query (otherwise we get problems with
// semi-reserved words like "storage" which is legal
// as an identifier name)
if ($mode != 'query_only') {
$arr[$i]['data'] = strtoupper($arr[$i]['data']);
}
if ((($typearr[1] != 'alpha_reservedWord')
|| (($typearr[1] == 'alpha_reservedWord')
&& PMA_STR_binarySearchInArr(strtoupper($arr[$i - 1]['data']), $keywords_no_newline, $keywords_no_newline_cnt)))
&& ($typearr[1] != 'punct_level_plus')
&& (!PMA_STR_binarySearchInArr($arr[$i]['data'], $keywords_no_newline, $keywords_no_newline_cnt))) {
// do not put a space before the first token, because
// we use a lot of eregi() checking for the first
// reserved word at beginning of query
// so do not put a newline before
//
// also we must not be inside a privilege list
if ($i > 0) {
// the alpha_identifier exception is there to
// catch cases like
// GRANT SELECT ON mydb.mytable TO myuser@localhost
// (else, we get mydb.mytableTO)
//
// the quote_single exception is there to
// catch cases like
// GRANT ... TO 'marc'@'domain.com' IDENTIFIED...
/**
* @todo fix all cases and find why this happens
*/
if (!$in_priv_list || $typearr[1] == 'alpha_identifier' || $typearr[1] == 'quote_single' || $typearr[1] == 'white_newline') {
$before .= $space_alpha_reserved_word;
}
} else {
// on first keyword, check if it introduces a
// privilege list
if (PMA_STR_binarySearchInArr($arr[$i]['data'], $keywords_priv_list, $keywords_priv_list_cnt)) {
$in_priv_list = TRUE;
}
}
} else {
$before .= ' ';
}
switch ($arr[$i]['data']) {
case 'CREATE':
if (!$in_priv_list) {
$space_punct_listsep = $html_line_break;
$space_alpha_reserved_word = ' ';
}
break;
case 'EXPLAIN':
case 'DESCRIBE':
case 'SET':
case 'ALTER':
case 'DELETE':
case 'SHOW':
case 'DROP':
case 'UPDATE':
case 'TRUNCATE':
case 'ANALYZE':
case 'ANALYSE':
if (!$in_priv_list) {
$space_punct_listsep = $html_line_break;
$space_alpha_reserved_word = ' ';
}
break;
case 'INSERT':
case 'REPLACE':
if (!$in_priv_list) {
$space_punct_listsep = $html_line_break;
$space_alpha_reserved_word = $html_line_break;
}
break;
case 'VALUES':
$space_punct_listsep = ' ';
$space_alpha_reserved_word = $html_line_break;
break;
case 'SELECT':
$space_punct_listsep = ' ';
$space_alpha_reserved_word = $html_line_break;
break;
default:
break;
} // end switch ($arr[$i]['data'])
$after .= ' ';
break;
case 'digit_integer':
case 'digit_float':
case 'digit_hex':
/**
* @todo could there be other types preceding a digit?
*/
if ($typearr[1] == 'alpha_reservedWord') {
$after .= ' ';
}
if ($infunction && $typearr[3] == 'punct_bracket_close_round') {
$after .= ' ';
}
if ($typearr[1] == 'alpha_columnAttrib') {
$before .= ' ';
}
break;
case 'alpha_variable':
$after = ' ';
break;
case 'quote_double':
case 'quote_single':
// workaround: for the query
// REVOKE SELECT ON `base2\_db`.* FROM 'user'@'%'
// the @ is incorrectly marked as alpha_variable
// in the parser, and here, the '%' gets a blank before,
// which is a syntax error
if ($typearr[1] != 'punct_user') {
$before .= ' ';
}
if ($infunction && $typearr[3] == 'punct_bracket_close_round') {
$after .= ' ';
}
break;
case 'quote_backtick':
// here we check for punct_user to handle correctly
// DEFINER = `username`@`%`
// where @ is the punct_user and `%` is the quote_backtick
if ($typearr[3] != 'punct_qualifier' && $typearr[3] != 'alpha_variable' && $typearr[3] != 'punct_user') {
$after .= ' ';
}
if ($typearr[1] != 'punct_qualifier' && $typearr[1] != 'alpha_variable' && $typearr[1] != 'punct_user') {
$before .= ' ';
}
break;
default:
break;
} // end switch ($typearr[2])
/*
if ($typearr[3] != 'punct_qualifier') {
$after .= ' ';
}
$after .= "\n";
*/
$str .= $before . ($mode=='color' ? PMA_SQP_formatHTML_colorize($arr[$i]) : $arr[$i]['data']). $after;
} // end for
if ($mode=='color') {
$str .= '</span>';
}
return $str;
} // end of the "PMA_SQP_formatHtml()" function
}
/**
* Builds a CSS rule used for html formatted SQL queries
*
* @param string The class name
* @param string The property name
* @param string The property value
*
* @return string The CSS rule
*
* @access public
*
* @see PMA_SQP_buildCssData()
*/
function PMA_SQP_buildCssRule($classname, $property, $value)
{
$str = '.' . $classname . ' {';
if ($value != '') {
$str .= $property . ': ' . $value . ';';
}
$str .= '}' . "\n";
return $str;
} // end of the "PMA_SQP_buildCssRule()" function
/**
* Builds CSS rules used for html formatted SQL queries
*
* @return string The CSS rules set
*
* @access public
*
* @global array The current PMA configuration
*
* @see PMA_SQP_buildCssRule()
*/
function PMA_SQP_buildCssData()
{
global $cfg;
$css_string = '';
foreach ($cfg['SQP']['fmtColor'] AS $key => $col) {
$css_string .= PMA_SQP_buildCssRule('syntax_' . $key, 'color', $col);
}
for ($i = 0; $i < 8; $i++) {
$css_string .= PMA_SQP_buildCssRule('syntax_indent' . $i, 'margin-left', ($i * $cfg['SQP']['fmtInd']) . $cfg['SQP']['fmtIndUnit']);
}
return $css_string;
} // end of the "PMA_SQP_buildCssData()" function
if (! defined('PMA_MINIMUM_COMMON')) {
/**
* Gets SQL queries with no format
*
* @param array The SQL queries list
*
* @return string The SQL queries with no format
*
* @access public
*/
function PMA_SQP_formatNone($arr)
{
$formatted_sql = htmlspecialchars($arr['raw']);
$formatted_sql = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $formatted_sql);
return $formatted_sql;
} // end of the "PMA_SQP_formatNone()" function
/**
* Gets SQL queries in text format
*
* @todo WRITE THIS!
* @param array The SQL queries list
*
* @return string The SQL queries in text format
*
* @access public
*/
function PMA_SQP_formatText($arr)
{
return PMA_SQP_formatNone($arr);
} // end of the "PMA_SQP_formatText()" function
} // end if: minimal common.lib needed?
?>
|
Pragm4/CS160-JobsBoard-CRLF
|
phpmyadmin/libraries/sqlparser.lib.php
|
PHP
|
gpl-2.0
| 104,361
|
<?php
// traditional chinese Language Module for v2.3 (translated by www.which.tw)
global $_VERSION;
$GLOBALS["charset"] = "utf-8";
$GLOBALS["text_dir"] = "ltr"; // ('ltr' for left to right, 'rtl' for right to left)
$GLOBALS["date_fmt"] = "Y/m/d H:i";
$GLOBALS["error_msg"] = array(
// error
"error" => "錯誤",
"back" => "回上頁",
// root
"home" => "主目錄並不存在, 請檢查設定.",
"abovehome" => "目前的目錄可能沒有在主目錄上.",
"targetabovehome" => "目標的目錄可能沒有在主目錄上.",
// exist
"direxist" => "此目錄不存在.",
//"filedoesexist" => "此目錄已存在.",
"fileexist" => "此檔案不存在.",
"itemdoesexist" => "此項目已存在.",
"itemexist" => "此項目不存在.",
"targetexist" => "這目標目錄不存在.",
"targetdoesexist" => "這目標項目已存在.",
// open
"opendir" => "無法打開目錄.",
"readdir" => "無法讀取目錄.",
// access
"accessdir" => "您不允許存取這個目錄.",
"accessfile" => "您不允許存取這個檔案.",
"accessitem" => "您不允許存取這個項目.",
"accessfunc" => "您不允許使用這個功能.",
"accesstarget" => "您不允許存取這個目標目錄.",
// actions
"permread" => "取得權限失敗.",
"permchange" => "權限更改失敗.",
"openfile" => "打開檔案失敗.",
"savefile" => "檔案儲存失敗.",
"createfile" => "新增檔案失敗.",
"createdir" => "新增目錄失敗.",
"uploadfile" => "檔案上傳失敗.",
"copyitem" => "複製失敗.",
"moveitem" => "移動失敗.",
"delitem" => "刪除失敗.",
"chpass" => "更改密碼失敗.",
"deluser" => "移除使用者失敗.",
"adduser" => "加入使用者失敗.",
"saveuser" => "儲存使用者失敗.",
"searchnothing" => "您必須輸入些什麼來搜尋.",
// misc
"miscnofunc" => "功能無效.",
"miscfilesize" => "檔案大小已達到最大.",
"miscfilepart" => "檔案只有一部分上傳.",
"miscnoname" => "您必須輸入名稱.",
"miscselitems" => "您還未選擇任何項目.",
"miscdelitems" => "您確定要刪除這些 \"+num+\" 項目?",
"miscdeluser" => "您確定要刪除使用者 '\"+user+\"'?",
"miscnopassdiff" => "新密碼跟舊密碼相同.",
"miscnopassmatch" => "密碼不符.",
"miscfieldmissed" => "您遺漏一個重要欄位.",
"miscnouserpass" => "使用者名稱或密碼錯誤.",
"miscselfremove" => "您無法移除您自己.",
"miscuserexist" => "使用者已存在.",
"miscnofinduser" => "無法找到使用者.",
"extract_noarchive" => "此檔案無法執行壓縮.",
"extract_unknowntype" => "未知的壓縮類型"
);
$GLOBALS["messages"] = array(
// links
"permlink" => "更改權限",
"editlink" => "編輯",
"downlink" => "下載",
"uplink" => "上一層",
"homelink" => "主頁",
"reloadlink" => "重新載入",
"copylink" => "複製",
"movelink" => "移動",
"dellink" => "刪除",
"comprlink" => "壓縮",
"adminlink" => "管理員",
"logoutlink" => "登出",
"uploadlink" => "上傳",
"searchlink" => "搜尋",
"extractlink" => "解開壓縮檔",
'chmodlink' => '更改 (chmod) 權限 (Folder/File(s))', // new mic
'mossysinfolink' => $_VERSION->PRODUCT.' 系統資訊 ('.$_VERSION->PRODUCT.', Server, PHP, mySQL)', // new mic
'logolink' => '前往 joomlaXplorer 網站 (另開視窗)', // new mic
// list
"nameheader" => "名稱",
"sizeheader" => "大小",
"typeheader" => "類型",
"modifheader" => "最後更新",
"permheader" => "權限",
"actionheader" => "動作",
"pathheader" => "路徑",
// buttons
"btncancel" => "取消",
"btnsave" => "儲存",
"btnchange" => "更改",
"btnreset" => "重設",
"btnclose" => "關閉",
"btncreate" => "新增",
"btnsearch" => "搜尋",
"btnupload" => "上傳",
"btncopy" => "複製",
"btnmove" => "移動",
"btnlogin" => "登入",
"btnlogout" => "登出",
"btnadd" => "增加",
"btnedit" => "編輯",
"btnremove" => "移除",
// user messages, new in joomlaXplorer 1.3.0
"renamelink" => "重新命名",
"confirm_delete_file" => "您確定要刪除這個檔案? \\n%s",
"success_delete_file" => "物件成功刪除.",
"success_rename_file" => "此目錄/檔案 %s 已成功重新命名為 %s.",
// actions
"actdir" => "目錄",
"actperms" => "更改權限",
"actedit" => "編輯檔案",
"actsearchresults" => "搜尋結果",
"actcopyitems" => "複製項目",
"actcopyfrom" => "從 /%s 複製到 /%s ",
"actmoveitems" => "移動項目",
"actmovefrom" => "從 /%s 移動到 /%s ",
"actlogin" => "登入",
"actloginheader" => "登入以使用 QuiXplorer",
"actadmin" => "管理選單",
"actchpwd" => "更改密碼",
"actusers" => "使用者",
"actarchive" => "壓縮項目",
"actupload" => "上傳檔案",
// misc
"miscitems" => "項目",
"miscfree" => "Free",
"miscusername" => "使用者名稱",
"miscpassword" => "密碼",
"miscoldpass" => "舊密碼",
"miscnewpass" => "新密碼",
"miscconfpass" => "確認密碼",
"miscconfnewpass" => "確認新密碼",
"miscchpass" => "更改密碼",
"mischomedir" => "主頁目錄",
"mischomeurl" => "主頁 URL",
"miscshowhidden" => "顯示隱藏項目",
"mischidepattern" => "隱藏樣式",
"miscperms" => "權限",
"miscuseritems" => "(名稱, 主頁目錄, 顯示隱藏項目, 權限, 啟用)",
"miscadduser" => "增加使用者",
"miscedituser" => "編輯使用者 '%s'",
"miscactive" => "啟用",
"misclang" => "語言",
"miscnoresult" => "無結果可用.",
"miscsubdirs" => "搜尋子目錄",
"miscpermnames" => array("只能瀏覽","修改","更改密碼","修改及更改密碼",
"管理員"),
"miscyesno" => array("是的","否","Y","N"),
"miscchmod" => array("擁有者", "群組", "公開的"),
// from here all new by mic
"miscowner" => "擁有者",
"miscownerdesc" => "<strong>描述:</strong><br />使用者 (UID) /<br />群組 (GID)<br />目前權限:<br /><strong> %s ( %s ) </strong>/<br /><strong> %s ( %s )</strong>",
// sysinfo (new by mic)
"simamsysinfo" => $_VERSION->PRODUCT." 系統資訊",
"sisysteminfo" => "系統資訊",
"sibuilton" => "運行系統",
"sidbversion" => "資料庫版本 (MySQL)",
"siphpversion" => "PHP 版本",
"siphpupdate" => "INFORMATION: The PHP version you use is <strong>not</strong> actual!<br />To guarantee all functions and features of Mambo and addons,<br />you should use as minimum <strong>PHP.Version 4.3</strong>!",
"siwebserver" => "Webserver",
"siwebsphpif" => "網頁伺服器 - PHP 介面",
'simamboversion' => $_VERSION->PRODUCT.' 版本',
"siuseragent" => "瀏覽器版本",
"sirelevantsettings" => "重要的 PHP 設定",
"sisafemode" => "安全模式",
"sibasedir" => "Open basedir",
"sidisplayerrors" => "PHP Errors",
"sishortopentags" => "Short Open Tags",
"sifileuploads" => "檔案上傳",
"simagicquotes" => "Magic Quotes",
"siregglobals" => "Register Globals",
"sioutputbuf" => "Output Buffer",
"sisesssavepath" => "Session Savepath",
"sisessautostart" => "Session auto start",
"sixmlenabled" => "XML 已啟動",
"sizlibenabled" => "ZLIB 已啟動",
"sidisabledfuncs" => "Non enabled functions",
"sieditor" => "WYSIWYG 編輯器",
"siconfigfile" => "Config file",
"siphpinfo" => "PHP Info",
"siphpinformation" => "PHP Information",
"sipermissions" => "權限",
"sidirperms" => "目錄權限",
"sidirpermsmess" => "To be shure that all functions and features of '.$_VERSION->PRODUCT.' are working correct, following folders should have permission to write [chmod 0777]",
"sionoff" => array( "On", "Off" ),
"extract_warning" => "您確定要在此處解壓檔案?\\n如果不小心使用這將會覆蓋已經存在的檔案!",
"extract_success" => "解壓縮成功 ",
"extract_failure" => "解壓縮失敗",
'overwrite_files' => '複蓋已存在的檔案?',
"viewlink" => "檢視",
"actview" => "顯示檔案來源",
// added by Paulino Michelazzo (paulino@michelazzo.com.br) to fun_chmod.php file
'recurse_subdirs' => 'Recurse into subdirectories?',
// added by Paulino Michelazzo (paulino@michelazzo.com.br) to footer.php file
'check_version' => 'Check for latest version',
// added by Paulino Michelazzo (paulino@michelazzo.com.br) to fun_rename.php file
'rename_file' => 'Rename a directory or file...',
'newname' => 'New Name',
// added by Paulino Michelazzo (paulino@michelazzo.com.br) to fun_edit.php file
'returndir' => 'Return to directory after saving?',
'line' => 'Line',
'column' => 'Column',
'wordwrap' => 'Wordwrap: (IE only)',
'copyfile' => 'Copy file into this filename',
// Bookmarks
'quick_jump' => 'Quick Jump To',
'already_bookmarked' => 'This directory is already bookmarked',
'bookmark_was_added' => 'This directory was added to the bookmark list.',
'not_a_bookmark' => 'This directory is not a bookmark.',
'bookmark_was_removed' => 'This directory was removed from the bookmark list.',
'bookmarkfile_not_writable' => "Failed to %s the bookmark.\n The Bookmark File '%s' \nis not writable.",
'lbl_add_bookmark' => 'Add this Directory as Bookmark',
'lbl_remove_bookmark' => 'Remove this Directory from the Bookmark List',
'enter_alias_name' => 'Please enter the alias name for this bookmark',
'normal_compression' => 'normal compression',
'good_compression' => 'good compression',
'best_compression' => 'best compression',
'no_compression' => 'no compression',
'creating_archive' => 'Creating Archive File...',
'processed_x_files' => 'Processed %s of %s Files',
'ftp_header' => 'Local FTP Authentication',
'ftp_login_lbl' => 'Please enter the login credentials for the FTP server',
'ftp_login_name' => 'FTP User Name',
'ftp_login_pass' => 'FTP Password',
'ftp_hostname_port' => 'FTP Server Hostname and Port <br />(Port is optional)',
'ftp_login_check' => 'Checking FTP connection...',
'ftp_connection_failed' => "The FTP server could not be contacted. \nPlease check that the FTP server is running on your server.",
'ftp_login_failed' => "The FTP login failed. Please check the username and password and try again.",
'switch_file_mode' => 'Current mode: <strong>%s</strong>. You could switch to %s mode.',
'symlink_target' => 'Target of the Symbolic Link',
"permchange" => "CHMOD Success:",
"savefile" => "The File was saved.",
"moveitem" => "Moving succeeded.",
"copyitem" => "Copying succeeded.",
'archive_name' => 'Name of the Archive File',
'archive_saveToDir' => 'Save the Archive in this directory',
'editor_simple' => 'Simple Editor Mode',
'editor_syntaxhighlight' => 'Syntax-Highlighted Mode'
);
?>
|
DimaSamodurov/erasvit
|
administrator/components/com_joomlaxplorer/languages/traditional_chinese.php
|
PHP
|
gpl-2.0
| 10,909
|
export declare function enableES5(): void;
//# sourceMappingURL=es5.d.ts.map
|
ENG-SYSTEMS/Kob-Eye
|
Skins/VetoccitanT3/ReactSrc/node_modules/immer/dist/plugins/es5.d.ts
|
TypeScript
|
gpl-2.0
| 76
|
/* World trinity_string */
SET NAMES 'utf8';
DELETE FROM trinity_string WHERE `entry` IN (950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983);
INSERT INTO `trinity_string` VALUES
('950', 'You are jailed by \'%s\' for %u hour(s)!', null, 'Vous tes emprisonn par \'%s\' pour %u heures!', 'Du wurdest von \'%s\' für %u Stunde(n) eingebuchtet!', null, null, null, null, null),
('951', '\'%s\' wrote this as reason: \'%s\'', null, '%s a crit ceci comme tant la raison de votre emprisonnement: %s.', '\'%s\' gab dies als Grund an: \'%s\'', null, null, null, null, null),
('952', '\'%s\' was jailed by you for %u hour(s).', null, 'Vous avez emprisonn %s pour %u heures!', '\'%s\' wurde von dir für %u Stunde(n) eingebuchtet.', null, null, null, null, null),
('953', 'You was released out of the jail by %s.', null, 'Vous avez t liber de la prison par %s.', '\'%s\' hat dich aus dem Knast entlassen.', null, null, null, null, null),
('954', 'You have released %s out of the jail.', null, 'Vous avez liber \'%s\' de la prison.', 'Du hast \'%s\' aus dem Knast geholt.', null, null, null, null, null),
('955', 'No reason given or reason is < %u chars!', null, 'Aucune raison d\\\'emprisonnement donne ou la raison est < %u personnages.', 'Du hast keinen Grund angegeben, oder der Grund ist < %u Zeichen!', null, null, null, null, null),
('956', 'No name given!', null, 'Aucun nom donn!', 'Du hast keinen Namen angegeben!', null, null, null, null, null),
('957', 'No time given!', null, 'Aucun temps donn!', 'Du hast keine Zeit angegeben!', null, null, null, null, null),
('958', 'The jailtime must be between 1 and %u hours!', null, 'Le temps d\\\'emprisonnement est situ entre 1 et %u heures!', 'Die Jail-Zeit muss zwischen 1 und %u Std. liegen!', null, null, null, null, null),
('959', 'The character \'%s\' is not jailed!', null, '\'%s\' n\\\'est pas emprisonn!', 'Der Charakter \'%s\' ist Überhaupt nicht im Knast!', null, null, null, null, null),
('960', 'Command forbidden for jailed characters!', null, 'Commandes interdites pour les personnages emprisons!', 'Sorry, aber das d?rfen Gefangene nicht!', null, null, null, null, null),
('961', 'You have %u hour(s) left in the jail.', null, 'Vous avez %u heures attendre avant de quitter la prison.', 'Du musst noch %u Stunde(n) absitzen.', null, null, null, null, null),
('962', 'You have %u minute(s) left in the jail.', null, 'Vous avez %u minutes attendre avant de quitter la prison.', 'Du musst noch %u Minute(n) absitzen.', null, null, null, null, null),
('963', 'You\'re a free like a bird! ;-)', null, 'Vous tes libre.', 'Du bist frei wie ein Vogel! ;-)', null, null, null, null, null),
('964', '%s was %u times jailed and has %u minute(s) left. Last time jailed by %s. Last reason was: \'%s\'', null, '%s a t librde prison, il avait t emprisonn pour %u et a t libr au aprs %u minutes. Il avait t emprisonn par %s, pour la raison suivante: %s', '\'%s\' war bis jetzt %u mal im Knast, und hat noch %u Minute(n) abzusitzen.\n Zuletzt eingebuchtet von: \'%s\'\nLetzter Grund: %s', null, null, null, null, null),
('965', '\'%s\' was never jailed.', null, '\'%s\' n\\\'a jamais t emprisonn.', '\'%s\' hat eine weiße Weste.', null, null, null, null, null),
('966', 'You can\'t jail yourself!', null, 'Vous ne pouvez pas vous emprisonner vous-m me!', 'Du kannst dich nicht selber einbuchten!', null, null, null, null, null),
('967', 'You can\'t unjail yourself!', null, 'Vous ne pouvez pas vous librer vous m me!', 'So weit kommt es noch, daß Knastbruder sich selber befreien! :-(', null, null, null, null, null),
('968', '|cffff0000[!!! ATTENTION - IMPORTANT - WARNING !!!\r\n You were already %u times in prison. If you are in Jail for a total of %u times, your character will be deleted\r\n|cffff0000!!! ATTENTION - IMPORTANT - WARNING !!!]', null, '|cffff0000[!!!ATTENTION - ATTENTION - ATTENTION!!!\r\n Vous étiez déjà %u fois en prison en %u fois, votre personnage supprimé\r\n|cffff0000!!! ATTENTION - ATTENTION - ATTENTION !!!]', '|cffff0000[!!! ACHTUNG - WICHTIG - WARNUNG !!!\r\n Du warst schon %u mal in Knast beim %u mal wird dein Charakter gelöscht\r\n|cffff0000!!! ACHTUNG - WICHTIG - WARNUNG !!!]', null, null, null, null, null),
('969', 'The character \'', null, 'Le personnage ', 'Der Charakter \'', null, null, null, null, null),
('970', '\' was jailed for ', null, ' a t emprisonn pour ', '\' wurde für ', null, null, null, null, null),
('971', ' hour(s) by the GM character \'', null, ' heure(s) par le MJ ', ' Stunde(n) von dem GM-Charakter \'', null, null, null, null, null),
('972', '\'. The reason is: ', null, '. La raison est: ', '\' eingebuchtet. Der Grund ist: ', null, null, null, null, null),
('973', 'The jail configuration was reloaded.', null, 'La configuration de jail a t recharge.', 'Die Gefängnis-Konfiguration wurde neu geladen.', null, null, null, null, null),
('974', '>> Trinity Jail config loaded.', null, '>> Configuration du jail charge.', '>> Gefängnis-Konfiguration geladen.', null, null, null, null, null),
('975', 'Can\'t load jail config! Table empty or missed! Use characters_jail.sql!', null, 'Impossible de charger la configuration du jail! Table vide ou innexistante! Appliquez characters_jail.sql!', 'Fehler beim laden der Gef?ngnis-Konfiguration! Der Table \'jail_conf\' ist leer oder nicht vorhanden! Nutze die \'characters_jail.sql\'!', null, null, null, null, null),
('976', 'Set all jail config settings to default...', null, 'Placez tous les param tres de configuration de prison par d faut.', 'Setze die Konfiguration des Gef?ngnisses auf Standardwerte...', null, null, null, null, null),
('977', 'The Character \'%s\' is jailed and teleportet into the jail.', null, 'Le personnage \'%s\' est emprisonn et t leport dans la prison.', 'Der Charakter \'%s\' ist ein Knastbruder und wird in den Knast teleportiert.', null, null, null, null, null),
('978', 'The Character \'%s\' was released out of the jail.', null, 'Le personnage %s est liber de prison.', 'Der Charakter \'%s\' wurde aus dem Knast entlassen.', null, null, null, null, null),
('979', 'A character with this name doesn\'t exists!', null, 'Il n\'y a aucun personnage portant ce nom.', 'Ein Charakter mit diesem Namen gibt es nicht!', null, null, null, null, null),
('980', '|cffff0000[!!! ATTENTION - IMPORTANT - WARNING !!!\r\n You were already %u times in prison. If you are in Jail for a total of %u times, your account will be banned!\r\n|cffff0000!!! ATTENTION - IMPORTANT - WARNING !!!]', null, '|cffff0000[!!!ATTENTION - ATTENTION - ATTENTION!!!\r\n Vous avez %u fois en prison en %u fois votre compte sera banni\r\n|cffff0000!!! ATTENTION - ATTENTION - ATTENTION !!!]', '|cffff0000[!!! ACHTUNG - WICHTIG - WARNUNG !!!\r\n Du hast %u mal in Knast beim %u mal wird dein Account gebannt\r\n|cffff0000!!! ACHTUNG - WICHTIG - WARNUNG !!!]', null, null, null, null, null),
('981', 'Max. jailtimes reached!', null, 'Nombre maximum d\'Jails atteint!', 'Maximale Anzahl an Jails erreicht!', null, null, null, null, null),
('982', 'Robotron', null, 'Robotron', 'Robotron', null, null, null, null, null),
('983', 'Your Jail status was reset to 0 ', null, 'Votre statut a été Jail à 0 ', 'Dein Jail status wurde auf 0 zurück gesatzt', null, null, null, null, null);
|
mynew/FunCore
|
sql/updates/updates/world_trinity_string.sql
|
SQL
|
gpl-2.0
| 7,402
|
#ifndef _HIDDEV_H
#define _HIDDEV_H
/*
* $Id: hiddev.h,v 1.1.1.1 2007/06/12 07:27:16 eyryu Exp $
*
* Copyright (c) 1999-2000 Vojtech Pavlik
*
* Sponsored by SuSE
*/
/*
* 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
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@suse.cz>, or by paper mail:
* Vojtech Pavlik, Ucitelska 1576, Prague 8, 182 00 Czech Republic
*/
/*
* The event structure itself
*/
struct hiddev_event {
unsigned hid;
signed int value;
};
struct hiddev_devinfo {
__u32 bustype;
__u32 busnum;
__u32 devnum;
__u32 ifnum;
__s16 vendor;
__s16 product;
__s16 version;
__u32 num_applications;
};
struct hiddev_collection_info {
__u32 index;
__u32 type;
__u32 usage;
__u32 level;
};
#define HID_STRING_SIZE 256
struct hiddev_string_descriptor {
__s32 index;
char value[HID_STRING_SIZE];
};
struct hiddev_report_info {
__u32 report_type;
__u32 report_id;
__u32 num_fields;
};
/* To do a GUSAGE/SUSAGE, fill in at least usage_code, report_type and
* report_id. Set report_id to REPORT_ID_UNKNOWN if the rest of the fields
* are unknown. Otherwise use a usage_ref struct filled in from a previous
* successful GUSAGE call to save time. To actually send a value to the
* device, perform a SUSAGE first, followed by a SREPORT. An INITREPORT or a
* GREPORT isn't necessary for a GUSAGE to return valid data.
*/
#define HID_REPORT_ID_UNKNOWN 0xffffffff
#define HID_REPORT_ID_FIRST 0x00000100
#define HID_REPORT_ID_NEXT 0x00000200
#define HID_REPORT_ID_MASK 0x000000ff
#define HID_REPORT_ID_MAX 0x000000ff
#define HID_REPORT_TYPE_INPUT 1
#define HID_REPORT_TYPE_OUTPUT 2
#define HID_REPORT_TYPE_FEATURE 3
#define HID_REPORT_TYPE_MIN 1
#define HID_REPORT_TYPE_MAX 3
struct hiddev_field_info {
__u32 report_type;
__u32 report_id;
__u32 field_index;
__u32 maxusage;
__u32 flags;
__u32 physical; /* physical usage for this field */
__u32 logical; /* logical usage for this field */
__u32 application; /* application usage for this field */
__s32 logical_minimum;
__s32 logical_maximum;
__s32 physical_minimum;
__s32 physical_maximum;
__u32 unit_exponent;
__u32 unit;
};
/* Fill in report_type, report_id and field_index to get the information on a
* field.
*/
#define HID_FIELD_CONSTANT 0x001
#define HID_FIELD_VARIABLE 0x002
#define HID_FIELD_RELATIVE 0x004
#define HID_FIELD_WRAP 0x008
#define HID_FIELD_NONLINEAR 0x010
#define HID_FIELD_NO_PREFERRED 0x020
#define HID_FIELD_NULL_STATE 0x040
#define HID_FIELD_VOLATILE 0x080
#define HID_FIELD_BUFFERED_BYTE 0x100
struct hiddev_usage_ref {
__u32 report_type;
__u32 report_id;
__u32 field_index;
__u32 usage_index;
__u32 usage_code;
__s32 value;
};
/* hiddev_usage_ref_multi is used for sending multiple bytes to a control.
* It really manifests itself as setting the value of consecutive usages */
#define HID_MAX_MULTI_USAGES 1024
struct hiddev_usage_ref_multi {
struct hiddev_usage_ref uref;
__u32 num_values;
__s32 values[HID_MAX_MULTI_USAGES];
};
/* FIELD_INDEX_NONE is returned in read() data from the kernel when flags
* is set to (HIDDEV_FLAG_UREF | HIDDEV_FLAG_REPORT) and a new report has
* been sent by the device
*/
#define HID_FIELD_INDEX_NONE 0xffffffff
/*
* Protocol version.
*/
#define HID_VERSION 0x010004
/*
* IOCTLs (0x00 - 0x7f)
*/
#define HIDIOCGVERSION _IOR('H', 0x01, int)
#define HIDIOCAPPLICATION _IO('H', 0x02)
#define HIDIOCGDEVINFO _IOR('H', 0x03, struct hiddev_devinfo)
#define HIDIOCGSTRING _IOR('H', 0x04, struct hiddev_string_descriptor)
#define HIDIOCINITREPORT _IO('H', 0x05)
#define HIDIOCGNAME(len) _IOC(_IOC_READ, 'H', 0x06, len)
#define HIDIOCGREPORT _IOW('H', 0x07, struct hiddev_report_info)
#define HIDIOCSREPORT _IOW('H', 0x08, struct hiddev_report_info)
#define HIDIOCGREPORTINFO _IOWR('H', 0x09, struct hiddev_report_info)
#define HIDIOCGFIELDINFO _IOWR('H', 0x0A, struct hiddev_field_info)
#define HIDIOCGUSAGE _IOWR('H', 0x0B, struct hiddev_usage_ref)
#define HIDIOCSUSAGE _IOW('H', 0x0C, struct hiddev_usage_ref)
#define HIDIOCGUCODE _IOWR('H', 0x0D, struct hiddev_usage_ref)
#define HIDIOCGFLAG _IOR('H', 0x0E, int)
#define HIDIOCSFLAG _IOW('H', 0x0F, int)
#define HIDIOCGCOLLECTIONINDEX _IOW('H', 0x10, struct hiddev_usage_ref)
#define HIDIOCGCOLLECTIONINFO _IOWR('H', 0x11, struct hiddev_collection_info)
#define HIDIOCGPHYS(len) _IOC(_IOC_READ, 'H', 0x12, len)
/* For writing/reading to multiple/consecutive usages */
#define HIDIOCGUSAGES _IOWR('H', 0x13, struct hiddev_usage_ref_multi)
#define HIDIOCSUSAGES _IOW('H', 0x14, struct hiddev_usage_ref_multi)
/*
* Flags to be used in HIDIOCSFLAG
*/
#define HIDDEV_FLAG_UREF 0x1
#define HIDDEV_FLAG_REPORT 0x2
#define HIDDEV_FLAGS 0x3
/* To traverse the input report descriptor info for a HID device, perform the
* following:
*
* rinfo.report_type = HID_REPORT_TYPE_INPUT;
* rinfo.report_id = HID_REPORT_ID_FIRST;
* ret = ioctl(fd, HIDIOCGREPORTINFO, &rinfo);
*
* while (ret >= 0) {
* for (i = 0; i < rinfo.num_fields; i++) {
* finfo.report_type = rinfo.report_type;
* finfo.report_id = rinfo.report_id;
* finfo.field_index = i;
* ioctl(fd, HIDIOCGFIELDINFO, &finfo);
* for (j = 0; j < finfo.maxusage; j++) {
* uref.field_index = i;
* uref.usage_index = j;
* ioctl(fd, HIDIOCGUCODE, &uref);
* ioctl(fd, HIDIOCGUSAGE, &uref);
* }
* }
* rinfo.report_id |= HID_REPORT_ID_NEXT;
* ret = ioctl(fd, HIDIOCGREPORTINFO, &rinfo);
* }
*/
#ifdef __KERNEL__
/*
* In-kernel definitions.
*/
struct hid_device;
struct hid_usage;
struct hid_field;
struct hid_report;
#ifdef CONFIG_USB_HIDDEV
int hiddev_connect(struct hid_device *);
void hiddev_disconnect(struct hid_device *);
void hiddev_hid_event(struct hid_device *hid, struct hid_field *field,
struct hid_usage *usage, __s32 value);
void hiddev_report_event(struct hid_device *hid, struct hid_report *report);
int __init hiddev_init(void);
void hiddev_exit(void);
#else
static inline int hiddev_connect(struct hid_device *hid) { return -1; }
static inline void hiddev_disconnect(struct hid_device *hid) { }
static inline void hiddev_hid_event(struct hid_device *hid, struct hid_field *field,
struct hid_usage *usage, __s32 value) { }
static inline void hiddev_report_event(struct hid_device *hid, struct hid_report *report) { }
static inline int hiddev_init(void) { return 0; }
static inline void hiddev_exit(void) { }
#endif
#endif
#endif
|
sdwuyawen/linux2.6.21_helper2416
|
include/linux/hiddev.h
|
C
|
gpl-2.0
| 7,231
|
/*
* ARM NEON vector operations.
*
* Copyright (c) 2007, 2008 CodeSourcery.
* Written by Paul Brook
*
* This code is licensed under the GNU GPL v2.
*/
#include <stdlib.h>
#include <stdio.h>
#include "cpu.h"
#include "exec/exec-all.h"
#include "exec/helper-proto.h"
#define SIGNBIT (uint32_t)0x80000000
#define SIGNBIT64 ((uint64_t)1 << 63)
#define SET_QC() env->vfp.xregs[ARM_VFP_FPSCR] |= CPSR_Q
#define NEON_TYPE1(name, type) \
typedef struct \
{ \
type v1; \
} neon_##name;
#ifdef HOST_WORDS_BIGENDIAN
#define NEON_TYPE2(name, type) \
typedef struct \
{ \
type v2; \
type v1; \
} neon_##name;
#define NEON_TYPE4(name, type) \
typedef struct \
{ \
type v4; \
type v3; \
type v2; \
type v1; \
} neon_##name;
#else
#define NEON_TYPE2(name, type) \
typedef struct \
{ \
type v1; \
type v2; \
} neon_##name;
#define NEON_TYPE4(name, type) \
typedef struct \
{ \
type v1; \
type v2; \
type v3; \
type v4; \
} neon_##name;
#endif
NEON_TYPE4(s8, int8_t)
NEON_TYPE4(u8, uint8_t)
NEON_TYPE2(s16, int16_t)
NEON_TYPE2(u16, uint16_t)
NEON_TYPE1(s32, int32_t)
NEON_TYPE1(u32, uint32_t)
#undef NEON_TYPE4
#undef NEON_TYPE2
#undef NEON_TYPE1
/* Copy from a uint32_t to a vector structure type. */
#define NEON_UNPACK(vtype, dest, val) do { \
union { \
vtype v; \
uint32_t i; \
} conv_u; \
conv_u.i = (val); \
dest = conv_u.v; \
} while(0)
/* Copy from a vector structure type to a uint32_t. */
#define NEON_PACK(vtype, dest, val) do { \
union { \
vtype v; \
uint32_t i; \
} conv_u; \
conv_u.v = (val); \
dest = conv_u.i; \
} while(0)
#define NEON_DO1 \
NEON_FN(vdest.v1, vsrc1.v1, vsrc2.v1);
#define NEON_DO2 \
NEON_FN(vdest.v1, vsrc1.v1, vsrc2.v1); \
NEON_FN(vdest.v2, vsrc1.v2, vsrc2.v2);
#define NEON_DO4 \
NEON_FN(vdest.v1, vsrc1.v1, vsrc2.v1); \
NEON_FN(vdest.v2, vsrc1.v2, vsrc2.v2); \
NEON_FN(vdest.v3, vsrc1.v3, vsrc2.v3); \
NEON_FN(vdest.v4, vsrc1.v4, vsrc2.v4);
#define NEON_VOP_BODY(vtype, n) \
{ \
uint32_t res; \
vtype vsrc1; \
vtype vsrc2; \
vtype vdest; \
NEON_UNPACK(vtype, vsrc1, arg1); \
NEON_UNPACK(vtype, vsrc2, arg2); \
NEON_DO##n; \
NEON_PACK(vtype, res, vdest); \
return res; \
}
#define NEON_VOP(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(uint32_t arg1, uint32_t arg2) \
NEON_VOP_BODY(vtype, n)
#define NEON_VOP_ENV(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(CPUARMState *env, uint32_t arg1, uint32_t arg2) \
NEON_VOP_BODY(vtype, n)
/* Pairwise operations. */
/* For 32-bit elements each segment only contains a single element, so
the elementwise and pairwise operations are the same. */
#define NEON_PDO2 \
NEON_FN(vdest.v1, vsrc1.v1, vsrc1.v2); \
NEON_FN(vdest.v2, vsrc2.v1, vsrc2.v2);
#define NEON_PDO4 \
NEON_FN(vdest.v1, vsrc1.v1, vsrc1.v2); \
NEON_FN(vdest.v2, vsrc1.v3, vsrc1.v4); \
NEON_FN(vdest.v3, vsrc2.v1, vsrc2.v2); \
NEON_FN(vdest.v4, vsrc2.v3, vsrc2.v4); \
#define NEON_POP(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(uint32_t arg1, uint32_t arg2) \
{ \
uint32_t res; \
vtype vsrc1; \
vtype vsrc2; \
vtype vdest; \
NEON_UNPACK(vtype, vsrc1, arg1); \
NEON_UNPACK(vtype, vsrc2, arg2); \
NEON_PDO##n; \
NEON_PACK(vtype, res, vdest); \
return res; \
}
/* Unary operators. */
#define NEON_VOP1(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(uint32_t arg) \
{ \
vtype vsrc1; \
vtype vdest; \
NEON_UNPACK(vtype, vsrc1, arg); \
NEON_DO##n; \
NEON_PACK(vtype, arg, vdest); \
return arg; \
}
#define NEON_USAT(dest, src1, src2, type) do { \
uint32_t tmp = (uint32_t)src1 + (uint32_t)src2; \
if (tmp != (type)tmp) { \
SET_QC(); \
dest = ~0; \
} else { \
dest = tmp; \
}} while(0)
#define NEON_FN(dest, src1, src2) NEON_USAT(dest, src1, src2, uint8_t)
NEON_VOP_ENV(qadd_u8, neon_u8, 4)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_USAT(dest, src1, src2, uint16_t)
NEON_VOP_ENV(qadd_u16, neon_u16, 2)
#undef NEON_FN
#undef NEON_USAT
uint32_t HELPER(neon_qadd_u32)(CPUARMState *env, uint32_t a, uint32_t b)
{
uint32_t res = a + b;
if (res < a) {
SET_QC();
res = ~0;
}
return res;
}
uint64_t HELPER(neon_qadd_u64)(CPUARMState *env, uint64_t src1, uint64_t src2)
{
uint64_t res;
res = src1 + src2;
if (res < src1) {
SET_QC();
res = ~(uint64_t)0;
}
return res;
}
#define NEON_SSAT(dest, src1, src2, type) do { \
int32_t tmp = (uint32_t)src1 + (uint32_t)src2; \
if (tmp != (type)tmp) { \
SET_QC(); \
if (src2 > 0) { \
tmp = (1 << (sizeof(type) * 8 - 1)) - 1; \
} else { \
tmp = 1 << (sizeof(type) * 8 - 1); \
} \
} \
dest = tmp; \
} while(0)
#define NEON_FN(dest, src1, src2) NEON_SSAT(dest, src1, src2, int8_t)
NEON_VOP_ENV(qadd_s8, neon_s8, 4)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_SSAT(dest, src1, src2, int16_t)
NEON_VOP_ENV(qadd_s16, neon_s16, 2)
#undef NEON_FN
#undef NEON_SSAT
uint32_t HELPER(neon_qadd_s32)(CPUARMState *env, uint32_t a, uint32_t b)
{
uint32_t res = a + b;
if (((res ^ a) & SIGNBIT) && !((a ^ b) & SIGNBIT)) {
SET_QC();
res = ~(((int32_t)a >> 31) ^ SIGNBIT);
}
return res;
}
uint64_t HELPER(neon_qadd_s64)(CPUARMState *env, uint64_t src1, uint64_t src2)
{
uint64_t res;
res = src1 + src2;
if (((res ^ src1) & SIGNBIT64) && !((src1 ^ src2) & SIGNBIT64)) {
SET_QC();
res = ((int64_t)src1 >> 63) ^ ~SIGNBIT64;
}
return res;
}
/* Unsigned saturating accumulate of signed value
*
* Op1/Rn is treated as signed
* Op2/Rd is treated as unsigned
*
* Explicit casting is used to ensure the correct sign extension of
* inputs. The result is treated as a unsigned value and saturated as such.
*
* We use a macro for the 8/16 bit cases which expects signed integers of va,
* vb, and vr for interim calculation and an unsigned 32 bit result value r.
*/
#define USATACC(bits, shift) \
do { \
va = sextract32(a, shift, bits); \
vb = extract32(b, shift, bits); \
vr = va + vb; \
if (vr > UINT##bits##_MAX) { \
SET_QC(); \
vr = UINT##bits##_MAX; \
} else if (vr < 0) { \
SET_QC(); \
vr = 0; \
} \
r = deposit32(r, shift, bits, vr); \
} while (0)
uint32_t HELPER(neon_uqadd_s8)(CPUARMState *env, uint32_t a, uint32_t b)
{
int16_t va, vb, vr;
uint32_t r = 0;
USATACC(8, 0);
USATACC(8, 8);
USATACC(8, 16);
USATACC(8, 24);
return r;
}
uint32_t HELPER(neon_uqadd_s16)(CPUARMState *env, uint32_t a, uint32_t b)
{
int32_t va, vb, vr;
uint64_t r = 0;
USATACC(16, 0);
USATACC(16, 16);
return r;
}
#undef USATACC
uint32_t HELPER(neon_uqadd_s32)(CPUARMState *env, uint32_t a, uint32_t b)
{
int64_t va = (int32_t)a;
int64_t vb = (uint32_t)b;
int64_t vr = va + vb;
if (vr > UINT32_MAX) {
SET_QC();
vr = UINT32_MAX;
} else if (vr < 0) {
SET_QC();
vr = 0;
}
return vr;
}
uint64_t HELPER(neon_uqadd_s64)(CPUARMState *env, uint64_t a, uint64_t b)
{
uint64_t res;
res = a + b;
/* We only need to look at the pattern of SIGN bits to detect
* +ve/-ve saturation
*/
if (~a & b & ~res & SIGNBIT64) {
SET_QC();
res = UINT64_MAX;
} else if (a & ~b & res & SIGNBIT64) {
SET_QC();
res = 0;
}
return res;
}
/* Signed saturating accumulate of unsigned value
*
* Op1/Rn is treated as unsigned
* Op2/Rd is treated as signed
*
* The result is treated as a signed value and saturated as such
*
* We use a macro for the 8/16 bit cases which expects signed integers of va,
* vb, and vr for interim calculation and an unsigned 32 bit result value r.
*/
#define SSATACC(bits, shift) \
do { \
va = extract32(a, shift, bits); \
vb = sextract32(b, shift, bits); \
vr = va + vb; \
if (vr > INT##bits##_MAX) { \
SET_QC(); \
vr = INT##bits##_MAX; \
} else if (vr < INT##bits##_MIN) { \
SET_QC(); \
vr = INT##bits##_MIN; \
} \
r = deposit32(r, shift, bits, vr); \
} while (0)
uint32_t HELPER(neon_sqadd_u8)(CPUARMState *env, uint32_t a, uint32_t b)
{
int16_t va, vb, vr;
uint32_t r = 0;
SSATACC(8, 0);
SSATACC(8, 8);
SSATACC(8, 16);
SSATACC(8, 24);
return r;
}
uint32_t HELPER(neon_sqadd_u16)(CPUARMState *env, uint32_t a, uint32_t b)
{
int32_t va, vb, vr;
uint32_t r = 0;
SSATACC(16, 0);
SSATACC(16, 16);
return r;
}
#undef SSATACC
uint32_t HELPER(neon_sqadd_u32)(CPUARMState *env, uint32_t a, uint32_t b)
{
int64_t res;
int64_t op1 = (uint32_t)a;
int64_t op2 = (int32_t)b;
res = op1 + op2;
if (res > INT32_MAX) {
SET_QC();
res = INT32_MAX;
} else if (res < INT32_MIN) {
SET_QC();
res = INT32_MIN;
}
return res;
}
uint64_t HELPER(neon_sqadd_u64)(CPUARMState *env, uint64_t a, uint64_t b)
{
uint64_t res;
res = a + b;
/* We only need to look at the pattern of SIGN bits to detect an overflow */
if (((a & res)
| (~b & res)
| (a & ~b)) & SIGNBIT64) {
SET_QC();
res = INT64_MAX;
}
return res;
}
#define NEON_USAT(dest, src1, src2, type) do { \
uint32_t tmp = (uint32_t)src1 - (uint32_t)src2; \
if (tmp != (type)tmp) { \
SET_QC(); \
dest = 0; \
} else { \
dest = tmp; \
}} while(0)
#define NEON_FN(dest, src1, src2) NEON_USAT(dest, src1, src2, uint8_t)
NEON_VOP_ENV(qsub_u8, neon_u8, 4)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_USAT(dest, src1, src2, uint16_t)
NEON_VOP_ENV(qsub_u16, neon_u16, 2)
#undef NEON_FN
#undef NEON_USAT
uint32_t HELPER(neon_qsub_u32)(CPUARMState *env, uint32_t a, uint32_t b)
{
uint32_t res = a - b;
if (res > a) {
SET_QC();
res = 0;
}
return res;
}
uint64_t HELPER(neon_qsub_u64)(CPUARMState *env, uint64_t src1, uint64_t src2)
{
uint64_t res;
if (src1 < src2) {
SET_QC();
res = 0;
} else {
res = src1 - src2;
}
return res;
}
#define NEON_SSAT(dest, src1, src2, type) do { \
int32_t tmp = (uint32_t)src1 - (uint32_t)src2; \
if (tmp != (type)tmp) { \
SET_QC(); \
if (src2 < 0) { \
tmp = (1 << (sizeof(type) * 8 - 1)) - 1; \
} else { \
tmp = 1 << (sizeof(type) * 8 - 1); \
} \
} \
dest = tmp; \
} while(0)
#define NEON_FN(dest, src1, src2) NEON_SSAT(dest, src1, src2, int8_t)
NEON_VOP_ENV(qsub_s8, neon_s8, 4)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_SSAT(dest, src1, src2, int16_t)
NEON_VOP_ENV(qsub_s16, neon_s16, 2)
#undef NEON_FN
#undef NEON_SSAT
uint32_t HELPER(neon_qsub_s32)(CPUARMState *env, uint32_t a, uint32_t b)
{
uint32_t res = a - b;
if (((res ^ a) & SIGNBIT) && ((a ^ b) & SIGNBIT)) {
SET_QC();
res = ~(((int32_t)a >> 31) ^ SIGNBIT);
}
return res;
}
uint64_t HELPER(neon_qsub_s64)(CPUARMState *env, uint64_t src1, uint64_t src2)
{
uint64_t res;
res = src1 - src2;
if (((res ^ src1) & SIGNBIT64) && ((src1 ^ src2) & SIGNBIT64)) {
SET_QC();
res = ((int64_t)src1 >> 63) ^ ~SIGNBIT64;
}
return res;
}
#define NEON_FN(dest, src1, src2) dest = (src1 + src2) >> 1
NEON_VOP(hadd_s8, neon_s8, 4)
NEON_VOP(hadd_u8, neon_u8, 4)
NEON_VOP(hadd_s16, neon_s16, 2)
NEON_VOP(hadd_u16, neon_u16, 2)
#undef NEON_FN
int32_t HELPER(neon_hadd_s32)(int32_t src1, int32_t src2)
{
int32_t dest;
dest = (src1 >> 1) + (src2 >> 1);
if (src1 & src2 & 1)
dest++;
return dest;
}
uint32_t HELPER(neon_hadd_u32)(uint32_t src1, uint32_t src2)
{
uint32_t dest;
dest = (src1 >> 1) + (src2 >> 1);
if (src1 & src2 & 1)
dest++;
return dest;
}
#define NEON_FN(dest, src1, src2) dest = (src1 + src2 + 1) >> 1
NEON_VOP(rhadd_s8, neon_s8, 4)
NEON_VOP(rhadd_u8, neon_u8, 4)
NEON_VOP(rhadd_s16, neon_s16, 2)
NEON_VOP(rhadd_u16, neon_u16, 2)
#undef NEON_FN
int32_t HELPER(neon_rhadd_s32)(int32_t src1, int32_t src2)
{
int32_t dest;
dest = (src1 >> 1) + (src2 >> 1);
if ((src1 | src2) & 1)
dest++;
return dest;
}
uint32_t HELPER(neon_rhadd_u32)(uint32_t src1, uint32_t src2)
{
uint32_t dest;
dest = (src1 >> 1) + (src2 >> 1);
if ((src1 | src2) & 1)
dest++;
return dest;
}
#define NEON_FN(dest, src1, src2) dest = (src1 - src2) >> 1
NEON_VOP(hsub_s8, neon_s8, 4)
NEON_VOP(hsub_u8, neon_u8, 4)
NEON_VOP(hsub_s16, neon_s16, 2)
NEON_VOP(hsub_u16, neon_u16, 2)
#undef NEON_FN
int32_t HELPER(neon_hsub_s32)(int32_t src1, int32_t src2)
{
int32_t dest;
dest = (src1 >> 1) - (src2 >> 1);
if ((~src1) & src2 & 1)
dest--;
return dest;
}
uint32_t HELPER(neon_hsub_u32)(uint32_t src1, uint32_t src2)
{
uint32_t dest;
dest = (src1 >> 1) - (src2 >> 1);
if ((~src1) & src2 & 1)
dest--;
return dest;
}
#define NEON_FN(dest, src1, src2) dest = (src1 > src2) ? ~0 : 0
NEON_VOP(cgt_s8, neon_s8, 4)
NEON_VOP(cgt_u8, neon_u8, 4)
NEON_VOP(cgt_s16, neon_s16, 2)
NEON_VOP(cgt_u16, neon_u16, 2)
NEON_VOP(cgt_s32, neon_s32, 1)
NEON_VOP(cgt_u32, neon_u32, 1)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) dest = (src1 >= src2) ? ~0 : 0
NEON_VOP(cge_s8, neon_s8, 4)
NEON_VOP(cge_u8, neon_u8, 4)
NEON_VOP(cge_s16, neon_s16, 2)
NEON_VOP(cge_u16, neon_u16, 2)
NEON_VOP(cge_s32, neon_s32, 1)
NEON_VOP(cge_u32, neon_u32, 1)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) dest = (src1 < src2) ? src1 : src2
NEON_VOP(min_s8, neon_s8, 4)
NEON_VOP(min_u8, neon_u8, 4)
NEON_VOP(min_s16, neon_s16, 2)
NEON_VOP(min_u16, neon_u16, 2)
NEON_VOP(min_s32, neon_s32, 1)
NEON_VOP(min_u32, neon_u32, 1)
NEON_POP(pmin_s8, neon_s8, 4)
NEON_POP(pmin_u8, neon_u8, 4)
NEON_POP(pmin_s16, neon_s16, 2)
NEON_POP(pmin_u16, neon_u16, 2)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) dest = (src1 > src2) ? src1 : src2
NEON_VOP(max_s8, neon_s8, 4)
NEON_VOP(max_u8, neon_u8, 4)
NEON_VOP(max_s16, neon_s16, 2)
NEON_VOP(max_u16, neon_u16, 2)
NEON_VOP(max_s32, neon_s32, 1)
NEON_VOP(max_u32, neon_u32, 1)
NEON_POP(pmax_s8, neon_s8, 4)
NEON_POP(pmax_u8, neon_u8, 4)
NEON_POP(pmax_s16, neon_s16, 2)
NEON_POP(pmax_u16, neon_u16, 2)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) \
dest = (src1 > src2) ? (src1 - src2) : (src2 - src1)
NEON_VOP(abd_s8, neon_s8, 4)
NEON_VOP(abd_u8, neon_u8, 4)
NEON_VOP(abd_s16, neon_s16, 2)
NEON_VOP(abd_u16, neon_u16, 2)
NEON_VOP(abd_s32, neon_s32, 1)
NEON_VOP(abd_u32, neon_u32, 1)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8 || \
tmp <= -(ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp < 0) { \
dest = src1 >> -tmp; \
} else { \
dest = src1 << tmp; \
}} while (0)
NEON_VOP(shl_u8, neon_u8, 4)
NEON_VOP(shl_u16, neon_u16, 2)
NEON_VOP(shl_u32, neon_u32, 1)
#undef NEON_FN
uint64_t HELPER(neon_shl_u64)(uint64_t val, uint64_t shiftop)
{
int8_t shift = (int8_t)shiftop;
if (shift >= 64 || shift <= -64) {
val = 0;
} else if (shift < 0) {
val >>= -shift;
} else {
val <<= shift;
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp <= -(ssize_t)sizeof(src1) * 8) { \
dest = src1 >> (sizeof(src1) * 8 - 1); \
} else if (tmp < 0) { \
dest = src1 >> -tmp; \
} else { \
dest = src1 << tmp; \
}} while (0)
NEON_VOP(shl_s8, neon_s8, 4)
NEON_VOP(shl_s16, neon_s16, 2)
NEON_VOP(shl_s32, neon_s32, 1)
#undef NEON_FN
uint64_t HELPER(neon_shl_s64)(uint64_t valop, uint64_t shiftop)
{
int8_t shift = (int8_t)shiftop;
int64_t val = valop;
if (shift >= 64) {
val = 0;
} else if (shift <= -64) {
val >>= 63;
} else if (shift < 0) {
val >>= -shift;
} else {
val <<= shift;
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if ((tmp >= (ssize_t)sizeof(src1) * 8) \
|| (tmp <= -(ssize_t)sizeof(src1) * 8)) { \
dest = 0; \
} else if (tmp < 0) { \
dest = (src1 + (1 << (-1 - tmp))) >> -tmp; \
} else { \
dest = src1 << tmp; \
}} while (0)
NEON_VOP(rshl_s8, neon_s8, 4)
NEON_VOP(rshl_s16, neon_s16, 2)
#undef NEON_FN
/* The addition of the rounding constant may overflow, so we use an
* intermediate 64 bit accumulator. */
uint32_t HELPER(neon_rshl_s32)(uint32_t valop, uint32_t shiftop)
{
int32_t dest;
int32_t val = (int32_t)valop;
int8_t shift = (int8_t)shiftop;
if ((shift >= 32) || (shift <= -32)) {
dest = 0;
} else if (shift < 0) {
int64_t big_dest = ((int64_t)val + (1 << (-1 - shift)));
dest = big_dest >> -shift;
} else {
dest = val << shift;
}
return dest;
}
/* Handling addition overflow with 64 bit input values is more
* tricky than with 32 bit values. */
uint64_t HELPER(neon_rshl_s64)(uint64_t valop, uint64_t shiftop)
{
int8_t shift = (int8_t)shiftop;
int64_t val = valop;
if ((shift >= 64) || (shift <= -64)) {
val = 0;
} else if (shift < 0) {
val >>= (-shift - 1);
if (val == INT64_MAX) {
/* In this case, it means that the rounding constant is 1,
* and the addition would overflow. Return the actual
* result directly. */
val = 0x4000000000000000LL;
} else {
val++;
val >>= 1;
}
} else {
val <<= shift;
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8 || \
tmp < -(ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp == -(ssize_t)sizeof(src1) * 8) { \
dest = src1 >> (-tmp - 1); \
} else if (tmp < 0) { \
dest = (src1 + (1 << (-1 - tmp))) >> -tmp; \
} else { \
dest = src1 << tmp; \
}} while (0)
NEON_VOP(rshl_u8, neon_u8, 4)
NEON_VOP(rshl_u16, neon_u16, 2)
#undef NEON_FN
/* The addition of the rounding constant may overflow, so we use an
* intermediate 64 bit accumulator. */
uint32_t HELPER(neon_rshl_u32)(uint32_t val, uint32_t shiftop)
{
uint32_t dest;
int8_t shift = (int8_t)shiftop;
if (shift >= 32 || shift < -32) {
dest = 0;
} else if (shift == -32) {
dest = val >> 31;
} else if (shift < 0) {
uint64_t big_dest = ((uint64_t)val + (1 << (-1 - shift)));
dest = big_dest >> -shift;
} else {
dest = val << shift;
}
return dest;
}
/* Handling addition overflow with 64 bit input values is more
* tricky than with 32 bit values. */
uint64_t HELPER(neon_rshl_u64)(uint64_t val, uint64_t shiftop)
{
int8_t shift = (uint8_t)shiftop;
if (shift >= 64 || shift < -64) {
val = 0;
} else if (shift == -64) {
/* Rounding a 1-bit result just preserves that bit. */
val >>= 63;
} else if (shift < 0) {
val >>= (-shift - 1);
if (val == UINT64_MAX) {
/* In this case, it means that the rounding constant is 1,
* and the addition would overflow. Return the actual
* result directly. */
val = 0x8000000000000000ULL;
} else {
val++;
val >>= 1;
}
} else {
val <<= shift;
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8) { \
if (src1) { \
SET_QC(); \
dest = ~0; \
} else { \
dest = 0; \
} \
} else if (tmp <= -(ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp < 0) { \
dest = src1 >> -tmp; \
} else { \
dest = src1 << tmp; \
if ((dest >> tmp) != src1) { \
SET_QC(); \
dest = ~0; \
} \
}} while (0)
NEON_VOP_ENV(qshl_u8, neon_u8, 4)
NEON_VOP_ENV(qshl_u16, neon_u16, 2)
NEON_VOP_ENV(qshl_u32, neon_u32, 1)
#undef NEON_FN
uint64_t HELPER(neon_qshl_u64)(CPUARMState *env, uint64_t val, uint64_t shiftop)
{
int8_t shift = (int8_t)shiftop;
if (shift >= 64) {
if (val) {
val = ~(uint64_t)0;
SET_QC();
}
} else if (shift <= -64) {
val = 0;
} else if (shift < 0) {
val >>= -shift;
} else {
uint64_t tmp = val;
val <<= shift;
if ((val >> shift) != tmp) {
SET_QC();
val = ~(uint64_t)0;
}
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8) { \
if (src1) { \
SET_QC(); \
dest = (uint32_t)(1 << (sizeof(src1) * 8 - 1)); \
if (src1 > 0) { \
dest--; \
} \
} else { \
dest = src1; \
} \
} else if (tmp <= -(ssize_t)sizeof(src1) * 8) { \
dest = src1 >> 31; \
} else if (tmp < 0) { \
dest = src1 >> -tmp; \
} else { \
dest = src1 << tmp; \
if ((dest >> tmp) != src1) { \
SET_QC(); \
dest = (uint32_t)(1 << (sizeof(src1) * 8 - 1)); \
if (src1 > 0) { \
dest--; \
} \
} \
}} while (0)
NEON_VOP_ENV(qshl_s8, neon_s8, 4)
NEON_VOP_ENV(qshl_s16, neon_s16, 2)
NEON_VOP_ENV(qshl_s32, neon_s32, 1)
#undef NEON_FN
uint64_t HELPER(neon_qshl_s64)(CPUARMState *env, uint64_t valop, uint64_t shiftop)
{
int8_t shift = (uint8_t)shiftop;
int64_t val = valop;
if (shift >= 64) {
if (val) {
SET_QC();
val = (val >> 63) ^ ~SIGNBIT64;
}
} else if (shift <= -64) {
val >>= 63;
} else if (shift < 0) {
val >>= -shift;
} else {
int64_t tmp = val;
val <<= shift;
if ((val >> shift) != tmp) {
SET_QC();
val = (tmp >> 63) ^ ~SIGNBIT64;
}
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
if (src1 & (1 << (sizeof(src1) * 8 - 1))) { \
SET_QC(); \
dest = 0; \
} else { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8) { \
if (src1) { \
SET_QC(); \
dest = ~0; \
} else { \
dest = 0; \
} \
} else if (tmp <= -(ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp < 0) { \
dest = src1 >> -tmp; \
} else { \
dest = src1 << tmp; \
if ((dest >> tmp) != src1) { \
SET_QC(); \
dest = ~0; \
} \
} \
}} while (0)
NEON_VOP_ENV(qshlu_s8, neon_u8, 4)
NEON_VOP_ENV(qshlu_s16, neon_u16, 2)
#undef NEON_FN
uint32_t HELPER(neon_qshlu_s32)(CPUARMState *env, uint32_t valop, uint32_t shiftop)
{
if ((int32_t)valop < 0) {
SET_QC();
return 0;
}
return helper_neon_qshl_u32(env, valop, shiftop);
}
uint64_t HELPER(neon_qshlu_s64)(CPUARMState *env, uint64_t valop, uint64_t shiftop)
{
if ((int64_t)valop < 0) {
SET_QC();
return 0;
}
return helper_neon_qshl_u64(env, valop, shiftop);
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8) { \
if (src1) { \
SET_QC(); \
dest = ~0; \
} else { \
dest = 0; \
} \
} else if (tmp < -(ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp == -(ssize_t)sizeof(src1) * 8) { \
dest = src1 >> (sizeof(src1) * 8 - 1); \
} else if (tmp < 0) { \
dest = (src1 + (1 << (-1 - tmp))) >> -tmp; \
} else { \
dest = src1 << tmp; \
if ((dest >> tmp) != src1) { \
SET_QC(); \
dest = ~0; \
} \
}} while (0)
NEON_VOP_ENV(qrshl_u8, neon_u8, 4)
NEON_VOP_ENV(qrshl_u16, neon_u16, 2)
#undef NEON_FN
/* The addition of the rounding constant may overflow, so we use an
* intermediate 64 bit accumulator. */
uint32_t HELPER(neon_qrshl_u32)(CPUARMState *env, uint32_t val, uint32_t shiftop)
{
uint32_t dest;
int8_t shift = (int8_t)shiftop;
if (shift >= 32) {
if (val) {
SET_QC();
dest = ~0;
} else {
dest = 0;
}
} else if (shift < -32) {
dest = 0;
} else if (shift == -32) {
dest = val >> 31;
} else if (shift < 0) {
uint64_t big_dest = ((uint64_t)val + (1 << (-1 - shift)));
dest = big_dest >> -shift;
} else {
dest = val << shift;
if ((dest >> shift) != val) {
SET_QC();
dest = ~0;
}
}
return dest;
}
/* Handling addition overflow with 64 bit input values is more
* tricky than with 32 bit values. */
uint64_t HELPER(neon_qrshl_u64)(CPUARMState *env, uint64_t val, uint64_t shiftop)
{
int8_t shift = (int8_t)shiftop;
if (shift >= 64) {
if (val) {
SET_QC();
val = ~0;
}
} else if (shift < -64) {
val = 0;
} else if (shift == -64) {
val >>= 63;
} else if (shift < 0) {
val >>= (-shift - 1);
if (val == UINT64_MAX) {
/* In this case, it means that the rounding constant is 1,
* and the addition would overflow. Return the actual
* result directly. */
val = 0x8000000000000000ULL;
} else {
val++;
val >>= 1;
}
} else { \
uint64_t tmp = val;
val <<= shift;
if ((val >> shift) != tmp) {
SET_QC();
val = ~0;
}
}
return val;
}
#define NEON_FN(dest, src1, src2) do { \
int8_t tmp; \
tmp = (int8_t)src2; \
if (tmp >= (ssize_t)sizeof(src1) * 8) { \
if (src1) { \
SET_QC(); \
dest = (1 << (sizeof(src1) * 8 - 1)); \
if (src1 > 0) { \
dest--; \
} \
} else { \
dest = 0; \
} \
} else if (tmp <= -(ssize_t)sizeof(src1) * 8) { \
dest = 0; \
} else if (tmp < 0) { \
dest = (src1 + (1 << (-1 - tmp))) >> -tmp; \
} else { \
dest = src1 << tmp; \
if ((dest >> tmp) != src1) { \
SET_QC(); \
dest = (uint32_t)(1 << (sizeof(src1) * 8 - 1)); \
if (src1 > 0) { \
dest--; \
} \
} \
}} while (0)
NEON_VOP_ENV(qrshl_s8, neon_s8, 4)
NEON_VOP_ENV(qrshl_s16, neon_s16, 2)
#undef NEON_FN
/* The addition of the rounding constant may overflow, so we use an
* intermediate 64 bit accumulator. */
uint32_t HELPER(neon_qrshl_s32)(CPUARMState *env, uint32_t valop, uint32_t shiftop)
{
int32_t dest;
int32_t val = (int32_t)valop;
int8_t shift = (int8_t)shiftop;
if (shift >= 32) {
if (val) {
SET_QC();
dest = (val >> 31) ^ ~SIGNBIT;
} else {
dest = 0;
}
} else if (shift <= -32) {
dest = 0;
} else if (shift < 0) {
int64_t big_dest = ((int64_t)val + (1 << (-1 - shift)));
dest = big_dest >> -shift;
} else {
dest = val << shift;
if ((dest >> shift) != val) {
SET_QC();
dest = (val >> 31) ^ ~SIGNBIT;
}
}
return dest;
}
/* Handling addition overflow with 64 bit input values is more
* tricky than with 32 bit values. */
uint64_t HELPER(neon_qrshl_s64)(CPUARMState *env, uint64_t valop, uint64_t shiftop)
{
int8_t shift = (uint8_t)shiftop;
int64_t val = valop;
if (shift >= 64) {
if (val) {
SET_QC();
val = (val >> 63) ^ ~SIGNBIT64;
}
} else if (shift <= -64) {
val = 0;
} else if (shift < 0) {
val >>= (-shift - 1);
if (val == INT64_MAX) {
/* In this case, it means that the rounding constant is 1,
* and the addition would overflow. Return the actual
* result directly. */
val = 0x4000000000000000ULL;
} else {
val++;
val >>= 1;
}
} else {
int64_t tmp = val;
val <<= shift;
if ((val >> shift) != tmp) {
SET_QC();
val = (tmp >> 63) ^ ~SIGNBIT64;
}
}
return val;
}
uint32_t HELPER(neon_add_u8)(uint32_t a, uint32_t b)
{
uint32_t mask;
mask = (a ^ b) & 0x80808080u;
a &= ~0x80808080u;
b &= ~0x80808080u;
return (a + b) ^ mask;
}
uint32_t HELPER(neon_add_u16)(uint32_t a, uint32_t b)
{
uint32_t mask;
mask = (a ^ b) & 0x80008000u;
a &= ~0x80008000u;
b &= ~0x80008000u;
return (a + b) ^ mask;
}
#define NEON_FN(dest, src1, src2) dest = src1 + src2
NEON_POP(padd_u8, neon_u8, 4)
NEON_POP(padd_u16, neon_u16, 2)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) dest = src1 - src2
NEON_VOP(sub_u8, neon_u8, 4)
NEON_VOP(sub_u16, neon_u16, 2)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) dest = src1 * src2
NEON_VOP(mul_u8, neon_u8, 4)
NEON_VOP(mul_u16, neon_u16, 2)
#undef NEON_FN
/* Polynomial multiplication is like integer multiplication except the
partial products are XORed, not added. */
uint32_t HELPER(neon_mul_p8)(uint32_t op1, uint32_t op2)
{
uint32_t mask;
uint32_t result;
result = 0;
while (op1) {
mask = 0;
if (op1 & 1)
mask |= 0xff;
if (op1 & (1 << 8))
mask |= (0xff << 8);
if (op1 & (1 << 16))
mask |= (0xff << 16);
if (op1 & (1 << 24))
mask |= (0xff << 24);
result ^= op2 & mask;
op1 = (op1 >> 1) & 0x7f7f7f7f;
op2 = (op2 << 1) & 0xfefefefe;
}
return result;
}
uint64_t HELPER(neon_mull_p8)(uint32_t op1, uint32_t op2)
{
uint64_t result = 0;
uint64_t mask;
uint64_t op2ex = op2;
op2ex = (op2ex & 0xff) |
((op2ex & 0xff00) << 8) |
((op2ex & 0xff0000) << 16) |
((op2ex & 0xff000000) << 24);
while (op1) {
mask = 0;
if (op1 & 1) {
mask |= 0xffff;
}
if (op1 & (1 << 8)) {
mask |= (0xffffU << 16);
}
if (op1 & (1 << 16)) {
mask |= (0xffffULL << 32);
}
if (op1 & (1 << 24)) {
mask |= (0xffffULL << 48);
}
result ^= op2ex & mask;
op1 = (op1 >> 1) & 0x7f7f7f7f;
op2ex <<= 1;
}
return result;
}
#define NEON_FN(dest, src1, src2) dest = (src1 & src2) ? -1 : 0
NEON_VOP(tst_u8, neon_u8, 4)
NEON_VOP(tst_u16, neon_u16, 2)
NEON_VOP(tst_u32, neon_u32, 1)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) dest = (src1 == src2) ? -1 : 0
NEON_VOP(ceq_u8, neon_u8, 4)
NEON_VOP(ceq_u16, neon_u16, 2)
NEON_VOP(ceq_u32, neon_u32, 1)
#undef NEON_FN
#define NEON_FN(dest, src, dummy) dest = (src < 0) ? -src : src
NEON_VOP1(abs_s8, neon_s8, 4)
NEON_VOP1(abs_s16, neon_s16, 2)
#undef NEON_FN
/* Count Leading Sign/Zero Bits. */
static inline int do_clz8(uint8_t x)
{
int n;
for (n = 8; x; n--)
x >>= 1;
return n;
}
static inline int do_clz16(uint16_t x)
{
int n;
for (n = 16; x; n--)
x >>= 1;
return n;
}
#define NEON_FN(dest, src, dummy) dest = do_clz8(src)
NEON_VOP1(clz_u8, neon_u8, 4)
#undef NEON_FN
#define NEON_FN(dest, src, dummy) dest = do_clz16(src)
NEON_VOP1(clz_u16, neon_u16, 2)
#undef NEON_FN
#define NEON_FN(dest, src, dummy) dest = do_clz8((src < 0) ? ~src : src) - 1
NEON_VOP1(cls_s8, neon_s8, 4)
#undef NEON_FN
#define NEON_FN(dest, src, dummy) dest = do_clz16((src < 0) ? ~src : src) - 1
NEON_VOP1(cls_s16, neon_s16, 2)
#undef NEON_FN
uint32_t HELPER(neon_cls_s32)(uint32_t x)
{
int count;
if ((int32_t)x < 0)
x = ~x;
for (count = 32; x; count--)
x = x >> 1;
return count - 1;
}
/* Bit count. */
uint32_t HELPER(neon_cnt_u8)(uint32_t x)
{
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f);
return x;
}
/* Reverse bits in each 8 bit word */
uint32_t HELPER(neon_rbit_u8)(uint32_t x)
{
x = ((x & 0xf0f0f0f0) >> 4)
| ((x & 0x0f0f0f0f) << 4);
x = ((x & 0x88888888) >> 3)
| ((x & 0x44444444) >> 1)
| ((x & 0x22222222) << 1)
| ((x & 0x11111111) << 3);
return x;
}
#define NEON_QDMULH16(dest, src1, src2, round) do { \
uint32_t tmp = (int32_t)(int16_t) src1 * (int16_t) src2; \
if ((tmp ^ (tmp << 1)) & SIGNBIT) { \
SET_QC(); \
tmp = (tmp >> 31) ^ ~SIGNBIT; \
} else { \
tmp <<= 1; \
} \
if (round) { \
int32_t old = tmp; \
tmp += 1 << 15; \
if ((int32_t)tmp < old) { \
SET_QC(); \
tmp = SIGNBIT - 1; \
} \
} \
dest = tmp >> 16; \
} while(0)
#define NEON_FN(dest, src1, src2) NEON_QDMULH16(dest, src1, src2, 0)
NEON_VOP_ENV(qdmulh_s16, neon_s16, 2)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_QDMULH16(dest, src1, src2, 1)
NEON_VOP_ENV(qrdmulh_s16, neon_s16, 2)
#undef NEON_FN
#undef NEON_QDMULH16
#define NEON_QDMULH32(dest, src1, src2, round) do { \
uint64_t tmp = (int64_t)(int32_t) src1 * (int32_t) src2; \
if ((tmp ^ (tmp << 1)) & SIGNBIT64) { \
SET_QC(); \
tmp = (tmp >> 63) ^ ~SIGNBIT64; \
} else { \
tmp <<= 1; \
} \
if (round) { \
int64_t old = tmp; \
tmp += (int64_t)1 << 31; \
if ((int64_t)tmp < old) { \
SET_QC(); \
tmp = SIGNBIT64 - 1; \
} \
} \
dest = tmp >> 32; \
} while(0)
#define NEON_FN(dest, src1, src2) NEON_QDMULH32(dest, src1, src2, 0)
NEON_VOP_ENV(qdmulh_s32, neon_s32, 1)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_QDMULH32(dest, src1, src2, 1)
NEON_VOP_ENV(qrdmulh_s32, neon_s32, 1)
#undef NEON_FN
#undef NEON_QDMULH32
uint32_t HELPER(neon_narrow_u8)(uint64_t x)
{
return (x & 0xffu) | ((x >> 8) & 0xff00u) | ((x >> 16) & 0xff0000u)
| ((x >> 24) & 0xff000000u);
}
uint32_t HELPER(neon_narrow_u16)(uint64_t x)
{
return (x & 0xffffu) | ((x >> 16) & 0xffff0000u);
}
uint32_t HELPER(neon_narrow_high_u8)(uint64_t x)
{
return ((x >> 8) & 0xff) | ((x >> 16) & 0xff00)
| ((x >> 24) & 0xff0000) | ((x >> 32) & 0xff000000);
}
uint32_t HELPER(neon_narrow_high_u16)(uint64_t x)
{
return ((x >> 16) & 0xffff) | ((x >> 32) & 0xffff0000);
}
uint32_t HELPER(neon_narrow_round_high_u8)(uint64_t x)
{
x &= 0xff80ff80ff80ff80ull;
x += 0x0080008000800080ull;
return ((x >> 8) & 0xff) | ((x >> 16) & 0xff00)
| ((x >> 24) & 0xff0000) | ((x >> 32) & 0xff000000);
}
uint32_t HELPER(neon_narrow_round_high_u16)(uint64_t x)
{
x &= 0xffff8000ffff8000ull;
x += 0x0000800000008000ull;
return ((x >> 16) & 0xffff) | ((x >> 32) & 0xffff0000);
}
uint32_t HELPER(neon_unarrow_sat8)(CPUARMState *env, uint64_t x)
{
uint16_t s;
uint8_t d;
uint32_t res = 0;
#define SAT8(n) \
s = x >> n; \
if (s & 0x8000) { \
SET_QC(); \
} else { \
if (s > 0xff) { \
d = 0xff; \
SET_QC(); \
} else { \
d = s; \
} \
res |= (uint32_t)d << (n / 2); \
}
SAT8(0);
SAT8(16);
SAT8(32);
SAT8(48);
#undef SAT8
return res;
}
uint32_t HELPER(neon_narrow_sat_u8)(CPUARMState *env, uint64_t x)
{
uint16_t s;
uint8_t d;
uint32_t res = 0;
#define SAT8(n) \
s = x >> n; \
if (s > 0xff) { \
d = 0xff; \
SET_QC(); \
} else { \
d = s; \
} \
res |= (uint32_t)d << (n / 2);
SAT8(0);
SAT8(16);
SAT8(32);
SAT8(48);
#undef SAT8
return res;
}
uint32_t HELPER(neon_narrow_sat_s8)(CPUARMState *env, uint64_t x)
{
int16_t s;
uint8_t d;
uint32_t res = 0;
#define SAT8(n) \
s = x >> n; \
if (s != (int8_t)s) { \
d = (s >> 15) ^ 0x7f; \
SET_QC(); \
} else { \
d = s; \
} \
res |= (uint32_t)d << (n / 2);
SAT8(0);
SAT8(16);
SAT8(32);
SAT8(48);
#undef SAT8
return res;
}
uint32_t HELPER(neon_unarrow_sat16)(CPUARMState *env, uint64_t x)
{
uint32_t high;
uint32_t low;
low = x;
if (low & 0x80000000) {
low = 0;
SET_QC();
} else if (low > 0xffff) {
low = 0xffff;
SET_QC();
}
high = x >> 32;
if (high & 0x80000000) {
high = 0;
SET_QC();
} else if (high > 0xffff) {
high = 0xffff;
SET_QC();
}
return low | (high << 16);
}
uint32_t HELPER(neon_narrow_sat_u16)(CPUARMState *env, uint64_t x)
{
uint32_t high;
uint32_t low;
low = x;
if (low > 0xffff) {
low = 0xffff;
SET_QC();
}
high = x >> 32;
if (high > 0xffff) {
high = 0xffff;
SET_QC();
}
return low | (high << 16);
}
uint32_t HELPER(neon_narrow_sat_s16)(CPUARMState *env, uint64_t x)
{
int32_t low;
int32_t high;
low = x;
if (low != (int16_t)low) {
low = (low >> 31) ^ 0x7fff;
SET_QC();
}
high = x >> 32;
if (high != (int16_t)high) {
high = (high >> 31) ^ 0x7fff;
SET_QC();
}
return (uint16_t)low | (high << 16);
}
uint32_t HELPER(neon_unarrow_sat32)(CPUARMState *env, uint64_t x)
{
if (x & 0x8000000000000000ull) {
SET_QC();
return 0;
}
if (x > 0xffffffffu) {
SET_QC();
return 0xffffffffu;
}
return x;
}
uint32_t HELPER(neon_narrow_sat_u32)(CPUARMState *env, uint64_t x)
{
if (x > 0xffffffffu) {
SET_QC();
return 0xffffffffu;
}
return x;
}
uint32_t HELPER(neon_narrow_sat_s32)(CPUARMState *env, uint64_t x)
{
if ((int64_t)x != (int32_t)x) {
SET_QC();
return ((int64_t)x >> 63) ^ 0x7fffffff;
}
return x;
}
uint64_t HELPER(neon_widen_u8)(uint32_t x)
{
uint64_t tmp;
uint64_t ret;
ret = (uint8_t)x;
tmp = (uint8_t)(x >> 8);
ret |= tmp << 16;
tmp = (uint8_t)(x >> 16);
ret |= tmp << 32;
tmp = (uint8_t)(x >> 24);
ret |= tmp << 48;
return ret;
}
uint64_t HELPER(neon_widen_s8)(uint32_t x)
{
uint64_t tmp;
uint64_t ret;
ret = (uint16_t)(int8_t)x;
tmp = (uint16_t)(int8_t)(x >> 8);
ret |= tmp << 16;
tmp = (uint16_t)(int8_t)(x >> 16);
ret |= tmp << 32;
tmp = (uint16_t)(int8_t)(x >> 24);
ret |= tmp << 48;
return ret;
}
uint64_t HELPER(neon_widen_u16)(uint32_t x)
{
uint64_t high = (uint16_t)(x >> 16);
return ((uint16_t)x) | (high << 32);
}
uint64_t HELPER(neon_widen_s16)(uint32_t x)
{
uint64_t high = (int16_t)(x >> 16);
return ((uint32_t)(int16_t)x) | (high << 32);
}
uint64_t HELPER(neon_addl_u16)(uint64_t a, uint64_t b)
{
uint64_t mask;
mask = (a ^ b) & 0x8000800080008000ull;
a &= ~0x8000800080008000ull;
b &= ~0x8000800080008000ull;
return (a + b) ^ mask;
}
uint64_t HELPER(neon_addl_u32)(uint64_t a, uint64_t b)
{
uint64_t mask;
mask = (a ^ b) & 0x8000000080000000ull;
a &= ~0x8000000080000000ull;
b &= ~0x8000000080000000ull;
return (a + b) ^ mask;
}
uint64_t HELPER(neon_paddl_u16)(uint64_t a, uint64_t b)
{
uint64_t tmp;
uint64_t tmp2;
tmp = a & 0x0000ffff0000ffffull;
tmp += (a >> 16) & 0x0000ffff0000ffffull;
tmp2 = b & 0xffff0000ffff0000ull;
tmp2 += (b << 16) & 0xffff0000ffff0000ull;
return ( tmp & 0xffff)
| ((tmp >> 16) & 0xffff0000ull)
| ((tmp2 << 16) & 0xffff00000000ull)
| ( tmp2 & 0xffff000000000000ull);
}
uint64_t HELPER(neon_paddl_u32)(uint64_t a, uint64_t b)
{
uint32_t low = a + (a >> 32);
uint32_t high = b + (b >> 32);
return low + ((uint64_t)high << 32);
}
uint64_t HELPER(neon_subl_u16)(uint64_t a, uint64_t b)
{
uint64_t mask;
mask = (a ^ ~b) & 0x8000800080008000ull;
a |= 0x8000800080008000ull;
b &= ~0x8000800080008000ull;
return (a - b) ^ mask;
}
uint64_t HELPER(neon_subl_u32)(uint64_t a, uint64_t b)
{
uint64_t mask;
mask = (a ^ ~b) & 0x8000000080000000ull;
a |= 0x8000000080000000ull;
b &= ~0x8000000080000000ull;
return (a - b) ^ mask;
}
uint64_t HELPER(neon_addl_saturate_s32)(CPUARMState *env, uint64_t a, uint64_t b)
{
uint32_t x, y;
uint32_t low, high;
x = a;
y = b;
low = x + y;
if (((low ^ x) & SIGNBIT) && !((x ^ y) & SIGNBIT)) {
SET_QC();
low = ((int32_t)x >> 31) ^ ~SIGNBIT;
}
x = a >> 32;
y = b >> 32;
high = x + y;
if (((high ^ x) & SIGNBIT) && !((x ^ y) & SIGNBIT)) {
SET_QC();
high = ((int32_t)x >> 31) ^ ~SIGNBIT;
}
return low | ((uint64_t)high << 32);
}
uint64_t HELPER(neon_addl_saturate_s64)(CPUARMState *env, uint64_t a, uint64_t b)
{
uint64_t result;
result = a + b;
if (((result ^ a) & SIGNBIT64) && !((a ^ b) & SIGNBIT64)) {
SET_QC();
result = ((int64_t)a >> 63) ^ ~SIGNBIT64;
}
return result;
}
/* We have to do the arithmetic in a larger type than
* the input type, because for example with a signed 32 bit
* op the absolute difference can overflow a signed 32 bit value.
*/
#define DO_ABD(dest, x, y, intype, arithtype) do { \
arithtype tmp_x = (intype)(x); \
arithtype tmp_y = (intype)(y); \
dest = ((tmp_x > tmp_y) ? tmp_x - tmp_y : tmp_y - tmp_x); \
} while(0)
uint64_t HELPER(neon_abdl_u16)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_ABD(result, a, b, uint8_t, uint32_t);
DO_ABD(tmp, a >> 8, b >> 8, uint8_t, uint32_t);
result |= tmp << 16;
DO_ABD(tmp, a >> 16, b >> 16, uint8_t, uint32_t);
result |= tmp << 32;
DO_ABD(tmp, a >> 24, b >> 24, uint8_t, uint32_t);
result |= tmp << 48;
return result;
}
uint64_t HELPER(neon_abdl_s16)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_ABD(result, a, b, int8_t, int32_t);
DO_ABD(tmp, a >> 8, b >> 8, int8_t, int32_t);
result |= tmp << 16;
DO_ABD(tmp, a >> 16, b >> 16, int8_t, int32_t);
result |= tmp << 32;
DO_ABD(tmp, a >> 24, b >> 24, int8_t, int32_t);
result |= tmp << 48;
return result;
}
uint64_t HELPER(neon_abdl_u32)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_ABD(result, a, b, uint16_t, uint32_t);
DO_ABD(tmp, a >> 16, b >> 16, uint16_t, uint32_t);
return result | (tmp << 32);
}
uint64_t HELPER(neon_abdl_s32)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_ABD(result, a, b, int16_t, int32_t);
DO_ABD(tmp, a >> 16, b >> 16, int16_t, int32_t);
return result | (tmp << 32);
}
uint64_t HELPER(neon_abdl_u64)(uint32_t a, uint32_t b)
{
uint64_t result;
DO_ABD(result, a, b, uint32_t, uint64_t);
return result;
}
uint64_t HELPER(neon_abdl_s64)(uint32_t a, uint32_t b)
{
uint64_t result;
DO_ABD(result, a, b, int32_t, int64_t);
return result;
}
#undef DO_ABD
/* Widening multiply. Named type is the source type. */
#define DO_MULL(dest, x, y, type1, type2) do { \
type1 tmp_x = x; \
type1 tmp_y = y; \
dest = (type2)((type2)tmp_x * (type2)tmp_y); \
} while(0)
uint64_t HELPER(neon_mull_u8)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_MULL(result, a, b, uint8_t, uint16_t);
DO_MULL(tmp, a >> 8, b >> 8, uint8_t, uint16_t);
result |= tmp << 16;
DO_MULL(tmp, a >> 16, b >> 16, uint8_t, uint16_t);
result |= tmp << 32;
DO_MULL(tmp, a >> 24, b >> 24, uint8_t, uint16_t);
result |= tmp << 48;
return result;
}
uint64_t HELPER(neon_mull_s8)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_MULL(result, a, b, int8_t, uint16_t);
DO_MULL(tmp, a >> 8, b >> 8, int8_t, uint16_t);
result |= tmp << 16;
DO_MULL(tmp, a >> 16, b >> 16, int8_t, uint16_t);
result |= tmp << 32;
DO_MULL(tmp, a >> 24, b >> 24, int8_t, uint16_t);
result |= tmp << 48;
return result;
}
uint64_t HELPER(neon_mull_u16)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_MULL(result, a, b, uint16_t, uint32_t);
DO_MULL(tmp, a >> 16, b >> 16, uint16_t, uint32_t);
return result | (tmp << 32);
}
uint64_t HELPER(neon_mull_s16)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_MULL(result, a, b, int16_t, uint32_t);
DO_MULL(tmp, a >> 16, b >> 16, int16_t, uint32_t);
return result | (tmp << 32);
}
uint64_t HELPER(neon_negl_u16)(uint64_t x)
{
uint16_t tmp;
uint64_t result;
result = (uint16_t)-x;
tmp = -(x >> 16);
result |= (uint64_t)tmp << 16;
tmp = -(x >> 32);
result |= (uint64_t)tmp << 32;
tmp = -(x >> 48);
result |= (uint64_t)tmp << 48;
return result;
}
uint64_t HELPER(neon_negl_u32)(uint64_t x)
{
uint32_t low = -x;
uint32_t high = -(x >> 32);
return low | ((uint64_t)high << 32);
}
/* Saturating sign manipulation. */
/* ??? Make these use NEON_VOP1 */
#define DO_QABS8(x) do { \
if (x == (int8_t)0x80) { \
x = 0x7f; \
SET_QC(); \
} else if (x < 0) { \
x = -x; \
}} while (0)
uint32_t HELPER(neon_qabs_s8)(CPUARMState *env, uint32_t x)
{
neon_s8 vec;
NEON_UNPACK(neon_s8, vec, x);
DO_QABS8(vec.v1);
DO_QABS8(vec.v2);
DO_QABS8(vec.v3);
DO_QABS8(vec.v4);
NEON_PACK(neon_s8, x, vec);
return x;
}
#undef DO_QABS8
#define DO_QNEG8(x) do { \
if (x == (int8_t)0x80) { \
x = 0x7f; \
SET_QC(); \
} else { \
x = -x; \
}} while (0)
uint32_t HELPER(neon_qneg_s8)(CPUARMState *env, uint32_t x)
{
neon_s8 vec;
NEON_UNPACK(neon_s8, vec, x);
DO_QNEG8(vec.v1);
DO_QNEG8(vec.v2);
DO_QNEG8(vec.v3);
DO_QNEG8(vec.v4);
NEON_PACK(neon_s8, x, vec);
return x;
}
#undef DO_QNEG8
#define DO_QABS16(x) do { \
if (x == (int16_t)0x8000) { \
x = 0x7fff; \
SET_QC(); \
} else if (x < 0) { \
x = -x; \
}} while (0)
uint32_t HELPER(neon_qabs_s16)(CPUARMState *env, uint32_t x)
{
neon_s16 vec;
NEON_UNPACK(neon_s16, vec, x);
DO_QABS16(vec.v1);
DO_QABS16(vec.v2);
NEON_PACK(neon_s16, x, vec);
return x;
}
#undef DO_QABS16
#define DO_QNEG16(x) do { \
if (x == (int16_t)0x8000) { \
x = 0x7fff; \
SET_QC(); \
} else { \
x = -x; \
}} while (0)
uint32_t HELPER(neon_qneg_s16)(CPUARMState *env, uint32_t x)
{
neon_s16 vec;
NEON_UNPACK(neon_s16, vec, x);
DO_QNEG16(vec.v1);
DO_QNEG16(vec.v2);
NEON_PACK(neon_s16, x, vec);
return x;
}
#undef DO_QNEG16
uint32_t HELPER(neon_qabs_s32)(CPUARMState *env, uint32_t x)
{
if (x == SIGNBIT) {
SET_QC();
x = ~SIGNBIT;
} else if ((int32_t)x < 0) {
x = -x;
}
return x;
}
uint32_t HELPER(neon_qneg_s32)(CPUARMState *env, uint32_t x)
{
if (x == SIGNBIT) {
SET_QC();
x = ~SIGNBIT;
} else {
x = -x;
}
return x;
}
uint64_t HELPER(neon_qabs_s64)(CPUARMState *env, uint64_t x)
{
if (x == SIGNBIT64) {
SET_QC();
x = ~SIGNBIT64;
} else if ((int64_t)x < 0) {
x = -x;
}
return x;
}
uint64_t HELPER(neon_qneg_s64)(CPUARMState *env, uint64_t x)
{
if (x == SIGNBIT64) {
SET_QC();
x = ~SIGNBIT64;
} else {
x = -x;
}
return x;
}
/* NEON Float helpers. */
uint32_t HELPER(neon_abd_f32)(uint32_t a, uint32_t b, void *fpstp)
{
float_status *fpst = fpstp;
float32 f0 = make_float32(a);
float32 f1 = make_float32(b);
return float32_val(float32_abs(float32_sub(f0, f1, fpst)));
}
/* Floating point comparisons produce an integer result.
* Note that EQ doesn't signal InvalidOp for QNaNs but GE and GT do.
* Softfloat routines return 0/1, which we convert to the 0/-1 Neon requires.
*/
uint32_t HELPER(neon_ceq_f32)(uint32_t a, uint32_t b, void *fpstp)
{
float_status *fpst = fpstp;
return -float32_eq_quiet(make_float32(a), make_float32(b), fpst);
}
uint32_t HELPER(neon_cge_f32)(uint32_t a, uint32_t b, void *fpstp)
{
float_status *fpst = fpstp;
return -float32_le(make_float32(b), make_float32(a), fpst);
}
uint32_t HELPER(neon_cgt_f32)(uint32_t a, uint32_t b, void *fpstp)
{
float_status *fpst = fpstp;
return -float32_lt(make_float32(b), make_float32(a), fpst);
}
uint32_t HELPER(neon_acge_f32)(uint32_t a, uint32_t b, void *fpstp)
{
float_status *fpst = fpstp;
float32 f0 = float32_abs(make_float32(a));
float32 f1 = float32_abs(make_float32(b));
return -float32_le(f1, f0, fpst);
}
uint32_t HELPER(neon_acgt_f32)(uint32_t a, uint32_t b, void *fpstp)
{
float_status *fpst = fpstp;
float32 f0 = float32_abs(make_float32(a));
float32 f1 = float32_abs(make_float32(b));
return -float32_lt(f1, f0, fpst);
}
uint64_t HELPER(neon_acge_f64)(uint64_t a, uint64_t b, void *fpstp)
{
float_status *fpst = fpstp;
float64 f0 = float64_abs(make_float64(a));
float64 f1 = float64_abs(make_float64(b));
return -float64_le(f1, f0, fpst);
}
uint64_t HELPER(neon_acgt_f64)(uint64_t a, uint64_t b, void *fpstp)
{
float_status *fpst = fpstp;
float64 f0 = float64_abs(make_float64(a));
float64 f1 = float64_abs(make_float64(b));
return -float64_lt(f1, f0, fpst);
}
#define ELEM(V, N, SIZE) (((V) >> ((N) * (SIZE))) & ((1ull << (SIZE)) - 1))
void HELPER(neon_qunzip8)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm0 = float64_val(env->vfp.regs[rm]);
uint64_t zm1 = float64_val(env->vfp.regs[rm + 1]);
uint64_t zd0 = float64_val(env->vfp.regs[rd]);
uint64_t zd1 = float64_val(env->vfp.regs[rd + 1]);
uint64_t d0 = ELEM(zd0, 0, 8) | (ELEM(zd0, 2, 8) << 8)
| (ELEM(zd0, 4, 8) << 16) | (ELEM(zd0, 6, 8) << 24)
| (ELEM(zd1, 0, 8) << 32) | (ELEM(zd1, 2, 8) << 40)
| (ELEM(zd1, 4, 8) << 48) | (ELEM(zd1, 6, 8) << 56);
uint64_t d1 = ELEM(zm0, 0, 8) | (ELEM(zm0, 2, 8) << 8)
| (ELEM(zm0, 4, 8) << 16) | (ELEM(zm0, 6, 8) << 24)
| (ELEM(zm1, 0, 8) << 32) | (ELEM(zm1, 2, 8) << 40)
| (ELEM(zm1, 4, 8) << 48) | (ELEM(zm1, 6, 8) << 56);
uint64_t m0 = ELEM(zd0, 1, 8) | (ELEM(zd0, 3, 8) << 8)
| (ELEM(zd0, 5, 8) << 16) | (ELEM(zd0, 7, 8) << 24)
| (ELEM(zd1, 1, 8) << 32) | (ELEM(zd1, 3, 8) << 40)
| (ELEM(zd1, 5, 8) << 48) | (ELEM(zd1, 7, 8) << 56);
uint64_t m1 = ELEM(zm0, 1, 8) | (ELEM(zm0, 3, 8) << 8)
| (ELEM(zm0, 5, 8) << 16) | (ELEM(zm0, 7, 8) << 24)
| (ELEM(zm1, 1, 8) << 32) | (ELEM(zm1, 3, 8) << 40)
| (ELEM(zm1, 5, 8) << 48) | (ELEM(zm1, 7, 8) << 56);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rm + 1] = make_float64(m1);
env->vfp.regs[rd] = make_float64(d0);
env->vfp.regs[rd + 1] = make_float64(d1);
}
void HELPER(neon_qunzip16)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm0 = float64_val(env->vfp.regs[rm]);
uint64_t zm1 = float64_val(env->vfp.regs[rm + 1]);
uint64_t zd0 = float64_val(env->vfp.regs[rd]);
uint64_t zd1 = float64_val(env->vfp.regs[rd + 1]);
uint64_t d0 = ELEM(zd0, 0, 16) | (ELEM(zd0, 2, 16) << 16)
| (ELEM(zd1, 0, 16) << 32) | (ELEM(zd1, 2, 16) << 48);
uint64_t d1 = ELEM(zm0, 0, 16) | (ELEM(zm0, 2, 16) << 16)
| (ELEM(zm1, 0, 16) << 32) | (ELEM(zm1, 2, 16) << 48);
uint64_t m0 = ELEM(zd0, 1, 16) | (ELEM(zd0, 3, 16) << 16)
| (ELEM(zd1, 1, 16) << 32) | (ELEM(zd1, 3, 16) << 48);
uint64_t m1 = ELEM(zm0, 1, 16) | (ELEM(zm0, 3, 16) << 16)
| (ELEM(zm1, 1, 16) << 32) | (ELEM(zm1, 3, 16) << 48);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rm + 1] = make_float64(m1);
env->vfp.regs[rd] = make_float64(d0);
env->vfp.regs[rd + 1] = make_float64(d1);
}
void HELPER(neon_qunzip32)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm0 = float64_val(env->vfp.regs[rm]);
uint64_t zm1 = float64_val(env->vfp.regs[rm + 1]);
uint64_t zd0 = float64_val(env->vfp.regs[rd]);
uint64_t zd1 = float64_val(env->vfp.regs[rd + 1]);
uint64_t d0 = ELEM(zd0, 0, 32) | (ELEM(zd1, 0, 32) << 32);
uint64_t d1 = ELEM(zm0, 0, 32) | (ELEM(zm1, 0, 32) << 32);
uint64_t m0 = ELEM(zd0, 1, 32) | (ELEM(zd1, 1, 32) << 32);
uint64_t m1 = ELEM(zm0, 1, 32) | (ELEM(zm1, 1, 32) << 32);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rm + 1] = make_float64(m1);
env->vfp.regs[rd] = make_float64(d0);
env->vfp.regs[rd + 1] = make_float64(d1);
}
void HELPER(neon_unzip8)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm = float64_val(env->vfp.regs[rm]);
uint64_t zd = float64_val(env->vfp.regs[rd]);
uint64_t d0 = ELEM(zd, 0, 8) | (ELEM(zd, 2, 8) << 8)
| (ELEM(zd, 4, 8) << 16) | (ELEM(zd, 6, 8) << 24)
| (ELEM(zm, 0, 8) << 32) | (ELEM(zm, 2, 8) << 40)
| (ELEM(zm, 4, 8) << 48) | (ELEM(zm, 6, 8) << 56);
uint64_t m0 = ELEM(zd, 1, 8) | (ELEM(zd, 3, 8) << 8)
| (ELEM(zd, 5, 8) << 16) | (ELEM(zd, 7, 8) << 24)
| (ELEM(zm, 1, 8) << 32) | (ELEM(zm, 3, 8) << 40)
| (ELEM(zm, 5, 8) << 48) | (ELEM(zm, 7, 8) << 56);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rd] = make_float64(d0);
}
void HELPER(neon_unzip16)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm = float64_val(env->vfp.regs[rm]);
uint64_t zd = float64_val(env->vfp.regs[rd]);
uint64_t d0 = ELEM(zd, 0, 16) | (ELEM(zd, 2, 16) << 16)
| (ELEM(zm, 0, 16) << 32) | (ELEM(zm, 2, 16) << 48);
uint64_t m0 = ELEM(zd, 1, 16) | (ELEM(zd, 3, 16) << 16)
| (ELEM(zm, 1, 16) << 32) | (ELEM(zm, 3, 16) << 48);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rd] = make_float64(d0);
}
void HELPER(neon_qzip8)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm0 = float64_val(env->vfp.regs[rm]);
uint64_t zm1 = float64_val(env->vfp.regs[rm + 1]);
uint64_t zd0 = float64_val(env->vfp.regs[rd]);
uint64_t zd1 = float64_val(env->vfp.regs[rd + 1]);
uint64_t d0 = ELEM(zd0, 0, 8) | (ELEM(zm0, 0, 8) << 8)
| (ELEM(zd0, 1, 8) << 16) | (ELEM(zm0, 1, 8) << 24)
| (ELEM(zd0, 2, 8) << 32) | (ELEM(zm0, 2, 8) << 40)
| (ELEM(zd0, 3, 8) << 48) | (ELEM(zm0, 3, 8) << 56);
uint64_t d1 = ELEM(zd0, 4, 8) | (ELEM(zm0, 4, 8) << 8)
| (ELEM(zd0, 5, 8) << 16) | (ELEM(zm0, 5, 8) << 24)
| (ELEM(zd0, 6, 8) << 32) | (ELEM(zm0, 6, 8) << 40)
| (ELEM(zd0, 7, 8) << 48) | (ELEM(zm0, 7, 8) << 56);
uint64_t m0 = ELEM(zd1, 0, 8) | (ELEM(zm1, 0, 8) << 8)
| (ELEM(zd1, 1, 8) << 16) | (ELEM(zm1, 1, 8) << 24)
| (ELEM(zd1, 2, 8) << 32) | (ELEM(zm1, 2, 8) << 40)
| (ELEM(zd1, 3, 8) << 48) | (ELEM(zm1, 3, 8) << 56);
uint64_t m1 = ELEM(zd1, 4, 8) | (ELEM(zm1, 4, 8) << 8)
| (ELEM(zd1, 5, 8) << 16) | (ELEM(zm1, 5, 8) << 24)
| (ELEM(zd1, 6, 8) << 32) | (ELEM(zm1, 6, 8) << 40)
| (ELEM(zd1, 7, 8) << 48) | (ELEM(zm1, 7, 8) << 56);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rm + 1] = make_float64(m1);
env->vfp.regs[rd] = make_float64(d0);
env->vfp.regs[rd + 1] = make_float64(d1);
}
void HELPER(neon_qzip16)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm0 = float64_val(env->vfp.regs[rm]);
uint64_t zm1 = float64_val(env->vfp.regs[rm + 1]);
uint64_t zd0 = float64_val(env->vfp.regs[rd]);
uint64_t zd1 = float64_val(env->vfp.regs[rd + 1]);
uint64_t d0 = ELEM(zd0, 0, 16) | (ELEM(zm0, 0, 16) << 16)
| (ELEM(zd0, 1, 16) << 32) | (ELEM(zm0, 1, 16) << 48);
uint64_t d1 = ELEM(zd0, 2, 16) | (ELEM(zm0, 2, 16) << 16)
| (ELEM(zd0, 3, 16) << 32) | (ELEM(zm0, 3, 16) << 48);
uint64_t m0 = ELEM(zd1, 0, 16) | (ELEM(zm1, 0, 16) << 16)
| (ELEM(zd1, 1, 16) << 32) | (ELEM(zm1, 1, 16) << 48);
uint64_t m1 = ELEM(zd1, 2, 16) | (ELEM(zm1, 2, 16) << 16)
| (ELEM(zd1, 3, 16) << 32) | (ELEM(zm1, 3, 16) << 48);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rm + 1] = make_float64(m1);
env->vfp.regs[rd] = make_float64(d0);
env->vfp.regs[rd + 1] = make_float64(d1);
}
void HELPER(neon_qzip32)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm0 = float64_val(env->vfp.regs[rm]);
uint64_t zm1 = float64_val(env->vfp.regs[rm + 1]);
uint64_t zd0 = float64_val(env->vfp.regs[rd]);
uint64_t zd1 = float64_val(env->vfp.regs[rd + 1]);
uint64_t d0 = ELEM(zd0, 0, 32) | (ELEM(zm0, 0, 32) << 32);
uint64_t d1 = ELEM(zd0, 1, 32) | (ELEM(zm0, 1, 32) << 32);
uint64_t m0 = ELEM(zd1, 0, 32) | (ELEM(zm1, 0, 32) << 32);
uint64_t m1 = ELEM(zd1, 1, 32) | (ELEM(zm1, 1, 32) << 32);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rm + 1] = make_float64(m1);
env->vfp.regs[rd] = make_float64(d0);
env->vfp.regs[rd + 1] = make_float64(d1);
}
void HELPER(neon_zip8)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm = float64_val(env->vfp.regs[rm]);
uint64_t zd = float64_val(env->vfp.regs[rd]);
uint64_t d0 = ELEM(zd, 0, 8) | (ELEM(zm, 0, 8) << 8)
| (ELEM(zd, 1, 8) << 16) | (ELEM(zm, 1, 8) << 24)
| (ELEM(zd, 2, 8) << 32) | (ELEM(zm, 2, 8) << 40)
| (ELEM(zd, 3, 8) << 48) | (ELEM(zm, 3, 8) << 56);
uint64_t m0 = ELEM(zd, 4, 8) | (ELEM(zm, 4, 8) << 8)
| (ELEM(zd, 5, 8) << 16) | (ELEM(zm, 5, 8) << 24)
| (ELEM(zd, 6, 8) << 32) | (ELEM(zm, 6, 8) << 40)
| (ELEM(zd, 7, 8) << 48) | (ELEM(zm, 7, 8) << 56);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rd] = make_float64(d0);
}
void HELPER(neon_zip16)(CPUARMState *env, uint32_t rd, uint32_t rm)
{
uint64_t zm = float64_val(env->vfp.regs[rm]);
uint64_t zd = float64_val(env->vfp.regs[rd]);
uint64_t d0 = ELEM(zd, 0, 16) | (ELEM(zm, 0, 16) << 16)
| (ELEM(zd, 1, 16) << 32) | (ELEM(zm, 1, 16) << 48);
uint64_t m0 = ELEM(zd, 2, 16) | (ELEM(zm, 2, 16) << 16)
| (ELEM(zd, 3, 16) << 32) | (ELEM(zm, 3, 16) << 48);
env->vfp.regs[rm] = make_float64(m0);
env->vfp.regs[rd] = make_float64(d0);
}
|
cherry-wb/qemu-dbaf
|
target-arm/neon_helper.c
|
C
|
gpl-2.0
| 59,592
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace CPUMonitor_1
{
public class Monitor
{
private bool finish = false;
private int interval;
private string filename;
private LinkedList<string> processes;
LinkedList<MonitorResource> resources;
public void ThreadProc()
{
this.start();
}
public void start()
{
finish = false;
while (!finish)
{
Thread.Sleep(this.interval);
foreach (MonitorResource resource in resources)
{
resource.captureValue();
}
}
}
public void stop()
{
finish = true;
foreach (MonitorResource resource in resources)
{
resource.saveResults(this.filename);
}
}
public void prepareMonitoring()
{
this.resources = new LinkedList<MonitorResource>();
this.resources.AddLast(new MemoryMonitor());
this.resources.AddLast(new DiskResource());
this.resources.AddLast(new CPUMonitor(this.processes));
foreach (MonitorResource resource in this.resources)
{
resource.prepareMonitoring();
}
}
public void setInterval(int interval)
{
this.interval = interval;
}
public void setFilename(string filename)
{
this.filename = filename;
}
public void setProcess(LinkedList<string> processes)
{
this.processes = processes;
}
/*static void Main(string[] args)
{
CPUMonitor monitor = new CPUMonitor();
Thread t = new Thread(new ThreadStart(CPUMonitor.ThreadProc));
t.Start();
Thread.Sleep(12000);
monitor.end();
}*/
}
}
|
Cotes/CPUMonitor
|
CPUMonitor_1/Monitor.cs
|
C#
|
gpl-2.0
| 2,046
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-22 14:09
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('eighth', '0036_eighthscheduledactivity_administrative'),
('eighth', '0037_auto_20160307_2342'),
]
|
jacobajit/ion
|
intranet/apps/eighth/migrations/0038_merge.py
|
Python
|
gpl-2.0
| 329
|
<div class="nav">{nav}</div>
<hr />
<div class="s">{state_msg}</div>
<form action="?phpmussel-page=config" method="POST">
<div style="display:none">{Indexes}</div>
<table>
<tr><td class="ng2"><div class="s">{link_config}</div></td></tr>
<tr>
<td class="ng1">
<div class="s">{tip_see_the_documentation}<hr /><em>{label_active_config_file}<span class="txtRd">{ActiveConfigFile}</span></em><hr /></div>
<div class="bNav"><input type="submit" value="{field_update}" /></div>
</td>
</tr>
</table>
{ConfigFields}
<table><tr><td class="ng1"><div class="bNav"><input type="submit" value="{field_update}" /></div></td></tr></table>
</form>
|
DanielRuf/phpMussel-themes
|
FE/fullmoon/_config.html
|
HTML
|
gpl-2.0
| 705
|
/* vim: set sw=4 sts=4 et foldmethod=syntax : */
/*
* Copyright (c) 2008, 2010 Ciaran McCreesh
*
* This file is part of the Paludis package manager. Paludis 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.
*
* Paludis 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
*/
#ifndef PALUDIS_GUARD_SRC_CLIENTS_CAVE_FORMAT_GENERAL_HH
#define PALUDIS_GUARD_SRC_CLIENTS_CAVE_FORMAT_GENERAL_HH 1
#include <paludis/util/attributes.hh>
#include <string>
namespace paludis
{
namespace cave
{
std::string format_general_s(const std::string & f, const std::string & s)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_si(const std::string & f, const std::string & s, const int i)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_sr(const std::string & f, const std::string & s, const std::string & r)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_kv(const std::string & f, const std::string & k, const std::string & v)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_rhvib(const std::string & f, const std::string & r,
const std::string & h, const std::string & v, const int i, const bool b)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_spad(const std::string & f, const std::string & s,
const int p, const int a, const int d)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_i(const std::string & f, const int i)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
std::string format_general_his(const std::string & f, const std::string & h, const int i, const std::string & s)
PALUDIS_VISIBLE PALUDIS_ATTRIBUTE((warn_unused_result));
}
}
#endif
|
pioto/paludis-pioto
|
src/clients/cave/format_general.hh
|
C++
|
gpl-2.0
| 2,493
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2007 - 2009, Digium, Inc.
*
* Joshua Colp <jcolp@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
* \brief Channel Bridging API
* \author Joshua Colp <jcolp@digium.com>
* \ref AstBridging
*/
/*!
* \page AstBridging Channel Bridging API
*
* The purpose of this API is to provide an easy and flexible way to bridge
* channels of different technologies with different features.
*
* Bridging technologies provide the mechanism that do the actual handling
* of frames between channels. They provide capability information, codec information,
* and preference value to assist the bridging core in choosing a bridging technology when
* creating a bridge. Different bridges may use different bridging technologies based on needs
* but once chosen they all operate under the same premise; they receive frames and send frames.
*
* Bridges are a combination of bridging technology, channels, and features. A
* developer creates a new bridge based on what they are currently expecting to do
* with it or what they will do with it in the future. The bridging core determines what
* available bridging technology will best fit the requirements and creates a new bridge.
* Once created, channels can be added to the bridge in a blocking or non-blocking fashion.
*
* Features are such things as channel muting or DTMF based features such as attended transfer,
* blind transfer, and hangup. Feature information must be set at the most granular level, on
* the channel. While you can use features on a global scope the presence of a feature structure
* on the channel will override the global scope. An example would be having the bridge muted
* at global scope and attended transfer enabled on a channel. Since the channel itself is not muted
* it would be able to speak.
*
* Feature hooks allow a developer to tell the bridging core that when a DTMF string
* is received from a channel a callback should be called in their application. For
* example, a conference bridge application may want to provide an IVR to control various
* settings on the conference bridge. This can be accomplished by attaching a feature hook
* that calls an IVR function when a DTMF string is entered.
*
*/
#ifndef _ASTERISK_BRIDGING_H
#define _ASTERISK_BRIDGING_H
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#include "asterisk/bridging_features.h"
#include "asterisk/dsp.h"
/*! \brief Capabilities for a bridge technology */
enum ast_bridge_capability {
/*! Bridge is only capable of mixing 2 channels */
AST_BRIDGE_CAPABILITY_1TO1MIX = (1 << 1),
/*! Bridge is capable of mixing 2 or more channels */
AST_BRIDGE_CAPABILITY_MULTIMIX = (1 << 2),
/*! Bridge should natively bridge two channels if possible */
AST_BRIDGE_CAPABILITY_NATIVE = (1 << 3),
/*! Bridge should run using the multithreaded model */
AST_BRIDGE_CAPABILITY_MULTITHREADED = (1 << 4),
/*! Bridge should run a central bridge thread */
AST_BRIDGE_CAPABILITY_THREAD = (1 << 5),
/*! Bridge technology can do video mixing (or something along those lines) */
AST_BRIDGE_CAPABILITY_VIDEO = (1 << 6),
/*! Bridge technology can optimize things based on who is talking */
AST_BRIDGE_CAPABILITY_OPTIMIZE = (1 << 7),
};
/*! \brief State information about a bridged channel */
enum ast_bridge_channel_state {
/*! Waiting for a signal */
AST_BRIDGE_CHANNEL_STATE_WAIT = 0,
/*! Bridged channel has ended itself (it has hung up) */
AST_BRIDGE_CHANNEL_STATE_END,
/*! Bridged channel should be hung up */
AST_BRIDGE_CHANNEL_STATE_HANGUP,
/*! Bridged channel should be removed from the bridge without being hung up */
AST_BRIDGE_CHANNEL_STATE_DEPART,
/*! Bridged channel is executing a feature hook */
AST_BRIDGE_CHANNEL_STATE_FEATURE,
/*! Bridged channel is sending a DTMF stream out */
AST_BRIDGE_CHANNEL_STATE_DTMF,
/*! Bridged channel began talking */
AST_BRIDGE_CHANNEL_STATE_START_TALKING,
/*! Bridged channel has stopped talking */
AST_BRIDGE_CHANNEL_STATE_STOP_TALKING,
};
/*! \brief Return values for bridge technology write function */
enum ast_bridge_write_result {
/*! Bridge technology wrote out frame fine */
AST_BRIDGE_WRITE_SUCCESS = 0,
/*! Bridge technology attempted to write out the frame but failed */
AST_BRIDGE_WRITE_FAILED,
/*! Bridge technology does not support writing out a frame of this type */
AST_BRIDGE_WRITE_UNSUPPORTED,
};
struct ast_bridge_technology;
struct ast_bridge;
/*!
* \brief Structure specific to bridge technologies capable of
* performing talking optimizations.
*/
struct ast_bridge_tech_optimizations {
/*! The amount of time in ms that talking must be detected before
* the dsp determines that talking has occurred */
unsigned int talking_threshold;
/*! The amount of time in ms that silence must be detected before
* the dsp determines that talking has stopped */
unsigned int silence_threshold;
/*! Whether or not the bridging technology should drop audio
* detected as silence from the mix. */
unsigned int drop_silence:1;
};
/*!
* \brief Structure that contains information regarding a channel in a bridge
*/
struct ast_bridge_channel {
/*! Lock to protect this data structure */
ast_mutex_t lock;
/*! Condition, used if we want to wake up a thread waiting on the bridged channel */
ast_cond_t cond;
/*! Current bridged channel state */
enum ast_bridge_channel_state state;
/*! Asterisk channel participating in the bridge */
struct ast_channel *chan;
/*! Asterisk channel we are swapping with (if swapping) */
struct ast_channel *swap;
/*! Bridge this channel is participating in */
struct ast_bridge *bridge;
/*! Private information unique to the bridge technology */
void *bridge_pvt;
/*! Thread handling the bridged channel */
pthread_t thread;
/*! Additional file descriptors to look at */
int fds[4];
/*! Bit to indicate whether the channel is suspended from the bridge or not */
unsigned int suspended:1;
/*! Bit to indicate if a imparted channel is allowed to get hungup after leaving the bridge by the bridging core. */
unsigned int allow_impart_hangup:1;
/*! Features structure for features that are specific to this channel */
struct ast_bridge_features *features;
/*! Technology optimization parameters used by bridging technologies capable of
* optimizing based upon talk detection. */
struct ast_bridge_tech_optimizations tech_args;
/*! Queue of DTMF digits used for DTMF streaming */
char dtmf_stream_q[8];
/*! Call ID associated with bridge channel */
struct ast_callid *callid;
/*! Linked list information */
AST_LIST_ENTRY(ast_bridge_channel) entry;
};
enum ast_bridge_video_mode_type {
/*! Video is not allowed in the bridge */
AST_BRIDGE_VIDEO_MODE_NONE = 0,
/*! A single user is picked as the only distributed of video across the bridge */
AST_BRIDGE_VIDEO_MODE_SINGLE_SRC,
/*! A single user's video feed is distributed to all bridge channels, but
* that feed is automatically picked based on who is talking the most. */
AST_BRIDGE_VIDEO_MODE_TALKER_SRC,
};
/*! This is used for both SINGLE_SRC mode to set what channel
* should be the current single video feed */
struct ast_bridge_video_single_src_data {
/*! Only accept video coming from this channel */
struct ast_channel *chan_vsrc;
};
/*! This is used for both SINGLE_SRC_TALKER mode to set what channel
* should be the current single video feed */
struct ast_bridge_video_talker_src_data {
/*! Only accept video coming from this channel */
struct ast_channel *chan_vsrc;
int average_talking_energy;
/*! Current talker see's this person */
struct ast_channel *chan_old_vsrc;
};
struct ast_bridge_video_mode {
enum ast_bridge_video_mode_type mode;
/* Add data for all the video modes here. */
union {
struct ast_bridge_video_single_src_data single_src_data;
struct ast_bridge_video_talker_src_data talker_src_data;
} mode_data;
};
/*!
* \brief Structure that contains information about a bridge
*/
struct ast_bridge {
/*! Number of channels participating in the bridge */
int num;
/*! The video mode this bridge is using */
struct ast_bridge_video_mode video_mode;
/*! The internal sample rate this bridge is mixed at when multiple channels are being mixed.
* If this value is 0, the bridge technology may auto adjust the internal mixing rate. */
unsigned int internal_sample_rate;
/*! The mixing interval indicates how quickly the bridges internal mixing should occur
* for bridge technologies that mix audio. When set to 0, the bridge tech must choose a
* default interval for itself. */
unsigned int internal_mixing_interval;
/*! Bit to indicate that the bridge thread is waiting on channels in the bridge array */
unsigned int waiting:1;
/*! Bit to indicate the bridge thread should stop */
unsigned int stop:1;
/*! Bit to indicate the bridge thread should refresh itself */
unsigned int refresh:1;
/*! Bridge flags to tweak behavior */
struct ast_flags feature_flags;
/*! Bridge technology that is handling the bridge */
struct ast_bridge_technology *technology;
/*! Private information unique to the bridge technology */
void *bridge_pvt;
/*! Thread running the bridge */
pthread_t thread;
/*! Enabled features information */
struct ast_bridge_features features;
/*! Array of channels that the bridge thread is currently handling */
struct ast_channel **array;
/*! Number of channels in the above array */
size_t array_num;
/*! Number of channels the array can handle */
size_t array_size;
/*! Call ID associated with the bridge */
struct ast_callid *callid;
/*! Linked list of channels participating in the bridge */
AST_LIST_HEAD_NOLOCK(, ast_bridge_channel) channels;
};
/*! \brief Create a new bridge
*
* \param capabilities The capabilities that we require to be used on the bridge
* \param flags Flags that will alter the behavior of the bridge
*
* \retval a pointer to a new bridge on success
* \retval NULL on failure
*
* Example usage:
*
* \code
* struct ast_bridge *bridge;
* bridge = ast_bridge_new(AST_BRIDGE_CAPABILITY_1TO1MIX, AST_BRIDGE_FLAG_DISSOLVE);
* \endcode
*
* This creates a simple two party bridge that will be destroyed once one of
* the channels hangs up.
*/
struct ast_bridge *ast_bridge_new(uint32_t capabilities, int flags);
/*!
* \brief Lock the bridge.
*
* \param bridge Bridge to lock
*
* \return Nothing
*/
#define ast_bridge_lock(bridge) _ast_bridge_lock(bridge, __FILE__, __PRETTY_FUNCTION__, __LINE__, #bridge)
static inline void _ast_bridge_lock(struct ast_bridge *bridge, const char *file, const char *function, int line, const char *var)
{
__ao2_lock(bridge, AO2_LOCK_REQ_MUTEX, file, function, line, var);
}
/*!
* \brief Unlock the bridge.
*
* \param bridge Bridge to unlock
*
* \return Nothing
*/
#define ast_bridge_unlock(bridge) _ast_bridge_unlock(bridge, __FILE__, __PRETTY_FUNCTION__, __LINE__, #bridge)
static inline void _ast_bridge_unlock(struct ast_bridge *bridge, const char *file, const char *function, int line, const char *var)
{
__ao2_unlock(bridge, file, function, line, var);
}
/*! \brief See if it is possible to create a bridge
*
* \param capabilities The capabilities that the bridge will use
*
* \retval 1 if possible
* \retval 0 if not possible
*
* Example usage:
*
* \code
* int possible = ast_bridge_check(AST_BRIDGE_CAPABILITY_1TO1MIX);
* \endcode
*
* This sees if it is possible to create a bridge capable of bridging two channels
* together.
*/
int ast_bridge_check(uint32_t capabilities);
/*! \brief Destroy a bridge
*
* \param bridge Bridge to destroy
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_destroy(bridge);
* \endcode
*
* This destroys a bridge that was previously created using ast_bridge_new.
*/
int ast_bridge_destroy(struct ast_bridge *bridge);
/*! \brief Join (blocking) a channel to a bridge
*
* \param bridge Bridge to join
* \param chan Channel to join
* \param swap Channel to swap out if swapping
* \param features Bridge features structure
* \param tech_args Optional Bridging tech optimization parameters for this channel.
*
* \retval state that channel exited the bridge with
*
* Example usage:
*
* \code
* ast_bridge_join(bridge, chan, NULL, NULL);
* \endcode
*
* This adds a channel pointed to by the chan pointer to the bridge pointed to by
* the bridge pointer. This function will not return until the channel has been
* removed from the bridge, swapped out for another channel, or has hung up.
*
* If this channel will be replacing another channel the other channel can be specified
* in the swap parameter. The other channel will be thrown out of the bridge in an
* atomic fashion.
*
* If channel specific features are enabled a pointer to the features structure
* can be specified in the features parameter.
*/
enum ast_bridge_channel_state ast_bridge_join(struct ast_bridge *bridge,
struct ast_channel *chan,
struct ast_channel *swap,
struct ast_bridge_features *features,
struct ast_bridge_tech_optimizations *tech_args);
/*! \brief Impart (non-blocking) a channel on a bridge
*
* \param bridge Bridge to impart on
* \param chan Channel to impart
* \param swap Channel to swap out if swapping
* \param features Bridge features structure
* \param allow_hangup Indicates if the bridge thread should manage hanging up of the channel or not.
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_impart(bridge, chan, NULL, NULL, 0);
* \endcode
*
* This adds a channel pointed to by the chan pointer to the bridge pointed to by
* the bridge pointer. This function will return immediately and will not wait
* until the channel is no longer part of the bridge.
*
* If this channel will be replacing another channel the other channel can be specified
* in the swap parameter. The other channel will be thrown out of the bridge in an
* atomic fashion.
*
* If channel specific features are enabled a pointer to the features structure
* can be specified in the features parameter.
*/
int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features, int allow_hangup);
/*! \brief Depart a channel from a bridge
*
* \param bridge Bridge to depart from
* \param chan Channel to depart
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_depart(bridge, chan);
* \endcode
*
* This removes the channel pointed to by the chan pointer from the bridge
* pointed to by the bridge pointer and gives control to the calling thread.
* This does not hang up the channel.
*
* \note This API call can only be used on channels that were added to the bridge
* using the ast_bridge_impart API call.
*/
int ast_bridge_depart(struct ast_bridge *bridge, struct ast_channel *chan);
/*! \brief Remove a channel from a bridge
*
* \param bridge Bridge that the channel is to be removed from
* \param chan Channel to remove
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_remove(bridge, chan);
* \endcode
*
* This removes the channel pointed to by the chan pointer from the bridge
* pointed to by the bridge pointer and requests that it be hung up. Control
* over the channel will NOT be given to the calling thread.
*
* \note This API call can be used on channels that were added to the bridge
* using both ast_bridge_join and ast_bridge_impart.
*/
int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan);
/*! \brief Merge two bridges together
*
* \param bridge0 First bridge
* \param bridge1 Second bridge
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_merge(bridge0, bridge1);
* \endcode
*
* This merges the bridge pointed to by bridge1 with the bridge pointed to by bridge0.
* In reality all of the channels in bridge1 are simply moved to bridge0.
*
* \note The second bridge specified is not destroyed when this operation is
* completed.
*/
int ast_bridge_merge(struct ast_bridge *bridge0, struct ast_bridge *bridge1);
/*! \brief Suspend a channel temporarily from a bridge
*
* \param bridge Bridge to suspend the channel from
* \param chan Channel to suspend
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_suspend(bridge, chan);
* \endcode
*
* This suspends the channel pointed to by chan from the bridge pointed to by bridge temporarily.
* Control of the channel is given to the calling thread. This differs from ast_bridge_depart as
* the channel will not be removed from the bridge.
*
* \note This API call can be used on channels that were added to the bridge
* using both ast_bridge_join and ast_bridge_impart.
*/
int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan);
/*! \brief Unsuspend a channel from a bridge
*
* \param bridge Bridge to unsuspend the channel from
* \param chan Channel to unsuspend
*
* \retval 0 on success
* \retval -1 on failure
*
* Example usage:
*
* \code
* ast_bridge_unsuspend(bridge, chan);
* \endcode
*
* This unsuspends the channel pointed to by chan from the bridge pointed to by bridge.
* The bridge will go back to handling the channel once this function returns.
*
* \note You must not mess with the channel once this function returns.
* Doing so may result in bad things happening.
*/
int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan);
/*! \brief Change the state of a bridged channel
*
* \param bridge_channel Channel to change the state on
* \param new_state The new state to place the channel into
*
* Example usage:
*
* \code
* ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_WAIT);
* \endcode
*
* This places the channel pointed to by bridge_channel into the state
* AST_BRIDGE_CHANNEL_STATE_WAIT.
*
* \note This API call is only meant to be used in feature hook callbacks to
* make sure the channel either hangs up or returns to the bridge.
*/
void ast_bridge_change_state(struct ast_bridge_channel *bridge_channel, enum ast_bridge_channel_state new_state);
/*! \brief Adjust the internal mixing sample rate of a bridge used during
* multimix mode.
*
* \param bridge Channel to change the sample rate on.
* \param sample_rate the sample rate to change to. If a
* value of 0 is passed here, the bridge will be free to pick
* what ever sample rate it chooses.
*
*/
void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate);
/*! \brief Adjust the internal mixing interval of a bridge used during
* multimix mode.
*
* \param bridge Channel to change the sample rate on.
* \param mixing_interval the sample rate to change to. If 0 is set
* the bridge tech is free to choose any mixing interval it uses by default.
*/
void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval);
/*!
* \brief Set a bridge to feed a single video source to all participants.
*/
void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan);
/*!
* \brief Set the bridge to pick the strongest talker supporting
* video as the single source video feed
*/
void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge);
/*!
* \brief Update information about talker energy for talker src video mode.
*/
void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyfame);
/*!
* \brief Returns the number of video sources currently active in the bridge
*/
int ast_bridge_number_video_src(struct ast_bridge *bridge);
/*!
* \brief Determine if a channel is a video src for the bridge
*
* \retval 0 Not a current video source of the bridge.
* \retval None 0, is a video source of the bridge, The number
* returned represents the priority this video stream has
* on the bridge where 1 is the highest priority.
*/
int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan);
/*!
* \brief remove a channel as a source of video for the bridge.
*/
void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif /* _ASTERISK_BRIDGING_H */
|
chiefdome/asterisk
|
include/asterisk/bridging.h
|
C
|
gpl-2.0
| 20,942
|
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.annotate;
import java.lang.annotation.*;
/**
* This annotation is used to filter out classes, methods and fields from the boot image
* based on the JDK used for building. For example, to specify that a method should only be
* included in an image built using at least JDK 7, this annotation is used as follows:
* <pre>
* JDK_VERSION("1.7")
* public void method() { ... }
* </pre>
*
* The value of the {@code version} element is a string used to match against the
* JDK version. The {@link com.sun.max.vm.jdk.JDK#thisVersionOrNewer(JDK_VERSION)} method
* performs the test.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD})
public @interface JDK_VERSION {
/**
* Specifies a JDK version. The annotated element is included if the JDK version used to
* build is at least the specified version. The version string must be in "x.y" format.
*/
String value() default "";
}
|
arodchen/MaxSim
|
maxine/com.oracle.max.vm/src/com/sun/max/annotate/JDK_VERSION.java
|
Java
|
gpl-2.0
| 2,063
|
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.hotspot.replacements;
import jdk.internal.jvmci.code.*;
import jdk.internal.jvmci.common.*;
import jdk.internal.jvmci.hotspot.*;
import jdk.internal.jvmci.meta.*;
import jdk.internal.jvmci.options.*;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.*;
import static com.oracle.graal.hotspot.replacements.InstanceOfSnippets.Options.*;
import static com.oracle.graal.hotspot.replacements.TypeCheckSnippetUtils.*;
import static com.oracle.graal.nodes.extended.BranchProbabilityNode.*;
import static jdk.internal.jvmci.meta.DeoptimizationAction.*;
import static jdk.internal.jvmci.meta.DeoptimizationReason.*;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.hotspot.meta.*;
import com.oracle.graal.hotspot.nodes.*;
import com.oracle.graal.hotspot.replacements.TypeCheckSnippetUtils.Hints;
import com.oracle.graal.hotspot.word.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.extended.*;
import com.oracle.graal.nodes.java.*;
import com.oracle.graal.nodes.spi.*;
import com.oracle.graal.replacements.*;
import com.oracle.graal.replacements.Snippet.ConstantParameter;
import com.oracle.graal.replacements.Snippet.VarargsParameter;
import com.oracle.graal.replacements.SnippetTemplate.Arguments;
import com.oracle.graal.replacements.SnippetTemplate.SnippetInfo;
import com.oracle.graal.replacements.nodes.*;
/**
* Snippets used for implementing the type test of an instanceof instruction. Since instanceof is a
* floating node, it is lowered separately for each of its usages.
*
* The type tests implemented are described in the paper <a
* href="http://dl.acm.org/citation.cfm?id=583821"> Fast subtype checking in the HotSpot JVM</a> by
* Cliff Click and John Rose.
*/
public class InstanceOfSnippets implements Snippets {
/**
* A test against a set of hints derived from a profile with 100% precise coverage of seen
* types. This snippet deoptimizes on hint miss paths.
*/
@Snippet
public static Object instanceofWithProfile(Object object, @VarargsParameter KlassPointer[] hints, @VarargsParameter boolean[] hintIsPositive, Object trueValue, Object falseValue,
@ConstantParameter boolean nullSeen) {
if (probability(NOT_FREQUENT_PROBABILITY, object == null)) {
isNull.inc();
if (!nullSeen) {
// See comment below for other deoptimization path; the
// same reasoning applies here.
DeoptimizeNode.deopt(InvalidateReprofile, OptimizedTypeCheckViolated);
}
return falseValue;
}
GuardingNode anchorNode = SnippetAnchorNode.anchor();
KlassPointer objectHub = loadHubIntrinsic(object, anchorNode);
// if we get an exact match: succeed immediately
ExplodeLoopNode.explodeLoop();
for (int i = 0; i < hints.length; i++) {
KlassPointer hintHub = hints[i];
boolean positive = hintIsPositive[i];
if (probability(LIKELY_PROBABILITY, hintHub.equal(objectHub))) {
hintsHit.inc();
return positive ? trueValue : falseValue;
}
hintsMiss.inc();
}
// This maybe just be a rare event but it might also indicate a phase change
// in the application. Ideally we want to use DeoptimizationAction.None for
// the former but the cost is too high if indeed it is the latter. As such,
// we defensively opt for InvalidateReprofile.
DeoptimizeNode.deopt(DeoptimizationAction.InvalidateReprofile, OptimizedTypeCheckViolated);
return falseValue;
}
/**
* A test against a final type.
*/
@Snippet
public static Object instanceofExact(Object object, KlassPointer exactHub, Object trueValue, Object falseValue) {
if (probability(NOT_FREQUENT_PROBABILITY, object == null)) {
isNull.inc();
return falseValue;
}
GuardingNode anchorNode = SnippetAnchorNode.anchor();
KlassPointer objectHub = loadHubIntrinsic(object, anchorNode);
if (probability(LIKELY_PROBABILITY, objectHub.notEqual(exactHub))) {
exactMiss.inc();
return falseValue;
}
exactHit.inc();
return trueValue;
}
/**
* A test against a primary type.
*/
@Snippet
public static Object instanceofPrimary(KlassPointer hub, Object object, @ConstantParameter int superCheckOffset, Object trueValue, Object falseValue) {
if (probability(NOT_FREQUENT_PROBABILITY, object == null)) {
isNull.inc();
return falseValue;
}
GuardingNode anchorNode = SnippetAnchorNode.anchor();
KlassPointer objectHub = loadHubIntrinsic(object, anchorNode);
if (probability(NOT_LIKELY_PROBABILITY, objectHub.readKlassPointer(superCheckOffset, PRIMARY_SUPERS_LOCATION).notEqual(hub))) {
displayMiss.inc();
return falseValue;
}
displayHit.inc();
return trueValue;
}
/**
* A test against a restricted secondary type type.
*/
@Snippet
public static Object instanceofSecondary(KlassPointer hub, Object object, @VarargsParameter KlassPointer[] hints, @VarargsParameter boolean[] hintIsPositive, Object trueValue, Object falseValue) {
if (probability(NOT_FREQUENT_PROBABILITY, object == null)) {
isNull.inc();
return falseValue;
}
GuardingNode anchorNode = SnippetAnchorNode.anchor();
KlassPointer objectHub = loadHubIntrinsic(object, anchorNode);
// if we get an exact match: succeed immediately
ExplodeLoopNode.explodeLoop();
for (int i = 0; i < hints.length; i++) {
KlassPointer hintHub = hints[i];
boolean positive = hintIsPositive[i];
if (probability(NOT_FREQUENT_PROBABILITY, hintHub.equal(objectHub))) {
hintsHit.inc();
return positive ? trueValue : falseValue;
}
}
hintsMiss.inc();
if (!checkSecondarySubType(hub, objectHub)) {
return falseValue;
}
return trueValue;
}
/**
* Type test used when the type being tested against is not known at compile time.
*/
@Snippet
public static Object instanceofDynamic(Class<?> mirror, Object object, Object trueValue, Object falseValue) {
if (probability(NOT_FREQUENT_PROBABILITY, object == null)) {
isNull.inc();
return falseValue;
}
GuardingNode anchorNode = SnippetAnchorNode.anchor();
KlassPointer hub = ClassGetHubNode.readClass(mirror, anchorNode);
KlassPointer objectHub = loadHubIntrinsic(object, anchorNode);
if (hub.isNull() || !checkUnknownSubType(hub, objectHub)) {
return falseValue;
}
return trueValue;
}
@Snippet
public static Object isAssignableFrom(Class<?> thisClass, Class<?> otherClass, Object trueValue, Object falseValue) {
if (BranchProbabilityNode.probability(BranchProbabilityNode.NOT_FREQUENT_PROBABILITY, otherClass == null)) {
DeoptimizeNode.deopt(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.NullCheckException);
return false;
}
GuardingNode anchorNode = SnippetAnchorNode.anchor();
KlassPointer thisHub = ClassGetHubNode.readClass(thisClass, anchorNode);
KlassPointer otherHub = ClassGetHubNode.readClass(otherClass, anchorNode);
if (thisHub.isNull() || otherHub.isNull()) {
// primitive types, only true if equal.
return thisClass == otherClass ? trueValue : falseValue;
}
if (!TypeCheckSnippetUtils.checkUnknownSubType(thisHub, otherHub)) {
return falseValue;
}
return trueValue;
}
static class Options {
// @formatter:off
@Option(help = "If the probability that a type check will hit one the profiled types (up to " +
"TypeCheckMaxHints) is below this value, the type check will be compiled without profiling info", type = OptionType.Expert)
static final OptionValue<Double> TypeCheckMinProfileHitProbability = new OptionValue<>(0.5);
@Option(help = "The maximum number of profiled types that will be used when compiling a profiled type check. " +
"Note that TypeCheckMinProfileHitProbability also influences whether profiling info is used in compiled type checks.", type = OptionType.Expert)
static final OptionValue<Integer> TypeCheckMaxHints = new OptionValue<>(2);
// @formatter:on
}
public static class Templates extends InstanceOfSnippetsTemplates {
private final SnippetInfo instanceofWithProfile = snippet(InstanceOfSnippets.class, "instanceofWithProfile");
private final SnippetInfo instanceofExact = snippet(InstanceOfSnippets.class, "instanceofExact");
private final SnippetInfo instanceofPrimary = snippet(InstanceOfSnippets.class, "instanceofPrimary");
private final SnippetInfo instanceofSecondary = snippet(InstanceOfSnippets.class, "instanceofSecondary", SECONDARY_SUPER_CACHE_LOCATION);
private final SnippetInfo instanceofDynamic = snippet(InstanceOfSnippets.class, "instanceofDynamic", SECONDARY_SUPER_CACHE_LOCATION);
private final SnippetInfo isAssignableFrom = snippet(InstanceOfSnippets.class, "isAssignableFrom", SECONDARY_SUPER_CACHE_LOCATION);
public Templates(HotSpotProviders providers, TargetDescription target) {
super(providers, providers.getSnippetReflection(), target);
}
@Override
protected Arguments makeArguments(InstanceOfUsageReplacer replacer, LoweringTool tool) {
Stamp hubStamp = tool.getStampProvider().createHubStamp(true);
if (replacer.instanceOf instanceof InstanceOfNode) {
InstanceOfNode instanceOf = (InstanceOfNode) replacer.instanceOf;
ValueNode object = instanceOf.getValue();
Assumptions assumptions = instanceOf.graph().getAssumptions();
TypeCheckHints hintInfo = new TypeCheckHints(instanceOf.type(), instanceOf.profile(), assumptions, TypeCheckMinProfileHitProbability.getValue(), TypeCheckMaxHints.getValue());
final HotSpotResolvedObjectType type = (HotSpotResolvedObjectType) instanceOf.type();
ConstantNode hub = ConstantNode.forConstant(hubStamp, type.klass(), providers.getMetaAccess(), instanceOf.graph());
Arguments args;
StructuredGraph graph = instanceOf.graph();
if (hintInfo.hintHitProbability >= 1.0 && hintInfo.exact == null) {
Hints hints = createHints(hintInfo, providers.getMetaAccess(), false, graph, tool);
args = new Arguments(instanceofWithProfile, graph.getGuardsStage(), tool.getLoweringStage());
args.add("object", object);
args.addVarargs("hints", KlassPointer.class, hubStamp, hints.hubs);
args.addVarargs("hintIsPositive", boolean.class, StampFactory.forKind(Kind.Boolean), hints.isPositive);
} else if (hintInfo.exact != null) {
args = new Arguments(instanceofExact, graph.getGuardsStage(), tool.getLoweringStage());
args.add("object", object);
args.add("exactHub", ConstantNode.forConstant(hubStamp, ((HotSpotResolvedObjectType) hintInfo.exact).klass(), providers.getMetaAccess(), graph));
} else if (type.isPrimaryType()) {
args = new Arguments(instanceofPrimary, graph.getGuardsStage(), tool.getLoweringStage());
args.add("hub", hub);
args.add("object", object);
args.addConst("superCheckOffset", type.superCheckOffset());
} else {
Hints hints = createHints(hintInfo, providers.getMetaAccess(), false, graph, tool);
args = new Arguments(instanceofSecondary, graph.getGuardsStage(), tool.getLoweringStage());
args.add("hub", hub);
args.add("object", object);
args.addVarargs("hints", KlassPointer.class, hubStamp, hints.hubs);
args.addVarargs("hintIsPositive", boolean.class, StampFactory.forKind(Kind.Boolean), hints.isPositive);
}
args.add("trueValue", replacer.trueValue);
args.add("falseValue", replacer.falseValue);
if (hintInfo.hintHitProbability >= 1.0 && hintInfo.exact == null) {
args.addConst("nullSeen", hintInfo.profile.getNullSeen() != TriState.FALSE);
}
return args;
} else if (replacer.instanceOf instanceof TypeCheckNode) {
TypeCheckNode typeCheck = (TypeCheckNode) replacer.instanceOf;
ValueNode object = typeCheck.getValue();
Arguments args = new Arguments(instanceofExact, typeCheck.graph().getGuardsStage(), tool.getLoweringStage());
args.add("object", object);
args.add("exactHub", ConstantNode.forConstant(hubStamp, ((HotSpotResolvedObjectType) typeCheck.type()).klass(), providers.getMetaAccess(), typeCheck.graph()));
args.add("trueValue", replacer.trueValue);
args.add("falseValue", replacer.falseValue);
return args;
} else if (replacer.instanceOf instanceof InstanceOfDynamicNode) {
InstanceOfDynamicNode instanceOf = (InstanceOfDynamicNode) replacer.instanceOf;
ValueNode object = instanceOf.object();
Arguments args = new Arguments(instanceofDynamic, instanceOf.graph().getGuardsStage(), tool.getLoweringStage());
args.add("mirror", instanceOf.mirror());
args.add("object", object);
args.add("trueValue", replacer.trueValue);
args.add("falseValue", replacer.falseValue);
return args;
} else if (replacer.instanceOf instanceof ClassIsAssignableFromNode) {
ClassIsAssignableFromNode isAssignable = (ClassIsAssignableFromNode) replacer.instanceOf;
Arguments args = new Arguments(isAssignableFrom, isAssignable.graph().getGuardsStage(), tool.getLoweringStage());
args.add("thisClass", isAssignable.getThisClass());
args.add("otherClass", isAssignable.getOtherClass());
args.add("trueValue", replacer.trueValue);
args.add("falseValue", replacer.falseValue);
return args;
} else {
throw JVMCIError.shouldNotReachHere();
}
}
}
}
|
smarr/GraalVM
|
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/replacements/InstanceOfSnippets.java
|
Java
|
gpl-2.0
| 15,976
|
<?php
if(!defined('InEmpireCMS'))
{
exit();
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?=$grpagetitle?></title>
<meta name="keywords" content="<?=$ecms_gr[keyboard]?>" />
<meta name="description" content="<?=nl2br($ecms_gr[smalltext])?>" />
<meta name="author" content="哈德逊瓷砖网络营销部Chan,哈德逊瓷砖官网 - www.hudsonhome.cn" />
<link rel="stylesheet" type="text/css" href="http://www.hudson.com/skin/default/css/style.css" />
<script type="text/javascript" src="http://www.hudson.com/skin/default/js/jquery.js"></script>
<script type="text/javascript" src="http://www.hudson.com/skin/default/js/jqnav.js"></script>
<script src="http://www.hudson.com/skin/default/js/tab.js" type="text/javascript"></script>
<!--[if lte IE 6]>
<SCRIPT src="http://www.hudson.com/skin/default/js/iepng.js" type="text/javascript"></SCRIPT>
<script>
EvPNG.fix('div, ul, img, li, input');
</script>
<![endif]-->
</head>
<body class="bgmm">
<!-- 头部开始 -->
<script type="text/javascript">
function uaredirect(murl){
try {
if(document.getElementById("bdmark") != null){
return;
}
var urlhash = window.location.hash;
if (!urlhash.match("fromapp")){
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i))) {
location.replace(murl);
}
}
} catch(err){}
}
uaredirect("http://www.hudson.com/wap/");
</script>
<a name="gotop"></a>
<div class="go">
<a title="返回顶部" class="top" href="#gotop">
<img src="http://www.hudson.com/skin/default/images/top2.png" width="50" height="50" /></a> <a class="top" href="#gotop">
<img src="http://www.hudson.com/skin/default/images/back2.png" width="50" height="50" /></a>
</div>
<div class="wrap">
<div name="gotop">
</div>
<div class="top">
<div class="topbox2">
<div class="searchcc">
<input name="txtSelAll" id="txtSelAll" type="text" class="in_sin" value="关键字" onblur="if (this.value=='')this.value='关键字';"
onclick="if (this.value=='关键字')this.value=''" /><input name="btnSearch" id="btnSearch"
type="button" value="" class="ins_b" onclick="checkAll();" />
</div>
<div class="lan2">
<img src="http://www.hudson.com/skin/default/images/icon_8.png" width="16" height="11" align="absmiddle" />
中国
</div>
</div>
<div class="topbox1">
<a target="_blank" href="http://hudson.tmall.com/shop/view_shop.htm?spm=a1z10.4.w5001-4530759858.6.yRhs4b&scene=taobao_shop">官方商城</a>
关注我们:<a target="_blank" rel="nofollow" href="http://weibo.com/1hudson">
<img src="http://www.hudson.com/skin/default/images/icon_4.png" width="16" height="16" align="absmiddle" alt="新浪微博" title="新浪微博" />
</a>
<a target="_blank" rel="nofollow" href="http://t.qq.com/hudson2006">
<img src="http://www.hudson.com/skin/default/images/icon_5.png" width="16" height="16" align="absmiddle" alt="腾讯微博" title="腾讯微博" />
</a>
<a rel="nofollow" href="http://www.jiathis.com/share/" class="jiathis" target="_blank">
<img src="http://www.hudson.com/skin/default/images/icon_6.png" width="16" height="16" align="absmiddle" />
</a>
</div>
</div>
</div>
<div class="head">
<div class="navbg" id="navbg">
</div>
<div class="wrap">
<div class="headone">
<h1>
<a href="http://www.hudson.com/">
<img src="http://www.hudson.com/skin/default/images/logo.png"/></a></h1>
<div class="nav">
<ul class="navlist">
<li><a href="http://www.hudson.com/">首 页</a></li>
</ul>
<ul class="navlist" id="nav">
<li class="lihover"><a href="http://www.hudson.com/zjhdx/2014-02-22/6.html">走进哈德逊</a>
<div class="navbox">
<p class="boxlist">
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select titleurl,title from phome_ecms_news where classid=2 order by id asc',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<span><a href="<?=$bqr[titleurl]?>"><?=$bqr[title]?></a></span>
<?php
}
}
?>
</p>
</div>
</li>
<li class="lihover"><a href="http://www.hudson.com/xwzx/hdzq/">新闻资讯</a>
<div class="navbox">
<p class="boxlist" style="padding-left: 50px;">
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select classname,classpath from phome_enewsclass where bclassid=3 order by classid asc',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<span><a href="http://www.hudson.com/<?=$bqr[classpath]?>"><?=$bqr[classname]?></a></span>
<?php
}
}
?>
</p>
</div>
</li>
<li class="bg lihover"><a href="http://www.hudson.com/cpyfw/zxcp/">产品与服务</a>
<div class="navbox">
<p class="boxlist" style="padding-left: 180px;">
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select classid,classname,classpath from phome_enewsclass where bclassid=4 order by classid asc',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<?php
if($bqr[classid]==13){
$bqr[classpath] = 'cpyfw/zxfk/2014-03-02/65.html';
}
?>
<span><a href="http://www.hudson.com/<?=$bqr[classpath]?>"><?=$bqr[classname]?></a></span>
<?php
}
}
?>
</p>
</div>
</li>
<li class="bg lihover"><a href="http://www.hudson.com/cptyg/alzs/">产品体验馆</a>
<div class="navbox">
<p class="boxlist" style="padding-left: 310px;">
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select classid,classname,classpath from phome_enewsclass where bclassid=5 order by classid asc',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<?php
if($bqr[classid]==15){
$bqr[classpath] = 'cptyg/shtyg/2014-03-07/24.html';
}
?>
<span><a href="http://www.hudson.com/<?=$bqr[classpath]?>"><?=$bqr[classname]?></a></span>
<?php
}
}
?>
</p>
</div>
</li>
<li class="bg lihover"><a href="http://www.hudson.com/rlzy/">人力资源</a>
<div class="navbox">
<p class="boxlist" style="padding-left: 280px;">
<span><a href="http://www.hudson.com/rlzy/rcg/2014-03-02/44.html">人才观</a></span>
<span><a href="http://www.hudson.com/rlzy/zwfz/2014-03-02/45.html">职位发展</a></span>
<span><a href="http://www.hudson.com/rlzy/xcfl/2014-03-02/46.html">薪酬福利</a></span>
<span><a href="http://www.hudson.com/rlzy/ypzn/2014-03-02/47.html">应聘指南</a></span>
<span><a href="http://www.hudson.com/rlzy/zwlb/">职位列表</a></span>
<span><a href="http://www.hudson.com/rlzy/wzhdx/">我在哈德逊</a></span>
</p>
</div>
</li>
<li class="lihover"><a href="http://hudson.tmall.com" style="font-weight:bold; color:#F00; font-size:20px;" target="_blank">逛商城</a></li>
</ul>
</div>
</div>
</div>
</div>
<!-- 头部结束 -->
<div class=" wrap">
<div class="home">当前位置:<?=$grurl?></div>
</div>
<div class="cls">
</div>
<div class="main">
<div class="wrap">
<div class="bg_t">
</div>
<div class="bg_c">
<div class="mleft">
<div class="mlefttitle">
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select classname from phome_enewsclass where classid='.$class_r[$GLOBALS[navclassid]][bclassid],2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<h2><?=$bqr[classname]?></h2>
<?php
}
}
?>
</div>
<ul class="mleftlist">
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select classid,classname,classpath from phome_enewsclass where bclassid='.$class_r[$GLOBALS[navclassid]][bclassid].' order by classid asc',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<?php
if($bqr[classid]==13){
$bqr[classpath] = 'cpyfw/zxfk/2014-03-02/65.html';
}
?>
<li id="about<?=$bqno?>" class=""><span><a href="http://www.hudson.com/<?=$bqr[classpath]?>" onclick="sethover('about',<?=$bqno?>,4)"><?=$bqr[classname]?></a></span></li>
<?php
}
}
?>
</ul>
</div>
<div class="mright">
<div class="news">
<div class="n_detail">
<h3>
<?=$ecms_gr[title]?>
<p>发布日期:<?=date('Y-m-d H:i:s',$ecms_gr[newstime])?></p>
</h3>
<?=strstr($ecms_gr[newstext],'[!--empirenews.page--]')?'[!--newstext--]':$ecms_gr[newstext]?>
[!--page.url--]
<div class="dlbox">
<div class="sxpage">
<p>
<strong>上一篇:</strong><?php
$next_r=$empire->fetch1("select isurl,titleurl,classid,id,title from {$dbtbpre}ecms_".$class_r[$ecms_gr[classid]][tbname]." where id<$ecms_gr[id] and classid='$ecms_gr[classid]' order by id desc limit 1");
if(empty($next_r[id]))
{$infonext="<a href='".$grclassurl."'>返回列表</a>";}
else
{
$nexttitleurl=sys_ReturnBqTitleLink($next_r);
$infonext="<a href='".$nexttitleurl."'>".$next_r[title]."</a>";
}
echo $infonext;
?></p>
<p>
<strong>下一篇:</strong><?php
$next_r=$empire->fetch1("select isurl,titleurl,classid,id,title from {$dbtbpre}ecms_".$class_r[$ecms_gr[classid]][tbname]." where id>$ecms_gr[id] and classid='$ecms_gr[classid]' order by id limit 1");
if(empty($next_r[id]))
{$infonext="<a href='".$grclassurl."'>返回列表</a>";}
else
{
$nexttitleurl=sys_ReturnBqTitleLink($next_r);
$infonext="<a href='".$nexttitleurl."'>".$next_r[title]."</a>";
}
echo $infonext;
?></p>
</div>
<div class="cls">
</div>
<div class="fenxiang">
<!-- JiaThis Button BEGIN -->
<div id="ckepop">
<span class="jiathis_txt">分享到:
<!-- chan baidu begin -->
<a href="javascript:window.open('http://cang.baidu.com/do/add?it='+encodeURIComponent(document.title.substring(0,76))+'&iu='+encodeURIComponent(location.href)+'&fr=ien#nw=1','_blank','scrollbars=no,width=600,height=450,left=75,top=20,status=no,resizable=yes'); void 0" style="color:#000000;text-decoration:none;font-size:12px;font-weight:normal"><span style="padding: 5px 5px 0px; font-size: 12px; margin-left: 10px; cursor: pointer;"><img border="0" alt="添加到百度搜藏" align="absmiddle" src="http://help.baidu.com/resources_new/static/images/code_socang_fav1.jpg?qq-pf-to=pcqq.c2c"> 添加到百度搜藏</span></a>
<!-- chan baidu end-->
</span> <a class="jiathis_button_icons_1"></a><a class="jiathis_button_icons_2">
</a><a class="jiathis_button_icons_3"></a><a class="jiathis_button_icons_4"></a>
<a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis"
target="_blank"></a><a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" src="http://v2.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->
</div>
<div class="cls">
</div>
<div class="fanhui2">
<a href="#">
<img src="http://www.hudson.com/skin/default/images/img_top.jpg" width="44" height="14" /></a> <a href="javascript:history.go(-1);">
<img src="http://www.hudson.com/skin/default/images/img_fanhui.jpg" /></a>
</div>
</div>
</div>
</div>
<div class="cls">
</div>
</div>
</div>
<div class="bg_f">
</div>
</div>
</div>
<div class="cls">
</div>
<!-- 尾部开始 -->
<div class="foot">
<div class="wrap">
<div class="fm_box">
<h3>公司动态</h3>
<ul>
<li><a href="http://www.hudson.com/xwzx/hdzq/">活动专区</a></li>
<li><a href="http://www.hudson.com/xwzx/qyxw/">企业新闻</a></li>
<li><a href="http://www.hudson.com/xwzx/axgy/">爱心公益</a></li>
</ul>
</div>
<div class="fm_box">
<h3>关于哈德逊</h3>
<ul>
<li><a href="http://www.hudson.com/">董事长介绍</a></li>
<li><a href="http://www.hudson.com/zjhdx/2014-02-22/6.html">企业简介</a></li>
<li><a href="http://www.hudson.com/zjhdx/2014-02-22/7.html">企业文化</a></li>
<li><a href="http://www.hudson.com/zjhdx/2014-02-22/8.html">发展历程</a></li>
<li><a href="http://www.hudson.com/zjhdx/2014-02-22/11.html">联系我们</a></li>
<li><a href="http://www.hudson.com/zjhdx/2014-02-22/10.html">哈德逊荣誉</a></li>
</ul>
</div>
<div class="fm_box">
<h3>最新职位</h3>
<ul>
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select title,titleurl from phome_ecms_news where classid=20 order by id desc limit 5',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<li><a href="<?=$bqr[titleurl]?>" title="<?=$bqr[title]?>"><?=esub($bqr[title],14)?></a></li>
<?php
}
}
?>
</ul>
</div>
<div class="fm_box">
<h3>人力资源</h3>
<ul>
<li><a href="http://www.hudson.com/rlzy/rcg/2014-03-02/44.html">人才观</a></li>
<li><a href="http://www.hudson.com/rlzy/zwfz/2014-03-02/45.html">职位发展</a></li>
<li><a href="http://www.hudson.com/rlzy/xcfl/2014-03-02/46.html">薪酬福利</a></li>
<li><a href="http://www.hudson.com/rlzy/ypzn/2014-03-02/47.html">应聘指南</a></li>
<li><a href="">职位列表</a></li>
<li><a href="http://www.hudson.com/rlzy/wzhdx/">我在哈德逊</a></li>
</ul>
</div>
<div class="fm_box" style="margin:0">
<h3>产品</h3>
<ul>
<?php
$bqno=0;
$ecms_bq_sql=sys_ReturnEcmsLoopBq('select classname,classpath from phome_enewsclass where bclassid=11 order by classid desc limit 7',2,24,0);
if($ecms_bq_sql){
while($bqr=$empire->fetch($ecms_bq_sql)){
$bqsr=sys_ReturnEcmsLoopStext($bqr);
$bqno++;
?>
<li><a href="http://www.hudson.com/<?=$bqr[classpath]?>"><?=$bqr[classname]?></a></li>
<?php
}
}
?>
</ul>
</div>
</div>
<div class="mfoot" style=" padding-top: 20px;">
<div class="warp" style=" text-align:center; border-bottom:#999 solid 1px;">
友情链接:
<a href="http://www.hudsonbuy.com/ " target="_blank">建材网上商城</a>
<a href="http://www.chinagzn.com" target="_blank">硅藻泥</a>
<a href="http://www.ganji.com/nuanqi" target="_blank">暖气</a>
<a href="http://www.china-lz.com" target="_blank">天津办公家具</a>
<a href="http://www.xuexi111.com/s/jiaju" target="_blank">家居装修设计</a>
<a href="http://www.reaz.com.cn" target="_blank">高端家居品牌</a>
<a href="http://xining.66zhuang.com" target="_blank">西宁装修网</a>
<a href="http://www.lejj.com/cizhuan/" target="_blank">瓷砖</a>
<a href="http://www.meilele.com/category-cizhuan/" target="_blank">瓷砖</a>
<a href="http://jxyczs.cn/" target="_blank">南昌装修公司</a>
<a href="http://beijing.kuyiso.com/jiancai/" target="_blank">北京建材加盟</a>
<a href="http://www.qianlima.com/zb/area_304/" target="_blank">佛山招标网</a>
<a href="http://www.whczs.com/" target="_blank">南宁装修公司</a>
<a href="http://huiz.pupuwang.com/" target="_blank">惠州商铺转让网</a>
<a href="http://world.fang.com/Singapore/" target="_blank">新加坡买房</a>
<a href="http://zz.huizhuang.com/" target="_blank">郑州装修网</a>
<a href="http://jiancai.11467.com/" target="_blank">中国建筑建材网</a>
<a href="http://bj.ganji.com/chuguijiancai/ " target="_blank">北京橱柜公司</a>
<a href="http://tj.ganji.com/dengshi/ " target="_blank">天津灯饰公司</a>
<a href="http://www.mfj95.com " target="_blank">瓷砖美缝剂</a>
<a href="http://www.zgdbw.cn/ " target="_blank">复合地板品牌 </a>
<script type="text/javascript" src="http://links.webscan.360.cn/index/index/b447b66a05b05015e513cd4b065ed8f6"></script>
</div>
<div class="wrap">
佛山哈德逊股份有限公司©版权所有 保留所有权利 <a href="http://www.hudson.com/wzdt.htm" target="_blank">网站地图</a> 展销中心:+86-757-82278159 客户服务中心:+86-757-82278159
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Faed9e7d575a1cc8a944631fa5314681e' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_5915010'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/stat.php%3Fid%3D5915010%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script><br/>
</div>
</div>
</div>
<!-- 尾部结束 -->
</body>
</html>
|
306076197/hudson
|
e/data/tmp/tempnews1_all.php
|
PHP
|
gpl-2.0
| 21,369
|
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#include "md5.h"
# if __BYTE_ORDER == __BIG_ENDIAN
#define HIGHFIRST
#endif
#ifndef HIGHFIRST
#define byteReverse(buf, len) /* Nothing */
#else
/*
* Note: this code is harmless on little-endian machines.
*/
static void
byteReverse(unsigned char *buf,
unsigned longs)
{
uint32_t t;
do {
t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
}
#endif
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
static void
MD5Transform(uint32_t buf[4],
uint32_t in[16])
{
uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void
MD5Init(struct MD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
void
MD5Update(struct MD5Context *ctx,
const void *data,
unsigned len)
{
const unsigned char *buf = data;
uint32_t t;
/* Update bitcount */
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
ctx->bits[1]++; /* Carry from low to high */
ctx->bits[1] += len >> 29;
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memcpy(ctx->in, buf, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
void
MD5Final(unsigned char digest[16],
struct MD5Context *ctx)
{
unsigned count;
unsigned char *p;
/* Compute number of bytes mod 64 */
count = (ctx->bits[0] >> 3) & 0x3F;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
p = ctx->in + count;
*p++ = 0x80;
/* Bytes of padding needed to make 64 bytes */
count = 64 - 1 - count;
/* Pad out to 56 mod 64 */
if (count < 8)
{
/* Two lots of padding: Pad the first block to 64 bytes */
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
/* Now fill the next block with 56 bytes */
memset(ctx->in, 0, 56);
}
else
{
/* Pad block to 56 bytes */
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
/* Append length in bits and transform */
((uint32_t *) ctx->in)[14] = ctx->bits[0];
((uint32_t *) ctx->in)[15] = ctx->bits[1];
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */
}
/* end of md5.c */
|
eryunyong/easycwmp-1.5.2
|
src/md5.c
|
C
|
gpl-2.0
| 7,734
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by jni4net. See http://jni4net.sourceforge.net/
// Runtime Version:2.0.50727.5456
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace com.google.javascript.jscomp {
#region Component Designer generated code
[global::net.sf.jni4net.attributes.JavaClassAttribute()]
public partial class JSError : global::java.lang.Object {
internal new static global::java.lang.Class staticClass;
internal static global::net.sf.jni4net.jni.MethodId j4n_make0;
internal static global::net.sf.jni4net.jni.MethodId j4n_make1;
internal static global::net.sf.jni4net.jni.MethodId j4n_make2;
internal static global::net.sf.jni4net.jni.MethodId j4n_make3;
internal static global::net.sf.jni4net.jni.MethodId j4n_make4;
internal static global::net.sf.jni4net.jni.MethodId j4n_format5;
internal static global::net.sf.jni4net.jni.MethodId j4n_getType6;
internal static global::net.sf.jni4net.jni.MethodId j4n_getLineNumber7;
internal static global::net.sf.jni4net.jni.MethodId j4n_getCharno8;
internal static global::net.sf.jni4net.jni.MethodId j4n_getNodeSourceOffset9;
internal static global::net.sf.jni4net.jni.MethodId j4n_getNodeLength10;
internal static global::net.sf.jni4net.jni.MethodId j4n_getDefaultLevel11;
internal static global::net.sf.jni4net.jni.FieldId j4n_description12;
internal static global::net.sf.jni4net.jni.FieldId j4n_sourceName13;
internal static global::net.sf.jni4net.jni.FieldId j4n_lineNumber14;
internal static global::net.sf.jni4net.jni.FieldId j4n_level15;
protected JSError(global::net.sf.jni4net.jni.JNIEnv @__env) :
base(@__env) {
}
public static global::java.lang.Class _class {
get {
return global::com.google.javascript.jscomp.JSError.staticClass;
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("Ljava/lang/String;")]
public global::java.lang.String description {
get {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2CpString(@__env, @__env.GetObjectFieldPtr(this, global::com.google.javascript.jscomp.JSError.j4n_description12));
}
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("Ljava/lang/String;")]
public global::java.lang.String sourceName {
get {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2CpString(@__env, @__env.GetObjectFieldPtr(this, global::com.google.javascript.jscomp.JSError.j4n_sourceName13));
}
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("I")]
public int lineNumber {
get {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return ((int)(@__env.GetIntField(this, global::com.google.javascript.jscomp.JSError.j4n_lineNumber14)));
}
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("Lcom/google/javascript/jscomp/CheckLevel;")]
public global::com.google.javascript.jscomp.CheckLevel level {
get {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.CheckLevel>(@__env, @__env.GetObjectFieldPtr(this, global::com.google.javascript.jscomp.JSError.j4n_level15));
}
}
}
private static void InitJNI(global::net.sf.jni4net.jni.JNIEnv @__env, java.lang.Class @__class) {
global::com.google.javascript.jscomp.JSError.staticClass = @__class;
global::com.google.javascript.jscomp.JSError.j4n_make0 = @__env.GetStaticMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "make", "(Lcom/google/javascript/jscomp/DiagnosticType;[Ljava/lang/String;)Lcom/google/jav" +
"ascript/jscomp/JSError;");
global::com.google.javascript.jscomp.JSError.j4n_make1 = @__env.GetStaticMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "make", "(Ljava/lang/String;IILcom/google/javascript/jscomp/DiagnosticType;[Ljava/lang/Str" +
"ing;)Lcom/google/javascript/jscomp/JSError;");
global::com.google.javascript.jscomp.JSError.j4n_make2 = @__env.GetStaticMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "make", "(Ljava/lang/String;IILcom/google/javascript/jscomp/CheckLevel;Lcom/google/javascr" +
"ipt/jscomp/DiagnosticType;[Ljava/lang/String;)Lcom/google/javascript/jscomp/JSEr" +
"ror;");
global::com.google.javascript.jscomp.JSError.j4n_make3 = @__env.GetStaticMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "make", "(Ljava/lang/String;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/jscom" +
"p/DiagnosticType;[Ljava/lang/String;)Lcom/google/javascript/jscomp/JSError;");
global::com.google.javascript.jscomp.JSError.j4n_make4 = @__env.GetStaticMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "make", "(Ljava/lang/String;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/jscom" +
"p/CheckLevel;Lcom/google/javascript/jscomp/DiagnosticType;[Ljava/lang/String;)Lc" +
"om/google/javascript/jscomp/JSError;");
global::com.google.javascript.jscomp.JSError.j4n_format5 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "format", "(Lcom/google/javascript/jscomp/CheckLevel;Lcom/google/javascript/jscomp/MessageFo" +
"rmatter;)Ljava/lang/String;");
global::com.google.javascript.jscomp.JSError.j4n_getType6 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "getType", "()Lcom/google/javascript/jscomp/DiagnosticType;");
global::com.google.javascript.jscomp.JSError.j4n_getLineNumber7 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "getLineNumber", "()I");
global::com.google.javascript.jscomp.JSError.j4n_getCharno8 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "getCharno", "()I");
global::com.google.javascript.jscomp.JSError.j4n_getNodeSourceOffset9 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "getNodeSourceOffset", "()I");
global::com.google.javascript.jscomp.JSError.j4n_getNodeLength10 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "getNodeLength", "()I");
global::com.google.javascript.jscomp.JSError.j4n_getDefaultLevel11 = @__env.GetMethodID(global::com.google.javascript.jscomp.JSError.staticClass, "getDefaultLevel", "()Lcom/google/javascript/jscomp/CheckLevel;");
global::com.google.javascript.jscomp.JSError.j4n_description12 = @__env.GetFieldID(global::com.google.javascript.jscomp.JSError.staticClass, "description", "Ljava/lang/String;");
global::com.google.javascript.jscomp.JSError.j4n_sourceName13 = @__env.GetFieldID(global::com.google.javascript.jscomp.JSError.staticClass, "sourceName", "Ljava/lang/String;");
global::com.google.javascript.jscomp.JSError.j4n_lineNumber14 = @__env.GetFieldID(global::com.google.javascript.jscomp.JSError.staticClass, "lineNumber", "I");
global::com.google.javascript.jscomp.JSError.j4n_level15 = @__env.GetFieldID(global::com.google.javascript.jscomp.JSError.staticClass, "level", "Lcom/google/javascript/jscomp/CheckLevel;");
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Lcom/google/javascript/jscomp/DiagnosticType;[Ljava/lang/String;)Lcom/google/jav" +
"ascript/jscomp/JSError;")]
public static global::com.google.javascript.jscomp.JSError make(global::java.lang.Object par0, java.lang.String[] par1) {
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.ThreadEnv;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 14)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.JSError>(@__env, @__env.CallStaticObjectMethodPtr(global::com.google.javascript.jscomp.JSError.staticClass, global::com.google.javascript.jscomp.JSError.j4n_make0, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0), global::net.sf.jni4net.utils.Convertor.ParArrayStrongCp2J(@__env, par1)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Ljava/lang/String;IILcom/google/javascript/jscomp/DiagnosticType;[Ljava/lang/Str" +
"ing;)Lcom/google/javascript/jscomp/JSError;")]
public static global::com.google.javascript.jscomp.JSError make(global::java.lang.String par0, int par1, int par2, global::java.lang.Object par3, java.lang.String[] par4) {
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.ThreadEnv;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 20)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.JSError>(@__env, @__env.CallStaticObjectMethodPtr(global::com.google.javascript.jscomp.JSError.staticClass, global::com.google.javascript.jscomp.JSError.j4n_make1, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0), global::net.sf.jni4net.utils.Convertor.ParPrimC2J(par1), global::net.sf.jni4net.utils.Convertor.ParPrimC2J(par2), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par3), global::net.sf.jni4net.utils.Convertor.ParArrayStrongCp2J(@__env, par4)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Ljava/lang/String;IILcom/google/javascript/jscomp/CheckLevel;Lcom/google/javascr" +
"ipt/jscomp/DiagnosticType;[Ljava/lang/String;)Lcom/google/javascript/jscomp/JSEr" +
"ror;")]
public static global::com.google.javascript.jscomp.JSError make(global::java.lang.String par0, int par1, int par2, global::com.google.javascript.jscomp.CheckLevel par3, global::java.lang.Object par4, java.lang.String[] par5) {
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.ThreadEnv;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 22)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.JSError>(@__env, @__env.CallStaticObjectMethodPtr(global::com.google.javascript.jscomp.JSError.staticClass, global::com.google.javascript.jscomp.JSError.j4n_make2, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0), global::net.sf.jni4net.utils.Convertor.ParPrimC2J(par1), global::net.sf.jni4net.utils.Convertor.ParPrimC2J(par2), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par3), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par4), global::net.sf.jni4net.utils.Convertor.ParArrayStrongCp2J(@__env, par5)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Ljava/lang/String;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/jscom" +
"p/DiagnosticType;[Ljava/lang/String;)Lcom/google/javascript/jscomp/JSError;")]
public static global::com.google.javascript.jscomp.JSError make(global::java.lang.String par0, global::java.lang.Object par1, global::java.lang.Object par2, java.lang.String[] par3) {
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.ThreadEnv;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 18)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.JSError>(@__env, @__env.CallStaticObjectMethodPtr(global::com.google.javascript.jscomp.JSError.staticClass, global::com.google.javascript.jscomp.JSError.j4n_make3, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par1), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par2), global::net.sf.jni4net.utils.Convertor.ParArrayStrongCp2J(@__env, par3)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Ljava/lang/String;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/jscom" +
"p/CheckLevel;Lcom/google/javascript/jscomp/DiagnosticType;[Ljava/lang/String;)Lc" +
"om/google/javascript/jscomp/JSError;")]
public static global::com.google.javascript.jscomp.JSError make(global::java.lang.String par0, global::java.lang.Object par1, global::com.google.javascript.jscomp.CheckLevel par2, global::java.lang.Object par3, java.lang.String[] par4) {
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.ThreadEnv;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 20)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.JSError>(@__env, @__env.CallStaticObjectMethodPtr(global::com.google.javascript.jscomp.JSError.staticClass, global::com.google.javascript.jscomp.JSError.j4n_make4, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par1), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par2), global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par3), global::net.sf.jni4net.utils.Convertor.ParArrayStrongCp2J(@__env, par4)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Lcom/google/javascript/jscomp/CheckLevel;Lcom/google/javascript/jscomp/MessageFo" +
"rmatter;)Ljava/lang/String;")]
public virtual global::java.lang.String format(global::com.google.javascript.jscomp.CheckLevel par0, global::java.lang.Object par1) {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 14)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2CpString(@__env, @__env.CallObjectMethodPtr(this, global::com.google.javascript.jscomp.JSError.j4n_format5, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0), global::net.sf.jni4net.utils.Convertor.ParFullC2J<global::java.lang.Object>(@__env, par1)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()Lcom/google/javascript/jscomp/DiagnosticType;")]
public virtual global::java.lang.Object getType() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::java.lang.Object>(@__env, @__env.CallObjectMethodPtr(this, global::com.google.javascript.jscomp.JSError.j4n_getType6));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()I")]
public virtual int getLineNumber() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return ((int)(@__env.CallIntMethod(this, global::com.google.javascript.jscomp.JSError.j4n_getLineNumber7)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()I")]
public virtual int getCharno() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return ((int)(@__env.CallIntMethod(this, global::com.google.javascript.jscomp.JSError.j4n_getCharno8)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()I")]
public virtual int getNodeSourceOffset() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return ((int)(@__env.CallIntMethod(this, global::com.google.javascript.jscomp.JSError.j4n_getNodeSourceOffset9)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()I")]
public virtual int getNodeLength() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return ((int)(@__env.CallIntMethod(this, global::com.google.javascript.jscomp.JSError.j4n_getNodeLength10)));
}
}
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()Lcom/google/javascript/jscomp/CheckLevel;")]
public virtual global::com.google.javascript.jscomp.CheckLevel getDefaultLevel() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::com.google.javascript.jscomp.CheckLevel>(@__env, @__env.CallObjectMethodPtr(this, global::com.google.javascript.jscomp.JSError.j4n_getDefaultLevel11));
}
}
new internal sealed class ContructionHelper : global::net.sf.jni4net.utils.IConstructionHelper {
public global::net.sf.jni4net.jni.IJvmProxy CreateProxy(global::net.sf.jni4net.jni.JNIEnv @__env) {
return new global::com.google.javascript.jscomp.JSError(@__env);
}
}
}
#endregion
}
|
MiguelCastillo/jsCompiler
|
googClosure/com/google/javascript/jscomp/JSError.generated.cs
|
C#
|
gpl-2.0
| 18,604
|
/* tc-arm.c -- Assemble for the ARM
Copyright (C) 1994-2015 Free Software Foundation, Inc.
Contributed by Richard Earnshaw (rwe@pegasus.esprit.ec.org)
Modified by David Taylor (dtaylor@armltd.co.uk)
Cirrus coprocessor mods by Aldy Hernandez (aldyh@redhat.com)
Cirrus coprocessor fixes by Petko Manolov (petkan@nucleusys.com)
Cirrus coprocessor fixes by Vladimir Ivanov (vladitx@nucleusys.com)
This file is part of GAS, the GNU Assembler.
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, 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 GAS; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
02110-1301, USA. */
#include "as.h"
#include <limits.h>
#include <stdarg.h>
#define NO_RELOC 0
#include "safe-ctype.h"
#include "subsegs.h"
#include "obstack.h"
#include "libiberty.h"
#include "opcode/arm.h"
#ifdef OBJ_ELF
#include "elf/arm.h"
#include "dw2gencfi.h"
#endif
#include "dwarf2dbg.h"
#ifdef OBJ_ELF
/* Must be at least the size of the largest unwind opcode (currently two). */
#define ARM_OPCODE_CHUNK_SIZE 8
/* This structure holds the unwinding state. */
static struct
{
symbolS * proc_start;
symbolS * table_entry;
symbolS * personality_routine;
int personality_index;
/* The segment containing the function. */
segT saved_seg;
subsegT saved_subseg;
/* Opcodes generated from this function. */
unsigned char * opcodes;
int opcode_count;
int opcode_alloc;
/* The number of bytes pushed to the stack. */
offsetT frame_size;
/* We don't add stack adjustment opcodes immediately so that we can merge
multiple adjustments. We can also omit the final adjustment
when using a frame pointer. */
offsetT pending_offset;
/* These two fields are set by both unwind_movsp and unwind_setfp. They
hold the reg+offset to use when restoring sp from a frame pointer. */
offsetT fp_offset;
int fp_reg;
/* Nonzero if an unwind_setfp directive has been seen. */
unsigned fp_used:1;
/* Nonzero if the last opcode restores sp from fp_reg. */
unsigned sp_restored:1;
} unwind;
#endif /* OBJ_ELF */
/* Results from operand parsing worker functions. */
typedef enum
{
PARSE_OPERAND_SUCCESS,
PARSE_OPERAND_FAIL,
PARSE_OPERAND_FAIL_NO_BACKTRACK
} parse_operand_result;
enum arm_float_abi
{
ARM_FLOAT_ABI_HARD,
ARM_FLOAT_ABI_SOFTFP,
ARM_FLOAT_ABI_SOFT
};
/* Types of processor to assemble for. */
#ifndef CPU_DEFAULT
/* The code that was here used to select a default CPU depending on compiler
pre-defines which were only present when doing native builds, thus
changing gas' default behaviour depending upon the build host.
If you have a target that requires a default CPU option then the you
should define CPU_DEFAULT here. */
#endif
#ifndef FPU_DEFAULT
# ifdef TE_LINUX
# define FPU_DEFAULT FPU_ARCH_FPA
# elif defined (TE_NetBSD)
# ifdef OBJ_ELF
# define FPU_DEFAULT FPU_ARCH_VFP /* Soft-float, but VFP order. */
# else
/* Legacy a.out format. */
# define FPU_DEFAULT FPU_ARCH_FPA /* Soft-float, but FPA order. */
# endif
# elif defined (TE_VXWORKS)
# define FPU_DEFAULT FPU_ARCH_VFP /* Soft-float, VFP order. */
# else
/* For backwards compatibility, default to FPA. */
# define FPU_DEFAULT FPU_ARCH_FPA
# endif
#endif /* ifndef FPU_DEFAULT */
#define streq(a, b) (strcmp (a, b) == 0)
static arm_feature_set cpu_variant;
static arm_feature_set arm_arch_used;
static arm_feature_set thumb_arch_used;
/* Flags stored in private area of BFD structure. */
static int uses_apcs_26 = FALSE;
static int atpcs = FALSE;
static int support_interwork = FALSE;
static int uses_apcs_float = FALSE;
static int pic_code = FALSE;
static int fix_v4bx = FALSE;
/* Warn on using deprecated features. */
static int warn_on_deprecated = TRUE;
/* Understand CodeComposer Studio assembly syntax. */
bfd_boolean codecomposer_syntax = FALSE;
/* 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 arm_feature_set *legacy_cpu = NULL;
static const arm_feature_set *legacy_fpu = NULL;
static const arm_feature_set *mcpu_cpu_opt = NULL;
static const arm_feature_set *mcpu_fpu_opt = NULL;
static const arm_feature_set *march_cpu_opt = NULL;
static const arm_feature_set *march_fpu_opt = NULL;
static const arm_feature_set *mfpu_opt = NULL;
static const arm_feature_set *object_arch = NULL;
/* Constants for known architecture features. */
static const arm_feature_set fpu_default = FPU_DEFAULT;
static const arm_feature_set fpu_arch_vfp_v1 = FPU_ARCH_VFP_V1;
static const arm_feature_set fpu_arch_vfp_v2 = FPU_ARCH_VFP_V2;
static const arm_feature_set fpu_arch_vfp_v3 = FPU_ARCH_VFP_V3;
static const arm_feature_set fpu_arch_neon_v1 = FPU_ARCH_NEON_V1;
static const arm_feature_set fpu_arch_fpa = FPU_ARCH_FPA;
static const arm_feature_set fpu_any_hard = FPU_ANY_HARD;
static const arm_feature_set fpu_arch_maverick = FPU_ARCH_MAVERICK;
static const arm_feature_set fpu_endian_pure = FPU_ARCH_ENDIAN_PURE;
#ifdef CPU_DEFAULT
static const arm_feature_set cpu_default = CPU_DEFAULT;
#endif
static const arm_feature_set arm_ext_v1 = ARM_FEATURE (ARM_EXT_V1, 0);
static const arm_feature_set arm_ext_v2 = ARM_FEATURE (ARM_EXT_V1, 0);
static const arm_feature_set arm_ext_v2s = ARM_FEATURE (ARM_EXT_V2S, 0);
static const arm_feature_set arm_ext_v3 = ARM_FEATURE (ARM_EXT_V3, 0);
static const arm_feature_set arm_ext_v3m = ARM_FEATURE (ARM_EXT_V3M, 0);
static const arm_feature_set arm_ext_v4 = ARM_FEATURE (ARM_EXT_V4, 0);
static const arm_feature_set arm_ext_v4t = ARM_FEATURE (ARM_EXT_V4T, 0);
static const arm_feature_set arm_ext_v5 = ARM_FEATURE (ARM_EXT_V5, 0);
static const arm_feature_set arm_ext_v4t_5 =
ARM_FEATURE (ARM_EXT_V4T | ARM_EXT_V5, 0);
static const arm_feature_set arm_ext_v5t = ARM_FEATURE (ARM_EXT_V5T, 0);
static const arm_feature_set arm_ext_v5e = ARM_FEATURE (ARM_EXT_V5E, 0);
static const arm_feature_set arm_ext_v5exp = ARM_FEATURE (ARM_EXT_V5ExP, 0);
static const arm_feature_set arm_ext_v5j = ARM_FEATURE (ARM_EXT_V5J, 0);
static const arm_feature_set arm_ext_v6 = ARM_FEATURE (ARM_EXT_V6, 0);
static const arm_feature_set arm_ext_v6k = ARM_FEATURE (ARM_EXT_V6K, 0);
static const arm_feature_set arm_ext_v6t2 = ARM_FEATURE (ARM_EXT_V6T2, 0);
static const arm_feature_set arm_ext_v6m = ARM_FEATURE (ARM_EXT_V6M, 0);
static const arm_feature_set arm_ext_v6_notm = ARM_FEATURE (ARM_EXT_V6_NOTM, 0);
static const arm_feature_set arm_ext_v6_dsp = ARM_FEATURE (ARM_EXT_V6_DSP, 0);
static const arm_feature_set arm_ext_barrier = ARM_FEATURE (ARM_EXT_BARRIER, 0);
static const arm_feature_set arm_ext_msr = ARM_FEATURE (ARM_EXT_THUMB_MSR, 0);
static const arm_feature_set arm_ext_div = ARM_FEATURE (ARM_EXT_DIV, 0);
static const arm_feature_set arm_ext_v7 = ARM_FEATURE (ARM_EXT_V7, 0);
static const arm_feature_set arm_ext_v7a = ARM_FEATURE (ARM_EXT_V7A, 0);
static const arm_feature_set arm_ext_v7r = ARM_FEATURE (ARM_EXT_V7R, 0);
static const arm_feature_set arm_ext_v7m = ARM_FEATURE (ARM_EXT_V7M, 0);
static const arm_feature_set arm_ext_v8 = ARM_FEATURE (ARM_EXT_V8, 0);
static const arm_feature_set arm_ext_m =
ARM_FEATURE (ARM_EXT_V6M | ARM_EXT_OS | ARM_EXT_V7M, 0);
static const arm_feature_set arm_ext_mp = ARM_FEATURE (ARM_EXT_MP, 0);
static const arm_feature_set arm_ext_sec = ARM_FEATURE (ARM_EXT_SEC, 0);
static const arm_feature_set arm_ext_os = ARM_FEATURE (ARM_EXT_OS, 0);
static const arm_feature_set arm_ext_adiv = ARM_FEATURE (ARM_EXT_ADIV, 0);
static const arm_feature_set arm_ext_virt = ARM_FEATURE (ARM_EXT_VIRT, 0);
static const arm_feature_set arm_arch_any = ARM_ANY;
static const arm_feature_set arm_arch_full = ARM_FEATURE (-1, -1);
static const arm_feature_set arm_arch_t2 = ARM_ARCH_THUMB2;
static const arm_feature_set arm_arch_none = ARM_ARCH_NONE;
static const arm_feature_set arm_arch_v6m_only = ARM_ARCH_V6M_ONLY;
static const arm_feature_set arm_cext_iwmmxt2 =
ARM_FEATURE (0, ARM_CEXT_IWMMXT2);
static const arm_feature_set arm_cext_iwmmxt =
ARM_FEATURE (0, ARM_CEXT_IWMMXT);
static const arm_feature_set arm_cext_xscale =
ARM_FEATURE (0, ARM_CEXT_XSCALE);
static const arm_feature_set arm_cext_maverick =
ARM_FEATURE (0, ARM_CEXT_MAVERICK);
static const arm_feature_set fpu_fpa_ext_v1 = ARM_FEATURE (0, FPU_FPA_EXT_V1);
static const arm_feature_set fpu_fpa_ext_v2 = ARM_FEATURE (0, FPU_FPA_EXT_V2);
static const arm_feature_set fpu_vfp_ext_v1xd =
ARM_FEATURE (0, FPU_VFP_EXT_V1xD);
static const arm_feature_set fpu_vfp_ext_v1 = ARM_FEATURE (0, FPU_VFP_EXT_V1);
static const arm_feature_set fpu_vfp_ext_v2 = ARM_FEATURE (0, FPU_VFP_EXT_V2);
static const arm_feature_set fpu_vfp_ext_v3xd = ARM_FEATURE (0, FPU_VFP_EXT_V3xD);
static const arm_feature_set fpu_vfp_ext_v3 = ARM_FEATURE (0, FPU_VFP_EXT_V3);
static const arm_feature_set fpu_vfp_ext_d32 =
ARM_FEATURE (0, FPU_VFP_EXT_D32);
static const arm_feature_set fpu_neon_ext_v1 = ARM_FEATURE (0, FPU_NEON_EXT_V1);
static const arm_feature_set fpu_vfp_v3_or_neon_ext =
ARM_FEATURE (0, FPU_NEON_EXT_V1 | FPU_VFP_EXT_V3);
static const arm_feature_set fpu_vfp_fp16 = ARM_FEATURE (0, FPU_VFP_EXT_FP16);
static const arm_feature_set fpu_neon_ext_fma = ARM_FEATURE (0, FPU_NEON_EXT_FMA);
static const arm_feature_set fpu_vfp_ext_fma = ARM_FEATURE (0, FPU_VFP_EXT_FMA);
static const arm_feature_set fpu_vfp_ext_armv8 =
ARM_FEATURE (0, FPU_VFP_EXT_ARMV8);
static const arm_feature_set fpu_vfp_ext_armv8xd =
ARM_FEATURE (0, FPU_VFP_EXT_ARMV8xD);
static const arm_feature_set fpu_neon_ext_armv8 =
ARM_FEATURE (0, FPU_NEON_EXT_ARMV8);
static const arm_feature_set fpu_crypto_ext_armv8 =
ARM_FEATURE (0, FPU_CRYPTO_EXT_ARMV8);
static const arm_feature_set crc_ext_armv8 =
ARM_FEATURE (0, CRC_EXT_ARMV8);
static int mfloat_abi_opt = -1;
/* Record user cpu selection for object attributes. */
static arm_feature_set selected_cpu = ARM_ARCH_NONE;
/* Must be long enough to hold any of the names in arm_cpus. */
static char selected_cpu_name[16];
extern FLONUM_TYPE generic_floating_point_number;
/* Return if no cpu was selected on command-line. */
static bfd_boolean
no_cpu_selected (void)
{
return selected_cpu.core == arm_arch_none.core
&& selected_cpu.coproc == arm_arch_none.coproc;
}
#ifdef OBJ_ELF
# ifdef EABI_DEFAULT
static int meabi_flags = EABI_DEFAULT;
# else
static int meabi_flags = EF_ARM_EABI_UNKNOWN;
# endif
static int attributes_set_explicitly[NUM_KNOWN_OBJ_ATTRIBUTES];
bfd_boolean
arm_is_eabi (void)
{
return (EF_ARM_EABI_VERSION (meabi_flags) >= EF_ARM_EABI_VER4);
}
#endif
#ifdef OBJ_ELF
/* Pre-defined "_GLOBAL_OFFSET_TABLE_" */
symbolS * GOT_symbol;
#endif
/* 0: assemble for ARM,
1: assemble for Thumb,
2: assemble for Thumb even though target CPU does not support thumb
instructions. */
static int thumb_mode = 0;
/* A value distinct from the possible values for thumb_mode that we
can use to record whether thumb_mode has been copied into the
tc_frag_data field of a frag. */
#define MODE_RECORDED (1 << 4)
/* Specifies the intrinsic IT insn behavior mode. */
enum implicit_it_mode
{
IMPLICIT_IT_MODE_NEVER = 0x00,
IMPLICIT_IT_MODE_ARM = 0x01,
IMPLICIT_IT_MODE_THUMB = 0x02,
IMPLICIT_IT_MODE_ALWAYS = (IMPLICIT_IT_MODE_ARM | IMPLICIT_IT_MODE_THUMB)
};
static int implicit_it_mode = IMPLICIT_IT_MODE_ARM;
/* If unified_syntax is true, we are processing the new unified
ARM/Thumb syntax. Important differences from the old ARM mode:
- Immediate operands do not require a # prefix.
- Conditional affixes always appear at the end of the
instruction. (For backward compatibility, those instructions
that formerly had them in the middle, continue to accept them
there.)
- The IT instruction may appear, and if it does is validated
against subsequent conditional affixes. It does not generate
machine code.
Important differences from the old Thumb mode:
- Immediate operands do not require a # prefix.
- Most of the V6T2 instructions are only available in unified mode.
- The .N and .W suffixes are recognized and honored (it is an error
if they cannot be honored).
- All instructions set the flags if and only if they have an 's' affix.
- Conditional affixes may be used. They are validated against
preceding IT instructions. Unlike ARM mode, you cannot use a
conditional affix except in the scope of an IT instruction. */
static bfd_boolean unified_syntax = FALSE;
/* An immediate operand can start with #, and ld*, st*, pld operands
can contain [ and ]. We need to tell APP not to elide whitespace
before a [, which can appear as the first operand for pld.
Likewise, a { can appear as the first operand for push, pop, vld*, etc. */
const char arm_symbol_chars[] = "#[]{}";
enum neon_el_type
{
NT_invtype,
NT_untyped,
NT_integer,
NT_float,
NT_poly,
NT_signed,
NT_unsigned
};
struct neon_type_el
{
enum neon_el_type type;
unsigned size;
};
#define NEON_MAX_TYPE_ELS 4
struct neon_type
{
struct neon_type_el el[NEON_MAX_TYPE_ELS];
unsigned elems;
};
enum it_instruction_type
{
OUTSIDE_IT_INSN,
INSIDE_IT_INSN,
INSIDE_IT_LAST_INSN,
IF_INSIDE_IT_LAST_INSN, /* Either outside or inside;
if inside, should be the last one. */
NEUTRAL_IT_INSN, /* This could be either inside or outside,
i.e. BKPT and NOP. */
IT_INSN /* The IT insn has been parsed. */
};
/* The maximum number of operands we need. */
#define ARM_IT_MAX_OPERANDS 6
struct arm_it
{
const char * error;
unsigned long instruction;
int size;
int size_req;
int cond;
/* "uncond_value" is set to the value in place of the conditional field in
unconditional versions of the instruction, or -1 if nothing is
appropriate. */
int uncond_value;
struct neon_type vectype;
/* This does not indicate an actual NEON instruction, only that
the mnemonic accepts neon-style type suffixes. */
int is_neon;
/* Set to the opcode if the instruction needs relaxation.
Zero if the instruction is not relaxed. */
unsigned long relax;
struct
{
bfd_reloc_code_real_type type;
expressionS exp;
int pc_rel;
} reloc;
enum it_instruction_type it_insn_type;
struct
{
unsigned reg;
signed int imm;
struct neon_type_el vectype;
unsigned present : 1; /* Operand present. */
unsigned isreg : 1; /* Operand was a register. */
unsigned immisreg : 1; /* .imm field is a second register. */
unsigned isscalar : 1; /* Operand is a (Neon) scalar. */
unsigned immisalign : 1; /* Immediate is an alignment specifier. */
unsigned immisfloat : 1; /* Immediate was parsed as a float. */
/* Note: we abuse "regisimm" to mean "is Neon register" in VMOV
instructions. This allows us to disambiguate ARM <-> vector insns. */
unsigned regisimm : 1; /* 64-bit immediate, reg forms high 32 bits. */
unsigned isvec : 1; /* Is a single, double or quad VFP/Neon reg. */
unsigned isquad : 1; /* Operand is Neon quad-precision register. */
unsigned issingle : 1; /* Operand is VFP single-precision register. */
unsigned hasreloc : 1; /* Operand has relocation suffix. */
unsigned writeback : 1; /* Operand has trailing ! */
unsigned preind : 1; /* Preindexed address. */
unsigned postind : 1; /* Postindexed address. */
unsigned negative : 1; /* Index register was negated. */
unsigned shifted : 1; /* Shift applied to operation. */
unsigned shift_kind : 3; /* Shift operation (enum shift_kind). */
} operands[ARM_IT_MAX_OPERANDS];
};
static struct arm_it inst;
#define NUM_FLOAT_VALS 8
const char * fp_const[] =
{
"0.0", "1.0", "2.0", "3.0", "4.0", "5.0", "0.5", "10.0", 0
};
/* Number of littlenums required to hold an extended precision number. */
#define MAX_LITTLENUMS 6
LITTLENUM_TYPE fp_values[NUM_FLOAT_VALS][MAX_LITTLENUMS];
#define FAIL (-1)
#define SUCCESS (0)
#define SUFF_S 1
#define SUFF_D 2
#define SUFF_E 3
#define SUFF_P 4
#define CP_T_X 0x00008000
#define CP_T_Y 0x00400000
#define CONDS_BIT 0x00100000
#define LOAD_BIT 0x00100000
#define DOUBLE_LOAD_FLAG 0x00000001
struct asm_cond
{
const char * template_name;
unsigned long value;
};
#define COND_ALWAYS 0xE
struct asm_psr
{
const char * template_name;
unsigned long field;
};
struct asm_barrier_opt
{
const char * template_name;
unsigned long value;
const arm_feature_set arch;
};
/* The bit that distinguishes CPSR and SPSR. */
#define SPSR_BIT (1 << 22)
/* The individual PSR flag bits. */
#define PSR_c (1 << 16)
#define PSR_x (1 << 17)
#define PSR_s (1 << 18)
#define PSR_f (1 << 19)
struct reloc_entry
{
char * name;
bfd_reloc_code_real_type reloc;
};
enum vfp_reg_pos
{
VFP_REG_Sd, VFP_REG_Sm, VFP_REG_Sn,
VFP_REG_Dd, VFP_REG_Dm, VFP_REG_Dn
};
enum vfp_ldstm_type
{
VFP_LDSTMIA, VFP_LDSTMDB, VFP_LDSTMIAX, VFP_LDSTMDBX
};
/* Bits for DEFINED field in neon_typed_alias. */
#define NTA_HASTYPE 1
#define NTA_HASINDEX 2
struct neon_typed_alias
{
unsigned char defined;
unsigned char index;
struct neon_type_el eltype;
};
/* ARM register categories. This includes coprocessor numbers and various
architecture extensions' registers. */
enum arm_reg_type
{
REG_TYPE_RN,
REG_TYPE_CP,
REG_TYPE_CN,
REG_TYPE_FN,
REG_TYPE_VFS,
REG_TYPE_VFD,
REG_TYPE_NQ,
REG_TYPE_VFSD,
REG_TYPE_NDQ,
REG_TYPE_NSDQ,
REG_TYPE_VFC,
REG_TYPE_MVF,
REG_TYPE_MVD,
REG_TYPE_MVFX,
REG_TYPE_MVDX,
REG_TYPE_MVAX,
REG_TYPE_DSPSC,
REG_TYPE_MMXWR,
REG_TYPE_MMXWC,
REG_TYPE_MMXWCG,
REG_TYPE_XSCALE,
REG_TYPE_RNB
};
/* Structure for a hash table entry for a register.
If TYPE is REG_TYPE_VFD or REG_TYPE_NQ, the NEON field can point to extra
information which states whether a vector type or index is specified (for a
register alias created with .dn or .qn). Otherwise NEON should be NULL. */
struct reg_entry
{
const char * name;
unsigned int number;
unsigned char type;
unsigned char builtin;
struct neon_typed_alias * neon;
};
/* Diagnostics used when we don't get a register of the expected type. */
const char * const reg_expected_msgs[] =
{
N_("ARM register expected"),
N_("bad or missing co-processor number"),
N_("co-processor register expected"),
N_("FPA register expected"),
N_("VFP single precision register expected"),
N_("VFP/Neon double precision register expected"),
N_("Neon quad precision register expected"),
N_("VFP single or double precision register expected"),
N_("Neon double or quad precision register expected"),
N_("VFP single, double or Neon quad precision register expected"),
N_("VFP system register expected"),
N_("Maverick MVF register expected"),
N_("Maverick MVD register expected"),
N_("Maverick MVFX register expected"),
N_("Maverick MVDX register expected"),
N_("Maverick MVAX register expected"),
N_("Maverick DSPSC register expected"),
N_("iWMMXt data register expected"),
N_("iWMMXt control register expected"),
N_("iWMMXt scalar register expected"),
N_("XScale accumulator register expected"),
};
/* Some well known registers that we refer to directly elsewhere. */
#define REG_R12 12
#define REG_SP 13
#define REG_LR 14
#define REG_PC 15
/* ARM instructions take 4bytes in the object file, Thumb instructions
take 2: */
#define INSN_SIZE 4
struct asm_opcode
{
/* Basic string to match. */
const char * template_name;
/* Parameters to instruction. */
unsigned int operands[8];
/* Conditional tag - see opcode_lookup. */
unsigned int tag : 4;
/* Basic instruction code. */
unsigned int avalue : 28;
/* Thumb-format instruction code. */
unsigned int tvalue;
/* Which architecture variant provides this instruction. */
const arm_feature_set * avariant;
const arm_feature_set * tvariant;
/* Function to call to encode instruction in ARM format. */
void (* aencode) (void);
/* Function to call to encode instruction in Thumb format. */
void (* tencode) (void);
};
/* Defines for various bits that we will want to toggle. */
#define INST_IMMEDIATE 0x02000000
#define OFFSET_REG 0x02000000
#define HWOFFSET_IMM 0x00400000
#define SHIFT_BY_REG 0x00000010
#define PRE_INDEX 0x01000000
#define INDEX_UP 0x00800000
#define WRITE_BACK 0x00200000
#define LDM_TYPE_2_OR_3 0x00400000
#define CPSI_MMOD 0x00020000
#define LITERAL_MASK 0xf000f000
#define OPCODE_MASK 0xfe1fffff
#define V4_STR_BIT 0x00000020
#define VLDR_VMOV_SAME 0x0040f000
#define T2_SUBS_PC_LR 0xf3de8f00
#define DATA_OP_SHIFT 21
#define T2_OPCODE_MASK 0xfe1fffff
#define T2_DATA_OP_SHIFT 21
#define A_COND_MASK 0xf0000000
#define A_PUSH_POP_OP_MASK 0x0fff0000
/* Opcodes for pushing/poping registers to/from the stack. */
#define A1_OPCODE_PUSH 0x092d0000
#define A2_OPCODE_PUSH 0x052d0004
#define A2_OPCODE_POP 0x049d0004
/* Codes to distinguish the arithmetic instructions. */
#define OPCODE_AND 0
#define OPCODE_EOR 1
#define OPCODE_SUB 2
#define OPCODE_RSB 3
#define OPCODE_ADD 4
#define OPCODE_ADC 5
#define OPCODE_SBC 6
#define OPCODE_RSC 7
#define OPCODE_TST 8
#define OPCODE_TEQ 9
#define OPCODE_CMP 10
#define OPCODE_CMN 11
#define OPCODE_ORR 12
#define OPCODE_MOV 13
#define OPCODE_BIC 14
#define OPCODE_MVN 15
#define T2_OPCODE_AND 0
#define T2_OPCODE_BIC 1
#define T2_OPCODE_ORR 2
#define T2_OPCODE_ORN 3
#define T2_OPCODE_EOR 4
#define T2_OPCODE_ADD 8
#define T2_OPCODE_ADC 10
#define T2_OPCODE_SBC 11
#define T2_OPCODE_SUB 13
#define T2_OPCODE_RSB 14
#define T_OPCODE_MUL 0x4340
#define T_OPCODE_TST 0x4200
#define T_OPCODE_CMN 0x42c0
#define T_OPCODE_NEG 0x4240
#define T_OPCODE_MVN 0x43c0
#define T_OPCODE_ADD_R3 0x1800
#define T_OPCODE_SUB_R3 0x1a00
#define T_OPCODE_ADD_HI 0x4400
#define T_OPCODE_ADD_ST 0xb000
#define T_OPCODE_SUB_ST 0xb080
#define T_OPCODE_ADD_SP 0xa800
#define T_OPCODE_ADD_PC 0xa000
#define T_OPCODE_ADD_I8 0x3000
#define T_OPCODE_SUB_I8 0x3800
#define T_OPCODE_ADD_I3 0x1c00
#define T_OPCODE_SUB_I3 0x1e00
#define T_OPCODE_ASR_R 0x4100
#define T_OPCODE_LSL_R 0x4080
#define T_OPCODE_LSR_R 0x40c0
#define T_OPCODE_ROR_R 0x41c0
#define T_OPCODE_ASR_I 0x1000
#define T_OPCODE_LSL_I 0x0000
#define T_OPCODE_LSR_I 0x0800
#define T_OPCODE_MOV_I8 0x2000
#define T_OPCODE_CMP_I8 0x2800
#define T_OPCODE_CMP_LR 0x4280
#define T_OPCODE_MOV_HR 0x4600
#define T_OPCODE_CMP_HR 0x4500
#define T_OPCODE_LDR_PC 0x4800
#define T_OPCODE_LDR_SP 0x9800
#define T_OPCODE_STR_SP 0x9000
#define T_OPCODE_LDR_IW 0x6800
#define T_OPCODE_STR_IW 0x6000
#define T_OPCODE_LDR_IH 0x8800
#define T_OPCODE_STR_IH 0x8000
#define T_OPCODE_LDR_IB 0x7800
#define T_OPCODE_STR_IB 0x7000
#define T_OPCODE_LDR_RW 0x5800
#define T_OPCODE_STR_RW 0x5000
#define T_OPCODE_LDR_RH 0x5a00
#define T_OPCODE_STR_RH 0x5200
#define T_OPCODE_LDR_RB 0x5c00
#define T_OPCODE_STR_RB 0x5400
#define T_OPCODE_PUSH 0xb400
#define T_OPCODE_POP 0xbc00
#define T_OPCODE_BRANCH 0xe000
#define THUMB_SIZE 2 /* Size of thumb instruction. */
#define THUMB_PP_PC_LR 0x0100
#define THUMB_LOAD_BIT 0x0800
#define THUMB2_LOAD_BIT 0x00100000
#define BAD_ARGS _("bad arguments to instruction")
#define BAD_SP _("r13 not allowed here")
#define BAD_PC _("r15 not allowed here")
#define BAD_COND _("instruction cannot be conditional")
#define BAD_OVERLAP _("registers may not be the same")
#define BAD_HIREG _("lo register required")
#define BAD_THUMB32 _("instruction not supported in Thumb16 mode")
#define BAD_ADDR_MODE _("instruction does not accept this addressing mode");
#define BAD_BRANCH _("branch must be last instruction in IT block")
#define BAD_NOT_IT _("instruction not allowed in IT block")
#define BAD_FPU _("selected FPU does not support instruction")
#define BAD_OUT_IT _("thumb conditional instruction should be in IT block")
#define BAD_IT_COND _("incorrect condition in IT block")
#define BAD_IT_IT _("IT falling in the range of a previous IT block")
#define MISSING_FNSTART _("missing .fnstart before unwinding directive")
#define BAD_PC_ADDRESSING \
_("cannot use register index with PC-relative addressing")
#define BAD_PC_WRITEBACK \
_("cannot use writeback with PC-relative addressing")
#define BAD_RANGE _("branch out of range")
#define UNPRED_REG(R) _("using " R " results in unpredictable behaviour")
static struct hash_control * arm_ops_hsh;
static struct hash_control * arm_cond_hsh;
static struct hash_control * arm_shift_hsh;
static struct hash_control * arm_psr_hsh;
static struct hash_control * arm_v7m_psr_hsh;
static struct hash_control * arm_reg_hsh;
static struct hash_control * arm_reloc_hsh;
static struct hash_control * arm_barrier_opt_hsh;
/* Stuff needed to resolve the label ambiguity
As:
...
label: <insn>
may differ from:
...
label:
<insn> */
symbolS * last_label_seen;
static int label_is_thumb_function_name = FALSE;
/* Literal pool structure. Held on a per-section
and per-sub-section basis. */
#define MAX_LITERAL_POOL_SIZE 1024
typedef struct literal_pool
{
expressionS literals [MAX_LITERAL_POOL_SIZE];
unsigned int next_free_entry;
unsigned int id;
symbolS * symbol;
segT section;
subsegT sub_section;
#ifdef OBJ_ELF
struct dwarf2_line_info locs [MAX_LITERAL_POOL_SIZE];
#endif
struct literal_pool * next;
unsigned int alignment;
} literal_pool;
/* Pointer to a linked list of literal pools. */
literal_pool * list_of_pools = NULL;
typedef enum asmfunc_states
{
OUTSIDE_ASMFUNC,
WAITING_ASMFUNC_NAME,
WAITING_ENDASMFUNC
} asmfunc_states;
static asmfunc_states asmfunc_state = OUTSIDE_ASMFUNC;
#ifdef OBJ_ELF
# define now_it seg_info (now_seg)->tc_segment_info_data.current_it
#else
static struct current_it now_it;
#endif
static inline int
now_it_compatible (int cond)
{
return (cond & ~1) == (now_it.cc & ~1);
}
static inline int
conditional_insn (void)
{
return inst.cond != COND_ALWAYS;
}
static int in_it_block (void);
static int handle_it_state (void);
static void force_automatic_it_block_close (void);
static void it_fsm_post_encode (void);
#define set_it_insn_type(type) \
do \
{ \
inst.it_insn_type = type; \
if (handle_it_state () == FAIL) \
return; \
} \
while (0)
#define set_it_insn_type_nonvoid(type, failret) \
do \
{ \
inst.it_insn_type = type; \
if (handle_it_state () == FAIL) \
return failret; \
} \
while(0)
#define set_it_insn_type_last() \
do \
{ \
if (inst.cond == COND_ALWAYS) \
set_it_insn_type (IF_INSIDE_IT_LAST_INSN); \
else \
set_it_insn_type (INSIDE_IT_LAST_INSN); \
} \
while (0)
/* Pure syntax. */
/* This array holds the chars that always start a comment. If the
pre-processor is disabled, these aren't very useful. */
char arm_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[] = "#";
char arm_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 characters that indicate the start of an immediate
value. */
#define is_immediate_prefix(C) ((C) == '#' || (C) == '$')
/* Separator character handling. */
#define skip_whitespace(str) do { if (*(str) == ' ') ++(str); } while (0)
static inline int
skip_past_char (char ** str, char c)
{
/* PR gas/14987: Allow for whitespace before the expected character. */
skip_whitespace (*str);
if (**str == c)
{
(*str)++;
return SUCCESS;
}
else
return FAIL;
}
#define skip_past_comma(str) skip_past_char (str, ',')
/* Arithmetic expressions (possibly involving symbols). */
/* Return TRUE if anything in the expression is a bignum. */
static int
walk_no_bignums (symbolS * sp)
{
if (symbol_get_value_expression (sp)->X_op == O_big)
return 1;
if (symbol_get_value_expression (sp)->X_add_symbol)
{
return (walk_no_bignums (symbol_get_value_expression (sp)->X_add_symbol)
|| (symbol_get_value_expression (sp)->X_op_symbol
&& walk_no_bignums (symbol_get_value_expression (sp)->X_op_symbol)));
}
return 0;
}
static int in_my_get_expression = 0;
/* Third argument to my_get_expression. */
#define GE_NO_PREFIX 0
#define GE_IMM_PREFIX 1
#define GE_OPT_PREFIX 2
/* This is a bit of a hack. Use an optional prefix, and also allow big (64-bit)
immediates, as can be used in Neon VMVN and VMOV immediate instructions. */
#define GE_OPT_PREFIX_BIG 3
static int
my_get_expression (expressionS * ep, char ** str, int prefix_mode)
{
char * save_in;
segT seg;
/* In unified syntax, all prefixes are optional. */
if (unified_syntax)
prefix_mode = (prefix_mode == GE_OPT_PREFIX_BIG) ? prefix_mode
: GE_OPT_PREFIX;
switch (prefix_mode)
{
case GE_NO_PREFIX: break;
case GE_IMM_PREFIX:
if (!is_immediate_prefix (**str))
{
inst.error = _("immediate expression requires a # prefix");
return FAIL;
}
(*str)++;
break;
case GE_OPT_PREFIX:
case GE_OPT_PREFIX_BIG:
if (is_immediate_prefix (**str))
(*str)++;
break;
default: abort ();
}
memset (ep, 0, sizeof (expressionS));
save_in = input_line_pointer;
input_line_pointer = *str;
in_my_get_expression = 1;
seg = expression (ep);
in_my_get_expression = 0;
if (ep->X_op == O_illegal || ep->X_op == O_absent)
{
/* We found a bad or missing expression in md_operand(). */
*str = input_line_pointer;
input_line_pointer = save_in;
if (inst.error == NULL)
inst.error = (ep->X_op == O_absent
? _("missing expression") :_("bad expression"));
return 1;
}
#ifdef OBJ_AOUT
if (seg != absolute_section
&& seg != text_section
&& seg != data_section
&& seg != bss_section
&& seg != undefined_section)
{
inst.error = _("bad segment");
*str = input_line_pointer;
input_line_pointer = save_in;
return 1;
}
#else
(void) seg;
#endif
/* Get rid of any bignums now, so that we don't generate an error for which
we can't establish a line number later on. Big numbers are never valid
in instructions, which is where this routine is always called. */
if (prefix_mode != GE_OPT_PREFIX_BIG
&& (ep->X_op == O_big
|| (ep->X_add_symbol
&& (walk_no_bignums (ep->X_add_symbol)
|| (ep->X_op_symbol
&& walk_no_bignums (ep->X_op_symbol))))))
{
inst.error = _("invalid constant");
*str = input_line_pointer;
input_line_pointer = save_in;
return 1;
}
*str = input_line_pointer;
input_line_pointer = save_in;
return 0;
}
/* 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.
Note that fp constants aren't represent in the normal way on the ARM.
In big endian mode, things are as expected. However, in little endian
mode fp constants are big-endian word-wise, and little-endian byte-wise
within the words. For example, (double) 1.1 in big endian mode is
the byte sequence 3f f1 99 99 99 99 99 9a, and in little endian mode is
the byte sequence 99 99 f1 3f 9a 99 99 99.
??? The format of 12 byte floats is uncertain according to gcc's arm.h. */
char *
md_atof (int type, char * litP, int * sizeP)
{
int prec;
LITTLENUM_TYPE words[MAX_LITTLENUMS];
char *t;
int i;
switch (type)
{
case 'f':
case 'F':
case 's':
case 'S':
prec = 2;
break;
case 'd':
case 'D':
case 'r':
case 'R':
prec = 4;
break;
case 'x':
case 'X':
prec = 5;
break;
case 'p':
case 'P':
prec = 5;
break;
default:
*sizeP = 0;
return _("Unrecognized or unsupported floating point constant");
}
t = atof_ieee (input_line_pointer, type, words);
if (t)
input_line_pointer = t;
*sizeP = prec * sizeof (LITTLENUM_TYPE);
if (target_big_endian)
{
for (i = 0; i < prec; i++)
{
md_number_to_chars (litP, (valueT) words[i], sizeof (LITTLENUM_TYPE));
litP += sizeof (LITTLENUM_TYPE);
}
}
else
{
if (ARM_CPU_HAS_FEATURE (cpu_variant, fpu_endian_pure))
for (i = prec - 1; i >= 0; i--)
{
md_number_to_chars (litP, (valueT) words[i], sizeof (LITTLENUM_TYPE));
litP += sizeof (LITTLENUM_TYPE);
}
else
/* For a 4 byte float the order of elements in `words' is 1 0.
For an 8 byte float the order is 1 0 3 2. */
for (i = 0; i < prec; i += 2)
{
md_number_to_chars (litP, (valueT) words[i + 1],
sizeof (LITTLENUM_TYPE));
md_number_to_chars (litP + sizeof (LITTLENUM_TYPE),
(valueT) words[i], sizeof (LITTLENUM_TYPE));
litP += 2 * sizeof (LITTLENUM_TYPE);
}
}
return NULL;
}
/* 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)
exp->X_op = O_illegal;
}
/* Immediate values. */
/* Generic immediate-value read function for use in directives.
Accepts anything that 'expression' can fold to a constant.
*val receives the number. */
#ifdef OBJ_ELF
static int
immediate_for_directive (int *val)
{
expressionS exp;
exp.X_op = O_illegal;
if (is_immediate_prefix (*input_line_pointer))
{
input_line_pointer++;
expression (&exp);
}
if (exp.X_op != O_constant)
{
as_bad (_("expected #constant"));
ignore_rest_of_line ();
return FAIL;
}
*val = exp.X_add_number;
return SUCCESS;
}
#endif
/* Register parsing. */
/* Generic register parser. 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. Does not issue diagnostics. */
static struct reg_entry *
arm_reg_parse_multi (char **ccp)
{
char *start = *ccp;
char *p;
struct reg_entry *reg;
skip_whitespace (start);
#ifdef REGISTER_PREFIX
if (*start != REGISTER_PREFIX)
return NULL;
start++;
#endif
#ifdef OPTIONAL_REGISTER_PREFIX
if (*start == OPTIONAL_REGISTER_PREFIX)
start++;
#endif
p = start;
if (!ISALPHA (*p) || !is_name_beginner (*p))
return NULL;
do
p++;
while (ISALPHA (*p) || ISDIGIT (*p) || *p == '_');
reg = (struct reg_entry *) hash_find_n (arm_reg_hsh, start, p - start);
if (!reg)
return NULL;
*ccp = p;
return reg;
}
static int
arm_reg_alt_syntax (char **ccp, char *start, struct reg_entry *reg,
enum arm_reg_type type)
{
/* Alternative syntaxes are accepted for a few register classes. */
switch (type)
{
case REG_TYPE_MVF:
case REG_TYPE_MVD:
case REG_TYPE_MVFX:
case REG_TYPE_MVDX:
/* Generic coprocessor register names are allowed for these. */
if (reg && reg->type == REG_TYPE_CN)
return reg->number;
break;
case REG_TYPE_CP:
/* For backward compatibility, a bare number is valid here. */
{
unsigned long processor = strtoul (start, ccp, 10);
if (*ccp != start && processor <= 15)
return processor;
}
case REG_TYPE_MMXWC:
/* WC includes WCG. ??? I'm not sure this is true for all
instructions that take WC registers. */
if (reg && reg->type == REG_TYPE_MMXWCG)
return reg->number;
break;
default:
break;
}
return FAIL;
}
/* As arm_reg_parse_multi, but the register must be of type TYPE, and the
return value is the register number or FAIL. */
static int
arm_reg_parse (char **ccp, enum arm_reg_type type)
{
char *start = *ccp;
struct reg_entry *reg = arm_reg_parse_multi (ccp);
int ret;
/* Do not allow a scalar (reg+index) to parse as a register. */
if (reg && reg->neon && (reg->neon->defined & NTA_HASINDEX))
return FAIL;
if (reg && reg->type == type)
return reg->number;
if ((ret = arm_reg_alt_syntax (ccp, start, reg, type)) != FAIL)
return ret;
*ccp = start;
return FAIL;
}
/* Parse a Neon type specifier. *STR should point at the leading '.'
character. Does no verification at this stage that the type fits the opcode
properly. E.g.,
.i32.i32.s16
.s32.f32
.u16
Can all be legally parsed by this function.
Fills in neon_type struct pointer with parsed information, and updates STR
to point after the parsed type specifier. Returns SUCCESS if this was a legal
type, FAIL if not. */
static int
parse_neon_type (struct neon_type *type, char **str)
{
char *ptr = *str;
if (type)
type->elems = 0;
while (type->elems < NEON_MAX_TYPE_ELS)
{
enum neon_el_type thistype = NT_untyped;
unsigned thissize = -1u;
if (*ptr != '.')
break;
ptr++;
/* Just a size without an explicit type. */
if (ISDIGIT (*ptr))
goto parsesize;
switch (TOLOWER (*ptr))
{
case 'i': thistype = NT_integer; break;
case 'f': thistype = NT_float; break;
case 'p': thistype = NT_poly; break;
case 's': thistype = NT_signed; break;
case 'u': thistype = NT_unsigned; break;
case 'd':
thistype = NT_float;
thissize = 64;
ptr++;
goto done;
default:
as_bad (_("unexpected character `%c' in type specifier"), *ptr);
return FAIL;
}
ptr++;
/* .f is an abbreviation for .f32. */
if (thistype == NT_float && !ISDIGIT (*ptr))
thissize = 32;
else
{
parsesize:
thissize = strtoul (ptr, &ptr, 10);
if (thissize != 8 && thissize != 16 && thissize != 32
&& thissize != 64)
{
as_bad (_("bad size %d in type specifier"), thissize);
return FAIL;
}
}
done:
if (type)
{
type->el[type->elems].type = thistype;
type->el[type->elems].size = thissize;
type->elems++;
}
}
/* Empty/missing type is not a successful parse. */
if (type->elems == 0)
return FAIL;
*str = ptr;
return SUCCESS;
}
/* 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 *err)
{
if (!inst.error)
inst.error = err;
}
/* Parse a single type, e.g. ".s32", leading period included. */
static int
parse_neon_operand_type (struct neon_type_el *vectype, char **ccp)
{
char *str = *ccp;
struct neon_type optype;
if (*str == '.')
{
if (parse_neon_type (&optype, &str) == SUCCESS)
{
if (optype.elems == 1)
*vectype = optype.el[0];
else
{
first_error (_("only one type should be specified for operand"));
return FAIL;
}
}
else
{
first_error (_("vector type expected"));
return FAIL;
}
}
else
return FAIL;
*ccp = str;
return SUCCESS;
}
/* Special meanings for indices (which have a range of 0-7), which will fit into
a 4-bit integer. */
#define NEON_ALL_LANES 15
#define NEON_INTERLEAVE_LANES 14
/* Parse either a register or a scalar, with an optional type. Return the
register number, and optionally fill in the actual type of the register
when multiple alternatives were given (NEON_TYPE_NDQ) in *RTYPE, and
type/index information in *TYPEINFO. */
static int
parse_typed_reg_or_scalar (char **ccp, enum arm_reg_type type,
enum arm_reg_type *rtype,
struct neon_typed_alias *typeinfo)
{
char *str = *ccp;
struct reg_entry *reg = arm_reg_parse_multi (&str);
struct neon_typed_alias atype;
struct neon_type_el parsetype;
atype.defined = 0;
atype.index = -1;
atype.eltype.type = NT_invtype;
atype.eltype.size = -1;
/* Try alternate syntax for some types of register. Note these are mutually
exclusive with the Neon syntax extensions. */
if (reg == NULL)
{
int altreg = arm_reg_alt_syntax (&str, *ccp, reg, type);
if (altreg != FAIL)
*ccp = str;
if (typeinfo)
*typeinfo = atype;
return altreg;
}
/* Undo polymorphism when a set of register types may be accepted. */
if ((type == REG_TYPE_NDQ
&& (reg->type == REG_TYPE_NQ || reg->type == REG_TYPE_VFD))
|| (type == REG_TYPE_VFSD
&& (reg->type == REG_TYPE_VFS || reg->type == REG_TYPE_VFD))
|| (type == REG_TYPE_NSDQ
&& (reg->type == REG_TYPE_VFS || reg->type == REG_TYPE_VFD
|| reg->type == REG_TYPE_NQ))
|| (type == REG_TYPE_MMXWC
&& (reg->type == REG_TYPE_MMXWCG)))
type = (enum arm_reg_type) reg->type;
if (type != reg->type)
return FAIL;
if (reg->neon)
atype = *reg->neon;
if (parse_neon_operand_type (&parsetype, &str) == SUCCESS)
{
if ((atype.defined & NTA_HASTYPE) != 0)
{
first_error (_("can't redefine type for operand"));
return FAIL;
}
atype.defined |= NTA_HASTYPE;
atype.eltype = parsetype;
}
if (skip_past_char (&str, '[') == SUCCESS)
{
if (type != REG_TYPE_VFD)
{
first_error (_("only D registers may be indexed"));
return FAIL;
}
if ((atype.defined & NTA_HASINDEX) != 0)
{
first_error (_("can't change index for operand"));
return FAIL;
}
atype.defined |= NTA_HASINDEX;
if (skip_past_char (&str, ']') == SUCCESS)
atype.index = NEON_ALL_LANES;
else
{
expressionS exp;
my_get_expression (&exp, &str, GE_NO_PREFIX);
if (exp.X_op != O_constant)
{
first_error (_("constant expression required"));
return FAIL;
}
if (skip_past_char (&str, ']') == FAIL)
return FAIL;
atype.index = exp.X_add_number;
}
}
if (typeinfo)
*typeinfo = atype;
if (rtype)
*rtype = type;
*ccp = str;
return reg->number;
}
/* Like arm_reg_parse, but allow allow the following extra features:
- If RTYPE is non-zero, return 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 type with additional type information, fill
in the struct pointed to by VECTYPE (if non-NULL).
This function will fault on encountering a scalar. */
static int
arm_typed_reg_parse (char **ccp, enum arm_reg_type type,
enum arm_reg_type *rtype, struct neon_type_el *vectype)
{
struct neon_typed_alias atype;
char *str = *ccp;
int reg = parse_typed_reg_or_scalar (&str, type, rtype, &atype);
if (reg == FAIL)
return FAIL;
/* Do not allow regname(... to parse as a register. */
if (*str == '(')
return FAIL;
/* Do not allow a scalar (reg+index) to parse as a register. */
if ((atype.defined & NTA_HASINDEX) != 0)
{
first_error (_("register operand expected, but got scalar"));
return FAIL;
}
if (vectype)
*vectype = atype.eltype;
*ccp = str;
return reg;
}
#define NEON_SCALAR_REG(X) ((X) >> 4)
#define NEON_SCALAR_INDEX(X) ((X) & 15)
/* Parse a Neon scalar. Most of the time when we're parsing a scalar, we don't
have enough information to be able to do a good job bounds-checking. So, we
just do easy checks here, and do further checks later. */
static int
parse_scalar (char **ccp, int elsize, struct neon_type_el *type)
{
int reg;
char *str = *ccp;
struct neon_typed_alias atype;
reg = parse_typed_reg_or_scalar (&str, REG_TYPE_VFD, NULL, &atype);
if (reg == FAIL || (atype.defined & NTA_HASINDEX) == 0)
return FAIL;
if (atype.index == NEON_ALL_LANES)
{
first_error (_("scalar must have an index"));
return FAIL;
}
else if (atype.index >= 64 / elsize)
{
first_error (_("scalar index out of range"));
return FAIL;
}
if (type)
*type = atype.eltype;
*ccp = str;
return reg * 16 + atype.index;
}
/* Parse an ARM register list. Returns the bitmask, or FAIL. */
static long
parse_reg_list (char ** strp)
{
char * str = * strp;
long range = 0;
int another_range;
/* We come back here if we get ranges concatenated by '+' or '|'. */
do
{
skip_whitespace (str);
another_range = 0;
if (*str == '{')
{
int in_range = 0;
int cur_reg = -1;
str++;
do
{
int reg;
if ((reg = arm_reg_parse (&str, REG_TYPE_RN)) == FAIL)
{
first_error (_(reg_expected_msgs[REG_TYPE_RN]));
return FAIL;
}
if (in_range)
{
int i;
if (reg <= cur_reg)
{
first_error (_("bad range in register list"));
return FAIL;
}
for (i = cur_reg + 1; i < reg; i++)
{
if (range & (1 << i))
as_tsktsk
(_("Warning: duplicated register (r%d) in register list"),
i);
else
range |= 1 << i;
}
in_range = 0;
}
if (range & (1 << reg))
as_tsktsk (_("Warning: duplicated register (r%d) in register list"),
reg);
else if (reg <= cur_reg)
as_tsktsk (_("Warning: register range not in ascending order"));
range |= 1 << reg;
cur_reg = reg;
}
while (skip_past_comma (&str) != FAIL
|| (in_range = 1, *str++ == '-'));
str--;
if (skip_past_char (&str, '}') == FAIL)
{
first_error (_("missing `}'"));
return FAIL;
}
}
else
{
expressionS exp;
if (my_get_expression (&exp, &str, GE_NO_PREFIX))
return FAIL;
if (exp.X_op == O_constant)
{
if (exp.X_add_number
!= (exp.X_add_number & 0x0000ffff))
{
inst.error = _("invalid register mask");
return FAIL;
}
if ((range & exp.X_add_number) != 0)
{
int regno = range & exp.X_add_number;
regno &= -regno;
regno = (1 << regno) - 1;
as_tsktsk
(_("Warning: duplicated register (r%d) in register list"),
regno);
}
range |= exp.X_add_number;
}
else
{
if (inst.reloc.type != 0)
{
inst.error = _("expression too complex");
return FAIL;
}
memcpy (&inst.reloc.exp, &exp, sizeof (expressionS));
inst.reloc.type = BFD_RELOC_ARM_MULTI;
inst.reloc.pc_rel = 0;
}
}
if (*str == '|' || *str == '+')
{
str++;
another_range = 1;
}
}
while (another_range);
*strp = str;
return range;
}
/* Types of registers in a list. */
enum reg_list_els
{
REGLIST_VFP_S,
REGLIST_VFP_D,
REGLIST_NEON_D
};
/* Parse a VFP register list. If the string is invalid return FAIL.
Otherwise return the number of registers, and set PBASE to the first
register. Parses registers of type ETYPE.
If REGLIST_NEON_D is used, several syntax enhancements are enabled:
- Q registers can be used to specify pairs of D registers
- { } can be omitted from around a singleton register list
FIXME: This is not implemented, as it would require backtracking in
some cases, e.g.:
vtbl.8 d3,d4,d5
This could be done (the meaning isn't really ambiguous), but doesn't
fit in well with the current parsing framework.
- 32 D registers may be used (also true for VFPv3).
FIXME: Types are ignored in these register lists, which is probably a
bug. */
static int
parse_vfp_reg_list (char **ccp, unsigned int *pbase, enum reg_list_els etype)
{
char *str = *ccp;
int base_reg;
int new_base;
enum arm_reg_type regtype = (enum arm_reg_type) 0;
int max_regs = 0;
int count = 0;
int warned = 0;
unsigned long mask = 0;
int i;
if (skip_past_char (&str, '{') == FAIL)
{
inst.error = _("expecting {");
return FAIL;
}
switch (etype)
{
case REGLIST_VFP_S:
regtype = REG_TYPE_VFS;
max_regs = 32;
break;
case REGLIST_VFP_D:
regtype = REG_TYPE_VFD;
break;
case REGLIST_NEON_D:
regtype = REG_TYPE_NDQ;
break;
}
if (etype != REGLIST_VFP_S)
{
/* VFPv3 allows 32 D registers, except for the VFPv3-D16 variant. */
if (ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_d32))
{
max_regs = 32;
if (thumb_mode)
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used,
fpu_vfp_ext_d32);
else
ARM_MERGE_FEATURE_SETS (arm_arch_used, arm_arch_used,
fpu_vfp_ext_d32);
}
else
max_regs = 16;
}
base_reg = max_regs;
do
{
int setmask = 1, addregs = 1;
new_base = arm_typed_reg_parse (&str, regtype, ®type, NULL);
if (new_base == FAIL)
{
first_error (_(reg_expected_msgs[regtype]));
return FAIL;
}
if (new_base >= max_regs)
{
first_error (_("register out of range in list"));
return FAIL;
}
/* Note: a value of 2 * n is returned for the register Q<n>. */
if (regtype == REG_TYPE_NQ)
{
setmask = 3;
addregs = 2;
}
if (new_base < base_reg)
base_reg = new_base;
if (mask & (setmask << new_base))
{
first_error (_("invalid register list"));
return FAIL;
}
if ((mask >> new_base) != 0 && ! warned)
{
as_tsktsk (_("register list not in ascending order"));
warned = 1;
}
mask |= setmask << new_base;
count += addregs;
if (*str == '-') /* We have the start of a range expression */
{
int high_range;
str++;
if ((high_range = arm_typed_reg_parse (&str, regtype, NULL, NULL))
== FAIL)
{
inst.error = gettext (reg_expected_msgs[regtype]);
return FAIL;
}
if (high_range >= max_regs)
{
first_error (_("register out of range in list"));
return FAIL;
}
if (regtype == REG_TYPE_NQ)
high_range = high_range + 1;
if (high_range <= new_base)
{
inst.error = _("register range not in ascending order");
return FAIL;
}
for (new_base += addregs; new_base <= high_range; new_base += addregs)
{
if (mask & (setmask << new_base))
{
inst.error = _("invalid register list");
return FAIL;
}
mask |= setmask << new_base;
count += addregs;
}
}
}
while (skip_past_comma (&str) != FAIL);
str++;
/* Sanity check -- should have raised a parse error above. */
if (count == 0 || count > max_regs)
abort ();
*pbase = base_reg;
/* Final test -- the registers must be consecutive. */
mask >>= base_reg;
for (i = 0; i < count; i++)
{
if ((mask & (1u << i)) == 0)
{
inst.error = _("non-contiguous register range");
return FAIL;
}
}
*ccp = str;
return count;
}
/* True if two alias types are the same. */
static bfd_boolean
neon_alias_types_same (struct neon_typed_alias *a, struct neon_typed_alias *b)
{
if (!a && !b)
return TRUE;
if (!a || !b)
return FALSE;
if (a->defined != b->defined)
return FALSE;
if ((a->defined & NTA_HASTYPE) != 0
&& (a->eltype.type != b->eltype.type
|| a->eltype.size != b->eltype.size))
return FALSE;
if ((a->defined & NTA_HASINDEX) != 0
&& (a->index != b->index))
return FALSE;
return TRUE;
}
/* Parse element/structure lists for Neon VLD<n> and VST<n> instructions.
The base register is put in *PBASE.
The lane (or one of the NEON_*_LANES constants) is placed in bits [3:0] of
the return value.
The register stride (minus one) is put in bit 4 of the return value.
Bits [6:5] encode the list length (minus one).
The type of the list elements is put in *ELTYPE, if non-NULL. */
#define NEON_LANE(X) ((X) & 0xf)
#define NEON_REG_STRIDE(X) ((((X) >> 4) & 1) + 1)
#define NEON_REGLIST_LENGTH(X) ((((X) >> 5) & 3) + 1)
static int
parse_neon_el_struct_list (char **str, unsigned *pbase,
struct neon_type_el *eltype)
{
char *ptr = *str;
int base_reg = -1;
int reg_incr = -1;
int count = 0;
int lane = -1;
int leading_brace = 0;
enum arm_reg_type rtype = REG_TYPE_NDQ;
const char *const incr_error = _("register stride must be 1 or 2");
const char *const type_error = _("mismatched element/structure types in list");
struct neon_typed_alias firsttype;
if (skip_past_char (&ptr, '{') == SUCCESS)
leading_brace = 1;
do
{
struct neon_typed_alias atype;
int getreg = parse_typed_reg_or_scalar (&ptr, rtype, &rtype, &atype);
if (getreg == FAIL)
{
first_error (_(reg_expected_msgs[rtype]));
return FAIL;
}
if (base_reg == -1)
{
base_reg = getreg;
if (rtype == REG_TYPE_NQ)
{
reg_incr = 1;
}
firsttype = atype;
}
else if (reg_incr == -1)
{
reg_incr = getreg - base_reg;
if (reg_incr < 1 || reg_incr > 2)
{
first_error (_(incr_error));
return FAIL;
}
}
else if (getreg != base_reg + reg_incr * count)
{
first_error (_(incr_error));
return FAIL;
}
if (! neon_alias_types_same (&atype, &firsttype))
{
first_error (_(type_error));
return FAIL;
}
/* Handle Dn-Dm or Qn-Qm syntax. Can only be used with non-indexed list
modes. */
if (ptr[0] == '-')
{
struct neon_typed_alias htype;
int hireg, dregs = (rtype == REG_TYPE_NQ) ? 2 : 1;
if (lane == -1)
lane = NEON_INTERLEAVE_LANES;
else if (lane != NEON_INTERLEAVE_LANES)
{
first_error (_(type_error));
return FAIL;
}
if (reg_incr == -1)
reg_incr = 1;
else if (reg_incr != 1)
{
first_error (_("don't use Rn-Rm syntax with non-unit stride"));
return FAIL;
}
ptr++;
hireg = parse_typed_reg_or_scalar (&ptr, rtype, NULL, &htype);
if (hireg == FAIL)
{
first_error (_(reg_expected_msgs[rtype]));
return FAIL;
}
if (! neon_alias_types_same (&htype, &firsttype))
{
first_error (_(type_error));
return FAIL;
}
count += hireg + dregs - getreg;
continue;
}
/* If we're using Q registers, we can't use [] or [n] syntax. */
if (rtype == REG_TYPE_NQ)
{
count += 2;
continue;
}
if ((atype.defined & NTA_HASINDEX) != 0)
{
if (lane == -1)
lane = atype.index;
else if (lane != atype.index)
{
first_error (_(type_error));
return FAIL;
}
}
else if (lane == -1)
lane = NEON_INTERLEAVE_LANES;
else if (lane != NEON_INTERLEAVE_LANES)
{
first_error (_(type_error));
return FAIL;
}
count++;
}
while ((count != 1 || leading_brace) && skip_past_comma (&ptr) != FAIL);
/* No lane set by [x]. We must be interleaving structures. */
if (lane == -1)
lane = NEON_INTERLEAVE_LANES;
/* Sanity check. */
if (lane == -1 || base_reg == -1 || count < 1 || count > 4
|| (count > 1 && reg_incr == -1))
{
first_error (_("error parsing element/structure list"));
return FAIL;
}
if ((count > 1 || leading_brace) && skip_past_char (&ptr, '}') == FAIL)
{
first_error (_("expected }"));
return FAIL;
}
if (reg_incr == -1)
reg_incr = 1;
if (eltype)
*eltype = firsttype.eltype;
*pbase = base_reg;
*str = ptr;
return lane | ((reg_incr - 1) << 4) | ((count - 1) << 5);
}
/* Parse an explicit relocation suffix on an expression. This is
either nothing, or a word in parentheses. Note that if !OBJ_ELF,
arm_reloc_hsh contains no entries, so this function can only
succeed if there is no () after the word. Returns -1 on error,
BFD_RELOC_UNUSED if there wasn't any suffix. */
static int
parse_reloc (char **str)
{
struct reloc_entry *r;
char *p, *q;
if (**str != '(')
return BFD_RELOC_UNUSED;
p = *str + 1;
q = p;
while (*q && *q != ')' && *q != ',')
q++;
if (*q != ')')
return -1;
if ((r = (struct reloc_entry *)
hash_find_n (arm_reloc_hsh, p, q - p)) == NULL)
return -1;
*str = q + 1;
return r->reloc;
}
/* Directives: register aliases. */
static struct reg_entry *
insert_reg_alias (char *str, unsigned number, int type)
{
struct reg_entry *new_reg;
const char *name;
if ((new_reg = (struct reg_entry *) hash_find (arm_reg_hsh, str)) != 0)
{
if (new_reg->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_reg->number != number || new_reg->type != type)
as_warn (_("ignoring redefinition of register alias '%s'"), str);
return NULL;
}
name = xstrdup (str);
new_reg = (struct reg_entry *) xmalloc (sizeof (struct reg_entry));
new_reg->name = name;
new_reg->number = number;
new_reg->type = type;
new_reg->builtin = FALSE;
new_reg->neon = NULL;
if (hash_insert (arm_reg_hsh, name, (void *) new_reg))
abort ();
return new_reg;
}
static void
insert_neon_reg_alias (char *str, int number, int type,
struct neon_typed_alias *atype)
{
struct reg_entry *reg = insert_reg_alias (str, number, type);
if (!reg)
{
first_error (_("attempt to redefine typed alias"));
return;
}
if (atype)
{
reg->neon = (struct neon_typed_alias *)
xmalloc (sizeof (struct neon_typed_alias));
*reg->neon = *atype;
}
}
/* 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)
{
struct 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 = (struct reg_entry *) hash_find (arm_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 = (char *) 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;
}
/* Create a Neon typed/indexed register alias using directives, e.g.:
X .dn d5.s32[1]
Y .qn 6.s16
Z .dn d7
T .dn Z[0]
These typed registers can be used instead of the types specified after the
Neon mnemonic, so long as all operands given have types. Types can also be
specified directly, e.g.:
vadd d0.s32, d1.s32, d2.s32 */
static bfd_boolean
create_neon_reg_alias (char *newname, char *p)
{
enum arm_reg_type basetype;
struct reg_entry *basereg;
struct reg_entry mybasereg;
struct neon_type ntype;
struct neon_typed_alias typeinfo;
char *namebuf, *nameend ATTRIBUTE_UNUSED;
int namelen;
typeinfo.defined = 0;
typeinfo.eltype.type = NT_invtype;
typeinfo.eltype.size = -1;
typeinfo.index = -1;
nameend = p;
if (strncmp (p, " .dn ", 5) == 0)
basetype = REG_TYPE_VFD;
else if (strncmp (p, " .qn ", 5) == 0)
basetype = REG_TYPE_NQ;
else
return FALSE;
p += 5;
if (*p == '\0')
return FALSE;
basereg = arm_reg_parse_multi (&p);
if (basereg && basereg->type != basetype)
{
as_bad (_("bad type for register"));
return FALSE;
}
if (basereg == NULL)
{
expressionS exp;
/* Try parsing as an integer. */
my_get_expression (&exp, &p, GE_NO_PREFIX);
if (exp.X_op != O_constant)
{
as_bad (_("expression must be constant"));
return FALSE;
}
basereg = &mybasereg;
basereg->number = (basetype == REG_TYPE_NQ) ? exp.X_add_number * 2
: exp.X_add_number;
basereg->neon = 0;
}
if (basereg->neon)
typeinfo = *basereg->neon;
if (parse_neon_type (&ntype, &p) == SUCCESS)
{
/* We got a type. */
if (typeinfo.defined & NTA_HASTYPE)
{
as_bad (_("can't redefine the type of a register alias"));
return FALSE;
}
typeinfo.defined |= NTA_HASTYPE;
if (ntype.elems != 1)
{
as_bad (_("you must specify a single type only"));
return FALSE;
}
typeinfo.eltype = ntype.el[0];
}
if (skip_past_char (&p, '[') == SUCCESS)
{
expressionS exp;
/* We got a scalar index. */
if (typeinfo.defined & NTA_HASINDEX)
{
as_bad (_("can't redefine the index of a scalar alias"));
return FALSE;
}
my_get_expression (&exp, &p, GE_NO_PREFIX);
if (exp.X_op != O_constant)
{
as_bad (_("scalar index must be constant"));
return FALSE;
}
typeinfo.defined |= NTA_HASINDEX;
typeinfo.index = exp.X_add_number;
if (skip_past_char (&p, ']') == FAIL)
{
as_bad (_("expecting ]"));
return FALSE;
}
}
/* 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
namelen = nameend - newname;
#else
newname = original_case_string;
namelen = strlen (newname);
#endif
namebuf = (char *) alloca (namelen + 1);
strncpy (namebuf, newname, namelen);
namebuf[namelen] = '\0';
insert_neon_reg_alias (namebuf, basereg->number, basetype,
typeinfo.defined != 0 ? &typeinfo : NULL);
/* Insert name in all uppercase. */
for (p = namebuf; *p; p++)
*p = TOUPPER (*p);
if (strncmp (namebuf, newname, namelen))
insert_neon_reg_alias (namebuf, basereg->number, basetype,
typeinfo.defined != 0 ? &typeinfo : NULL);
/* Insert name in all lowercase. */
for (p = namebuf; *p; p++)
*p = TOLOWER (*p);
if (strncmp (namebuf, newname, namelen))
insert_neon_reg_alias (namebuf, basereg->number, basetype,
typeinfo.defined != 0 ? &typeinfo : NULL);
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"));
}
static void
s_dn (int a ATTRIBUTE_UNUSED)
{
as_bad (_("invalid syntax for .dn directive"));
}
static void
s_qn (int a ATTRIBUTE_UNUSED)
{
as_bad (_("invalid syntax for .qn 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
{
struct reg_entry *reg = (struct reg_entry *) hash_find (arm_reg_hsh,
name);
if (!reg)
as_bad (_("unknown register alias '%s'"), name);
else if (reg->builtin)
as_warn (_("ignoring attempt to use .unreq on fixed register name: '%s'"),
name);
else
{
char * p;
char * nbuf;
hash_delete (arm_reg_hsh, name, FALSE);
free ((char *) reg->name);
if (reg->neon)
free (reg->neon);
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 = (struct reg_entry *) hash_find (arm_reg_hsh, nbuf);
if (reg)
{
hash_delete (arm_reg_hsh, nbuf, FALSE);
free ((char *) reg->name);
if (reg->neon)
free (reg->neon);
free (reg);
}
for (p = nbuf; *p; p++)
*p = TOLOWER (*p);
reg = (struct reg_entry *) hash_find (arm_reg_hsh, nbuf);
if (reg)
{
hash_delete (arm_reg_hsh, nbuf, FALSE);
free ((char *) reg->name);
if (reg->neon)
free (reg->neon);
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 ELF spec.
(See "Mapping symbols", section 4.5.5, ARM AAELF version 1.0).
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_ARM:
symname = "$a";
type = BSF_NO_FLAGS;
break;
case MAP_THUMB:
symname = "$t";
type = BSF_NO_FLAGS;
break;
default:
abort ();
}
symbolP = symbol_new (symname, now_seg, value, frag);
symbol_get_bfdsym (symbolP)->flags |= type | BSF_LOCAL;
switch (state)
{
case MAP_ARM:
THUMB_SET_FUNC (symbolP, 0);
ARM_SET_THUMB (symbolP, 0);
ARM_SET_INTERWORK (symbolP, support_interwork);
break;
case MAP_THUMB:
THUMB_SET_FUNC (symbolP, 1);
ARM_SET_THUMB (symbolP, 1);
ARM_SET_INTERWORK (symbolP, support_interwork);
break;
case MAP_DATA:
default:
break;
}
/* 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. */
#define TRANSITION(from, to) (mapstate == (from) && state == (to))
void
mapping_state (enum mstate state)
{
enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
if (mapstate == state)
/* The mapping symbol has already been emitted.
There is nothing else to do. */
return;
if (state == MAP_ARM || state == MAP_THUMB)
/* PR gas/12931
All ARM instructions require 4-byte alignment.
(Almost) all Thumb instructions require 2-byte alignment.
When emitting instructions into any section, mark the section
appropriately.
Some Thumb instructions are alignment-sensitive modulo 4 bytes,
but themselves require 2-byte alignment; this applies to some
PC- relative forms. However, these cases will invovle implicit
literal pool generation or an explicit .align >=2, both of
which will cause the section to me marked with sufficient
alignment. Thus, we don't handle those cases here. */
record_alignment (now_seg, state == MAP_ARM ? 2 : 1);
if (TRANSITION (MAP_UNDEFINED, MAP_DATA))
/* This case will be evaluated later. */
return;
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;
if (TRANSITION (MAP_UNDEFINED, MAP_ARM)
|| TRANSITION (MAP_UNDEFINED, MAP_THUMB))
{
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);
}
seg_info (now_seg)->tc_segment_info_data.mapstate = state;
make_mapping_symbol (state, (valueT) frag_now_fix () - max_chars, frag_now);
}
#undef TRANSITION
#else
#define mapping_state(x) ((void)0)
#define mapping_state_2(x, y) ((void)0)
#endif
/* Find the real, Thumb encoded start of a Thumb function. */
#ifdef OBJ_COFF
static symbolS *
find_real_start (symbolS * symbolP)
{
char * real_start;
const char * name = S_GET_NAME (symbolP);
symbolS * new_target;
/* This definition must agree with the one in gcc/config/arm/thumb.c. */
#define STUB_NAME ".real_start_of"
if (name == NULL)
abort ();
/* The compiler may generate BL instructions to local labels because
it needs to perform a branch to a far away location. These labels
do not have a corresponding ".real_start_of" label. We check
both for S_IS_LOCAL and for a leading dot, to give a way to bypass
the ".real_start_of" convention for nonlocal branches. */
if (S_IS_LOCAL (symbolP) || name[0] == '.')
return symbolP;
real_start = ACONCAT ((STUB_NAME, name, NULL));
new_target = symbol_find (real_start);
if (new_target == NULL)
{
as_warn (_("Failed to find real start of function: %s\n"), name);
new_target = symbolP;
}
return new_target;
}
#endif
static void
opcode_select (int width)
{
switch (width)
{
case 16:
if (! thumb_mode)
{
if (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v4t))
as_bad (_("selected processor does not support THUMB opcodes"));
thumb_mode = 1;
/* No need to force the alignment, since we will have been
coming from ARM mode, which is word-aligned. */
record_alignment (now_seg, 1);
}
break;
case 32:
if (thumb_mode)
{
if (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v1))
as_bad (_("selected processor does not support ARM opcodes"));
thumb_mode = 0;
if (!need_pass_2)
frag_align (2, 0, 0);
record_alignment (now_seg, 1);
}
break;
default:
as_bad (_("invalid instruction size selected (%d)"), width);
}
}
static void
s_arm (int ignore ATTRIBUTE_UNUSED)
{
opcode_select (32);
demand_empty_rest_of_line ();
}
static void
s_thumb (int ignore ATTRIBUTE_UNUSED)
{
opcode_select (16);
demand_empty_rest_of_line ();
}
static void
s_code (int unused ATTRIBUTE_UNUSED)
{
int temp;
temp = get_absolute_expression ();
switch (temp)
{
case 16:
case 32:
opcode_select (temp);
break;
default:
as_bad (_("invalid operand to .code directive (%d) (expecting 16 or 32)"), temp);
}
}
static void
s_force_thumb (int ignore ATTRIBUTE_UNUSED)
{
/* If we are not already in thumb mode go into it, EVEN if
the target processor does not support thumb instructions.
This is used by gcc/config/arm/lib1funcs.asm for example
to compile interworking support functions even if the
target processor should not support interworking. */
if (! thumb_mode)
{
thumb_mode = 2;
record_alignment (now_seg, 1);
}
demand_empty_rest_of_line ();
}
static void
s_thumb_func (int ignore ATTRIBUTE_UNUSED)
{
s_thumb (0);
/* The following label is the name/address of the start of a Thumb function.
We need to know this for the interworking support. */
label_is_thumb_function_name = TRUE;
}
/* Perform a .set directive, but also mark the alias as
being a thumb function. */
static void
s_thumb_set (int equiv)
{
/* XXX the following is a duplicate of the code for s_set() in read.c
We cannot just call that code as we need to get at the symbol that
is created. */
char * name;
char delim;
char * end_name;
symbolS * symbolP;
/* Especial apologies for the random logic:
This just grew, and could be parsed much more simply!
Dean - in haste. */
name = input_line_pointer;
delim = get_symbol_end ();
end_name = input_line_pointer;
*end_name = delim;
if (*input_line_pointer != ',')
{
*end_name = 0;
as_bad (_("expected comma after name \"%s\""), name);
*end_name = delim;
ignore_rest_of_line ();
return;
}
input_line_pointer++;
*end_name = 0;
if (name[0] == '.' && name[1] == '\0')
{
/* XXX - this should not happen to .thumb_set. */
abort ();
}
if ((symbolP = symbol_find (name)) == NULL
&& (symbolP = md_undefined_symbol (name)) == NULL)
{
#ifndef NO_LISTING
/* When doing symbol listings, play games with dummy fragments living
outside the normal fragment chain to record the file and line info
for this symbol. */
if (listing & LISTING_SYMBOLS)
{
extern struct list_info_struct * listing_tail;
fragS * dummy_frag = (fragS * ) xmalloc (sizeof (fragS));
memset (dummy_frag, 0, sizeof (fragS));
dummy_frag->fr_type = rs_fill;
dummy_frag->line = listing_tail;
symbolP = symbol_new (name, undefined_section, 0, dummy_frag);
dummy_frag->fr_symbol = symbolP;
}
else
#endif
symbolP = symbol_new (name, undefined_section, 0, &zero_address_frag);
#ifdef OBJ_COFF
/* "set" symbols are local unless otherwise specified. */
SF_SET_LOCAL (symbolP);
#endif /* OBJ_COFF */
} /* Make a new symbol. */
symbol_table_insert (symbolP);
* end_name = delim;
if (equiv
&& S_IS_DEFINED (symbolP)
&& S_GET_SEGMENT (symbolP) != reg_section)
as_bad (_("symbol `%s' already defined"), S_GET_NAME (symbolP));
pseudo_set (symbolP);
demand_empty_rest_of_line ();
/* XXX Now we come to the Thumb specific bit of code. */
THUMB_SET_FUNC (symbolP, 1);
ARM_SET_THUMB (symbolP, 1);
#if defined OBJ_ELF || defined OBJ_COFF
ARM_SET_INTERWORK (symbolP, support_interwork);
#endif
}
/* Directives: Mode selection. */
/* .syntax [unified|divided] - choose the new unified syntax
(same for Arm and Thumb encoding, modulo slight differences in what
can be represented) or the old divergent syntax for each mode. */
static void
s_syntax (int unused ATTRIBUTE_UNUSED)
{
char *name, delim;
name = input_line_pointer;
delim = get_symbol_end ();
if (!strcasecmp (name, "unified"))
unified_syntax = TRUE;
else if (!strcasecmp (name, "divided"))
unified_syntax = FALSE;
else
{
as_bad (_("unrecognized syntax mode \"%s\""), name);
return;
}
*input_line_pointer = delim;
demand_empty_rest_of_line ();
}
/* Directives: sectioning and alignment. */
/* Same as s_align_ptwo but align 0 => align 2. */
static void
s_align (int unused ATTRIBUTE_UNUSED)
{
int temp;
bfd_boolean fill_p;
long temp_fill;
long max_alignment = 15;
temp = get_absolute_expression ();
if (temp > max_alignment)
as_bad (_("alignment too large: %d assumed"), temp = max_alignment);
else if (temp < 0)
{
as_bad (_("alignment negative. 0 assumed."));
temp = 0;
}
if (*input_line_pointer == ',')
{
input_line_pointer++;
temp_fill = get_absolute_expression ();
fill_p = TRUE;
}
else
{
fill_p = FALSE;
temp_fill = 0;
}
if (!temp)
temp = 2;
/* Only make a frag if we HAVE to. */
if (temp && !need_pass_2)
{
if (!fill_p && subseg_text_p (now_seg))
frag_align_code (temp, 0);
else
frag_align (temp, (int) temp_fill, 0);
}
demand_empty_rest_of_line ();
record_alignment (now_seg, temp);
}
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 ();
#ifdef md_elf_section_change_hook
md_elf_section_change_hook ();
#endif
}
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: CodeComposer Studio. */
/* .ref (for CodeComposer Studio syntax only). */
static void
s_ccs_ref (int unused ATTRIBUTE_UNUSED)
{
if (codecomposer_syntax)
ignore_rest_of_line ();
else
as_bad (_(".ref pseudo-op only available with -mccs flag."));
}
/* If name is not NULL, then it is used for marking the beginning of a
function, wherease if it is NULL then it means the function end. */
static void
asmfunc_debug (const char * name)
{
static const char * last_name = NULL;
if (name != NULL)
{
gas_assert (last_name == NULL);
last_name = name;
if (debug_type == DEBUG_STABS)
stabs_generate_asm_func (name, name);
}
else
{
gas_assert (last_name != NULL);
if (debug_type == DEBUG_STABS)
stabs_generate_asm_endfunc (last_name, last_name);
last_name = NULL;
}
}
static void
s_ccs_asmfunc (int unused ATTRIBUTE_UNUSED)
{
if (codecomposer_syntax)
{
switch (asmfunc_state)
{
case OUTSIDE_ASMFUNC:
asmfunc_state = WAITING_ASMFUNC_NAME;
break;
case WAITING_ASMFUNC_NAME:
as_bad (_(".asmfunc repeated."));
break;
case WAITING_ENDASMFUNC:
as_bad (_(".asmfunc without function."));
break;
}
demand_empty_rest_of_line ();
}
else
as_bad (_(".asmfunc pseudo-op only available with -mccs flag."));
}
static void
s_ccs_endasmfunc (int unused ATTRIBUTE_UNUSED)
{
if (codecomposer_syntax)
{
switch (asmfunc_state)
{
case OUTSIDE_ASMFUNC:
as_bad (_(".endasmfunc without a .asmfunc."));
break;
case WAITING_ASMFUNC_NAME:
as_bad (_(".endasmfunc without function."));
break;
case WAITING_ENDASMFUNC:
asmfunc_state = OUTSIDE_ASMFUNC;
asmfunc_debug (NULL);
break;
}
demand_empty_rest_of_line ();
}
else
as_bad (_(".endasmfunc pseudo-op only available with -mccs flag."));
}
static void
s_ccs_def (int name)
{
if (codecomposer_syntax)
s_globl (name);
else
as_bad (_(".def pseudo-op only available with -mccs flag."));
}
/* Directives: Literal pools. */
static literal_pool *
find_literal_pool (void)
{
literal_pool * pool;
for (pool = list_of_pools; pool != NULL; pool = pool->next)
{
if (pool->section == now_seg
&& pool->sub_section == now_subseg)
break;
}
return pool;
}
static literal_pool *
find_or_make_literal_pool (void)
{
/* Next literal pool ID number. */
static unsigned int latest_pool_num = 1;
literal_pool * pool;
pool = find_literal_pool ();
if (pool == NULL)
{
/* Create a new pool. */
pool = (literal_pool *) xmalloc (sizeof (* pool));
if (! pool)
return NULL;
pool->next_free_entry = 0;
pool->section = now_seg;
pool->sub_section = now_subseg;
pool->next = list_of_pools;
pool->symbol = NULL;
pool->alignment = 2;
/* 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 in the global 'inst'
structure to the relevant literal pool. */
static int
add_to_lit_pool (unsigned int nbytes)
{
#define PADDING_SLOT 0x1
#define LIT_ENTRY_SIZE_MASK 0xFF
literal_pool * pool;
unsigned int entry, pool_size = 0;
bfd_boolean padding_slot_p = FALSE;
unsigned imm1 = 0;
unsigned imm2 = 0;
if (nbytes == 8)
{
imm1 = inst.operands[1].imm;
imm2 = (inst.operands[1].regisimm ? inst.operands[1].reg
: inst.reloc.exp.X_unsigned ? 0
: ((bfd_int64_t) inst.operands[1].imm) >> 32);
if (target_big_endian)
{
imm1 = imm2;
imm2 = inst.operands[1].imm;
}
}
pool = find_or_make_literal_pool ();
/* Check if this literal value is already in the pool. */
for (entry = 0; entry < pool->next_free_entry; entry ++)
{
if (nbytes == 4)
{
if ((pool->literals[entry].X_op == inst.reloc.exp.X_op)
&& (inst.reloc.exp.X_op == O_constant)
&& (pool->literals[entry].X_add_number
== inst.reloc.exp.X_add_number)
&& (pool->literals[entry].X_md == nbytes)
&& (pool->literals[entry].X_unsigned
== inst.reloc.exp.X_unsigned))
break;
if ((pool->literals[entry].X_op == inst.reloc.exp.X_op)
&& (inst.reloc.exp.X_op == O_symbol)
&& (pool->literals[entry].X_add_number
== inst.reloc.exp.X_add_number)
&& (pool->literals[entry].X_add_symbol
== inst.reloc.exp.X_add_symbol)
&& (pool->literals[entry].X_op_symbol
== inst.reloc.exp.X_op_symbol)
&& (pool->literals[entry].X_md == nbytes))
break;
}
else if ((nbytes == 8)
&& !(pool_size & 0x7)
&& ((entry + 1) != pool->next_free_entry)
&& (pool->literals[entry].X_op == O_constant)
&& (pool->literals[entry].X_add_number == (offsetT) imm1)
&& (pool->literals[entry].X_unsigned
== inst.reloc.exp.X_unsigned)
&& (pool->literals[entry + 1].X_op == O_constant)
&& (pool->literals[entry + 1].X_add_number == (offsetT) imm2)
&& (pool->literals[entry + 1].X_unsigned
== inst.reloc.exp.X_unsigned))
break;
padding_slot_p = ((pool->literals[entry].X_md >> 8) == PADDING_SLOT);
if (padding_slot_p && (nbytes == 4))
break;
pool_size += 4;
}
/* Do we need to create a new entry? */
if (entry == pool->next_free_entry)
{
if (entry >= MAX_LITERAL_POOL_SIZE)
{
inst.error = _("literal pool overflow");
return FAIL;
}
if (nbytes == 8)
{
/* For 8-byte entries, we align to an 8-byte boundary,
and split it into two 4-byte entries, because on 32-bit
host, 8-byte constants are treated as big num, thus
saved in "generic_bignum" which will be overwritten
by later assignments.
We also need to make sure there is enough space for
the split.
We also check to make sure the literal operand is a
constant number. */
if (!(inst.reloc.exp.X_op == O_constant
|| inst.reloc.exp.X_op == O_big))
{
inst.error = _("invalid type for literal pool");
return FAIL;
}
else if (pool_size & 0x7)
{
if ((entry + 2) >= MAX_LITERAL_POOL_SIZE)
{
inst.error = _("literal pool overflow");
return FAIL;
}
pool->literals[entry] = inst.reloc.exp;
pool->literals[entry].X_add_number = 0;
pool->literals[entry++].X_md = (PADDING_SLOT << 8) | 4;
pool->next_free_entry += 1;
pool_size += 4;
}
else if ((entry + 1) >= MAX_LITERAL_POOL_SIZE)
{
inst.error = _("literal pool overflow");
return FAIL;
}
pool->literals[entry] = inst.reloc.exp;
pool->literals[entry].X_op = O_constant;
pool->literals[entry].X_add_number = imm1;
pool->literals[entry].X_unsigned = inst.reloc.exp.X_unsigned;
pool->literals[entry++].X_md = 4;
pool->literals[entry] = inst.reloc.exp;
pool->literals[entry].X_op = O_constant;
pool->literals[entry].X_add_number = imm2;
pool->literals[entry].X_unsigned = inst.reloc.exp.X_unsigned;
pool->literals[entry].X_md = 4;
pool->alignment = 3;
pool->next_free_entry += 1;
}
else
{
pool->literals[entry] = inst.reloc.exp;
pool->literals[entry].X_md = 4;
}
#ifdef OBJ_ELF
/* PR ld/12974: Record the location of the first source line to reference
this entry in the literal pool. If it turns out during linking that the
symbol does not exist we will be able to give an accurate line number for
the (first use of the) missing reference. */
if (debug_type == DEBUG_DWARF2)
dwarf2_where (pool->locs + entry);
#endif
pool->next_free_entry += 1;
}
else if (padding_slot_p)
{
pool->literals[entry] = inst.reloc.exp;
pool->literals[entry].X_md = nbytes;
}
inst.reloc.exp.X_op = O_symbol;
inst.reloc.exp.X_add_number = pool_size;
inst.reloc.exp.X_add_symbol = pool->symbol;
return SUCCESS;
}
bfd_boolean
tc_start_label_without_colon (char unused1 ATTRIBUTE_UNUSED, const char * rest)
{
bfd_boolean ret = TRUE;
if (codecomposer_syntax && asmfunc_state == WAITING_ASMFUNC_NAME)
{
const char *label = rest;
while (!is_end_of_line[(int) label[-1]])
--label;
if (*label == '.')
{
as_bad (_("Invalid label '%s'"), label);
ret = FALSE;
}
asmfunc_debug (label);
asmfunc_state = WAITING_ENDASMFUNC;
}
return ret;
}
/* 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 = (char *) 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];
pool = find_literal_pool ();
if (pool == NULL
|| pool->symbol == NULL
|| pool->next_free_entry == 0)
return;
/* Align pool as you have word accesses.
Only make a frag if we have to. */
if (!need_pass_2)
frag_align (pool->alignment, 0, 0);
record_alignment (now_seg, 2);
#ifdef OBJ_ELF
seg_info (now_seg)->tc_segment_info_data.mapstate = MAP_DATA;
make_mapping_symbol (MAP_DATA, (valueT) frag_now_fix (), frag_now);
#endif
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);
ARM_SET_THUMB (pool->symbol, thumb_mode);
#if defined OBJ_COFF || defined OBJ_ELF
ARM_SET_INTERWORK (pool->symbol, support_interwork);
#endif
for (entry = 0; entry < pool->next_free_entry; entry ++)
{
#ifdef OBJ_ELF
if (debug_type == DEBUG_DWARF2)
dwarf2_gen_line_info (frag_now_fix (), pool->locs + entry);
#endif
/* First output the expression in the instruction to the pool. */
emit_expr (&(pool->literals[entry]),
pool->literals[entry].X_md & LIT_ENTRY_SIZE_MASK);
}
/* 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 void fix_new_arm (fragS *, int, short, expressionS *, int, int);
static valueT create_unwind_entry (int);
static void start_unwind_section (const segT, int);
static void add_unwind_opcode (valueT, int);
static void flush_pending_unwind (void);
/* Directives: Data. */
static void
s_arm_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
{
int reloc;
char *base = input_line_pointer;
expression (& exp);
if (exp.X_op != O_symbol)
emit_expr (&exp, (unsigned int) nbytes);
else
{
char *before_reloc = input_line_pointer;
reloc = parse_reloc (&input_line_pointer);
if (reloc == -1)
{
as_bad (_("unrecognized relocation suffix"));
ignore_rest_of_line ();
return;
}
else if (reloc == BFD_RELOC_UNUSED)
emit_expr (&exp, (unsigned int) nbytes);
else
{
reloc_howto_type *howto = (reloc_howto_type *)
bfd_reloc_type_lookup (stdoutput,
(bfd_reloc_code_real_type) reloc);
int size = bfd_get_reloc_size (howto);
if (reloc == BFD_RELOC_ARM_PLT32)
{
as_bad (_("(plt) is only valid on branch targets"));
reloc = BFD_RELOC_UNUSED;
size = 0;
}
if (size > nbytes)
as_bad (_("%s relocations do not fit in %d bytes"),
howto->name, nbytes);
else
{
/* We've parsed an expression stopping at O_symbol.
But there may be more expression left now that we
have parsed the relocation marker. Parse it again.
XXX Surely there is a cleaner way to do this. */
char *p = input_line_pointer;
int offset;
char *save_buf = (char *) alloca (input_line_pointer - base);
memcpy (save_buf, base, input_line_pointer - base);
memmove (base + (input_line_pointer - before_reloc),
base, before_reloc - base);
input_line_pointer = base + (input_line_pointer-before_reloc);
expression (&exp);
memcpy (base, save_buf, p - base);
offset = nbytes - size;
p = frag_more (nbytes);
memset (p, 0, nbytes);
fix_new_exp (frag_now, p - frag_now->fr_literal + offset,
size, &exp, 0, (enum bfd_reloc_code_real) reloc);
}
}
}
}
while (*input_line_pointer++ == ',');
/* Put terminator back into stream. */
input_line_pointer --;
demand_empty_rest_of_line ();
}
/* Emit an expression containing a 32-bit thumb instruction.
Implementation based on put_thumb32_insn. */
static void
emit_thumb32_expr (expressionS * exp)
{
expressionS exp_high = *exp;
exp_high.X_add_number = (unsigned long)exp_high.X_add_number >> 16;
emit_expr (& exp_high, (unsigned int) THUMB_SIZE);
exp->X_add_number &= 0xffff;
emit_expr (exp, (unsigned int) THUMB_SIZE);
}
/* Guess the instruction size based on the opcode. */
static int
thumb_insn_size (int opcode)
{
if ((unsigned int) opcode < 0xe800u)
return 2;
else if ((unsigned int) opcode >= 0xe8000000u)
return 4;
else
return 0;
}
static bfd_boolean
emit_insn (expressionS *exp, int nbytes)
{
int size = 0;
if (exp->X_op == O_constant)
{
size = nbytes;
if (size == 0)
size = thumb_insn_size (exp->X_add_number);
if (size != 0)
{
if (size == 2 && (unsigned int)exp->X_add_number > 0xffffu)
{
as_bad (_(".inst.n operand too big. "\
"Use .inst.w instead"));
size = 0;
}
else
{
if (now_it.state == AUTOMATIC_IT_BLOCK)
set_it_insn_type_nonvoid (OUTSIDE_IT_INSN, 0);
else
set_it_insn_type_nonvoid (NEUTRAL_IT_INSN, 0);
if (thumb_mode && (size > THUMB_SIZE) && !target_big_endian)
emit_thumb32_expr (exp);
else
emit_expr (exp, (unsigned int) size);
it_fsm_post_encode ();
}
}
else
as_bad (_("cannot determine Thumb instruction size. " \
"Use .inst.n/.inst.w instead"));
}
else
as_bad (_("constant expression required"));
return (size != 0);
}
/* Like s_arm_elf_cons but do not use md_cons_align and
set the mapping state to MAP_ARM/MAP_THUMB. */
static void
s_arm_elf_inst (int nbytes)
{
if (is_it_end_of_statement ())
{
demand_empty_rest_of_line ();
return;
}
/* Calling mapping_state () here will not change ARM/THUMB,
but will ensure not to be in DATA state. */
if (thumb_mode)
mapping_state (MAP_THUMB);
else
{
if (nbytes != 0)
{
as_bad (_("width suffixes are invalid in ARM mode"));
ignore_rest_of_line ();
return;
}
nbytes = 4;
mapping_state (MAP_ARM);
}
do
{
expressionS exp;
expression (& exp);
if (! emit_insn (& exp, nbytes))
{
ignore_rest_of_line ();
return;
}
}
while (*input_line_pointer++ == ',');
/* Put terminator back into stream. */
input_line_pointer --;
demand_empty_rest_of_line ();
}
/* Parse a .rel31 directive. */
static void
s_arm_rel31 (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
char *p;
valueT highbit;
highbit = 0;
if (*input_line_pointer == '1')
highbit = 0x80000000;
else if (*input_line_pointer != '0')
as_bad (_("expected 0 or 1"));
input_line_pointer++;
if (*input_line_pointer != ',')
as_bad (_("missing comma"));
input_line_pointer++;
#ifdef md_flush_pending_output
md_flush_pending_output ();
#endif
#ifdef md_cons_align
md_cons_align (4);
#endif
mapping_state (MAP_DATA);
expression (&exp);
p = frag_more (4);
md_number_to_chars (p, highbit, 4);
fix_new_arm (frag_now, p - frag_now->fr_literal, 4, &exp, 1,
BFD_RELOC_ARM_PREL31);
demand_empty_rest_of_line ();
}
/* Directives: AEABI stack-unwind tables. */
/* Parse an unwind_fnstart directive. Simply records the current location. */
static void
s_arm_unwind_fnstart (int ignored ATTRIBUTE_UNUSED)
{
demand_empty_rest_of_line ();
if (unwind.proc_start)
{
as_bad (_("duplicate .fnstart directive"));
return;
}
/* Mark the start of the function. */
unwind.proc_start = expr_build_dot ();
/* Reset the rest of the unwind info. */
unwind.opcode_count = 0;
unwind.table_entry = NULL;
unwind.personality_routine = NULL;
unwind.personality_index = -1;
unwind.frame_size = 0;
unwind.fp_offset = 0;
unwind.fp_reg = REG_SP;
unwind.fp_used = 0;
unwind.sp_restored = 0;
}
/* Parse a handlerdata directive. Creates the exception handling table entry
for the function. */
static void
s_arm_unwind_handlerdata (int ignored ATTRIBUTE_UNUSED)
{
demand_empty_rest_of_line ();
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
if (unwind.table_entry)
as_bad (_("duplicate .handlerdata directive"));
create_unwind_entry (1);
}
/* Parse an unwind_fnend directive. Generates the index table entry. */
static void
s_arm_unwind_fnend (int ignored ATTRIBUTE_UNUSED)
{
long where;
char *ptr;
valueT val;
unsigned int marked_pr_dependency;
demand_empty_rest_of_line ();
if (!unwind.proc_start)
{
as_bad (_(".fnend directive without .fnstart"));
return;
}
/* Add eh table entry. */
if (unwind.table_entry == NULL)
val = create_unwind_entry (0);
else
val = 0;
/* Add index table entry. This is two words. */
start_unwind_section (unwind.saved_seg, 1);
frag_align (2, 0, 0);
record_alignment (now_seg, 2);
ptr = frag_more (8);
memset (ptr, 0, 8);
where = frag_now_fix () - 8;
/* Self relative offset of the function start. */
fix_new (frag_now, where, 4, unwind.proc_start, 0, 1,
BFD_RELOC_ARM_PREL31);
/* Indicate dependency on EHABI-defined personality routines to the
linker, if it hasn't been done already. */
marked_pr_dependency
= seg_info (now_seg)->tc_segment_info_data.marked_pr_dependency;
if (unwind.personality_index >= 0 && unwind.personality_index < 3
&& !(marked_pr_dependency & (1 << unwind.personality_index)))
{
static const char *const name[] =
{
"__aeabi_unwind_cpp_pr0",
"__aeabi_unwind_cpp_pr1",
"__aeabi_unwind_cpp_pr2"
};
symbolS *pr = symbol_find_or_make (name[unwind.personality_index]);
fix_new (frag_now, where, 0, pr, 0, 1, BFD_RELOC_NONE);
seg_info (now_seg)->tc_segment_info_data.marked_pr_dependency
|= 1 << unwind.personality_index;
}
if (val)
/* Inline exception table entry. */
md_number_to_chars (ptr + 4, val, 4);
else
/* Self relative offset of the table entry. */
fix_new (frag_now, where + 4, 4, unwind.table_entry, 0, 1,
BFD_RELOC_ARM_PREL31);
/* Restore the original section. */
subseg_set (unwind.saved_seg, unwind.saved_subseg);
unwind.proc_start = NULL;
}
/* Parse an unwind_cantunwind directive. */
static void
s_arm_unwind_cantunwind (int ignored ATTRIBUTE_UNUSED)
{
demand_empty_rest_of_line ();
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
if (unwind.personality_routine || unwind.personality_index != -1)
as_bad (_("personality routine specified for cantunwind frame"));
unwind.personality_index = -2;
}
/* Parse a personalityindex directive. */
static void
s_arm_unwind_personalityindex (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
if (unwind.personality_routine || unwind.personality_index != -1)
as_bad (_("duplicate .personalityindex directive"));
expression (&exp);
if (exp.X_op != O_constant
|| exp.X_add_number < 0 || exp.X_add_number > 15)
{
as_bad (_("bad personality routine number"));
ignore_rest_of_line ();
return;
}
unwind.personality_index = exp.X_add_number;
demand_empty_rest_of_line ();
}
/* Parse a personality directive. */
static void
s_arm_unwind_personality (int ignored ATTRIBUTE_UNUSED)
{
char *name, *p, c;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
if (unwind.personality_routine || unwind.personality_index != -1)
as_bad (_("duplicate .personality directive"));
name = input_line_pointer;
c = get_symbol_end ();
p = input_line_pointer;
unwind.personality_routine = symbol_find_or_make (name);
*p = c;
demand_empty_rest_of_line ();
}
/* Parse a directive saving core registers. */
static void
s_arm_unwind_save_core (void)
{
valueT op;
long range;
int n;
range = parse_reg_list (&input_line_pointer);
if (range == FAIL)
{
as_bad (_("expected register list"));
ignore_rest_of_line ();
return;
}
demand_empty_rest_of_line ();
/* Turn .unwind_movsp ip followed by .unwind_save {..., ip, ...}
into .unwind_save {..., sp...}. We aren't bothered about the value of
ip because it is clobbered by calls. */
if (unwind.sp_restored && unwind.fp_reg == 12
&& (range & 0x3000) == 0x1000)
{
unwind.opcode_count--;
unwind.sp_restored = 0;
range = (range | 0x2000) & ~0x1000;
unwind.pending_offset = 0;
}
/* Pop r4-r15. */
if (range & 0xfff0)
{
/* See if we can use the short opcodes. These pop a block of up to 8
registers starting with r4, plus maybe r14. */
for (n = 0; n < 8; n++)
{
/* Break at the first non-saved register. */
if ((range & (1 << (n + 4))) == 0)
break;
}
/* See if there are any other bits set. */
if (n == 0 || (range & (0xfff0 << n) & 0xbff0) != 0)
{
/* Use the long form. */
op = 0x8000 | ((range >> 4) & 0xfff);
add_unwind_opcode (op, 2);
}
else
{
/* Use the short form. */
if (range & 0x4000)
op = 0xa8; /* Pop r14. */
else
op = 0xa0; /* Do not pop r14. */
op |= (n - 1);
add_unwind_opcode (op, 1);
}
}
/* Pop r0-r3. */
if (range & 0xf)
{
op = 0xb100 | (range & 0xf);
add_unwind_opcode (op, 2);
}
/* Record the number of bytes pushed. */
for (n = 0; n < 16; n++)
{
if (range & (1 << n))
unwind.frame_size += 4;
}
}
/* Parse a directive saving FPA registers. */
static void
s_arm_unwind_save_fpa (int reg)
{
expressionS exp;
int num_regs;
valueT op;
/* Get Number of registers to transfer. */
if (skip_past_comma (&input_line_pointer) != FAIL)
expression (&exp);
else
exp.X_op = O_illegal;
if (exp.X_op != O_constant)
{
as_bad (_("expected , <constant>"));
ignore_rest_of_line ();
return;
}
num_regs = exp.X_add_number;
if (num_regs < 1 || num_regs > 4)
{
as_bad (_("number of registers must be in the range [1:4]"));
ignore_rest_of_line ();
return;
}
demand_empty_rest_of_line ();
if (reg == 4)
{
/* Short form. */
op = 0xb4 | (num_regs - 1);
add_unwind_opcode (op, 1);
}
else
{
/* Long form. */
op = 0xc800 | (reg << 4) | (num_regs - 1);
add_unwind_opcode (op, 2);
}
unwind.frame_size += num_regs * 12;
}
/* Parse a directive saving VFP registers for ARMv6 and above. */
static void
s_arm_unwind_save_vfp_armv6 (void)
{
int count;
unsigned int start;
valueT op;
int num_vfpv3_regs = 0;
int num_regs_below_16;
count = parse_vfp_reg_list (&input_line_pointer, &start, REGLIST_VFP_D);
if (count == FAIL)
{
as_bad (_("expected register list"));
ignore_rest_of_line ();
return;
}
demand_empty_rest_of_line ();
/* We always generate FSTMD/FLDMD-style unwinding opcodes (rather
than FSTMX/FLDMX-style ones). */
/* Generate opcode for (VFPv3) registers numbered in the range 16 .. 31. */
if (start >= 16)
num_vfpv3_regs = count;
else if (start + count > 16)
num_vfpv3_regs = start + count - 16;
if (num_vfpv3_regs > 0)
{
int start_offset = start > 16 ? start - 16 : 0;
op = 0xc800 | (start_offset << 4) | (num_vfpv3_regs - 1);
add_unwind_opcode (op, 2);
}
/* Generate opcode for registers numbered in the range 0 .. 15. */
num_regs_below_16 = num_vfpv3_regs > 0 ? 16 - (int) start : count;
gas_assert (num_regs_below_16 + num_vfpv3_regs == count);
if (num_regs_below_16 > 0)
{
op = 0xc900 | (start << 4) | (num_regs_below_16 - 1);
add_unwind_opcode (op, 2);
}
unwind.frame_size += count * 8;
}
/* Parse a directive saving VFP registers for pre-ARMv6. */
static void
s_arm_unwind_save_vfp (void)
{
int count;
unsigned int reg;
valueT op;
count = parse_vfp_reg_list (&input_line_pointer, ®, REGLIST_VFP_D);
if (count == FAIL)
{
as_bad (_("expected register list"));
ignore_rest_of_line ();
return;
}
demand_empty_rest_of_line ();
if (reg == 8)
{
/* Short form. */
op = 0xb8 | (count - 1);
add_unwind_opcode (op, 1);
}
else
{
/* Long form. */
op = 0xb300 | (reg << 4) | (count - 1);
add_unwind_opcode (op, 2);
}
unwind.frame_size += count * 8 + 4;
}
/* Parse a directive saving iWMMXt data registers. */
static void
s_arm_unwind_save_mmxwr (void)
{
int reg;
int hi_reg;
int i;
unsigned mask = 0;
valueT op;
if (*input_line_pointer == '{')
input_line_pointer++;
do
{
reg = arm_reg_parse (&input_line_pointer, REG_TYPE_MMXWR);
if (reg == FAIL)
{
as_bad ("%s", _(reg_expected_msgs[REG_TYPE_MMXWR]));
goto error;
}
if (mask >> reg)
as_tsktsk (_("register list not in ascending order"));
mask |= 1 << reg;
if (*input_line_pointer == '-')
{
input_line_pointer++;
hi_reg = arm_reg_parse (&input_line_pointer, REG_TYPE_MMXWR);
if (hi_reg == FAIL)
{
as_bad ("%s", _(reg_expected_msgs[REG_TYPE_MMXWR]));
goto error;
}
else if (reg >= hi_reg)
{
as_bad (_("bad register range"));
goto error;
}
for (; reg < hi_reg; reg++)
mask |= 1 << reg;
}
}
while (skip_past_comma (&input_line_pointer) != FAIL);
skip_past_char (&input_line_pointer, '}');
demand_empty_rest_of_line ();
/* Generate any deferred opcodes because we're going to be looking at
the list. */
flush_pending_unwind ();
for (i = 0; i < 16; i++)
{
if (mask & (1 << i))
unwind.frame_size += 8;
}
/* Attempt to combine with a previous opcode. We do this because gcc
likes to output separate unwind directives for a single block of
registers. */
if (unwind.opcode_count > 0)
{
i = unwind.opcodes[unwind.opcode_count - 1];
if ((i & 0xf8) == 0xc0)
{
i &= 7;
/* Only merge if the blocks are contiguous. */
if (i < 6)
{
if ((mask & 0xfe00) == (1 << 9))
{
mask |= ((1 << (i + 11)) - 1) & 0xfc00;
unwind.opcode_count--;
}
}
else if (i == 6 && unwind.opcode_count >= 2)
{
i = unwind.opcodes[unwind.opcode_count - 2];
reg = i >> 4;
i &= 0xf;
op = 0xffff << (reg - 1);
if (reg > 0
&& ((mask & op) == (1u << (reg - 1))))
{
op = (1 << (reg + i + 1)) - 1;
op &= ~((1 << reg) - 1);
mask |= op;
unwind.opcode_count -= 2;
}
}
}
}
hi_reg = 15;
/* We want to generate opcodes in the order the registers have been
saved, ie. descending order. */
for (reg = 15; reg >= -1; reg--)
{
/* Save registers in blocks. */
if (reg < 0
|| !(mask & (1 << reg)))
{
/* We found an unsaved reg. Generate opcodes to save the
preceding block. */
if (reg != hi_reg)
{
if (reg == 9)
{
/* Short form. */
op = 0xc0 | (hi_reg - 10);
add_unwind_opcode (op, 1);
}
else
{
/* Long form. */
op = 0xc600 | ((reg + 1) << 4) | ((hi_reg - reg) - 1);
add_unwind_opcode (op, 2);
}
}
hi_reg = reg - 1;
}
}
return;
error:
ignore_rest_of_line ();
}
static void
s_arm_unwind_save_mmxwcg (void)
{
int reg;
int hi_reg;
unsigned mask = 0;
valueT op;
if (*input_line_pointer == '{')
input_line_pointer++;
skip_whitespace (input_line_pointer);
do
{
reg = arm_reg_parse (&input_line_pointer, REG_TYPE_MMXWCG);
if (reg == FAIL)
{
as_bad ("%s", _(reg_expected_msgs[REG_TYPE_MMXWCG]));
goto error;
}
reg -= 8;
if (mask >> reg)
as_tsktsk (_("register list not in ascending order"));
mask |= 1 << reg;
if (*input_line_pointer == '-')
{
input_line_pointer++;
hi_reg = arm_reg_parse (&input_line_pointer, REG_TYPE_MMXWCG);
if (hi_reg == FAIL)
{
as_bad ("%s", _(reg_expected_msgs[REG_TYPE_MMXWCG]));
goto error;
}
else if (reg >= hi_reg)
{
as_bad (_("bad register range"));
goto error;
}
for (; reg < hi_reg; reg++)
mask |= 1 << reg;
}
}
while (skip_past_comma (&input_line_pointer) != FAIL);
skip_past_char (&input_line_pointer, '}');
demand_empty_rest_of_line ();
/* Generate any deferred opcodes because we're going to be looking at
the list. */
flush_pending_unwind ();
for (reg = 0; reg < 16; reg++)
{
if (mask & (1 << reg))
unwind.frame_size += 4;
}
op = 0xc700 | mask;
add_unwind_opcode (op, 2);
return;
error:
ignore_rest_of_line ();
}
/* Parse an unwind_save directive.
If the argument is non-zero, this is a .vsave directive. */
static void
s_arm_unwind_save (int arch_v6)
{
char *peek;
struct reg_entry *reg;
bfd_boolean had_brace = FALSE;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
/* Figure out what sort of save we have. */
peek = input_line_pointer;
if (*peek == '{')
{
had_brace = TRUE;
peek++;
}
reg = arm_reg_parse_multi (&peek);
if (!reg)
{
as_bad (_("register expected"));
ignore_rest_of_line ();
return;
}
switch (reg->type)
{
case REG_TYPE_FN:
if (had_brace)
{
as_bad (_("FPA .unwind_save does not take a register list"));
ignore_rest_of_line ();
return;
}
input_line_pointer = peek;
s_arm_unwind_save_fpa (reg->number);
return;
case REG_TYPE_RN:
s_arm_unwind_save_core ();
return;
case REG_TYPE_VFD:
if (arch_v6)
s_arm_unwind_save_vfp_armv6 ();
else
s_arm_unwind_save_vfp ();
return;
case REG_TYPE_MMXWR:
s_arm_unwind_save_mmxwr ();
return;
case REG_TYPE_MMXWCG:
s_arm_unwind_save_mmxwcg ();
return;
default:
as_bad (_(".unwind_save does not support this kind of register"));
ignore_rest_of_line ();
}
}
/* Parse an unwind_movsp directive. */
static void
s_arm_unwind_movsp (int ignored ATTRIBUTE_UNUSED)
{
int reg;
valueT op;
int offset;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
reg = arm_reg_parse (&input_line_pointer, REG_TYPE_RN);
if (reg == FAIL)
{
as_bad ("%s", _(reg_expected_msgs[REG_TYPE_RN]));
ignore_rest_of_line ();
return;
}
/* Optional constant. */
if (skip_past_comma (&input_line_pointer) != FAIL)
{
if (immediate_for_directive (&offset) == FAIL)
return;
}
else
offset = 0;
demand_empty_rest_of_line ();
if (reg == REG_SP || reg == REG_PC)
{
as_bad (_("SP and PC not permitted in .unwind_movsp directive"));
return;
}
if (unwind.fp_reg != REG_SP)
as_bad (_("unexpected .unwind_movsp directive"));
/* Generate opcode to restore the value. */
op = 0x90 | reg;
add_unwind_opcode (op, 1);
/* Record the information for later. */
unwind.fp_reg = reg;
unwind.fp_offset = unwind.frame_size - offset;
unwind.sp_restored = 1;
}
/* Parse an unwind_pad directive. */
static void
s_arm_unwind_pad (int ignored ATTRIBUTE_UNUSED)
{
int offset;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
if (immediate_for_directive (&offset) == FAIL)
return;
if (offset & 3)
{
as_bad (_("stack increment must be multiple of 4"));
ignore_rest_of_line ();
return;
}
/* Don't generate any opcodes, just record the details for later. */
unwind.frame_size += offset;
unwind.pending_offset += offset;
demand_empty_rest_of_line ();
}
/* Parse an unwind_setfp directive. */
static void
s_arm_unwind_setfp (int ignored ATTRIBUTE_UNUSED)
{
int sp_reg;
int fp_reg;
int offset;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
fp_reg = arm_reg_parse (&input_line_pointer, REG_TYPE_RN);
if (skip_past_comma (&input_line_pointer) == FAIL)
sp_reg = FAIL;
else
sp_reg = arm_reg_parse (&input_line_pointer, REG_TYPE_RN);
if (fp_reg == FAIL || sp_reg == FAIL)
{
as_bad (_("expected <reg>, <reg>"));
ignore_rest_of_line ();
return;
}
/* Optional constant. */
if (skip_past_comma (&input_line_pointer) != FAIL)
{
if (immediate_for_directive (&offset) == FAIL)
return;
}
else
offset = 0;
demand_empty_rest_of_line ();
if (sp_reg != REG_SP && sp_reg != unwind.fp_reg)
{
as_bad (_("register must be either sp or set by a previous"
"unwind_movsp directive"));
return;
}
/* Don't generate any opcodes, just record the information for later. */
unwind.fp_reg = fp_reg;
unwind.fp_used = 1;
if (sp_reg == REG_SP)
unwind.fp_offset = unwind.frame_size - offset;
else
unwind.fp_offset -= offset;
}
/* Parse an unwind_raw directive. */
static void
s_arm_unwind_raw (int ignored ATTRIBUTE_UNUSED)
{
expressionS exp;
/* This is an arbitrary limit. */
unsigned char op[16];
int count;
if (!unwind.proc_start)
as_bad (MISSING_FNSTART);
expression (&exp);
if (exp.X_op == O_constant
&& skip_past_comma (&input_line_pointer) != FAIL)
{
unwind.frame_size += exp.X_add_number;
expression (&exp);
}
else
exp.X_op = O_illegal;
if (exp.X_op != O_constant)
{
as_bad (_("expected <offset>, <opcode>"));
ignore_rest_of_line ();
return;
}
count = 0;
/* Parse the opcode. */
for (;;)
{
if (count >= 16)
{
as_bad (_("unwind opcode too long"));
ignore_rest_of_line ();
}
if (exp.X_op != O_constant || exp.X_add_number & ~0xff)
{
as_bad (_("invalid unwind opcode"));
ignore_rest_of_line ();
return;
}
op[count++] = exp.X_add_number;
/* Parse the next byte. */
if (skip_past_comma (&input_line_pointer) == FAIL)
break;
expression (&exp);
}
/* Add the opcode bytes in reverse order. */
while (count--)
add_unwind_opcode (op[count], 1);
demand_empty_rest_of_line ();
}
/* Parse a .eabi_attribute directive. */
static void
s_arm_eabi_attribute (int ignored ATTRIBUTE_UNUSED)
{
int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
if (tag < NUM_KNOWN_OBJ_ATTRIBUTES)
attributes_set_explicitly[tag] = 1;
}
/* Emit a tls fix for the symbol. */
static void
s_arm_tls_descseq (int ignored ATTRIBUTE_UNUSED)
{
char *p;
expressionS exp;
#ifdef md_flush_pending_output
md_flush_pending_output ();
#endif
#ifdef md_cons_align
md_cons_align (4);
#endif
/* Since we're just labelling the code, there's no need to define a
mapping symbol. */
expression (&exp);
p = obstack_next_free (&frchain_now->frch_obstack);
fix_new_arm (frag_now, p - frag_now->fr_literal, 4, &exp, 0,
thumb_mode ? BFD_RELOC_ARM_THM_TLS_DESCSEQ
: BFD_RELOC_ARM_TLS_DESCSEQ);
}
#endif /* OBJ_ELF */
static void s_arm_arch (int);
static void s_arm_object_arch (int);
static void s_arm_cpu (int);
static void s_arm_fpu (int);
static void s_arm_arch_extension (int);
#ifdef TE_PE
static void
pe_directive_secrel (int dummy ATTRIBUTE_UNUSED)
{
expressionS exp;
do
{
expression (&exp);
if (exp.X_op == O_symbol)
exp.X_op = O_secrel;
emit_expr (&exp, 4);
}
while (*input_line_pointer++ == ',');
input_line_pointer--;
demand_empty_rest_of_line ();
}
#endif /* TE_PE */
/* 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 },
/* Following two are likewise never called. */
{ "dn", s_dn, 0 },
{ "qn", s_qn, 0 },
{ "unreq", s_unreq, 0 },
{ "bss", s_bss, 0 },
{ "align", s_align, 0 },
{ "arm", s_arm, 0 },
{ "thumb", s_thumb, 0 },
{ "code", s_code, 0 },
{ "force_thumb", s_force_thumb, 0 },
{ "thumb_func", s_thumb_func, 0 },
{ "thumb_set", s_thumb_set, 0 },
{ "even", s_even, 0 },
{ "ltorg", s_ltorg, 0 },
{ "pool", s_ltorg, 0 },
{ "syntax", s_syntax, 0 },
{ "cpu", s_arm_cpu, 0 },
{ "arch", s_arm_arch, 0 },
{ "object_arch", s_arm_object_arch, 0 },
{ "fpu", s_arm_fpu, 0 },
{ "arch_extension", s_arm_arch_extension, 0 },
#ifdef OBJ_ELF
{ "word", s_arm_elf_cons, 4 },
{ "long", s_arm_elf_cons, 4 },
{ "inst.n", s_arm_elf_inst, 2 },
{ "inst.w", s_arm_elf_inst, 4 },
{ "inst", s_arm_elf_inst, 0 },
{ "rel31", s_arm_rel31, 0 },
{ "fnstart", s_arm_unwind_fnstart, 0 },
{ "fnend", s_arm_unwind_fnend, 0 },
{ "cantunwind", s_arm_unwind_cantunwind, 0 },
{ "personality", s_arm_unwind_personality, 0 },
{ "personalityindex", s_arm_unwind_personalityindex, 0 },
{ "handlerdata", s_arm_unwind_handlerdata, 0 },
{ "save", s_arm_unwind_save, 0 },
{ "vsave", s_arm_unwind_save, 1 },
{ "movsp", s_arm_unwind_movsp, 0 },
{ "pad", s_arm_unwind_pad, 0 },
{ "setfp", s_arm_unwind_setfp, 0 },
{ "unwind_raw", s_arm_unwind_raw, 0 },
{ "eabi_attribute", s_arm_eabi_attribute, 0 },
{ "tlsdescseq", s_arm_tls_descseq, 0 },
#else
{ "word", cons, 4},
/* These are used for dwarf. */
{"2byte", cons, 2},
{"4byte", cons, 4},
{"8byte", cons, 8},
/* These are used for dwarf2. */
{ "file", (void (*) (int)) dwarf2_directive_file, 0 },
{ "loc", dwarf2_directive_loc, 0 },
{ "loc_mark_labels", dwarf2_directive_loc_mark_labels, 0 },
#endif
{ "extend", float_cons, 'x' },
{ "ldouble", float_cons, 'x' },
{ "packed", float_cons, 'p' },
#ifdef TE_PE
{"secrel32", pe_directive_secrel, 0},
#endif
/* These are for compatibility with CodeComposer Studio. */
{"ref", s_ccs_ref, 0},
{"def", s_ccs_def, 0},
{"asmfunc", s_ccs_asmfunc, 0},
{"endasmfunc", s_ccs_endasmfunc, 0},
{ 0, 0, 0 }
};
/* Parser functions used exclusively in instruction operands. */
/* Generic immediate-value read function for use in insn parsing.
STR points to the beginning of the immediate (the leading #);
VAL receives the value; if the value is outside [MIN, MAX]
issue an error. PREFIX_OPT is true if the immediate prefix is
optional. */
static int
parse_immediate (char **str, int *val, int min, int max,
bfd_boolean prefix_opt)
{
expressionS exp;
my_get_expression (&exp, str, prefix_opt ? GE_OPT_PREFIX : GE_IMM_PREFIX);
if (exp.X_op != O_constant)
{
inst.error = _("constant expression required");
return FAIL;
}
if (exp.X_add_number < min || exp.X_add_number > max)
{
inst.error = _("immediate value out of range");
return FAIL;
}
*val = exp.X_add_number;
return SUCCESS;
}
/* Less-generic immediate-value read function with the possibility of loading a
big (64-bit) immediate, as required by Neon VMOV, VMVN and logic immediate
instructions. Puts the result directly in inst.operands[i]. */
static int
parse_big_immediate (char **str, int i, expressionS *in_exp,
bfd_boolean allow_symbol_p)
{
expressionS exp;
expressionS *exp_p = in_exp ? in_exp : &exp;
char *ptr = *str;
my_get_expression (exp_p, &ptr, GE_OPT_PREFIX_BIG);
if (exp_p->X_op == O_constant)
{
inst.operands[i].imm = exp_p->X_add_number & 0xffffffff;
/* If we're on a 64-bit host, then a 64-bit number can be returned using
O_constant. We have to be careful not to break compilation for
32-bit X_add_number, though. */
if ((exp_p->X_add_number & ~(offsetT)(0xffffffffU)) != 0)
{
/* X >> 32 is illegal if sizeof (exp_p->X_add_number) == 4. */
inst.operands[i].reg = (((exp_p->X_add_number >> 16) >> 16)
& 0xffffffff);
inst.operands[i].regisimm = 1;
}
}
else if (exp_p->X_op == O_big
&& LITTLENUM_NUMBER_OF_BITS * exp_p->X_add_number > 32)
{
unsigned parts = 32 / LITTLENUM_NUMBER_OF_BITS, j, idx = 0;
/* Bignums have their least significant bits in
generic_bignum[0]. Make sure we put 32 bits in imm and
32 bits in reg, in a (hopefully) portable way. */
gas_assert (parts != 0);
/* Make sure that the number is not too big.
PR 11972: Bignums can now be sign-extended to the
size of a .octa so check that the out of range bits
are all zero or all one. */
if (LITTLENUM_NUMBER_OF_BITS * exp_p->X_add_number > 64)
{
LITTLENUM_TYPE m = -1;
if (generic_bignum[parts * 2] != 0
&& generic_bignum[parts * 2] != m)
return FAIL;
for (j = parts * 2 + 1; j < (unsigned) exp_p->X_add_number; j++)
if (generic_bignum[j] != generic_bignum[j-1])
return FAIL;
}
inst.operands[i].imm = 0;
for (j = 0; j < parts; j++, idx++)
inst.operands[i].imm |= generic_bignum[idx]
<< (LITTLENUM_NUMBER_OF_BITS * j);
inst.operands[i].reg = 0;
for (j = 0; j < parts; j++, idx++)
inst.operands[i].reg |= generic_bignum[idx]
<< (LITTLENUM_NUMBER_OF_BITS * j);
inst.operands[i].regisimm = 1;
}
else if (!(exp_p->X_op == O_symbol && allow_symbol_p))
return FAIL;
*str = ptr;
return SUCCESS;
}
/* Returns the pseudo-register number of an FPA immediate constant,
or FAIL if there isn't a valid constant here. */
static int
parse_fpa_immediate (char ** str)
{
LITTLENUM_TYPE words[MAX_LITTLENUMS];
char * save_in;
expressionS exp;
int i;
int j;
/* First try and match exact strings, this is to guarantee
that some formats will work even for cross assembly. */
for (i = 0; fp_const[i]; i++)
{
if (strncmp (*str, fp_const[i], strlen (fp_const[i])) == 0)
{
char *start = *str;
*str += strlen (fp_const[i]);
if (is_end_of_line[(unsigned char) **str])
return i + 8;
*str = start;
}
}
/* Just because we didn't get a match doesn't mean that the constant
isn't valid, just that it is in a format that we don't
automatically recognize. Try parsing it with the standard
expression routines. */
memset (words, 0, MAX_LITTLENUMS * sizeof (LITTLENUM_TYPE));
/* Look for a raw floating point number. */
if ((save_in = atof_ieee (*str, 'x', words)) != NULL
&& is_end_of_line[(unsigned char) *save_in])
{
for (i = 0; i < NUM_FLOAT_VALS; i++)
{
for (j = 0; j < MAX_LITTLENUMS; j++)
{
if (words[j] != fp_values[i][j])
break;
}
if (j == MAX_LITTLENUMS)
{
*str = save_in;
return i + 8;
}
}
}
/* Try and parse a more complex expression, this will probably fail
unless the code uses a floating point prefix (eg "0f"). */
save_in = input_line_pointer;
input_line_pointer = *str;
if (expression (&exp) == absolute_section
&& exp.X_op == O_big
&& exp.X_add_number < 0)
{
/* FIXME: 5 = X_PRECISION, should be #define'd where we can use it.
Ditto for 15. */
if (gen_to_words (words, 5, (long) 15) == 0)
{
for (i = 0; i < NUM_FLOAT_VALS; i++)
{
for (j = 0; j < MAX_LITTLENUMS; j++)
{
if (words[j] != fp_values[i][j])
break;
}
if (j == MAX_LITTLENUMS)
{
*str = input_line_pointer;
input_line_pointer = save_in;
return i + 8;
}
}
}
}
*str = input_line_pointer;
input_line_pointer = save_in;
inst.error = _("invalid FPA immediate expression");
return FAIL;
}
/* Returns 1 if a number has "quarter-precision" float format
0baBbbbbbc defgh000 00000000 00000000. */
static int
is_quarter_float (unsigned imm)
{
int bs = (imm & 0x20000000) ? 0x3e000000 : 0x40000000;
return (imm & 0x7ffff) == 0 && ((imm & 0x7e000000) ^ bs) == 0;
}
/* Detect the presence of a floating point or integer zero constant,
i.e. #0.0 or #0. */
static bfd_boolean
parse_ifimm_zero (char **in)
{
int error_code;
if (!is_immediate_prefix (**in))
return FALSE;
++*in;
/* Accept #0x0 as a synonym for #0. */
if (strncmp (*in, "0x", 2) == 0)
{
int val;
if (parse_immediate (in, &val, 0, 0, TRUE) == FAIL)
return FALSE;
return TRUE;
}
error_code = atof_generic (in, ".", EXP_CHARS,
&generic_floating_point_number);
if (!error_code
&& generic_floating_point_number.sign == '+'
&& (generic_floating_point_number.low
> generic_floating_point_number.leader))
return TRUE;
return FALSE;
}
/* Parse an 8-bit "quarter-precision" floating point number of the form:
0baBbbbbbc defgh000 00000000 00000000.
The zero and minus-zero cases need special handling, since they can't be
encoded in the "quarter-precision" float format, but can nonetheless be
loaded as integer constants. */
static unsigned
parse_qfloat_immediate (char **ccp, int *immed)
{
char *str = *ccp;
char *fpnum;
LITTLENUM_TYPE words[MAX_LITTLENUMS];
int found_fpchar = 0;
skip_past_char (&str, '#');
/* 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'.
FIXME: This is a horrible hack, but doing better is tricky because type
information isn't in a very usable state at parse time. */
fpnum = str;
skip_whitespace (fpnum);
if (strncmp (fpnum, "0x", 2) == 0)
return FAIL;
else
{
for (; *fpnum != '\0' && *fpnum != ' ' && *fpnum != '\n'; fpnum++)
if (*fpnum == '.' || *fpnum == 'e' || *fpnum == 'E')
{
found_fpchar = 1;
break;
}
if (!found_fpchar)
return FAIL;
}
if ((str = atof_ieee (str, 's', words)) != NULL)
{
unsigned fpword = 0;
int i;
/* 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 (is_quarter_float (fpword) || (fpword & 0x7fffffff) == 0)
*immed = fpword;
else
return FAIL;
*ccp = str;
return SUCCESS;
}
return FAIL;
}
/* Shift operands. */
enum shift_kind
{
SHIFT_LSL, SHIFT_LSR, SHIFT_ASR, SHIFT_ROR, SHIFT_RRX
};
struct asm_shift_name
{
const char *name;
enum shift_kind kind;
};
/* Third argument to parse_shift. */
enum parse_shift_mode
{
NO_SHIFT_RESTRICT, /* Any kind of shift is accepted. */
SHIFT_IMMEDIATE, /* Shift operand must be an immediate. */
SHIFT_LSL_OR_ASR_IMMEDIATE, /* Shift must be LSL or ASR immediate. */
SHIFT_ASR_IMMEDIATE, /* Shift must be ASR immediate. */
SHIFT_LSL_IMMEDIATE, /* Shift must be LSL immediate. */
};
/* Parse a <shift> specifier on an ARM data processing instruction.
This has three forms:
(LSL|LSR|ASL|ASR|ROR) Rs
(LSL|LSR|ASL|ASR|ROR) #imm
RRX
Note that ASL is assimilated to LSL in the instruction encoding, and
RRX to ROR #0 (which cannot be written as such). */
static int
parse_shift (char **str, int i, enum parse_shift_mode mode)
{
const struct asm_shift_name *shift_name;
enum shift_kind shift;
char *s = *str;
char *p = s;
int reg;
for (p = *str; ISALPHA (*p); p++)
;
if (p == *str)
{
inst.error = _("shift expression expected");
return FAIL;
}
shift_name = (const struct asm_shift_name *) hash_find_n (arm_shift_hsh, *str,
p - *str);
if (shift_name == NULL)
{
inst.error = _("shift expression expected");
return FAIL;
}
shift = shift_name->kind;
switch (mode)
{
case NO_SHIFT_RESTRICT:
case SHIFT_IMMEDIATE: break;
case SHIFT_LSL_OR_ASR_IMMEDIATE:
if (shift != SHIFT_LSL && shift != SHIFT_ASR)
{
inst.error = _("'LSL' or 'ASR' required");
return FAIL;
}
break;
case SHIFT_LSL_IMMEDIATE:
if (shift != SHIFT_LSL)
{
inst.error = _("'LSL' required");
return FAIL;
}
break;
case SHIFT_ASR_IMMEDIATE:
if (shift != SHIFT_ASR)
{
inst.error = _("'ASR' required");
return FAIL;
}
break;
default: abort ();
}
if (shift != SHIFT_RRX)
{
/* Whitespace can appear here if the next thing is a bare digit. */
skip_whitespace (p);
if (mode == NO_SHIFT_RESTRICT
&& (reg = arm_reg_parse (&p, REG_TYPE_RN)) != FAIL)
{
inst.operands[i].imm = reg;
inst.operands[i].immisreg = 1;
}
else if (my_get_expression (&inst.reloc.exp, &p, GE_IMM_PREFIX))
return FAIL;
}
inst.operands[i].shift_kind = shift;
inst.operands[i].shifted = 1;
*str = p;
return SUCCESS;
}
/* Parse a <shifter_operand> for an ARM data processing instruction:
#<immediate>
#<immediate>, <rotate>
<Rm>
<Rm>, <shift>
where <shift> is defined by parse_shift above, and <rotate> is a
multiple of 2 between 0 and 30. Validation of immediate operands
is deferred to md_apply_fix. */
static int
parse_shifter_operand (char **str, int i)
{
int value;
expressionS exp;
if ((value = arm_reg_parse (str, REG_TYPE_RN)) != FAIL)
{
inst.operands[i].reg = value;
inst.operands[i].isreg = 1;
/* parse_shift will override this if appropriate */
inst.reloc.exp.X_op = O_constant;
inst.reloc.exp.X_add_number = 0;
if (skip_past_comma (str) == FAIL)
return SUCCESS;
/* Shift operation on register. */
return parse_shift (str, i, NO_SHIFT_RESTRICT);
}
if (my_get_expression (&inst.reloc.exp, str, GE_IMM_PREFIX))
return FAIL;
if (skip_past_comma (str) == SUCCESS)
{
/* #x, y -- ie explicit rotation by Y. */
if (my_get_expression (&exp, str, GE_NO_PREFIX))
return FAIL;
if (exp.X_op != O_constant || inst.reloc.exp.X_op != O_constant)
{
inst.error = _("constant expression expected");
return FAIL;
}
value = exp.X_add_number;
if (value < 0 || value > 30 || value % 2 != 0)
{
inst.error = _("invalid rotation");
return FAIL;
}
if (inst.reloc.exp.X_add_number < 0 || inst.reloc.exp.X_add_number > 255)
{
inst.error = _("invalid constant");
return FAIL;
}
/* Encode as specified. */
inst.operands[i].imm = inst.reloc.exp.X_add_number | value << 7;
return SUCCESS;
}
inst.reloc.type = BFD_RELOC_ARM_IMMEDIATE;
inst.reloc.pc_rel = 0;
return SUCCESS;
}
/* Group relocation information. Each entry in the table contains the
textual name of the relocation as may appear in assembler source
and must end with a colon.
Along with this textual name are the relocation codes to be used if
the corresponding instruction is an ALU instruction (ADD or SUB only),
an LDR, an LDRS, or an LDC. */
struct group_reloc_table_entry
{
const char *name;
int alu_code;
int ldr_code;
int ldrs_code;
int ldc_code;
};
typedef enum
{
/* Varieties of non-ALU group relocation. */
GROUP_LDR,
GROUP_LDRS,
GROUP_LDC
} group_reloc_type;
static struct group_reloc_table_entry group_reloc_table[] =
{ /* Program counter relative: */
{ "pc_g0_nc",
BFD_RELOC_ARM_ALU_PC_G0_NC, /* ALU */
0, /* LDR */
0, /* LDRS */
0 }, /* LDC */
{ "pc_g0",
BFD_RELOC_ARM_ALU_PC_G0, /* ALU */
BFD_RELOC_ARM_LDR_PC_G0, /* LDR */
BFD_RELOC_ARM_LDRS_PC_G0, /* LDRS */
BFD_RELOC_ARM_LDC_PC_G0 }, /* LDC */
{ "pc_g1_nc",
BFD_RELOC_ARM_ALU_PC_G1_NC, /* ALU */
0, /* LDR */
0, /* LDRS */
0 }, /* LDC */
{ "pc_g1",
BFD_RELOC_ARM_ALU_PC_G1, /* ALU */
BFD_RELOC_ARM_LDR_PC_G1, /* LDR */
BFD_RELOC_ARM_LDRS_PC_G1, /* LDRS */
BFD_RELOC_ARM_LDC_PC_G1 }, /* LDC */
{ "pc_g2",
BFD_RELOC_ARM_ALU_PC_G2, /* ALU */
BFD_RELOC_ARM_LDR_PC_G2, /* LDR */
BFD_RELOC_ARM_LDRS_PC_G2, /* LDRS */
BFD_RELOC_ARM_LDC_PC_G2 }, /* LDC */
/* Section base relative */
{ "sb_g0_nc",
BFD_RELOC_ARM_ALU_SB_G0_NC, /* ALU */
0, /* LDR */
0, /* LDRS */
0 }, /* LDC */
{ "sb_g0",
BFD_RELOC_ARM_ALU_SB_G0, /* ALU */
BFD_RELOC_ARM_LDR_SB_G0, /* LDR */
BFD_RELOC_ARM_LDRS_SB_G0, /* LDRS */
BFD_RELOC_ARM_LDC_SB_G0 }, /* LDC */
{ "sb_g1_nc",
BFD_RELOC_ARM_ALU_SB_G1_NC, /* ALU */
0, /* LDR */
0, /* LDRS */
0 }, /* LDC */
{ "sb_g1",
BFD_RELOC_ARM_ALU_SB_G1, /* ALU */
BFD_RELOC_ARM_LDR_SB_G1, /* LDR */
BFD_RELOC_ARM_LDRS_SB_G1, /* LDRS */
BFD_RELOC_ARM_LDC_SB_G1 }, /* LDC */
{ "sb_g2",
BFD_RELOC_ARM_ALU_SB_G2, /* ALU */
BFD_RELOC_ARM_LDR_SB_G2, /* LDR */
BFD_RELOC_ARM_LDRS_SB_G2, /* LDRS */
BFD_RELOC_ARM_LDC_SB_G2 } }; /* LDC */
/* Given the address of a pointer pointing to the textual name of a group
relocation as may appear in assembler source, attempt to find its details
in group_reloc_table. The pointer will be updated to the character after
the trailing colon. On failure, FAIL will be returned; SUCCESS
otherwise. On success, *entry will be updated to point at the relevant
group_reloc_table entry. */
static int
find_group_reloc_table_entry (char **str, struct group_reloc_table_entry **out)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE (group_reloc_table); i++)
{
int length = strlen (group_reloc_table[i].name);
if (strncasecmp (group_reloc_table[i].name, *str, length) == 0
&& (*str)[length] == ':')
{
*out = &group_reloc_table[i];
*str += (length + 1);
return SUCCESS;
}
}
return FAIL;
}
/* Parse a <shifter_operand> for an ARM data processing instruction
(as for parse_shifter_operand) where group relocations are allowed:
#<immediate>
#<immediate>, <rotate>
#:<group_reloc>:<expression>
<Rm>
<Rm>, <shift>
where <group_reloc> is one of the strings defined in group_reloc_table.
The hashes are optional.
Everything else is as for parse_shifter_operand. */
static parse_operand_result
parse_shifter_operand_group_reloc (char **str, int i)
{
/* Determine if we have the sequence of characters #: or just :
coming next. If we do, then we check for a group relocation.
If we don't, punt the whole lot to parse_shifter_operand. */
if (((*str)[0] == '#' && (*str)[1] == ':')
|| (*str)[0] == ':')
{
struct group_reloc_table_entry *entry;
if ((*str)[0] == '#')
(*str) += 2;
else
(*str)++;
/* Try to parse a group relocation. Anything else is an error. */
if (find_group_reloc_table_entry (str, &entry) == FAIL)
{
inst.error = _("unknown group relocation");
return PARSE_OPERAND_FAIL_NO_BACKTRACK;
}
/* 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 (&inst.reloc.exp, str, GE_NO_PREFIX))
return PARSE_OPERAND_FAIL_NO_BACKTRACK;
/* Record the relocation type (always the ALU variant here). */
inst.reloc.type = (bfd_reloc_code_real_type) entry->alu_code;
gas_assert (inst.reloc.type != 0);
return PARSE_OPERAND_SUCCESS;
}
else
return parse_shifter_operand (str, i) == SUCCESS
? PARSE_OPERAND_SUCCESS : PARSE_OPERAND_FAIL;
/* Never reached. */
}
/* Parse a Neon alignment expression. Information is written to
inst.operands[i]. We assume the initial ':' has been skipped.
align .imm = align << 8, .immisalign=1, .preind=0 */
static parse_operand_result
parse_neon_alignment (char **str, int i)
{
char *p = *str;
expressionS exp;
my_get_expression (&exp, &p, GE_NO_PREFIX);
if (exp.X_op != O_constant)
{
inst.error = _("alignment must be constant");
return PARSE_OPERAND_FAIL;
}
inst.operands[i].imm = exp.X_add_number << 8;
inst.operands[i].immisalign = 1;
/* Alignments are not pre-indexes. */
inst.operands[i].preind = 0;
*str = p;
return PARSE_OPERAND_SUCCESS;
}
/* Parse all forms of an ARM address expression. Information is written
to inst.operands[i] and/or inst.reloc.
Preindexed addressing (.preind=1):
[Rn, #offset] .reg=Rn .reloc.exp=offset
[Rn, +/-Rm] .reg=Rn .imm=Rm .immisreg=1 .negative=0/1
[Rn, +/-Rm, shift] .reg=Rn .imm=Rm .immisreg=1 .negative=0/1
.shift_kind=shift .reloc.exp=shift_imm
These three may have a trailing ! which causes .writeback to be set also.
Postindexed addressing (.postind=1, .writeback=1):
[Rn], #offset .reg=Rn .reloc.exp=offset
[Rn], +/-Rm .reg=Rn .imm=Rm .immisreg=1 .negative=0/1
[Rn], +/-Rm, shift .reg=Rn .imm=Rm .immisreg=1 .negative=0/1
.shift_kind=shift .reloc.exp=shift_imm
Unindexed addressing (.preind=0, .postind=0):
[Rn], {option} .reg=Rn .imm=option .immisreg=0
Other:
[Rn]{!} shorthand for [Rn,#0]{!}
=immediate .isreg=0 .reloc.exp=immediate
label .reg=PC .reloc.pc_rel=1 .reloc.exp=label
It is the caller's responsibility to check for addressing modes not
supported by the instruction, and to set inst.reloc.type. */
static parse_operand_result
parse_address_main (char **str, int i, int group_relocations,
group_reloc_type group_type)
{
char *p = *str;
int reg;
if (skip_past_char (&p, '[') == FAIL)
{
if (skip_past_char (&p, '=') == FAIL)
{
/* Bare address - translate to PC-relative offset. */
inst.reloc.pc_rel = 1;
inst.operands[i].reg = REG_PC;
inst.operands[i].isreg = 1;
inst.operands[i].preind = 1;
if (my_get_expression (&inst.reloc.exp, &p, GE_OPT_PREFIX_BIG))
return PARSE_OPERAND_FAIL;
}
else if (parse_big_immediate (&p, i, &inst.reloc.exp,
/*allow_symbol_p=*/TRUE))
return PARSE_OPERAND_FAIL;
*str = p;
return PARSE_OPERAND_SUCCESS;
}
/* PR gas/14887: Allow for whitespace after the opening bracket. */
skip_whitespace (p);
if ((reg = arm_reg_parse (&p, REG_TYPE_RN)) == FAIL)
{
inst.error = _(reg_expected_msgs[REG_TYPE_RN]);
return PARSE_OPERAND_FAIL;
}
inst.operands[i].reg = reg;
inst.operands[i].isreg = 1;
if (skip_past_comma (&p) == SUCCESS)
{
inst.operands[i].preind = 1;
if (*p == '+') p++;
else if (*p == '-') p++, inst.operands[i].negative = 1;
if ((reg = arm_reg_parse (&p, REG_TYPE_RN)) != FAIL)
{
inst.operands[i].imm = reg;
inst.operands[i].immisreg = 1;
if (skip_past_comma (&p) == SUCCESS)
if (parse_shift (&p, i, SHIFT_IMMEDIATE) == FAIL)
return PARSE_OPERAND_FAIL;
}
else if (skip_past_char (&p, ':') == SUCCESS)
{
/* FIXME: '@' should be used here, but it's filtered out by generic
code before we get to see it here. This may be subject to
change. */
parse_operand_result result = parse_neon_alignment (&p, i);
if (result != PARSE_OPERAND_SUCCESS)
return result;
}
else
{
if (inst.operands[i].negative)
{
inst.operands[i].negative = 0;
p--;
}
if (group_relocations
&& ((*p == '#' && *(p + 1) == ':') || *p == ':'))
{
struct group_reloc_table_entry *entry;
/* Skip over the #: or : sequence. */
if (*p == '#')
p += 2;
else
p++;
/* Try to parse a group relocation. Anything else is an
error. */
if (find_group_reloc_table_entry (&p, &entry) == FAIL)
{
inst.error = _("unknown group relocation");
return PARSE_OPERAND_FAIL_NO_BACKTRACK;
}
/* 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 (&inst.reloc.exp, &p, GE_NO_PREFIX))
return PARSE_OPERAND_FAIL_NO_BACKTRACK;
/* Record the relocation type. */
switch (group_type)
{
case GROUP_LDR:
inst.reloc.type = (bfd_reloc_code_real_type) entry->ldr_code;
break;
case GROUP_LDRS:
inst.reloc.type = (bfd_reloc_code_real_type) entry->ldrs_code;
break;
case GROUP_LDC:
inst.reloc.type = (bfd_reloc_code_real_type) entry->ldc_code;
break;
default:
gas_assert (0);
}
if (inst.reloc.type == 0)
{
inst.error = _("this group relocation is not allowed on this instruction");
return PARSE_OPERAND_FAIL_NO_BACKTRACK;
}
}
else
{
char *q = p;
if (my_get_expression (&inst.reloc.exp, &p, GE_IMM_PREFIX))
return PARSE_OPERAND_FAIL;
/* If the offset is 0, find out if it's a +0 or -0. */
if (inst.reloc.exp.X_op == O_constant
&& inst.reloc.exp.X_add_number == 0)
{
skip_whitespace (q);
if (*q == '#')
{
q++;
skip_whitespace (q);
}
if (*q == '-')
inst.operands[i].negative = 1;
}
}
}
}
else if (skip_past_char (&p, ':') == SUCCESS)
{
/* FIXME: '@' should be used here, but it's filtered out by generic code
before we get to see it here. This may be subject to change. */
parse_operand_result result = parse_neon_alignment (&p, i);
if (result != PARSE_OPERAND_SUCCESS)
return result;
}
if (skip_past_char (&p, ']') == FAIL)
{
inst.error = _("']' expected");
return PARSE_OPERAND_FAIL;
}
if (skip_past_char (&p, '!') == SUCCESS)
inst.operands[i].writeback = 1;
else if (skip_past_comma (&p) == SUCCESS)
{
if (skip_past_char (&p, '{') == SUCCESS)
{
/* [Rn], {expr} - unindexed, with option */
if (parse_immediate (&p, &inst.operands[i].imm,
0, 255, TRUE) == FAIL)
return PARSE_OPERAND_FAIL;
if (skip_past_char (&p, '}') == FAIL)
{
inst.error = _("'}' expected at end of 'option' field");
return PARSE_OPERAND_FAIL;
}
if (inst.operands[i].preind)
{
inst.error = _("cannot combine index with option");
return PARSE_OPERAND_FAIL;
}
*str = p;
return PARSE_OPERAND_SUCCESS;
}
else
{
inst.operands[i].postind = 1;
inst.operands[i].writeback = 1;
if (inst.operands[i].preind)
{
inst.error = _("cannot combine pre- and post-indexing");
return PARSE_OPERAND_FAIL;
}
if (*p == '+') p++;
else if (*p == '-') p++, inst.operands[i].negative = 1;
if ((reg = arm_reg_parse (&p, REG_TYPE_RN)) != FAIL)
{
/* We might be using the immediate for alignment already. If we
are, OR the register number into the low-order bits. */
if (inst.operands[i].immisalign)
inst.operands[i].imm |= reg;
else
inst.operands[i].imm = reg;
inst.operands[i].immisreg = 1;
if (skip_past_comma (&p) == SUCCESS)
if (parse_shift (&p, i, SHIFT_IMMEDIATE) == FAIL)
return PARSE_OPERAND_FAIL;
}
else
{
char *q = p;
if (inst.operands[i].negative)
{
inst.operands[i].negative = 0;
p--;
}
if (my_get_expression (&inst.reloc.exp, &p, GE_IMM_PREFIX))
return PARSE_OPERAND_FAIL;
/* If the offset is 0, find out if it's a +0 or -0. */
if (inst.reloc.exp.X_op == O_constant
&& inst.reloc.exp.X_add_number == 0)
{
skip_whitespace (q);
if (*q == '#')
{
q++;
skip_whitespace (q);
}
if (*q == '-')
inst.operands[i].negative = 1;
}
}
}
}
/* If at this point neither .preind nor .postind is set, we have a
bare [Rn]{!}, which is shorthand for [Rn,#0]{!}. */
if (inst.operands[i].preind == 0 && inst.operands[i].postind == 0)
{
inst.operands[i].preind = 1;
inst.reloc.exp.X_op = O_constant;
inst.reloc.exp.X_add_number = 0;
}
*str = p;
return PARSE_OPERAND_SUCCESS;
}
static int
parse_address (char **str, int i)
{
return parse_address_main (str, i, 0, GROUP_LDR) == PARSE_OPERAND_SUCCESS
? SUCCESS : FAIL;
}
static parse_operand_result
parse_address_group_reloc (char **str, int i, group_reloc_type type)
{
return parse_address_main (str, i, 1, type);
}
/* Parse an operand for a MOVW or MOVT instruction. */
static int
parse_half (char **str)
{
char * p;
p = *str;
skip_past_char (&p, '#');
if (strncasecmp (p, ":lower16:", 9) == 0)
inst.reloc.type = BFD_RELOC_ARM_MOVW;
else if (strncasecmp (p, ":upper16:", 9) == 0)
inst.reloc.type = BFD_RELOC_ARM_MOVT;
if (inst.reloc.type != BFD_RELOC_UNUSED)
{
p += 9;
skip_whitespace (p);
}
if (my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX))
return FAIL;
if (inst.reloc.type == BFD_RELOC_UNUSED)
{
if (inst.reloc.exp.X_op != O_constant)
{
inst.error = _("constant expression expected");
return FAIL;
}
if (inst.reloc.exp.X_add_number < 0
|| inst.reloc.exp.X_add_number > 0xffff)
{
inst.error = _("immediate value out of range");
return FAIL;
}
}
*str = p;
return SUCCESS;
}
/* Miscellaneous. */
/* Parse a PSR flag operand. The value returned is FAIL on syntax error,
or a bitmask suitable to be or-ed into the ARM msr instruction. */
static int
parse_psr (char **str, bfd_boolean lhs)
{
char *p;
unsigned long psr_field;
const struct asm_psr *psr;
char *start;
bfd_boolean is_apsr = FALSE;
bfd_boolean m_profile = ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_m);
/* PR gas/12698: If the user has specified -march=all then m_profile will
be TRUE, but we want to ignore it in this case as we are building for any
CPU type, including non-m variants. */
if (selected_cpu.core == arm_arch_any.core)
m_profile = FALSE;
/* CPSR's and SPSR's can now be lowercase. This is just a convenience
feature for ease of use and backwards compatibility. */
p = *str;
if (strncasecmp (p, "SPSR", 4) == 0)
{
if (m_profile)
goto unsupported_psr;
psr_field = SPSR_BIT;
}
else if (strncasecmp (p, "CPSR", 4) == 0)
{
if (m_profile)
goto unsupported_psr;
psr_field = 0;
}
else if (strncasecmp (p, "APSR", 4) == 0)
{
/* APSR[_<bits>] can be used as a synonym for CPSR[_<flags>] on ARMv7-A
and ARMv7-R architecture CPUs. */
is_apsr = TRUE;
psr_field = 0;
}
else if (m_profile)
{
start = p;
do
p++;
while (ISALNUM (*p) || *p == '_');
if (strncasecmp (start, "iapsr", 5) == 0
|| strncasecmp (start, "eapsr", 5) == 0
|| strncasecmp (start, "xpsr", 4) == 0
|| strncasecmp (start, "psr", 3) == 0)
p = start + strcspn (start, "rR") + 1;
psr = (const struct asm_psr *) hash_find_n (arm_v7m_psr_hsh, start,
p - start);
if (!psr)
return FAIL;
/* If APSR is being written, a bitfield may be specified. Note that
APSR itself is handled above. */
if (psr->field <= 3)
{
psr_field = psr->field;
is_apsr = TRUE;
goto check_suffix;
}
*str = p;
/* M-profile MSR instructions have the mask field set to "10", except
*PSR variants which modify APSR, which may use a different mask (and
have been handled already). Do that by setting the PSR_f field
here. */
return psr->field | (lhs ? PSR_f : 0);
}
else
goto unsupported_psr;
p += 4;
check_suffix:
if (*p == '_')
{
/* A suffix follows. */
p++;
start = p;
do
p++;
while (ISALNUM (*p) || *p == '_');
if (is_apsr)
{
/* APSR uses a notation for bits, rather than fields. */
unsigned int nzcvq_bits = 0;
unsigned int g_bit = 0;
char *bit;
for (bit = start; bit != p; bit++)
{
switch (TOLOWER (*bit))
{
case 'n':
nzcvq_bits |= (nzcvq_bits & 0x01) ? 0x20 : 0x01;
break;
case 'z':
nzcvq_bits |= (nzcvq_bits & 0x02) ? 0x20 : 0x02;
break;
case 'c':
nzcvq_bits |= (nzcvq_bits & 0x04) ? 0x20 : 0x04;
break;
case 'v':
nzcvq_bits |= (nzcvq_bits & 0x08) ? 0x20 : 0x08;
break;
case 'q':
nzcvq_bits |= (nzcvq_bits & 0x10) ? 0x20 : 0x10;
break;
case 'g':
g_bit |= (g_bit & 0x1) ? 0x2 : 0x1;
break;
default:
inst.error = _("unexpected bit specified after APSR");
return FAIL;
}
}
if (nzcvq_bits == 0x1f)
psr_field |= PSR_f;
if (g_bit == 0x1)
{
if (!ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6_dsp))
{
inst.error = _("selected processor does not "
"support DSP extension");
return FAIL;
}
psr_field |= PSR_s;
}
if ((nzcvq_bits & 0x20) != 0
|| (nzcvq_bits != 0x1f && nzcvq_bits != 0)
|| (g_bit & 0x2) != 0)
{
inst.error = _("bad bitmask specified after APSR");
return FAIL;
}
}
else
{
psr = (const struct asm_psr *) hash_find_n (arm_psr_hsh, start,
p - start);
if (!psr)
goto error;
psr_field |= psr->field;
}
}
else
{
if (ISALNUM (*p))
goto error; /* Garbage after "[CS]PSR". */
/* Unadorned APSR is equivalent to APSR_nzcvq/CPSR_f (for writes). This
is deprecated, but allow it anyway. */
if (is_apsr && lhs)
{
psr_field |= PSR_f;
as_tsktsk (_("writing to APSR without specifying a bitmask is "
"deprecated"));
}
else if (!m_profile)
/* These bits are never right for M-profile devices: don't set them
(only code paths which read/write APSR reach here). */
psr_field |= (PSR_c | PSR_f);
}
*str = p;
return psr_field;
unsupported_psr:
inst.error = _("selected processor does not support requested special "
"purpose register");
return FAIL;
error:
inst.error = _("flag for {c}psr instruction expected");
return FAIL;
}
/* Parse the flags argument to CPSI[ED]. Returns FAIL on error, or a
value suitable for splatting into the AIF field of the instruction. */
static int
parse_cps_flags (char **str)
{
int val = 0;
int saw_a_flag = 0;
char *s = *str;
for (;;)
switch (*s++)
{
case '\0': case ',':
goto done;
case 'a': case 'A': saw_a_flag = 1; val |= 0x4; break;
case 'i': case 'I': saw_a_flag = 1; val |= 0x2; break;
case 'f': case 'F': saw_a_flag = 1; val |= 0x1; break;
default:
inst.error = _("unrecognized CPS flag");
return FAIL;
}
done:
if (saw_a_flag == 0)
{
inst.error = _("missing CPS flags");
return FAIL;
}
*str = s - 1;
return val;
}
/* Parse an endian specifier ("BE" or "LE", case insensitive);
returns 0 for big-endian, 1 for little-endian, FAIL for an error. */
static int
parse_endian_specifier (char **str)
{
int little_endian;
char *s = *str;
if (strncasecmp (s, "BE", 2))
little_endian = 0;
else if (strncasecmp (s, "LE", 2))
little_endian = 1;
else
{
inst.error = _("valid endian specifiers are be or le");
return FAIL;
}
if (ISALNUM (s[2]) || s[2] == '_')
{
inst.error = _("valid endian specifiers are be or le");
return FAIL;
}
*str = s + 2;
return little_endian;
}
/* Parse a rotation specifier: ROR #0, #8, #16, #24. *val receives a
value suitable for poking into the rotate field of an sxt or sxta
instruction, or FAIL on error. */
static int
parse_ror (char **str)
{
int rot;
char *s = *str;
if (strncasecmp (s, "ROR", 3) == 0)
s += 3;
else
{
inst.error = _("missing rotation field after comma");
return FAIL;
}
if (parse_immediate (&s, &rot, 0, 24, FALSE) == FAIL)
return FAIL;
switch (rot)
{
case 0: *str = s; return 0x0;
case 8: *str = s; return 0x1;
case 16: *str = s; return 0x2;
case 24: *str = s; return 0x3;
default:
inst.error = _("rotation can only be 0, 8, 16, or 24");
return FAIL;
}
}
/* Parse a conditional code (from conds[] below). The value returned is in the
range 0 .. 14, or FAIL. */
static int
parse_cond (char **str)
{
char *q;
const struct asm_cond *c;
int n;
/* Condition codes are always 2 characters, so matching up to
3 characters is sufficient. */
char cond[3];
q = *str;
n = 0;
while (ISALPHA (*q) && n < 3)
{
cond[n] = TOLOWER (*q);
q++;
n++;
}
c = (const struct asm_cond *) hash_find_n (arm_cond_hsh, cond, n);
if (!c)
{
inst.error = _("condition required");
return FAIL;
}
*str = q;
return c->value;
}
/* If the given feature available in the selected CPU, mark it as used.
Returns TRUE iff feature is available. */
static bfd_boolean
mark_feature_used (const arm_feature_set *feature)
{
/* Ensure the option is valid on the current architecture. */
if (!ARM_CPU_HAS_FEATURE (cpu_variant, *feature))
return FALSE;
/* Add the appropriate architecture feature for the barrier option used.
*/
if (thumb_mode)
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used, *feature);
else
ARM_MERGE_FEATURE_SETS (arm_arch_used, arm_arch_used, *feature);
return TRUE;
}
/* Parse an option for a barrier instruction. Returns the encoding for the
option, or FAIL. */
static int
parse_barrier (char **str)
{
char *p, *q;
const struct asm_barrier_opt *o;
p = q = *str;
while (ISALPHA (*q))
q++;
o = (const struct asm_barrier_opt *) hash_find_n (arm_barrier_opt_hsh, p,
q - p);
if (!o)
return FAIL;
if (!mark_feature_used (&o->arch))
return FAIL;
*str = q;
return o->value;
}
/* Parse the operands of a table branch instruction. Similar to a memory
operand. */
static int
parse_tb (char **str)
{
char * p = *str;
int reg;
if (skip_past_char (&p, '[') == FAIL)
{
inst.error = _("'[' expected");
return FAIL;
}
if ((reg = arm_reg_parse (&p, REG_TYPE_RN)) == FAIL)
{
inst.error = _(reg_expected_msgs[REG_TYPE_RN]);
return FAIL;
}
inst.operands[0].reg = reg;
if (skip_past_comma (&p) == FAIL)
{
inst.error = _("',' expected");
return FAIL;
}
if ((reg = arm_reg_parse (&p, REG_TYPE_RN)) == FAIL)
{
inst.error = _(reg_expected_msgs[REG_TYPE_RN]);
return FAIL;
}
inst.operands[0].imm = reg;
if (skip_past_comma (&p) == SUCCESS)
{
if (parse_shift (&p, 0, SHIFT_LSL_IMMEDIATE) == FAIL)
return FAIL;
if (inst.reloc.exp.X_add_number != 1)
{
inst.error = _("invalid shift");
return FAIL;
}
inst.operands[0].shifted = 1;
}
if (skip_past_char (&p, ']') == FAIL)
{
inst.error = _("']' expected");
return FAIL;
}
*str = p;
return SUCCESS;
}
/* Parse the operands of a Neon VMOV instruction. See do_neon_mov for more
information on the types the operands can take and how they are encoded.
Up to four operands may be read; this function handles setting the
".present" field for each read operand itself.
Updates STR and WHICH_OPERAND if parsing is successful and returns SUCCESS,
else returns FAIL. */
static int
parse_neon_mov (char **str, int *which_operand)
{
int i = *which_operand, val;
enum arm_reg_type rtype;
char *ptr = *str;
struct neon_type_el optype;
if ((val = parse_scalar (&ptr, 8, &optype)) != FAIL)
{
/* Case 4: VMOV<c><q>.<size> <Dn[x]>, <Rd>. */
inst.operands[i].reg = val;
inst.operands[i].isscalar = 1;
inst.operands[i].vectype = optype;
inst.operands[i++].present = 1;
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) == FAIL)
goto wanted_arm;
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].present = 1;
}
else if ((val = arm_typed_reg_parse (&ptr, REG_TYPE_NSDQ, &rtype, &optype))
!= FAIL)
{
/* Cases 0, 1, 2, 3, 5 (D only). */
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].isquad = (rtype == REG_TYPE_NQ);
inst.operands[i].issingle = (rtype == REG_TYPE_VFS);
inst.operands[i].isvec = 1;
inst.operands[i].vectype = optype;
inst.operands[i++].present = 1;
if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) != FAIL)
{
/* Case 5: VMOV<c><q> <Dm>, <Rd>, <Rn>.
Case 13: VMOV <Sd>, <Rm> */
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].present = 1;
if (rtype == REG_TYPE_NQ)
{
first_error (_("can't use Neon quad register here"));
return FAIL;
}
else if (rtype != REG_TYPE_VFS)
{
i++;
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) == FAIL)
goto wanted_arm;
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].present = 1;
}
}
else if ((val = arm_typed_reg_parse (&ptr, REG_TYPE_NSDQ, &rtype,
&optype)) != FAIL)
{
/* Case 0: VMOV<c><q> <Qd>, <Qm>
Case 1: VMOV<c><q> <Dd>, <Dm>
Case 8: VMOV.F32 <Sd>, <Sm>
Case 15: VMOV <Sd>, <Se>, <Rn>, <Rm> */
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].isquad = (rtype == REG_TYPE_NQ);
inst.operands[i].issingle = (rtype == REG_TYPE_VFS);
inst.operands[i].isvec = 1;
inst.operands[i].vectype = optype;
inst.operands[i].present = 1;
if (skip_past_comma (&ptr) == SUCCESS)
{
/* Case 15. */
i++;
if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) == FAIL)
goto wanted_arm;
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i++].present = 1;
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) == FAIL)
goto wanted_arm;
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].present = 1;
}
}
else if (parse_qfloat_immediate (&ptr, &inst.operands[i].imm) == SUCCESS)
/* Case 2: VMOV<c><q>.<dt> <Qd>, #<float-imm>
Case 3: VMOV<c><q>.<dt> <Dd>, #<float-imm>
Case 10: VMOV.F32 <Sd>, #<imm>
Case 11: VMOV.F64 <Dd>, #<imm> */
inst.operands[i].immisfloat = 1;
else if (parse_big_immediate (&ptr, i, NULL, /*allow_symbol_p=*/FALSE)
== SUCCESS)
/* Case 2: VMOV<c><q>.<dt> <Qd>, #<imm>
Case 3: VMOV<c><q>.<dt> <Dd>, #<imm> */
;
else
{
first_error (_("expected <Rm> or <Dm> or <Qm> operand"));
return FAIL;
}
}
else if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) != FAIL)
{
/* Cases 6, 7. */
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i++].present = 1;
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
if ((val = parse_scalar (&ptr, 8, &optype)) != FAIL)
{
/* Case 6: VMOV<c><q>.<dt> <Rd>, <Dn[x]> */
inst.operands[i].reg = val;
inst.operands[i].isscalar = 1;
inst.operands[i].present = 1;
inst.operands[i].vectype = optype;
}
else if ((val = arm_reg_parse (&ptr, REG_TYPE_RN)) != FAIL)
{
/* Case 7: VMOV<c><q> <Rd>, <Rn>, <Dm> */
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i++].present = 1;
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
if ((val = arm_typed_reg_parse (&ptr, REG_TYPE_VFSD, &rtype, &optype))
== FAIL)
{
first_error (_(reg_expected_msgs[REG_TYPE_VFSD]));
return FAIL;
}
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].isvec = 1;
inst.operands[i].issingle = (rtype == REG_TYPE_VFS);
inst.operands[i].vectype = optype;
inst.operands[i].present = 1;
if (rtype == REG_TYPE_VFS)
{
/* Case 14. */
i++;
if (skip_past_comma (&ptr) == FAIL)
goto wanted_comma;
if ((val = arm_typed_reg_parse (&ptr, REG_TYPE_VFS, NULL,
&optype)) == FAIL)
{
first_error (_(reg_expected_msgs[REG_TYPE_VFS]));
return FAIL;
}
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].isvec = 1;
inst.operands[i].issingle = 1;
inst.operands[i].vectype = optype;
inst.operands[i].present = 1;
}
}
else if ((val = arm_typed_reg_parse (&ptr, REG_TYPE_VFS, NULL, &optype))
!= FAIL)
{
/* Case 13. */
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
inst.operands[i].isvec = 1;
inst.operands[i].issingle = 1;
inst.operands[i].vectype = optype;
inst.operands[i].present = 1;
}
}
else
{
first_error (_("parse error"));
return FAIL;
}
/* Successfully parsed the operands. Update args. */
*which_operand = i;
*str = ptr;
return SUCCESS;
wanted_comma:
first_error (_("expected comma"));
return FAIL;
wanted_arm:
first_error (_(reg_expected_msgs[REG_TYPE_RN]));
return FAIL;
}
/* Use this macro when the operand constraints are different
for ARM and THUMB (e.g. ldrd). */
#define MIX_ARM_THUMB_OPERANDS(arm_operand, thumb_operand) \
((arm_operand) | ((thumb_operand) << 16))
/* Matcher codes for parse_operands. */
enum operand_parse_code
{
OP_stop, /* end of line */
OP_RR, /* ARM register */
OP_RRnpc, /* ARM register, not r15 */
OP_RRnpcsp, /* ARM register, neither r15 nor r13 (a.k.a. 'BadReg') */
OP_RRnpcb, /* ARM register, not r15, in square brackets */
OP_RRnpctw, /* ARM register, not r15 in Thumb-state or with writeback,
optional trailing ! */
OP_RRw, /* ARM register, not r15, optional trailing ! */
OP_RCP, /* Coprocessor number */
OP_RCN, /* Coprocessor register */
OP_RF, /* FPA register */
OP_RVS, /* VFP single precision register */
OP_RVD, /* VFP double precision register (0..15) */
OP_RND, /* Neon double precision register (0..31) */
OP_RNQ, /* Neon quad precision register */
OP_RVSD, /* VFP single or double precision register */
OP_RNDQ, /* Neon double or quad precision register */
OP_RNSDQ, /* Neon single, double or quad precision register */
OP_RNSC, /* Neon scalar D[X] */
OP_RVC, /* VFP control register */
OP_RMF, /* Maverick F register */
OP_RMD, /* Maverick D register */
OP_RMFX, /* Maverick FX register */
OP_RMDX, /* Maverick DX register */
OP_RMAX, /* Maverick AX register */
OP_RMDS, /* Maverick DSPSC register */
OP_RIWR, /* iWMMXt wR register */
OP_RIWC, /* iWMMXt wC register */
OP_RIWG, /* iWMMXt wCG register */
OP_RXA, /* XScale accumulator register */
OP_REGLST, /* ARM register list */
OP_VRSLST, /* VFP single-precision register list */
OP_VRDLST, /* VFP double-precision register list */
OP_VRSDLST, /* VFP single or double-precision register list (& quad) */
OP_NRDLST, /* Neon double-precision register list (d0-d31, qN aliases) */
OP_NSTRLST, /* Neon element/structure list */
OP_RNDQ_I0, /* Neon D or Q reg, or immediate zero. */
OP_RVSD_I0, /* VFP S or D reg, or immediate zero. */
OP_RSVD_FI0, /* VFP S or D reg, or floating point immediate zero. */
OP_RR_RNSC, /* ARM reg or Neon scalar. */
OP_RNSDQ_RNSC, /* Vector S, D or Q reg, or Neon scalar. */
OP_RNDQ_RNSC, /* Neon D or Q reg, or Neon scalar. */
OP_RND_RNSC, /* Neon D reg, or Neon scalar. */
OP_VMOV, /* Neon VMOV operands. */
OP_RNDQ_Ibig, /* Neon D or Q reg, or big immediate for logic and VMVN. */
OP_RNDQ_I63b, /* Neon D or Q reg, or immediate for shift. */
OP_RIWR_I32z, /* iWMMXt wR register, or immediate 0 .. 32 for iWMMXt2. */
OP_I0, /* immediate zero */
OP_I7, /* immediate value 0 .. 7 */
OP_I15, /* 0 .. 15 */
OP_I16, /* 1 .. 16 */
OP_I16z, /* 0 .. 16 */
OP_I31, /* 0 .. 31 */
OP_I31w, /* 0 .. 31, optional trailing ! */
OP_I32, /* 1 .. 32 */
OP_I32z, /* 0 .. 32 */
OP_I63, /* 0 .. 63 */
OP_I63s, /* -64 .. 63 */
OP_I64, /* 1 .. 64 */
OP_I64z, /* 0 .. 64 */
OP_I255, /* 0 .. 255 */
OP_I4b, /* immediate, prefix optional, 1 .. 4 */
OP_I7b, /* 0 .. 7 */
OP_I15b, /* 0 .. 15 */
OP_I31b, /* 0 .. 31 */
OP_SH, /* shifter operand */
OP_SHG, /* shifter operand with possible group relocation */
OP_ADDR, /* Memory address expression (any mode) */
OP_ADDRGLDR, /* Mem addr expr (any mode) with possible LDR group reloc */
OP_ADDRGLDRS, /* Mem addr expr (any mode) with possible LDRS group reloc */
OP_ADDRGLDC, /* Mem addr expr (any mode) with possible LDC group reloc */
OP_EXP, /* arbitrary expression */
OP_EXPi, /* same, with optional immediate prefix */
OP_EXPr, /* same, with optional relocation suffix */
OP_HALF, /* 0 .. 65535 or low/high reloc. */
OP_CPSF, /* CPS flags */
OP_ENDI, /* Endianness specifier */
OP_wPSR, /* CPSR/SPSR/APSR mask for msr (writing). */
OP_rPSR, /* CPSR/SPSR/APSR mask for msr (reading). */
OP_COND, /* conditional code */
OP_TB, /* Table branch. */
OP_APSR_RR, /* ARM register or "APSR_nzcv". */
OP_RRnpc_I0, /* ARM register or literal 0 */
OP_RR_EXr, /* ARM register or expression with opt. reloc suff. */
OP_RR_EXi, /* ARM register or expression with imm prefix */
OP_RF_IF, /* FPA register or immediate */
OP_RIWR_RIWC, /* iWMMXt R or C reg */
OP_RIWC_RIWG, /* iWMMXt wC or wCG reg */
/* Optional operands. */
OP_oI7b, /* immediate, prefix optional, 0 .. 7 */
OP_oI31b, /* 0 .. 31 */
OP_oI32b, /* 1 .. 32 */
OP_oI32z, /* 0 .. 32 */
OP_oIffffb, /* 0 .. 65535 */
OP_oI255c, /* curly-brace enclosed, 0 .. 255 */
OP_oRR, /* ARM register */
OP_oRRnpc, /* ARM register, not the PC */
OP_oRRnpcsp, /* ARM register, neither the PC nor the SP (a.k.a. BadReg) */
OP_oRRw, /* ARM register, not r15, optional trailing ! */
OP_oRND, /* Optional Neon double precision register */
OP_oRNQ, /* Optional Neon quad precision register */
OP_oRNDQ, /* Optional Neon double or quad precision register */
OP_oRNSDQ, /* Optional single, double or quad precision vector register */
OP_oSHll, /* LSL immediate */
OP_oSHar, /* ASR immediate */
OP_oSHllar, /* LSL or ASR immediate */
OP_oROR, /* ROR 0/8/16/24 */
OP_oBARRIER_I15, /* Option argument for a barrier instruction. */
/* Some pre-defined mixed (ARM/THUMB) operands. */
OP_RR_npcsp = MIX_ARM_THUMB_OPERANDS (OP_RR, OP_RRnpcsp),
OP_RRnpc_npcsp = MIX_ARM_THUMB_OPERANDS (OP_RRnpc, OP_RRnpcsp),
OP_oRRnpc_npcsp = MIX_ARM_THUMB_OPERANDS (OP_oRRnpc, OP_oRRnpcsp),
OP_FIRST_OPTIONAL = OP_oI7b
};
/* Generic instruction operand parser. This does no encoding and no
semantic validation; it merely squirrels values away in the inst
structure. Returns SUCCESS or FAIL depending on whether the
specified grammar matched. */
static int
parse_operands (char *str, const unsigned int *pattern, bfd_boolean thumb)
{
unsigned const int *upat = pattern;
char *backtrack_pos = 0;
const char *backtrack_error = 0;
int i, val = 0, backtrack_index = 0;
enum arm_reg_type rtype;
parse_operand_result result;
unsigned int op_parse_code;
#define po_char_or_fail(chr) \
do \
{ \
if (skip_past_char (&str, chr) == FAIL) \
goto bad_args; \
} \
while (0)
#define po_reg_or_fail(regtype) \
do \
{ \
val = arm_typed_reg_parse (& str, regtype, & rtype, \
& inst.operands[i].vectype); \
if (val == FAIL) \
{ \
first_error (_(reg_expected_msgs[regtype])); \
goto failure; \
} \
inst.operands[i].reg = val; \
inst.operands[i].isreg = 1; \
inst.operands[i].isquad = (rtype == REG_TYPE_NQ); \
inst.operands[i].issingle = (rtype == REG_TYPE_VFS); \
inst.operands[i].isvec = (rtype == REG_TYPE_VFS \
|| rtype == REG_TYPE_VFD \
|| rtype == REG_TYPE_NQ); \
} \
while (0)
#define po_reg_or_goto(regtype, label) \
do \
{ \
val = arm_typed_reg_parse (& str, regtype, & rtype, \
& inst.operands[i].vectype); \
if (val == FAIL) \
goto label; \
\
inst.operands[i].reg = val; \
inst.operands[i].isreg = 1; \
inst.operands[i].isquad = (rtype == REG_TYPE_NQ); \
inst.operands[i].issingle = (rtype == REG_TYPE_VFS); \
inst.operands[i].isvec = (rtype == REG_TYPE_VFS \
|| rtype == REG_TYPE_VFD \
|| rtype == REG_TYPE_NQ); \
} \
while (0)
#define po_imm_or_fail(min, max, popt) \
do \
{ \
if (parse_immediate (&str, &val, min, max, popt) == FAIL) \
goto failure; \
inst.operands[i].imm = val; \
} \
while (0)
#define po_scalar_or_goto(elsz, label) \
do \
{ \
val = parse_scalar (& str, elsz, & inst.operands[i].vectype); \
if (val == FAIL) \
goto label; \
inst.operands[i].reg = val; \
inst.operands[i].isscalar = 1; \
} \
while (0)
#define po_misc_or_fail(expr) \
do \
{ \
if (expr) \
goto failure; \
} \
while (0)
#define po_misc_or_fail_no_backtrack(expr) \
do \
{ \
result = expr; \
if (result == PARSE_OPERAND_FAIL_NO_BACKTRACK) \
backtrack_pos = 0; \
if (result != PARSE_OPERAND_SUCCESS) \
goto failure; \
} \
while (0)
#define po_barrier_or_imm(str) \
do \
{ \
val = parse_barrier (&str); \
if (val == FAIL && ! ISALPHA (*str)) \
goto immediate; \
if (val == FAIL \
/* ISB can only take SY as an option. */ \
|| ((inst.instruction & 0xf0) == 0x60 \
&& val != 0xf)) \
{ \
inst.error = _("invalid barrier type"); \
backtrack_pos = 0; \
goto failure; \
} \
} \
while (0)
skip_whitespace (str);
for (i = 0; upat[i] != OP_stop; i++)
{
op_parse_code = upat[i];
if (op_parse_code >= 1<<16)
op_parse_code = thumb ? (op_parse_code >> 16)
: (op_parse_code & ((1<<16)-1));
if (op_parse_code >= OP_FIRST_OPTIONAL)
{
/* Remember where we are in case we need to backtrack. */
gas_assert (!backtrack_pos);
backtrack_pos = str;
backtrack_error = inst.error;
backtrack_index = i;
}
if (i > 0 && (i > 1 || inst.operands[0].present))
po_char_or_fail (',');
switch (op_parse_code)
{
/* Registers */
case OP_oRRnpc:
case OP_oRRnpcsp:
case OP_RRnpc:
case OP_RRnpcsp:
case OP_oRR:
case OP_RR: po_reg_or_fail (REG_TYPE_RN); break;
case OP_RCP: po_reg_or_fail (REG_TYPE_CP); break;
case OP_RCN: po_reg_or_fail (REG_TYPE_CN); break;
case OP_RF: po_reg_or_fail (REG_TYPE_FN); break;
case OP_RVS: po_reg_or_fail (REG_TYPE_VFS); break;
case OP_RVD: po_reg_or_fail (REG_TYPE_VFD); break;
case OP_oRND:
case OP_RND: po_reg_or_fail (REG_TYPE_VFD); break;
case OP_RVC:
po_reg_or_goto (REG_TYPE_VFC, coproc_reg);
break;
/* Also accept generic coprocessor regs for unknown registers. */
coproc_reg:
po_reg_or_fail (REG_TYPE_CN);
break;
case OP_RMF: po_reg_or_fail (REG_TYPE_MVF); break;
case OP_RMD: po_reg_or_fail (REG_TYPE_MVD); break;
case OP_RMFX: po_reg_or_fail (REG_TYPE_MVFX); break;
case OP_RMDX: po_reg_or_fail (REG_TYPE_MVDX); break;
case OP_RMAX: po_reg_or_fail (REG_TYPE_MVAX); break;
case OP_RMDS: po_reg_or_fail (REG_TYPE_DSPSC); break;
case OP_RIWR: po_reg_or_fail (REG_TYPE_MMXWR); break;
case OP_RIWC: po_reg_or_fail (REG_TYPE_MMXWC); break;
case OP_RIWG: po_reg_or_fail (REG_TYPE_MMXWCG); break;
case OP_RXA: po_reg_or_fail (REG_TYPE_XSCALE); break;
case OP_oRNQ:
case OP_RNQ: po_reg_or_fail (REG_TYPE_NQ); break;
case OP_oRNDQ:
case OP_RNDQ: po_reg_or_fail (REG_TYPE_NDQ); break;
case OP_RVSD: po_reg_or_fail (REG_TYPE_VFSD); break;
case OP_oRNSDQ:
case OP_RNSDQ: po_reg_or_fail (REG_TYPE_NSDQ); break;
/* Neon scalar. Using an element size of 8 means that some invalid
scalars are accepted here, so deal with those in later code. */
case OP_RNSC: po_scalar_or_goto (8, failure); break;
case OP_RNDQ_I0:
{
po_reg_or_goto (REG_TYPE_NDQ, try_imm0);
break;
try_imm0:
po_imm_or_fail (0, 0, TRUE);
}
break;
case OP_RVSD_I0:
po_reg_or_goto (REG_TYPE_VFSD, try_imm0);
break;
case OP_RSVD_FI0:
{
po_reg_or_goto (REG_TYPE_VFSD, try_ifimm0);
break;
try_ifimm0:
if (parse_ifimm_zero (&str))
inst.operands[i].imm = 0;
else
{
inst.error
= _("only floating point zero is allowed as immediate value");
goto failure;
}
}
break;
case OP_RR_RNSC:
{
po_scalar_or_goto (8, try_rr);
break;
try_rr:
po_reg_or_fail (REG_TYPE_RN);
}
break;
case OP_RNSDQ_RNSC:
{
po_scalar_or_goto (8, try_nsdq);
break;
try_nsdq:
po_reg_or_fail (REG_TYPE_NSDQ);
}
break;
case OP_RNDQ_RNSC:
{
po_scalar_or_goto (8, try_ndq);
break;
try_ndq:
po_reg_or_fail (REG_TYPE_NDQ);
}
break;
case OP_RND_RNSC:
{
po_scalar_or_goto (8, try_vfd);
break;
try_vfd:
po_reg_or_fail (REG_TYPE_VFD);
}
break;
case OP_VMOV:
/* WARNING: parse_neon_mov can move the operand counter, i. If we're
not careful then bad things might happen. */
po_misc_or_fail (parse_neon_mov (&str, &i) == FAIL);
break;
case OP_RNDQ_Ibig:
{
po_reg_or_goto (REG_TYPE_NDQ, try_immbig);
break;
try_immbig:
/* There's a possibility of getting a 64-bit immediate here, so
we need special handling. */
if (parse_big_immediate (&str, i, NULL, /*allow_symbol_p=*/FALSE)
== FAIL)
{
inst.error = _("immediate value is out of range");
goto failure;
}
}
break;
case OP_RNDQ_I63b:
{
po_reg_or_goto (REG_TYPE_NDQ, try_shimm);
break;
try_shimm:
po_imm_or_fail (0, 63, TRUE);
}
break;
case OP_RRnpcb:
po_char_or_fail ('[');
po_reg_or_fail (REG_TYPE_RN);
po_char_or_fail (']');
break;
case OP_RRnpctw:
case OP_RRw:
case OP_oRRw:
po_reg_or_fail (REG_TYPE_RN);
if (skip_past_char (&str, '!') == SUCCESS)
inst.operands[i].writeback = 1;
break;
/* Immediates */
case OP_I7: po_imm_or_fail ( 0, 7, FALSE); break;
case OP_I15: po_imm_or_fail ( 0, 15, FALSE); break;
case OP_I16: po_imm_or_fail ( 1, 16, FALSE); break;
case OP_I16z: po_imm_or_fail ( 0, 16, FALSE); break;
case OP_I31: po_imm_or_fail ( 0, 31, FALSE); break;
case OP_I32: po_imm_or_fail ( 1, 32, FALSE); break;
case OP_I32z: po_imm_or_fail ( 0, 32, FALSE); break;
case OP_I63s: po_imm_or_fail (-64, 63, FALSE); break;
case OP_I63: po_imm_or_fail ( 0, 63, FALSE); break;
case OP_I64: po_imm_or_fail ( 1, 64, FALSE); break;
case OP_I64z: po_imm_or_fail ( 0, 64, FALSE); break;
case OP_I255: po_imm_or_fail ( 0, 255, FALSE); break;
case OP_I4b: po_imm_or_fail ( 1, 4, TRUE); break;
case OP_oI7b:
case OP_I7b: po_imm_or_fail ( 0, 7, TRUE); break;
case OP_I15b: po_imm_or_fail ( 0, 15, TRUE); break;
case OP_oI31b:
case OP_I31b: po_imm_or_fail ( 0, 31, TRUE); break;
case OP_oI32b: po_imm_or_fail ( 1, 32, TRUE); break;
case OP_oI32z: po_imm_or_fail ( 0, 32, TRUE); break;
case OP_oIffffb: po_imm_or_fail ( 0, 0xffff, TRUE); break;
/* Immediate variants */
case OP_oI255c:
po_char_or_fail ('{');
po_imm_or_fail (0, 255, TRUE);
po_char_or_fail ('}');
break;
case OP_I31w:
/* The expression parser chokes on a trailing !, so we have
to find it first and zap it. */
{
char *s = str;
while (*s && *s != ',')
s++;
if (s[-1] == '!')
{
s[-1] = '\0';
inst.operands[i].writeback = 1;
}
po_imm_or_fail (0, 31, TRUE);
if (str == s - 1)
str = s;
}
break;
/* Expressions */
case OP_EXPi: EXPi:
po_misc_or_fail (my_get_expression (&inst.reloc.exp, &str,
GE_OPT_PREFIX));
break;
case OP_EXP:
po_misc_or_fail (my_get_expression (&inst.reloc.exp, &str,
GE_NO_PREFIX));
break;
case OP_EXPr: EXPr:
po_misc_or_fail (my_get_expression (&inst.reloc.exp, &str,
GE_NO_PREFIX));
if (inst.reloc.exp.X_op == O_symbol)
{
val = parse_reloc (&str);
if (val == -1)
{
inst.error = _("unrecognized relocation suffix");
goto failure;
}
else if (val != BFD_RELOC_UNUSED)
{
inst.operands[i].imm = val;
inst.operands[i].hasreloc = 1;
}
}
break;
/* Operand for MOVW or MOVT. */
case OP_HALF:
po_misc_or_fail (parse_half (&str));
break;
/* Register or expression. */
case OP_RR_EXr: po_reg_or_goto (REG_TYPE_RN, EXPr); break;
case OP_RR_EXi: po_reg_or_goto (REG_TYPE_RN, EXPi); break;
/* Register or immediate. */
case OP_RRnpc_I0: po_reg_or_goto (REG_TYPE_RN, I0); break;
I0: po_imm_or_fail (0, 0, FALSE); break;
case OP_RF_IF: po_reg_or_goto (REG_TYPE_FN, IF); break;
IF:
if (!is_immediate_prefix (*str))
goto bad_args;
str++;
val = parse_fpa_immediate (&str);
if (val == FAIL)
goto failure;
/* FPA immediates are encoded as registers 8-15.
parse_fpa_immediate has already applied the offset. */
inst.operands[i].reg = val;
inst.operands[i].isreg = 1;
break;
case OP_RIWR_I32z: po_reg_or_goto (REG_TYPE_MMXWR, I32z); break;
I32z: po_imm_or_fail (0, 32, FALSE); break;
/* Two kinds of register. */
case OP_RIWR_RIWC:
{
struct reg_entry *rege = arm_reg_parse_multi (&str);
if (!rege
|| (rege->type != REG_TYPE_MMXWR
&& rege->type != REG_TYPE_MMXWC
&& rege->type != REG_TYPE_MMXWCG))
{
inst.error = _("iWMMXt data or control register expected");
goto failure;
}
inst.operands[i].reg = rege->number;
inst.operands[i].isreg = (rege->type == REG_TYPE_MMXWR);
}
break;
case OP_RIWC_RIWG:
{
struct reg_entry *rege = arm_reg_parse_multi (&str);
if (!rege
|| (rege->type != REG_TYPE_MMXWC
&& rege->type != REG_TYPE_MMXWCG))
{
inst.error = _("iWMMXt control register expected");
goto failure;
}
inst.operands[i].reg = rege->number;
inst.operands[i].isreg = 1;
}
break;
/* Misc */
case OP_CPSF: val = parse_cps_flags (&str); break;
case OP_ENDI: val = parse_endian_specifier (&str); break;
case OP_oROR: val = parse_ror (&str); break;
case OP_COND: val = parse_cond (&str); break;
case OP_oBARRIER_I15:
po_barrier_or_imm (str); break;
immediate:
if (parse_immediate (&str, &val, 0, 15, TRUE) == FAIL)
goto failure;
break;
case OP_wPSR:
case OP_rPSR:
po_reg_or_goto (REG_TYPE_RNB, try_psr);
if (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_virt))
{
inst.error = _("Banked registers are not available with this "
"architecture.");
goto failure;
}
break;
try_psr:
val = parse_psr (&str, op_parse_code == OP_wPSR);
break;
case OP_APSR_RR:
po_reg_or_goto (REG_TYPE_RN, try_apsr);
break;
try_apsr:
/* Parse "APSR_nvzc" operand (for FMSTAT-equivalent MRS
instruction). */
if (strncasecmp (str, "APSR_", 5) == 0)
{
unsigned found = 0;
str += 5;
while (found < 15)
switch (*str++)
{
case 'c': found = (found & 1) ? 16 : found | 1; break;
case 'n': found = (found & 2) ? 16 : found | 2; break;
case 'z': found = (found & 4) ? 16 : found | 4; break;
case 'v': found = (found & 8) ? 16 : found | 8; break;
default: found = 16;
}
if (found != 15)
goto failure;
inst.operands[i].isvec = 1;
/* APSR_nzcv is encoded in instructions as if it were the REG_PC. */
inst.operands[i].reg = REG_PC;
}
else
goto failure;
break;
case OP_TB:
po_misc_or_fail (parse_tb (&str));
break;
/* Register lists. */
case OP_REGLST:
val = parse_reg_list (&str);
if (*str == '^')
{
inst.operands[i].writeback = 1;
str++;
}
break;
case OP_VRSLST:
val = parse_vfp_reg_list (&str, &inst.operands[i].reg, REGLIST_VFP_S);
break;
case OP_VRDLST:
val = parse_vfp_reg_list (&str, &inst.operands[i].reg, REGLIST_VFP_D);
break;
case OP_VRSDLST:
/* Allow Q registers too. */
val = parse_vfp_reg_list (&str, &inst.operands[i].reg,
REGLIST_NEON_D);
if (val == FAIL)
{
inst.error = NULL;
val = parse_vfp_reg_list (&str, &inst.operands[i].reg,
REGLIST_VFP_S);
inst.operands[i].issingle = 1;
}
break;
case OP_NRDLST:
val = parse_vfp_reg_list (&str, &inst.operands[i].reg,
REGLIST_NEON_D);
break;
case OP_NSTRLST:
val = parse_neon_el_struct_list (&str, &inst.operands[i].reg,
&inst.operands[i].vectype);
break;
/* Addressing modes */
case OP_ADDR:
po_misc_or_fail (parse_address (&str, i));
break;
case OP_ADDRGLDR:
po_misc_or_fail_no_backtrack (
parse_address_group_reloc (&str, i, GROUP_LDR));
break;
case OP_ADDRGLDRS:
po_misc_or_fail_no_backtrack (
parse_address_group_reloc (&str, i, GROUP_LDRS));
break;
case OP_ADDRGLDC:
po_misc_or_fail_no_backtrack (
parse_address_group_reloc (&str, i, GROUP_LDC));
break;
case OP_SH:
po_misc_or_fail (parse_shifter_operand (&str, i));
break;
case OP_SHG:
po_misc_or_fail_no_backtrack (
parse_shifter_operand_group_reloc (&str, i));
break;
case OP_oSHll:
po_misc_or_fail (parse_shift (&str, i, SHIFT_LSL_IMMEDIATE));
break;
case OP_oSHar:
po_misc_or_fail (parse_shift (&str, i, SHIFT_ASR_IMMEDIATE));
break;
case OP_oSHllar:
po_misc_or_fail (parse_shift (&str, i, SHIFT_LSL_OR_ASR_IMMEDIATE));
break;
default:
as_fatal (_("unhandled operand code %d"), op_parse_code);
}
/* Various value-based sanity checks and shared operations. We
do not signal immediate failures for the register constraints;
this allows a syntax error to take precedence. */
switch (op_parse_code)
{
case OP_oRRnpc:
case OP_RRnpc:
case OP_RRnpcb:
case OP_RRw:
case OP_oRRw:
case OP_RRnpc_I0:
if (inst.operands[i].isreg && inst.operands[i].reg == REG_PC)
inst.error = BAD_PC;
break;
case OP_oRRnpcsp:
case OP_RRnpcsp:
if (inst.operands[i].isreg)
{
if (inst.operands[i].reg == REG_PC)
inst.error = BAD_PC;
else if (inst.operands[i].reg == REG_SP)
inst.error = BAD_SP;
}
break;
case OP_RRnpctw:
if (inst.operands[i].isreg
&& inst.operands[i].reg == REG_PC
&& (inst.operands[i].writeback || thumb))
inst.error = BAD_PC;
break;
case OP_CPSF:
case OP_ENDI:
case OP_oROR:
case OP_wPSR:
case OP_rPSR:
case OP_COND:
case OP_oBARRIER_I15:
case OP_REGLST:
case OP_VRSLST:
case OP_VRDLST:
case OP_VRSDLST:
case OP_NRDLST:
case OP_NSTRLST:
if (val == FAIL)
goto failure;
inst.operands[i].imm = val;
break;
default:
break;
}
/* If we get here, this operand was successfully parsed. */
inst.operands[i].present = 1;
continue;
bad_args:
inst.error = BAD_ARGS;
failure:
if (!backtrack_pos)
{
/* The parse routine should already have set inst.error, but set a
default here just in case. */
if (!inst.error)
inst.error = _("syntax error");
return FAIL;
}
/* Do not backtrack over a trailing optional argument that
absorbed some text. We will only fail again, with the
'garbage following instruction' error message, which is
probably less helpful than the current one. */
if (backtrack_index == i && backtrack_pos != str
&& upat[i+1] == OP_stop)
{
if (!inst.error)
inst.error = _("syntax error");
return FAIL;
}
/* Try again, skipping the optional argument at backtrack_pos. */
str = backtrack_pos;
inst.error = backtrack_error;
inst.operands[backtrack_index].present = 0;
i = backtrack_index;
backtrack_pos = 0;
}
/* Check that we have parsed all the arguments. */
if (*str != '\0' && !inst.error)
inst.error = _("garbage following instruction");
return inst.error ? FAIL : SUCCESS;
}
#undef po_char_or_fail
#undef po_reg_or_fail
#undef po_reg_or_goto
#undef po_imm_or_fail
#undef po_scalar_or_fail
#undef po_barrier_or_imm
/* Shorthand macro for instruction encoding functions issuing errors. */
#define constraint(expr, err) \
do \
{ \
if (expr) \
{ \
inst.error = err; \
return; \
} \
} \
while (0)
/* Reject "bad registers" for Thumb-2 instructions. Many Thumb-2
instructions are unpredictable if these registers are used. This
is the BadReg predicate in ARM's Thumb-2 documentation. */
#define reject_bad_reg(reg) \
do \
if (reg == REG_SP || reg == REG_PC) \
{ \
inst.error = (reg == REG_SP) ? BAD_SP : BAD_PC; \
return; \
} \
while (0)
/* If REG is R13 (the stack pointer), warn that its use is
deprecated. */
#define warn_deprecated_sp(reg) \
do \
if (warn_on_deprecated && reg == REG_SP) \
as_tsktsk (_("use of r13 is deprecated")); \
while (0)
/* Functions for operand encoding. ARM, then Thumb. */
#define rotate_left(v, n) (v << (n & 31) | v >> ((32 - n) & 31))
/* If VAL can be encoded in the immediate field of an ARM instruction,
return the encoded form. Otherwise, return FAIL. */
static unsigned int
encode_arm_immediate (unsigned int val)
{
unsigned int a, i;
for (i = 0; i < 32; i += 2)
if ((a = rotate_left (val, i)) <= 0xff)
return a | (i << 7); /* 12-bit pack: [shift-cnt,const]. */
return FAIL;
}
/* If VAL can be encoded in the immediate field of a Thumb32 instruction,
return the encoded form. Otherwise, return FAIL. */
static unsigned int
encode_thumb32_immediate (unsigned int val)
{
unsigned int a, i;
if (val <= 0xff)
return val;
for (i = 1; i <= 24; i++)
{
a = val >> i;
if ((val & ~(0xff << i)) == 0)
return ((val >> i) & 0x7f) | ((32 - i) << 7);
}
a = val & 0xff;
if (val == ((a << 16) | a))
return 0x100 | a;
if (val == ((a << 24) | (a << 16) | (a << 8) | a))
return 0x300 | a;
a = val & 0xff00;
if (val == ((a << 16) | a))
return 0x200 | (a >> 8);
return FAIL;
}
/* Encode a VFP SP or DP register number into inst.instruction. */
static void
encode_arm_vfp_reg (int reg, enum vfp_reg_pos pos)
{
if ((pos == VFP_REG_Dd || pos == VFP_REG_Dn || pos == VFP_REG_Dm)
&& reg > 15)
{
if (ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_d32))
{
if (thumb_mode)
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used,
fpu_vfp_ext_d32);
else
ARM_MERGE_FEATURE_SETS (arm_arch_used, arm_arch_used,
fpu_vfp_ext_d32);
}
else
{
first_error (_("D register out of range for selected VFP version"));
return;
}
}
switch (pos)
{
case VFP_REG_Sd:
inst.instruction |= ((reg >> 1) << 12) | ((reg & 1) << 22);
break;
case VFP_REG_Sn:
inst.instruction |= ((reg >> 1) << 16) | ((reg & 1) << 7);
break;
case VFP_REG_Sm:
inst.instruction |= ((reg >> 1) << 0) | ((reg & 1) << 5);
break;
case VFP_REG_Dd:
inst.instruction |= ((reg & 15) << 12) | ((reg >> 4) << 22);
break;
case VFP_REG_Dn:
inst.instruction |= ((reg & 15) << 16) | ((reg >> 4) << 7);
break;
case VFP_REG_Dm:
inst.instruction |= (reg & 15) | ((reg >> 4) << 5);
break;
default:
abort ();
}
}
/* Encode a <shift> in an ARM-format instruction. The immediate,
if any, is handled by md_apply_fix. */
static void
encode_arm_shift (int i)
{
if (inst.operands[i].shift_kind == SHIFT_RRX)
inst.instruction |= SHIFT_ROR << 5;
else
{
inst.instruction |= inst.operands[i].shift_kind << 5;
if (inst.operands[i].immisreg)
{
inst.instruction |= SHIFT_BY_REG;
inst.instruction |= inst.operands[i].imm << 8;
}
else
inst.reloc.type = BFD_RELOC_ARM_SHIFT_IMM;
}
}
static void
encode_arm_shifter_operand (int i)
{
if (inst.operands[i].isreg)
{
inst.instruction |= inst.operands[i].reg;
encode_arm_shift (i);
}
else
{
inst.instruction |= INST_IMMEDIATE;
if (inst.reloc.type != BFD_RELOC_ARM_IMMEDIATE)
inst.instruction |= inst.operands[i].imm;
}
}
/* Subroutine of encode_arm_addr_mode_2 and encode_arm_addr_mode_3. */
static void
encode_arm_addr_mode_common (int i, bfd_boolean is_t)
{
/* PR 14260:
Generate an error if the operand is not a register. */
constraint (!inst.operands[i].isreg,
_("Instruction does not support =N addresses"));
inst.instruction |= inst.operands[i].reg << 16;
if (inst.operands[i].preind)
{
if (is_t)
{
inst.error = _("instruction does not accept preindexed addressing");
return;
}
inst.instruction |= PRE_INDEX;
if (inst.operands[i].writeback)
inst.instruction |= WRITE_BACK;
}
else if (inst.operands[i].postind)
{
gas_assert (inst.operands[i].writeback);
if (is_t)
inst.instruction |= WRITE_BACK;
}
else /* unindexed - only for coprocessor */
{
inst.error = _("instruction does not accept unindexed addressing");
return;
}
if (((inst.instruction & WRITE_BACK) || !(inst.instruction & PRE_INDEX))
&& (((inst.instruction & 0x000f0000) >> 16)
== ((inst.instruction & 0x0000f000) >> 12)))
as_warn ((inst.instruction & LOAD_BIT)
? _("destination register same as write-back base")
: _("source register same as write-back base"));
}
/* inst.operands[i] was set up by parse_address. Encode it into an
ARM-format mode 2 load or store instruction. If is_t is true,
reject forms that cannot be used with a T instruction (i.e. not
post-indexed). */
static void
encode_arm_addr_mode_2 (int i, bfd_boolean is_t)
{
const bfd_boolean is_pc = (inst.operands[i].reg == REG_PC);
encode_arm_addr_mode_common (i, is_t);
if (inst.operands[i].immisreg)
{
constraint ((inst.operands[i].imm == REG_PC
|| (is_pc && inst.operands[i].writeback)),
BAD_PC_ADDRESSING);
inst.instruction |= INST_IMMEDIATE; /* yes, this is backwards */
inst.instruction |= inst.operands[i].imm;
if (!inst.operands[i].negative)
inst.instruction |= INDEX_UP;
if (inst.operands[i].shifted)
{
if (inst.operands[i].shift_kind == SHIFT_RRX)
inst.instruction |= SHIFT_ROR << 5;
else
{
inst.instruction |= inst.operands[i].shift_kind << 5;
inst.reloc.type = BFD_RELOC_ARM_SHIFT_IMM;
}
}
}
else /* immediate offset in inst.reloc */
{
if (is_pc && !inst.reloc.pc_rel)
{
const bfd_boolean is_load = ((inst.instruction & LOAD_BIT) != 0);
/* If is_t is TRUE, it's called from do_ldstt. ldrt/strt
cannot use PC in addressing.
PC cannot be used in writeback addressing, either. */
constraint ((is_t || inst.operands[i].writeback),
BAD_PC_ADDRESSING);
/* Use of PC in str is deprecated for ARMv7. */
if (warn_on_deprecated
&& !is_load
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v7))
as_tsktsk (_("use of PC in this instruction is deprecated"));
}
if (inst.reloc.type == BFD_RELOC_UNUSED)
{
/* Prefer + for zero encoded value. */
if (!inst.operands[i].negative)
inst.instruction |= INDEX_UP;
inst.reloc.type = BFD_RELOC_ARM_OFFSET_IMM;
}
}
}
/* inst.operands[i] was set up by parse_address. Encode it into an
ARM-format mode 3 load or store instruction. Reject forms that
cannot be used with such instructions. If is_t is true, reject
forms that cannot be used with a T instruction (i.e. not
post-indexed). */
static void
encode_arm_addr_mode_3 (int i, bfd_boolean is_t)
{
if (inst.operands[i].immisreg && inst.operands[i].shifted)
{
inst.error = _("instruction does not accept scaled register index");
return;
}
encode_arm_addr_mode_common (i, is_t);
if (inst.operands[i].immisreg)
{
constraint ((inst.operands[i].imm == REG_PC
|| (is_t && inst.operands[i].reg == REG_PC)),
BAD_PC_ADDRESSING);
constraint (inst.operands[i].reg == REG_PC && inst.operands[i].writeback,
BAD_PC_WRITEBACK);
inst.instruction |= inst.operands[i].imm;
if (!inst.operands[i].negative)
inst.instruction |= INDEX_UP;
}
else /* immediate offset in inst.reloc */
{
constraint ((inst.operands[i].reg == REG_PC && !inst.reloc.pc_rel
&& inst.operands[i].writeback),
BAD_PC_WRITEBACK);
inst.instruction |= HWOFFSET_IMM;
if (inst.reloc.type == BFD_RELOC_UNUSED)
{
/* Prefer + for zero encoded value. */
if (!inst.operands[i].negative)
inst.instruction |= INDEX_UP;
inst.reloc.type = BFD_RELOC_ARM_OFFSET_IMM8;
}
}
}
/* Write immediate bits [7:0] to the following locations:
|28/24|23 19|18 16|15 4|3 0|
| a |x x x x x|b c d|x x x x x x x x x x x x|e f g h|
This function is used by VMOV/VMVN/VORR/VBIC. */
static void
neon_write_immbits (unsigned immbits)
{
inst.instruction |= immbits & 0xf;
inst.instruction |= ((immbits >> 4) & 0x7) << 16;
inst.instruction |= ((immbits >> 7) & 0x1) << (thumb_mode ? 28 : 24);
}
/* Invert low-order SIZE bits of XHI:XLO. */
static void
neon_invert_size (unsigned *xlo, unsigned *xhi, int size)
{
unsigned immlo = xlo ? *xlo : 0;
unsigned immhi = xhi ? *xhi : 0;
switch (size)
{
case 8:
immlo = (~immlo) & 0xff;
break;
case 16:
immlo = (~immlo) & 0xffff;
break;
case 64:
immhi = (~immhi) & 0xffffffff;
/* fall through. */
case 32:
immlo = (~immlo) & 0xffffffff;
break;
default:
abort ();
}
if (xlo)
*xlo = immlo;
if (xhi)
*xhi = immhi;
}
/* True if IMM has form 0bAAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD for bits
A, B, C, D. */
static int
neon_bits_same_in_bytes (unsigned imm)
{
return ((imm & 0x000000ff) == 0 || (imm & 0x000000ff) == 0x000000ff)
&& ((imm & 0x0000ff00) == 0 || (imm & 0x0000ff00) == 0x0000ff00)
&& ((imm & 0x00ff0000) == 0 || (imm & 0x00ff0000) == 0x00ff0000)
&& ((imm & 0xff000000) == 0 || (imm & 0xff000000) == 0xff000000);
}
/* For immediate of above form, return 0bABCD. */
static unsigned
neon_squash_bits (unsigned imm)
{
return (imm & 0x01) | ((imm & 0x0100) >> 7) | ((imm & 0x010000) >> 14)
| ((imm & 0x01000000) >> 21);
}
/* Compress quarter-float representation to 0b...000 abcdefgh. */
static unsigned
neon_qfloat_bits (unsigned imm)
{
return ((imm >> 19) & 0x7f) | ((imm >> 24) & 0x80);
}
/* Returns CMODE. IMMBITS [7:0] is set to bits suitable for inserting into
the instruction. *OP is passed as the initial value of the op field, and
may be set to a different value depending on the constant (i.e.
"MOV I64, 0bAAAAAAAABBBB..." which uses OP = 1 despite being MOV not
MVN). If the immediate looks like a repeated pattern then also
try smaller element sizes. */
static int
neon_cmode_for_move_imm (unsigned immlo, unsigned immhi, int float_p,
unsigned *immbits, int *op, int size,
enum neon_el_type type)
{
/* Only permit float immediates (including 0.0/-0.0) if the operand type is
float. */
if (type == NT_float && !float_p)
return FAIL;
if (type == NT_float && is_quarter_float (immlo) && immhi == 0)
{
if (size != 32 || *op == 1)
return FAIL;
*immbits = neon_qfloat_bits (immlo);
return 0xf;
}
if (size == 64)
{
if (neon_bits_same_in_bytes (immhi)
&& neon_bits_same_in_bytes (immlo))
{
if (*op == 1)
return FAIL;
*immbits = (neon_squash_bits (immhi) << 4)
| neon_squash_bits (immlo);
*op = 1;
return 0xe;
}
if (immhi != immlo)
return FAIL;
}
if (size >= 32)
{
if (immlo == (immlo & 0x000000ff))
{
*immbits = immlo;
return 0x0;
}
else if (immlo == (immlo & 0x0000ff00))
{
*immbits = immlo >> 8;
return 0x2;
}
else if (immlo == (immlo & 0x00ff0000))
{
*immbits = immlo >> 16;
return 0x4;
}
else if (immlo == (immlo & 0xff000000))
{
*immbits = immlo >> 24;
return 0x6;
}
else if (immlo == ((immlo & 0x0000ff00) | 0x000000ff))
{
*immbits = (immlo >> 8) & 0xff;
return 0xc;
}
else if (immlo == ((immlo & 0x00ff0000) | 0x0000ffff))
{
*immbits = (immlo >> 16) & 0xff;
return 0xd;
}
if ((immlo & 0xffff) != (immlo >> 16))
return FAIL;
immlo &= 0xffff;
}
if (size >= 16)
{
if (immlo == (immlo & 0x000000ff))
{
*immbits = immlo;
return 0x8;
}
else if (immlo == (immlo & 0x0000ff00))
{
*immbits = immlo >> 8;
return 0xa;
}
if ((immlo & 0xff) != (immlo >> 8))
return FAIL;
immlo &= 0xff;
}
if (immlo == (immlo & 0x000000ff))
{
/* Don't allow MVN with 8-bit immediate. */
if (*op == 1)
return FAIL;
*immbits = immlo;
return 0xe;
}
return FAIL;
}
enum lit_type
{
CONST_THUMB,
CONST_ARM,
CONST_VEC
};
/* inst.reloc.exp describes an "=expr" load pseudo-operation.
Determine whether it can be performed with a move instruction; if
it can, convert inst.instruction to that move instruction and
return TRUE; if it can't, convert inst.instruction to a literal-pool
load and return FALSE. If this is not a valid thing to do in the
current context, set inst.error and return TRUE.
inst.operands[i] describes the destination register. */
static bfd_boolean
move_or_literal_pool (int i, enum lit_type t, bfd_boolean mode_3)
{
unsigned long tbit;
bfd_boolean thumb_p = (t == CONST_THUMB);
bfd_boolean arm_p = (t == CONST_ARM);
bfd_boolean vec64_p = (t == CONST_VEC) && !inst.operands[i].issingle;
if (thumb_p)
tbit = (inst.instruction > 0xffff) ? THUMB2_LOAD_BIT : THUMB_LOAD_BIT;
else
tbit = LOAD_BIT;
if ((inst.instruction & tbit) == 0)
{
inst.error = _("invalid pseudo operation");
return TRUE;
}
if (inst.reloc.exp.X_op != O_constant
&& inst.reloc.exp.X_op != O_symbol
&& inst.reloc.exp.X_op != O_big)
{
inst.error = _("constant expression expected");
return TRUE;
}
if ((inst.reloc.exp.X_op == O_constant
|| inst.reloc.exp.X_op == O_big)
&& !inst.operands[i].issingle)
{
if (thumb_p && inst.reloc.exp.X_op == O_constant)
{
if (!unified_syntax && (inst.reloc.exp.X_add_number & ~0xFF) == 0)
{
/* This can be done with a mov(1) instruction. */
inst.instruction = T_OPCODE_MOV_I8 | (inst.operands[i].reg << 8);
inst.instruction |= inst.reloc.exp.X_add_number;
return TRUE;
}
}
else if (arm_p && inst.reloc.exp.X_op == O_constant)
{
int value = encode_arm_immediate (inst.reloc.exp.X_add_number);
if (value != FAIL)
{
/* This can be done with a mov instruction. */
inst.instruction &= LITERAL_MASK;
inst.instruction |= INST_IMMEDIATE | (OPCODE_MOV << DATA_OP_SHIFT);
inst.instruction |= value & 0xfff;
return TRUE;
}
value = encode_arm_immediate (~inst.reloc.exp.X_add_number);
if (value != FAIL)
{
/* This can be done with a mvn instruction. */
inst.instruction &= LITERAL_MASK;
inst.instruction |= INST_IMMEDIATE | (OPCODE_MVN << DATA_OP_SHIFT);
inst.instruction |= value & 0xfff;
return TRUE;
}
}
else if (vec64_p)
{
int op = 0;
unsigned immbits = 0;
unsigned immlo = inst.operands[1].imm;
unsigned immhi = inst.operands[1].regisimm
? inst.operands[1].reg
: inst.reloc.exp.X_unsigned
? 0
: ((bfd_int64_t)((int) immlo)) >> 32;
int cmode = neon_cmode_for_move_imm (immlo, immhi, FALSE, &immbits,
&op, 64, NT_invtype);
if (cmode == FAIL)
{
neon_invert_size (&immlo, &immhi, 64);
op = !op;
cmode = neon_cmode_for_move_imm (immlo, immhi, FALSE, &immbits,
&op, 64, NT_invtype);
}
if (cmode != FAIL)
{
inst.instruction = (inst.instruction & VLDR_VMOV_SAME)
| (1 << 23)
| (cmode << 8)
| (op << 5)
| (1 << 4);
/* Fill other bits in vmov encoding for both thumb and arm. */
if (thumb_mode)
inst.instruction |= (0x7 << 29) | (0xF << 24);
else
inst.instruction |= (0xF << 28) | (0x1 << 25);
neon_write_immbits (immbits);
return TRUE;
}
}
}
if (add_to_lit_pool ((!inst.operands[i].isvec
|| inst.operands[i].issingle) ? 4 : 8) == FAIL)
return TRUE;
inst.operands[1].reg = REG_PC;
inst.operands[1].isreg = 1;
inst.operands[1].preind = 1;
inst.reloc.pc_rel = 1;
inst.reloc.type = (thumb_p
? BFD_RELOC_ARM_THUMB_OFFSET
: (mode_3
? BFD_RELOC_ARM_HWLITERAL
: BFD_RELOC_ARM_LITERAL));
return FALSE;
}
/* inst.operands[i] was set up by parse_address. Encode it into an
ARM-format instruction. Reject all forms which cannot be encoded
into a coprocessor load/store instruction. If wb_ok is false,
reject use of writeback; if unind_ok is false, reject use of
unindexed addressing. If reloc_override is not 0, use it instead
of BFD_ARM_CP_OFF_IMM, unless the initial relocation is a group one
(in which case it is preserved). */
static int
encode_arm_cp_address (int i, int wb_ok, int unind_ok, int reloc_override)
{
if (!inst.operands[i].isreg)
{
gas_assert (inst.operands[0].isvec);
if (move_or_literal_pool (0, CONST_VEC, /*mode_3=*/FALSE))
return SUCCESS;
}
inst.instruction |= inst.operands[i].reg << 16;
gas_assert (!(inst.operands[i].preind && inst.operands[i].postind));
if (!inst.operands[i].preind && !inst.operands[i].postind) /* unindexed */
{
gas_assert (!inst.operands[i].writeback);
if (!unind_ok)
{
inst.error = _("instruction does not support unindexed addressing");
return FAIL;
}
inst.instruction |= inst.operands[i].imm;
inst.instruction |= INDEX_UP;
return SUCCESS;
}
if (inst.operands[i].preind)
inst.instruction |= PRE_INDEX;
if (inst.operands[i].writeback)
{
if (inst.operands[i].reg == REG_PC)
{
inst.error = _("pc may not be used with write-back");
return FAIL;
}
if (!wb_ok)
{
inst.error = _("instruction does not support writeback");
return FAIL;
}
inst.instruction |= WRITE_BACK;
}
if (reloc_override)
inst.reloc.type = (bfd_reloc_code_real_type) reloc_override;
else if ((inst.reloc.type < BFD_RELOC_ARM_ALU_PC_G0_NC
|| inst.reloc.type > BFD_RELOC_ARM_LDC_SB_G2)
&& inst.reloc.type != BFD_RELOC_ARM_LDR_PC_G0)
{
if (thumb_mode)
inst.reloc.type = BFD_RELOC_ARM_T32_CP_OFF_IMM;
else
inst.reloc.type = BFD_RELOC_ARM_CP_OFF_IMM;
}
/* Prefer + for zero encoded value. */
if (!inst.operands[i].negative)
inst.instruction |= INDEX_UP;
return SUCCESS;
}
/* Functions for instruction encoding, sorted by sub-architecture.
First some generics; their names are taken from the conventional
bit positions for register arguments in ARM format instructions. */
static void
do_noargs (void)
{
}
static void
do_rd (void)
{
inst.instruction |= inst.operands[0].reg << 12;
}
static void
do_rd_rm (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
}
static void
do_rm_rn (void)
{
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 16;
}
static void
do_rd_rn (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
}
static void
do_rn_rd (void)
{
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg << 12;
}
static bfd_boolean
check_obsolete (const arm_feature_set *feature, const char *msg)
{
if (ARM_CPU_IS_ANY (cpu_variant))
{
as_tsktsk ("%s", msg);
return TRUE;
}
else if (ARM_CPU_HAS_FEATURE (cpu_variant, *feature))
{
as_bad ("%s", msg);
return TRUE;
}
return FALSE;
}
static void
do_rd_rm_rn (void)
{
unsigned Rn = inst.operands[2].reg;
/* Enforce restrictions on SWP instruction. */
if ((inst.instruction & 0x0fbfffff) == 0x01000090)
{
constraint (Rn == inst.operands[0].reg || Rn == inst.operands[1].reg,
_("Rn must not overlap other operands"));
/* SWP{b} is obsolete for ARMv8-A, and deprecated for ARMv6* and ARMv7.
*/
if (!check_obsolete (&arm_ext_v8,
_("swp{b} use is obsoleted for ARMv8 and later"))
&& warn_on_deprecated
&& ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v6))
as_tsktsk (_("swp{b} use is deprecated for ARMv6 and ARMv7"));
}
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= Rn << 16;
}
static void
do_rd_rn_rm (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
}
static void
do_rm_rd_rn (void)
{
constraint ((inst.operands[2].reg == REG_PC), BAD_PC);
constraint (((inst.reloc.exp.X_op != O_constant
&& inst.reloc.exp.X_op != O_illegal)
|| inst.reloc.exp.X_add_number != 0),
BAD_ADDR_MODE);
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
}
static void
do_imm0 (void)
{
inst.instruction |= inst.operands[0].imm;
}
static void
do_rd_cpaddr (void)
{
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_cp_address (1, TRUE, TRUE, 0);
}
/* ARM instructions, in alphabetical order by function name (except
that wrapper functions appear immediately after the function they
wrap). */
/* This is a pseudo-op of the form "adr rd, label" to be converted
into a relative address of the form "add rd, pc, #label-.-8". */
static void
do_adr (void)
{
inst.instruction |= (inst.operands[0].reg << 12); /* Rd */
/* Frag hacking will turn this into a sub instruction if the offset turns
out to be negative. */
inst.reloc.type = BFD_RELOC_ARM_IMMEDIATE;
inst.reloc.pc_rel = 1;
inst.reloc.exp.X_add_number -= 8;
}
/* This is a pseudo-op of the form "adrl rd, label" to be converted
into a relative address of the form:
add rd, pc, #low(label-.-8)"
add rd, rd, #high(label-.-8)" */
static void
do_adrl (void)
{
inst.instruction |= (inst.operands[0].reg << 12); /* Rd */
/* Frag hacking will turn this into a sub instruction if the offset turns
out to be negative. */
inst.reloc.type = BFD_RELOC_ARM_ADRL_IMMEDIATE;
inst.reloc.pc_rel = 1;
inst.size = INSN_SIZE * 2;
inst.reloc.exp.X_add_number -= 8;
}
static void
do_arit (void)
{
if (!inst.operands[1].present)
inst.operands[1].reg = inst.operands[0].reg;
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
encode_arm_shifter_operand (2);
}
static void
do_barrier (void)
{
if (inst.operands[0].present)
inst.instruction |= inst.operands[0].imm;
else
inst.instruction |= 0xf;
}
static void
do_bfc (void)
{
unsigned int msb = inst.operands[1].imm + inst.operands[2].imm;
constraint (msb > 32, _("bit-field extends past end of register"));
/* The instruction encoding stores the LSB and MSB,
not the LSB and width. */
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].imm << 7;
inst.instruction |= (msb - 1) << 16;
}
static void
do_bfi (void)
{
unsigned int msb;
/* #0 in second position is alternative syntax for bfc, which is
the same instruction but with REG_PC in the Rm field. */
if (!inst.operands[1].isreg)
inst.operands[1].reg = REG_PC;
msb = inst.operands[2].imm + inst.operands[3].imm;
constraint (msb > 32, _("bit-field extends past end of register"));
/* The instruction encoding stores the LSB and MSB,
not the LSB and width. */
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].imm << 7;
inst.instruction |= (msb - 1) << 16;
}
static void
do_bfx (void)
{
constraint (inst.operands[2].imm + inst.operands[3].imm > 32,
_("bit-field extends past end of register"));
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].imm << 7;
inst.instruction |= (inst.operands[3].imm - 1) << 16;
}
/* ARM V5 breakpoint instruction (argument parse)
BKPT <16 bit unsigned immediate>
Instruction is not conditional.
The bit pattern given in insns[] has the COND_ALWAYS condition,
and it is an error if the caller tried to override that. */
static void
do_bkpt (void)
{
/* Top 12 of 16 bits to bits 19:8. */
inst.instruction |= (inst.operands[0].imm & 0xfff0) << 4;
/* Bottom 4 of 16 bits to bits 3:0. */
inst.instruction |= inst.operands[0].imm & 0xf;
}
static void
encode_branch (int default_reloc)
{
if (inst.operands[0].hasreloc)
{
constraint (inst.operands[0].imm != BFD_RELOC_ARM_PLT32
&& inst.operands[0].imm != BFD_RELOC_ARM_TLS_CALL,
_("the only valid suffixes here are '(plt)' and '(tlscall)'"));
inst.reloc.type = inst.operands[0].imm == BFD_RELOC_ARM_PLT32
? BFD_RELOC_ARM_PLT32
: thumb_mode ? BFD_RELOC_ARM_THM_TLS_CALL : BFD_RELOC_ARM_TLS_CALL;
}
else
inst.reloc.type = (bfd_reloc_code_real_type) default_reloc;
inst.reloc.pc_rel = 1;
}
static void
do_branch (void)
{
#ifdef OBJ_ELF
if (EF_ARM_EABI_VERSION (meabi_flags) >= EF_ARM_EABI_VER4)
encode_branch (BFD_RELOC_ARM_PCREL_JUMP);
else
#endif
encode_branch (BFD_RELOC_ARM_PCREL_BRANCH);
}
static void
do_bl (void)
{
#ifdef OBJ_ELF
if (EF_ARM_EABI_VERSION (meabi_flags) >= EF_ARM_EABI_VER4)
{
if (inst.cond == COND_ALWAYS)
encode_branch (BFD_RELOC_ARM_PCREL_CALL);
else
encode_branch (BFD_RELOC_ARM_PCREL_JUMP);
}
else
#endif
encode_branch (BFD_RELOC_ARM_PCREL_BRANCH);
}
/* ARM V5 branch-link-exchange instruction (argument parse)
BLX <target_addr> ie BLX(1)
BLX{<condition>} <Rm> ie BLX(2)
Unfortunately, there are two different opcodes for this mnemonic.
So, the insns[].value is not used, and the code here zaps values
into inst.instruction.
Also, the <target_addr> can be 25 bits, hence has its own reloc. */
static void
do_blx (void)
{
if (inst.operands[0].isreg)
{
/* Arg is a register; the opcode provided by insns[] is correct.
It is not illegal to do "blx pc", just useless. */
if (inst.operands[0].reg == REG_PC)
as_tsktsk (_("use of r15 in blx in ARM mode is not really useful"));
inst.instruction |= inst.operands[0].reg;
}
else
{
/* Arg is an address; this instruction cannot be executed
conditionally, and the opcode must be adjusted.
We retain the BFD_RELOC_ARM_PCREL_BLX till the very end
where we generate out a BFD_RELOC_ARM_PCREL_CALL instead. */
constraint (inst.cond != COND_ALWAYS, BAD_COND);
inst.instruction = 0xfa000000;
encode_branch (BFD_RELOC_ARM_PCREL_BLX);
}
}
static void
do_bx (void)
{
bfd_boolean want_reloc;
if (inst.operands[0].reg == REG_PC)
as_tsktsk (_("use of r15 in bx in ARM mode is not really useful"));
inst.instruction |= inst.operands[0].reg;
/* Output R_ARM_V4BX relocations if is an EABI object that looks like
it is for ARMv4t or earlier. */
want_reloc = !ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5);
if (object_arch && !ARM_CPU_HAS_FEATURE (*object_arch, arm_ext_v5))
want_reloc = TRUE;
#ifdef OBJ_ELF
if (EF_ARM_EABI_VERSION (meabi_flags) < EF_ARM_EABI_VER4)
#endif
want_reloc = FALSE;
if (want_reloc)
inst.reloc.type = BFD_RELOC_ARM_V4BX;
}
/* ARM v5TEJ. Jump to Jazelle code. */
static void
do_bxj (void)
{
if (inst.operands[0].reg == REG_PC)
as_tsktsk (_("use of r15 in bxj is not really useful"));
inst.instruction |= inst.operands[0].reg;
}
/* Co-processor data operation:
CDP{cond} <coproc>, <opcode_1>, <CRd>, <CRn>, <CRm>{, <opcode_2>}
CDP2 <coproc>, <opcode_1>, <CRd>, <CRn>, <CRm>{, <opcode_2>} */
static void
do_cdp (void)
{
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].imm << 20;
inst.instruction |= inst.operands[2].reg << 12;
inst.instruction |= inst.operands[3].reg << 16;
inst.instruction |= inst.operands[4].reg;
inst.instruction |= inst.operands[5].imm << 5;
}
static void
do_cmp (void)
{
inst.instruction |= inst.operands[0].reg << 16;
encode_arm_shifter_operand (1);
}
/* Transfer between coprocessor and ARM registers.
MRC{cond} <coproc>, <opcode_1>, <Rd>, <CRn>, <CRm>{, <opcode_2>}
MRC2
MCR{cond}
MCR2
No special properties. */
struct deprecated_coproc_regs_s
{
unsigned cp;
int opc1;
unsigned crn;
unsigned crm;
int opc2;
arm_feature_set deprecated;
arm_feature_set obsoleted;
const char *dep_msg;
const char *obs_msg;
};
#define DEPR_ACCESS_V8 \
N_("This coprocessor register access is deprecated in ARMv8")
/* Table of all deprecated coprocessor registers. */
static struct deprecated_coproc_regs_s deprecated_coproc_regs[] =
{
{15, 0, 7, 10, 5, /* CP15DMB. */
ARM_FEATURE (ARM_EXT_V8, 0), ARM_FEATURE (0, 0),
DEPR_ACCESS_V8, NULL},
{15, 0, 7, 10, 4, /* CP15DSB. */
ARM_FEATURE (ARM_EXT_V8, 0), ARM_FEATURE (0, 0),
DEPR_ACCESS_V8, NULL},
{15, 0, 7, 5, 4, /* CP15ISB. */
ARM_FEATURE (ARM_EXT_V8, 0), ARM_FEATURE (0, 0),
DEPR_ACCESS_V8, NULL},
{14, 6, 1, 0, 0, /* TEEHBR. */
ARM_FEATURE (ARM_EXT_V8, 0), ARM_FEATURE (0, 0),
DEPR_ACCESS_V8, NULL},
{14, 6, 0, 0, 0, /* TEECR. */
ARM_FEATURE (ARM_EXT_V8, 0), ARM_FEATURE (0, 0),
DEPR_ACCESS_V8, NULL},
};
#undef DEPR_ACCESS_V8
static const size_t deprecated_coproc_reg_count =
sizeof (deprecated_coproc_regs) / sizeof (deprecated_coproc_regs[0]);
static void
do_co_reg (void)
{
unsigned Rd;
size_t i;
Rd = inst.operands[2].reg;
if (thumb_mode)
{
if (inst.instruction == 0xee000010
|| inst.instruction == 0xfe000010)
/* MCR, MCR2 */
reject_bad_reg (Rd);
else
/* MRC, MRC2 */
constraint (Rd == REG_SP, BAD_SP);
}
else
{
/* MCR */
if (inst.instruction == 0xe000010)
constraint (Rd == REG_PC, BAD_PC);
}
for (i = 0; i < deprecated_coproc_reg_count; ++i)
{
const struct deprecated_coproc_regs_s *r =
deprecated_coproc_regs + i;
if (inst.operands[0].reg == r->cp
&& inst.operands[1].imm == r->opc1
&& inst.operands[3].reg == r->crn
&& inst.operands[4].reg == r->crm
&& inst.operands[5].imm == r->opc2)
{
if (! ARM_CPU_IS_ANY (cpu_variant)
&& warn_on_deprecated
&& ARM_CPU_HAS_FEATURE (cpu_variant, r->deprecated))
as_tsktsk ("%s", r->dep_msg);
}
}
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].imm << 21;
inst.instruction |= Rd << 12;
inst.instruction |= inst.operands[3].reg << 16;
inst.instruction |= inst.operands[4].reg;
inst.instruction |= inst.operands[5].imm << 5;
}
/* Transfer between coprocessor register and pair of ARM registers.
MCRR{cond} <coproc>, <opcode>, <Rd>, <Rn>, <CRm>.
MCRR2
MRRC{cond}
MRRC2
Two XScale instructions are special cases of these:
MAR{cond} acc0, <RdLo>, <RdHi> == MCRR{cond} p0, #0, <RdLo>, <RdHi>, c0
MRA{cond} acc0, <RdLo>, <RdHi> == MRRC{cond} p0, #0, <RdLo>, <RdHi>, c0
Result unpredictable if Rd or Rn is R15. */
static void
do_co_reg2c (void)
{
unsigned Rd, Rn;
Rd = inst.operands[2].reg;
Rn = inst.operands[3].reg;
if (thumb_mode)
{
reject_bad_reg (Rd);
reject_bad_reg (Rn);
}
else
{
constraint (Rd == REG_PC, BAD_PC);
constraint (Rn == REG_PC, BAD_PC);
}
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].imm << 4;
inst.instruction |= Rd << 12;
inst.instruction |= Rn << 16;
inst.instruction |= inst.operands[4].reg;
}
static void
do_cpsi (void)
{
inst.instruction |= inst.operands[0].imm << 6;
if (inst.operands[1].present)
{
inst.instruction |= CPSI_MMOD;
inst.instruction |= inst.operands[1].imm;
}
}
static void
do_dbg (void)
{
inst.instruction |= inst.operands[0].imm;
}
static void
do_div (void)
{
unsigned Rd, Rn, Rm;
Rd = inst.operands[0].reg;
Rn = (inst.operands[1].present
? inst.operands[1].reg : Rd);
Rm = inst.operands[2].reg;
constraint ((Rd == REG_PC), BAD_PC);
constraint ((Rn == REG_PC), BAD_PC);
constraint ((Rm == REG_PC), BAD_PC);
inst.instruction |= Rd << 16;
inst.instruction |= Rn << 0;
inst.instruction |= Rm << 8;
}
static void
do_it (void)
{
/* There is no IT instruction in ARM mode. We
process it to do the validation as if in
thumb mode, just in case the code gets
assembled for thumb using the unified syntax. */
inst.size = 0;
if (unified_syntax)
{
set_it_insn_type (IT_INSN);
now_it.mask = (inst.instruction & 0xf) | 0x10;
now_it.cc = inst.operands[0].imm;
}
}
/* If there is only one register in the register list,
then return its register number. Otherwise return -1. */
static int
only_one_reg_in_list (int range)
{
int i = ffs (range) - 1;
return (i > 15 || range != (1 << i)) ? -1 : i;
}
static void
encode_ldmstm(int from_push_pop_mnem)
{
int base_reg = inst.operands[0].reg;
int range = inst.operands[1].imm;
int one_reg;
inst.instruction |= base_reg << 16;
inst.instruction |= range;
if (inst.operands[1].writeback)
inst.instruction |= LDM_TYPE_2_OR_3;
if (inst.operands[0].writeback)
{
inst.instruction |= WRITE_BACK;
/* Check for unpredictable uses of writeback. */
if (inst.instruction & LOAD_BIT)
{
/* Not allowed in LDM type 2. */
if ((inst.instruction & LDM_TYPE_2_OR_3)
&& ((range & (1 << REG_PC)) == 0))
as_warn (_("writeback of base register is UNPREDICTABLE"));
/* Only allowed if base reg not in list for other types. */
else if (range & (1 << base_reg))
as_warn (_("writeback of base register when in register list is UNPREDICTABLE"));
}
else /* STM. */
{
/* Not allowed for type 2. */
if (inst.instruction & LDM_TYPE_2_OR_3)
as_warn (_("writeback of base register is UNPREDICTABLE"));
/* Only allowed if base reg not in list, or first in list. */
else if ((range & (1 << base_reg))
&& (range & ((1 << base_reg) - 1)))
as_warn (_("if writeback register is in list, it must be the lowest reg in the list"));
}
}
/* If PUSH/POP has only one register, then use the A2 encoding. */
one_reg = only_one_reg_in_list (range);
if (from_push_pop_mnem && one_reg >= 0)
{
int is_push = (inst.instruction & A_PUSH_POP_OP_MASK) == A1_OPCODE_PUSH;
inst.instruction &= A_COND_MASK;
inst.instruction |= is_push ? A2_OPCODE_PUSH : A2_OPCODE_POP;
inst.instruction |= one_reg << 12;
}
}
static void
do_ldmstm (void)
{
encode_ldmstm (/*from_push_pop_mnem=*/FALSE);
}
/* ARMv5TE load-consecutive (argument parse)
Mode is like LDRH.
LDRccD R, mode
STRccD R, mode. */
static void
do_ldrd (void)
{
constraint (inst.operands[0].reg % 2 != 0,
_("first transfer register must be even"));
constraint (inst.operands[1].present
&& inst.operands[1].reg != inst.operands[0].reg + 1,
_("can only transfer two consecutive registers"));
constraint (inst.operands[0].reg == REG_LR, _("r14 not allowed here"));
constraint (!inst.operands[2].isreg, _("'[' expected"));
if (!inst.operands[1].present)
inst.operands[1].reg = inst.operands[0].reg + 1;
/* encode_arm_addr_mode_3 will diagnose overlap between the base
register and the first register written; we have to diagnose
overlap between the base and the second register written here. */
if (inst.operands[2].reg == inst.operands[1].reg
&& (inst.operands[2].writeback || inst.operands[2].postind))
as_warn (_("base register written back, and overlaps "
"second transfer register"));
if (!(inst.instruction & V4_STR_BIT))
{
/* For an index-register load, the index register must not overlap the
destination (even if not write-back). */
if (inst.operands[2].immisreg
&& ((unsigned) inst.operands[2].imm == inst.operands[0].reg
|| (unsigned) inst.operands[2].imm == inst.operands[1].reg))
as_warn (_("index register overlaps transfer register"));
}
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_addr_mode_3 (2, /*is_t=*/FALSE);
}
static void
do_ldrex (void)
{
constraint (!inst.operands[1].isreg || !inst.operands[1].preind
|| inst.operands[1].postind || inst.operands[1].writeback
|| inst.operands[1].immisreg || inst.operands[1].shifted
|| inst.operands[1].negative
/* This can arise if the programmer has written
strex rN, rM, foo
or if they have mistakenly used a register name as the last
operand, eg:
strex rN, rM, rX
It is very difficult to distinguish between these two cases
because "rX" might actually be a label. ie the register
name has been occluded by a symbol of the same name. So we
just generate a general 'bad addressing mode' type error
message and leave it up to the programmer to discover the
true cause and fix their mistake. */
|| (inst.operands[1].reg == REG_PC),
BAD_ADDR_MODE);
constraint (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0,
_("offset must be zero in ARM encoding"));
constraint ((inst.operands[1].reg == REG_PC), BAD_PC);
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.reloc.type = BFD_RELOC_UNUSED;
}
static void
do_ldrexd (void)
{
constraint (inst.operands[0].reg % 2 != 0,
_("even register required"));
constraint (inst.operands[1].present
&& inst.operands[1].reg != inst.operands[0].reg + 1,
_("can only load two consecutive registers"));
/* If op 1 were present and equal to PC, this function wouldn't
have been called in the first place. */
constraint (inst.operands[0].reg == REG_LR, _("r14 not allowed here"));
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
}
/* In both ARM and thumb state 'ldr pc, #imm' with an immediate
which is not a multiple of four is UNPREDICTABLE. */
static void
check_ldr_r15_aligned (void)
{
constraint (!(inst.operands[1].immisreg)
&& (inst.operands[0].reg == REG_PC
&& inst.operands[1].reg == REG_PC
&& (inst.reloc.exp.X_add_number & 0x3)),
_("ldr to register 15 must be 4-byte alligned"));
}
static void
do_ldst (void)
{
inst.instruction |= inst.operands[0].reg << 12;
if (!inst.operands[1].isreg)
if (move_or_literal_pool (0, CONST_ARM, /*mode_3=*/FALSE))
return;
encode_arm_addr_mode_2 (1, /*is_t=*/FALSE);
check_ldr_r15_aligned ();
}
static void
do_ldstt (void)
{
/* ldrt/strt always use post-indexed addressing. Turn [Rn] into [Rn]! and
reject [Rn,...]. */
if (inst.operands[1].preind)
{
constraint (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0,
_("this instruction requires a post-indexed address"));
inst.operands[1].preind = 0;
inst.operands[1].postind = 1;
inst.operands[1].writeback = 1;
}
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_addr_mode_2 (1, /*is_t=*/TRUE);
}
/* Halfword and signed-byte load/store operations. */
static void
do_ldstv4 (void)
{
constraint (inst.operands[0].reg == REG_PC, BAD_PC);
inst.instruction |= inst.operands[0].reg << 12;
if (!inst.operands[1].isreg)
if (move_or_literal_pool (0, CONST_ARM, /*mode_3=*/TRUE))
return;
encode_arm_addr_mode_3 (1, /*is_t=*/FALSE);
}
static void
do_ldsttv4 (void)
{
/* ldrt/strt always use post-indexed addressing. Turn [Rn] into [Rn]! and
reject [Rn,...]. */
if (inst.operands[1].preind)
{
constraint (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0,
_("this instruction requires a post-indexed address"));
inst.operands[1].preind = 0;
inst.operands[1].postind = 1;
inst.operands[1].writeback = 1;
}
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_addr_mode_3 (1, /*is_t=*/TRUE);
}
/* Co-processor register load/store.
Format: <LDC|STC>{cond}[L] CP#,CRd,<address> */
static void
do_lstc (void)
{
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].reg << 12;
encode_arm_cp_address (2, TRUE, TRUE, 0);
}
static void
do_mlas (void)
{
/* This restriction does not apply to mls (nor to mla in v6 or later). */
if (inst.operands[0].reg == inst.operands[1].reg
&& !ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6)
&& !(inst.instruction & 0x00400000))
as_tsktsk (_("Rd and Rm should be different in mla"));
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 8;
inst.instruction |= inst.operands[3].reg << 12;
}
static void
do_mov (void)
{
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_shifter_operand (1);
}
/* ARM V6T2 16-bit immediate register load: MOV[WT]{cond} Rd, #<imm16>. */
static void
do_mov16 (void)
{
bfd_vma imm;
bfd_boolean top;
top = (inst.instruction & 0x00400000) != 0;
constraint (top && inst.reloc.type == BFD_RELOC_ARM_MOVW,
_(":lower16: not allowed this instruction"));
constraint (!top && inst.reloc.type == BFD_RELOC_ARM_MOVT,
_(":upper16: not allowed instruction"));
inst.instruction |= inst.operands[0].reg << 12;
if (inst.reloc.type == BFD_RELOC_UNUSED)
{
imm = inst.reloc.exp.X_add_number;
/* The value is in two pieces: 0:11, 16:19. */
inst.instruction |= (imm & 0x00000fff);
inst.instruction |= (imm & 0x0000f000) << 4;
}
}
static void do_vfp_nsyn_opcode (const char *);
static int
do_vfp_nsyn_mrs (void)
{
if (inst.operands[0].isvec)
{
if (inst.operands[1].reg != 1)
first_error (_("operand 1 must be FPSCR"));
memset (&inst.operands[0], '\0', sizeof (inst.operands[0]));
memset (&inst.operands[1], '\0', sizeof (inst.operands[1]));
do_vfp_nsyn_opcode ("fmstat");
}
else if (inst.operands[1].isvec)
do_vfp_nsyn_opcode ("fmrx");
else
return FAIL;
return SUCCESS;
}
static int
do_vfp_nsyn_msr (void)
{
if (inst.operands[0].isvec)
do_vfp_nsyn_opcode ("fmxr");
else
return FAIL;
return SUCCESS;
}
static void
do_vmrs (void)
{
unsigned Rt = inst.operands[0].reg;
if (thumb_mode && Rt == REG_SP)
{
inst.error = BAD_SP;
return;
}
/* APSR_ sets isvec. All other refs to PC are illegal. */
if (!inst.operands[0].isvec && Rt == REG_PC)
{
inst.error = BAD_PC;
return;
}
/* If we get through parsing the register name, we just insert the number
generated into the instruction without further validation. */
inst.instruction |= (inst.operands[1].reg << 16);
inst.instruction |= (Rt << 12);
}
static void
do_vmsr (void)
{
unsigned Rt = inst.operands[1].reg;
if (thumb_mode)
reject_bad_reg (Rt);
else if (Rt == REG_PC)
{
inst.error = BAD_PC;
return;
}
/* If we get through parsing the register name, we just insert the number
generated into the instruction without further validation. */
inst.instruction |= (inst.operands[0].reg << 16);
inst.instruction |= (Rt << 12);
}
static void
do_mrs (void)
{
unsigned br;
if (do_vfp_nsyn_mrs () == SUCCESS)
return;
constraint (inst.operands[0].reg == REG_PC, BAD_PC);
inst.instruction |= inst.operands[0].reg << 12;
if (inst.operands[1].isreg)
{
br = inst.operands[1].reg;
if (((br & 0x200) == 0) && ((br & 0xf0000) != 0xf000))
as_bad (_("bad register for mrs"));
}
else
{
/* mrs only accepts CPSR/SPSR/CPSR_all/SPSR_all. */
constraint ((inst.operands[1].imm & (PSR_c|PSR_x|PSR_s|PSR_f))
!= (PSR_c|PSR_f),
_("'APSR', 'CPSR' or 'SPSR' expected"));
br = (15<<16) | (inst.operands[1].imm & SPSR_BIT);
}
inst.instruction |= br;
}
/* Two possible forms:
"{C|S}PSR_<field>, Rm",
"{C|S}PSR_f, #expression". */
static void
do_msr (void)
{
if (do_vfp_nsyn_msr () == SUCCESS)
return;
inst.instruction |= inst.operands[0].imm;
if (inst.operands[1].isreg)
inst.instruction |= inst.operands[1].reg;
else
{
inst.instruction |= INST_IMMEDIATE;
inst.reloc.type = BFD_RELOC_ARM_IMMEDIATE;
inst.reloc.pc_rel = 0;
}
}
static void
do_mul (void)
{
constraint (inst.operands[2].reg == REG_PC, BAD_PC);
if (!inst.operands[2].present)
inst.operands[2].reg = inst.operands[0].reg;
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 8;
if (inst.operands[0].reg == inst.operands[1].reg
&& !ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6))
as_tsktsk (_("Rd and Rm should be different in mul"));
}
/* Long Multiply Parser
UMULL RdLo, RdHi, Rm, Rs
SMULL RdLo, RdHi, Rm, Rs
UMLAL RdLo, RdHi, Rm, Rs
SMLAL RdLo, RdHi, Rm, Rs. */
static void
do_mull (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
inst.instruction |= inst.operands[3].reg << 8;
/* rdhi and rdlo must be different. */
if (inst.operands[0].reg == inst.operands[1].reg)
as_tsktsk (_("rdhi and rdlo must be different"));
/* rdhi, rdlo and rm must all be different before armv6. */
if ((inst.operands[0].reg == inst.operands[2].reg
|| inst.operands[1].reg == inst.operands[2].reg)
&& !ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6))
as_tsktsk (_("rdhi, rdlo and rm must all be different"));
}
static void
do_nop (void)
{
if (inst.operands[0].present
|| ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6k))
{
/* Architectural NOP hints are CPSR sets with no bits selected. */
inst.instruction &= 0xf0000000;
inst.instruction |= 0x0320f000;
if (inst.operands[0].present)
inst.instruction |= inst.operands[0].imm;
}
}
/* ARM V6 Pack Halfword Bottom Top instruction (argument parse).
PKHBT {<cond>} <Rd>, <Rn>, <Rm> {, LSL #<shift_imm>}
Condition defaults to COND_ALWAYS.
Error if Rd, Rn or Rm are R15. */
static void
do_pkhbt (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
if (inst.operands[3].present)
encode_arm_shift (3);
}
/* ARM V6 PKHTB (Argument Parse). */
static void
do_pkhtb (void)
{
if (!inst.operands[3].present)
{
/* If the shift specifier is omitted, turn the instruction
into pkhbt rd, rm, rn. */
inst.instruction &= 0xfff00010;
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 16;
}
else
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
encode_arm_shift (3);
}
}
/* ARMv5TE: Preload-Cache
MP Extensions: Preload for write
PLD(W) <addr_mode>
Syntactically, like LDR with B=1, W=0, L=1. */
static void
do_pld (void)
{
constraint (!inst.operands[0].isreg,
_("'[' expected after PLD mnemonic"));
constraint (inst.operands[0].postind,
_("post-indexed expression used in preload instruction"));
constraint (inst.operands[0].writeback,
_("writeback used in preload instruction"));
constraint (!inst.operands[0].preind,
_("unindexed addressing used in preload instruction"));
encode_arm_addr_mode_2 (0, /*is_t=*/FALSE);
}
/* ARMv7: PLI <addr_mode> */
static void
do_pli (void)
{
constraint (!inst.operands[0].isreg,
_("'[' expected after PLI mnemonic"));
constraint (inst.operands[0].postind,
_("post-indexed expression used in preload instruction"));
constraint (inst.operands[0].writeback,
_("writeback used in preload instruction"));
constraint (!inst.operands[0].preind,
_("unindexed addressing used in preload instruction"));
encode_arm_addr_mode_2 (0, /*is_t=*/FALSE);
inst.instruction &= ~PRE_INDEX;
}
static void
do_push_pop (void)
{
constraint (inst.operands[0].writeback,
_("push/pop do not support {reglist}^"));
inst.operands[1] = inst.operands[0];
memset (&inst.operands[0], 0, sizeof inst.operands[0]);
inst.operands[0].isreg = 1;
inst.operands[0].writeback = 1;
inst.operands[0].reg = REG_SP;
encode_ldmstm (/*from_push_pop_mnem=*/TRUE);
}
/* ARM V6 RFE (Return from Exception) loads the PC and CPSR from the
word at the specified address and the following word
respectively.
Unconditionally executed.
Error if Rn is R15. */
static void
do_rfe (void)
{
inst.instruction |= inst.operands[0].reg << 16;
if (inst.operands[0].writeback)
inst.instruction |= WRITE_BACK;
}
/* ARM V6 ssat (argument parse). */
static void
do_ssat (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= (inst.operands[1].imm - 1) << 16;
inst.instruction |= inst.operands[2].reg;
if (inst.operands[3].present)
encode_arm_shift (3);
}
/* ARM V6 usat (argument parse). */
static void
do_usat (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].imm << 16;
inst.instruction |= inst.operands[2].reg;
if (inst.operands[3].present)
encode_arm_shift (3);
}
/* ARM V6 ssat16 (argument parse). */
static void
do_ssat16 (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= ((inst.operands[1].imm - 1) << 16);
inst.instruction |= inst.operands[2].reg;
}
static void
do_usat16 (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].imm << 16;
inst.instruction |= inst.operands[2].reg;
}
/* ARM V6 SETEND (argument parse). Sets the E bit in the CPSR while
preserving the other bits.
setend <endian_specifier>, where <endian_specifier> is either
BE or LE. */
static void
do_setend (void)
{
if (warn_on_deprecated
&& ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v8))
as_tsktsk (_("setend use is deprecated for ARMv8"));
if (inst.operands[0].imm)
inst.instruction |= 0x200;
}
static void
do_shift (void)
{
unsigned int Rm = (inst.operands[1].present
? inst.operands[1].reg
: inst.operands[0].reg);
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= Rm;
if (inst.operands[2].isreg) /* Rd, {Rm,} Rs */
{
inst.instruction |= inst.operands[2].reg << 8;
inst.instruction |= SHIFT_BY_REG;
/* PR 12854: Error on extraneous shifts. */
constraint (inst.operands[2].shifted,
_("extraneous shift as part of operand to shift insn"));
}
else
inst.reloc.type = BFD_RELOC_ARM_SHIFT_IMM;
}
static void
do_smc (void)
{
inst.reloc.type = BFD_RELOC_ARM_SMC;
inst.reloc.pc_rel = 0;
}
static void
do_hvc (void)
{
inst.reloc.type = BFD_RELOC_ARM_HVC;
inst.reloc.pc_rel = 0;
}
static void
do_swi (void)
{
inst.reloc.type = BFD_RELOC_ARM_SWI;
inst.reloc.pc_rel = 0;
}
/* ARM V5E (El Segundo) signed-multiply-accumulate (argument parse)
SMLAxy{cond} Rd,Rm,Rs,Rn
SMLAWy{cond} Rd,Rm,Rs,Rn
Error if any register is R15. */
static void
do_smla (void)
{
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 8;
inst.instruction |= inst.operands[3].reg << 12;
}
/* ARM V5E (El Segundo) signed-multiply-accumulate-long (argument parse)
SMLALxy{cond} Rdlo,Rdhi,Rm,Rs
Error if any register is R15.
Warning if Rdlo == Rdhi. */
static void
do_smlal (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
inst.instruction |= inst.operands[3].reg << 8;
if (inst.operands[0].reg == inst.operands[1].reg)
as_tsktsk (_("rdhi and rdlo must be different"));
}
/* ARM V5E (El Segundo) signed-multiply (argument parse)
SMULxy{cond} Rd,Rm,Rs
Error if any register is R15. */
static void
do_smul (void)
{
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 8;
}
/* ARM V6 srs (argument parse). The variable fields in the encoding are
the same for both ARM and Thumb-2. */
static void
do_srs (void)
{
int reg;
if (inst.operands[0].present)
{
reg = inst.operands[0].reg;
constraint (reg != REG_SP, _("SRS base register must be r13"));
}
else
reg = REG_SP;
inst.instruction |= reg << 16;
inst.instruction |= inst.operands[1].imm;
if (inst.operands[0].writeback || inst.operands[1].writeback)
inst.instruction |= WRITE_BACK;
}
/* ARM V6 strex (argument parse). */
static void
do_strex (void)
{
constraint (!inst.operands[2].isreg || !inst.operands[2].preind
|| inst.operands[2].postind || inst.operands[2].writeback
|| inst.operands[2].immisreg || inst.operands[2].shifted
|| inst.operands[2].negative
/* See comment in do_ldrex(). */
|| (inst.operands[2].reg == REG_PC),
BAD_ADDR_MODE);
constraint (inst.operands[0].reg == inst.operands[1].reg
|| inst.operands[0].reg == inst.operands[2].reg, BAD_OVERLAP);
constraint (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0,
_("offset must be zero in ARM encoding"));
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 16;
inst.reloc.type = BFD_RELOC_UNUSED;
}
static void
do_t_strexbh (void)
{
constraint (!inst.operands[2].isreg || !inst.operands[2].preind
|| inst.operands[2].postind || inst.operands[2].writeback
|| inst.operands[2].immisreg || inst.operands[2].shifted
|| inst.operands[2].negative,
BAD_ADDR_MODE);
constraint (inst.operands[0].reg == inst.operands[1].reg
|| inst.operands[0].reg == inst.operands[2].reg, BAD_OVERLAP);
do_rm_rd_rn ();
}
static void
do_strexd (void)
{
constraint (inst.operands[1].reg % 2 != 0,
_("even register required"));
constraint (inst.operands[2].present
&& inst.operands[2].reg != inst.operands[1].reg + 1,
_("can only store two consecutive registers"));
/* If op 2 were present and equal to PC, this function wouldn't
have been called in the first place. */
constraint (inst.operands[1].reg == REG_LR, _("r14 not allowed here"));
constraint (inst.operands[0].reg == inst.operands[1].reg
|| inst.operands[0].reg == inst.operands[1].reg + 1
|| inst.operands[0].reg == inst.operands[3].reg,
BAD_OVERLAP);
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[3].reg << 16;
}
/* ARM V8 STRL. */
static void
do_stlex (void)
{
constraint (inst.operands[0].reg == inst.operands[1].reg
|| inst.operands[0].reg == inst.operands[2].reg, BAD_OVERLAP);
do_rd_rm_rn ();
}
static void
do_t_stlex (void)
{
constraint (inst.operands[0].reg == inst.operands[1].reg
|| inst.operands[0].reg == inst.operands[2].reg, BAD_OVERLAP);
do_rm_rd_rn ();
}
/* ARM V6 SXTAH extracts a 16-bit value from a register, sign
extends it to 32-bits, and adds the result to a value in another
register. You can specify a rotation by 0, 8, 16, or 24 bits
before extracting the 16-bit value.
SXTAH{<cond>} <Rd>, <Rn>, <Rm>{, <rotation>}
Condition defaults to COND_ALWAYS.
Error if any register uses R15. */
static void
do_sxtah (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
inst.instruction |= inst.operands[3].imm << 10;
}
/* ARM V6 SXTH.
SXTH {<cond>} <Rd>, <Rm>{, <rotation>}
Condition defaults to COND_ALWAYS.
Error if any register uses R15. */
static void
do_sxth (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].imm << 10;
}
/* VFP instructions. In a logical order: SP variant first, monad
before dyad, arithmetic then move then load/store. */
static void
do_vfp_sp_monadic (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Sm);
}
static void
do_vfp_sp_dyadic (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Sn);
encode_arm_vfp_reg (inst.operands[2].reg, VFP_REG_Sm);
}
static void
do_vfp_sp_compare_z (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
}
static void
do_vfp_dp_sp_cvt (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Sm);
}
static void
do_vfp_sp_dp_cvt (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dm);
}
static void
do_vfp_reg_from_sp (void)
{
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Sn);
}
static void
do_vfp_reg2_from_sp2 (void)
{
constraint (inst.operands[2].imm != 2,
_("only two consecutive VFP SP registers allowed here"));
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
encode_arm_vfp_reg (inst.operands[2].reg, VFP_REG_Sm);
}
static void
do_vfp_sp_from_reg (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sn);
inst.instruction |= inst.operands[1].reg << 12;
}
static void
do_vfp_sp2_from_reg2 (void)
{
constraint (inst.operands[0].imm != 2,
_("only two consecutive VFP SP registers allowed here"));
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sm);
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
}
static void
do_vfp_sp_ldst (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
encode_arm_cp_address (1, FALSE, TRUE, 0);
}
static void
do_vfp_dp_ldst (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
encode_arm_cp_address (1, FALSE, TRUE, 0);
}
static void
vfp_sp_ldstm (enum vfp_ldstm_type ldstm_type)
{
if (inst.operands[0].writeback)
inst.instruction |= WRITE_BACK;
else
constraint (ldstm_type != VFP_LDSTMIA,
_("this addressing mode requires base-register writeback"));
inst.instruction |= inst.operands[0].reg << 16;
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Sd);
inst.instruction |= inst.operands[1].imm;
}
static void
vfp_dp_ldstm (enum vfp_ldstm_type ldstm_type)
{
int count;
if (inst.operands[0].writeback)
inst.instruction |= WRITE_BACK;
else
constraint (ldstm_type != VFP_LDSTMIA && ldstm_type != VFP_LDSTMIAX,
_("this addressing mode requires base-register writeback"));
inst.instruction |= inst.operands[0].reg << 16;
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dd);
count = inst.operands[1].imm << 1;
if (ldstm_type == VFP_LDSTMIAX || ldstm_type == VFP_LDSTMDBX)
count += 1;
inst.instruction |= count;
}
static void
do_vfp_sp_ldstmia (void)
{
vfp_sp_ldstm (VFP_LDSTMIA);
}
static void
do_vfp_sp_ldstmdb (void)
{
vfp_sp_ldstm (VFP_LDSTMDB);
}
static void
do_vfp_dp_ldstmia (void)
{
vfp_dp_ldstm (VFP_LDSTMIA);
}
static void
do_vfp_dp_ldstmdb (void)
{
vfp_dp_ldstm (VFP_LDSTMDB);
}
static void
do_vfp_xp_ldstmia (void)
{
vfp_dp_ldstm (VFP_LDSTMIAX);
}
static void
do_vfp_xp_ldstmdb (void)
{
vfp_dp_ldstm (VFP_LDSTMDBX);
}
static void
do_vfp_dp_rd_rm (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dm);
}
static void
do_vfp_dp_rn_rd (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dn);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dd);
}
static void
do_vfp_dp_rd_rn (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dn);
}
static void
do_vfp_dp_rd_rn_rm (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dn);
encode_arm_vfp_reg (inst.operands[2].reg, VFP_REG_Dm);
}
static void
do_vfp_dp_rd (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
}
static void
do_vfp_dp_rm_rd_rn (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dm);
encode_arm_vfp_reg (inst.operands[1].reg, VFP_REG_Dd);
encode_arm_vfp_reg (inst.operands[2].reg, VFP_REG_Dn);
}
/* VFPv3 instructions. */
static void
do_vfp_sp_const (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
inst.instruction |= (inst.operands[1].imm & 0xf0) << 12;
inst.instruction |= (inst.operands[1].imm & 0x0f);
}
static void
do_vfp_dp_const (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
inst.instruction |= (inst.operands[1].imm & 0xf0) << 12;
inst.instruction |= (inst.operands[1].imm & 0x0f);
}
static void
vfp_conv (int srcsize)
{
int immbits = srcsize - inst.operands[1].imm;
if (srcsize == 16 && !(immbits >= 0 && immbits <= srcsize))
{
/* If srcsize is 16, inst.operands[1].imm must be in the range 0-16.
i.e. immbits must be in range 0 - 16. */
inst.error = _("immediate value out of range, expected range [0, 16]");
return;
}
else if (srcsize == 32 && !(immbits >= 0 && immbits < srcsize))
{
/* If srcsize is 32, inst.operands[1].imm must be in the range 1-32.
i.e. immbits must be in range 0 - 31. */
inst.error = _("immediate value out of range, expected range [1, 32]");
return;
}
inst.instruction |= (immbits & 1) << 5;
inst.instruction |= (immbits >> 1);
}
static void
do_vfp_sp_conv_16 (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
vfp_conv (16);
}
static void
do_vfp_dp_conv_16 (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
vfp_conv (16);
}
static void
do_vfp_sp_conv_32 (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
vfp_conv (32);
}
static void
do_vfp_dp_conv_32 (void)
{
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Dd);
vfp_conv (32);
}
/* FPA instructions. Also in a logical order. */
static void
do_fpa_cmp (void)
{
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg;
}
static void
do_fpa_ldmstm (void)
{
inst.instruction |= inst.operands[0].reg << 12;
switch (inst.operands[1].imm)
{
case 1: inst.instruction |= CP_T_X; break;
case 2: inst.instruction |= CP_T_Y; break;
case 3: inst.instruction |= CP_T_Y | CP_T_X; break;
case 4: break;
default: abort ();
}
if (inst.instruction & (PRE_INDEX | INDEX_UP))
{
/* The instruction specified "ea" or "fd", so we can only accept
[Rn]{!}. The instruction does not really support stacking or
unstacking, so we have to emulate these by setting appropriate
bits and offsets. */
constraint (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0,
_("this instruction does not support indexing"));
if ((inst.instruction & PRE_INDEX) || inst.operands[2].writeback)
inst.reloc.exp.X_add_number = 12 * inst.operands[1].imm;
if (!(inst.instruction & INDEX_UP))
inst.reloc.exp.X_add_number = -inst.reloc.exp.X_add_number;
if (!(inst.instruction & PRE_INDEX) && inst.operands[2].writeback)
{
inst.operands[2].preind = 0;
inst.operands[2].postind = 1;
}
}
encode_arm_cp_address (2, TRUE, TRUE, 0);
}
/* iWMMXt instructions: strictly in alphabetical order. */
static void
do_iwmmxt_tandorc (void)
{
constraint (inst.operands[0].reg != REG_PC, _("only r15 allowed here"));
}
static void
do_iwmmxt_textrc (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].imm;
}
static void
do_iwmmxt_textrm (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].imm;
}
static void
do_iwmmxt_tinsr (void)
{
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].imm;
}
static void
do_iwmmxt_tmia (void)
{
inst.instruction |= inst.operands[0].reg << 5;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 12;
}
static void
do_iwmmxt_waligni (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
inst.instruction |= inst.operands[3].imm << 20;
}
static void
do_iwmmxt_wmerge (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
inst.instruction |= inst.operands[3].imm << 21;
}
static void
do_iwmmxt_wmov (void)
{
/* WMOV rD, rN is an alias for WOR rD, rN, rN. */
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[1].reg;
}
static void
do_iwmmxt_wldstbh (void)
{
int reloc;
inst.instruction |= inst.operands[0].reg << 12;
if (thumb_mode)
reloc = BFD_RELOC_ARM_T32_CP_OFF_IMM_S2;
else
reloc = BFD_RELOC_ARM_CP_OFF_IMM_S2;
encode_arm_cp_address (1, TRUE, FALSE, reloc);
}
static void
do_iwmmxt_wldstw (void)
{
/* RIWR_RIWC clears .isreg for a control register. */
if (!inst.operands[0].isreg)
{
constraint (inst.cond != COND_ALWAYS, BAD_COND);
inst.instruction |= 0xf0000000;
}
inst.instruction |= inst.operands[0].reg << 12;
encode_arm_cp_address (1, TRUE, TRUE, 0);
}
static void
do_iwmmxt_wldstd (void)
{
inst.instruction |= inst.operands[0].reg << 12;
if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_cext_iwmmxt2)
&& inst.operands[1].immisreg)
{
inst.instruction &= ~0x1a000ff;
inst.instruction |= (0xf << 28);
if (inst.operands[1].preind)
inst.instruction |= PRE_INDEX;
if (!inst.operands[1].negative)
inst.instruction |= INDEX_UP;
if (inst.operands[1].writeback)
inst.instruction |= WRITE_BACK;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.reloc.exp.X_add_number << 4;
inst.instruction |= inst.operands[1].imm;
}
else
encode_arm_cp_address (1, TRUE, FALSE, 0);
}
static void
do_iwmmxt_wshufh (void)
{
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= ((inst.operands[2].imm & 0xf0) << 16);
inst.instruction |= (inst.operands[2].imm & 0x0f);
}
static void
do_iwmmxt_wzero (void)
{
/* WZERO reg is an alias for WANDN reg, reg, reg. */
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[0].reg << 16;
}
static void
do_iwmmxt_wrwrwr_or_imm5 (void)
{
if (inst.operands[2].isreg)
do_rd_rn_rm ();
else {
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_cext_iwmmxt2),
_("immediate operand requires iWMMXt2"));
do_rd_rn ();
if (inst.operands[2].imm == 0)
{
switch ((inst.instruction >> 20) & 0xf)
{
case 4:
case 5:
case 6:
case 7:
/* w...h wrd, wrn, #0 -> wrorh wrd, wrn, #16. */
inst.operands[2].imm = 16;
inst.instruction = (inst.instruction & 0xff0fffff) | (0x7 << 20);
break;
case 8:
case 9:
case 10:
case 11:
/* w...w wrd, wrn, #0 -> wrorw wrd, wrn, #32. */
inst.operands[2].imm = 32;
inst.instruction = (inst.instruction & 0xff0fffff) | (0xb << 20);
break;
case 12:
case 13:
case 14:
case 15:
{
/* w...d wrd, wrn, #0 -> wor wrd, wrn, wrn. */
unsigned long wrn;
wrn = (inst.instruction >> 16) & 0xf;
inst.instruction &= 0xff0fff0f;
inst.instruction |= wrn;
/* Bail out here; the instruction is now assembled. */
return;
}
}
}
/* Map 32 -> 0, etc. */
inst.operands[2].imm &= 0x1f;
inst.instruction |= (0xf << 28) | ((inst.operands[2].imm & 0x10) << 4) | (inst.operands[2].imm & 0xf);
}
}
/* Cirrus Maverick instructions. Simple 2-, 3-, and 4-register
operations first, then control, shift, and load/store. */
/* Insns like "foo X,Y,Z". */
static void
do_mav_triple (void)
{
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 12;
}
/* Insns like "foo W,X,Y,Z".
where W=MVAX[0:3] and X,Y,Z=MVFX[0:15]. */
static void
do_mav_quad (void)
{
inst.instruction |= inst.operands[0].reg << 5;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
inst.instruction |= inst.operands[3].reg;
}
/* cfmvsc32<cond> DSPSC,MVDX[15:0]. */
static void
do_mav_dspsc (void)
{
inst.instruction |= inst.operands[1].reg << 12;
}
/* Maverick shift immediate instructions.
cfsh32<cond> MVFX[15:0],MVFX[15:0],Shift[6:0].
cfsh64<cond> MVDX[15:0],MVDX[15:0],Shift[6:0]. */
static void
do_mav_shift (void)
{
int imm = inst.operands[2].imm;
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
/* Bits 0-3 of the insn should have bits 0-3 of the immediate.
Bits 5-7 of the insn should have bits 4-6 of the immediate.
Bit 4 should be 0. */
imm = (imm & 0xf) | ((imm & 0x70) << 1);
inst.instruction |= imm;
}
/* XScale instructions. Also sorted arithmetic before move. */
/* Xscale multiply-accumulate (argument parse)
MIAcc acc0,Rm,Rs
MIAPHcc acc0,Rm,Rs
MIAxycc acc0,Rm,Rs. */
static void
do_xsc_mia (void)
{
inst.instruction |= inst.operands[1].reg;
inst.instruction |= inst.operands[2].reg << 12;
}
/* Xscale move-accumulator-register (argument parse)
MARcc acc0,RdLo,RdHi. */
static void
do_xsc_mar (void)
{
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
}
/* Xscale move-register-accumulator (argument parse)
MRAcc RdLo,RdHi,acc0. */
static void
do_xsc_mra (void)
{
constraint (inst.operands[0].reg == inst.operands[1].reg, BAD_OVERLAP);
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
}
/* Encoding functions relevant only to Thumb. */
/* inst.operands[i] is a shifted-register operand; encode
it into inst.instruction in the format used by Thumb32. */
static void
encode_thumb32_shifted_operand (int i)
{
unsigned int value = inst.reloc.exp.X_add_number;
unsigned int shift = inst.operands[i].shift_kind;
constraint (inst.operands[i].immisreg,
_("shift by register not allowed in thumb mode"));
inst.instruction |= inst.operands[i].reg;
if (shift == SHIFT_RRX)
inst.instruction |= SHIFT_ROR << 4;
else
{
constraint (inst.reloc.exp.X_op != O_constant,
_("expression too complex"));
constraint (value > 32
|| (value == 32 && (shift == SHIFT_LSL
|| shift == SHIFT_ROR)),
_("shift expression is too large"));
if (value == 0)
shift = SHIFT_LSL;
else if (value == 32)
value = 0;
inst.instruction |= shift << 4;
inst.instruction |= (value & 0x1c) << 10;
inst.instruction |= (value & 0x03) << 6;
}
}
/* inst.operands[i] was set up by parse_address. Encode it into a
Thumb32 format load or store instruction. Reject forms that cannot
be used with such instructions. If is_t is true, reject forms that
cannot be used with a T instruction; if is_d is true, reject forms
that cannot be used with a D instruction. If it is a store insn,
reject PC in Rn. */
static void
encode_thumb32_addr_mode (int i, bfd_boolean is_t, bfd_boolean is_d)
{
const bfd_boolean is_pc = (inst.operands[i].reg == REG_PC);
constraint (!inst.operands[i].isreg,
_("Instruction does not support =N addresses"));
inst.instruction |= inst.operands[i].reg << 16;
if (inst.operands[i].immisreg)
{
constraint (is_pc, BAD_PC_ADDRESSING);
constraint (is_t || is_d, _("cannot use register index with this instruction"));
constraint (inst.operands[i].negative,
_("Thumb does not support negative register indexing"));
constraint (inst.operands[i].postind,
_("Thumb does not support register post-indexing"));
constraint (inst.operands[i].writeback,
_("Thumb does not support register indexing with writeback"));
constraint (inst.operands[i].shifted && inst.operands[i].shift_kind != SHIFT_LSL,
_("Thumb supports only LSL in shifted register indexing"));
inst.instruction |= inst.operands[i].imm;
if (inst.operands[i].shifted)
{
constraint (inst.reloc.exp.X_op != O_constant,
_("expression too complex"));
constraint (inst.reloc.exp.X_add_number < 0
|| inst.reloc.exp.X_add_number > 3,
_("shift out of range"));
inst.instruction |= inst.reloc.exp.X_add_number << 4;
}
inst.reloc.type = BFD_RELOC_UNUSED;
}
else if (inst.operands[i].preind)
{
constraint (is_pc && inst.operands[i].writeback, BAD_PC_WRITEBACK);
constraint (is_t && inst.operands[i].writeback,
_("cannot use writeback with this instruction"));
constraint (is_pc && ((inst.instruction & THUMB2_LOAD_BIT) == 0),
BAD_PC_ADDRESSING);
if (is_d)
{
inst.instruction |= 0x01000000;
if (inst.operands[i].writeback)
inst.instruction |= 0x00200000;
}
else
{
inst.instruction |= 0x00000c00;
if (inst.operands[i].writeback)
inst.instruction |= 0x00000100;
}
inst.reloc.type = BFD_RELOC_ARM_T32_OFFSET_IMM;
}
else if (inst.operands[i].postind)
{
gas_assert (inst.operands[i].writeback);
constraint (is_pc, _("cannot use post-indexing with PC-relative addressing"));
constraint (is_t, _("cannot use post-indexing with this instruction"));
if (is_d)
inst.instruction |= 0x00200000;
else
inst.instruction |= 0x00000900;
inst.reloc.type = BFD_RELOC_ARM_T32_OFFSET_IMM;
}
else /* unindexed - only for coprocessor */
inst.error = _("instruction does not accept unindexed addressing");
}
/* Table of Thumb instructions which exist in both 16- and 32-bit
encodings (the latter only in post-V6T2 cores). The index is the
value used in the insns table below. When there is more than one
possible 16-bit encoding for the instruction, this table always
holds variant (1).
Also contains several pseudo-instructions used during relaxation. */
#define T16_32_TAB \
X(_adc, 4140, eb400000), \
X(_adcs, 4140, eb500000), \
X(_add, 1c00, eb000000), \
X(_adds, 1c00, eb100000), \
X(_addi, 0000, f1000000), \
X(_addis, 0000, f1100000), \
X(_add_pc,000f, f20f0000), \
X(_add_sp,000d, f10d0000), \
X(_adr, 000f, f20f0000), \
X(_and, 4000, ea000000), \
X(_ands, 4000, ea100000), \
X(_asr, 1000, fa40f000), \
X(_asrs, 1000, fa50f000), \
X(_b, e000, f000b000), \
X(_bcond, d000, f0008000), \
X(_bic, 4380, ea200000), \
X(_bics, 4380, ea300000), \
X(_cmn, 42c0, eb100f00), \
X(_cmp, 2800, ebb00f00), \
X(_cpsie, b660, f3af8400), \
X(_cpsid, b670, f3af8600), \
X(_cpy, 4600, ea4f0000), \
X(_dec_sp,80dd, f1ad0d00), \
X(_eor, 4040, ea800000), \
X(_eors, 4040, ea900000), \
X(_inc_sp,00dd, f10d0d00), \
X(_ldmia, c800, e8900000), \
X(_ldr, 6800, f8500000), \
X(_ldrb, 7800, f8100000), \
X(_ldrh, 8800, f8300000), \
X(_ldrsb, 5600, f9100000), \
X(_ldrsh, 5e00, f9300000), \
X(_ldr_pc,4800, f85f0000), \
X(_ldr_pc2,4800, f85f0000), \
X(_ldr_sp,9800, f85d0000), \
X(_lsl, 0000, fa00f000), \
X(_lsls, 0000, fa10f000), \
X(_lsr, 0800, fa20f000), \
X(_lsrs, 0800, fa30f000), \
X(_mov, 2000, ea4f0000), \
X(_movs, 2000, ea5f0000), \
X(_mul, 4340, fb00f000), \
X(_muls, 4340, ffffffff), /* no 32b muls */ \
X(_mvn, 43c0, ea6f0000), \
X(_mvns, 43c0, ea7f0000), \
X(_neg, 4240, f1c00000), /* rsb #0 */ \
X(_negs, 4240, f1d00000), /* rsbs #0 */ \
X(_orr, 4300, ea400000), \
X(_orrs, 4300, ea500000), \
X(_pop, bc00, e8bd0000), /* ldmia sp!,... */ \
X(_push, b400, e92d0000), /* stmdb sp!,... */ \
X(_rev, ba00, fa90f080), \
X(_rev16, ba40, fa90f090), \
X(_revsh, bac0, fa90f0b0), \
X(_ror, 41c0, fa60f000), \
X(_rors, 41c0, fa70f000), \
X(_sbc, 4180, eb600000), \
X(_sbcs, 4180, eb700000), \
X(_stmia, c000, e8800000), \
X(_str, 6000, f8400000), \
X(_strb, 7000, f8000000), \
X(_strh, 8000, f8200000), \
X(_str_sp,9000, f84d0000), \
X(_sub, 1e00, eba00000), \
X(_subs, 1e00, ebb00000), \
X(_subi, 8000, f1a00000), \
X(_subis, 8000, f1b00000), \
X(_sxtb, b240, fa4ff080), \
X(_sxth, b200, fa0ff080), \
X(_tst, 4200, ea100f00), \
X(_uxtb, b2c0, fa5ff080), \
X(_uxth, b280, fa1ff080), \
X(_nop, bf00, f3af8000), \
X(_yield, bf10, f3af8001), \
X(_wfe, bf20, f3af8002), \
X(_wfi, bf30, f3af8003), \
X(_sev, bf40, f3af8004), \
X(_sevl, bf50, f3af8005), \
X(_udf, de00, f7f0a000)
/* To catch errors in encoding functions, the codes are all offset by
0xF800, putting them in one of the 32-bit prefix ranges, ergo undefined
as 16-bit instructions. */
#define X(a,b,c) T_MNEM##a
enum t16_32_codes { T16_32_OFFSET = 0xF7FF, T16_32_TAB };
#undef X
#define X(a,b,c) 0x##b
static const unsigned short thumb_op16[] = { T16_32_TAB };
#define THUMB_OP16(n) (thumb_op16[(n) - (T16_32_OFFSET + 1)])
#undef X
#define X(a,b,c) 0x##c
static const unsigned int thumb_op32[] = { T16_32_TAB };
#define THUMB_OP32(n) (thumb_op32[(n) - (T16_32_OFFSET + 1)])
#define THUMB_SETS_FLAGS(n) (THUMB_OP32 (n) & 0x00100000)
#undef X
#undef T16_32_TAB
/* Thumb instruction encoders, in alphabetical order. */
/* ADDW or SUBW. */
static void
do_t_add_sub_w (void)
{
int Rd, Rn;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
/* If Rn is REG_PC, this is ADR; if Rn is REG_SP, then this
is the SP-{plus,minus}-immediate form of the instruction. */
if (Rn == REG_SP)
constraint (Rd == REG_PC, BAD_PC);
else
reject_bad_reg (Rd);
inst.instruction |= (Rn << 16) | (Rd << 8);
inst.reloc.type = BFD_RELOC_ARM_T32_IMM12;
}
/* Parse an add or subtract instruction. We get here with inst.instruction
equalling any of THUMB_OPCODE_add, adds, sub, or subs. */
static void
do_t_add_sub (void)
{
int Rd, Rs, Rn;
Rd = inst.operands[0].reg;
Rs = (inst.operands[1].present
? inst.operands[1].reg /* Rd, Rs, foo */
: inst.operands[0].reg); /* Rd, foo -> Rd, Rd, foo */
if (Rd == REG_PC)
set_it_insn_type_last ();
if (unified_syntax)
{
bfd_boolean flags;
bfd_boolean narrow;
int opcode;
flags = (inst.instruction == T_MNEM_adds
|| inst.instruction == T_MNEM_subs);
if (flags)
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (!inst.operands[2].isreg)
{
int add;
constraint (Rd == REG_SP && Rs != REG_SP, BAD_SP);
add = (inst.instruction == T_MNEM_add
|| inst.instruction == T_MNEM_adds);
opcode = 0;
if (inst.size_req != 4)
{
/* Attempt to use a narrow opcode, with relaxation if
appropriate. */
if (Rd == REG_SP && Rs == REG_SP && !flags)
opcode = add ? T_MNEM_inc_sp : T_MNEM_dec_sp;
else if (Rd <= 7 && Rs == REG_SP && add && !flags)
opcode = T_MNEM_add_sp;
else if (Rd <= 7 && Rs == REG_PC && add && !flags)
opcode = T_MNEM_add_pc;
else if (Rd <= 7 && Rs <= 7 && narrow)
{
if (flags)
opcode = add ? T_MNEM_addis : T_MNEM_subis;
else
opcode = add ? T_MNEM_addi : T_MNEM_subi;
}
if (opcode)
{
inst.instruction = THUMB_OP16(opcode);
inst.instruction |= (Rd << 4) | Rs;
inst.reloc.type = BFD_RELOC_ARM_THUMB_ADD;
if (inst.size_req != 2)
inst.relax = opcode;
}
else
constraint (inst.size_req == 2, BAD_HIREG);
}
if (inst.size_req == 4
|| (inst.size_req != 2 && !opcode))
{
if (Rd == REG_PC)
{
constraint (add, BAD_PC);
constraint (Rs != REG_LR || inst.instruction != T_MNEM_subs,
_("only SUBS PC, LR, #const allowed"));
constraint (inst.reloc.exp.X_op != O_constant,
_("expression too complex"));
constraint (inst.reloc.exp.X_add_number < 0
|| inst.reloc.exp.X_add_number > 0xff,
_("immediate value out of range"));
inst.instruction = T2_SUBS_PC_LR
| inst.reloc.exp.X_add_number;
inst.reloc.type = BFD_RELOC_UNUSED;
return;
}
else if (Rs == REG_PC)
{
/* Always use addw/subw. */
inst.instruction = add ? 0xf20f0000 : 0xf2af0000;
inst.reloc.type = BFD_RELOC_ARM_T32_IMM12;
}
else
{
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction = (inst.instruction & 0xe1ffffff)
| 0x10000000;
if (flags)
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
else
inst.reloc.type = BFD_RELOC_ARM_T32_ADD_IMM;
}
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
}
}
else
{
unsigned int value = inst.reloc.exp.X_add_number;
unsigned int shift = inst.operands[2].shift_kind;
Rn = inst.operands[2].reg;
/* See if we can do this with a 16-bit instruction. */
if (!inst.operands[2].shifted && inst.size_req != 4)
{
if (Rd > 7 || Rs > 7 || Rn > 7)
narrow = FALSE;
if (narrow)
{
inst.instruction = ((inst.instruction == T_MNEM_adds
|| inst.instruction == T_MNEM_add)
? T_OPCODE_ADD_R3
: T_OPCODE_SUB_R3);
inst.instruction |= Rd | (Rs << 3) | (Rn << 6);
return;
}
if (inst.instruction == T_MNEM_add && (Rd == Rs || Rd == Rn))
{
/* Thumb-1 cores (except v6-M) require at least one high
register in a narrow non flag setting add. */
if (Rd > 7 || Rn > 7
|| ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6t2)
|| ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_msr))
{
if (Rd == Rn)
{
Rn = Rs;
Rs = Rd;
}
inst.instruction = T_OPCODE_ADD_HI;
inst.instruction |= (Rd & 8) << 4;
inst.instruction |= (Rd & 7);
inst.instruction |= Rn << 3;
return;
}
}
}
constraint (Rd == REG_PC, BAD_PC);
constraint (Rd == REG_SP && Rs != REG_SP, BAD_SP);
constraint (Rs == REG_PC, BAD_PC);
reject_bad_reg (Rn);
/* If we get here, it can't be done in 16 bits. */
constraint (inst.operands[2].shifted && inst.operands[2].immisreg,
_("shift must be constant"));
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
constraint (Rd == REG_SP && Rs == REG_SP && value > 3,
_("shift value over 3 not allowed in thumb mode"));
constraint (Rd == REG_SP && Rs == REG_SP && shift != SHIFT_LSL,
_("only LSL shift allowed in thumb mode"));
encode_thumb32_shifted_operand (2);
}
}
else
{
constraint (inst.instruction == T_MNEM_adds
|| inst.instruction == T_MNEM_subs,
BAD_THUMB32);
if (!inst.operands[2].isreg) /* Rd, Rs, #imm */
{
constraint ((Rd > 7 && (Rd != REG_SP || Rs != REG_SP))
|| (Rs > 7 && Rs != REG_SP && Rs != REG_PC),
BAD_HIREG);
inst.instruction = (inst.instruction == T_MNEM_add
? 0x0000 : 0x8000);
inst.instruction |= (Rd << 4) | Rs;
inst.reloc.type = BFD_RELOC_ARM_THUMB_ADD;
return;
}
Rn = inst.operands[2].reg;
constraint (inst.operands[2].shifted, _("unshifted register required"));
/* We now have Rd, Rs, and Rn set to registers. */
if (Rd > 7 || Rs > 7 || Rn > 7)
{
/* Can't do this for SUB. */
constraint (inst.instruction == T_MNEM_sub, BAD_HIREG);
inst.instruction = T_OPCODE_ADD_HI;
inst.instruction |= (Rd & 8) << 4;
inst.instruction |= (Rd & 7);
if (Rs == Rd)
inst.instruction |= Rn << 3;
else if (Rn == Rd)
inst.instruction |= Rs << 3;
else
constraint (1, _("dest must overlap one source register"));
}
else
{
inst.instruction = (inst.instruction == T_MNEM_add
? T_OPCODE_ADD_R3 : T_OPCODE_SUB_R3);
inst.instruction |= Rd | (Rs << 3) | (Rn << 6);
}
}
}
static void
do_t_adr (void)
{
unsigned Rd;
Rd = inst.operands[0].reg;
reject_bad_reg (Rd);
if (unified_syntax && inst.size_req == 0 && Rd <= 7)
{
/* Defer to section relaxation. */
inst.relax = inst.instruction;
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd << 4;
}
else if (unified_syntax && inst.size_req != 2)
{
/* Generate a 32-bit opcode. */
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.reloc.type = BFD_RELOC_ARM_T32_ADD_PC12;
inst.reloc.pc_rel = 1;
}
else
{
/* Generate a 16-bit opcode. */
inst.instruction = THUMB_OP16 (inst.instruction);
inst.reloc.type = BFD_RELOC_ARM_THUMB_ADD;
inst.reloc.exp.X_add_number -= 4; /* PC relative adjust. */
inst.reloc.pc_rel = 1;
inst.instruction |= Rd << 4;
}
}
/* Arithmetic instructions for which there is just one 16-bit
instruction encoding, and it allows only two low registers.
For maximal compatibility with ARM syntax, we allow three register
operands even when Thumb-32 instructions are not available, as long
as the first two are identical. For instance, both "sbc r0,r1" and
"sbc r0,r0,r1" are allowed. */
static void
do_t_arit3 (void)
{
int Rd, Rs, Rn;
Rd = inst.operands[0].reg;
Rs = (inst.operands[1].present
? inst.operands[1].reg /* Rd, Rs, foo */
: inst.operands[0].reg); /* Rd, foo -> Rd, Rd, foo */
Rn = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rs);
if (inst.operands[2].isreg)
reject_bad_reg (Rn);
if (unified_syntax)
{
if (!inst.operands[2].isreg)
{
/* For an immediate, we always generate a 32-bit opcode;
section relaxation will shrink it later if possible. */
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction = (inst.instruction & 0xe1ffffff) | 0x10000000;
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
else
{
bfd_boolean narrow;
/* See if we can do this with a 16-bit instruction. */
if (THUMB_SETS_FLAGS (inst.instruction))
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (Rd > 7 || Rn > 7 || Rs > 7)
narrow = FALSE;
if (inst.operands[2].shifted)
narrow = FALSE;
if (inst.size_req == 4)
narrow = FALSE;
if (narrow
&& Rd == Rs)
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
inst.instruction |= Rn << 3;
return;
}
/* If we get here, it can't be done in 16 bits. */
constraint (inst.operands[2].shifted
&& inst.operands[2].immisreg,
_("shift must be constant"));
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
encode_thumb32_shifted_operand (2);
}
}
else
{
/* On its face this is a lie - the instruction does set the
flags. However, the only supported mnemonic in this mode
says it doesn't. */
constraint (THUMB_SETS_FLAGS (inst.instruction), BAD_THUMB32);
constraint (!inst.operands[2].isreg || inst.operands[2].shifted,
_("unshifted register required"));
constraint (Rd > 7 || Rs > 7 || Rn > 7, BAD_HIREG);
constraint (Rd != Rs,
_("dest and source1 must be the same register"));
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
inst.instruction |= Rn << 3;
}
}
/* Similarly, but for instructions where the arithmetic operation is
commutative, so we can allow either of them to be different from
the destination operand in a 16-bit instruction. For instance, all
three of "adc r0,r1", "adc r0,r0,r1", and "adc r0,r1,r0" are
accepted. */
static void
do_t_arit3c (void)
{
int Rd, Rs, Rn;
Rd = inst.operands[0].reg;
Rs = (inst.operands[1].present
? inst.operands[1].reg /* Rd, Rs, foo */
: inst.operands[0].reg); /* Rd, foo -> Rd, Rd, foo */
Rn = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rs);
if (inst.operands[2].isreg)
reject_bad_reg (Rn);
if (unified_syntax)
{
if (!inst.operands[2].isreg)
{
/* For an immediate, we always generate a 32-bit opcode;
section relaxation will shrink it later if possible. */
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction = (inst.instruction & 0xe1ffffff) | 0x10000000;
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
else
{
bfd_boolean narrow;
/* See if we can do this with a 16-bit instruction. */
if (THUMB_SETS_FLAGS (inst.instruction))
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (Rd > 7 || Rn > 7 || Rs > 7)
narrow = FALSE;
if (inst.operands[2].shifted)
narrow = FALSE;
if (inst.size_req == 4)
narrow = FALSE;
if (narrow)
{
if (Rd == Rs)
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
inst.instruction |= Rn << 3;
return;
}
if (Rd == Rn)
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
inst.instruction |= Rs << 3;
return;
}
}
/* If we get here, it can't be done in 16 bits. */
constraint (inst.operands[2].shifted
&& inst.operands[2].immisreg,
_("shift must be constant"));
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
encode_thumb32_shifted_operand (2);
}
}
else
{
/* On its face this is a lie - the instruction does set the
flags. However, the only supported mnemonic in this mode
says it doesn't. */
constraint (THUMB_SETS_FLAGS (inst.instruction), BAD_THUMB32);
constraint (!inst.operands[2].isreg || inst.operands[2].shifted,
_("unshifted register required"));
constraint (Rd > 7 || Rs > 7 || Rn > 7, BAD_HIREG);
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
if (Rd == Rs)
inst.instruction |= Rn << 3;
else if (Rd == Rn)
inst.instruction |= Rs << 3;
else
constraint (1, _("dest must overlap one source register"));
}
}
static void
do_t_bfc (void)
{
unsigned Rd;
unsigned int msb = inst.operands[1].imm + inst.operands[2].imm;
constraint (msb > 32, _("bit-field extends past end of register"));
/* The instruction encoding stores the LSB and MSB,
not the LSB and width. */
Rd = inst.operands[0].reg;
reject_bad_reg (Rd);
inst.instruction |= Rd << 8;
inst.instruction |= (inst.operands[1].imm & 0x1c) << 10;
inst.instruction |= (inst.operands[1].imm & 0x03) << 6;
inst.instruction |= msb - 1;
}
static void
do_t_bfi (void)
{
int Rd, Rn;
unsigned int msb;
Rd = inst.operands[0].reg;
reject_bad_reg (Rd);
/* #0 in second position is alternative syntax for bfc, which is
the same instruction but with REG_PC in the Rm field. */
if (!inst.operands[1].isreg)
Rn = REG_PC;
else
{
Rn = inst.operands[1].reg;
reject_bad_reg (Rn);
}
msb = inst.operands[2].imm + inst.operands[3].imm;
constraint (msb > 32, _("bit-field extends past end of register"));
/* The instruction encoding stores the LSB and MSB,
not the LSB and width. */
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= (inst.operands[2].imm & 0x1c) << 10;
inst.instruction |= (inst.operands[2].imm & 0x03) << 6;
inst.instruction |= msb - 1;
}
static void
do_t_bfx (void)
{
unsigned Rd, Rn;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
constraint (inst.operands[2].imm + inst.operands[3].imm > 32,
_("bit-field extends past end of register"));
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= (inst.operands[2].imm & 0x1c) << 10;
inst.instruction |= (inst.operands[2].imm & 0x03) << 6;
inst.instruction |= inst.operands[3].imm - 1;
}
/* ARM V5 Thumb BLX (argument parse)
BLX <target_addr> which is BLX(1)
BLX <Rm> which is BLX(2)
Unfortunately, there are two different opcodes for this mnemonic.
So, the insns[].value is not used, and the code here zaps values
into inst.instruction.
??? How to take advantage of the additional two bits of displacement
available in Thumb32 mode? Need new relocation? */
static void
do_t_blx (void)
{
set_it_insn_type_last ();
if (inst.operands[0].isreg)
{
constraint (inst.operands[0].reg == REG_PC, BAD_PC);
/* We have a register, so this is BLX(2). */
inst.instruction |= inst.operands[0].reg << 3;
}
else
{
/* No register. This must be BLX(1). */
inst.instruction = 0xf000e800;
encode_branch (BFD_RELOC_THUMB_PCREL_BLX);
}
}
static void
do_t_branch (void)
{
int opcode;
int cond;
int reloc;
cond = inst.cond;
set_it_insn_type (IF_INSIDE_IT_LAST_INSN);
if (in_it_block ())
{
/* Conditional branches inside IT blocks are encoded as unconditional
branches. */
cond = COND_ALWAYS;
}
else
cond = inst.cond;
if (cond != COND_ALWAYS)
opcode = T_MNEM_bcond;
else
opcode = inst.instruction;
if (unified_syntax
&& (inst.size_req == 4
|| (inst.size_req != 2
&& (inst.operands[0].hasreloc
|| inst.reloc.exp.X_op == O_constant))))
{
inst.instruction = THUMB_OP32(opcode);
if (cond == COND_ALWAYS)
reloc = BFD_RELOC_THUMB_PCREL_BRANCH25;
else
{
gas_assert (cond != 0xF);
inst.instruction |= cond << 22;
reloc = BFD_RELOC_THUMB_PCREL_BRANCH20;
}
}
else
{
inst.instruction = THUMB_OP16(opcode);
if (cond == COND_ALWAYS)
reloc = BFD_RELOC_THUMB_PCREL_BRANCH12;
else
{
inst.instruction |= cond << 8;
reloc = BFD_RELOC_THUMB_PCREL_BRANCH9;
}
/* Allow section relaxation. */
if (unified_syntax && inst.size_req != 2)
inst.relax = opcode;
}
inst.reloc.type = reloc;
inst.reloc.pc_rel = 1;
}
/* Actually do the work for Thumb state bkpt and hlt. The only difference
between the two is the maximum immediate allowed - which is passed in
RANGE. */
static void
do_t_bkpt_hlt1 (int range)
{
constraint (inst.cond != COND_ALWAYS,
_("instruction is always unconditional"));
if (inst.operands[0].present)
{
constraint (inst.operands[0].imm > range,
_("immediate value out of range"));
inst.instruction |= inst.operands[0].imm;
}
set_it_insn_type (NEUTRAL_IT_INSN);
}
static void
do_t_hlt (void)
{
do_t_bkpt_hlt1 (63);
}
static void
do_t_bkpt (void)
{
do_t_bkpt_hlt1 (255);
}
static void
do_t_branch23 (void)
{
set_it_insn_type_last ();
encode_branch (BFD_RELOC_THUMB_PCREL_BRANCH23);
/* md_apply_fix blows up with 'bl foo(PLT)' where foo is defined in
this file. We used to simply ignore the PLT reloc type here --
the branch encoding is now needed to deal with TLSCALL relocs.
So if we see a PLT reloc now, put it back to how it used to be to
keep the preexisting behaviour. */
if (inst.reloc.type == BFD_RELOC_ARM_PLT32)
inst.reloc.type = BFD_RELOC_THUMB_PCREL_BRANCH23;
#if defined(OBJ_COFF)
/* If the destination of the branch is a defined symbol which does not have
the THUMB_FUNC attribute, then we must be calling a function which has
the (interfacearm) attribute. We look for the Thumb entry point to that
function and change the branch to refer to that function instead. */
if ( inst.reloc.exp.X_op == O_symbol
&& inst.reloc.exp.X_add_symbol != NULL
&& S_IS_DEFINED (inst.reloc.exp.X_add_symbol)
&& ! THUMB_IS_FUNC (inst.reloc.exp.X_add_symbol))
inst.reloc.exp.X_add_symbol =
find_real_start (inst.reloc.exp.X_add_symbol);
#endif
}
static void
do_t_bx (void)
{
set_it_insn_type_last ();
inst.instruction |= inst.operands[0].reg << 3;
/* ??? FIXME: Should add a hacky reloc here if reg is REG_PC. The reloc
should cause the alignment to be checked once it is known. This is
because BX PC only works if the instruction is word aligned. */
}
static void
do_t_bxj (void)
{
int Rm;
set_it_insn_type_last ();
Rm = inst.operands[0].reg;
reject_bad_reg (Rm);
inst.instruction |= Rm << 16;
}
static void
do_t_clz (void)
{
unsigned Rd;
unsigned Rm;
Rd = inst.operands[0].reg;
Rm = inst.operands[1].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rm << 16;
inst.instruction |= Rm;
}
static void
do_t_cps (void)
{
set_it_insn_type (OUTSIDE_IT_INSN);
inst.instruction |= inst.operands[0].imm;
}
static void
do_t_cpsi (void)
{
set_it_insn_type (OUTSIDE_IT_INSN);
if (unified_syntax
&& (inst.operands[1].present || inst.size_req == 4)
&& ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v6_notm))
{
unsigned int imod = (inst.instruction & 0x0030) >> 4;
inst.instruction = 0xf3af8000;
inst.instruction |= imod << 9;
inst.instruction |= inst.operands[0].imm << 5;
if (inst.operands[1].present)
inst.instruction |= 0x100 | inst.operands[1].imm;
}
else
{
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v1)
&& (inst.operands[0].imm & 4),
_("selected processor does not support 'A' form "
"of this instruction"));
constraint (inst.operands[1].present || inst.size_req == 4,
_("Thumb does not support the 2-argument "
"form of this instruction"));
inst.instruction |= inst.operands[0].imm;
}
}
/* THUMB CPY instruction (argument parse). */
static void
do_t_cpy (void)
{
if (inst.size_req == 4)
{
inst.instruction = THUMB_OP32 (T_MNEM_mov);
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].reg;
}
else
{
inst.instruction |= (inst.operands[0].reg & 0x8) << 4;
inst.instruction |= (inst.operands[0].reg & 0x7);
inst.instruction |= inst.operands[1].reg << 3;
}
}
static void
do_t_cbz (void)
{
set_it_insn_type (OUTSIDE_IT_INSN);
constraint (inst.operands[0].reg > 7, BAD_HIREG);
inst.instruction |= inst.operands[0].reg;
inst.reloc.pc_rel = 1;
inst.reloc.type = BFD_RELOC_THUMB_PCREL_BRANCH7;
}
static void
do_t_dbg (void)
{
inst.instruction |= inst.operands[0].imm;
}
static void
do_t_div (void)
{
unsigned Rd, Rn, Rm;
Rd = inst.operands[0].reg;
Rn = (inst.operands[1].present
? inst.operands[1].reg : Rd);
Rm = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
}
static void
do_t_hint (void)
{
if (unified_syntax && inst.size_req == 4)
inst.instruction = THUMB_OP32 (inst.instruction);
else
inst.instruction = THUMB_OP16 (inst.instruction);
}
static void
do_t_it (void)
{
unsigned int cond = inst.operands[0].imm;
set_it_insn_type (IT_INSN);
now_it.mask = (inst.instruction & 0xf) | 0x10;
now_it.cc = cond;
now_it.warn_deprecated = FALSE;
/* If the condition is a negative condition, invert the mask. */
if ((cond & 0x1) == 0x0)
{
unsigned int mask = inst.instruction & 0x000f;
if ((mask & 0x7) == 0)
{
/* No conversion needed. */
now_it.block_length = 1;
}
else if ((mask & 0x3) == 0)
{
mask ^= 0x8;
now_it.block_length = 2;
}
else if ((mask & 0x1) == 0)
{
mask ^= 0xC;
now_it.block_length = 3;
}
else
{
mask ^= 0xE;
now_it.block_length = 4;
}
inst.instruction &= 0xfff0;
inst.instruction |= mask;
}
inst.instruction |= cond << 4;
}
/* Helper function used for both push/pop and ldm/stm. */
static void
encode_thumb2_ldmstm (int base, unsigned mask, bfd_boolean writeback)
{
bfd_boolean load;
load = (inst.instruction & (1 << 20)) != 0;
if (mask & (1 << 13))
inst.error = _("SP not allowed in register list");
if ((mask & (1 << base)) != 0
&& writeback)
inst.error = _("having the base register in the register list when "
"using write back is UNPREDICTABLE");
if (load)
{
if (mask & (1 << 15))
{
if (mask & (1 << 14))
inst.error = _("LR and PC should not both be in register list");
else
set_it_insn_type_last ();
}
}
else
{
if (mask & (1 << 15))
inst.error = _("PC not allowed in register list");
}
if ((mask & (mask - 1)) == 0)
{
/* Single register transfers implemented as str/ldr. */
if (writeback)
{
if (inst.instruction & (1 << 23))
inst.instruction = 0x00000b04; /* ia! -> [base], #4 */
else
inst.instruction = 0x00000d04; /* db! -> [base, #-4]! */
}
else
{
if (inst.instruction & (1 << 23))
inst.instruction = 0x00800000; /* ia -> [base] */
else
inst.instruction = 0x00000c04; /* db -> [base, #-4] */
}
inst.instruction |= 0xf8400000;
if (load)
inst.instruction |= 0x00100000;
mask = ffs (mask) - 1;
mask <<= 12;
}
else if (writeback)
inst.instruction |= WRITE_BACK;
inst.instruction |= mask;
inst.instruction |= base << 16;
}
static void
do_t_ldmstm (void)
{
/* This really doesn't seem worth it. */
constraint (inst.reloc.type != BFD_RELOC_UNUSED,
_("expression too complex"));
constraint (inst.operands[1].writeback,
_("Thumb load/store multiple does not support {reglist}^"));
if (unified_syntax)
{
bfd_boolean narrow;
unsigned mask;
narrow = FALSE;
/* See if we can use a 16-bit instruction. */
if (inst.instruction < 0xffff /* not ldmdb/stmdb */
&& inst.size_req != 4
&& !(inst.operands[1].imm & ~0xff))
{
mask = 1 << inst.operands[0].reg;
if (inst.operands[0].reg <= 7)
{
if (inst.instruction == T_MNEM_stmia
? inst.operands[0].writeback
: (inst.operands[0].writeback
== !(inst.operands[1].imm & mask)))
{
if (inst.instruction == T_MNEM_stmia
&& (inst.operands[1].imm & mask)
&& (inst.operands[1].imm & (mask - 1)))
as_warn (_("value stored for r%d is UNKNOWN"),
inst.operands[0].reg);
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].imm;
narrow = TRUE;
}
else if ((inst.operands[1].imm & (inst.operands[1].imm-1)) == 0)
{
/* This means 1 register in reg list one of 3 situations:
1. Instruction is stmia, but without writeback.
2. lmdia without writeback, but with Rn not in
reglist.
3. ldmia with writeback, but with Rn in reglist.
Case 3 is UNPREDICTABLE behaviour, so we handle
case 1 and 2 which can be converted into a 16-bit
str or ldr. The SP cases are handled below. */
unsigned long opcode;
/* First, record an error for Case 3. */
if (inst.operands[1].imm & mask
&& inst.operands[0].writeback)
inst.error =
_("having the base register in the register list when "
"using write back is UNPREDICTABLE");
opcode = (inst.instruction == T_MNEM_stmia ? T_MNEM_str
: T_MNEM_ldr);
inst.instruction = THUMB_OP16 (opcode);
inst.instruction |= inst.operands[0].reg << 3;
inst.instruction |= (ffs (inst.operands[1].imm)-1);
narrow = TRUE;
}
}
else if (inst.operands[0] .reg == REG_SP)
{
if (inst.operands[0].writeback)
{
inst.instruction =
THUMB_OP16 (inst.instruction == T_MNEM_stmia
? T_MNEM_push : T_MNEM_pop);
inst.instruction |= inst.operands[1].imm;
narrow = TRUE;
}
else if ((inst.operands[1].imm & (inst.operands[1].imm-1)) == 0)
{
inst.instruction =
THUMB_OP16 (inst.instruction == T_MNEM_stmia
? T_MNEM_str_sp : T_MNEM_ldr_sp);
inst.instruction |= ((ffs (inst.operands[1].imm)-1) << 8);
narrow = TRUE;
}
}
}
if (!narrow)
{
if (inst.instruction < 0xffff)
inst.instruction = THUMB_OP32 (inst.instruction);
encode_thumb2_ldmstm (inst.operands[0].reg, inst.operands[1].imm,
inst.operands[0].writeback);
}
}
else
{
constraint (inst.operands[0].reg > 7
|| (inst.operands[1].imm & ~0xff), BAD_HIREG);
constraint (inst.instruction != T_MNEM_ldmia
&& inst.instruction != T_MNEM_stmia,
_("Thumb-2 instruction only valid in unified syntax"));
if (inst.instruction == T_MNEM_stmia)
{
if (!inst.operands[0].writeback)
as_warn (_("this instruction will write back the base register"));
if ((inst.operands[1].imm & (1 << inst.operands[0].reg))
&& (inst.operands[1].imm & ((1 << inst.operands[0].reg) - 1)))
as_warn (_("value stored for r%d is UNKNOWN"),
inst.operands[0].reg);
}
else
{
if (!inst.operands[0].writeback
&& !(inst.operands[1].imm & (1 << inst.operands[0].reg)))
as_warn (_("this instruction will write back the base register"));
else if (inst.operands[0].writeback
&& (inst.operands[1].imm & (1 << inst.operands[0].reg)))
as_warn (_("this instruction will not write back the base register"));
}
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].imm;
}
}
static void
do_t_ldrex (void)
{
constraint (!inst.operands[1].isreg || !inst.operands[1].preind
|| inst.operands[1].postind || inst.operands[1].writeback
|| inst.operands[1].immisreg || inst.operands[1].shifted
|| inst.operands[1].negative,
BAD_ADDR_MODE);
constraint ((inst.operands[1].reg == REG_PC), BAD_PC);
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.reloc.type = BFD_RELOC_ARM_T32_OFFSET_U8;
}
static void
do_t_ldrexd (void)
{
if (!inst.operands[1].present)
{
constraint (inst.operands[0].reg == REG_LR,
_("r14 not allowed as first register "
"when second register is omitted"));
inst.operands[1].reg = inst.operands[0].reg + 1;
}
constraint (inst.operands[0].reg == inst.operands[1].reg,
BAD_OVERLAP);
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 8;
inst.instruction |= inst.operands[2].reg << 16;
}
static void
do_t_ldst (void)
{
unsigned long opcode;
int Rn;
if (inst.operands[0].isreg
&& !inst.operands[0].preind
&& inst.operands[0].reg == REG_PC)
set_it_insn_type_last ();
opcode = inst.instruction;
if (unified_syntax)
{
if (!inst.operands[1].isreg)
{
if (opcode <= 0xffff)
inst.instruction = THUMB_OP32 (opcode);
if (move_or_literal_pool (0, CONST_THUMB, /*mode_3=*/FALSE))
return;
}
if (inst.operands[1].isreg
&& !inst.operands[1].writeback
&& !inst.operands[1].shifted && !inst.operands[1].postind
&& !inst.operands[1].negative && inst.operands[0].reg <= 7
&& opcode <= 0xffff
&& inst.size_req != 4)
{
/* Insn may have a 16-bit form. */
Rn = inst.operands[1].reg;
if (inst.operands[1].immisreg)
{
inst.instruction = THUMB_OP16 (opcode);
/* [Rn, Rik] */
if (Rn <= 7 && inst.operands[1].imm <= 7)
goto op16;
else if (opcode != T_MNEM_ldr && opcode != T_MNEM_str)
reject_bad_reg (inst.operands[1].imm);
}
else if ((Rn <= 7 && opcode != T_MNEM_ldrsh
&& opcode != T_MNEM_ldrsb)
|| ((Rn == REG_PC || Rn == REG_SP) && opcode == T_MNEM_ldr)
|| (Rn == REG_SP && opcode == T_MNEM_str))
{
/* [Rn, #const] */
if (Rn > 7)
{
if (Rn == REG_PC)
{
if (inst.reloc.pc_rel)
opcode = T_MNEM_ldr_pc2;
else
opcode = T_MNEM_ldr_pc;
}
else
{
if (opcode == T_MNEM_ldr)
opcode = T_MNEM_ldr_sp;
else
opcode = T_MNEM_str_sp;
}
inst.instruction = inst.operands[0].reg << 8;
}
else
{
inst.instruction = inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
}
inst.instruction |= THUMB_OP16 (opcode);
if (inst.size_req == 2)
inst.reloc.type = BFD_RELOC_ARM_THUMB_OFFSET;
else
inst.relax = opcode;
return;
}
}
/* Definitely a 32-bit variant. */
/* Warning for Erratum 752419. */
if (opcode == T_MNEM_ldr
&& inst.operands[0].reg == REG_SP
&& inst.operands[1].writeback == 1
&& !inst.operands[1].immisreg)
{
if (no_cpu_selected ()
|| (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v7)
&& !ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v7a)
&& !ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v7r)))
as_warn (_("This instruction may be unpredictable "
"if executed on M-profile cores "
"with interrupts enabled."));
}
/* Do some validations regarding addressing modes. */
if (inst.operands[1].immisreg)
reject_bad_reg (inst.operands[1].imm);
constraint (inst.operands[1].writeback == 1
&& inst.operands[0].reg == inst.operands[1].reg,
BAD_OVERLAP);
inst.instruction = THUMB_OP32 (opcode);
inst.instruction |= inst.operands[0].reg << 12;
encode_thumb32_addr_mode (1, /*is_t=*/FALSE, /*is_d=*/FALSE);
check_ldr_r15_aligned ();
return;
}
constraint (inst.operands[0].reg > 7, BAD_HIREG);
if (inst.instruction == T_MNEM_ldrsh || inst.instruction == T_MNEM_ldrsb)
{
/* Only [Rn,Rm] is acceptable. */
constraint (inst.operands[1].reg > 7 || inst.operands[1].imm > 7, BAD_HIREG);
constraint (!inst.operands[1].isreg || !inst.operands[1].immisreg
|| inst.operands[1].postind || inst.operands[1].shifted
|| inst.operands[1].negative,
_("Thumb does not support this addressing mode"));
inst.instruction = THUMB_OP16 (inst.instruction);
goto op16;
}
inst.instruction = THUMB_OP16 (inst.instruction);
if (!inst.operands[1].isreg)
if (move_or_literal_pool (0, CONST_THUMB, /*mode_3=*/FALSE))
return;
constraint (!inst.operands[1].preind
|| inst.operands[1].shifted
|| inst.operands[1].writeback,
_("Thumb does not support this addressing mode"));
if (inst.operands[1].reg == REG_PC || inst.operands[1].reg == REG_SP)
{
constraint (inst.instruction & 0x0600,
_("byte or halfword not valid for base register"));
constraint (inst.operands[1].reg == REG_PC
&& !(inst.instruction & THUMB_LOAD_BIT),
_("r15 based store not allowed"));
constraint (inst.operands[1].immisreg,
_("invalid base register for register offset"));
if (inst.operands[1].reg == REG_PC)
inst.instruction = T_OPCODE_LDR_PC;
else if (inst.instruction & THUMB_LOAD_BIT)
inst.instruction = T_OPCODE_LDR_SP;
else
inst.instruction = T_OPCODE_STR_SP;
inst.instruction |= inst.operands[0].reg << 8;
inst.reloc.type = BFD_RELOC_ARM_THUMB_OFFSET;
return;
}
constraint (inst.operands[1].reg > 7, BAD_HIREG);
if (!inst.operands[1].immisreg)
{
/* Immediate offset. */
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
inst.reloc.type = BFD_RELOC_ARM_THUMB_OFFSET;
return;
}
/* Register offset. */
constraint (inst.operands[1].imm > 7, BAD_HIREG);
constraint (inst.operands[1].negative,
_("Thumb does not support this addressing mode"));
op16:
switch (inst.instruction)
{
case T_OPCODE_STR_IW: inst.instruction = T_OPCODE_STR_RW; break;
case T_OPCODE_STR_IH: inst.instruction = T_OPCODE_STR_RH; break;
case T_OPCODE_STR_IB: inst.instruction = T_OPCODE_STR_RB; break;
case T_OPCODE_LDR_IW: inst.instruction = T_OPCODE_LDR_RW; break;
case T_OPCODE_LDR_IH: inst.instruction = T_OPCODE_LDR_RH; break;
case T_OPCODE_LDR_IB: inst.instruction = T_OPCODE_LDR_RB; break;
case 0x5600 /* ldrsb */:
case 0x5e00 /* ldrsh */: break;
default: abort ();
}
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
inst.instruction |= inst.operands[1].imm << 6;
}
static void
do_t_ldstd (void)
{
if (!inst.operands[1].present)
{
inst.operands[1].reg = inst.operands[0].reg + 1;
constraint (inst.operands[0].reg == REG_LR,
_("r14 not allowed here"));
constraint (inst.operands[0].reg == REG_R12,
_("r12 not allowed here"));
}
if (inst.operands[2].writeback
&& (inst.operands[0].reg == inst.operands[2].reg
|| inst.operands[1].reg == inst.operands[2].reg))
as_warn (_("base register written back, and overlaps "
"one of transfer registers"));
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 8;
encode_thumb32_addr_mode (2, /*is_t=*/FALSE, /*is_d=*/TRUE);
}
static void
do_t_ldstt (void)
{
inst.instruction |= inst.operands[0].reg << 12;
encode_thumb32_addr_mode (1, /*is_t=*/TRUE, /*is_d=*/FALSE);
}
static void
do_t_mla (void)
{
unsigned Rd, Rn, Rm, Ra;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
Rm = inst.operands[2].reg;
Ra = inst.operands[3].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
reject_bad_reg (Ra);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
inst.instruction |= Ra << 12;
}
static void
do_t_mlal (void)
{
unsigned RdLo, RdHi, Rn, Rm;
RdLo = inst.operands[0].reg;
RdHi = inst.operands[1].reg;
Rn = inst.operands[2].reg;
Rm = inst.operands[3].reg;
reject_bad_reg (RdLo);
reject_bad_reg (RdHi);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= RdLo << 12;
inst.instruction |= RdHi << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
}
static void
do_t_mov_cmp (void)
{
unsigned Rn, Rm;
Rn = inst.operands[0].reg;
Rm = inst.operands[1].reg;
if (Rn == REG_PC)
set_it_insn_type_last ();
if (unified_syntax)
{
int r0off = (inst.instruction == T_MNEM_mov
|| inst.instruction == T_MNEM_movs) ? 8 : 16;
unsigned long opcode;
bfd_boolean narrow;
bfd_boolean low_regs;
low_regs = (Rn <= 7 && Rm <= 7);
opcode = inst.instruction;
if (in_it_block ())
narrow = opcode != T_MNEM_movs;
else
narrow = opcode != T_MNEM_movs || low_regs;
if (inst.size_req == 4
|| inst.operands[1].shifted)
narrow = FALSE;
/* MOVS PC, LR is encoded as SUBS PC, LR, #0. */
if (opcode == T_MNEM_movs && inst.operands[1].isreg
&& !inst.operands[1].shifted
&& Rn == REG_PC
&& Rm == REG_LR)
{
inst.instruction = T2_SUBS_PC_LR;
return;
}
if (opcode == T_MNEM_cmp)
{
constraint (Rn == REG_PC, BAD_PC);
if (narrow)
{
/* In the Thumb-2 ISA, use of R13 as Rm is deprecated,
but valid. */
warn_deprecated_sp (Rm);
/* R15 was documented as a valid choice for Rm in ARMv6,
but as UNPREDICTABLE in ARMv7. ARM's proprietary
tools reject R15, so we do too. */
constraint (Rm == REG_PC, BAD_PC);
}
else
reject_bad_reg (Rm);
}
else if (opcode == T_MNEM_mov
|| opcode == T_MNEM_movs)
{
if (inst.operands[1].isreg)
{
if (opcode == T_MNEM_movs)
{
reject_bad_reg (Rn);
reject_bad_reg (Rm);
}
else if (narrow)
{
/* This is mov.n. */
if ((Rn == REG_SP || Rn == REG_PC)
&& (Rm == REG_SP || Rm == REG_PC))
{
as_tsktsk (_("Use of r%u as a source register is "
"deprecated when r%u is the destination "
"register."), Rm, Rn);
}
}
else
{
/* This is mov.w. */
constraint (Rn == REG_PC, BAD_PC);
constraint (Rm == REG_PC, BAD_PC);
constraint (Rn == REG_SP && Rm == REG_SP, BAD_SP);
}
}
else
reject_bad_reg (Rn);
}
if (!inst.operands[1].isreg)
{
/* Immediate operand. */
if (!in_it_block () && opcode == T_MNEM_mov)
narrow = 0;
if (low_regs && narrow)
{
inst.instruction = THUMB_OP16 (opcode);
inst.instruction |= Rn << 8;
if (inst.size_req == 2)
inst.reloc.type = BFD_RELOC_ARM_THUMB_IMM;
else
inst.relax = opcode;
}
else
{
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction = (inst.instruction & 0xe1ffffff) | 0x10000000;
inst.instruction |= Rn << r0off;
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
}
else if (inst.operands[1].shifted && inst.operands[1].immisreg
&& (inst.instruction == T_MNEM_mov
|| inst.instruction == T_MNEM_movs))
{
/* Register shifts are encoded as separate shift instructions. */
bfd_boolean flags = (inst.instruction == T_MNEM_movs);
if (in_it_block ())
narrow = !flags;
else
narrow = flags;
if (inst.size_req == 4)
narrow = FALSE;
if (!low_regs || inst.operands[1].imm > 7)
narrow = FALSE;
if (Rn != Rm)
narrow = FALSE;
switch (inst.operands[1].shift_kind)
{
case SHIFT_LSL:
opcode = narrow ? T_OPCODE_LSL_R : THUMB_OP32 (T_MNEM_lsl);
break;
case SHIFT_ASR:
opcode = narrow ? T_OPCODE_ASR_R : THUMB_OP32 (T_MNEM_asr);
break;
case SHIFT_LSR:
opcode = narrow ? T_OPCODE_LSR_R : THUMB_OP32 (T_MNEM_lsr);
break;
case SHIFT_ROR:
opcode = narrow ? T_OPCODE_ROR_R : THUMB_OP32 (T_MNEM_ror);
break;
default:
abort ();
}
inst.instruction = opcode;
if (narrow)
{
inst.instruction |= Rn;
inst.instruction |= inst.operands[1].imm << 3;
}
else
{
if (flags)
inst.instruction |= CONDS_BIT;
inst.instruction |= Rn << 8;
inst.instruction |= Rm << 16;
inst.instruction |= inst.operands[1].imm;
}
}
else if (!narrow)
{
/* Some mov with immediate shift have narrow variants.
Register shifts are handled above. */
if (low_regs && inst.operands[1].shifted
&& (inst.instruction == T_MNEM_mov
|| inst.instruction == T_MNEM_movs))
{
if (in_it_block ())
narrow = (inst.instruction == T_MNEM_mov);
else
narrow = (inst.instruction == T_MNEM_movs);
}
if (narrow)
{
switch (inst.operands[1].shift_kind)
{
case SHIFT_LSL: inst.instruction = T_OPCODE_LSL_I; break;
case SHIFT_LSR: inst.instruction = T_OPCODE_LSR_I; break;
case SHIFT_ASR: inst.instruction = T_OPCODE_ASR_I; break;
default: narrow = FALSE; break;
}
}
if (narrow)
{
inst.instruction |= Rn;
inst.instruction |= Rm << 3;
inst.reloc.type = BFD_RELOC_ARM_THUMB_SHIFT;
}
else
{
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rn << r0off;
encode_thumb32_shifted_operand (1);
}
}
else
switch (inst.instruction)
{
case T_MNEM_mov:
/* In v4t or v5t a move of two lowregs produces unpredictable
results. Don't allow this. */
if (low_regs)
{
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v6),
"MOV Rd, Rs with two low registers is not "
"permitted on this architecture");
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used,
arm_ext_v6);
}
inst.instruction = T_OPCODE_MOV_HR;
inst.instruction |= (Rn & 0x8) << 4;
inst.instruction |= (Rn & 0x7);
inst.instruction |= Rm << 3;
break;
case T_MNEM_movs:
/* We know we have low registers at this point.
Generate LSLS Rd, Rs, #0. */
inst.instruction = T_OPCODE_LSL_I;
inst.instruction |= Rn;
inst.instruction |= Rm << 3;
break;
case T_MNEM_cmp:
if (low_regs)
{
inst.instruction = T_OPCODE_CMP_LR;
inst.instruction |= Rn;
inst.instruction |= Rm << 3;
}
else
{
inst.instruction = T_OPCODE_CMP_HR;
inst.instruction |= (Rn & 0x8) << 4;
inst.instruction |= (Rn & 0x7);
inst.instruction |= Rm << 3;
}
break;
}
return;
}
inst.instruction = THUMB_OP16 (inst.instruction);
/* PR 10443: Do not silently ignore shifted operands. */
constraint (inst.operands[1].shifted,
_("shifts in CMP/MOV instructions are only supported in unified syntax"));
if (inst.operands[1].isreg)
{
if (Rn < 8 && Rm < 8)
{
/* A move of two lowregs is encoded as ADD Rd, Rs, #0
since a MOV instruction produces unpredictable results. */
if (inst.instruction == T_OPCODE_MOV_I8)
inst.instruction = T_OPCODE_ADD_I3;
else
inst.instruction = T_OPCODE_CMP_LR;
inst.instruction |= Rn;
inst.instruction |= Rm << 3;
}
else
{
if (inst.instruction == T_OPCODE_MOV_I8)
inst.instruction = T_OPCODE_MOV_HR;
else
inst.instruction = T_OPCODE_CMP_HR;
do_t_cpy ();
}
}
else
{
constraint (Rn > 7,
_("only lo regs allowed with immediate"));
inst.instruction |= Rn << 8;
inst.reloc.type = BFD_RELOC_ARM_THUMB_IMM;
}
}
static void
do_t_mov16 (void)
{
unsigned Rd;
bfd_vma imm;
bfd_boolean top;
top = (inst.instruction & 0x00800000) != 0;
if (inst.reloc.type == BFD_RELOC_ARM_MOVW)
{
constraint (top, _(":lower16: not allowed this instruction"));
inst.reloc.type = BFD_RELOC_ARM_THUMB_MOVW;
}
else if (inst.reloc.type == BFD_RELOC_ARM_MOVT)
{
constraint (!top, _(":upper16: not allowed this instruction"));
inst.reloc.type = BFD_RELOC_ARM_THUMB_MOVT;
}
Rd = inst.operands[0].reg;
reject_bad_reg (Rd);
inst.instruction |= Rd << 8;
if (inst.reloc.type == BFD_RELOC_UNUSED)
{
imm = inst.reloc.exp.X_add_number;
inst.instruction |= (imm & 0xf000) << 4;
inst.instruction |= (imm & 0x0800) << 15;
inst.instruction |= (imm & 0x0700) << 4;
inst.instruction |= (imm & 0x00ff);
}
}
static void
do_t_mvn_tst (void)
{
unsigned Rn, Rm;
Rn = inst.operands[0].reg;
Rm = inst.operands[1].reg;
if (inst.instruction == T_MNEM_cmp
|| inst.instruction == T_MNEM_cmn)
constraint (Rn == REG_PC, BAD_PC);
else
reject_bad_reg (Rn);
reject_bad_reg (Rm);
if (unified_syntax)
{
int r0off = (inst.instruction == T_MNEM_mvn
|| inst.instruction == T_MNEM_mvns) ? 8 : 16;
bfd_boolean narrow;
if (inst.size_req == 4
|| inst.instruction > 0xffff
|| inst.operands[1].shifted
|| Rn > 7 || Rm > 7)
narrow = FALSE;
else if (inst.instruction == T_MNEM_cmn
|| inst.instruction == T_MNEM_tst)
narrow = TRUE;
else if (THUMB_SETS_FLAGS (inst.instruction))
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (!inst.operands[1].isreg)
{
/* For an immediate, we always generate a 32-bit opcode;
section relaxation will shrink it later if possible. */
if (inst.instruction < 0xffff)
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction = (inst.instruction & 0xe1ffffff) | 0x10000000;
inst.instruction |= Rn << r0off;
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
else
{
/* See if we can do this with a 16-bit instruction. */
if (narrow)
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rn;
inst.instruction |= Rm << 3;
}
else
{
constraint (inst.operands[1].shifted
&& inst.operands[1].immisreg,
_("shift must be constant"));
if (inst.instruction < 0xffff)
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rn << r0off;
encode_thumb32_shifted_operand (1);
}
}
}
else
{
constraint (inst.instruction > 0xffff
|| inst.instruction == T_MNEM_mvns, BAD_THUMB32);
constraint (!inst.operands[1].isreg || inst.operands[1].shifted,
_("unshifted register required"));
constraint (Rn > 7 || Rm > 7,
BAD_HIREG);
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rn;
inst.instruction |= Rm << 3;
}
}
static void
do_t_mrs (void)
{
unsigned Rd;
if (do_vfp_nsyn_mrs () == SUCCESS)
return;
Rd = inst.operands[0].reg;
reject_bad_reg (Rd);
inst.instruction |= Rd << 8;
if (inst.operands[1].isreg)
{
unsigned br = inst.operands[1].reg;
if (((br & 0x200) == 0) && ((br & 0xf000) != 0xf000))
as_bad (_("bad register for mrs"));
inst.instruction |= br & (0xf << 16);
inst.instruction |= (br & 0x300) >> 4;
inst.instruction |= (br & SPSR_BIT) >> 2;
}
else
{
int flags = inst.operands[1].imm & (PSR_c|PSR_x|PSR_s|PSR_f|SPSR_BIT);
if (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_m))
{
/* PR gas/12698: The constraint is only applied for m_profile.
If the user has specified -march=all, we want to ignore it as
we are building for any CPU type, including non-m variants. */
bfd_boolean m_profile = selected_cpu.core != arm_arch_any.core;
constraint ((flags != 0) && m_profile, _("selected processor does "
"not support requested special purpose register"));
}
else
/* mrs only accepts APSR/CPSR/SPSR/CPSR_all/SPSR_all (for non-M profile
devices). */
constraint ((flags & ~SPSR_BIT) != (PSR_c|PSR_f),
_("'APSR', 'CPSR' or 'SPSR' expected"));
inst.instruction |= (flags & SPSR_BIT) >> 2;
inst.instruction |= inst.operands[1].imm & 0xff;
inst.instruction |= 0xf0000;
}
}
static void
do_t_msr (void)
{
int flags;
unsigned Rn;
if (do_vfp_nsyn_msr () == SUCCESS)
return;
constraint (!inst.operands[1].isreg,
_("Thumb encoding does not support an immediate here"));
if (inst.operands[0].isreg)
flags = (int)(inst.operands[0].reg);
else
flags = inst.operands[0].imm;
if (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_m))
{
int bits = inst.operands[0].imm & (PSR_c|PSR_x|PSR_s|PSR_f|SPSR_BIT);
/* PR gas/12698: The constraint is only applied for m_profile.
If the user has specified -march=all, we want to ignore it as
we are building for any CPU type, including non-m variants. */
bfd_boolean m_profile = selected_cpu.core != arm_arch_any.core;
constraint (((ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6_dsp)
&& (bits & ~(PSR_s | PSR_f)) != 0)
|| (!ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6_dsp)
&& bits != PSR_f)) && m_profile,
_("selected processor does not support requested special "
"purpose register"));
}
else
constraint ((flags & 0xff) != 0, _("selected processor does not support "
"requested special purpose register"));
Rn = inst.operands[1].reg;
reject_bad_reg (Rn);
inst.instruction |= (flags & SPSR_BIT) >> 2;
inst.instruction |= (flags & 0xf0000) >> 8;
inst.instruction |= (flags & 0x300) >> 4;
inst.instruction |= (flags & 0xff);
inst.instruction |= Rn << 16;
}
static void
do_t_mul (void)
{
bfd_boolean narrow;
unsigned Rd, Rn, Rm;
if (!inst.operands[2].present)
inst.operands[2].reg = inst.operands[0].reg;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
Rm = inst.operands[2].reg;
if (unified_syntax)
{
if (inst.size_req == 4
|| (Rd != Rn
&& Rd != Rm)
|| Rn > 7
|| Rm > 7)
narrow = FALSE;
else if (inst.instruction == T_MNEM_muls)
narrow = !in_it_block ();
else
narrow = in_it_block ();
}
else
{
constraint (inst.instruction == T_MNEM_muls, BAD_THUMB32);
constraint (Rn > 7 || Rm > 7,
BAD_HIREG);
narrow = TRUE;
}
if (narrow)
{
/* 16-bit MULS/Conditional MUL. */
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
if (Rd == Rn)
inst.instruction |= Rm << 3;
else if (Rd == Rm)
inst.instruction |= Rn << 3;
else
constraint (1, _("dest must overlap one source register"));
}
else
{
constraint (inst.instruction != T_MNEM_mul,
_("Thumb-2 MUL must not set flags"));
/* 32-bit MUL. */
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm << 0;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
}
}
static void
do_t_mull (void)
{
unsigned RdLo, RdHi, Rn, Rm;
RdLo = inst.operands[0].reg;
RdHi = inst.operands[1].reg;
Rn = inst.operands[2].reg;
Rm = inst.operands[3].reg;
reject_bad_reg (RdLo);
reject_bad_reg (RdHi);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= RdLo << 12;
inst.instruction |= RdHi << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
if (RdLo == RdHi)
as_tsktsk (_("rdhi and rdlo must be different"));
}
static void
do_t_nop (void)
{
set_it_insn_type (NEUTRAL_IT_INSN);
if (unified_syntax)
{
if (inst.size_req == 4 || inst.operands[0].imm > 15)
{
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= inst.operands[0].imm;
}
else
{
/* PR9722: Check for Thumb2 availability before
generating a thumb2 nop instruction. */
if (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v6t2))
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= inst.operands[0].imm << 4;
}
else
inst.instruction = 0x46c0;
}
}
else
{
constraint (inst.operands[0].present,
_("Thumb does not support NOP with hints"));
inst.instruction = 0x46c0;
}
}
static void
do_t_neg (void)
{
if (unified_syntax)
{
bfd_boolean narrow;
if (THUMB_SETS_FLAGS (inst.instruction))
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (inst.operands[0].reg > 7 || inst.operands[1].reg > 7)
narrow = FALSE;
if (inst.size_req == 4)
narrow = FALSE;
if (!narrow)
{
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].reg << 16;
}
else
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
}
}
else
{
constraint (inst.operands[0].reg > 7 || inst.operands[1].reg > 7,
BAD_HIREG);
constraint (THUMB_SETS_FLAGS (inst.instruction), BAD_THUMB32);
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
}
}
static void
do_t_orn (void)
{
unsigned Rd, Rn;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].present ? inst.operands[1].reg : Rd;
reject_bad_reg (Rd);
/* Rn == REG_SP is unpredictable; Rn == REG_PC is MVN. */
reject_bad_reg (Rn);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
if (!inst.operands[2].isreg)
{
inst.instruction = (inst.instruction & 0xe1ffffff) | 0x10000000;
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
else
{
unsigned Rm;
Rm = inst.operands[2].reg;
reject_bad_reg (Rm);
constraint (inst.operands[2].shifted
&& inst.operands[2].immisreg,
_("shift must be constant"));
encode_thumb32_shifted_operand (2);
}
}
static void
do_t_pkhbt (void)
{
unsigned Rd, Rn, Rm;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
Rm = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
if (inst.operands[3].present)
{
unsigned int val = inst.reloc.exp.X_add_number;
constraint (inst.reloc.exp.X_op != O_constant,
_("expression too complex"));
inst.instruction |= (val & 0x1c) << 10;
inst.instruction |= (val & 0x03) << 6;
}
}
static void
do_t_pkhtb (void)
{
if (!inst.operands[3].present)
{
unsigned Rtmp;
inst.instruction &= ~0x00000020;
/* PR 10168. Swap the Rm and Rn registers. */
Rtmp = inst.operands[1].reg;
inst.operands[1].reg = inst.operands[2].reg;
inst.operands[2].reg = Rtmp;
}
do_t_pkhbt ();
}
static void
do_t_pld (void)
{
if (inst.operands[0].immisreg)
reject_bad_reg (inst.operands[0].imm);
encode_thumb32_addr_mode (0, /*is_t=*/FALSE, /*is_d=*/FALSE);
}
static void
do_t_push_pop (void)
{
unsigned mask;
constraint (inst.operands[0].writeback,
_("push/pop do not support {reglist}^"));
constraint (inst.reloc.type != BFD_RELOC_UNUSED,
_("expression too complex"));
mask = inst.operands[0].imm;
if (inst.size_req != 4 && (mask & ~0xff) == 0)
inst.instruction = THUMB_OP16 (inst.instruction) | mask;
else if (inst.size_req != 4
&& (mask & ~0xff) == (1 << (inst.instruction == T_MNEM_push
? REG_LR : REG_PC)))
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= THUMB_PP_PC_LR;
inst.instruction |= mask & 0xff;
}
else if (unified_syntax)
{
inst.instruction = THUMB_OP32 (inst.instruction);
encode_thumb2_ldmstm (13, mask, TRUE);
}
else
{
inst.error = _("invalid register list to push/pop instruction");
return;
}
}
static void
do_t_rbit (void)
{
unsigned Rd, Rm;
Rd = inst.operands[0].reg;
Rm = inst.operands[1].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rm << 16;
inst.instruction |= Rm;
}
static void
do_t_rev (void)
{
unsigned Rd, Rm;
Rd = inst.operands[0].reg;
Rm = inst.operands[1].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rm);
if (Rd <= 7 && Rm <= 7
&& inst.size_req != 4)
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
inst.instruction |= Rm << 3;
}
else if (unified_syntax)
{
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.instruction |= Rm << 16;
inst.instruction |= Rm;
}
else
inst.error = BAD_HIREG;
}
static void
do_t_rrx (void)
{
unsigned Rd, Rm;
Rd = inst.operands[0].reg;
Rm = inst.operands[1].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rm;
}
static void
do_t_rsb (void)
{
unsigned Rd, Rs;
Rd = inst.operands[0].reg;
Rs = (inst.operands[1].present
? inst.operands[1].reg /* Rd, Rs, foo */
: inst.operands[0].reg); /* Rd, foo -> Rd, Rd, foo */
reject_bad_reg (Rd);
reject_bad_reg (Rs);
if (inst.operands[2].isreg)
reject_bad_reg (inst.operands[2].reg);
inst.instruction |= Rd << 8;
inst.instruction |= Rs << 16;
if (!inst.operands[2].isreg)
{
bfd_boolean narrow;
if ((inst.instruction & 0x00100000) != 0)
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (Rd > 7 || Rs > 7)
narrow = FALSE;
if (inst.size_req == 4 || !unified_syntax)
narrow = FALSE;
if (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0)
narrow = FALSE;
/* Turn rsb #0 into 16-bit neg. We should probably do this via
relaxation, but it doesn't seem worth the hassle. */
if (narrow)
{
inst.reloc.type = BFD_RELOC_UNUSED;
inst.instruction = THUMB_OP16 (T_MNEM_negs);
inst.instruction |= Rs << 3;
inst.instruction |= Rd;
}
else
{
inst.instruction = (inst.instruction & 0xe1ffffff) | 0x10000000;
inst.reloc.type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
}
else
encode_thumb32_shifted_operand (2);
}
static void
do_t_setend (void)
{
if (warn_on_deprecated
&& ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v8))
as_tsktsk (_("setend use is deprecated for ARMv8"));
set_it_insn_type (OUTSIDE_IT_INSN);
if (inst.operands[0].imm)
inst.instruction |= 0x8;
}
static void
do_t_shift (void)
{
if (!inst.operands[1].present)
inst.operands[1].reg = inst.operands[0].reg;
if (unified_syntax)
{
bfd_boolean narrow;
int shift_kind;
switch (inst.instruction)
{
case T_MNEM_asr:
case T_MNEM_asrs: shift_kind = SHIFT_ASR; break;
case T_MNEM_lsl:
case T_MNEM_lsls: shift_kind = SHIFT_LSL; break;
case T_MNEM_lsr:
case T_MNEM_lsrs: shift_kind = SHIFT_LSR; break;
case T_MNEM_ror:
case T_MNEM_rors: shift_kind = SHIFT_ROR; break;
default: abort ();
}
if (THUMB_SETS_FLAGS (inst.instruction))
narrow = !in_it_block ();
else
narrow = in_it_block ();
if (inst.operands[0].reg > 7 || inst.operands[1].reg > 7)
narrow = FALSE;
if (!inst.operands[2].isreg && shift_kind == SHIFT_ROR)
narrow = FALSE;
if (inst.operands[2].isreg
&& (inst.operands[1].reg != inst.operands[0].reg
|| inst.operands[2].reg > 7))
narrow = FALSE;
if (inst.size_req == 4)
narrow = FALSE;
reject_bad_reg (inst.operands[0].reg);
reject_bad_reg (inst.operands[1].reg);
if (!narrow)
{
if (inst.operands[2].isreg)
{
reject_bad_reg (inst.operands[2].reg);
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= inst.operands[2].reg;
/* PR 12854: Error on extraneous shifts. */
constraint (inst.operands[2].shifted,
_("extraneous shift as part of operand to shift insn"));
}
else
{
inst.operands[1].shifted = 1;
inst.operands[1].shift_kind = shift_kind;
inst.instruction = THUMB_OP32 (THUMB_SETS_FLAGS (inst.instruction)
? T_MNEM_movs : T_MNEM_mov);
inst.instruction |= inst.operands[0].reg << 8;
encode_thumb32_shifted_operand (1);
/* Prevent the incorrect generation of an ARM_IMMEDIATE fixup. */
inst.reloc.type = BFD_RELOC_UNUSED;
}
}
else
{
if (inst.operands[2].isreg)
{
switch (shift_kind)
{
case SHIFT_ASR: inst.instruction = T_OPCODE_ASR_R; break;
case SHIFT_LSL: inst.instruction = T_OPCODE_LSL_R; break;
case SHIFT_LSR: inst.instruction = T_OPCODE_LSR_R; break;
case SHIFT_ROR: inst.instruction = T_OPCODE_ROR_R; break;
default: abort ();
}
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[2].reg << 3;
/* PR 12854: Error on extraneous shifts. */
constraint (inst.operands[2].shifted,
_("extraneous shift as part of operand to shift insn"));
}
else
{
switch (shift_kind)
{
case SHIFT_ASR: inst.instruction = T_OPCODE_ASR_I; break;
case SHIFT_LSL: inst.instruction = T_OPCODE_LSL_I; break;
case SHIFT_LSR: inst.instruction = T_OPCODE_LSR_I; break;
default: abort ();
}
inst.reloc.type = BFD_RELOC_ARM_THUMB_SHIFT;
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
}
}
}
else
{
constraint (inst.operands[0].reg > 7
|| inst.operands[1].reg > 7, BAD_HIREG);
constraint (THUMB_SETS_FLAGS (inst.instruction), BAD_THUMB32);
if (inst.operands[2].isreg) /* Rd, {Rs,} Rn */
{
constraint (inst.operands[2].reg > 7, BAD_HIREG);
constraint (inst.operands[0].reg != inst.operands[1].reg,
_("source1 and dest must be same register"));
switch (inst.instruction)
{
case T_MNEM_asr: inst.instruction = T_OPCODE_ASR_R; break;
case T_MNEM_lsl: inst.instruction = T_OPCODE_LSL_R; break;
case T_MNEM_lsr: inst.instruction = T_OPCODE_LSR_R; break;
case T_MNEM_ror: inst.instruction = T_OPCODE_ROR_R; break;
default: abort ();
}
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[2].reg << 3;
/* PR 12854: Error on extraneous shifts. */
constraint (inst.operands[2].shifted,
_("extraneous shift as part of operand to shift insn"));
}
else
{
switch (inst.instruction)
{
case T_MNEM_asr: inst.instruction = T_OPCODE_ASR_I; break;
case T_MNEM_lsl: inst.instruction = T_OPCODE_LSL_I; break;
case T_MNEM_lsr: inst.instruction = T_OPCODE_LSR_I; break;
case T_MNEM_ror: inst.error = _("ror #imm not supported"); return;
default: abort ();
}
inst.reloc.type = BFD_RELOC_ARM_THUMB_SHIFT;
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 3;
}
}
}
static void
do_t_simd (void)
{
unsigned Rd, Rn, Rm;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
Rm = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
}
static void
do_t_simd2 (void)
{
unsigned Rd, Rn, Rm;
Rd = inst.operands[0].reg;
Rm = inst.operands[1].reg;
Rn = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
}
static void
do_t_smc (void)
{
unsigned int value = inst.reloc.exp.X_add_number;
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v7a),
_("SMC is not permitted on this architecture"));
constraint (inst.reloc.exp.X_op != O_constant,
_("expression too complex"));
inst.reloc.type = BFD_RELOC_UNUSED;
inst.instruction |= (value & 0xf000) >> 12;
inst.instruction |= (value & 0x0ff0);
inst.instruction |= (value & 0x000f) << 16;
/* PR gas/15623: SMC instructions must be last in an IT block. */
set_it_insn_type_last ();
}
static void
do_t_hvc (void)
{
unsigned int value = inst.reloc.exp.X_add_number;
inst.reloc.type = BFD_RELOC_UNUSED;
inst.instruction |= (value & 0x0fff);
inst.instruction |= (value & 0xf000) << 4;
}
static void
do_t_ssat_usat (int bias)
{
unsigned Rd, Rn;
Rd = inst.operands[0].reg;
Rn = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
inst.instruction |= Rd << 8;
inst.instruction |= inst.operands[1].imm - bias;
inst.instruction |= Rn << 16;
if (inst.operands[3].present)
{
offsetT shift_amount = inst.reloc.exp.X_add_number;
inst.reloc.type = BFD_RELOC_UNUSED;
constraint (inst.reloc.exp.X_op != O_constant,
_("expression too complex"));
if (shift_amount != 0)
{
constraint (shift_amount > 31,
_("shift expression is too large"));
if (inst.operands[3].shift_kind == SHIFT_ASR)
inst.instruction |= 0x00200000; /* sh bit. */
inst.instruction |= (shift_amount & 0x1c) << 10;
inst.instruction |= (shift_amount & 0x03) << 6;
}
}
}
static void
do_t_ssat (void)
{
do_t_ssat_usat (1);
}
static void
do_t_ssat16 (void)
{
unsigned Rd, Rn;
Rd = inst.operands[0].reg;
Rn = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
inst.instruction |= Rd << 8;
inst.instruction |= inst.operands[1].imm - 1;
inst.instruction |= Rn << 16;
}
static void
do_t_strex (void)
{
constraint (!inst.operands[2].isreg || !inst.operands[2].preind
|| inst.operands[2].postind || inst.operands[2].writeback
|| inst.operands[2].immisreg || inst.operands[2].shifted
|| inst.operands[2].negative,
BAD_ADDR_MODE);
constraint (inst.operands[2].reg == REG_PC, BAD_PC);
inst.instruction |= inst.operands[0].reg << 8;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
inst.reloc.type = BFD_RELOC_ARM_T32_OFFSET_U8;
}
static void
do_t_strexd (void)
{
if (!inst.operands[2].present)
inst.operands[2].reg = inst.operands[1].reg + 1;
constraint (inst.operands[0].reg == inst.operands[1].reg
|| inst.operands[0].reg == inst.operands[2].reg
|| inst.operands[0].reg == inst.operands[3].reg,
BAD_OVERLAP);
inst.instruction |= inst.operands[0].reg;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 8;
inst.instruction |= inst.operands[3].reg << 16;
}
static void
do_t_sxtah (void)
{
unsigned Rd, Rn, Rm;
Rd = inst.operands[0].reg;
Rn = inst.operands[1].reg;
Rm = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
reject_bad_reg (Rm);
inst.instruction |= Rd << 8;
inst.instruction |= Rn << 16;
inst.instruction |= Rm;
inst.instruction |= inst.operands[3].imm << 4;
}
static void
do_t_sxth (void)
{
unsigned Rd, Rm;
Rd = inst.operands[0].reg;
Rm = inst.operands[1].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rm);
if (inst.instruction <= 0xffff
&& inst.size_req != 4
&& Rd <= 7 && Rm <= 7
&& (!inst.operands[2].present || inst.operands[2].imm == 0))
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= Rd;
inst.instruction |= Rm << 3;
}
else if (unified_syntax)
{
if (inst.instruction <= 0xffff)
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= Rd << 8;
inst.instruction |= Rm;
inst.instruction |= inst.operands[2].imm << 4;
}
else
{
constraint (inst.operands[2].present && inst.operands[2].imm != 0,
_("Thumb encoding does not support rotation"));
constraint (1, BAD_HIREG);
}
}
static void
do_t_swi (void)
{
/* We have to do the following check manually as ARM_EXT_OS only applies
to ARM_EXT_V6M. */
if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v6m))
{
if (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_os)
/* This only applies to the v6m howver, not later architectures. */
&& ! ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v7))
as_bad (_("SVC is not permitted on this architecture"));
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used, arm_ext_os);
}
inst.reloc.type = BFD_RELOC_ARM_SWI;
}
static void
do_t_tb (void)
{
unsigned Rn, Rm;
int half;
half = (inst.instruction & 0x10) != 0;
set_it_insn_type_last ();
constraint (inst.operands[0].immisreg,
_("instruction requires register index"));
Rn = inst.operands[0].reg;
Rm = inst.operands[0].imm;
constraint (Rn == REG_SP, BAD_SP);
reject_bad_reg (Rm);
constraint (!half && inst.operands[0].shifted,
_("instruction does not allow shifted index"));
inst.instruction |= (Rn << 16) | Rm;
}
static void
do_t_udf (void)
{
if (!inst.operands[0].present)
inst.operands[0].imm = 0;
if ((unsigned int) inst.operands[0].imm > 255 || inst.size_req == 4)
{
constraint (inst.size_req == 2,
_("immediate value out of range"));
inst.instruction = THUMB_OP32 (inst.instruction);
inst.instruction |= (inst.operands[0].imm & 0xf000u) << 4;
inst.instruction |= (inst.operands[0].imm & 0x0fffu) << 0;
}
else
{
inst.instruction = THUMB_OP16 (inst.instruction);
inst.instruction |= inst.operands[0].imm;
}
set_it_insn_type (NEUTRAL_IT_INSN);
}
static void
do_t_usat (void)
{
do_t_ssat_usat (0);
}
static void
do_t_usat16 (void)
{
unsigned Rd, Rn;
Rd = inst.operands[0].reg;
Rn = inst.operands[2].reg;
reject_bad_reg (Rd);
reject_bad_reg (Rn);
inst.instruction |= Rd << 8;
inst.instruction |= inst.operands[1].imm;
inst.instruction |= Rn << 16;
}
/* Neon instruction encoder helpers. */
/* Encodings for the different types for various Neon opcodes. */
/* An "invalid" code for the following tables. */
#define N_INV -1u
struct neon_tab_entry
{
unsigned integer;
unsigned float_or_poly;
unsigned scalar_or_imm;
};
/* Map overloaded Neon opcodes to their respective encodings. */
#define NEON_ENC_TAB \
X(vabd, 0x0000700, 0x1200d00, N_INV), \
X(vmax, 0x0000600, 0x0000f00, N_INV), \
X(vmin, 0x0000610, 0x0200f00, N_INV), \
X(vpadd, 0x0000b10, 0x1000d00, N_INV), \
X(vpmax, 0x0000a00, 0x1000f00, N_INV), \
X(vpmin, 0x0000a10, 0x1200f00, N_INV), \
X(vadd, 0x0000800, 0x0000d00, N_INV), \
X(vsub, 0x1000800, 0x0200d00, N_INV), \
X(vceq, 0x1000810, 0x0000e00, 0x1b10100), \
X(vcge, 0x0000310, 0x1000e00, 0x1b10080), \
X(vcgt, 0x0000300, 0x1200e00, 0x1b10000), \
/* Register variants of the following two instructions are encoded as
vcge / vcgt with the operands reversed. */ \
X(vclt, 0x0000300, 0x1200e00, 0x1b10200), \
X(vcle, 0x0000310, 0x1000e00, 0x1b10180), \
X(vfma, N_INV, 0x0000c10, N_INV), \
X(vfms, N_INV, 0x0200c10, N_INV), \
X(vmla, 0x0000900, 0x0000d10, 0x0800040), \
X(vmls, 0x1000900, 0x0200d10, 0x0800440), \
X(vmul, 0x0000910, 0x1000d10, 0x0800840), \
X(vmull, 0x0800c00, 0x0800e00, 0x0800a40), /* polynomial not float. */ \
X(vmlal, 0x0800800, N_INV, 0x0800240), \
X(vmlsl, 0x0800a00, N_INV, 0x0800640), \
X(vqdmlal, 0x0800900, N_INV, 0x0800340), \
X(vqdmlsl, 0x0800b00, N_INV, 0x0800740), \
X(vqdmull, 0x0800d00, N_INV, 0x0800b40), \
X(vqdmulh, 0x0000b00, N_INV, 0x0800c40), \
X(vqrdmulh, 0x1000b00, N_INV, 0x0800d40), \
X(vshl, 0x0000400, N_INV, 0x0800510), \
X(vqshl, 0x0000410, N_INV, 0x0800710), \
X(vand, 0x0000110, N_INV, 0x0800030), \
X(vbic, 0x0100110, N_INV, 0x0800030), \
X(veor, 0x1000110, N_INV, N_INV), \
X(vorn, 0x0300110, N_INV, 0x0800010), \
X(vorr, 0x0200110, N_INV, 0x0800010), \
X(vmvn, 0x1b00580, N_INV, 0x0800030), \
X(vshll, 0x1b20300, N_INV, 0x0800a10), /* max shift, immediate. */ \
X(vcvt, 0x1b30600, N_INV, 0x0800e10), /* integer, fixed-point. */ \
X(vdup, 0xe800b10, N_INV, 0x1b00c00), /* arm, scalar. */ \
X(vld1, 0x0200000, 0x0a00000, 0x0a00c00), /* interlv, lane, dup. */ \
X(vst1, 0x0000000, 0x0800000, N_INV), \
X(vld2, 0x0200100, 0x0a00100, 0x0a00d00), \
X(vst2, 0x0000100, 0x0800100, N_INV), \
X(vld3, 0x0200200, 0x0a00200, 0x0a00e00), \
X(vst3, 0x0000200, 0x0800200, N_INV), \
X(vld4, 0x0200300, 0x0a00300, 0x0a00f00), \
X(vst4, 0x0000300, 0x0800300, N_INV), \
X(vmovn, 0x1b20200, N_INV, N_INV), \
X(vtrn, 0x1b20080, N_INV, N_INV), \
X(vqmovn, 0x1b20200, N_INV, N_INV), \
X(vqmovun, 0x1b20240, N_INV, N_INV), \
X(vnmul, 0xe200a40, 0xe200b40, N_INV), \
X(vnmla, 0xe100a40, 0xe100b40, N_INV), \
X(vnmls, 0xe100a00, 0xe100b00, N_INV), \
X(vfnma, 0xe900a40, 0xe900b40, N_INV), \
X(vfnms, 0xe900a00, 0xe900b00, N_INV), \
X(vcmp, 0xeb40a40, 0xeb40b40, N_INV), \
X(vcmpz, 0xeb50a40, 0xeb50b40, N_INV), \
X(vcmpe, 0xeb40ac0, 0xeb40bc0, N_INV), \
X(vcmpez, 0xeb50ac0, 0xeb50bc0, N_INV), \
X(vseleq, 0xe000a00, N_INV, N_INV), \
X(vselvs, 0xe100a00, N_INV, N_INV), \
X(vselge, 0xe200a00, N_INV, N_INV), \
X(vselgt, 0xe300a00, N_INV, N_INV), \
X(vmaxnm, 0xe800a00, 0x3000f10, N_INV), \
X(vminnm, 0xe800a40, 0x3200f10, N_INV), \
X(vcvta, 0xebc0a40, 0x3bb0000, N_INV), \
X(vrintr, 0xeb60a40, 0x3ba0400, N_INV), \
X(vrinta, 0xeb80a40, 0x3ba0400, N_INV), \
X(aes, 0x3b00300, N_INV, N_INV), \
X(sha3op, 0x2000c00, N_INV, N_INV), \
X(sha1h, 0x3b902c0, N_INV, N_INV), \
X(sha2op, 0x3ba0380, N_INV, N_INV)
enum neon_opc
{
#define X(OPC,I,F,S) N_MNEM_##OPC
NEON_ENC_TAB
#undef X
};
static const struct neon_tab_entry neon_enc_tab[] =
{
#define X(OPC,I,F,S) { (I), (F), (S) }
NEON_ENC_TAB
#undef X
};
/* Do not use these macros; instead, use NEON_ENCODE defined below. */
#define NEON_ENC_INTEGER_(X) (neon_enc_tab[(X) & 0x0fffffff].integer)
#define NEON_ENC_ARMREG_(X) (neon_enc_tab[(X) & 0x0fffffff].integer)
#define NEON_ENC_POLY_(X) (neon_enc_tab[(X) & 0x0fffffff].float_or_poly)
#define NEON_ENC_FLOAT_(X) (neon_enc_tab[(X) & 0x0fffffff].float_or_poly)
#define NEON_ENC_SCALAR_(X) (neon_enc_tab[(X) & 0x0fffffff].scalar_or_imm)
#define NEON_ENC_IMMED_(X) (neon_enc_tab[(X) & 0x0fffffff].scalar_or_imm)
#define NEON_ENC_INTERLV_(X) (neon_enc_tab[(X) & 0x0fffffff].integer)
#define NEON_ENC_LANE_(X) (neon_enc_tab[(X) & 0x0fffffff].float_or_poly)
#define NEON_ENC_DUP_(X) (neon_enc_tab[(X) & 0x0fffffff].scalar_or_imm)
#define NEON_ENC_SINGLE_(X) \
((neon_enc_tab[(X) & 0x0fffffff].integer) | ((X) & 0xf0000000))
#define NEON_ENC_DOUBLE_(X) \
((neon_enc_tab[(X) & 0x0fffffff].float_or_poly) | ((X) & 0xf0000000))
#define NEON_ENC_FPV8_(X) \
((neon_enc_tab[(X) & 0x0fffffff].integer) | ((X) & 0xf000000))
#define NEON_ENCODE(type, inst) \
do \
{ \
inst.instruction = NEON_ENC_##type##_ (inst.instruction); \
inst.is_neon = 1; \
} \
while (0)
#define check_neon_suffixes \
do \
{ \
if (!inst.error && inst.vectype.elems > 0 && !inst.is_neon) \
{ \
as_bad (_("invalid neon suffix for non neon instruction")); \
return; \
} \
} \
while (0)
/* Define shapes for instruction operands. The following mnemonic characters
are used in this table:
F - VFP S<n> register
D - Neon D<n> register
Q - Neon Q<n> register
I - Immediate
S - Scalar
R - ARM register
L - D<n> register list
This table is used to generate various data:
- enumerations of the form NS_DDR to be used as arguments to
neon_select_shape.
- a table classifying shapes into single, double, quad, mixed.
- a table used to drive neon_select_shape. */
#define NEON_SHAPE_DEF \
X(3, (D, D, D), DOUBLE), \
X(3, (Q, Q, Q), QUAD), \
X(3, (D, D, I), DOUBLE), \
X(3, (Q, Q, I), QUAD), \
X(3, (D, D, S), DOUBLE), \
X(3, (Q, Q, S), QUAD), \
X(2, (D, D), DOUBLE), \
X(2, (Q, Q), QUAD), \
X(2, (D, S), DOUBLE), \
X(2, (Q, S), QUAD), \
X(2, (D, R), DOUBLE), \
X(2, (Q, R), QUAD), \
X(2, (D, I), DOUBLE), \
X(2, (Q, I), QUAD), \
X(3, (D, L, D), DOUBLE), \
X(2, (D, Q), MIXED), \
X(2, (Q, D), MIXED), \
X(3, (D, Q, I), MIXED), \
X(3, (Q, D, I), MIXED), \
X(3, (Q, D, D), MIXED), \
X(3, (D, Q, Q), MIXED), \
X(3, (Q, Q, D), MIXED), \
X(3, (Q, D, S), MIXED), \
X(3, (D, Q, S), MIXED), \
X(4, (D, D, D, I), DOUBLE), \
X(4, (Q, Q, Q, I), QUAD), \
X(2, (F, F), SINGLE), \
X(3, (F, F, F), SINGLE), \
X(2, (F, I), SINGLE), \
X(2, (F, D), MIXED), \
X(2, (D, F), MIXED), \
X(3, (F, F, I), MIXED), \
X(4, (R, R, F, F), SINGLE), \
X(4, (F, F, R, R), SINGLE), \
X(3, (D, R, R), DOUBLE), \
X(3, (R, R, D), DOUBLE), \
X(2, (S, R), SINGLE), \
X(2, (R, S), SINGLE), \
X(2, (F, R), SINGLE), \
X(2, (R, F), SINGLE)
#define S2(A,B) NS_##A##B
#define S3(A,B,C) NS_##A##B##C
#define S4(A,B,C,D) NS_##A##B##C##D
#define X(N, L, C) S##N L
enum neon_shape
{
NEON_SHAPE_DEF,
NS_NULL
};
#undef X
#undef S2
#undef S3
#undef S4
enum neon_shape_class
{
SC_SINGLE,
SC_DOUBLE,
SC_QUAD,
SC_MIXED
};
#define X(N, L, C) SC_##C
static enum neon_shape_class neon_shape_class[] =
{
NEON_SHAPE_DEF
};
#undef X
enum neon_shape_el
{
SE_F,
SE_D,
SE_Q,
SE_I,
SE_S,
SE_R,
SE_L
};
/* Register widths of above. */
static unsigned neon_shape_el_size[] =
{
32,
64,
128,
0,
32,
32,
0
};
struct neon_shape_info
{
unsigned els;
enum neon_shape_el el[NEON_MAX_TYPE_ELS];
};
#define S2(A,B) { SE_##A, SE_##B }
#define S3(A,B,C) { SE_##A, SE_##B, SE_##C }
#define S4(A,B,C,D) { SE_##A, SE_##B, SE_##C, SE_##D }
#define X(N, L, C) { N, S##N L }
static struct neon_shape_info neon_shape_tab[] =
{
NEON_SHAPE_DEF
};
#undef X
#undef S2
#undef S3
#undef S4
/* Bit masks used in type checking given instructions.
'N_EQK' means the type must be the same as (or based on in some way) the key
type, which itself is marked with the 'N_KEY' bit. If the 'N_EQK' bit is
set, various other bits can be set as well in order to modify the meaning of
the type constraint. */
enum neon_type_mask
{
N_S8 = 0x0000001,
N_S16 = 0x0000002,
N_S32 = 0x0000004,
N_S64 = 0x0000008,
N_U8 = 0x0000010,
N_U16 = 0x0000020,
N_U32 = 0x0000040,
N_U64 = 0x0000080,
N_I8 = 0x0000100,
N_I16 = 0x0000200,
N_I32 = 0x0000400,
N_I64 = 0x0000800,
N_8 = 0x0001000,
N_16 = 0x0002000,
N_32 = 0x0004000,
N_64 = 0x0008000,
N_P8 = 0x0010000,
N_P16 = 0x0020000,
N_F16 = 0x0040000,
N_F32 = 0x0080000,
N_F64 = 0x0100000,
N_P64 = 0x0200000,
N_KEY = 0x1000000, /* Key element (main type specifier). */
N_EQK = 0x2000000, /* Given operand has the same type & size as the key. */
N_VFP = 0x4000000, /* VFP mode: operand size must match register width. */
N_UNT = 0x8000000, /* Must be explicitly untyped. */
N_DBL = 0x0000001, /* If N_EQK, this operand is twice the size. */
N_HLF = 0x0000002, /* If N_EQK, this operand is half the size. */
N_SGN = 0x0000004, /* If N_EQK, this operand is forced to be signed. */
N_UNS = 0x0000008, /* If N_EQK, this operand is forced to be unsigned. */
N_INT = 0x0000010, /* If N_EQK, this operand is forced to be integer. */
N_FLT = 0x0000020, /* If N_EQK, this operand is forced to be float. */
N_SIZ = 0x0000040, /* If N_EQK, this operand is forced to be size-only. */
N_UTYP = 0,
N_MAX_NONSPECIAL = N_P64
};
#define N_ALLMODS (N_DBL | N_HLF | N_SGN | N_UNS | N_INT | N_FLT | N_SIZ)
#define N_SU_ALL (N_S8 | N_S16 | N_S32 | N_S64 | N_U8 | N_U16 | N_U32 | N_U64)
#define N_SU_32 (N_S8 | N_S16 | N_S32 | N_U8 | N_U16 | N_U32)
#define N_SU_16_64 (N_S16 | N_S32 | N_S64 | N_U16 | N_U32 | N_U64)
#define N_SUF_32 (N_SU_32 | N_F32)
#define N_I_ALL (N_I8 | N_I16 | N_I32 | N_I64)
#define N_IF_32 (N_I8 | N_I16 | N_I32 | N_F32)
/* Pass this as the first type argument to neon_check_type to ignore types
altogether. */
#define N_IGNORE_TYPE (N_KEY | N_EQK)
/* Select a "shape" for the current instruction (describing register types or
sizes) from a list of alternatives. Return NS_NULL if the current instruction
doesn't fit. For non-polymorphic shapes, checking is usually done as a
function of operand parsing, so this function doesn't need to be called.
Shapes should be listed in order of decreasing length. */
static enum neon_shape
neon_select_shape (enum neon_shape shape, ...)
{
va_list ap;
enum neon_shape first_shape = shape;
/* Fix missing optional operands. FIXME: we don't know at this point how
many arguments we should have, so this makes the assumption that we have
> 1. This is true of all current Neon opcodes, I think, but may not be
true in the future. */
if (!inst.operands[1].present)
inst.operands[1] = inst.operands[0];
va_start (ap, shape);
for (; shape != NS_NULL; shape = (enum neon_shape) va_arg (ap, int))
{
unsigned j;
int matches = 1;
for (j = 0; j < neon_shape_tab[shape].els; j++)
{
if (!inst.operands[j].present)
{
matches = 0;
break;
}
switch (neon_shape_tab[shape].el[j])
{
case SE_F:
if (!(inst.operands[j].isreg
&& inst.operands[j].isvec
&& inst.operands[j].issingle
&& !inst.operands[j].isquad))
matches = 0;
break;
case SE_D:
if (!(inst.operands[j].isreg
&& inst.operands[j].isvec
&& !inst.operands[j].isquad
&& !inst.operands[j].issingle))
matches = 0;
break;
case SE_R:
if (!(inst.operands[j].isreg
&& !inst.operands[j].isvec))
matches = 0;
break;
case SE_Q:
if (!(inst.operands[j].isreg
&& inst.operands[j].isvec
&& inst.operands[j].isquad
&& !inst.operands[j].issingle))
matches = 0;
break;
case SE_I:
if (!(!inst.operands[j].isreg
&& !inst.operands[j].isscalar))
matches = 0;
break;
case SE_S:
if (!(!inst.operands[j].isreg
&& inst.operands[j].isscalar))
matches = 0;
break;
case SE_L:
break;
}
if (!matches)
break;
}
if (matches && (j >= ARM_IT_MAX_OPERANDS || !inst.operands[j].present))
/* We've matched all the entries in the shape table, and we don't
have any left over operands which have not been matched. */
break;
}
va_end (ap);
if (shape == NS_NULL && first_shape != NS_NULL)
first_error (_("invalid instruction shape"));
return shape;
}
/* True if SHAPE is predominantly a quadword operation (most of the time, this
means the Q bit should be set). */
static int
neon_quad (enum neon_shape shape)
{
return neon_shape_class[shape] == SC_QUAD;
}
static void
neon_modify_type_size (unsigned typebits, enum neon_el_type *g_type,
unsigned *g_size)
{
/* Allow modification to be made to types which are constrained to be
based on the key element, based on bits set alongside N_EQK. */
if ((typebits & N_EQK) != 0)
{
if ((typebits & N_HLF) != 0)
*g_size /= 2;
else if ((typebits & N_DBL) != 0)
*g_size *= 2;
if ((typebits & N_SGN) != 0)
*g_type = NT_signed;
else if ((typebits & N_UNS) != 0)
*g_type = NT_unsigned;
else if ((typebits & N_INT) != 0)
*g_type = NT_integer;
else if ((typebits & N_FLT) != 0)
*g_type = NT_float;
else if ((typebits & N_SIZ) != 0)
*g_type = NT_untyped;
}
}
/* Return operand OPNO promoted by bits set in THISARG. KEY should be the "key"
operand type, i.e. the single type specified in a Neon instruction when it
is the only one given. */
static struct neon_type_el
neon_type_promote (struct neon_type_el *key, unsigned thisarg)
{
struct neon_type_el dest = *key;
gas_assert ((thisarg & N_EQK) != 0);
neon_modify_type_size (thisarg, &dest.type, &dest.size);
return dest;
}
/* Convert Neon type and size into compact bitmask representation. */
static enum neon_type_mask
type_chk_of_el_type (enum neon_el_type type, unsigned size)
{
switch (type)
{
case NT_untyped:
switch (size)
{
case 8: return N_8;
case 16: return N_16;
case 32: return N_32;
case 64: return N_64;
default: ;
}
break;
case NT_integer:
switch (size)
{
case 8: return N_I8;
case 16: return N_I16;
case 32: return N_I32;
case 64: return N_I64;
default: ;
}
break;
case NT_float:
switch (size)
{
case 16: return N_F16;
case 32: return N_F32;
case 64: return N_F64;
default: ;
}
break;
case NT_poly:
switch (size)
{
case 8: return N_P8;
case 16: return N_P16;
case 64: return N_P64;
default: ;
}
break;
case NT_signed:
switch (size)
{
case 8: return N_S8;
case 16: return N_S16;
case 32: return N_S32;
case 64: return N_S64;
default: ;
}
break;
case NT_unsigned:
switch (size)
{
case 8: return N_U8;
case 16: return N_U16;
case 32: return N_U32;
case 64: return N_U64;
default: ;
}
break;
default: ;
}
return N_UTYP;
}
/* Convert compact Neon bitmask type representation to a type and size. Only
handles the case where a single bit is set in the mask. */
static int
el_type_of_type_chk (enum neon_el_type *type, unsigned *size,
enum neon_type_mask mask)
{
if ((mask & N_EQK) != 0)
return FAIL;
if ((mask & (N_S8 | N_U8 | N_I8 | N_8 | N_P8)) != 0)
*size = 8;
else if ((mask & (N_S16 | N_U16 | N_I16 | N_16 | N_F16 | N_P16)) != 0)
*size = 16;
else if ((mask & (N_S32 | N_U32 | N_I32 | N_32 | N_F32)) != 0)
*size = 32;
else if ((mask & (N_S64 | N_U64 | N_I64 | N_64 | N_F64 | N_P64)) != 0)
*size = 64;
else
return FAIL;
if ((mask & (N_S8 | N_S16 | N_S32 | N_S64)) != 0)
*type = NT_signed;
else if ((mask & (N_U8 | N_U16 | N_U32 | N_U64)) != 0)
*type = NT_unsigned;
else if ((mask & (N_I8 | N_I16 | N_I32 | N_I64)) != 0)
*type = NT_integer;
else if ((mask & (N_8 | N_16 | N_32 | N_64)) != 0)
*type = NT_untyped;
else if ((mask & (N_P8 | N_P16 | N_P64)) != 0)
*type = NT_poly;
else if ((mask & (N_F16 | N_F32 | N_F64)) != 0)
*type = NT_float;
else
return FAIL;
return SUCCESS;
}
/* Modify a bitmask of allowed types. This is only needed for type
relaxation. */
static unsigned
modify_types_allowed (unsigned allowed, unsigned mods)
{
unsigned size;
enum neon_el_type type;
unsigned destmask;
int i;
destmask = 0;
for (i = 1; i <= N_MAX_NONSPECIAL; i <<= 1)
{
if (el_type_of_type_chk (&type, &size,
(enum neon_type_mask) (allowed & i)) == SUCCESS)
{
neon_modify_type_size (mods, &type, &size);
destmask |= type_chk_of_el_type (type, size);
}
}
return destmask;
}
/* Check type and return type classification.
The manual states (paraphrase): If one datatype is given, it indicates the
type given in:
- the second operand, if there is one
- the operand, if there is no second operand
- the result, if there are no operands.
This isn't quite good enough though, so we use a concept of a "key" datatype
which is set on a per-instruction basis, which is the one which matters when
only one data type is written.
Note: this function has side-effects (e.g. filling in missing operands). All
Neon instructions should call it before performing bit encoding. */
static struct neon_type_el
neon_check_type (unsigned els, enum neon_shape ns, ...)
{
va_list ap;
unsigned i, pass, key_el = 0;
unsigned types[NEON_MAX_TYPE_ELS];
enum neon_el_type k_type = NT_invtype;
unsigned k_size = -1u;
struct neon_type_el badtype = {NT_invtype, -1};
unsigned key_allowed = 0;
/* Optional registers in Neon instructions are always (not) in operand 1.
Fill in the missing operand here, if it was omitted. */
if (els > 1 && !inst.operands[1].present)
inst.operands[1] = inst.operands[0];
/* Suck up all the varargs. */
va_start (ap, ns);
for (i = 0; i < els; i++)
{
unsigned thisarg = va_arg (ap, unsigned);
if (thisarg == N_IGNORE_TYPE)
{
va_end (ap);
return badtype;
}
types[i] = thisarg;
if ((thisarg & N_KEY) != 0)
key_el = i;
}
va_end (ap);
if (inst.vectype.elems > 0)
for (i = 0; i < els; i++)
if (inst.operands[i].vectype.type != NT_invtype)
{
first_error (_("types specified in both the mnemonic and operands"));
return badtype;
}
/* Duplicate inst.vectype elements here as necessary.
FIXME: No idea if this is exactly the same as the ARM assembler,
particularly when an insn takes one register and one non-register
operand. */
if (inst.vectype.elems == 1 && els > 1)
{
unsigned j;
inst.vectype.elems = els;
inst.vectype.el[key_el] = inst.vectype.el[0];
for (j = 0; j < els; j++)
if (j != key_el)
inst.vectype.el[j] = neon_type_promote (&inst.vectype.el[key_el],
types[j]);
}
else if (inst.vectype.elems == 0 && els > 0)
{
unsigned j;
/* No types were given after the mnemonic, so look for types specified
after each operand. We allow some flexibility here; as long as the
"key" operand has a type, we can infer the others. */
for (j = 0; j < els; j++)
if (inst.operands[j].vectype.type != NT_invtype)
inst.vectype.el[j] = inst.operands[j].vectype;
if (inst.operands[key_el].vectype.type != NT_invtype)
{
for (j = 0; j < els; j++)
if (inst.operands[j].vectype.type == NT_invtype)
inst.vectype.el[j] = neon_type_promote (&inst.vectype.el[key_el],
types[j]);
}
else
{
first_error (_("operand types can't be inferred"));
return badtype;
}
}
else if (inst.vectype.elems != els)
{
first_error (_("type specifier has the wrong number of parts"));
return badtype;
}
for (pass = 0; pass < 2; pass++)
{
for (i = 0; i < els; i++)
{
unsigned thisarg = types[i];
unsigned types_allowed = ((thisarg & N_EQK) != 0 && pass != 0)
? modify_types_allowed (key_allowed, thisarg) : thisarg;
enum neon_el_type g_type = inst.vectype.el[i].type;
unsigned g_size = inst.vectype.el[i].size;
/* Decay more-specific signed & unsigned types to sign-insensitive
integer types if sign-specific variants are unavailable. */
if ((g_type == NT_signed || g_type == NT_unsigned)
&& (types_allowed & N_SU_ALL) == 0)
g_type = NT_integer;
/* If only untyped args are allowed, decay any more specific types to
them. Some instructions only care about signs for some element
sizes, so handle that properly. */
if (((types_allowed & N_UNT) == 0)
&& ((g_size == 8 && (types_allowed & N_8) != 0)
|| (g_size == 16 && (types_allowed & N_16) != 0)
|| (g_size == 32 && (types_allowed & N_32) != 0)
|| (g_size == 64 && (types_allowed & N_64) != 0)))
g_type = NT_untyped;
if (pass == 0)
{
if ((thisarg & N_KEY) != 0)
{
k_type = g_type;
k_size = g_size;
key_allowed = thisarg & ~N_KEY;
}
}
else
{
if ((thisarg & N_VFP) != 0)
{
enum neon_shape_el regshape;
unsigned regwidth, match;
/* PR 11136: Catch the case where we are passed a shape of NS_NULL. */
if (ns == NS_NULL)
{
first_error (_("invalid instruction shape"));
return badtype;
}
regshape = neon_shape_tab[ns].el[i];
regwidth = neon_shape_el_size[regshape];
/* In VFP mode, operands must match register widths. If we
have a key operand, use its width, else use the width of
the current operand. */
if (k_size != -1u)
match = k_size;
else
match = g_size;
if (regwidth != match)
{
first_error (_("operand size must match register width"));
return badtype;
}
}
if ((thisarg & N_EQK) == 0)
{
unsigned given_type = type_chk_of_el_type (g_type, g_size);
if ((given_type & types_allowed) == 0)
{
first_error (_("bad type in Neon instruction"));
return badtype;
}
}
else
{
enum neon_el_type mod_k_type = k_type;
unsigned mod_k_size = k_size;
neon_modify_type_size (thisarg, &mod_k_type, &mod_k_size);
if (g_type != mod_k_type || g_size != mod_k_size)
{
first_error (_("inconsistent types in Neon instruction"));
return badtype;
}
}
}
}
}
return inst.vectype.el[key_el];
}
/* Neon-style VFP instruction forwarding. */
/* Thumb VFP instructions have 0xE in the condition field. */
static void
do_vfp_cond_or_thumb (void)
{
inst.is_neon = 1;
if (thumb_mode)
inst.instruction |= 0xe0000000;
else
inst.instruction |= inst.cond << 28;
}
/* Look up and encode a simple mnemonic, for use as a helper function for the
Neon-style VFP syntax. This avoids duplication of bits of the insns table,
etc. It is assumed that operand parsing has already been done, and that the
operands are in the form expected by the given opcode (this isn't necessarily
the same as the form in which they were parsed, hence some massaging must
take place before this function is called).
Checks current arch version against that in the looked-up opcode. */
static void
do_vfp_nsyn_opcode (const char *opname)
{
const struct asm_opcode *opcode;
opcode = (const struct asm_opcode *) hash_find (arm_ops_hsh, opname);
if (!opcode)
abort ();
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant,
thumb_mode ? *opcode->tvariant : *opcode->avariant),
_(BAD_FPU));
inst.is_neon = 1;
if (thumb_mode)
{
inst.instruction = opcode->tvalue;
opcode->tencode ();
}
else
{
inst.instruction = (inst.cond << 28) | opcode->avalue;
opcode->aencode ();
}
}
static void
do_vfp_nsyn_add_sub (enum neon_shape rs)
{
int is_add = (inst.instruction & 0x0fffffff) == N_MNEM_vadd;
if (rs == NS_FFF)
{
if (is_add)
do_vfp_nsyn_opcode ("fadds");
else
do_vfp_nsyn_opcode ("fsubs");
}
else
{
if (is_add)
do_vfp_nsyn_opcode ("faddd");
else
do_vfp_nsyn_opcode ("fsubd");
}
}
/* Check operand types to see if this is a VFP instruction, and if so call
PFN (). */
static int
try_vfp_nsyn (int args, void (*pfn) (enum neon_shape))
{
enum neon_shape rs;
struct neon_type_el et;
switch (args)
{
case 2:
rs = neon_select_shape (NS_FF, NS_DD, NS_NULL);
et = neon_check_type (2, rs,
N_EQK | N_VFP, N_F32 | N_F64 | N_KEY | N_VFP);
break;
case 3:
rs = neon_select_shape (NS_FFF, NS_DDD, NS_NULL);
et = neon_check_type (3, rs,
N_EQK | N_VFP, N_EQK | N_VFP, N_F32 | N_F64 | N_KEY | N_VFP);
break;
default:
abort ();
}
if (et.type != NT_invtype)
{
pfn (rs);
return SUCCESS;
}
inst.error = NULL;
return FAIL;
}
static void
do_vfp_nsyn_mla_mls (enum neon_shape rs)
{
int is_mla = (inst.instruction & 0x0fffffff) == N_MNEM_vmla;
if (rs == NS_FFF)
{
if (is_mla)
do_vfp_nsyn_opcode ("fmacs");
else
do_vfp_nsyn_opcode ("fnmacs");
}
else
{
if (is_mla)
do_vfp_nsyn_opcode ("fmacd");
else
do_vfp_nsyn_opcode ("fnmacd");
}
}
static void
do_vfp_nsyn_fma_fms (enum neon_shape rs)
{
int is_fma = (inst.instruction & 0x0fffffff) == N_MNEM_vfma;
if (rs == NS_FFF)
{
if (is_fma)
do_vfp_nsyn_opcode ("ffmas");
else
do_vfp_nsyn_opcode ("ffnmas");
}
else
{
if (is_fma)
do_vfp_nsyn_opcode ("ffmad");
else
do_vfp_nsyn_opcode ("ffnmad");
}
}
static void
do_vfp_nsyn_mul (enum neon_shape rs)
{
if (rs == NS_FFF)
do_vfp_nsyn_opcode ("fmuls");
else
do_vfp_nsyn_opcode ("fmuld");
}
static void
do_vfp_nsyn_abs_neg (enum neon_shape rs)
{
int is_neg = (inst.instruction & 0x80) != 0;
neon_check_type (2, rs, N_EQK | N_VFP, N_F32 | N_F64 | N_VFP | N_KEY);
if (rs == NS_FF)
{
if (is_neg)
do_vfp_nsyn_opcode ("fnegs");
else
do_vfp_nsyn_opcode ("fabss");
}
else
{
if (is_neg)
do_vfp_nsyn_opcode ("fnegd");
else
do_vfp_nsyn_opcode ("fabsd");
}
}
/* Encode single-precision (only!) VFP fldm/fstm instructions. Double precision
insns belong to Neon, and are handled elsewhere. */
static void
do_vfp_nsyn_ldm_stm (int is_dbmode)
{
int is_ldm = (inst.instruction & (1 << 20)) != 0;
if (is_ldm)
{
if (is_dbmode)
do_vfp_nsyn_opcode ("fldmdbs");
else
do_vfp_nsyn_opcode ("fldmias");
}
else
{
if (is_dbmode)
do_vfp_nsyn_opcode ("fstmdbs");
else
do_vfp_nsyn_opcode ("fstmias");
}
}
static void
do_vfp_nsyn_sqrt (void)
{
enum neon_shape rs = neon_select_shape (NS_FF, NS_DD, NS_NULL);
neon_check_type (2, rs, N_EQK | N_VFP, N_F32 | N_F64 | N_KEY | N_VFP);
if (rs == NS_FF)
do_vfp_nsyn_opcode ("fsqrts");
else
do_vfp_nsyn_opcode ("fsqrtd");
}
static void
do_vfp_nsyn_div (void)
{
enum neon_shape rs = neon_select_shape (NS_FFF, NS_DDD, NS_NULL);
neon_check_type (3, rs, N_EQK | N_VFP, N_EQK | N_VFP,
N_F32 | N_F64 | N_KEY | N_VFP);
if (rs == NS_FFF)
do_vfp_nsyn_opcode ("fdivs");
else
do_vfp_nsyn_opcode ("fdivd");
}
static void
do_vfp_nsyn_nmul (void)
{
enum neon_shape rs = neon_select_shape (NS_FFF, NS_DDD, NS_NULL);
neon_check_type (3, rs, N_EQK | N_VFP, N_EQK | N_VFP,
N_F32 | N_F64 | N_KEY | N_VFP);
if (rs == NS_FFF)
{
NEON_ENCODE (SINGLE, inst);
do_vfp_sp_dyadic ();
}
else
{
NEON_ENCODE (DOUBLE, inst);
do_vfp_dp_rd_rn_rm ();
}
do_vfp_cond_or_thumb ();
}
static void
do_vfp_nsyn_cmp (void)
{
if (inst.operands[1].isreg)
{
enum neon_shape rs = neon_select_shape (NS_FF, NS_DD, NS_NULL);
neon_check_type (2, rs, N_EQK | N_VFP, N_F32 | N_F64 | N_KEY | N_VFP);
if (rs == NS_FF)
{
NEON_ENCODE (SINGLE, inst);
do_vfp_sp_monadic ();
}
else
{
NEON_ENCODE (DOUBLE, inst);
do_vfp_dp_rd_rm ();
}
}
else
{
enum neon_shape rs = neon_select_shape (NS_FI, NS_DI, NS_NULL);
neon_check_type (2, rs, N_F32 | N_F64 | N_KEY | N_VFP, N_EQK);
switch (inst.instruction & 0x0fffffff)
{
case N_MNEM_vcmp:
inst.instruction += N_MNEM_vcmpz - N_MNEM_vcmp;
break;
case N_MNEM_vcmpe:
inst.instruction += N_MNEM_vcmpez - N_MNEM_vcmpe;
break;
default:
abort ();
}
if (rs == NS_FI)
{
NEON_ENCODE (SINGLE, inst);
do_vfp_sp_compare_z ();
}
else
{
NEON_ENCODE (DOUBLE, inst);
do_vfp_dp_rd ();
}
}
do_vfp_cond_or_thumb ();
}
static void
nsyn_insert_sp (void)
{
inst.operands[1] = inst.operands[0];
memset (&inst.operands[0], '\0', sizeof (inst.operands[0]));
inst.operands[0].reg = REG_SP;
inst.operands[0].isreg = 1;
inst.operands[0].writeback = 1;
inst.operands[0].present = 1;
}
static void
do_vfp_nsyn_push (void)
{
nsyn_insert_sp ();
if (inst.operands[1].issingle)
do_vfp_nsyn_opcode ("fstmdbs");
else
do_vfp_nsyn_opcode ("fstmdbd");
}
static void
do_vfp_nsyn_pop (void)
{
nsyn_insert_sp ();
if (inst.operands[1].issingle)
do_vfp_nsyn_opcode ("fldmias");
else
do_vfp_nsyn_opcode ("fldmiad");
}
/* Fix up Neon data-processing instructions, ORing in the correct bits for
ARM mode or Thumb mode and moving the encoded bit 24 to bit 28. */
static void
neon_dp_fixup (struct arm_it* insn)
{
unsigned int i = insn->instruction;
insn->is_neon = 1;
if (thumb_mode)
{
/* The U bit is at bit 24 by default. Move to bit 28 in Thumb mode. */
if (i & (1 << 24))
i |= 1 << 28;
i &= ~(1 << 24);
i |= 0xef000000;
}
else
i |= 0xf2000000;
insn->instruction = i;
}
/* Turn a size (8, 16, 32, 64) into the respective bit number minus 3
(0, 1, 2, 3). */
static unsigned
neon_logbits (unsigned x)
{
return ffs (x) - 4;
}
#define LOW4(R) ((R) & 0xf)
#define HI1(R) (((R) >> 4) & 1)
/* Encode insns with bit pattern:
|28/24|23|22 |21 20|19 16|15 12|11 8|7|6|5|4|3 0|
| U |x |D |size | Rn | Rd |x x x x|N|Q|M|x| Rm |
SIZE is passed in bits. -1 means size field isn't changed, in case it has a
different meaning for some instruction. */
static void
neon_three_same (int isquad, int ubit, int size)
{
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg) << 16;
inst.instruction |= HI1 (inst.operands[1].reg) << 7;
inst.instruction |= LOW4 (inst.operands[2].reg);
inst.instruction |= HI1 (inst.operands[2].reg) << 5;
inst.instruction |= (isquad != 0) << 6;
inst.instruction |= (ubit != 0) << 24;
if (size != -1)
inst.instruction |= neon_logbits (size) << 20;
neon_dp_fixup (&inst);
}
/* Encode instructions of the form:
|28/24|23|22|21 20|19 18|17 16|15 12|11 7|6|5|4|3 0|
| U |x |D |x x |size |x x | Rd |x x x x x|Q|M|x| Rm |
Don't write size if SIZE == -1. */
static void
neon_two_same (int qbit, int ubit, int size)
{
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= (qbit != 0) << 6;
inst.instruction |= (ubit != 0) << 24;
if (size != -1)
inst.instruction |= neon_logbits (size) << 18;
neon_dp_fixup (&inst);
}
/* Neon instruction encoders, in approximate order of appearance. */
static void
do_neon_dyadic_i_su (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_SU_32 | N_KEY);
neon_three_same (neon_quad (rs), et.type == NT_unsigned, et.size);
}
static void
do_neon_dyadic_i64_su (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_SU_ALL | N_KEY);
neon_three_same (neon_quad (rs), et.type == NT_unsigned, et.size);
}
static void
neon_imm_shift (int write_ubit, int uval, int isquad, struct neon_type_el et,
unsigned immbits)
{
unsigned size = et.size >> 3;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= (isquad != 0) << 6;
inst.instruction |= immbits << 16;
inst.instruction |= (size >> 3) << 7;
inst.instruction |= (size & 0x7) << 19;
if (write_ubit)
inst.instruction |= (uval != 0) << 24;
neon_dp_fixup (&inst);
}
static void
do_neon_shl_imm (void)
{
if (!inst.operands[2].isreg)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs, N_EQK, N_KEY | N_I_ALL);
int imm = inst.operands[2].imm;
constraint (imm < 0 || (unsigned)imm >= et.size,
_("immediate out of range for shift"));
NEON_ENCODE (IMMED, inst);
neon_imm_shift (FALSE, 0, neon_quad (rs), et, imm);
}
else
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_SU_ALL | N_KEY, N_EQK | N_SGN);
unsigned int tmp;
/* VSHL/VQSHL 3-register variants have syntax such as:
vshl.xx Dd, Dm, Dn
whereas other 3-register operations encoded by neon_three_same have
syntax like:
vadd.xx Dd, Dn, Dm
(i.e. with Dn & Dm reversed). Swap operands[1].reg and operands[2].reg
here. */
tmp = inst.operands[2].reg;
inst.operands[2].reg = inst.operands[1].reg;
inst.operands[1].reg = tmp;
NEON_ENCODE (INTEGER, inst);
neon_three_same (neon_quad (rs), et.type == NT_unsigned, et.size);
}
}
static void
do_neon_qshl_imm (void)
{
if (!inst.operands[2].isreg)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs, N_EQK, N_SU_ALL | N_KEY);
int imm = inst.operands[2].imm;
constraint (imm < 0 || (unsigned)imm >= et.size,
_("immediate out of range for shift"));
NEON_ENCODE (IMMED, inst);
neon_imm_shift (TRUE, et.type == NT_unsigned, neon_quad (rs), et, imm);
}
else
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_SU_ALL | N_KEY, N_EQK | N_SGN);
unsigned int tmp;
/* See note in do_neon_shl_imm. */
tmp = inst.operands[2].reg;
inst.operands[2].reg = inst.operands[1].reg;
inst.operands[1].reg = tmp;
NEON_ENCODE (INTEGER, inst);
neon_three_same (neon_quad (rs), et.type == NT_unsigned, et.size);
}
}
static void
do_neon_rshl (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_SU_ALL | N_KEY);
unsigned int tmp;
tmp = inst.operands[2].reg;
inst.operands[2].reg = inst.operands[1].reg;
inst.operands[1].reg = tmp;
neon_three_same (neon_quad (rs), et.type == NT_unsigned, et.size);
}
static int
neon_cmode_for_logic_imm (unsigned immediate, unsigned *immbits, int size)
{
/* Handle .I8 pseudo-instructions. */
if (size == 8)
{
/* Unfortunately, this will make everything apart from zero out-of-range.
FIXME is this the intended semantics? There doesn't seem much point in
accepting .I8 if so. */
immediate |= immediate << 8;
size = 16;
}
if (size >= 32)
{
if (immediate == (immediate & 0x000000ff))
{
*immbits = immediate;
return 0x1;
}
else if (immediate == (immediate & 0x0000ff00))
{
*immbits = immediate >> 8;
return 0x3;
}
else if (immediate == (immediate & 0x00ff0000))
{
*immbits = immediate >> 16;
return 0x5;
}
else if (immediate == (immediate & 0xff000000))
{
*immbits = immediate >> 24;
return 0x7;
}
if ((immediate & 0xffff) != (immediate >> 16))
goto bad_immediate;
immediate &= 0xffff;
}
if (immediate == (immediate & 0x000000ff))
{
*immbits = immediate;
return 0x9;
}
else if (immediate == (immediate & 0x0000ff00))
{
*immbits = immediate >> 8;
return 0xb;
}
bad_immediate:
first_error (_("immediate value out of range"));
return FAIL;
}
static void
do_neon_logic (void)
{
if (inst.operands[2].present && inst.operands[2].isreg)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
neon_check_type (3, rs, N_IGNORE_TYPE);
/* U bit and size field were set as part of the bitmask. */
NEON_ENCODE (INTEGER, inst);
neon_three_same (neon_quad (rs), 0, -1);
}
else
{
const int three_ops_form = (inst.operands[2].present
&& !inst.operands[2].isreg);
const int immoperand = (three_ops_form ? 2 : 1);
enum neon_shape rs = (three_ops_form
? neon_select_shape (NS_DDI, NS_QQI, NS_NULL)
: neon_select_shape (NS_DI, NS_QI, NS_NULL));
struct neon_type_el et = neon_check_type (2, rs,
N_I8 | N_I16 | N_I32 | N_I64 | N_F32 | N_KEY, N_EQK);
enum neon_opc opcode = (enum neon_opc) inst.instruction & 0x0fffffff;
unsigned immbits;
int cmode;
if (et.type == NT_invtype)
return;
if (three_ops_form)
constraint (inst.operands[0].reg != inst.operands[1].reg,
_("first and second operands shall be the same register"));
NEON_ENCODE (IMMED, inst);
immbits = inst.operands[immoperand].imm;
if (et.size == 64)
{
/* .i64 is a pseudo-op, so the immediate must be a repeating
pattern. */
if (immbits != (inst.operands[immoperand].regisimm ?
inst.operands[immoperand].reg : 0))
{
/* Set immbits to an invalid constant. */
immbits = 0xdeadbeef;
}
}
switch (opcode)
{
case N_MNEM_vbic:
cmode = neon_cmode_for_logic_imm (immbits, &immbits, et.size);
break;
case N_MNEM_vorr:
cmode = neon_cmode_for_logic_imm (immbits, &immbits, et.size);
break;
case N_MNEM_vand:
/* Pseudo-instruction for VBIC. */
neon_invert_size (&immbits, 0, et.size);
cmode = neon_cmode_for_logic_imm (immbits, &immbits, et.size);
break;
case N_MNEM_vorn:
/* Pseudo-instruction for VORR. */
neon_invert_size (&immbits, 0, et.size);
cmode = neon_cmode_for_logic_imm (immbits, &immbits, et.size);
break;
default:
abort ();
}
if (cmode == FAIL)
return;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= cmode << 8;
neon_write_immbits (immbits);
neon_dp_fixup (&inst);
}
}
static void
do_neon_bitfield (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
neon_check_type (3, rs, N_IGNORE_TYPE);
neon_three_same (neon_quad (rs), 0, -1);
}
static void
neon_dyadic_misc (enum neon_el_type ubit_meaning, unsigned types,
unsigned destbits)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs, N_EQK | destbits, N_EQK,
types | N_KEY);
if (et.type == NT_float)
{
NEON_ENCODE (FLOAT, inst);
neon_three_same (neon_quad (rs), 0, -1);
}
else
{
NEON_ENCODE (INTEGER, inst);
neon_three_same (neon_quad (rs), et.type == ubit_meaning, et.size);
}
}
static void
do_neon_dyadic_if_su (void)
{
neon_dyadic_misc (NT_unsigned, N_SUF_32, 0);
}
static void
do_neon_dyadic_if_su_d (void)
{
/* This version only allow D registers, but that constraint is enforced during
operand parsing so we don't need to do anything extra here. */
neon_dyadic_misc (NT_unsigned, N_SUF_32, 0);
}
static void
do_neon_dyadic_if_i_d (void)
{
/* The "untyped" case can't happen. Do this to stop the "U" bit being
affected if we specify unsigned args. */
neon_dyadic_misc (NT_untyped, N_IF_32, 0);
}
enum vfp_or_neon_is_neon_bits
{
NEON_CHECK_CC = 1,
NEON_CHECK_ARCH = 2,
NEON_CHECK_ARCH8 = 4
};
/* Call this function if an instruction which may have belonged to the VFP or
Neon instruction sets, but turned out to be a Neon instruction (due to the
operand types involved, etc.). We have to check and/or fix-up a couple of
things:
- Make sure the user hasn't attempted to make a Neon instruction
conditional.
- Alter the value in the condition code field if necessary.
- Make sure that the arch supports Neon instructions.
Which of these operations take place depends on bits from enum
vfp_or_neon_is_neon_bits.
WARNING: This function has side effects! If NEON_CHECK_CC is used and the
current instruction's condition is COND_ALWAYS, the condition field is
changed to inst.uncond_value. This is necessary because instructions shared
between VFP and Neon may be conditional for the VFP variants only, and the
unconditional Neon version must have, e.g., 0xF in the condition field. */
static int
vfp_or_neon_is_neon (unsigned check)
{
/* Conditions are always legal in Thumb mode (IT blocks). */
if (!thumb_mode && (check & NEON_CHECK_CC))
{
if (inst.cond != COND_ALWAYS)
{
first_error (_(BAD_COND));
return FAIL;
}
if (inst.uncond_value != -1)
inst.instruction |= inst.uncond_value << 28;
}
if ((check & NEON_CHECK_ARCH)
&& !mark_feature_used (&fpu_neon_ext_v1))
{
first_error (_(BAD_FPU));
return FAIL;
}
if ((check & NEON_CHECK_ARCH8)
&& !mark_feature_used (&fpu_neon_ext_armv8))
{
first_error (_(BAD_FPU));
return FAIL;
}
return SUCCESS;
}
static void
do_neon_addsub_if_i (void)
{
if (try_vfp_nsyn (3, do_vfp_nsyn_add_sub) == SUCCESS)
return;
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
/* The "untyped" case can't happen. Do this to stop the "U" bit being
affected if we specify unsigned args. */
neon_dyadic_misc (NT_untyped, N_IF_32 | N_I64, 0);
}
/* Swaps operands 1 and 2. If operand 1 (optional arg) was omitted, we want the
result to be:
V<op> A,B (A is operand 0, B is operand 2)
to mean:
V<op> A,B,A
not:
V<op> A,B,B
so handle that case specially. */
static void
neon_exchange_operands (void)
{
void *scratch = alloca (sizeof (inst.operands[0]));
if (inst.operands[1].present)
{
/* Swap operands[1] and operands[2]. */
memcpy (scratch, &inst.operands[1], sizeof (inst.operands[0]));
inst.operands[1] = inst.operands[2];
memcpy (&inst.operands[2], scratch, sizeof (inst.operands[0]));
}
else
{
inst.operands[1] = inst.operands[2];
inst.operands[2] = inst.operands[0];
}
}
static void
neon_compare (unsigned regtypes, unsigned immtypes, int invert)
{
if (inst.operands[2].isreg)
{
if (invert)
neon_exchange_operands ();
neon_dyadic_misc (NT_unsigned, regtypes, N_SIZ);
}
else
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK | N_SIZ, immtypes | N_KEY);
NEON_ENCODE (IMMED, inst);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= (et.type == NT_float) << 10;
inst.instruction |= neon_logbits (et.size) << 18;
neon_dp_fixup (&inst);
}
}
static void
do_neon_cmp (void)
{
neon_compare (N_SUF_32, N_S8 | N_S16 | N_S32 | N_F32, FALSE);
}
static void
do_neon_cmp_inv (void)
{
neon_compare (N_SUF_32, N_S8 | N_S16 | N_S32 | N_F32, TRUE);
}
static void
do_neon_ceq (void)
{
neon_compare (N_IF_32, N_IF_32, FALSE);
}
/* For multiply instructions, we have the possibility of 16-bit or 32-bit
scalars, which are encoded in 5 bits, M : Rm.
For 16-bit scalars, the register is encoded in Rm[2:0] and the index in
M:Rm[3], and for 32-bit scalars, the register is encoded in Rm[3:0] and the
index in M. */
static unsigned
neon_scalar_for_mul (unsigned scalar, unsigned elsize)
{
unsigned regno = NEON_SCALAR_REG (scalar);
unsigned elno = NEON_SCALAR_INDEX (scalar);
switch (elsize)
{
case 16:
if (regno > 7 || elno > 3)
goto bad_scalar;
return regno | (elno << 3);
case 32:
if (regno > 15 || elno > 1)
goto bad_scalar;
return regno | (elno << 4);
default:
bad_scalar:
first_error (_("scalar out of range for multiply instruction"));
}
return 0;
}
/* Encode multiply / multiply-accumulate scalar instructions. */
static void
neon_mul_mac (struct neon_type_el et, int ubit)
{
unsigned scalar;
/* Give a more helpful error message if we have an invalid type. */
if (et.type == NT_invtype)
return;
scalar = neon_scalar_for_mul (inst.operands[2].reg, et.size);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg) << 16;
inst.instruction |= HI1 (inst.operands[1].reg) << 7;
inst.instruction |= LOW4 (scalar);
inst.instruction |= HI1 (scalar) << 5;
inst.instruction |= (et.type == NT_float) << 8;
inst.instruction |= neon_logbits (et.size) << 20;
inst.instruction |= (ubit != 0) << 24;
neon_dp_fixup (&inst);
}
static void
do_neon_mac_maybe_scalar (void)
{
if (try_vfp_nsyn (3, do_vfp_nsyn_mla_mls) == SUCCESS)
return;
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
if (inst.operands[2].isscalar)
{
enum neon_shape rs = neon_select_shape (NS_DDS, NS_QQS, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_I16 | N_I32 | N_F32 | N_KEY);
NEON_ENCODE (SCALAR, inst);
neon_mul_mac (et, neon_quad (rs));
}
else
{
/* The "untyped" case can't happen. Do this to stop the "U" bit being
affected if we specify unsigned args. */
neon_dyadic_misc (NT_untyped, N_IF_32, 0);
}
}
static void
do_neon_fmac (void)
{
if (try_vfp_nsyn (3, do_vfp_nsyn_fma_fms) == SUCCESS)
return;
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
neon_dyadic_misc (NT_untyped, N_IF_32, 0);
}
static void
do_neon_tst (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_8 | N_16 | N_32 | N_KEY);
neon_three_same (neon_quad (rs), 0, et.size);
}
/* VMUL with 3 registers allows the P8 type. The scalar version supports the
same types as the MAC equivalents. The polynomial type for this instruction
is encoded the same as the integer type. */
static void
do_neon_mul (void)
{
if (try_vfp_nsyn (3, do_vfp_nsyn_mul) == SUCCESS)
return;
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
if (inst.operands[2].isscalar)
do_neon_mac_maybe_scalar ();
else
neon_dyadic_misc (NT_poly, N_I8 | N_I16 | N_I32 | N_F32 | N_P8, 0);
}
static void
do_neon_qdmulh (void)
{
if (inst.operands[2].isscalar)
{
enum neon_shape rs = neon_select_shape (NS_DDS, NS_QQS, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_S16 | N_S32 | N_KEY);
NEON_ENCODE (SCALAR, inst);
neon_mul_mac (et, neon_quad (rs));
}
else
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_S16 | N_S32 | N_KEY);
NEON_ENCODE (INTEGER, inst);
/* The U bit (rounding) comes from bit mask. */
neon_three_same (neon_quad (rs), 0, et.size);
}
}
static void
do_neon_fcmp_absolute (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
neon_check_type (3, rs, N_EQK, N_EQK, N_F32 | N_KEY);
/* Size field comes from bit mask. */
neon_three_same (neon_quad (rs), 1, -1);
}
static void
do_neon_fcmp_absolute_inv (void)
{
neon_exchange_operands ();
do_neon_fcmp_absolute ();
}
static void
do_neon_step (void)
{
enum neon_shape rs = neon_select_shape (NS_DDD, NS_QQQ, NS_NULL);
neon_check_type (3, rs, N_EQK, N_EQK, N_F32 | N_KEY);
neon_three_same (neon_quad (rs), 0, -1);
}
static void
do_neon_abs_neg (void)
{
enum neon_shape rs;
struct neon_type_el et;
if (try_vfp_nsyn (2, do_vfp_nsyn_abs_neg) == SUCCESS)
return;
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
et = neon_check_type (2, rs, N_EQK, N_S8 | N_S16 | N_S32 | N_F32 | N_KEY);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= (et.type == NT_float) << 10;
inst.instruction |= neon_logbits (et.size) << 18;
neon_dp_fixup (&inst);
}
static void
do_neon_sli (void)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_8 | N_16 | N_32 | N_64 | N_KEY);
int imm = inst.operands[2].imm;
constraint (imm < 0 || (unsigned)imm >= et.size,
_("immediate out of range for insert"));
neon_imm_shift (FALSE, 0, neon_quad (rs), et, imm);
}
static void
do_neon_sri (void)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_8 | N_16 | N_32 | N_64 | N_KEY);
int imm = inst.operands[2].imm;
constraint (imm < 1 || (unsigned)imm > et.size,
_("immediate out of range for insert"));
neon_imm_shift (FALSE, 0, neon_quad (rs), et, et.size - imm);
}
static void
do_neon_qshlu_imm (void)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK | N_UNS, N_S8 | N_S16 | N_S32 | N_S64 | N_KEY);
int imm = inst.operands[2].imm;
constraint (imm < 0 || (unsigned)imm >= et.size,
_("immediate out of range for shift"));
/* Only encodes the 'U present' variant of the instruction.
In this case, signed types have OP (bit 8) set to 0.
Unsigned types have OP set to 1. */
inst.instruction |= (et.type == NT_unsigned) << 8;
/* The rest of the bits are the same as other immediate shifts. */
neon_imm_shift (FALSE, 0, neon_quad (rs), et, imm);
}
static void
do_neon_qmovn (void)
{
struct neon_type_el et = neon_check_type (2, NS_DQ,
N_EQK | N_HLF, N_SU_16_64 | N_KEY);
/* Saturating move where operands can be signed or unsigned, and the
destination has the same signedness. */
NEON_ENCODE (INTEGER, inst);
if (et.type == NT_unsigned)
inst.instruction |= 0xc0;
else
inst.instruction |= 0x80;
neon_two_same (0, 1, et.size / 2);
}
static void
do_neon_qmovun (void)
{
struct neon_type_el et = neon_check_type (2, NS_DQ,
N_EQK | N_HLF | N_UNS, N_S16 | N_S32 | N_S64 | N_KEY);
/* Saturating move with unsigned results. Operands must be signed. */
NEON_ENCODE (INTEGER, inst);
neon_two_same (0, 1, et.size / 2);
}
static void
do_neon_rshift_sat_narrow (void)
{
/* FIXME: Types for narrowing. If operands are signed, results can be signed
or unsigned. If operands are unsigned, results must also be unsigned. */
struct neon_type_el et = neon_check_type (2, NS_DQI,
N_EQK | N_HLF, N_SU_16_64 | N_KEY);
int imm = inst.operands[2].imm;
/* This gets the bounds check, size encoding and immediate bits calculation
right. */
et.size /= 2;
/* VQ{R}SHRN.I<size> <Dd>, <Qm>, #0 is a synonym for
VQMOVN.I<size> <Dd>, <Qm>. */
if (imm == 0)
{
inst.operands[2].present = 0;
inst.instruction = N_MNEM_vqmovn;
do_neon_qmovn ();
return;
}
constraint (imm < 1 || (unsigned)imm > et.size,
_("immediate out of range"));
neon_imm_shift (TRUE, et.type == NT_unsigned, 0, et, et.size - imm);
}
static void
do_neon_rshift_sat_narrow_u (void)
{
/* FIXME: Types for narrowing. If operands are signed, results can be signed
or unsigned. If operands are unsigned, results must also be unsigned. */
struct neon_type_el et = neon_check_type (2, NS_DQI,
N_EQK | N_HLF | N_UNS, N_S16 | N_S32 | N_S64 | N_KEY);
int imm = inst.operands[2].imm;
/* This gets the bounds check, size encoding and immediate bits calculation
right. */
et.size /= 2;
/* VQSHRUN.I<size> <Dd>, <Qm>, #0 is a synonym for
VQMOVUN.I<size> <Dd>, <Qm>. */
if (imm == 0)
{
inst.operands[2].present = 0;
inst.instruction = N_MNEM_vqmovun;
do_neon_qmovun ();
return;
}
constraint (imm < 1 || (unsigned)imm > et.size,
_("immediate out of range"));
/* FIXME: The manual is kind of unclear about what value U should have in
VQ{R}SHRUN instructions, but U=0, op=0 definitely encodes VRSHR, so it
must be 1. */
neon_imm_shift (TRUE, 1, 0, et, et.size - imm);
}
static void
do_neon_movn (void)
{
struct neon_type_el et = neon_check_type (2, NS_DQ,
N_EQK | N_HLF, N_I16 | N_I32 | N_I64 | N_KEY);
NEON_ENCODE (INTEGER, inst);
neon_two_same (0, 1, et.size / 2);
}
static void
do_neon_rshift_narrow (void)
{
struct neon_type_el et = neon_check_type (2, NS_DQI,
N_EQK | N_HLF, N_I16 | N_I32 | N_I64 | N_KEY);
int imm = inst.operands[2].imm;
/* This gets the bounds check, size encoding and immediate bits calculation
right. */
et.size /= 2;
/* If immediate is zero then we are a pseudo-instruction for
VMOVN.I<size> <Dd>, <Qm> */
if (imm == 0)
{
inst.operands[2].present = 0;
inst.instruction = N_MNEM_vmovn;
do_neon_movn ();
return;
}
constraint (imm < 1 || (unsigned)imm > et.size,
_("immediate out of range for narrowing operation"));
neon_imm_shift (FALSE, 0, 0, et, et.size - imm);
}
static void
do_neon_shll (void)
{
/* FIXME: Type checking when lengthening. */
struct neon_type_el et = neon_check_type (2, NS_QDI,
N_EQK | N_DBL, N_I8 | N_I16 | N_I32 | N_KEY);
unsigned imm = inst.operands[2].imm;
if (imm == et.size)
{
/* Maximum shift variant. */
NEON_ENCODE (INTEGER, inst);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_logbits (et.size) << 18;
neon_dp_fixup (&inst);
}
else
{
/* A more-specific type check for non-max versions. */
et = neon_check_type (2, NS_QDI,
N_EQK | N_DBL, N_SU_32 | N_KEY);
NEON_ENCODE (IMMED, inst);
neon_imm_shift (TRUE, et.type == NT_unsigned, 0, et, imm);
}
}
/* Check the various types for the VCVT instruction, and return which version
the current instruction is. */
#define CVT_FLAVOUR_VAR \
CVT_VAR (s32_f32, N_S32, N_F32, whole_reg, "ftosls", "ftosis", "ftosizs") \
CVT_VAR (u32_f32, N_U32, N_F32, whole_reg, "ftouls", "ftouis", "ftouizs") \
CVT_VAR (f32_s32, N_F32, N_S32, whole_reg, "fsltos", "fsitos", NULL) \
CVT_VAR (f32_u32, N_F32, N_U32, whole_reg, "fultos", "fuitos", NULL) \
/* Half-precision conversions. */ \
CVT_VAR (f32_f16, N_F32, N_F16, whole_reg, NULL, NULL, NULL) \
CVT_VAR (f16_f32, N_F16, N_F32, whole_reg, NULL, NULL, NULL) \
/* VFP instructions. */ \
CVT_VAR (f32_f64, N_F32, N_F64, N_VFP, NULL, "fcvtsd", NULL) \
CVT_VAR (f64_f32, N_F64, N_F32, N_VFP, NULL, "fcvtds", NULL) \
CVT_VAR (s32_f64, N_S32, N_F64 | key, N_VFP, "ftosld", "ftosid", "ftosizd") \
CVT_VAR (u32_f64, N_U32, N_F64 | key, N_VFP, "ftould", "ftouid", "ftouizd") \
CVT_VAR (f64_s32, N_F64 | key, N_S32, N_VFP, "fsltod", "fsitod", NULL) \
CVT_VAR (f64_u32, N_F64 | key, N_U32, N_VFP, "fultod", "fuitod", NULL) \
/* VFP instructions with bitshift. */ \
CVT_VAR (f32_s16, N_F32 | key, N_S16, N_VFP, "fshtos", NULL, NULL) \
CVT_VAR (f32_u16, N_F32 | key, N_U16, N_VFP, "fuhtos", NULL, NULL) \
CVT_VAR (f64_s16, N_F64 | key, N_S16, N_VFP, "fshtod", NULL, NULL) \
CVT_VAR (f64_u16, N_F64 | key, N_U16, N_VFP, "fuhtod", NULL, NULL) \
CVT_VAR (s16_f32, N_S16, N_F32 | key, N_VFP, "ftoshs", NULL, NULL) \
CVT_VAR (u16_f32, N_U16, N_F32 | key, N_VFP, "ftouhs", NULL, NULL) \
CVT_VAR (s16_f64, N_S16, N_F64 | key, N_VFP, "ftoshd", NULL, NULL) \
CVT_VAR (u16_f64, N_U16, N_F64 | key, N_VFP, "ftouhd", NULL, NULL)
#define CVT_VAR(C, X, Y, R, BSN, CN, ZN) \
neon_cvt_flavour_##C,
/* The different types of conversions we can do. */
enum neon_cvt_flavour
{
CVT_FLAVOUR_VAR
neon_cvt_flavour_invalid,
neon_cvt_flavour_first_fp = neon_cvt_flavour_f32_f64
};
#undef CVT_VAR
static enum neon_cvt_flavour
get_neon_cvt_flavour (enum neon_shape rs)
{
#define CVT_VAR(C,X,Y,R,BSN,CN,ZN) \
et = neon_check_type (2, rs, (R) | (X), (R) | (Y)); \
if (et.type != NT_invtype) \
{ \
inst.error = NULL; \
return (neon_cvt_flavour_##C); \
}
struct neon_type_el et;
unsigned whole_reg = (rs == NS_FFI || rs == NS_FD || rs == NS_DF
|| rs == NS_FF) ? N_VFP : 0;
/* The instruction versions which take an immediate take one register
argument, which is extended to the width of the full register. Thus the
"source" and "destination" registers must have the same width. Hack that
here by making the size equal to the key (wider, in this case) operand. */
unsigned key = (rs == NS_QQI || rs == NS_DDI || rs == NS_FFI) ? N_KEY : 0;
CVT_FLAVOUR_VAR;
return neon_cvt_flavour_invalid;
#undef CVT_VAR
}
enum neon_cvt_mode
{
neon_cvt_mode_a,
neon_cvt_mode_n,
neon_cvt_mode_p,
neon_cvt_mode_m,
neon_cvt_mode_z,
neon_cvt_mode_x,
neon_cvt_mode_r
};
/* Neon-syntax VFP conversions. */
static void
do_vfp_nsyn_cvt (enum neon_shape rs, enum neon_cvt_flavour flavour)
{
const char *opname = 0;
if (rs == NS_DDI || rs == NS_QQI || rs == NS_FFI)
{
/* Conversions with immediate bitshift. */
const char *enc[] =
{
#define CVT_VAR(C,A,B,R,BSN,CN,ZN) BSN,
CVT_FLAVOUR_VAR
NULL
#undef CVT_VAR
};
if (flavour < (int) ARRAY_SIZE (enc))
{
opname = enc[flavour];
constraint (inst.operands[0].reg != inst.operands[1].reg,
_("operands 0 and 1 must be the same register"));
inst.operands[1] = inst.operands[2];
memset (&inst.operands[2], '\0', sizeof (inst.operands[2]));
}
}
else
{
/* Conversions without bitshift. */
const char *enc[] =
{
#define CVT_VAR(C,A,B,R,BSN,CN,ZN) CN,
CVT_FLAVOUR_VAR
NULL
#undef CVT_VAR
};
if (flavour < (int) ARRAY_SIZE (enc))
opname = enc[flavour];
}
if (opname)
do_vfp_nsyn_opcode (opname);
}
static void
do_vfp_nsyn_cvtz (void)
{
enum neon_shape rs = neon_select_shape (NS_FF, NS_FD, NS_NULL);
enum neon_cvt_flavour flavour = get_neon_cvt_flavour (rs);
const char *enc[] =
{
#define CVT_VAR(C,A,B,R,BSN,CN,ZN) ZN,
CVT_FLAVOUR_VAR
NULL
#undef CVT_VAR
};
if (flavour < (int) ARRAY_SIZE (enc) && enc[flavour])
do_vfp_nsyn_opcode (enc[flavour]);
}
static void
do_vfp_nsyn_cvt_fpv8 (enum neon_cvt_flavour flavour,
enum neon_cvt_mode mode)
{
int sz, op;
int rm;
/* Targets like FPv5-SP-D16 don't support FP v8 instructions with
D register operands. */
if (flavour == neon_cvt_flavour_s32_f64
|| flavour == neon_cvt_flavour_u32_f64)
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_armv8),
_(BAD_FPU));
set_it_insn_type (OUTSIDE_IT_INSN);
switch (flavour)
{
case neon_cvt_flavour_s32_f64:
sz = 1;
op = 1;
break;
case neon_cvt_flavour_s32_f32:
sz = 0;
op = 1;
break;
case neon_cvt_flavour_u32_f64:
sz = 1;
op = 0;
break;
case neon_cvt_flavour_u32_f32:
sz = 0;
op = 0;
break;
default:
first_error (_("invalid instruction shape"));
return;
}
switch (mode)
{
case neon_cvt_mode_a: rm = 0; break;
case neon_cvt_mode_n: rm = 1; break;
case neon_cvt_mode_p: rm = 2; break;
case neon_cvt_mode_m: rm = 3; break;
default: first_error (_("invalid rounding mode")); return;
}
NEON_ENCODE (FPV8, inst);
encode_arm_vfp_reg (inst.operands[0].reg, VFP_REG_Sd);
encode_arm_vfp_reg (inst.operands[1].reg, sz == 1 ? VFP_REG_Dm : VFP_REG_Sm);
inst.instruction |= sz << 8;
inst.instruction |= op << 7;
inst.instruction |= rm << 16;
inst.instruction |= 0xf0000000;
inst.is_neon = TRUE;
}
static void
do_neon_cvt_1 (enum neon_cvt_mode mode)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_FFI, NS_DD, NS_QQ,
NS_FD, NS_DF, NS_FF, NS_QD, NS_DQ, NS_NULL);
enum neon_cvt_flavour flavour = get_neon_cvt_flavour (rs);
/* PR11109: Handle round-to-zero for VCVT conversions. */
if (mode == neon_cvt_mode_z
&& ARM_CPU_HAS_FEATURE (cpu_variant, fpu_arch_vfp_v2)
&& (flavour == neon_cvt_flavour_s32_f32
|| flavour == neon_cvt_flavour_u32_f32
|| flavour == neon_cvt_flavour_s32_f64
|| flavour == neon_cvt_flavour_u32_f64)
&& (rs == NS_FD || rs == NS_FF))
{
do_vfp_nsyn_cvtz ();
return;
}
/* VFP rather than Neon conversions. */
if (flavour >= neon_cvt_flavour_first_fp)
{
if (mode == neon_cvt_mode_x || mode == neon_cvt_mode_z)
do_vfp_nsyn_cvt (rs, flavour);
else
do_vfp_nsyn_cvt_fpv8 (flavour, mode);
return;
}
switch (rs)
{
case NS_DDI:
case NS_QQI:
{
unsigned immbits;
unsigned enctab[] = { 0x0000100, 0x1000100, 0x0, 0x1000000 };
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
/* Fixed-point conversion with #0 immediate is encoded as an
integer conversion. */
if (inst.operands[2].present && inst.operands[2].imm == 0)
goto int_encode;
immbits = 32 - inst.operands[2].imm;
NEON_ENCODE (IMMED, inst);
if (flavour != neon_cvt_flavour_invalid)
inst.instruction |= enctab[flavour];
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= 1 << 21;
inst.instruction |= immbits << 16;
neon_dp_fixup (&inst);
}
break;
case NS_DD:
case NS_QQ:
if (mode != neon_cvt_mode_x && mode != neon_cvt_mode_z)
{
NEON_ENCODE (FLOAT, inst);
set_it_insn_type (OUTSIDE_IT_INSN);
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH8) == FAIL)
return;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= (flavour == neon_cvt_flavour_u32_f32) << 7;
inst.instruction |= mode << 8;
if (thumb_mode)
inst.instruction |= 0xfc000000;
else
inst.instruction |= 0xf0000000;
}
else
{
int_encode:
{
unsigned enctab[] = { 0x100, 0x180, 0x0, 0x080 };
NEON_ENCODE (INTEGER, inst);
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
if (flavour != neon_cvt_flavour_invalid)
inst.instruction |= enctab[flavour];
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= 2 << 18;
neon_dp_fixup (&inst);
}
}
break;
/* Half-precision conversions for Advanced SIMD -- neon. */
case NS_QD:
case NS_DQ:
if ((rs == NS_DQ)
&& (inst.vectype.el[0].size != 16 || inst.vectype.el[1].size != 32))
{
as_bad (_("operand size must match register width"));
break;
}
if ((rs == NS_QD)
&& ((inst.vectype.el[0].size != 32 || inst.vectype.el[1].size != 16)))
{
as_bad (_("operand size must match register width"));
break;
}
if (rs == NS_DQ)
inst.instruction = 0x3b60600;
else
inst.instruction = 0x3b60700;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
neon_dp_fixup (&inst);
break;
default:
/* Some VFP conversions go here (s32 <-> f32, u32 <-> f32). */
if (mode == neon_cvt_mode_x || mode == neon_cvt_mode_z)
do_vfp_nsyn_cvt (rs, flavour);
else
do_vfp_nsyn_cvt_fpv8 (flavour, mode);
}
}
static void
do_neon_cvtr (void)
{
do_neon_cvt_1 (neon_cvt_mode_x);
}
static void
do_neon_cvt (void)
{
do_neon_cvt_1 (neon_cvt_mode_z);
}
static void
do_neon_cvta (void)
{
do_neon_cvt_1 (neon_cvt_mode_a);
}
static void
do_neon_cvtn (void)
{
do_neon_cvt_1 (neon_cvt_mode_n);
}
static void
do_neon_cvtp (void)
{
do_neon_cvt_1 (neon_cvt_mode_p);
}
static void
do_neon_cvtm (void)
{
do_neon_cvt_1 (neon_cvt_mode_m);
}
static void
do_neon_cvttb_2 (bfd_boolean t, bfd_boolean to, bfd_boolean is_double)
{
if (is_double)
mark_feature_used (&fpu_vfp_ext_armv8);
encode_arm_vfp_reg (inst.operands[0].reg,
(is_double && !to) ? VFP_REG_Dd : VFP_REG_Sd);
encode_arm_vfp_reg (inst.operands[1].reg,
(is_double && to) ? VFP_REG_Dm : VFP_REG_Sm);
inst.instruction |= to ? 0x10000 : 0;
inst.instruction |= t ? 0x80 : 0;
inst.instruction |= is_double ? 0x100 : 0;
do_vfp_cond_or_thumb ();
}
static void
do_neon_cvttb_1 (bfd_boolean t)
{
enum neon_shape rs = neon_select_shape (NS_FF, NS_FD, NS_DF, NS_NULL);
if (rs == NS_NULL)
return;
else if (neon_check_type (2, rs, N_F16, N_F32 | N_VFP).type != NT_invtype)
{
inst.error = NULL;
do_neon_cvttb_2 (t, /*to=*/TRUE, /*is_double=*/FALSE);
}
else if (neon_check_type (2, rs, N_F32 | N_VFP, N_F16).type != NT_invtype)
{
inst.error = NULL;
do_neon_cvttb_2 (t, /*to=*/FALSE, /*is_double=*/FALSE);
}
else if (neon_check_type (2, rs, N_F16, N_F64 | N_VFP).type != NT_invtype)
{
/* The VCVTB and VCVTT instructions with D-register operands
don't work for SP only targets. */
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_armv8),
_(BAD_FPU));
inst.error = NULL;
do_neon_cvttb_2 (t, /*to=*/TRUE, /*is_double=*/TRUE);
}
else if (neon_check_type (2, rs, N_F64 | N_VFP, N_F16).type != NT_invtype)
{
/* The VCVTB and VCVTT instructions with D-register operands
don't work for SP only targets. */
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_armv8),
_(BAD_FPU));
inst.error = NULL;
do_neon_cvttb_2 (t, /*to=*/FALSE, /*is_double=*/TRUE);
}
else
return;
}
static void
do_neon_cvtb (void)
{
do_neon_cvttb_1 (FALSE);
}
static void
do_neon_cvtt (void)
{
do_neon_cvttb_1 (TRUE);
}
static void
neon_move_immediate (void)
{
enum neon_shape rs = neon_select_shape (NS_DI, NS_QI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_I8 | N_I16 | N_I32 | N_I64 | N_F32 | N_KEY, N_EQK);
unsigned immlo, immhi = 0, immbits;
int op, cmode, float_p;
constraint (et.type == NT_invtype,
_("operand size must be specified for immediate VMOV"));
/* We start out as an MVN instruction if OP = 1, MOV otherwise. */
op = (inst.instruction & (1 << 5)) != 0;
immlo = inst.operands[1].imm;
if (inst.operands[1].regisimm)
immhi = inst.operands[1].reg;
constraint (et.size < 32 && (immlo & ~((1 << et.size) - 1)) != 0,
_("immediate has bits set outside the operand size"));
float_p = inst.operands[1].immisfloat;
if ((cmode = neon_cmode_for_move_imm (immlo, immhi, float_p, &immbits, &op,
et.size, et.type)) == FAIL)
{
/* Invert relevant bits only. */
neon_invert_size (&immlo, &immhi, et.size);
/* Flip from VMOV/VMVN to VMVN/VMOV. Some immediate types are unavailable
with one or the other; those cases are caught by
neon_cmode_for_move_imm. */
op = !op;
if ((cmode = neon_cmode_for_move_imm (immlo, immhi, float_p, &immbits,
&op, et.size, et.type)) == FAIL)
{
first_error (_("immediate out of range"));
return;
}
}
inst.instruction &= ~(1 << 5);
inst.instruction |= op << 5;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= cmode << 8;
neon_write_immbits (immbits);
}
static void
do_neon_mvn (void)
{
if (inst.operands[1].isreg)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
NEON_ENCODE (INTEGER, inst);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
}
else
{
NEON_ENCODE (IMMED, inst);
neon_move_immediate ();
}
neon_dp_fixup (&inst);
}
/* Encode instructions of form:
|28/24|23|22|21 20|19 16|15 12|11 8|7|6|5|4|3 0|
| U |x |D |size | Rn | Rd |x x x x|N|x|M|x| Rm | */
static void
neon_mixed_length (struct neon_type_el et, unsigned size)
{
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg) << 16;
inst.instruction |= HI1 (inst.operands[1].reg) << 7;
inst.instruction |= LOW4 (inst.operands[2].reg);
inst.instruction |= HI1 (inst.operands[2].reg) << 5;
inst.instruction |= (et.type == NT_unsigned) << 24;
inst.instruction |= neon_logbits (size) << 20;
neon_dp_fixup (&inst);
}
static void
do_neon_dyadic_long (void)
{
/* FIXME: Type checking for lengthening op. */
struct neon_type_el et = neon_check_type (3, NS_QDD,
N_EQK | N_DBL, N_EQK, N_SU_32 | N_KEY);
neon_mixed_length (et, et.size);
}
static void
do_neon_abal (void)
{
struct neon_type_el et = neon_check_type (3, NS_QDD,
N_EQK | N_INT | N_DBL, N_EQK, N_SU_32 | N_KEY);
neon_mixed_length (et, et.size);
}
static void
neon_mac_reg_scalar_long (unsigned regtypes, unsigned scalartypes)
{
if (inst.operands[2].isscalar)
{
struct neon_type_el et = neon_check_type (3, NS_QDS,
N_EQK | N_DBL, N_EQK, regtypes | N_KEY);
NEON_ENCODE (SCALAR, inst);
neon_mul_mac (et, et.type == NT_unsigned);
}
else
{
struct neon_type_el et = neon_check_type (3, NS_QDD,
N_EQK | N_DBL, N_EQK, scalartypes | N_KEY);
NEON_ENCODE (INTEGER, inst);
neon_mixed_length (et, et.size);
}
}
static void
do_neon_mac_maybe_scalar_long (void)
{
neon_mac_reg_scalar_long (N_S16 | N_S32 | N_U16 | N_U32, N_SU_32);
}
static void
do_neon_dyadic_wide (void)
{
struct neon_type_el et = neon_check_type (3, NS_QQD,
N_EQK | N_DBL, N_EQK | N_DBL, N_SU_32 | N_KEY);
neon_mixed_length (et, et.size);
}
static void
do_neon_dyadic_narrow (void)
{
struct neon_type_el et = neon_check_type (3, NS_QDD,
N_EQK | N_DBL, N_EQK, N_I16 | N_I32 | N_I64 | N_KEY);
/* Operand sign is unimportant, and the U bit is part of the opcode,
so force the operand type to integer. */
et.type = NT_integer;
neon_mixed_length (et, et.size / 2);
}
static void
do_neon_mul_sat_scalar_long (void)
{
neon_mac_reg_scalar_long (N_S16 | N_S32, N_S16 | N_S32);
}
static void
do_neon_vmull (void)
{
if (inst.operands[2].isscalar)
do_neon_mac_maybe_scalar_long ();
else
{
struct neon_type_el et = neon_check_type (3, NS_QDD,
N_EQK | N_DBL, N_EQK, N_SU_32 | N_P8 | N_P64 | N_KEY);
if (et.type == NT_poly)
NEON_ENCODE (POLY, inst);
else
NEON_ENCODE (INTEGER, inst);
/* For polynomial encoding the U bit must be zero, and the size must
be 8 (encoded as 0b00) or, on ARMv8 or later 64 (encoded, non
obviously, as 0b10). */
if (et.size == 64)
{
/* Check we're on the correct architecture. */
if (!mark_feature_used (&fpu_crypto_ext_armv8))
inst.error =
_("Instruction form not available on this architecture.");
et.size = 32;
}
neon_mixed_length (et, et.size);
}
}
static void
do_neon_ext (void)
{
enum neon_shape rs = neon_select_shape (NS_DDDI, NS_QQQI, NS_NULL);
struct neon_type_el et = neon_check_type (3, rs,
N_EQK, N_EQK, N_8 | N_16 | N_32 | N_64 | N_KEY);
unsigned imm = (inst.operands[3].imm * et.size) / 8;
constraint (imm >= (unsigned) (neon_quad (rs) ? 16 : 8),
_("shift out of range"));
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg) << 16;
inst.instruction |= HI1 (inst.operands[1].reg) << 7;
inst.instruction |= LOW4 (inst.operands[2].reg);
inst.instruction |= HI1 (inst.operands[2].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= imm << 8;
neon_dp_fixup (&inst);
}
static void
do_neon_rev (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_8 | N_16 | N_32 | N_KEY);
unsigned op = (inst.instruction >> 7) & 3;
/* N (width of reversed regions) is encoded as part of the bitmask. We
extract it here to check the elements to be reversed are smaller.
Otherwise we'd get a reserved instruction. */
unsigned elsize = (op == 2) ? 16 : (op == 1) ? 32 : (op == 0) ? 64 : 0;
gas_assert (elsize != 0);
constraint (et.size >= elsize,
_("elements must be smaller than reversal region"));
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_dup (void)
{
if (inst.operands[1].isscalar)
{
enum neon_shape rs = neon_select_shape (NS_DS, NS_QS, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_8 | N_16 | N_32 | N_KEY);
unsigned sizebits = et.size >> 3;
unsigned dm = NEON_SCALAR_REG (inst.operands[1].reg);
int logsize = neon_logbits (et.size);
unsigned x = NEON_SCALAR_INDEX (inst.operands[1].reg) << logsize;
if (vfp_or_neon_is_neon (NEON_CHECK_CC) == FAIL)
return;
NEON_ENCODE (SCALAR, inst);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (dm);
inst.instruction |= HI1 (dm) << 5;
inst.instruction |= neon_quad (rs) << 6;
inst.instruction |= x << 17;
inst.instruction |= sizebits << 16;
neon_dp_fixup (&inst);
}
else
{
enum neon_shape rs = neon_select_shape (NS_DR, NS_QR, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_8 | N_16 | N_32 | N_KEY, N_EQK);
/* Duplicate ARM register to lanes of vector. */
NEON_ENCODE (ARMREG, inst);
switch (et.size)
{
case 8: inst.instruction |= 0x400000; break;
case 16: inst.instruction |= 0x000020; break;
case 32: inst.instruction |= 0x000000; break;
default: break;
}
inst.instruction |= LOW4 (inst.operands[1].reg) << 12;
inst.instruction |= LOW4 (inst.operands[0].reg) << 16;
inst.instruction |= HI1 (inst.operands[0].reg) << 7;
inst.instruction |= neon_quad (rs) << 21;
/* The encoding for this instruction is identical for the ARM and Thumb
variants, except for the condition field. */
do_vfp_cond_or_thumb ();
}
}
/* VMOV has particularly many variations. It can be one of:
0. VMOV<c><q> <Qd>, <Qm>
1. VMOV<c><q> <Dd>, <Dm>
(Register operations, which are VORR with Rm = Rn.)
2. VMOV<c><q>.<dt> <Qd>, #<imm>
3. VMOV<c><q>.<dt> <Dd>, #<imm>
(Immediate loads.)
4. VMOV<c><q>.<size> <Dn[x]>, <Rd>
(ARM register to scalar.)
5. VMOV<c><q> <Dm>, <Rd>, <Rn>
(Two ARM registers to vector.)
6. VMOV<c><q>.<dt> <Rd>, <Dn[x]>
(Scalar to ARM register.)
7. VMOV<c><q> <Rd>, <Rn>, <Dm>
(Vector to two ARM registers.)
8. VMOV.F32 <Sd>, <Sm>
9. VMOV.F64 <Dd>, <Dm>
(VFP register moves.)
10. VMOV.F32 <Sd>, #imm
11. VMOV.F64 <Dd>, #imm
(VFP float immediate load.)
12. VMOV <Rd>, <Sm>
(VFP single to ARM reg.)
13. VMOV <Sd>, <Rm>
(ARM reg to VFP single.)
14. VMOV <Rd>, <Re>, <Sn>, <Sm>
(Two ARM regs to two VFP singles.)
15. VMOV <Sd>, <Se>, <Rn>, <Rm>
(Two VFP singles to two ARM regs.)
These cases can be disambiguated using neon_select_shape, except cases 1/9
and 3/11 which depend on the operand type too.
All the encoded bits are hardcoded by this function.
Cases 4, 6 may be used with VFPv1 and above (only 32-bit transfers!).
Cases 5, 7 may be used with VFPv2 and above.
FIXME: Some of the checking may be a bit sloppy (in a couple of cases you
can specify a type where it doesn't make sense to, and is ignored). */
static void
do_neon_mov (void)
{
enum neon_shape rs = neon_select_shape (NS_RRFF, NS_FFRR, NS_DRR, NS_RRD,
NS_QQ, NS_DD, NS_QI, NS_DI, NS_SR, NS_RS, NS_FF, NS_FI, NS_RF, NS_FR,
NS_NULL);
struct neon_type_el et;
const char *ldconst = 0;
switch (rs)
{
case NS_DD: /* case 1/9. */
et = neon_check_type (2, rs, N_EQK, N_F64 | N_KEY);
/* It is not an error here if no type is given. */
inst.error = NULL;
if (et.type == NT_float && et.size == 64)
{
do_vfp_nsyn_opcode ("fcpyd");
break;
}
/* fall through. */
case NS_QQ: /* case 0/1. */
{
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
/* The architecture manual I have doesn't explicitly state which
value the U bit should have for register->register moves, but
the equivalent VORR instruction has U = 0, so do that. */
inst.instruction = 0x0200110;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= LOW4 (inst.operands[1].reg) << 16;
inst.instruction |= HI1 (inst.operands[1].reg) << 7;
inst.instruction |= neon_quad (rs) << 6;
neon_dp_fixup (&inst);
}
break;
case NS_DI: /* case 3/11. */
et = neon_check_type (2, rs, N_EQK, N_F64 | N_KEY);
inst.error = NULL;
if (et.type == NT_float && et.size == 64)
{
/* case 11 (fconstd). */
ldconst = "fconstd";
goto encode_fconstd;
}
/* fall through. */
case NS_QI: /* case 2/3. */
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH) == FAIL)
return;
inst.instruction = 0x0800010;
neon_move_immediate ();
neon_dp_fixup (&inst);
break;
case NS_SR: /* case 4. */
{
unsigned bcdebits = 0;
int logsize;
unsigned dn = NEON_SCALAR_REG (inst.operands[0].reg);
unsigned x = NEON_SCALAR_INDEX (inst.operands[0].reg);
/* .<size> is optional here, defaulting to .32. */
if (inst.vectype.elems == 0
&& inst.operands[0].vectype.type == NT_invtype
&& inst.operands[1].vectype.type == NT_invtype)
{
inst.vectype.el[0].type = NT_untyped;
inst.vectype.el[0].size = 32;
inst.vectype.elems = 1;
}
et = neon_check_type (2, NS_NULL, N_8 | N_16 | N_32 | N_KEY, N_EQK);
logsize = neon_logbits (et.size);
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_v1),
_(BAD_FPU));
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_neon_ext_v1)
&& et.size != 32, _(BAD_FPU));
constraint (et.type == NT_invtype, _("bad type for scalar"));
constraint (x >= 64 / et.size, _("scalar index out of range"));
switch (et.size)
{
case 8: bcdebits = 0x8; break;
case 16: bcdebits = 0x1; break;
case 32: bcdebits = 0x0; break;
default: ;
}
bcdebits |= x << logsize;
inst.instruction = 0xe000b10;
do_vfp_cond_or_thumb ();
inst.instruction |= LOW4 (dn) << 16;
inst.instruction |= HI1 (dn) << 7;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= (bcdebits & 3) << 5;
inst.instruction |= (bcdebits >> 2) << 21;
}
break;
case NS_DRR: /* case 5 (fmdrr). */
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_v2),
_(BAD_FPU));
inst.instruction = 0xc400b10;
do_vfp_cond_or_thumb ();
inst.instruction |= LOW4 (inst.operands[0].reg);
inst.instruction |= HI1 (inst.operands[0].reg) << 5;
inst.instruction |= inst.operands[1].reg << 12;
inst.instruction |= inst.operands[2].reg << 16;
break;
case NS_RS: /* case 6. */
{
unsigned logsize;
unsigned dn = NEON_SCALAR_REG (inst.operands[1].reg);
unsigned x = NEON_SCALAR_INDEX (inst.operands[1].reg);
unsigned abcdebits = 0;
/* .<dt> is optional here, defaulting to .32. */
if (inst.vectype.elems == 0
&& inst.operands[0].vectype.type == NT_invtype
&& inst.operands[1].vectype.type == NT_invtype)
{
inst.vectype.el[0].type = NT_untyped;
inst.vectype.el[0].size = 32;
inst.vectype.elems = 1;
}
et = neon_check_type (2, NS_NULL,
N_EQK, N_S8 | N_S16 | N_U8 | N_U16 | N_32 | N_KEY);
logsize = neon_logbits (et.size);
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_v1),
_(BAD_FPU));
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_neon_ext_v1)
&& et.size != 32, _(BAD_FPU));
constraint (et.type == NT_invtype, _("bad type for scalar"));
constraint (x >= 64 / et.size, _("scalar index out of range"));
switch (et.size)
{
case 8: abcdebits = (et.type == NT_signed) ? 0x08 : 0x18; break;
case 16: abcdebits = (et.type == NT_signed) ? 0x01 : 0x11; break;
case 32: abcdebits = 0x00; break;
default: ;
}
abcdebits |= x << logsize;
inst.instruction = 0xe100b10;
do_vfp_cond_or_thumb ();
inst.instruction |= LOW4 (dn) << 16;
inst.instruction |= HI1 (dn) << 7;
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= (abcdebits & 3) << 5;
inst.instruction |= (abcdebits >> 2) << 21;
}
break;
case NS_RRD: /* case 7 (fmrrd). */
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_v2),
_(BAD_FPU));
inst.instruction = 0xc500b10;
do_vfp_cond_or_thumb ();
inst.instruction |= inst.operands[0].reg << 12;
inst.instruction |= inst.operands[1].reg << 16;
inst.instruction |= LOW4 (inst.operands[2].reg);
inst.instruction |= HI1 (inst.operands[2].reg) << 5;
break;
case NS_FF: /* case 8 (fcpys). */
do_vfp_nsyn_opcode ("fcpys");
break;
case NS_FI: /* case 10 (fconsts). */
ldconst = "fconsts";
encode_fconstd:
if (is_quarter_float (inst.operands[1].imm))
{
inst.operands[1].imm = neon_qfloat_bits (inst.operands[1].imm);
do_vfp_nsyn_opcode (ldconst);
}
else
first_error (_("immediate out of range"));
break;
case NS_RF: /* case 12 (fmrs). */
do_vfp_nsyn_opcode ("fmrs");
break;
case NS_FR: /* case 13 (fmsr). */
do_vfp_nsyn_opcode ("fmsr");
break;
/* The encoders for the fmrrs and fmsrr instructions expect three operands
(one of which is a list), but we have parsed four. Do some fiddling to
make the operands what do_vfp_reg2_from_sp2 and do_vfp_sp2_from_reg2
expect. */
case NS_RRFF: /* case 14 (fmrrs). */
constraint (inst.operands[3].reg != inst.operands[2].reg + 1,
_("VFP registers must be adjacent"));
inst.operands[2].imm = 2;
memset (&inst.operands[3], '\0', sizeof (inst.operands[3]));
do_vfp_nsyn_opcode ("fmrrs");
break;
case NS_FFRR: /* case 15 (fmsrr). */
constraint (inst.operands[1].reg != inst.operands[0].reg + 1,
_("VFP registers must be adjacent"));
inst.operands[1] = inst.operands[2];
inst.operands[2] = inst.operands[3];
inst.operands[0].imm = 2;
memset (&inst.operands[3], '\0', sizeof (inst.operands[3]));
do_vfp_nsyn_opcode ("fmsrr");
break;
case NS_NULL:
/* neon_select_shape has determined that the instruction
shape is wrong and has already set the error message. */
break;
default:
abort ();
}
}
static void
do_neon_rshift_round_imm (void)
{
enum neon_shape rs = neon_select_shape (NS_DDI, NS_QQI, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs, N_EQK, N_SU_ALL | N_KEY);
int imm = inst.operands[2].imm;
/* imm == 0 case is encoded as VMOV for V{R}SHR. */
if (imm == 0)
{
inst.operands[2].present = 0;
do_neon_mov ();
return;
}
constraint (imm < 1 || (unsigned)imm > et.size,
_("immediate out of range for shift"));
neon_imm_shift (TRUE, et.type == NT_unsigned, neon_quad (rs), et,
et.size - imm);
}
static void
do_neon_movl (void)
{
struct neon_type_el et = neon_check_type (2, NS_QD,
N_EQK | N_DBL, N_SU_32 | N_KEY);
unsigned sizebits = et.size >> 3;
inst.instruction |= sizebits << 19;
neon_two_same (0, et.type == NT_unsigned, -1);
}
static void
do_neon_trn (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_8 | N_16 | N_32 | N_KEY);
NEON_ENCODE (INTEGER, inst);
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_zip_uzp (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_8 | N_16 | N_32 | N_KEY);
if (rs == NS_DD && et.size == 32)
{
/* Special case: encode as VTRN.32 <Dd>, <Dm>. */
inst.instruction = N_MNEM_vtrn;
do_neon_trn ();
return;
}
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_sat_abs_neg (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_S8 | N_S16 | N_S32 | N_KEY);
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_pair_long (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs, N_EQK, N_SU_32 | N_KEY);
/* Unsigned is encoded in OP field (bit 7) for these instruction. */
inst.instruction |= (et.type == NT_unsigned) << 7;
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_recip_est (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK | N_FLT, N_F32 | N_U32 | N_KEY);
inst.instruction |= (et.type == NT_float) << 8;
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_cls (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_S8 | N_S16 | N_S32 | N_KEY);
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_clz (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK, N_I8 | N_I16 | N_I32 | N_KEY);
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_cnt (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et = neon_check_type (2, rs,
N_EQK | N_INT, N_8 | N_KEY);
neon_two_same (neon_quad (rs), 1, et.size);
}
static void
do_neon_swp (void)
{
enum neon_shape rs = neon_select_shape (NS_DD, NS_QQ, NS_NULL);
neon_two_same (neon_quad (rs), 1, -1);
}
static void
do_neon_tbl_tbx (void)
{
unsigned listlenbits;
neon_check_type (3, NS_DLD, N_EQK, N_EQK, N_8 | N_KEY);
if (inst.operands[1].imm < 1 || inst.operands[1].imm > 4)
{
first_error (_("bad list length for table lookup"));
return;
}
listlenbits = inst.operands[1].imm - 1;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg) << 16;
inst.instruction |= HI1 (inst.operands[1].reg) << 7;
inst.instruction |= LOW4 (inst.operands[2].reg);
inst.instruction |= HI1 (inst.operands[2].reg) << 5;
inst.instruction |= listlenbits << 8;
neon_dp_fixup (&inst);
}
static void
do_neon_ldm_stm (void)
{
/* P, U and L bits are part of bitmask. */
int is_dbmode = (inst.instruction & (1 << 24)) != 0;
unsigned offsetbits = inst.operands[1].imm * 2;
if (inst.operands[1].issingle)
{
do_vfp_nsyn_ldm_stm (is_dbmode);
return;
}
constraint (is_dbmode && !inst.operands[0].writeback,
_("writeback (!) must be used for VLDMDB and VSTMDB"));
constraint (inst.operands[1].imm < 1 || inst.operands[1].imm > 16,
_("register list must contain at least 1 and at most 16 "
"registers"));
inst.instruction |= inst.operands[0].reg << 16;
inst.instruction |= inst.operands[0].writeback << 21;
inst.instruction |= LOW4 (inst.operands[1].reg) << 12;
inst.instruction |= HI1 (inst.operands[1].reg) << 22;
inst.instruction |= offsetbits;
do_vfp_cond_or_thumb ();
}
static void
do_neon_ldr_str (void)
{
int is_ldr = (inst.instruction & (1 << 20)) != 0;
/* Use of PC in vstr in ARM mode is deprecated in ARMv7.
And is UNPREDICTABLE in thumb mode. */
if (!is_ldr
&& inst.operands[1].reg == REG_PC
&& (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v7) || thumb_mode))
{
if (thumb_mode)
inst.error = _("Use of PC here is UNPREDICTABLE");
else if (warn_on_deprecated)
as_tsktsk (_("Use of PC here is deprecated"));
}
if (inst.operands[0].issingle)
{
if (is_ldr)
do_vfp_nsyn_opcode ("flds");
else
do_vfp_nsyn_opcode ("fsts");
}
else
{
if (is_ldr)
do_vfp_nsyn_opcode ("fldd");
else
do_vfp_nsyn_opcode ("fstd");
}
}
/* "interleave" version also handles non-interleaving register VLD1/VST1
instructions. */
static void
do_neon_ld_st_interleave (void)
{
struct neon_type_el et = neon_check_type (1, NS_NULL,
N_8 | N_16 | N_32 | N_64);
unsigned alignbits = 0;
unsigned idx;
/* The bits in this table go:
0: register stride of one (0) or two (1)
1,2: register list length, minus one (1, 2, 3, 4).
3,4: <n> in instruction type, minus one (VLD<n> / VST<n>).
We use -1 for invalid entries. */
const int typetable[] =
{
0x7, -1, 0xa, -1, 0x6, -1, 0x2, -1, /* VLD1 / VST1. */
-1, -1, 0x8, 0x9, -1, -1, 0x3, -1, /* VLD2 / VST2. */
-1, -1, -1, -1, 0x4, 0x5, -1, -1, /* VLD3 / VST3. */
-1, -1, -1, -1, -1, -1, 0x0, 0x1 /* VLD4 / VST4. */
};
int typebits;
if (et.type == NT_invtype)
return;
if (inst.operands[1].immisalign)
switch (inst.operands[1].imm >> 8)
{
case 64: alignbits = 1; break;
case 128:
if (NEON_REGLIST_LENGTH (inst.operands[0].imm) != 2
&& NEON_REGLIST_LENGTH (inst.operands[0].imm) != 4)
goto bad_alignment;
alignbits = 2;
break;
case 256:
if (NEON_REGLIST_LENGTH (inst.operands[0].imm) != 4)
goto bad_alignment;
alignbits = 3;
break;
default:
bad_alignment:
first_error (_("bad alignment"));
return;
}
inst.instruction |= alignbits << 4;
inst.instruction |= neon_logbits (et.size) << 6;
/* Bits [4:6] of the immediate in a list specifier encode register stride
(minus 1) in bit 4, and list length in bits [5:6]. We put the <n> of
VLD<n>/VST<n> in bits [9:8] of the initial bitmask. Suck it out here, look
up the right value for "type" in a table based on this value and the given
list style, then stick it back. */
idx = ((inst.operands[0].imm >> 4) & 7)
| (((inst.instruction >> 8) & 3) << 3);
typebits = typetable[idx];
constraint (typebits == -1, _("bad list type for instruction"));
constraint (((inst.instruction >> 8) & 3) && et.size == 64,
_("bad element type for instruction"));
inst.instruction &= ~0xf00;
inst.instruction |= typebits << 8;
}
/* Check alignment is valid for do_neon_ld_st_lane and do_neon_ld_dup.
*DO_ALIGN is set to 1 if the relevant alignment bit should be set, 0
otherwise. The variable arguments are a list of pairs of legal (size, align)
values, terminated with -1. */
static int
neon_alignment_bit (int size, int align, int *do_align, ...)
{
va_list ap;
int result = FAIL, thissize, thisalign;
if (!inst.operands[1].immisalign)
{
*do_align = 0;
return SUCCESS;
}
va_start (ap, do_align);
do
{
thissize = va_arg (ap, int);
if (thissize == -1)
break;
thisalign = va_arg (ap, int);
if (size == thissize && align == thisalign)
result = SUCCESS;
}
while (result != SUCCESS);
va_end (ap);
if (result == SUCCESS)
*do_align = 1;
else
first_error (_("unsupported alignment for instruction"));
return result;
}
static void
do_neon_ld_st_lane (void)
{
struct neon_type_el et = neon_check_type (1, NS_NULL, N_8 | N_16 | N_32);
int align_good, do_align = 0;
int logsize = neon_logbits (et.size);
int align = inst.operands[1].imm >> 8;
int n = (inst.instruction >> 8) & 3;
int max_el = 64 / et.size;
if (et.type == NT_invtype)
return;
constraint (NEON_REGLIST_LENGTH (inst.operands[0].imm) != n + 1,
_("bad list length"));
constraint (NEON_LANE (inst.operands[0].imm) >= max_el,
_("scalar index out of range"));
constraint (n != 0 && NEON_REG_STRIDE (inst.operands[0].imm) == 2
&& et.size == 8,
_("stride of 2 unavailable when element size is 8"));
switch (n)
{
case 0: /* VLD1 / VST1. */
align_good = neon_alignment_bit (et.size, align, &do_align, 16, 16,
32, 32, -1);
if (align_good == FAIL)
return;
if (do_align)
{
unsigned alignbits = 0;
switch (et.size)
{
case 16: alignbits = 0x1; break;
case 32: alignbits = 0x3; break;
default: ;
}
inst.instruction |= alignbits << 4;
}
break;
case 1: /* VLD2 / VST2. */
align_good = neon_alignment_bit (et.size, align, &do_align, 8, 16, 16, 32,
32, 64, -1);
if (align_good == FAIL)
return;
if (do_align)
inst.instruction |= 1 << 4;
break;
case 2: /* VLD3 / VST3. */
constraint (inst.operands[1].immisalign,
_("can't use alignment with this instruction"));
break;
case 3: /* VLD4 / VST4. */
align_good = neon_alignment_bit (et.size, align, &do_align, 8, 32,
16, 64, 32, 64, 32, 128, -1);
if (align_good == FAIL)
return;
if (do_align)
{
unsigned alignbits = 0;
switch (et.size)
{
case 8: alignbits = 0x1; break;
case 16: alignbits = 0x1; break;
case 32: alignbits = (align == 64) ? 0x1 : 0x2; break;
default: ;
}
inst.instruction |= alignbits << 4;
}
break;
default: ;
}
/* Reg stride of 2 is encoded in bit 5 when size==16, bit 6 when size==32. */
if (n != 0 && NEON_REG_STRIDE (inst.operands[0].imm) == 2)
inst.instruction |= 1 << (4 + logsize);
inst.instruction |= NEON_LANE (inst.operands[0].imm) << (logsize + 5);
inst.instruction |= logsize << 10;
}
/* Encode single n-element structure to all lanes VLD<n> instructions. */
static void
do_neon_ld_dup (void)
{
struct neon_type_el et = neon_check_type (1, NS_NULL, N_8 | N_16 | N_32);
int align_good, do_align = 0;
if (et.type == NT_invtype)
return;
switch ((inst.instruction >> 8) & 3)
{
case 0: /* VLD1. */
gas_assert (NEON_REG_STRIDE (inst.operands[0].imm) != 2);
align_good = neon_alignment_bit (et.size, inst.operands[1].imm >> 8,
&do_align, 16, 16, 32, 32, -1);
if (align_good == FAIL)
return;
switch (NEON_REGLIST_LENGTH (inst.operands[0].imm))
{
case 1: break;
case 2: inst.instruction |= 1 << 5; break;
default: first_error (_("bad list length")); return;
}
inst.instruction |= neon_logbits (et.size) << 6;
break;
case 1: /* VLD2. */
align_good = neon_alignment_bit (et.size, inst.operands[1].imm >> 8,
&do_align, 8, 16, 16, 32, 32, 64, -1);
if (align_good == FAIL)
return;
constraint (NEON_REGLIST_LENGTH (inst.operands[0].imm) != 2,
_("bad list length"));
if (NEON_REG_STRIDE (inst.operands[0].imm) == 2)
inst.instruction |= 1 << 5;
inst.instruction |= neon_logbits (et.size) << 6;
break;
case 2: /* VLD3. */
constraint (inst.operands[1].immisalign,
_("can't use alignment with this instruction"));
constraint (NEON_REGLIST_LENGTH (inst.operands[0].imm) != 3,
_("bad list length"));
if (NEON_REG_STRIDE (inst.operands[0].imm) == 2)
inst.instruction |= 1 << 5;
inst.instruction |= neon_logbits (et.size) << 6;
break;
case 3: /* VLD4. */
{
int align = inst.operands[1].imm >> 8;
align_good = neon_alignment_bit (et.size, align, &do_align, 8, 32,
16, 64, 32, 64, 32, 128, -1);
if (align_good == FAIL)
return;
constraint (NEON_REGLIST_LENGTH (inst.operands[0].imm) != 4,
_("bad list length"));
if (NEON_REG_STRIDE (inst.operands[0].imm) == 2)
inst.instruction |= 1 << 5;
if (et.size == 32 && align == 128)
inst.instruction |= 0x3 << 6;
else
inst.instruction |= neon_logbits (et.size) << 6;
}
break;
default: ;
}
inst.instruction |= do_align << 4;
}
/* Disambiguate VLD<n> and VST<n> instructions, and fill in common bits (those
apart from bits [11:4]. */
static void
do_neon_ldx_stx (void)
{
if (inst.operands[1].isreg)
constraint (inst.operands[1].reg == REG_PC, BAD_PC);
switch (NEON_LANE (inst.operands[0].imm))
{
case NEON_INTERLEAVE_LANES:
NEON_ENCODE (INTERLV, inst);
do_neon_ld_st_interleave ();
break;
case NEON_ALL_LANES:
NEON_ENCODE (DUP, inst);
if (inst.instruction == N_INV)
{
first_error ("only loads support such operands");
break;
}
do_neon_ld_dup ();
break;
default:
NEON_ENCODE (LANE, inst);
do_neon_ld_st_lane ();
}
/* L bit comes from bit mask. */
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= inst.operands[1].reg << 16;
if (inst.operands[1].postind)
{
int postreg = inst.operands[1].imm & 0xf;
constraint (!inst.operands[1].immisreg,
_("post-index must be a register"));
constraint (postreg == 0xd || postreg == 0xf,
_("bad register for post-index"));
inst.instruction |= postreg;
}
else
{
constraint (inst.operands[1].immisreg, BAD_ADDR_MODE);
constraint (inst.reloc.exp.X_op != O_constant
|| inst.reloc.exp.X_add_number != 0,
BAD_ADDR_MODE);
if (inst.operands[1].writeback)
{
inst.instruction |= 0xd;
}
else
inst.instruction |= 0xf;
}
if (thumb_mode)
inst.instruction |= 0xf9000000;
else
inst.instruction |= 0xf4000000;
}
/* FP v8. */
static void
do_vfp_nsyn_fpv8 (enum neon_shape rs)
{
/* Targets like FPv5-SP-D16 don't support FP v8 instructions with
D register operands. */
if (neon_shape_class[rs] == SC_DOUBLE)
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_armv8),
_(BAD_FPU));
NEON_ENCODE (FPV8, inst);
if (rs == NS_FFF)
do_vfp_sp_dyadic ();
else
do_vfp_dp_rd_rn_rm ();
if (rs == NS_DDD)
inst.instruction |= 0x100;
inst.instruction |= 0xf0000000;
}
static void
do_vsel (void)
{
set_it_insn_type (OUTSIDE_IT_INSN);
if (try_vfp_nsyn (3, do_vfp_nsyn_fpv8) != SUCCESS)
first_error (_("invalid instruction shape"));
}
static void
do_vmaxnm (void)
{
set_it_insn_type (OUTSIDE_IT_INSN);
if (try_vfp_nsyn (3, do_vfp_nsyn_fpv8) == SUCCESS)
return;
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH8) == FAIL)
return;
neon_dyadic_misc (NT_untyped, N_F32, 0);
}
static void
do_vrint_1 (enum neon_cvt_mode mode)
{
enum neon_shape rs = neon_select_shape (NS_FF, NS_DD, NS_QQ, NS_NULL);
struct neon_type_el et;
if (rs == NS_NULL)
return;
/* Targets like FPv5-SP-D16 don't support FP v8 instructions with
D register operands. */
if (neon_shape_class[rs] == SC_DOUBLE)
constraint (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_vfp_ext_armv8),
_(BAD_FPU));
et = neon_check_type (2, rs, N_EQK | N_VFP, N_F32 | N_F64 | N_KEY | N_VFP);
if (et.type != NT_invtype)
{
/* VFP encodings. */
if (mode == neon_cvt_mode_a || mode == neon_cvt_mode_n
|| mode == neon_cvt_mode_p || mode == neon_cvt_mode_m)
set_it_insn_type (OUTSIDE_IT_INSN);
NEON_ENCODE (FPV8, inst);
if (rs == NS_FF)
do_vfp_sp_monadic ();
else
do_vfp_dp_rd_rm ();
switch (mode)
{
case neon_cvt_mode_r: inst.instruction |= 0x00000000; break;
case neon_cvt_mode_z: inst.instruction |= 0x00000080; break;
case neon_cvt_mode_x: inst.instruction |= 0x00010000; break;
case neon_cvt_mode_a: inst.instruction |= 0xf0000000; break;
case neon_cvt_mode_n: inst.instruction |= 0xf0010000; break;
case neon_cvt_mode_p: inst.instruction |= 0xf0020000; break;
case neon_cvt_mode_m: inst.instruction |= 0xf0030000; break;
default: abort ();
}
inst.instruction |= (rs == NS_DD) << 8;
do_vfp_cond_or_thumb ();
}
else
{
/* Neon encodings (or something broken...). */
inst.error = NULL;
et = neon_check_type (2, rs, N_EQK, N_F32 | N_KEY);
if (et.type == NT_invtype)
return;
set_it_insn_type (OUTSIDE_IT_INSN);
NEON_ENCODE (FLOAT, inst);
if (vfp_or_neon_is_neon (NEON_CHECK_CC | NEON_CHECK_ARCH8) == FAIL)
return;
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
inst.instruction |= neon_quad (rs) << 6;
switch (mode)
{
case neon_cvt_mode_z: inst.instruction |= 3 << 7; break;
case neon_cvt_mode_x: inst.instruction |= 1 << 7; break;
case neon_cvt_mode_a: inst.instruction |= 2 << 7; break;
case neon_cvt_mode_n: inst.instruction |= 0 << 7; break;
case neon_cvt_mode_p: inst.instruction |= 7 << 7; break;
case neon_cvt_mode_m: inst.instruction |= 5 << 7; break;
case neon_cvt_mode_r: inst.error = _("invalid rounding mode"); break;
default: abort ();
}
if (thumb_mode)
inst.instruction |= 0xfc000000;
else
inst.instruction |= 0xf0000000;
}
}
static void
do_vrintx (void)
{
do_vrint_1 (neon_cvt_mode_x);
}
static void
do_vrintz (void)
{
do_vrint_1 (neon_cvt_mode_z);
}
static void
do_vrintr (void)
{
do_vrint_1 (neon_cvt_mode_r);
}
static void
do_vrinta (void)
{
do_vrint_1 (neon_cvt_mode_a);
}
static void
do_vrintn (void)
{
do_vrint_1 (neon_cvt_mode_n);
}
static void
do_vrintp (void)
{
do_vrint_1 (neon_cvt_mode_p);
}
static void
do_vrintm (void)
{
do_vrint_1 (neon_cvt_mode_m);
}
/* Crypto v1 instructions. */
static void
do_crypto_2op_1 (unsigned elttype, int op)
{
set_it_insn_type (OUTSIDE_IT_INSN);
if (neon_check_type (2, NS_QQ, N_EQK | N_UNT, elttype | N_UNT | N_KEY).type
== NT_invtype)
return;
inst.error = NULL;
NEON_ENCODE (INTEGER, inst);
inst.instruction |= LOW4 (inst.operands[0].reg) << 12;
inst.instruction |= HI1 (inst.operands[0].reg) << 22;
inst.instruction |= LOW4 (inst.operands[1].reg);
inst.instruction |= HI1 (inst.operands[1].reg) << 5;
if (op != -1)
inst.instruction |= op << 6;
if (thumb_mode)
inst.instruction |= 0xfc000000;
else
inst.instruction |= 0xf0000000;
}
static void
do_crypto_3op_1 (int u, int op)
{
set_it_insn_type (OUTSIDE_IT_INSN);
if (neon_check_type (3, NS_QQQ, N_EQK | N_UNT, N_EQK | N_UNT,
N_32 | N_UNT | N_KEY).type == NT_invtype)
return;
inst.error = NULL;
NEON_ENCODE (INTEGER, inst);
neon_three_same (1, u, 8 << op);
}
static void
do_aese (void)
{
do_crypto_2op_1 (N_8, 0);
}
static void
do_aesd (void)
{
do_crypto_2op_1 (N_8, 1);
}
static void
do_aesmc (void)
{
do_crypto_2op_1 (N_8, 2);
}
static void
do_aesimc (void)
{
do_crypto_2op_1 (N_8, 3);
}
static void
do_sha1c (void)
{
do_crypto_3op_1 (0, 0);
}
static void
do_sha1p (void)
{
do_crypto_3op_1 (0, 1);
}
static void
do_sha1m (void)
{
do_crypto_3op_1 (0, 2);
}
static void
do_sha1su0 (void)
{
do_crypto_3op_1 (0, 3);
}
static void
do_sha256h (void)
{
do_crypto_3op_1 (1, 0);
}
static void
do_sha256h2 (void)
{
do_crypto_3op_1 (1, 1);
}
static void
do_sha256su1 (void)
{
do_crypto_3op_1 (1, 2);
}
static void
do_sha1h (void)
{
do_crypto_2op_1 (N_32, -1);
}
static void
do_sha1su1 (void)
{
do_crypto_2op_1 (N_32, 0);
}
static void
do_sha256su0 (void)
{
do_crypto_2op_1 (N_32, 1);
}
static void
do_crc32_1 (unsigned int poly, unsigned int sz)
{
unsigned int Rd = inst.operands[0].reg;
unsigned int Rn = inst.operands[1].reg;
unsigned int Rm = inst.operands[2].reg;
set_it_insn_type (OUTSIDE_IT_INSN);
inst.instruction |= LOW4 (Rd) << (thumb_mode ? 8 : 12);
inst.instruction |= LOW4 (Rn) << 16;
inst.instruction |= LOW4 (Rm);
inst.instruction |= sz << (thumb_mode ? 4 : 21);
inst.instruction |= poly << (thumb_mode ? 20 : 9);
if (Rd == REG_PC || Rn == REG_PC || Rm == REG_PC)
as_warn (UNPRED_REG ("r15"));
if (thumb_mode && (Rd == REG_SP || Rn == REG_SP || Rm == REG_SP))
as_warn (UNPRED_REG ("r13"));
}
static void
do_crc32b (void)
{
do_crc32_1 (0, 0);
}
static void
do_crc32h (void)
{
do_crc32_1 (0, 1);
}
static void
do_crc32w (void)
{
do_crc32_1 (0, 2);
}
static void
do_crc32cb (void)
{
do_crc32_1 (1, 0);
}
static void
do_crc32ch (void)
{
do_crc32_1 (1, 1);
}
static void
do_crc32cw (void)
{
do_crc32_1 (1, 2);
}
/* 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 void
fix_new_arm (fragS * frag,
int where,
short int size,
expressionS * exp,
int pc_rel,
int reloc)
{
fixS * new_fix;
switch (exp->X_op)
{
case O_constant:
if (pc_rel)
{
/* Create an absolute valued symbol, so we have something to
refer to in the object file. Unfortunately for us, gas's
generic expression parsing will already have folded out
any use of .set foo/.type foo %function that may have
been used to set type information of the target location,
that's being specified symbolically. We have to presume
the user knows what they are doing. */
char name[16 + 8];
symbolS *symbol;
sprintf (name, "*ABS*0x%lx", (unsigned long)exp->X_add_number);
symbol = symbol_find_or_make (name);
S_SET_SEGMENT (symbol, absolute_section);
symbol_set_frag (symbol, &zero_address_frag);
S_SET_VALUE (symbol, exp->X_add_number);
exp->X_op = O_symbol;
exp->X_add_symbol = symbol;
exp->X_add_number = 0;
}
/* FALLTHROUGH */
case O_symbol:
case O_add:
case O_subtract:
new_fix = fix_new_exp (frag, where, size, exp, pc_rel,
(enum bfd_reloc_code_real) reloc);
break;
default:
new_fix = (fixS *) fix_new (frag, where, size, make_expr_symbol (exp), 0,
pc_rel, (enum bfd_reloc_code_real) reloc);
break;
}
/* Mark whether the fix is to a THUMB instruction, or an ARM
instruction. */
new_fix->tc_fix_data = thumb_mode;
}
/* Create a frg for an instruction requiring relaxation. */
static void
output_relax_insn (void)
{
char * to;
symbolS *sym;
int offset;
/* The size of the instruction is unknown, so tie the debug info to the
start of the instruction. */
dwarf2_emit_insn (0);
switch (inst.reloc.exp.X_op)
{
case O_symbol:
sym = inst.reloc.exp.X_add_symbol;
offset = inst.reloc.exp.X_add_number;
break;
case O_constant:
sym = NULL;
offset = inst.reloc.exp.X_add_number;
break;
default:
sym = make_expr_symbol (&inst.reloc.exp);
offset = 0;
break;
}
to = frag_var (rs_machine_dependent, INSN_SIZE, THUMB_SIZE,
inst.relax, sym, offset, NULL/*offset, opcode*/);
md_number_to_chars (to, inst.instruction, THUMB_SIZE);
}
/* Write a 32-bit thumb instruction to buf. */
static void
put_thumb32_insn (char * buf, unsigned long insn)
{
md_number_to_chars (buf, insn >> 16, THUMB_SIZE);
md_number_to_chars (buf + THUMB_SIZE, insn, THUMB_SIZE);
}
static void
output_inst (const char * str)
{
char * to = NULL;
if (inst.error)
{
as_bad ("%s -- `%s'", inst.error, str);
return;
}
if (inst.relax)
{
output_relax_insn ();
return;
}
if (inst.size == 0)
return;
to = frag_more (inst.size);
/* PR 9814: Record the thumb mode into the current frag so that we know
what type of NOP padding to use, if necessary. We override any previous
setting so that if the mode has changed then the NOPS that we use will
match the encoding of the last instruction in the frag. */
frag_now->tc_frag_data.thumb_mode = thumb_mode | MODE_RECORDED;
if (thumb_mode && (inst.size > THUMB_SIZE))
{
gas_assert (inst.size == (2 * THUMB_SIZE));
put_thumb32_insn (to, inst.instruction);
}
else if (inst.size > INSN_SIZE)
{
gas_assert (inst.size == (2 * INSN_SIZE));
md_number_to_chars (to, inst.instruction, INSN_SIZE);
md_number_to_chars (to + INSN_SIZE, inst.instruction, INSN_SIZE);
}
else
md_number_to_chars (to, inst.instruction, inst.size);
if (inst.reloc.type != BFD_RELOC_UNUSED)
fix_new_arm (frag_now, to - frag_now->fr_literal,
inst.size, & inst.reloc.exp, inst.reloc.pc_rel,
inst.reloc.type);
dwarf2_emit_insn (inst.size);
}
static char *
output_it_inst (int cond, int mask, char * to)
{
unsigned long instruction = 0xbf00;
mask &= 0xf;
instruction |= mask;
instruction |= cond << 4;
if (to == NULL)
{
to = frag_more (2);
#ifdef OBJ_ELF
dwarf2_emit_insn (2);
#endif
}
md_number_to_chars (to, instruction, 2);
return to;
}
/* Tag values used in struct asm_opcode's tag field. */
enum opcode_tag
{
OT_unconditional, /* Instruction cannot be conditionalized.
The ARM condition field is still 0xE. */
OT_unconditionalF, /* Instruction cannot be conditionalized
and carries 0xF in its ARM condition field. */
OT_csuffix, /* Instruction takes a conditional suffix. */
OT_csuffixF, /* Some forms of the instruction take a conditional
suffix, others place 0xF where the condition field
would be. */
OT_cinfix3, /* Instruction takes a conditional infix,
beginning at character index 3. (In
unified mode, it becomes a suffix.) */
OT_cinfix3_deprecated, /* The same as OT_cinfix3. This is used for
tsts, cmps, cmns, and teqs. */
OT_cinfix3_legacy, /* Legacy instruction takes a conditional infix at
character index 3, even in unified mode. Used for
legacy instructions where suffix and infix forms
may be ambiguous. */
OT_csuf_or_in3, /* Instruction takes either a conditional
suffix or an infix at character index 3. */
OT_odd_infix_unc, /* This is the unconditional variant of an
instruction that takes a conditional infix
at an unusual position. In unified mode,
this variant will accept a suffix. */
OT_odd_infix_0 /* Values greater than or equal to OT_odd_infix_0
are the conditional variants of instructions that
take conditional infixes in unusual positions.
The infix appears at character index
(tag - OT_odd_infix_0). These are not accepted
in unified mode. */
};
/* 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.
This is not simply a hash table lookup, because of conditional
variants. Most instructions have conditional variants, which are
expressed with a _conditional affix_ to the mnemonic. If we were
to encode each conditional variant as a literal string in the opcode
table, it would have approximately 20,000 entries.
Most mnemonics take this affix as a suffix, and in unified syntax,
'most' is upgraded to 'all'. However, in the divided syntax, some
instructions take the affix as an infix, notably the s-variants of
the arithmetic instructions. Of those instructions, all but six
have the infix appear after the third character of the mnemonic.
Accordingly, the algorithm for looking up primary opcodes given
an identifier is:
1. Look up the identifier in the opcode table.
If we find a match, go to step U.
2. Look up the last two characters of the identifier in the
conditions table. If we find a match, look up the first N-2
characters of the identifier in the opcode table. If we
find a match, go to step CE.
3. Look up the fourth and fifth characters of the identifier in
the conditions table. If we find a match, extract those
characters from the identifier, and look up the remaining
characters in the opcode table. If we find a match, go
to step CM.
4. Fail.
U. Examine the tag field of the opcode structure, in case this is
one of the six instructions with its conditional infix in an
unusual place. If it is, the tag tells us where to find the
infix; look it up in the conditions table and set inst.cond
accordingly. Otherwise, this is an unconditional instruction.
Again set inst.cond accordingly. Return the opcode structure.
CE. Examine the tag field to make sure this is an instruction that
should receive a conditional suffix. If it is not, fail.
Otherwise, set inst.cond from the suffix we already looked up,
and return the opcode structure.
CM. Examine the tag field to make sure this is an instruction that
should receive a conditional infix after the third character.
If it is not, fail. Otherwise, undo the edits to the current
line of input and proceed as for case CE. */
static const struct asm_opcode *
opcode_lookup (char **str)
{
char *end, *base;
char *affix;
const struct asm_opcode *opcode;
const struct asm_cond *cond;
char save[2];
/* Scan up to the end of the mnemonic, which must end in white space,
'.' (in unified mode, or for Neon/VFP instructions), or end of string. */
for (base = end = *str; *end != '\0'; end++)
if (*end == ' ' || *end == '.')
break;
if (end == base)
return NULL;
/* Handle a possible width suffix and/or Neon type suffix. */
if (end[0] == '.')
{
int offset = 2;
/* The .w and .n suffixes are only valid if the unified syntax is in
use. */
if (unified_syntax && end[1] == 'w')
inst.size_req = 4;
else if (unified_syntax && end[1] == 'n')
inst.size_req = 2;
else
offset = 0;
inst.vectype.elems = 0;
*str = end + offset;
if (end[offset] == '.')
{
/* See if we have a Neon type suffix (possible in either unified or
non-unified ARM syntax mode). */
if (parse_neon_type (&inst.vectype, str) == FAIL)
return NULL;
}
else if (end[offset] != '\0' && end[offset] != ' ')
return NULL;
}
else
*str = end;
/* Look for unaffixed or special-case affixed mnemonic. */
opcode = (const struct asm_opcode *) hash_find_n (arm_ops_hsh, base,
end - base);
if (opcode)
{
/* step U */
if (opcode->tag < OT_odd_infix_0)
{
inst.cond = COND_ALWAYS;
return opcode;
}
if (warn_on_deprecated && unified_syntax)
as_tsktsk (_("conditional infixes are deprecated in unified syntax"));
affix = base + (opcode->tag - OT_odd_infix_0);
cond = (const struct asm_cond *) hash_find_n (arm_cond_hsh, affix, 2);
gas_assert (cond);
inst.cond = cond->value;
return opcode;
}
/* Cannot have a conditional suffix on a mnemonic of less than two
characters. */
if (end - base < 3)
return NULL;
/* Look for suffixed mnemonic. */
affix = end - 2;
cond = (const struct asm_cond *) hash_find_n (arm_cond_hsh, affix, 2);
opcode = (const struct asm_opcode *) hash_find_n (arm_ops_hsh, base,
affix - base);
if (opcode && cond)
{
/* step CE */
switch (opcode->tag)
{
case OT_cinfix3_legacy:
/* Ignore conditional suffixes matched on infix only mnemonics. */
break;
case OT_cinfix3:
case OT_cinfix3_deprecated:
case OT_odd_infix_unc:
if (!unified_syntax)
return 0;
/* else fall through */
case OT_csuffix:
case OT_csuffixF:
case OT_csuf_or_in3:
inst.cond = cond->value;
return opcode;
case OT_unconditional:
case OT_unconditionalF:
if (thumb_mode)
inst.cond = cond->value;
else
{
/* Delayed diagnostic. */
inst.error = BAD_COND;
inst.cond = COND_ALWAYS;
}
return opcode;
default:
return NULL;
}
}
/* Cannot have a usual-position infix on a mnemonic of less than
six characters (five would be a suffix). */
if (end - base < 6)
return NULL;
/* Look for infixed mnemonic in the usual position. */
affix = base + 3;
cond = (const struct asm_cond *) hash_find_n (arm_cond_hsh, affix, 2);
if (!cond)
return NULL;
memcpy (save, affix, 2);
memmove (affix, affix + 2, (end - affix) - 2);
opcode = (const struct asm_opcode *) hash_find_n (arm_ops_hsh, base,
(end - base) - 2);
memmove (affix + 2, affix, (end - affix) - 2);
memcpy (affix, save, 2);
if (opcode
&& (opcode->tag == OT_cinfix3
|| opcode->tag == OT_cinfix3_deprecated
|| opcode->tag == OT_csuf_or_in3
|| opcode->tag == OT_cinfix3_legacy))
{
/* Step CM. */
if (warn_on_deprecated && unified_syntax
&& (opcode->tag == OT_cinfix3
|| opcode->tag == OT_cinfix3_deprecated))
as_tsktsk (_("conditional infixes are deprecated in unified syntax"));
inst.cond = cond->value;
return opcode;
}
return NULL;
}
/* This function generates an initial IT instruction, leaving its block
virtually open for the new instructions. Eventually,
the mask will be updated by now_it_add_mask () each time
a new instruction needs to be included in the IT block.
Finally, the block is closed with close_automatic_it_block ().
The block closure can be requested either from md_assemble (),
a tencode (), or due to a label hook. */
static void
new_automatic_it_block (int cond)
{
now_it.state = AUTOMATIC_IT_BLOCK;
now_it.mask = 0x18;
now_it.cc = cond;
now_it.block_length = 1;
mapping_state (MAP_THUMB);
now_it.insn = output_it_inst (cond, now_it.mask, NULL);
now_it.warn_deprecated = FALSE;
now_it.insn_cond = TRUE;
}
/* Close an automatic IT block.
See comments in new_automatic_it_block (). */
static void
close_automatic_it_block (void)
{
now_it.mask = 0x10;
now_it.block_length = 0;
}
/* Update the mask of the current automatically-generated IT
instruction. See comments in new_automatic_it_block (). */
static void
now_it_add_mask (int cond)
{
#define CLEAR_BIT(value, nbit) ((value) & ~(1 << (nbit)))
#define SET_BIT_VALUE(value, bitvalue, nbit) (CLEAR_BIT (value, nbit) \
| ((bitvalue) << (nbit)))
const int resulting_bit = (cond & 1);
now_it.mask &= 0xf;
now_it.mask = SET_BIT_VALUE (now_it.mask,
resulting_bit,
(5 - now_it.block_length));
now_it.mask = SET_BIT_VALUE (now_it.mask,
1,
((5 - now_it.block_length) - 1) );
output_it_inst (now_it.cc, now_it.mask, now_it.insn);
#undef CLEAR_BIT
#undef SET_BIT_VALUE
}
/* The IT blocks handling machinery is accessed through the these functions:
it_fsm_pre_encode () from md_assemble ()
set_it_insn_type () optional, from the tencode functions
set_it_insn_type_last () ditto
in_it_block () ditto
it_fsm_post_encode () from md_assemble ()
force_automatic_it_block_close () from label habdling functions
Rationale:
1) md_assemble () calls it_fsm_pre_encode () before calling tencode (),
initializing the IT insn type with a generic initial value depending
on the inst.condition.
2) During the tencode function, two things may happen:
a) The tencode function overrides the IT insn type by
calling either set_it_insn_type (type) or set_it_insn_type_last ().
b) The tencode function queries the IT block state by
calling in_it_block () (i.e. to determine narrow/not narrow mode).
Both set_it_insn_type and in_it_block run the internal FSM state
handling function (handle_it_state), because: a) setting the IT insn
type may incur in an invalid state (exiting the function),
and b) querying the state requires the FSM to be updated.
Specifically we want to avoid creating an IT block for conditional
branches, so it_fsm_pre_encode is actually a guess and we can't
determine whether an IT block is required until the tencode () routine
has decided what type of instruction this actually it.
Because of this, if set_it_insn_type and in_it_block have to be used,
set_it_insn_type has to be called first.
set_it_insn_type_last () is a wrapper of set_it_insn_type (type), that
determines the insn IT type depending on the inst.cond code.
When a tencode () routine encodes an instruction that can be
either outside an IT block, or, in the case of being inside, has to be
the last one, set_it_insn_type_last () will determine the proper
IT instruction type based on the inst.cond code. Otherwise,
set_it_insn_type can be called for overriding that logic or
for covering other cases.
Calling handle_it_state () may not transition the IT block state to
OUTSIDE_IT_BLOCK immediatelly, since the (current) state could be
still queried. Instead, if the FSM determines that the state should
be transitioned to OUTSIDE_IT_BLOCK, a flag is marked to be closed
after the tencode () function: that's what it_fsm_post_encode () does.
Since in_it_block () calls the state handling function to get an
updated state, an error may occur (due to invalid insns combination).
In that case, inst.error is set.
Therefore, inst.error has to be checked after the execution of
the tencode () routine.
3) Back in md_assemble(), it_fsm_post_encode () is called to commit
any pending state change (if any) that didn't take place in
handle_it_state () as explained above. */
static void
it_fsm_pre_encode (void)
{
if (inst.cond != COND_ALWAYS)
inst.it_insn_type = INSIDE_IT_INSN;
else
inst.it_insn_type = OUTSIDE_IT_INSN;
now_it.state_handled = 0;
}
/* IT state FSM handling function. */
static int
handle_it_state (void)
{
now_it.state_handled = 1;
now_it.insn_cond = FALSE;
switch (now_it.state)
{
case OUTSIDE_IT_BLOCK:
switch (inst.it_insn_type)
{
case OUTSIDE_IT_INSN:
break;
case INSIDE_IT_INSN:
case INSIDE_IT_LAST_INSN:
if (thumb_mode == 0)
{
if (unified_syntax
&& !(implicit_it_mode & IMPLICIT_IT_MODE_ARM))
as_tsktsk (_("Warning: conditional outside an IT block"\
" for Thumb."));
}
else
{
if ((implicit_it_mode & IMPLICIT_IT_MODE_THUMB)
&& ARM_CPU_HAS_FEATURE (cpu_variant, arm_arch_t2))
{
/* Automatically generate the IT instruction. */
new_automatic_it_block (inst.cond);
if (inst.it_insn_type == INSIDE_IT_LAST_INSN)
close_automatic_it_block ();
}
else
{
inst.error = BAD_OUT_IT;
return FAIL;
}
}
break;
case IF_INSIDE_IT_LAST_INSN:
case NEUTRAL_IT_INSN:
break;
case IT_INSN:
now_it.state = MANUAL_IT_BLOCK;
now_it.block_length = 0;
break;
}
break;
case AUTOMATIC_IT_BLOCK:
/* Three things may happen now:
a) We should increment current it block size;
b) We should close current it block (closing insn or 4 insns);
c) We should close current it block and start a new one (due
to incompatible conditions or
4 insns-length block reached). */
switch (inst.it_insn_type)
{
case OUTSIDE_IT_INSN:
/* The closure of the block shall happen immediatelly,
so any in_it_block () call reports the block as closed. */
force_automatic_it_block_close ();
break;
case INSIDE_IT_INSN:
case INSIDE_IT_LAST_INSN:
case IF_INSIDE_IT_LAST_INSN:
now_it.block_length++;
if (now_it.block_length > 4
|| !now_it_compatible (inst.cond))
{
force_automatic_it_block_close ();
if (inst.it_insn_type != IF_INSIDE_IT_LAST_INSN)
new_automatic_it_block (inst.cond);
}
else
{
now_it.insn_cond = TRUE;
now_it_add_mask (inst.cond);
}
if (now_it.state == AUTOMATIC_IT_BLOCK
&& (inst.it_insn_type == INSIDE_IT_LAST_INSN
|| inst.it_insn_type == IF_INSIDE_IT_LAST_INSN))
close_automatic_it_block ();
break;
case NEUTRAL_IT_INSN:
now_it.block_length++;
now_it.insn_cond = TRUE;
if (now_it.block_length > 4)
force_automatic_it_block_close ();
else
now_it_add_mask (now_it.cc & 1);
break;
case IT_INSN:
close_automatic_it_block ();
now_it.state = MANUAL_IT_BLOCK;
break;
}
break;
case MANUAL_IT_BLOCK:
{
/* Check conditional suffixes. */
const int cond = now_it.cc ^ ((now_it.mask >> 4) & 1) ^ 1;
int is_last;
now_it.mask <<= 1;
now_it.mask &= 0x1f;
is_last = (now_it.mask == 0x10);
now_it.insn_cond = TRUE;
switch (inst.it_insn_type)
{
case OUTSIDE_IT_INSN:
inst.error = BAD_NOT_IT;
return FAIL;
case INSIDE_IT_INSN:
if (cond != inst.cond)
{
inst.error = BAD_IT_COND;
return FAIL;
}
break;
case INSIDE_IT_LAST_INSN:
case IF_INSIDE_IT_LAST_INSN:
if (cond != inst.cond)
{
inst.error = BAD_IT_COND;
return FAIL;
}
if (!is_last)
{
inst.error = BAD_BRANCH;
return FAIL;
}
break;
case NEUTRAL_IT_INSN:
/* The BKPT instruction is unconditional even in an IT block. */
break;
case IT_INSN:
inst.error = BAD_IT_IT;
return FAIL;
}
}
break;
}
return SUCCESS;
}
struct depr_insn_mask
{
unsigned long pattern;
unsigned long mask;
const char* description;
};
/* List of 16-bit instruction patterns deprecated in an IT block in
ARMv8. */
static const struct depr_insn_mask depr_it_insns[] = {
{ 0xc000, 0xc000, N_("Short branches, Undefined, SVC, LDM/STM") },
{ 0xb000, 0xb000, N_("Miscellaneous 16-bit instructions") },
{ 0xa000, 0xb800, N_("ADR") },
{ 0x4800, 0xf800, N_("Literal loads") },
{ 0x4478, 0xf478, N_("Hi-register ADD, MOV, CMP, BX, BLX using pc") },
{ 0x4487, 0xfc87, N_("Hi-register ADD, MOV, CMP using pc") },
/* NOTE: 0x00dd is not the real encoding, instead, it is the 'tvalue'
field in asm_opcode. 'tvalue' is used at the stage this check happen. */
{ 0x00dd, 0x7fff, N_("ADD/SUB sp, sp #imm") },
{ 0, 0, NULL }
};
static void
it_fsm_post_encode (void)
{
int is_last;
if (!now_it.state_handled)
handle_it_state ();
if (now_it.insn_cond
&& !now_it.warn_deprecated
&& warn_on_deprecated
&& ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v8))
{
if (inst.instruction >= 0x10000)
{
as_tsktsk (_("IT blocks containing 32-bit Thumb instructions are "
"deprecated in ARMv8"));
now_it.warn_deprecated = TRUE;
}
else
{
const struct depr_insn_mask *p = depr_it_insns;
while (p->mask != 0)
{
if ((inst.instruction & p->mask) == p->pattern)
{
as_tsktsk (_("IT blocks containing 16-bit Thumb instructions "
"of the following class are deprecated in ARMv8: "
"%s"), p->description);
now_it.warn_deprecated = TRUE;
break;
}
++p;
}
}
if (now_it.block_length > 1)
{
as_tsktsk (_("IT blocks containing more than one conditional "
"instruction are deprecated in ARMv8"));
now_it.warn_deprecated = TRUE;
}
}
is_last = (now_it.mask == 0x10);
if (is_last)
{
now_it.state = OUTSIDE_IT_BLOCK;
now_it.mask = 0;
}
}
static void
force_automatic_it_block_close (void)
{
if (now_it.state == AUTOMATIC_IT_BLOCK)
{
close_automatic_it_block ();
now_it.state = OUTSIDE_IT_BLOCK;
now_it.mask = 0;
}
}
static int
in_it_block (void)
{
if (!now_it.state_handled)
handle_it_state ();
return now_it.state != OUTSIDE_IT_BLOCK;
}
void
md_assemble (char *str)
{
char *p = str;
const struct asm_opcode * opcode;
/* 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);
}
memset (&inst, '\0', sizeof (inst));
inst.reloc.type = BFD_RELOC_UNUSED;
opcode = opcode_lookup (&p);
if (!opcode)
{
/* It wasn't an instruction, but it might be a register alias of
the form alias .req reg, or a Neon .dn/.qn directive. */
if (! create_register_alias (str, p)
&& ! create_neon_reg_alias (str, p))
as_bad (_("bad instruction `%s'"), str);
return;
}
if (warn_on_deprecated && opcode->tag == OT_cinfix3_deprecated)
as_tsktsk (_("s suffix on comparison instruction is deprecated"));
/* The value which unconditional instructions should have in place of the
condition field. */
inst.uncond_value = (opcode->tag == OT_csuffixF) ? 0xf : -1;
if (thumb_mode)
{
arm_feature_set variant;
variant = cpu_variant;
/* Only allow coprocessor instructions on Thumb-2 capable devices. */
if (!ARM_CPU_HAS_FEATURE (variant, arm_arch_t2))
ARM_CLEAR_FEATURE (variant, variant, fpu_any_hard);
/* Check that this instruction is supported for this CPU. */
if (!opcode->tvariant
|| (thumb_mode == 1
&& !ARM_CPU_HAS_FEATURE (variant, *opcode->tvariant)))
{
as_bad (_("selected processor does not support Thumb mode `%s'"), str);
return;
}
if (inst.cond != COND_ALWAYS && !unified_syntax
&& opcode->tencode != do_t_branch)
{
as_bad (_("Thumb does not support conditional execution"));
return;
}
if (!ARM_CPU_HAS_FEATURE (variant, arm_ext_v6t2))
{
if (opcode->tencode != do_t_blx && opcode->tencode != do_t_branch23
&& !(ARM_CPU_HAS_FEATURE(*opcode->tvariant, arm_ext_msr)
|| ARM_CPU_HAS_FEATURE(*opcode->tvariant, arm_ext_barrier)))
{
/* Two things are addressed here.
1) Implicit require narrow instructions on Thumb-1.
This avoids relaxation accidentally introducing Thumb-2
instructions.
2) Reject wide instructions in non Thumb-2 cores. */
if (inst.size_req == 0)
inst.size_req = 2;
else if (inst.size_req == 4)
{
as_bad (_("selected processor does not support Thumb-2 mode `%s'"), str);
return;
}
}
}
inst.instruction = opcode->tvalue;
if (!parse_operands (p, opcode->operands, /*thumb=*/TRUE))
{
/* Prepare the it_insn_type for those encodings that don't set
it. */
it_fsm_pre_encode ();
opcode->tencode ();
it_fsm_post_encode ();
}
if (!(inst.error || inst.relax))
{
gas_assert (inst.instruction < 0xe800 || inst.instruction > 0xffff);
inst.size = (inst.instruction > 0xffff ? 4 : 2);
if (inst.size_req && inst.size_req != inst.size)
{
as_bad (_("cannot honor width suffix -- `%s'"), str);
return;
}
}
/* Something has gone badly wrong if we try to relax a fixed size
instruction. */
gas_assert (inst.size_req == 0 || !inst.relax);
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used,
*opcode->tvariant);
/* Many Thumb-2 instructions also have Thumb-1 variants, so explicitly
set those bits when Thumb-2 32-bit instructions are seen. ie.
anything other than bl/blx and v6-M instructions.
The impact of relaxable instructions will be considered later after we
finish all relaxation. */
if ((inst.size == 4 && (inst.instruction & 0xf800e800) != 0xf000e800)
&& !(ARM_CPU_HAS_FEATURE (*opcode->tvariant, arm_ext_msr)
|| ARM_CPU_HAS_FEATURE (*opcode->tvariant, arm_ext_barrier)))
ARM_MERGE_FEATURE_SETS (thumb_arch_used, thumb_arch_used,
arm_ext_v6t2);
check_neon_suffixes;
if (!inst.error)
{
mapping_state (MAP_THUMB);
}
}
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v1))
{
bfd_boolean is_bx;
/* bx is allowed on v5 cores, and sometimes on v4 cores. */
is_bx = (opcode->aencode == do_bx);
/* Check that this instruction is supported for this CPU. */
if (!(is_bx && fix_v4bx)
&& !(opcode->avariant &&
ARM_CPU_HAS_FEATURE (cpu_variant, *opcode->avariant)))
{
as_bad (_("selected processor does not support ARM mode `%s'"), str);
return;
}
if (inst.size_req)
{
as_bad (_("width suffixes are invalid in ARM mode -- `%s'"), str);
return;
}
inst.instruction = opcode->avalue;
if (opcode->tag == OT_unconditionalF)
inst.instruction |= 0xF << 28;
else
inst.instruction |= inst.cond << 28;
inst.size = INSN_SIZE;
if (!parse_operands (p, opcode->operands, /*thumb=*/FALSE))
{
it_fsm_pre_encode ();
opcode->aencode ();
it_fsm_post_encode ();
}
/* Arm mode bx is marked as both v4T and v5 because it's still required
on a hypothetical non-thumb v5 core. */
if (is_bx)
ARM_MERGE_FEATURE_SETS (arm_arch_used, arm_arch_used, arm_ext_v4t);
else
ARM_MERGE_FEATURE_SETS (arm_arch_used, arm_arch_used,
*opcode->avariant);
check_neon_suffixes;
if (!inst.error)
{
mapping_state (MAP_ARM);
}
}
else
{
as_bad (_("attempt to use an ARM instruction on a Thumb-only processor "
"-- `%s'"), str);
return;
}
output_inst (str);
}
static void
check_it_blocks_finished (void)
{
#ifdef OBJ_ELF
asection *sect;
for (sect = stdoutput->sections; sect != NULL; sect = sect->next)
if (seg_info (sect)->tc_segment_info_data.current_it.state
== MANUAL_IT_BLOCK)
{
as_warn (_("section '%s' finished with an open IT block."),
sect->name);
}
#else
if (now_it.state == MANUAL_IT_BLOCK)
as_warn (_("file finished with an open IT block."));
#endif
}
/* Various frobbings of labels and their addresses. */
void
arm_start_line_hook (void)
{
last_label_seen = NULL;
}
void
arm_frob_label (symbolS * sym)
{
last_label_seen = sym;
ARM_SET_THUMB (sym, thumb_mode);
#if defined OBJ_COFF || defined OBJ_ELF
ARM_SET_INTERWORK (sym, support_interwork);
#endif
force_automatic_it_block_close ();
/* Note - do not allow local symbols (.Lxxx) to be labelled
as Thumb functions. This is because these labels, whilst
they exist inside Thumb code, are not the entry points for
possible ARM->Thumb calls. Also, these labels can be used
as part of a computed goto or switch statement. eg gcc
can generate code that looks like this:
ldr r2, [pc, .Laaa]
lsl r3, r3, #2
ldr r2, [r3, r2]
mov pc, r2
.Lbbb: .word .Lxxx
.Lccc: .word .Lyyy
..etc...
.Laaa: .word Lbbb
The first instruction loads the address of the jump table.
The second instruction converts a table index into a byte offset.
The third instruction gets the jump address out of the table.
The fourth instruction performs the jump.
If the address stored at .Laaa is that of a symbol which has the
Thumb_Func bit set, then the linker will arrange for this address
to have the bottom bit set, which in turn would mean that the
address computation performed by the third instruction would end
up with the bottom bit set. Since the ARM is capable of unaligned
word loads, the instruction would then load the incorrect address
out of the jump table, and chaos would ensue. */
if (label_is_thumb_function_name
&& (S_GET_NAME (sym)[0] != '.' || S_GET_NAME (sym)[1] != 'L')
&& (bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) != 0)
{
/* When the address of a Thumb function is taken the bottom
bit of that address should be set. This will allow
interworking between Arm and Thumb functions to work
correctly. */
THUMB_SET_FUNC (sym, 1);
label_is_thumb_function_name = FALSE;
}
dwarf2_emit_label (sym);
}
bfd_boolean
arm_data_in_code (void)
{
if (thumb_mode && ! strncmp (input_line_pointer + 1, "data:", 5))
{
*input_line_pointer = '/';
input_line_pointer += 5;
*input_line_pointer = 0;
return TRUE;
}
return FALSE;
}
char *
arm_canonicalize_symbol_name (char * name)
{
int len;
if (thumb_mode && (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, 0 }
#define REGNUM(p,n,t) REGDEF(p##n, n, t)
#define REGNUM2(p,n,t) REGDEF(p##n, 2 * n, t)
#define REGSET(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)
#define REGSETH(p,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), REGNUM(p,31,t)
#define REGSET2(p,t) \
REGNUM2(p, 0,t), REGNUM2(p, 1,t), REGNUM2(p, 2,t), REGNUM2(p, 3,t), \
REGNUM2(p, 4,t), REGNUM2(p, 5,t), REGNUM2(p, 6,t), REGNUM2(p, 7,t), \
REGNUM2(p, 8,t), REGNUM2(p, 9,t), REGNUM2(p,10,t), REGNUM2(p,11,t), \
REGNUM2(p,12,t), REGNUM2(p,13,t), REGNUM2(p,14,t), REGNUM2(p,15,t)
#define SPLRBANK(base,bank,t) \
REGDEF(lr_##bank, 768|((base+0)<<16), t), \
REGDEF(sp_##bank, 768|((base+1)<<16), t), \
REGDEF(spsr_##bank, 768|(base<<16)|SPSR_BIT, t), \
REGDEF(LR_##bank, 768|((base+0)<<16), t), \
REGDEF(SP_##bank, 768|((base+1)<<16), t), \
REGDEF(SPSR_##bank, 768|(base<<16)|SPSR_BIT, t)
static const struct reg_entry reg_names[] =
{
/* ARM integer registers. */
REGSET(r, RN), REGSET(R, RN),
/* ATPCS synonyms. */
REGDEF(a1,0,RN), REGDEF(a2,1,RN), REGDEF(a3, 2,RN), REGDEF(a4, 3,RN),
REGDEF(v1,4,RN), REGDEF(v2,5,RN), REGDEF(v3, 6,RN), REGDEF(v4, 7,RN),
REGDEF(v5,8,RN), REGDEF(v6,9,RN), REGDEF(v7,10,RN), REGDEF(v8,11,RN),
REGDEF(A1,0,RN), REGDEF(A2,1,RN), REGDEF(A3, 2,RN), REGDEF(A4, 3,RN),
REGDEF(V1,4,RN), REGDEF(V2,5,RN), REGDEF(V3, 6,RN), REGDEF(V4, 7,RN),
REGDEF(V5,8,RN), REGDEF(V6,9,RN), REGDEF(V7,10,RN), REGDEF(V8,11,RN),
/* Well-known aliases. */
REGDEF(wr, 7,RN), REGDEF(sb, 9,RN), REGDEF(sl,10,RN), REGDEF(fp,11,RN),
REGDEF(ip,12,RN), REGDEF(sp,13,RN), REGDEF(lr,14,RN), REGDEF(pc,15,RN),
REGDEF(WR, 7,RN), REGDEF(SB, 9,RN), REGDEF(SL,10,RN), REGDEF(FP,11,RN),
REGDEF(IP,12,RN), REGDEF(SP,13,RN), REGDEF(LR,14,RN), REGDEF(PC,15,RN),
/* Coprocessor numbers. */
REGSET(p, CP), REGSET(P, CP),
/* Coprocessor register numbers. The "cr" variants are for backward
compatibility. */
REGSET(c, CN), REGSET(C, CN),
REGSET(cr, CN), REGSET(CR, CN),
/* ARM banked registers. */
REGDEF(R8_usr,512|(0<<16),RNB), REGDEF(r8_usr,512|(0<<16),RNB),
REGDEF(R9_usr,512|(1<<16),RNB), REGDEF(r9_usr,512|(1<<16),RNB),
REGDEF(R10_usr,512|(2<<16),RNB), REGDEF(r10_usr,512|(2<<16),RNB),
REGDEF(R11_usr,512|(3<<16),RNB), REGDEF(r11_usr,512|(3<<16),RNB),
REGDEF(R12_usr,512|(4<<16),RNB), REGDEF(r12_usr,512|(4<<16),RNB),
REGDEF(SP_usr,512|(5<<16),RNB), REGDEF(sp_usr,512|(5<<16),RNB),
REGDEF(LR_usr,512|(6<<16),RNB), REGDEF(lr_usr,512|(6<<16),RNB),
REGDEF(R8_fiq,512|(8<<16),RNB), REGDEF(r8_fiq,512|(8<<16),RNB),
REGDEF(R9_fiq,512|(9<<16),RNB), REGDEF(r9_fiq,512|(9<<16),RNB),
REGDEF(R10_fiq,512|(10<<16),RNB), REGDEF(r10_fiq,512|(10<<16),RNB),
REGDEF(R11_fiq,512|(11<<16),RNB), REGDEF(r11_fiq,512|(11<<16),RNB),
REGDEF(R12_fiq,512|(12<<16),RNB), REGDEF(r12_fiq,512|(12<<16),RNB),
REGDEF(SP_fiq,512|(13<<16),RNB), REGDEF(sp_fiq,512|(13<<16),RNB),
REGDEF(LR_fiq,512|(14<<16),RNB), REGDEF(lr_fiq,512|(14<<16),RNB),
REGDEF(SPSR_fiq,512|(14<<16)|SPSR_BIT,RNB), REGDEF(spsr_fiq,512|(14<<16)|SPSR_BIT,RNB),
SPLRBANK(0,IRQ,RNB), SPLRBANK(0,irq,RNB),
SPLRBANK(2,SVC,RNB), SPLRBANK(2,svc,RNB),
SPLRBANK(4,ABT,RNB), SPLRBANK(4,abt,RNB),
SPLRBANK(6,UND,RNB), SPLRBANK(6,und,RNB),
SPLRBANK(12,MON,RNB), SPLRBANK(12,mon,RNB),
REGDEF(elr_hyp,768|(14<<16),RNB), REGDEF(ELR_hyp,768|(14<<16),RNB),
REGDEF(sp_hyp,768|(15<<16),RNB), REGDEF(SP_hyp,768|(15<<16),RNB),
REGDEF(spsr_hyp,768|(14<<16)|SPSR_BIT,RNB),
REGDEF(SPSR_hyp,768|(14<<16)|SPSR_BIT,RNB),
/* FPA registers. */
REGNUM(f,0,FN), REGNUM(f,1,FN), REGNUM(f,2,FN), REGNUM(f,3,FN),
REGNUM(f,4,FN), REGNUM(f,5,FN), REGNUM(f,6,FN), REGNUM(f,7, FN),
REGNUM(F,0,FN), REGNUM(F,1,FN), REGNUM(F,2,FN), REGNUM(F,3,FN),
REGNUM(F,4,FN), REGNUM(F,5,FN), REGNUM(F,6,FN), REGNUM(F,7, FN),
/* VFP SP registers. */
REGSET(s,VFS), REGSET(S,VFS),
REGSETH(s,VFS), REGSETH(S,VFS),
/* VFP DP Registers. */
REGSET(d,VFD), REGSET(D,VFD),
/* Extra Neon DP registers. */
REGSETH(d,VFD), REGSETH(D,VFD),
/* Neon QP registers. */
REGSET2(q,NQ), REGSET2(Q,NQ),
/* VFP control registers. */
REGDEF(fpsid,0,VFC), REGDEF(fpscr,1,VFC), REGDEF(fpexc,8,VFC),
REGDEF(FPSID,0,VFC), REGDEF(FPSCR,1,VFC), REGDEF(FPEXC,8,VFC),
REGDEF(fpinst,9,VFC), REGDEF(fpinst2,10,VFC),
REGDEF(FPINST,9,VFC), REGDEF(FPINST2,10,VFC),
REGDEF(mvfr0,7,VFC), REGDEF(mvfr1,6,VFC),
REGDEF(MVFR0,7,VFC), REGDEF(MVFR1,6,VFC),
/* Maverick DSP coprocessor registers. */
REGSET(mvf,MVF), REGSET(mvd,MVD), REGSET(mvfx,MVFX), REGSET(mvdx,MVDX),
REGSET(MVF,MVF), REGSET(MVD,MVD), REGSET(MVFX,MVFX), REGSET(MVDX,MVDX),
REGNUM(mvax,0,MVAX), REGNUM(mvax,1,MVAX),
REGNUM(mvax,2,MVAX), REGNUM(mvax,3,MVAX),
REGDEF(dspsc,0,DSPSC),
REGNUM(MVAX,0,MVAX), REGNUM(MVAX,1,MVAX),
REGNUM(MVAX,2,MVAX), REGNUM(MVAX,3,MVAX),
REGDEF(DSPSC,0,DSPSC),
/* iWMMXt data registers - p0, c0-15. */
REGSET(wr,MMXWR), REGSET(wR,MMXWR), REGSET(WR, MMXWR),
/* iWMMXt control registers - p1, c0-3. */
REGDEF(wcid, 0,MMXWC), REGDEF(wCID, 0,MMXWC), REGDEF(WCID, 0,MMXWC),
REGDEF(wcon, 1,MMXWC), REGDEF(wCon, 1,MMXWC), REGDEF(WCON, 1,MMXWC),
REGDEF(wcssf, 2,MMXWC), REGDEF(wCSSF, 2,MMXWC), REGDEF(WCSSF, 2,MMXWC),
REGDEF(wcasf, 3,MMXWC), REGDEF(wCASF, 3,MMXWC), REGDEF(WCASF, 3,MMXWC),
/* iWMMXt scalar (constant/offset) registers - p1, c8-11. */
REGDEF(wcgr0, 8,MMXWCG), REGDEF(wCGR0, 8,MMXWCG), REGDEF(WCGR0, 8,MMXWCG),
REGDEF(wcgr1, 9,MMXWCG), REGDEF(wCGR1, 9,MMXWCG), REGDEF(WCGR1, 9,MMXWCG),
REGDEF(wcgr2,10,MMXWCG), REGDEF(wCGR2,10,MMXWCG), REGDEF(WCGR2,10,MMXWCG),
REGDEF(wcgr3,11,MMXWCG), REGDEF(wCGR3,11,MMXWCG), REGDEF(WCGR3,11,MMXWCG),
/* XScale accumulator registers. */
REGNUM(acc,0,XSCALE), REGNUM(ACC,0,XSCALE),
};
#undef REGDEF
#undef REGNUM
#undef REGSET
/* Table of all PSR suffixes. Bare "CPSR" and "SPSR" are handled
within psr_required_here. */
static const struct asm_psr psrs[] =
{
/* Backward compatibility notation. Note that "all" is no longer
truly all possible PSR bits. */
{"all", PSR_c | PSR_f},
{"flg", PSR_f},
{"ctl", PSR_c},
/* Individual flags. */
{"f", PSR_f},
{"c", PSR_c},
{"x", PSR_x},
{"s", PSR_s},
/* Combinations of flags. */
{"fs", PSR_f | PSR_s},
{"fx", PSR_f | PSR_x},
{"fc", PSR_f | PSR_c},
{"sf", PSR_s | PSR_f},
{"sx", PSR_s | PSR_x},
{"sc", PSR_s | PSR_c},
{"xf", PSR_x | PSR_f},
{"xs", PSR_x | PSR_s},
{"xc", PSR_x | PSR_c},
{"cf", PSR_c | PSR_f},
{"cs", PSR_c | PSR_s},
{"cx", PSR_c | PSR_x},
{"fsx", PSR_f | PSR_s | PSR_x},
{"fsc", PSR_f | PSR_s | PSR_c},
{"fxs", PSR_f | PSR_x | PSR_s},
{"fxc", PSR_f | PSR_x | PSR_c},
{"fcs", PSR_f | PSR_c | PSR_s},
{"fcx", PSR_f | PSR_c | PSR_x},
{"sfx", PSR_s | PSR_f | PSR_x},
{"sfc", PSR_s | PSR_f | PSR_c},
{"sxf", PSR_s | PSR_x | PSR_f},
{"sxc", PSR_s | PSR_x | PSR_c},
{"scf", PSR_s | PSR_c | PSR_f},
{"scx", PSR_s | PSR_c | PSR_x},
{"xfs", PSR_x | PSR_f | PSR_s},
{"xfc", PSR_x | PSR_f | PSR_c},
{"xsf", PSR_x | PSR_s | PSR_f},
{"xsc", PSR_x | PSR_s | PSR_c},
{"xcf", PSR_x | PSR_c | PSR_f},
{"xcs", PSR_x | PSR_c | PSR_s},
{"cfs", PSR_c | PSR_f | PSR_s},
{"cfx", PSR_c | PSR_f | PSR_x},
{"csf", PSR_c | PSR_s | PSR_f},
{"csx", PSR_c | PSR_s | PSR_x},
{"cxf", PSR_c | PSR_x | PSR_f},
{"cxs", PSR_c | PSR_x | PSR_s},
{"fsxc", PSR_f | PSR_s | PSR_x | PSR_c},
{"fscx", PSR_f | PSR_s | PSR_c | PSR_x},
{"fxsc", PSR_f | PSR_x | PSR_s | PSR_c},
{"fxcs", PSR_f | PSR_x | PSR_c | PSR_s},
{"fcsx", PSR_f | PSR_c | PSR_s | PSR_x},
{"fcxs", PSR_f | PSR_c | PSR_x | PSR_s},
{"sfxc", PSR_s | PSR_f | PSR_x | PSR_c},
{"sfcx", PSR_s | PSR_f | PSR_c | PSR_x},
{"sxfc", PSR_s | PSR_x | PSR_f | PSR_c},
{"sxcf", PSR_s | PSR_x | PSR_c | PSR_f},
{"scfx", PSR_s | PSR_c | PSR_f | PSR_x},
{"scxf", PSR_s | PSR_c | PSR_x | PSR_f},
{"xfsc", PSR_x | PSR_f | PSR_s | PSR_c},
{"xfcs", PSR_x | PSR_f | PSR_c | PSR_s},
{"xsfc", PSR_x | PSR_s | PSR_f | PSR_c},
{"xscf", PSR_x | PSR_s | PSR_c | PSR_f},
{"xcfs", PSR_x | PSR_c | PSR_f | PSR_s},
{"xcsf", PSR_x | PSR_c | PSR_s | PSR_f},
{"cfsx", PSR_c | PSR_f | PSR_s | PSR_x},
{"cfxs", PSR_c | PSR_f | PSR_x | PSR_s},
{"csfx", PSR_c | PSR_s | PSR_f | PSR_x},
{"csxf", PSR_c | PSR_s | PSR_x | PSR_f},
{"cxfs", PSR_c | PSR_x | PSR_f | PSR_s},
{"cxsf", PSR_c | PSR_x | PSR_s | PSR_f},
};
/* Table of V7M psr names. */
static const struct asm_psr v7m_psrs[] =
{
{"apsr", 0 }, {"APSR", 0 },
{"iapsr", 1 }, {"IAPSR", 1 },
{"eapsr", 2 }, {"EAPSR", 2 },
{"psr", 3 }, {"PSR", 3 },
{"xpsr", 3 }, {"XPSR", 3 }, {"xPSR", 3 },
{"ipsr", 5 }, {"IPSR", 5 },
{"epsr", 6 }, {"EPSR", 6 },
{"iepsr", 7 }, {"IEPSR", 7 },
{"msp", 8 }, {"MSP", 8 },
{"psp", 9 }, {"PSP", 9 },
{"primask", 16}, {"PRIMASK", 16},
{"basepri", 17}, {"BASEPRI", 17},
{"basepri_max", 18}, {"BASEPRI_MAX", 18},
{"basepri_max", 18}, {"BASEPRI_MASK", 18}, /* Typo, preserved for backwards compatibility. */
{"faultmask", 19}, {"FAULTMASK", 19},
{"control", 20}, {"CONTROL", 20}
};
/* Table of all shift-in-operand names. */
static const struct asm_shift_name shift_names [] =
{
{ "asl", SHIFT_LSL }, { "ASL", SHIFT_LSL },
{ "lsl", SHIFT_LSL }, { "LSL", SHIFT_LSL },
{ "lsr", SHIFT_LSR }, { "LSR", SHIFT_LSR },
{ "asr", SHIFT_ASR }, { "ASR", SHIFT_ASR },
{ "ror", SHIFT_ROR }, { "ROR", SHIFT_ROR },
{ "rrx", SHIFT_RRX }, { "RRX", SHIFT_RRX }
};
/* Table of all explicit relocation names. */
#ifdef OBJ_ELF
static struct reloc_entry reloc_names[] =
{
{ "got", BFD_RELOC_ARM_GOT32 }, { "GOT", BFD_RELOC_ARM_GOT32 },
{ "gotoff", BFD_RELOC_ARM_GOTOFF }, { "GOTOFF", BFD_RELOC_ARM_GOTOFF },
{ "plt", BFD_RELOC_ARM_PLT32 }, { "PLT", BFD_RELOC_ARM_PLT32 },
{ "target1", BFD_RELOC_ARM_TARGET1 }, { "TARGET1", BFD_RELOC_ARM_TARGET1 },
{ "target2", BFD_RELOC_ARM_TARGET2 }, { "TARGET2", BFD_RELOC_ARM_TARGET2 },
{ "sbrel", BFD_RELOC_ARM_SBREL32 }, { "SBREL", BFD_RELOC_ARM_SBREL32 },
{ "tlsgd", BFD_RELOC_ARM_TLS_GD32}, { "TLSGD", BFD_RELOC_ARM_TLS_GD32},
{ "tlsldm", BFD_RELOC_ARM_TLS_LDM32}, { "TLSLDM", BFD_RELOC_ARM_TLS_LDM32},
{ "tlsldo", BFD_RELOC_ARM_TLS_LDO32}, { "TLSLDO", BFD_RELOC_ARM_TLS_LDO32},
{ "gottpoff",BFD_RELOC_ARM_TLS_IE32}, { "GOTTPOFF",BFD_RELOC_ARM_TLS_IE32},
{ "tpoff", BFD_RELOC_ARM_TLS_LE32}, { "TPOFF", BFD_RELOC_ARM_TLS_LE32},
{ "got_prel", BFD_RELOC_ARM_GOT_PREL}, { "GOT_PREL", BFD_RELOC_ARM_GOT_PREL},
{ "tlsdesc", BFD_RELOC_ARM_TLS_GOTDESC},
{ "TLSDESC", BFD_RELOC_ARM_TLS_GOTDESC},
{ "tlscall", BFD_RELOC_ARM_TLS_CALL},
{ "TLSCALL", BFD_RELOC_ARM_TLS_CALL},
{ "tlsdescseq", BFD_RELOC_ARM_TLS_DESCSEQ},
{ "TLSDESCSEQ", BFD_RELOC_ARM_TLS_DESCSEQ}
};
#endif
/* Table of all conditional affixes. 0xF is not defined as a condition code. */
static const struct asm_cond conds[] =
{
{"eq", 0x0},
{"ne", 0x1},
{"cs", 0x2}, {"hs", 0x2},
{"cc", 0x3}, {"ul", 0x3}, {"lo", 0x3},
{"mi", 0x4},
{"pl", 0x5},
{"vs", 0x6},
{"vc", 0x7},
{"hi", 0x8},
{"ls", 0x9},
{"ge", 0xa},
{"lt", 0xb},
{"gt", 0xc},
{"le", 0xd},
{"al", 0xe}
};
#define UL_BARRIER(L,U,CODE,FEAT) \
{ L, CODE, ARM_FEATURE (FEAT, 0) }, \
{ U, CODE, ARM_FEATURE (FEAT, 0) }
static struct asm_barrier_opt barrier_opt_names[] =
{
UL_BARRIER ("sy", "SY", 0xf, ARM_EXT_BARRIER),
UL_BARRIER ("st", "ST", 0xe, ARM_EXT_BARRIER),
UL_BARRIER ("ld", "LD", 0xd, ARM_EXT_V8),
UL_BARRIER ("ish", "ISH", 0xb, ARM_EXT_BARRIER),
UL_BARRIER ("sh", "SH", 0xb, ARM_EXT_BARRIER),
UL_BARRIER ("ishst", "ISHST", 0xa, ARM_EXT_BARRIER),
UL_BARRIER ("shst", "SHST", 0xa, ARM_EXT_BARRIER),
UL_BARRIER ("ishld", "ISHLD", 0x9, ARM_EXT_V8),
UL_BARRIER ("un", "UN", 0x7, ARM_EXT_BARRIER),
UL_BARRIER ("nsh", "NSH", 0x7, ARM_EXT_BARRIER),
UL_BARRIER ("unst", "UNST", 0x6, ARM_EXT_BARRIER),
UL_BARRIER ("nshst", "NSHST", 0x6, ARM_EXT_BARRIER),
UL_BARRIER ("nshld", "NSHLD", 0x5, ARM_EXT_V8),
UL_BARRIER ("osh", "OSH", 0x3, ARM_EXT_BARRIER),
UL_BARRIER ("oshst", "OSHST", 0x2, ARM_EXT_BARRIER),
UL_BARRIER ("oshld", "OSHLD", 0x1, ARM_EXT_V8)
};
#undef UL_BARRIER
/* Table of ARM-format instructions. */
/* Macros for gluing together operand strings. N.B. In all cases
other than OPS0, the trailing OP_stop comes from default
zero-initialization of the unspecified elements of the array. */
#define OPS0() { OP_stop, }
#define OPS1(a) { OP_##a, }
#define OPS2(a,b) { OP_##a,OP_##b, }
#define OPS3(a,b,c) { OP_##a,OP_##b,OP_##c, }
#define OPS4(a,b,c,d) { OP_##a,OP_##b,OP_##c,OP_##d, }
#define OPS5(a,b,c,d,e) { OP_##a,OP_##b,OP_##c,OP_##d,OP_##e, }
#define OPS6(a,b,c,d,e,f) { OP_##a,OP_##b,OP_##c,OP_##d,OP_##e,OP_##f, }
/* These macros are similar to the OPSn, but do not prepend the OP_ prefix.
This is useful when mixing operands for ARM and THUMB, i.e. using the
MIX_ARM_THUMB_OPERANDS macro.
In order to use these macros, prefix the number of operands with _
e.g. _3. */
#define OPS_1(a) { a, }
#define OPS_2(a,b) { a,b, }
#define OPS_3(a,b,c) { a,b,c, }
#define OPS_4(a,b,c,d) { a,b,c,d, }
#define OPS_5(a,b,c,d,e) { a,b,c,d,e, }
#define OPS_6(a,b,c,d,e,f) { a,b,c,d,e,f, }
/* These macros abstract out the exact format of the mnemonic table and
save some repeated characters. */
/* The normal sort of mnemonic; has a Thumb variant; takes a conditional suffix. */
#define TxCE(mnem, op, top, nops, ops, ae, te) \
{ mnem, OPS##nops ops, OT_csuffix, 0x##op, top, ARM_VARIANT, \
THUMB_VARIANT, do_##ae, do_##te }
/* Two variants of the above - TCE for a numeric Thumb opcode, tCE for
a T_MNEM_xyz enumerator. */
#define TCE(mnem, aop, top, nops, ops, ae, te) \
TxCE (mnem, aop, 0x##top, nops, ops, ae, te)
#define tCE(mnem, aop, top, nops, ops, ae, te) \
TxCE (mnem, aop, T_MNEM##top, nops, ops, ae, te)
/* Second most common sort of mnemonic: has a Thumb variant, takes a conditional
infix after the third character. */
#define TxC3(mnem, op, top, nops, ops, ae, te) \
{ mnem, OPS##nops ops, OT_cinfix3, 0x##op, top, ARM_VARIANT, \
THUMB_VARIANT, do_##ae, do_##te }
#define TxC3w(mnem, op, top, nops, ops, ae, te) \
{ mnem, OPS##nops ops, OT_cinfix3_deprecated, 0x##op, top, ARM_VARIANT, \
THUMB_VARIANT, do_##ae, do_##te }
#define TC3(mnem, aop, top, nops, ops, ae, te) \
TxC3 (mnem, aop, 0x##top, nops, ops, ae, te)
#define TC3w(mnem, aop, top, nops, ops, ae, te) \
TxC3w (mnem, aop, 0x##top, nops, ops, ae, te)
#define tC3(mnem, aop, top, nops, ops, ae, te) \
TxC3 (mnem, aop, T_MNEM##top, nops, ops, ae, te)
#define tC3w(mnem, aop, top, nops, ops, ae, te) \
TxC3w (mnem, aop, T_MNEM##top, nops, ops, ae, te)
/* Mnemonic that cannot be conditionalized. The ARM condition-code
field is still 0xE. Many of the Thumb variants can be executed
conditionally, so this is checked separately. */
#define TUE(mnem, op, top, nops, ops, ae, te) \
{ mnem, OPS##nops ops, OT_unconditional, 0x##op, 0x##top, ARM_VARIANT, \
THUMB_VARIANT, do_##ae, do_##te }
/* Same as TUE but the encoding function for ARM and Thumb modes is the same.
Used by mnemonics that have very minimal differences in the encoding for
ARM and Thumb variants and can be handled in a common function. */
#define TUEc(mnem, op, top, nops, ops, en) \
{ mnem, OPS##nops ops, OT_unconditional, 0x##op, 0x##top, ARM_VARIANT, \
THUMB_VARIANT, do_##en, do_##en }
/* Mnemonic that cannot be conditionalized, and bears 0xF in its ARM
condition code field. */
#define TUF(mnem, op, top, nops, ops, ae, te) \
{ mnem, OPS##nops ops, OT_unconditionalF, 0x##op, 0x##top, ARM_VARIANT, \
THUMB_VARIANT, do_##ae, do_##te }
/* ARM-only variants of all the above. */
#define CE(mnem, op, nops, ops, ae) \
{ mnem, OPS##nops ops, OT_csuffix, 0x##op, 0x0, ARM_VARIANT, 0, do_##ae, NULL }
#define C3(mnem, op, nops, ops, ae) \
{ #mnem, OPS##nops ops, OT_cinfix3, 0x##op, 0x0, ARM_VARIANT, 0, do_##ae, NULL }
/* Legacy mnemonics that always have conditional infix after the third
character. */
#define CL(mnem, op, nops, ops, ae) \
{ mnem, OPS##nops ops, OT_cinfix3_legacy, \
0x##op, 0x0, ARM_VARIANT, 0, do_##ae, NULL }
/* Coprocessor instructions. Isomorphic between Arm and Thumb-2. */
#define cCE(mnem, op, nops, ops, ae) \
{ mnem, OPS##nops ops, OT_csuffix, 0x##op, 0xe##op, ARM_VARIANT, ARM_VARIANT, do_##ae, do_##ae }
/* Legacy coprocessor instructions where conditional infix and conditional
suffix are ambiguous. For consistency this includes all FPA instructions,
not just the potentially ambiguous ones. */
#define cCL(mnem, op, nops, ops, ae) \
{ mnem, OPS##nops ops, OT_cinfix3_legacy, \
0x##op, 0xe##op, ARM_VARIANT, ARM_VARIANT, do_##ae, do_##ae }
/* Coprocessor, takes either a suffix or a position-3 infix
(for an FPA corner case). */
#define C3E(mnem, op, nops, ops, ae) \
{ mnem, OPS##nops ops, OT_csuf_or_in3, \
0x##op, 0xe##op, ARM_VARIANT, ARM_VARIANT, do_##ae, do_##ae }
#define xCM_(m1, m2, m3, op, nops, ops, ae) \
{ m1 #m2 m3, OPS##nops ops, \
sizeof (#m2) == 1 ? OT_odd_infix_unc : OT_odd_infix_0 + sizeof (m1) - 1, \
0x##op, 0x0, ARM_VARIANT, 0, do_##ae, NULL }
#define CM(m1, m2, op, nops, ops, ae) \
xCM_ (m1, , m2, op, nops, ops, ae), \
xCM_ (m1, eq, m2, op, nops, ops, ae), \
xCM_ (m1, ne, m2, op, nops, ops, ae), \
xCM_ (m1, cs, m2, op, nops, ops, ae), \
xCM_ (m1, hs, m2, op, nops, ops, ae), \
xCM_ (m1, cc, m2, op, nops, ops, ae), \
xCM_ (m1, ul, m2, op, nops, ops, ae), \
xCM_ (m1, lo, m2, op, nops, ops, ae), \
xCM_ (m1, mi, m2, op, nops, ops, ae), \
xCM_ (m1, pl, m2, op, nops, ops, ae), \
xCM_ (m1, vs, m2, op, nops, ops, ae), \
xCM_ (m1, vc, m2, op, nops, ops, ae), \
xCM_ (m1, hi, m2, op, nops, ops, ae), \
xCM_ (m1, ls, m2, op, nops, ops, ae), \
xCM_ (m1, ge, m2, op, nops, ops, ae), \
xCM_ (m1, lt, m2, op, nops, ops, ae), \
xCM_ (m1, gt, m2, op, nops, ops, ae), \
xCM_ (m1, le, m2, op, nops, ops, ae), \
xCM_ (m1, al, m2, op, nops, ops, ae)
#define UE(mnem, op, nops, ops, ae) \
{ #mnem, OPS##nops ops, OT_unconditional, 0x##op, 0, ARM_VARIANT, 0, do_##ae, NULL }
#define UF(mnem, op, nops, ops, ae) \
{ #mnem, OPS##nops ops, OT_unconditionalF, 0x##op, 0, ARM_VARIANT, 0, do_##ae, NULL }
/* Neon data-processing. ARM versions are unconditional with cond=0xf.
The Thumb and ARM variants are mostly the same (bits 0-23 and 24/28), so we
use the same encoding function for each. */
#define NUF(mnem, op, nops, ops, enc) \
{ #mnem, OPS##nops ops, OT_unconditionalF, 0x##op, 0x##op, \
ARM_VARIANT, THUMB_VARIANT, do_##enc, do_##enc }
/* Neon data processing, version which indirects through neon_enc_tab for
the various overloaded versions of opcodes. */
#define nUF(mnem, op, nops, ops, enc) \
{ #mnem, OPS##nops ops, OT_unconditionalF, N_MNEM##op, N_MNEM##op, \
ARM_VARIANT, THUMB_VARIANT, do_##enc, do_##enc }
/* Neon insn with conditional suffix for the ARM version, non-overloaded
version. */
#define NCE_tag(mnem, op, nops, ops, enc, tag) \
{ #mnem, OPS##nops ops, tag, 0x##op, 0x##op, ARM_VARIANT, \
THUMB_VARIANT, do_##enc, do_##enc }
#define NCE(mnem, op, nops, ops, enc) \
NCE_tag (mnem, op, nops, ops, enc, OT_csuffix)
#define NCEF(mnem, op, nops, ops, enc) \
NCE_tag (mnem, op, nops, ops, enc, OT_csuffixF)
/* Neon insn with conditional suffix for the ARM version, overloaded types. */
#define nCE_tag(mnem, op, nops, ops, enc, tag) \
{ #mnem, OPS##nops ops, tag, N_MNEM##op, N_MNEM##op, \
ARM_VARIANT, THUMB_VARIANT, do_##enc, do_##enc }
#define nCE(mnem, op, nops, ops, enc) \
nCE_tag (mnem, op, nops, ops, enc, OT_csuffix)
#define nCEF(mnem, op, nops, ops, enc) \
nCE_tag (mnem, op, nops, ops, enc, OT_csuffixF)
#define do_0 0
static const struct asm_opcode insns[] =
{
#define ARM_VARIANT & arm_ext_v1 /* Core ARM Instructions. */
#define THUMB_VARIANT & arm_ext_v4t
tCE("and", 0000000, _and, 3, (RR, oRR, SH), arit, t_arit3c),
tC3("ands", 0100000, _ands, 3, (RR, oRR, SH), arit, t_arit3c),
tCE("eor", 0200000, _eor, 3, (RR, oRR, SH), arit, t_arit3c),
tC3("eors", 0300000, _eors, 3, (RR, oRR, SH), arit, t_arit3c),
tCE("sub", 0400000, _sub, 3, (RR, oRR, SH), arit, t_add_sub),
tC3("subs", 0500000, _subs, 3, (RR, oRR, SH), arit, t_add_sub),
tCE("add", 0800000, _add, 3, (RR, oRR, SHG), arit, t_add_sub),
tC3("adds", 0900000, _adds, 3, (RR, oRR, SHG), arit, t_add_sub),
tCE("adc", 0a00000, _adc, 3, (RR, oRR, SH), arit, t_arit3c),
tC3("adcs", 0b00000, _adcs, 3, (RR, oRR, SH), arit, t_arit3c),
tCE("sbc", 0c00000, _sbc, 3, (RR, oRR, SH), arit, t_arit3),
tC3("sbcs", 0d00000, _sbcs, 3, (RR, oRR, SH), arit, t_arit3),
tCE("orr", 1800000, _orr, 3, (RR, oRR, SH), arit, t_arit3c),
tC3("orrs", 1900000, _orrs, 3, (RR, oRR, SH), arit, t_arit3c),
tCE("bic", 1c00000, _bic, 3, (RR, oRR, SH), arit, t_arit3),
tC3("bics", 1d00000, _bics, 3, (RR, oRR, SH), arit, t_arit3),
/* The p-variants of tst/cmp/cmn/teq (below) are the pre-V6 mechanism
for setting PSR flag bits. They are obsolete in V6 and do not
have Thumb equivalents. */
tCE("tst", 1100000, _tst, 2, (RR, SH), cmp, t_mvn_tst),
tC3w("tsts", 1100000, _tst, 2, (RR, SH), cmp, t_mvn_tst),
CL("tstp", 110f000, 2, (RR, SH), cmp),
tCE("cmp", 1500000, _cmp, 2, (RR, SH), cmp, t_mov_cmp),
tC3w("cmps", 1500000, _cmp, 2, (RR, SH), cmp, t_mov_cmp),
CL("cmpp", 150f000, 2, (RR, SH), cmp),
tCE("cmn", 1700000, _cmn, 2, (RR, SH), cmp, t_mvn_tst),
tC3w("cmns", 1700000, _cmn, 2, (RR, SH), cmp, t_mvn_tst),
CL("cmnp", 170f000, 2, (RR, SH), cmp),
tCE("mov", 1a00000, _mov, 2, (RR, SH), mov, t_mov_cmp),
tC3("movs", 1b00000, _movs, 2, (RR, SH), mov, t_mov_cmp),
tCE("mvn", 1e00000, _mvn, 2, (RR, SH), mov, t_mvn_tst),
tC3("mvns", 1f00000, _mvns, 2, (RR, SH), mov, t_mvn_tst),
tCE("ldr", 4100000, _ldr, 2, (RR, ADDRGLDR),ldst, t_ldst),
tC3("ldrb", 4500000, _ldrb, 2, (RRnpc_npcsp, ADDRGLDR),ldst, t_ldst),
tCE("str", 4000000, _str, _2, (MIX_ARM_THUMB_OPERANDS (OP_RR,
OP_RRnpc),
OP_ADDRGLDR),ldst, t_ldst),
tC3("strb", 4400000, _strb, 2, (RRnpc_npcsp, ADDRGLDR),ldst, t_ldst),
tCE("stm", 8800000, _stmia, 2, (RRw, REGLST), ldmstm, t_ldmstm),
tC3("stmia", 8800000, _stmia, 2, (RRw, REGLST), ldmstm, t_ldmstm),
tC3("stmea", 8800000, _stmia, 2, (RRw, REGLST), ldmstm, t_ldmstm),
tCE("ldm", 8900000, _ldmia, 2, (RRw, REGLST), ldmstm, t_ldmstm),
tC3("ldmia", 8900000, _ldmia, 2, (RRw, REGLST), ldmstm, t_ldmstm),
tC3("ldmfd", 8900000, _ldmia, 2, (RRw, REGLST), ldmstm, t_ldmstm),
TCE("swi", f000000, df00, 1, (EXPi), swi, t_swi),
TCE("svc", f000000, df00, 1, (EXPi), swi, t_swi),
tCE("b", a000000, _b, 1, (EXPr), branch, t_branch),
TCE("bl", b000000, f000f800, 1, (EXPr), bl, t_branch23),
/* Pseudo ops. */
tCE("adr", 28f0000, _adr, 2, (RR, EXP), adr, t_adr),
C3(adrl, 28f0000, 2, (RR, EXP), adrl),
tCE("nop", 1a00000, _nop, 1, (oI255c), nop, t_nop),
tCE("udf", 7f000f0, _udf, 1, (oIffffb), bkpt, t_udf),
/* Thumb-compatibility pseudo ops. */
tCE("lsl", 1a00000, _lsl, 3, (RR, oRR, SH), shift, t_shift),
tC3("lsls", 1b00000, _lsls, 3, (RR, oRR, SH), shift, t_shift),
tCE("lsr", 1a00020, _lsr, 3, (RR, oRR, SH), shift, t_shift),
tC3("lsrs", 1b00020, _lsrs, 3, (RR, oRR, SH), shift, t_shift),
tCE("asr", 1a00040, _asr, 3, (RR, oRR, SH), shift, t_shift),
tC3("asrs", 1b00040, _asrs, 3, (RR, oRR, SH), shift, t_shift),
tCE("ror", 1a00060, _ror, 3, (RR, oRR, SH), shift, t_shift),
tC3("rors", 1b00060, _rors, 3, (RR, oRR, SH), shift, t_shift),
tCE("neg", 2600000, _neg, 2, (RR, RR), rd_rn, t_neg),
tC3("negs", 2700000, _negs, 2, (RR, RR), rd_rn, t_neg),
tCE("push", 92d0000, _push, 1, (REGLST), push_pop, t_push_pop),
tCE("pop", 8bd0000, _pop, 1, (REGLST), push_pop, t_push_pop),
/* These may simplify to neg. */
TCE("rsb", 0600000, ebc00000, 3, (RR, oRR, SH), arit, t_rsb),
TC3("rsbs", 0700000, ebd00000, 3, (RR, oRR, SH), arit, t_rsb),
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6
TCE("cpy", 1a00000, 4600, 2, (RR, RR), rd_rm, t_cpy),
/* V1 instructions with no Thumb analogue prior to V6T2. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("teq", 1300000, ea900f00, 2, (RR, SH), cmp, t_mvn_tst),
TC3w("teqs", 1300000, ea900f00, 2, (RR, SH), cmp, t_mvn_tst),
CL("teqp", 130f000, 2, (RR, SH), cmp),
TC3("ldrt", 4300000, f8500e00, 2, (RRnpc_npcsp, ADDR),ldstt, t_ldstt),
TC3("ldrbt", 4700000, f8100e00, 2, (RRnpc_npcsp, ADDR),ldstt, t_ldstt),
TC3("strt", 4200000, f8400e00, 2, (RR_npcsp, ADDR), ldstt, t_ldstt),
TC3("strbt", 4600000, f8000e00, 2, (RRnpc_npcsp, ADDR),ldstt, t_ldstt),
TC3("stmdb", 9000000, e9000000, 2, (RRw, REGLST), ldmstm, t_ldmstm),
TC3("stmfd", 9000000, e9000000, 2, (RRw, REGLST), ldmstm, t_ldmstm),
TC3("ldmdb", 9100000, e9100000, 2, (RRw, REGLST), ldmstm, t_ldmstm),
TC3("ldmea", 9100000, e9100000, 2, (RRw, REGLST), ldmstm, t_ldmstm),
/* V1 instructions with no Thumb analogue at all. */
CE("rsc", 0e00000, 3, (RR, oRR, SH), arit),
C3(rscs, 0f00000, 3, (RR, oRR, SH), arit),
C3(stmib, 9800000, 2, (RRw, REGLST), ldmstm),
C3(stmfa, 9800000, 2, (RRw, REGLST), ldmstm),
C3(stmda, 8000000, 2, (RRw, REGLST), ldmstm),
C3(stmed, 8000000, 2, (RRw, REGLST), ldmstm),
C3(ldmib, 9900000, 2, (RRw, REGLST), ldmstm),
C3(ldmed, 9900000, 2, (RRw, REGLST), ldmstm),
C3(ldmda, 8100000, 2, (RRw, REGLST), ldmstm),
C3(ldmfa, 8100000, 2, (RRw, REGLST), ldmstm),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v2 /* ARM 2 - multiplies. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v4t
tCE("mul", 0000090, _mul, 3, (RRnpc, RRnpc, oRR), mul, t_mul),
tC3("muls", 0100090, _muls, 3, (RRnpc, RRnpc, oRR), mul, t_mul),
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("mla", 0200090, fb000000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mlas, t_mla),
C3(mlas, 0300090, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mlas),
/* Generic coprocessor instructions. */
TCE("cdp", e000000, ee000000, 6, (RCP, I15b, RCN, RCN, RCN, oI7b), cdp, cdp),
TCE("ldc", c100000, ec100000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TC3("ldcl", c500000, ec500000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TCE("stc", c000000, ec000000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TC3("stcl", c400000, ec400000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TCE("mcr", e000010, ee000010, 6, (RCP, I7b, RR, RCN, RCN, oI7b), co_reg, co_reg),
TCE("mrc", e100010, ee100010, 6, (RCP, I7b, APSR_RR, RCN, RCN, oI7b), co_reg, co_reg),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v2s /* ARM 3 - swp instructions. */
CE("swp", 1000090, 3, (RRnpc, RRnpc, RRnpcb), rd_rm_rn),
C3(swpb, 1400090, 3, (RRnpc, RRnpc, RRnpcb), rd_rm_rn),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v3 /* ARM 6 Status register instructions. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_msr
TCE("mrs", 1000000, f3e08000, 2, (RRnpc, rPSR), mrs, t_mrs),
TCE("msr", 120f000, f3808000, 2, (wPSR, RR_EXi), msr, t_msr),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v3m /* ARM 7M long multiplies. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("smull", 0c00090, fb800000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull, t_mull),
CM("smull","s", 0d00090, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull),
TCE("umull", 0800090, fba00000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull, t_mull),
CM("umull","s", 0900090, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull),
TCE("smlal", 0e00090, fbc00000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull, t_mull),
CM("smlal","s", 0f00090, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull),
TCE("umlal", 0a00090, fbe00000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull, t_mull),
CM("umlal","s", 0b00090, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mull),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v4 /* ARM Architecture 4. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v4t
tC3("ldrh", 01000b0, _ldrh, 2, (RRnpc_npcsp, ADDRGLDRS), ldstv4, t_ldst),
tC3("strh", 00000b0, _strh, 2, (RRnpc_npcsp, ADDRGLDRS), ldstv4, t_ldst),
tC3("ldrsh", 01000f0, _ldrsh, 2, (RRnpc_npcsp, ADDRGLDRS), ldstv4, t_ldst),
tC3("ldrsb", 01000d0, _ldrsb, 2, (RRnpc_npcsp, ADDRGLDRS), ldstv4, t_ldst),
tC3("ldsh", 01000f0, _ldrsh, 2, (RRnpc_npcsp, ADDRGLDRS), ldstv4, t_ldst),
tC3("ldsb", 01000d0, _ldrsb, 2, (RRnpc_npcsp, ADDRGLDRS), ldstv4, t_ldst),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v4t_5
/* ARM Architecture 4T. */
/* Note: bx (and blx) are required on V5, even if the processor does
not support Thumb. */
TCE("bx", 12fff10, 4700, 1, (RR), bx, t_bx),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v5 /* ARM Architecture 5T. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v5t
/* Note: blx has 2 variants; the .value coded here is for
BLX(2). Only this variant has conditional execution. */
TCE("blx", 12fff30, 4780, 1, (RR_EXr), blx, t_blx),
TUE("bkpt", 1200070, be00, 1, (oIffffb), bkpt, t_bkpt),
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("clz", 16f0f10, fab0f080, 2, (RRnpc, RRnpc), rd_rm, t_clz),
TUF("ldc2", c100000, fc100000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TUF("ldc2l", c500000, fc500000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TUF("stc2", c000000, fc000000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TUF("stc2l", c400000, fc400000, 3, (RCP, RCN, ADDRGLDC), lstc, lstc),
TUF("cdp2", e000000, fe000000, 6, (RCP, I15b, RCN, RCN, RCN, oI7b), cdp, cdp),
TUF("mcr2", e000010, fe000010, 6, (RCP, I7b, RR, RCN, RCN, oI7b), co_reg, co_reg),
TUF("mrc2", e100010, fe100010, 6, (RCP, I7b, RR, RCN, RCN, oI7b), co_reg, co_reg),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v5exp /* ARM Architecture 5TExP. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v5exp
TCE("smlabb", 1000080, fb100000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smla, t_mla),
TCE("smlatb", 10000a0, fb100020, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smla, t_mla),
TCE("smlabt", 10000c0, fb100010, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smla, t_mla),
TCE("smlatt", 10000e0, fb100030, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smla, t_mla),
TCE("smlawb", 1200080, fb300000, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smla, t_mla),
TCE("smlawt", 12000c0, fb300010, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smla, t_mla),
TCE("smlalbb", 1400080, fbc00080, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smlal, t_mlal),
TCE("smlaltb", 14000a0, fbc000a0, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smlal, t_mlal),
TCE("smlalbt", 14000c0, fbc00090, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smlal, t_mlal),
TCE("smlaltt", 14000e0, fbc000b0, 4, (RRnpc, RRnpc, RRnpc, RRnpc), smlal, t_mlal),
TCE("smulbb", 1600080, fb10f000, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smultb", 16000a0, fb10f020, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smulbt", 16000c0, fb10f010, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smultt", 16000e0, fb10f030, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smulwb", 12000a0, fb30f000, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smulwt", 12000e0, fb30f010, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("qadd", 1000050, fa80f080, 3, (RRnpc, RRnpc, RRnpc), rd_rm_rn, t_simd2),
TCE("qdadd", 1400050, fa80f090, 3, (RRnpc, RRnpc, RRnpc), rd_rm_rn, t_simd2),
TCE("qsub", 1200050, fa80f0a0, 3, (RRnpc, RRnpc, RRnpc), rd_rm_rn, t_simd2),
TCE("qdsub", 1600050, fa80f0b0, 3, (RRnpc, RRnpc, RRnpc), rd_rm_rn, t_simd2),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v5e /* ARM Architecture 5TE. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TUF("pld", 450f000, f810f000, 1, (ADDR), pld, t_pld),
TC3("ldrd", 00000d0, e8500000, 3, (RRnpc_npcsp, oRRnpc_npcsp, ADDRGLDRS),
ldrd, t_ldstd),
TC3("strd", 00000f0, e8400000, 3, (RRnpc_npcsp, oRRnpc_npcsp,
ADDRGLDRS), ldrd, t_ldstd),
TCE("mcrr", c400000, ec400000, 5, (RCP, I15b, RRnpc, RRnpc, RCN), co_reg2c, co_reg2c),
TCE("mrrc", c500000, ec500000, 5, (RCP, I15b, RRnpc, RRnpc, RCN), co_reg2c, co_reg2c),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v5j /* ARM Architecture 5TEJ. */
TCE("bxj", 12fff20, f3c08f00, 1, (RR), bxj, t_bxj),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v6 /* ARM V6. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6
TUF("cpsie", 1080000, b660, 2, (CPSF, oI31b), cpsi, t_cpsi),
TUF("cpsid", 10c0000, b670, 2, (CPSF, oI31b), cpsi, t_cpsi),
tCE("rev", 6bf0f30, _rev, 2, (RRnpc, RRnpc), rd_rm, t_rev),
tCE("rev16", 6bf0fb0, _rev16, 2, (RRnpc, RRnpc), rd_rm, t_rev),
tCE("revsh", 6ff0fb0, _revsh, 2, (RRnpc, RRnpc), rd_rm, t_rev),
tCE("sxth", 6bf0070, _sxth, 3, (RRnpc, RRnpc, oROR), sxth, t_sxth),
tCE("uxth", 6ff0070, _uxth, 3, (RRnpc, RRnpc, oROR), sxth, t_sxth),
tCE("sxtb", 6af0070, _sxtb, 3, (RRnpc, RRnpc, oROR), sxth, t_sxth),
tCE("uxtb", 6ef0070, _uxtb, 3, (RRnpc, RRnpc, oROR), sxth, t_sxth),
TUF("setend", 1010000, b650, 1, (ENDI), setend, t_setend),
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("ldrex", 1900f9f, e8500f00, 2, (RRnpc_npcsp, ADDR), ldrex, t_ldrex),
TCE("strex", 1800f90, e8400000, 3, (RRnpc_npcsp, RRnpc_npcsp, ADDR),
strex, t_strex),
TUF("mcrr2", c400000, fc400000, 5, (RCP, I15b, RRnpc, RRnpc, RCN), co_reg2c, co_reg2c),
TUF("mrrc2", c500000, fc500000, 5, (RCP, I15b, RRnpc, RRnpc, RCN), co_reg2c, co_reg2c),
TCE("ssat", 6a00010, f3000000, 4, (RRnpc, I32, RRnpc, oSHllar),ssat, t_ssat),
TCE("usat", 6e00010, f3800000, 4, (RRnpc, I31, RRnpc, oSHllar),usat, t_usat),
/* ARM V6 not included in V7M. */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6_notm
TUF("rfeia", 8900a00, e990c000, 1, (RRw), rfe, rfe),
TUF("rfe", 8900a00, e990c000, 1, (RRw), rfe, rfe),
UF(rfeib, 9900a00, 1, (RRw), rfe),
UF(rfeda, 8100a00, 1, (RRw), rfe),
TUF("rfedb", 9100a00, e810c000, 1, (RRw), rfe, rfe),
TUF("rfefd", 8900a00, e990c000, 1, (RRw), rfe, rfe),
UF(rfefa, 8100a00, 1, (RRw), rfe),
TUF("rfeea", 9100a00, e810c000, 1, (RRw), rfe, rfe),
UF(rfeed, 9900a00, 1, (RRw), rfe),
TUF("srsia", 8c00500, e980c000, 2, (oRRw, I31w), srs, srs),
TUF("srs", 8c00500, e980c000, 2, (oRRw, I31w), srs, srs),
TUF("srsea", 8c00500, e980c000, 2, (oRRw, I31w), srs, srs),
UF(srsib, 9c00500, 2, (oRRw, I31w), srs),
UF(srsfa, 9c00500, 2, (oRRw, I31w), srs),
UF(srsda, 8400500, 2, (oRRw, I31w), srs),
UF(srsed, 8400500, 2, (oRRw, I31w), srs),
TUF("srsdb", 9400500, e800c000, 2, (oRRw, I31w), srs, srs),
TUF("srsfd", 9400500, e800c000, 2, (oRRw, I31w), srs, srs),
/* ARM V6 not included in V7M (eg. integer SIMD). */
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6_dsp
TUF("cps", 1020000, f3af8100, 1, (I31b), imm0, t_cps),
TCE("pkhbt", 6800010, eac00000, 4, (RRnpc, RRnpc, RRnpc, oSHll), pkhbt, t_pkhbt),
TCE("pkhtb", 6800050, eac00020, 4, (RRnpc, RRnpc, RRnpc, oSHar), pkhtb, t_pkhtb),
TCE("qadd16", 6200f10, fa90f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("qadd8", 6200f90, fa80f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("qasx", 6200f30, faa0f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for QASX. */
TCE("qaddsubx",6200f30, faa0f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("qsax", 6200f50, fae0f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for QSAX. */
TCE("qsubaddx",6200f50, fae0f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("qsub16", 6200f70, fad0f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("qsub8", 6200ff0, fac0f010, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("sadd16", 6100f10, fa90f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("sadd8", 6100f90, fa80f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("sasx", 6100f30, faa0f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for SASX. */
TCE("saddsubx",6100f30, faa0f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("shadd16", 6300f10, fa90f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("shadd8", 6300f90, fa80f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("shasx", 6300f30, faa0f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for SHASX. */
TCE("shaddsubx", 6300f30, faa0f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("shsax", 6300f50, fae0f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for SHSAX. */
TCE("shsubaddx", 6300f50, fae0f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("shsub16", 6300f70, fad0f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("shsub8", 6300ff0, fac0f020, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("ssax", 6100f50, fae0f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for SSAX. */
TCE("ssubaddx",6100f50, fae0f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("ssub16", 6100f70, fad0f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("ssub8", 6100ff0, fac0f000, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uadd16", 6500f10, fa90f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uadd8", 6500f90, fa80f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uasx", 6500f30, faa0f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for UASX. */
TCE("uaddsubx",6500f30, faa0f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uhadd16", 6700f10, fa90f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uhadd8", 6700f90, fa80f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uhasx", 6700f30, faa0f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for UHASX. */
TCE("uhaddsubx", 6700f30, faa0f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uhsax", 6700f50, fae0f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for UHSAX. */
TCE("uhsubaddx", 6700f50, fae0f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uhsub16", 6700f70, fad0f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uhsub8", 6700ff0, fac0f060, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uqadd16", 6600f10, fa90f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uqadd8", 6600f90, fa80f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uqasx", 6600f30, faa0f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for UQASX. */
TCE("uqaddsubx", 6600f30, faa0f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uqsax", 6600f50, fae0f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for UQSAX. */
TCE("uqsubaddx", 6600f50, fae0f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uqsub16", 6600f70, fad0f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("uqsub8", 6600ff0, fac0f050, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("usub16", 6500f70, fad0f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("usax", 6500f50, fae0f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
/* Old name for USAX. */
TCE("usubaddx",6500f50, fae0f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("usub8", 6500ff0, fac0f040, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("sxtah", 6b00070, fa00f080, 4, (RRnpc, RRnpc, RRnpc, oROR), sxtah, t_sxtah),
TCE("sxtab16", 6800070, fa20f080, 4, (RRnpc, RRnpc, RRnpc, oROR), sxtah, t_sxtah),
TCE("sxtab", 6a00070, fa40f080, 4, (RRnpc, RRnpc, RRnpc, oROR), sxtah, t_sxtah),
TCE("sxtb16", 68f0070, fa2ff080, 3, (RRnpc, RRnpc, oROR), sxth, t_sxth),
TCE("uxtah", 6f00070, fa10f080, 4, (RRnpc, RRnpc, RRnpc, oROR), sxtah, t_sxtah),
TCE("uxtab16", 6c00070, fa30f080, 4, (RRnpc, RRnpc, RRnpc, oROR), sxtah, t_sxtah),
TCE("uxtab", 6e00070, fa50f080, 4, (RRnpc, RRnpc, RRnpc, oROR), sxtah, t_sxtah),
TCE("uxtb16", 6cf0070, fa3ff080, 3, (RRnpc, RRnpc, oROR), sxth, t_sxth),
TCE("sel", 6800fb0, faa0f080, 3, (RRnpc, RRnpc, RRnpc), rd_rn_rm, t_simd),
TCE("smlad", 7000010, fb200000, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smladx", 7000030, fb200010, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smlald", 7400010, fbc000c0, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smlal,t_mlal),
TCE("smlaldx", 7400030, fbc000d0, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smlal,t_mlal),
TCE("smlsd", 7000050, fb400000, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smlsdx", 7000070, fb400010, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smlsld", 7400050, fbd000c0, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smlal,t_mlal),
TCE("smlsldx", 7400070, fbd000d0, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smlal,t_mlal),
TCE("smmla", 7500010, fb500000, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smmlar", 7500030, fb500010, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smmls", 75000d0, fb600000, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smmlsr", 75000f0, fb600010, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("smmul", 750f010, fb50f000, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smmulr", 750f030, fb50f010, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smuad", 700f010, fb20f000, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smuadx", 700f030, fb20f010, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smusd", 700f050, fb40f000, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("smusdx", 700f070, fb40f010, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("ssat16", 6a00f30, f3200000, 3, (RRnpc, I16, RRnpc), ssat16, t_ssat16),
TCE("umaal", 0400090, fbe00060, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smlal, t_mlal),
TCE("usad8", 780f010, fb70f000, 3, (RRnpc, RRnpc, RRnpc), smul, t_simd),
TCE("usada8", 7800010, fb700000, 4, (RRnpc, RRnpc, RRnpc, RRnpc),smla, t_mla),
TCE("usat16", 6e00f30, f3a00000, 3, (RRnpc, I15, RRnpc), usat16, t_usat16),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v6k
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6k
tCE("yield", 320f001, _yield, 0, (), noargs, t_hint),
tCE("wfe", 320f002, _wfe, 0, (), noargs, t_hint),
tCE("wfi", 320f003, _wfi, 0, (), noargs, t_hint),
tCE("sev", 320f004, _sev, 0, (), noargs, t_hint),
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6_notm
TCE("ldrexd", 1b00f9f, e8d0007f, 3, (RRnpc_npcsp, oRRnpc_npcsp, RRnpcb),
ldrexd, t_ldrexd),
TCE("strexd", 1a00f90, e8c00070, 4, (RRnpc_npcsp, RRnpc_npcsp, oRRnpc_npcsp,
RRnpcb), strexd, t_strexd),
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("ldrexb", 1d00f9f, e8d00f4f, 2, (RRnpc_npcsp,RRnpcb),
rd_rn, rd_rn),
TCE("ldrexh", 1f00f9f, e8d00f5f, 2, (RRnpc_npcsp, RRnpcb),
rd_rn, rd_rn),
TCE("strexb", 1c00f90, e8c00f40, 3, (RRnpc_npcsp, RRnpc_npcsp, ADDR),
strex, t_strexbh),
TCE("strexh", 1e00f90, e8c00f50, 3, (RRnpc_npcsp, RRnpc_npcsp, ADDR),
strex, t_strexbh),
TUF("clrex", 57ff01f, f3bf8f2f, 0, (), noargs, noargs),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_sec
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_sec
TCE("smc", 1600070, f7f08000, 1, (EXPi), smc, t_smc),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_virt
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_virt
TCE("hvc", 1400070, f7e08000, 1, (EXPi), hvc, t_hvc),
TCE("eret", 160006e, f3de8f00, 0, (), noargs, noargs),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v6t2
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v6t2
TCE("bfc", 7c0001f, f36f0000, 3, (RRnpc, I31, I32), bfc, t_bfc),
TCE("bfi", 7c00010, f3600000, 4, (RRnpc, RRnpc_I0, I31, I32), bfi, t_bfi),
TCE("sbfx", 7a00050, f3400000, 4, (RR, RR, I31, I32), bfx, t_bfx),
TCE("ubfx", 7e00050, f3c00000, 4, (RR, RR, I31, I32), bfx, t_bfx),
TCE("mls", 0600090, fb000010, 4, (RRnpc, RRnpc, RRnpc, RRnpc), mlas, t_mla),
TCE("movw", 3000000, f2400000, 2, (RRnpc, HALF), mov16, t_mov16),
TCE("movt", 3400000, f2c00000, 2, (RRnpc, HALF), mov16, t_mov16),
TCE("rbit", 6ff0f30, fa90f0a0, 2, (RR, RR), rd_rm, t_rbit),
TC3("ldrht", 03000b0, f8300e00, 2, (RRnpc_npcsp, ADDR), ldsttv4, t_ldstt),
TC3("ldrsht", 03000f0, f9300e00, 2, (RRnpc_npcsp, ADDR), ldsttv4, t_ldstt),
TC3("ldrsbt", 03000d0, f9100e00, 2, (RRnpc_npcsp, ADDR), ldsttv4, t_ldstt),
TC3("strht", 02000b0, f8200e00, 2, (RRnpc_npcsp, ADDR), ldsttv4, t_ldstt),
/* Thumb-only instructions. */
#undef ARM_VARIANT
#define ARM_VARIANT NULL
TUE("cbnz", 0, b900, 2, (RR, EXP), 0, t_cbz),
TUE("cbz", 0, b100, 2, (RR, EXP), 0, t_cbz),
/* ARM does not really have an IT instruction, so always allow it.
The opcode is copied from Thumb in order to allow warnings in
-mimplicit-it=[never | arm] modes. */
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v1
TUE("it", bf08, bf08, 1, (COND), it, t_it),
TUE("itt", bf0c, bf0c, 1, (COND), it, t_it),
TUE("ite", bf04, bf04, 1, (COND), it, t_it),
TUE("ittt", bf0e, bf0e, 1, (COND), it, t_it),
TUE("itet", bf06, bf06, 1, (COND), it, t_it),
TUE("itte", bf0a, bf0a, 1, (COND), it, t_it),
TUE("itee", bf02, bf02, 1, (COND), it, t_it),
TUE("itttt", bf0f, bf0f, 1, (COND), it, t_it),
TUE("itett", bf07, bf07, 1, (COND), it, t_it),
TUE("ittet", bf0b, bf0b, 1, (COND), it, t_it),
TUE("iteet", bf03, bf03, 1, (COND), it, t_it),
TUE("ittte", bf0d, bf0d, 1, (COND), it, t_it),
TUE("itete", bf05, bf05, 1, (COND), it, t_it),
TUE("ittee", bf09, bf09, 1, (COND), it, t_it),
TUE("iteee", bf01, bf01, 1, (COND), it, t_it),
/* ARM/Thumb-2 instructions with no Thumb-1 equivalent. */
TC3("rrx", 01a00060, ea4f0030, 2, (RR, RR), rd_rm, t_rrx),
TC3("rrxs", 01b00060, ea5f0030, 2, (RR, RR), rd_rm, t_rrx),
/* Thumb2 only instructions. */
#undef ARM_VARIANT
#define ARM_VARIANT NULL
TCE("addw", 0, f2000000, 3, (RR, RR, EXPi), 0, t_add_sub_w),
TCE("subw", 0, f2a00000, 3, (RR, RR, EXPi), 0, t_add_sub_w),
TCE("orn", 0, ea600000, 3, (RR, oRR, SH), 0, t_orn),
TCE("orns", 0, ea700000, 3, (RR, oRR, SH), 0, t_orn),
TCE("tbb", 0, e8d0f000, 1, (TB), 0, t_tb),
TCE("tbh", 0, e8d0f010, 1, (TB), 0, t_tb),
/* Hardware division instructions. */
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_adiv
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_div
TCE("sdiv", 710f010, fb90f0f0, 3, (RR, oRR, RR), div, t_div),
TCE("udiv", 730f010, fbb0f0f0, 3, (RR, oRR, RR), div, t_div),
/* ARM V6M/V7 instructions. */
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_barrier
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_barrier
TUF("dmb", 57ff050, f3bf8f50, 1, (oBARRIER_I15), barrier, barrier),
TUF("dsb", 57ff040, f3bf8f40, 1, (oBARRIER_I15), barrier, barrier),
TUF("isb", 57ff060, f3bf8f60, 1, (oBARRIER_I15), barrier, barrier),
/* ARM V7 instructions. */
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v7
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v7
TUF("pli", 450f000, f910f000, 1, (ADDR), pli, t_pld),
TCE("dbg", 320f0f0, f3af80f0, 1, (I15), dbg, t_dbg),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_mp
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_mp
TUF("pldw", 410f000, f830f000, 1, (ADDR), pld, t_pld),
/* AArchv8 instructions. */
#undef ARM_VARIANT
#define ARM_VARIANT & arm_ext_v8
#undef THUMB_VARIANT
#define THUMB_VARIANT & arm_ext_v8
tCE("sevl", 320f005, _sevl, 0, (), noargs, t_hint),
TUE("hlt", 1000070, ba80, 1, (oIffffb), bkpt, t_hlt),
TCE("ldaex", 1900e9f, e8d00fef, 2, (RRnpc, RRnpcb), rd_rn, rd_rn),
TCE("ldaexd", 1b00e9f, e8d000ff, 3, (RRnpc, oRRnpc, RRnpcb),
ldrexd, t_ldrexd),
TCE("ldaexb", 1d00e9f, e8d00fcf, 2, (RRnpc,RRnpcb), rd_rn, rd_rn),
TCE("ldaexh", 1f00e9f, e8d00fdf, 2, (RRnpc, RRnpcb), rd_rn, rd_rn),
TCE("stlex", 1800e90, e8c00fe0, 3, (RRnpc, RRnpc, RRnpcb),
stlex, t_stlex),
TCE("stlexd", 1a00e90, e8c000f0, 4, (RRnpc, RRnpc, oRRnpc, RRnpcb),
strexd, t_strexd),
TCE("stlexb", 1c00e90, e8c00fc0, 3, (RRnpc, RRnpc, RRnpcb),
stlex, t_stlex),
TCE("stlexh", 1e00e90, e8c00fd0, 3, (RRnpc, RRnpc, RRnpcb),
stlex, t_stlex),
TCE("lda", 1900c9f, e8d00faf, 2, (RRnpc, RRnpcb), rd_rn, rd_rn),
TCE("ldab", 1d00c9f, e8d00f8f, 2, (RRnpc, RRnpcb), rd_rn, rd_rn),
TCE("ldah", 1f00c9f, e8d00f9f, 2, (RRnpc, RRnpcb), rd_rn, rd_rn),
TCE("stl", 180fc90, e8c00faf, 2, (RRnpc, RRnpcb), rm_rn, rd_rn),
TCE("stlb", 1c0fc90, e8c00f8f, 2, (RRnpc, RRnpcb), rm_rn, rd_rn),
TCE("stlh", 1e0fc90, e8c00f9f, 2, (RRnpc, RRnpcb), rm_rn, rd_rn),
/* ARMv8 T32 only. */
#undef ARM_VARIANT
#define ARM_VARIANT NULL
TUF("dcps1", 0, f78f8001, 0, (), noargs, noargs),
TUF("dcps2", 0, f78f8002, 0, (), noargs, noargs),
TUF("dcps3", 0, f78f8003, 0, (), noargs, noargs),
/* FP for ARMv8. */
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_armv8xd
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_vfp_ext_armv8xd
nUF(vseleq, _vseleq, 3, (RVSD, RVSD, RVSD), vsel),
nUF(vselvs, _vselvs, 3, (RVSD, RVSD, RVSD), vsel),
nUF(vselge, _vselge, 3, (RVSD, RVSD, RVSD), vsel),
nUF(vselgt, _vselgt, 3, (RVSD, RVSD, RVSD), vsel),
nUF(vmaxnm, _vmaxnm, 3, (RNSDQ, oRNSDQ, RNSDQ), vmaxnm),
nUF(vminnm, _vminnm, 3, (RNSDQ, oRNSDQ, RNSDQ), vmaxnm),
nUF(vcvta, _vcvta, 2, (RNSDQ, oRNSDQ), neon_cvta),
nUF(vcvtn, _vcvta, 2, (RNSDQ, oRNSDQ), neon_cvtn),
nUF(vcvtp, _vcvta, 2, (RNSDQ, oRNSDQ), neon_cvtp),
nUF(vcvtm, _vcvta, 2, (RNSDQ, oRNSDQ), neon_cvtm),
nCE(vrintr, _vrintr, 2, (RNSDQ, oRNSDQ), vrintr),
nCE(vrintz, _vrintr, 2, (RNSDQ, oRNSDQ), vrintz),
nCE(vrintx, _vrintr, 2, (RNSDQ, oRNSDQ), vrintx),
nUF(vrinta, _vrinta, 2, (RNSDQ, oRNSDQ), vrinta),
nUF(vrintn, _vrinta, 2, (RNSDQ, oRNSDQ), vrintn),
nUF(vrintp, _vrinta, 2, (RNSDQ, oRNSDQ), vrintp),
nUF(vrintm, _vrinta, 2, (RNSDQ, oRNSDQ), vrintm),
/* Crypto v1 extensions. */
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_crypto_ext_armv8
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_crypto_ext_armv8
nUF(aese, _aes, 2, (RNQ, RNQ), aese),
nUF(aesd, _aes, 2, (RNQ, RNQ), aesd),
nUF(aesmc, _aes, 2, (RNQ, RNQ), aesmc),
nUF(aesimc, _aes, 2, (RNQ, RNQ), aesimc),
nUF(sha1c, _sha3op, 3, (RNQ, RNQ, RNQ), sha1c),
nUF(sha1p, _sha3op, 3, (RNQ, RNQ, RNQ), sha1p),
nUF(sha1m, _sha3op, 3, (RNQ, RNQ, RNQ), sha1m),
nUF(sha1su0, _sha3op, 3, (RNQ, RNQ, RNQ), sha1su0),
nUF(sha256h, _sha3op, 3, (RNQ, RNQ, RNQ), sha256h),
nUF(sha256h2, _sha3op, 3, (RNQ, RNQ, RNQ), sha256h2),
nUF(sha256su1, _sha3op, 3, (RNQ, RNQ, RNQ), sha256su1),
nUF(sha1h, _sha1h, 2, (RNQ, RNQ), sha1h),
nUF(sha1su1, _sha2op, 2, (RNQ, RNQ), sha1su1),
nUF(sha256su0, _sha2op, 2, (RNQ, RNQ), sha256su0),
#undef ARM_VARIANT
#define ARM_VARIANT & crc_ext_armv8
#undef THUMB_VARIANT
#define THUMB_VARIANT & crc_ext_armv8
TUEc("crc32b", 1000040, fac0f080, 3, (RR, oRR, RR), crc32b),
TUEc("crc32h", 1200040, fac0f090, 3, (RR, oRR, RR), crc32h),
TUEc("crc32w", 1400040, fac0f0a0, 3, (RR, oRR, RR), crc32w),
TUEc("crc32cb",1000240, fad0f080, 3, (RR, oRR, RR), crc32cb),
TUEc("crc32ch",1200240, fad0f090, 3, (RR, oRR, RR), crc32ch),
TUEc("crc32cw",1400240, fad0f0a0, 3, (RR, oRR, RR), crc32cw),
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_fpa_ext_v1 /* Core FPA instruction set (V1). */
#undef THUMB_VARIANT
#define THUMB_VARIANT NULL
cCE("wfs", e200110, 1, (RR), rd),
cCE("rfs", e300110, 1, (RR), rd),
cCE("wfc", e400110, 1, (RR), rd),
cCE("rfc", e500110, 1, (RR), rd),
cCL("ldfs", c100100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("ldfd", c108100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("ldfe", c500100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("ldfp", c508100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("stfs", c000100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("stfd", c008100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("stfe", c400100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("stfp", c408100, 2, (RF, ADDRGLDC), rd_cpaddr),
cCL("mvfs", e008100, 2, (RF, RF_IF), rd_rm),
cCL("mvfsp", e008120, 2, (RF, RF_IF), rd_rm),
cCL("mvfsm", e008140, 2, (RF, RF_IF), rd_rm),
cCL("mvfsz", e008160, 2, (RF, RF_IF), rd_rm),
cCL("mvfd", e008180, 2, (RF, RF_IF), rd_rm),
cCL("mvfdp", e0081a0, 2, (RF, RF_IF), rd_rm),
cCL("mvfdm", e0081c0, 2, (RF, RF_IF), rd_rm),
cCL("mvfdz", e0081e0, 2, (RF, RF_IF), rd_rm),
cCL("mvfe", e088100, 2, (RF, RF_IF), rd_rm),
cCL("mvfep", e088120, 2, (RF, RF_IF), rd_rm),
cCL("mvfem", e088140, 2, (RF, RF_IF), rd_rm),
cCL("mvfez", e088160, 2, (RF, RF_IF), rd_rm),
cCL("mnfs", e108100, 2, (RF, RF_IF), rd_rm),
cCL("mnfsp", e108120, 2, (RF, RF_IF), rd_rm),
cCL("mnfsm", e108140, 2, (RF, RF_IF), rd_rm),
cCL("mnfsz", e108160, 2, (RF, RF_IF), rd_rm),
cCL("mnfd", e108180, 2, (RF, RF_IF), rd_rm),
cCL("mnfdp", e1081a0, 2, (RF, RF_IF), rd_rm),
cCL("mnfdm", e1081c0, 2, (RF, RF_IF), rd_rm),
cCL("mnfdz", e1081e0, 2, (RF, RF_IF), rd_rm),
cCL("mnfe", e188100, 2, (RF, RF_IF), rd_rm),
cCL("mnfep", e188120, 2, (RF, RF_IF), rd_rm),
cCL("mnfem", e188140, 2, (RF, RF_IF), rd_rm),
cCL("mnfez", e188160, 2, (RF, RF_IF), rd_rm),
cCL("abss", e208100, 2, (RF, RF_IF), rd_rm),
cCL("abssp", e208120, 2, (RF, RF_IF), rd_rm),
cCL("abssm", e208140, 2, (RF, RF_IF), rd_rm),
cCL("abssz", e208160, 2, (RF, RF_IF), rd_rm),
cCL("absd", e208180, 2, (RF, RF_IF), rd_rm),
cCL("absdp", e2081a0, 2, (RF, RF_IF), rd_rm),
cCL("absdm", e2081c0, 2, (RF, RF_IF), rd_rm),
cCL("absdz", e2081e0, 2, (RF, RF_IF), rd_rm),
cCL("abse", e288100, 2, (RF, RF_IF), rd_rm),
cCL("absep", e288120, 2, (RF, RF_IF), rd_rm),
cCL("absem", e288140, 2, (RF, RF_IF), rd_rm),
cCL("absez", e288160, 2, (RF, RF_IF), rd_rm),
cCL("rnds", e308100, 2, (RF, RF_IF), rd_rm),
cCL("rndsp", e308120, 2, (RF, RF_IF), rd_rm),
cCL("rndsm", e308140, 2, (RF, RF_IF), rd_rm),
cCL("rndsz", e308160, 2, (RF, RF_IF), rd_rm),
cCL("rndd", e308180, 2, (RF, RF_IF), rd_rm),
cCL("rnddp", e3081a0, 2, (RF, RF_IF), rd_rm),
cCL("rnddm", e3081c0, 2, (RF, RF_IF), rd_rm),
cCL("rnddz", e3081e0, 2, (RF, RF_IF), rd_rm),
cCL("rnde", e388100, 2, (RF, RF_IF), rd_rm),
cCL("rndep", e388120, 2, (RF, RF_IF), rd_rm),
cCL("rndem", e388140, 2, (RF, RF_IF), rd_rm),
cCL("rndez", e388160, 2, (RF, RF_IF), rd_rm),
cCL("sqts", e408100, 2, (RF, RF_IF), rd_rm),
cCL("sqtsp", e408120, 2, (RF, RF_IF), rd_rm),
cCL("sqtsm", e408140, 2, (RF, RF_IF), rd_rm),
cCL("sqtsz", e408160, 2, (RF, RF_IF), rd_rm),
cCL("sqtd", e408180, 2, (RF, RF_IF), rd_rm),
cCL("sqtdp", e4081a0, 2, (RF, RF_IF), rd_rm),
cCL("sqtdm", e4081c0, 2, (RF, RF_IF), rd_rm),
cCL("sqtdz", e4081e0, 2, (RF, RF_IF), rd_rm),
cCL("sqte", e488100, 2, (RF, RF_IF), rd_rm),
cCL("sqtep", e488120, 2, (RF, RF_IF), rd_rm),
cCL("sqtem", e488140, 2, (RF, RF_IF), rd_rm),
cCL("sqtez", e488160, 2, (RF, RF_IF), rd_rm),
cCL("logs", e508100, 2, (RF, RF_IF), rd_rm),
cCL("logsp", e508120, 2, (RF, RF_IF), rd_rm),
cCL("logsm", e508140, 2, (RF, RF_IF), rd_rm),
cCL("logsz", e508160, 2, (RF, RF_IF), rd_rm),
cCL("logd", e508180, 2, (RF, RF_IF), rd_rm),
cCL("logdp", e5081a0, 2, (RF, RF_IF), rd_rm),
cCL("logdm", e5081c0, 2, (RF, RF_IF), rd_rm),
cCL("logdz", e5081e0, 2, (RF, RF_IF), rd_rm),
cCL("loge", e588100, 2, (RF, RF_IF), rd_rm),
cCL("logep", e588120, 2, (RF, RF_IF), rd_rm),
cCL("logem", e588140, 2, (RF, RF_IF), rd_rm),
cCL("logez", e588160, 2, (RF, RF_IF), rd_rm),
cCL("lgns", e608100, 2, (RF, RF_IF), rd_rm),
cCL("lgnsp", e608120, 2, (RF, RF_IF), rd_rm),
cCL("lgnsm", e608140, 2, (RF, RF_IF), rd_rm),
cCL("lgnsz", e608160, 2, (RF, RF_IF), rd_rm),
cCL("lgnd", e608180, 2, (RF, RF_IF), rd_rm),
cCL("lgndp", e6081a0, 2, (RF, RF_IF), rd_rm),
cCL("lgndm", e6081c0, 2, (RF, RF_IF), rd_rm),
cCL("lgndz", e6081e0, 2, (RF, RF_IF), rd_rm),
cCL("lgne", e688100, 2, (RF, RF_IF), rd_rm),
cCL("lgnep", e688120, 2, (RF, RF_IF), rd_rm),
cCL("lgnem", e688140, 2, (RF, RF_IF), rd_rm),
cCL("lgnez", e688160, 2, (RF, RF_IF), rd_rm),
cCL("exps", e708100, 2, (RF, RF_IF), rd_rm),
cCL("expsp", e708120, 2, (RF, RF_IF), rd_rm),
cCL("expsm", e708140, 2, (RF, RF_IF), rd_rm),
cCL("expsz", e708160, 2, (RF, RF_IF), rd_rm),
cCL("expd", e708180, 2, (RF, RF_IF), rd_rm),
cCL("expdp", e7081a0, 2, (RF, RF_IF), rd_rm),
cCL("expdm", e7081c0, 2, (RF, RF_IF), rd_rm),
cCL("expdz", e7081e0, 2, (RF, RF_IF), rd_rm),
cCL("expe", e788100, 2, (RF, RF_IF), rd_rm),
cCL("expep", e788120, 2, (RF, RF_IF), rd_rm),
cCL("expem", e788140, 2, (RF, RF_IF), rd_rm),
cCL("expdz", e788160, 2, (RF, RF_IF), rd_rm),
cCL("sins", e808100, 2, (RF, RF_IF), rd_rm),
cCL("sinsp", e808120, 2, (RF, RF_IF), rd_rm),
cCL("sinsm", e808140, 2, (RF, RF_IF), rd_rm),
cCL("sinsz", e808160, 2, (RF, RF_IF), rd_rm),
cCL("sind", e808180, 2, (RF, RF_IF), rd_rm),
cCL("sindp", e8081a0, 2, (RF, RF_IF), rd_rm),
cCL("sindm", e8081c0, 2, (RF, RF_IF), rd_rm),
cCL("sindz", e8081e0, 2, (RF, RF_IF), rd_rm),
cCL("sine", e888100, 2, (RF, RF_IF), rd_rm),
cCL("sinep", e888120, 2, (RF, RF_IF), rd_rm),
cCL("sinem", e888140, 2, (RF, RF_IF), rd_rm),
cCL("sinez", e888160, 2, (RF, RF_IF), rd_rm),
cCL("coss", e908100, 2, (RF, RF_IF), rd_rm),
cCL("cossp", e908120, 2, (RF, RF_IF), rd_rm),
cCL("cossm", e908140, 2, (RF, RF_IF), rd_rm),
cCL("cossz", e908160, 2, (RF, RF_IF), rd_rm),
cCL("cosd", e908180, 2, (RF, RF_IF), rd_rm),
cCL("cosdp", e9081a0, 2, (RF, RF_IF), rd_rm),
cCL("cosdm", e9081c0, 2, (RF, RF_IF), rd_rm),
cCL("cosdz", e9081e0, 2, (RF, RF_IF), rd_rm),
cCL("cose", e988100, 2, (RF, RF_IF), rd_rm),
cCL("cosep", e988120, 2, (RF, RF_IF), rd_rm),
cCL("cosem", e988140, 2, (RF, RF_IF), rd_rm),
cCL("cosez", e988160, 2, (RF, RF_IF), rd_rm),
cCL("tans", ea08100, 2, (RF, RF_IF), rd_rm),
cCL("tansp", ea08120, 2, (RF, RF_IF), rd_rm),
cCL("tansm", ea08140, 2, (RF, RF_IF), rd_rm),
cCL("tansz", ea08160, 2, (RF, RF_IF), rd_rm),
cCL("tand", ea08180, 2, (RF, RF_IF), rd_rm),
cCL("tandp", ea081a0, 2, (RF, RF_IF), rd_rm),
cCL("tandm", ea081c0, 2, (RF, RF_IF), rd_rm),
cCL("tandz", ea081e0, 2, (RF, RF_IF), rd_rm),
cCL("tane", ea88100, 2, (RF, RF_IF), rd_rm),
cCL("tanep", ea88120, 2, (RF, RF_IF), rd_rm),
cCL("tanem", ea88140, 2, (RF, RF_IF), rd_rm),
cCL("tanez", ea88160, 2, (RF, RF_IF), rd_rm),
cCL("asns", eb08100, 2, (RF, RF_IF), rd_rm),
cCL("asnsp", eb08120, 2, (RF, RF_IF), rd_rm),
cCL("asnsm", eb08140, 2, (RF, RF_IF), rd_rm),
cCL("asnsz", eb08160, 2, (RF, RF_IF), rd_rm),
cCL("asnd", eb08180, 2, (RF, RF_IF), rd_rm),
cCL("asndp", eb081a0, 2, (RF, RF_IF), rd_rm),
cCL("asndm", eb081c0, 2, (RF, RF_IF), rd_rm),
cCL("asndz", eb081e0, 2, (RF, RF_IF), rd_rm),
cCL("asne", eb88100, 2, (RF, RF_IF), rd_rm),
cCL("asnep", eb88120, 2, (RF, RF_IF), rd_rm),
cCL("asnem", eb88140, 2, (RF, RF_IF), rd_rm),
cCL("asnez", eb88160, 2, (RF, RF_IF), rd_rm),
cCL("acss", ec08100, 2, (RF, RF_IF), rd_rm),
cCL("acssp", ec08120, 2, (RF, RF_IF), rd_rm),
cCL("acssm", ec08140, 2, (RF, RF_IF), rd_rm),
cCL("acssz", ec08160, 2, (RF, RF_IF), rd_rm),
cCL("acsd", ec08180, 2, (RF, RF_IF), rd_rm),
cCL("acsdp", ec081a0, 2, (RF, RF_IF), rd_rm),
cCL("acsdm", ec081c0, 2, (RF, RF_IF), rd_rm),
cCL("acsdz", ec081e0, 2, (RF, RF_IF), rd_rm),
cCL("acse", ec88100, 2, (RF, RF_IF), rd_rm),
cCL("acsep", ec88120, 2, (RF, RF_IF), rd_rm),
cCL("acsem", ec88140, 2, (RF, RF_IF), rd_rm),
cCL("acsez", ec88160, 2, (RF, RF_IF), rd_rm),
cCL("atns", ed08100, 2, (RF, RF_IF), rd_rm),
cCL("atnsp", ed08120, 2, (RF, RF_IF), rd_rm),
cCL("atnsm", ed08140, 2, (RF, RF_IF), rd_rm),
cCL("atnsz", ed08160, 2, (RF, RF_IF), rd_rm),
cCL("atnd", ed08180, 2, (RF, RF_IF), rd_rm),
cCL("atndp", ed081a0, 2, (RF, RF_IF), rd_rm),
cCL("atndm", ed081c0, 2, (RF, RF_IF), rd_rm),
cCL("atndz", ed081e0, 2, (RF, RF_IF), rd_rm),
cCL("atne", ed88100, 2, (RF, RF_IF), rd_rm),
cCL("atnep", ed88120, 2, (RF, RF_IF), rd_rm),
cCL("atnem", ed88140, 2, (RF, RF_IF), rd_rm),
cCL("atnez", ed88160, 2, (RF, RF_IF), rd_rm),
cCL("urds", ee08100, 2, (RF, RF_IF), rd_rm),
cCL("urdsp", ee08120, 2, (RF, RF_IF), rd_rm),
cCL("urdsm", ee08140, 2, (RF, RF_IF), rd_rm),
cCL("urdsz", ee08160, 2, (RF, RF_IF), rd_rm),
cCL("urdd", ee08180, 2, (RF, RF_IF), rd_rm),
cCL("urddp", ee081a0, 2, (RF, RF_IF), rd_rm),
cCL("urddm", ee081c0, 2, (RF, RF_IF), rd_rm),
cCL("urddz", ee081e0, 2, (RF, RF_IF), rd_rm),
cCL("urde", ee88100, 2, (RF, RF_IF), rd_rm),
cCL("urdep", ee88120, 2, (RF, RF_IF), rd_rm),
cCL("urdem", ee88140, 2, (RF, RF_IF), rd_rm),
cCL("urdez", ee88160, 2, (RF, RF_IF), rd_rm),
cCL("nrms", ef08100, 2, (RF, RF_IF), rd_rm),
cCL("nrmsp", ef08120, 2, (RF, RF_IF), rd_rm),
cCL("nrmsm", ef08140, 2, (RF, RF_IF), rd_rm),
cCL("nrmsz", ef08160, 2, (RF, RF_IF), rd_rm),
cCL("nrmd", ef08180, 2, (RF, RF_IF), rd_rm),
cCL("nrmdp", ef081a0, 2, (RF, RF_IF), rd_rm),
cCL("nrmdm", ef081c0, 2, (RF, RF_IF), rd_rm),
cCL("nrmdz", ef081e0, 2, (RF, RF_IF), rd_rm),
cCL("nrme", ef88100, 2, (RF, RF_IF), rd_rm),
cCL("nrmep", ef88120, 2, (RF, RF_IF), rd_rm),
cCL("nrmem", ef88140, 2, (RF, RF_IF), rd_rm),
cCL("nrmez", ef88160, 2, (RF, RF_IF), rd_rm),
cCL("adfs", e000100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfsp", e000120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfsm", e000140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfsz", e000160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfd", e000180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfdp", e0001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfdm", e0001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfdz", e0001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfe", e080100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfep", e080120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfem", e080140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("adfez", e080160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufs", e200100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufsp", e200120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufsm", e200140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufsz", e200160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufd", e200180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufdp", e2001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufdm", e2001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufdz", e2001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufe", e280100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufep", e280120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufem", e280140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("sufez", e280160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfs", e300100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfsp", e300120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfsm", e300140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfsz", e300160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfd", e300180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfdp", e3001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfdm", e3001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfdz", e3001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfe", e380100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfep", e380120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfem", e380140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rsfez", e380160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufs", e100100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufsp", e100120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufsm", e100140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufsz", e100160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufd", e100180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufdp", e1001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufdm", e1001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufdz", e1001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufe", e180100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufep", e180120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufem", e180140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("mufez", e180160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfs", e400100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfsp", e400120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfsm", e400140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfsz", e400160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfd", e400180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfdp", e4001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfdm", e4001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfdz", e4001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfe", e480100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfep", e480120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfem", e480140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("dvfez", e480160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfs", e500100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfsp", e500120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfsm", e500140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfsz", e500160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfd", e500180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfdp", e5001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfdm", e5001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfdz", e5001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfe", e580100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfep", e580120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfem", e580140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rdfez", e580160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("pows", e600100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powsp", e600120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powsm", e600140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powsz", e600160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powd", e600180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powdp", e6001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powdm", e6001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powdz", e6001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powe", e680100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powep", e680120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powem", e680140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("powez", e680160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpws", e700100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwsp", e700120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwsm", e700140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwsz", e700160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwd", e700180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwdp", e7001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwdm", e7001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwdz", e7001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwe", e780100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwep", e780120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwem", e780140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rpwez", e780160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfs", e800100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfsp", e800120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfsm", e800140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfsz", e800160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfd", e800180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfdp", e8001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfdm", e8001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfdz", e8001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfe", e880100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfep", e880120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfem", e880140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("rmfez", e880160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmls", e900100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmlsp", e900120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmlsm", e900140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmlsz", e900160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmld", e900180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmldp", e9001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmldm", e9001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmldz", e9001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmle", e980100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmlep", e980120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmlem", e980140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fmlez", e980160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvs", ea00100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvsp", ea00120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvsm", ea00140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvsz", ea00160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvd", ea00180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvdp", ea001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvdm", ea001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvdz", ea001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdve", ea80100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvep", ea80120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvem", ea80140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("fdvez", ea80160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frds", eb00100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdsp", eb00120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdsm", eb00140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdsz", eb00160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdd", eb00180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frddp", eb001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frddm", eb001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frddz", eb001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frde", eb80100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdep", eb80120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdem", eb80140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("frdez", eb80160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("pols", ec00100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("polsp", ec00120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("polsm", ec00140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("polsz", ec00160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("pold", ec00180, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("poldp", ec001a0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("poldm", ec001c0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("poldz", ec001e0, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("pole", ec80100, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("polep", ec80120, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("polem", ec80140, 3, (RF, RF, RF_IF), rd_rn_rm),
cCL("polez", ec80160, 3, (RF, RF, RF_IF), rd_rn_rm),
cCE("cmf", e90f110, 2, (RF, RF_IF), fpa_cmp),
C3E("cmfe", ed0f110, 2, (RF, RF_IF), fpa_cmp),
cCE("cnf", eb0f110, 2, (RF, RF_IF), fpa_cmp),
C3E("cnfe", ef0f110, 2, (RF, RF_IF), fpa_cmp),
cCL("flts", e000110, 2, (RF, RR), rn_rd),
cCL("fltsp", e000130, 2, (RF, RR), rn_rd),
cCL("fltsm", e000150, 2, (RF, RR), rn_rd),
cCL("fltsz", e000170, 2, (RF, RR), rn_rd),
cCL("fltd", e000190, 2, (RF, RR), rn_rd),
cCL("fltdp", e0001b0, 2, (RF, RR), rn_rd),
cCL("fltdm", e0001d0, 2, (RF, RR), rn_rd),
cCL("fltdz", e0001f0, 2, (RF, RR), rn_rd),
cCL("flte", e080110, 2, (RF, RR), rn_rd),
cCL("fltep", e080130, 2, (RF, RR), rn_rd),
cCL("fltem", e080150, 2, (RF, RR), rn_rd),
cCL("fltez", e080170, 2, (RF, RR), rn_rd),
/* The implementation of the FIX instruction is broken on some
assemblers, in that it accepts a precision specifier as well as a
rounding specifier, despite the fact that this is meaningless.
To be more compatible, we accept it as well, though of course it
does not set any bits. */
cCE("fix", e100110, 2, (RR, RF), rd_rm),
cCL("fixp", e100130, 2, (RR, RF), rd_rm),
cCL("fixm", e100150, 2, (RR, RF), rd_rm),
cCL("fixz", e100170, 2, (RR, RF), rd_rm),
cCL("fixsp", e100130, 2, (RR, RF), rd_rm),
cCL("fixsm", e100150, 2, (RR, RF), rd_rm),
cCL("fixsz", e100170, 2, (RR, RF), rd_rm),
cCL("fixdp", e100130, 2, (RR, RF), rd_rm),
cCL("fixdm", e100150, 2, (RR, RF), rd_rm),
cCL("fixdz", e100170, 2, (RR, RF), rd_rm),
cCL("fixep", e100130, 2, (RR, RF), rd_rm),
cCL("fixem", e100150, 2, (RR, RF), rd_rm),
cCL("fixez", e100170, 2, (RR, RF), rd_rm),
/* Instructions that were new with the real FPA, call them V2. */
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_fpa_ext_v2
cCE("lfm", c100200, 3, (RF, I4b, ADDR), fpa_ldmstm),
cCL("lfmfd", c900200, 3, (RF, I4b, ADDR), fpa_ldmstm),
cCL("lfmea", d100200, 3, (RF, I4b, ADDR), fpa_ldmstm),
cCE("sfm", c000200, 3, (RF, I4b, ADDR), fpa_ldmstm),
cCL("sfmfd", d000200, 3, (RF, I4b, ADDR), fpa_ldmstm),
cCL("sfmea", c800200, 3, (RF, I4b, ADDR), fpa_ldmstm),
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_v1xd /* VFP V1xD (single precision). */
/* Moves and type conversions. */
cCE("fcpys", eb00a40, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fmrs", e100a10, 2, (RR, RVS), vfp_reg_from_sp),
cCE("fmsr", e000a10, 2, (RVS, RR), vfp_sp_from_reg),
cCE("fmstat", ef1fa10, 0, (), noargs),
cCE("vmrs", ef00a10, 2, (APSR_RR, RVC), vmrs),
cCE("vmsr", ee00a10, 2, (RVC, RR), vmsr),
cCE("fsitos", eb80ac0, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fuitos", eb80a40, 2, (RVS, RVS), vfp_sp_monadic),
cCE("ftosis", ebd0a40, 2, (RVS, RVS), vfp_sp_monadic),
cCE("ftosizs", ebd0ac0, 2, (RVS, RVS), vfp_sp_monadic),
cCE("ftouis", ebc0a40, 2, (RVS, RVS), vfp_sp_monadic),
cCE("ftouizs", ebc0ac0, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fmrx", ef00a10, 2, (RR, RVC), rd_rn),
cCE("fmxr", ee00a10, 2, (RVC, RR), rn_rd),
/* Memory operations. */
cCE("flds", d100a00, 2, (RVS, ADDRGLDC), vfp_sp_ldst),
cCE("fsts", d000a00, 2, (RVS, ADDRGLDC), vfp_sp_ldst),
cCE("fldmias", c900a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmia),
cCE("fldmfds", c900a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmia),
cCE("fldmdbs", d300a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmdb),
cCE("fldmeas", d300a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmdb),
cCE("fldmiax", c900b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmia),
cCE("fldmfdx", c900b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmia),
cCE("fldmdbx", d300b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmdb),
cCE("fldmeax", d300b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmdb),
cCE("fstmias", c800a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmia),
cCE("fstmeas", c800a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmia),
cCE("fstmdbs", d200a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmdb),
cCE("fstmfds", d200a00, 2, (RRnpctw, VRSLST), vfp_sp_ldstmdb),
cCE("fstmiax", c800b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmia),
cCE("fstmeax", c800b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmia),
cCE("fstmdbx", d200b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmdb),
cCE("fstmfdx", d200b00, 2, (RRnpctw, VRDLST), vfp_xp_ldstmdb),
/* Monadic operations. */
cCE("fabss", eb00ac0, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fnegs", eb10a40, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fsqrts", eb10ac0, 2, (RVS, RVS), vfp_sp_monadic),
/* Dyadic operations. */
cCE("fadds", e300a00, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fsubs", e300a40, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fmuls", e200a00, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fdivs", e800a00, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fmacs", e000a00, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fmscs", e100a00, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fnmuls", e200a40, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fnmacs", e000a40, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("fnmscs", e100a40, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
/* Comparisons. */
cCE("fcmps", eb40a40, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fcmpzs", eb50a40, 1, (RVS), vfp_sp_compare_z),
cCE("fcmpes", eb40ac0, 2, (RVS, RVS), vfp_sp_monadic),
cCE("fcmpezs", eb50ac0, 1, (RVS), vfp_sp_compare_z),
/* Double precision load/store are still present on single precision
implementations. */
cCE("fldd", d100b00, 2, (RVD, ADDRGLDC), vfp_dp_ldst),
cCE("fstd", d000b00, 2, (RVD, ADDRGLDC), vfp_dp_ldst),
cCE("fldmiad", c900b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmia),
cCE("fldmfdd", c900b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmia),
cCE("fldmdbd", d300b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmdb),
cCE("fldmead", d300b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmdb),
cCE("fstmiad", c800b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmia),
cCE("fstmead", c800b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmia),
cCE("fstmdbd", d200b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmdb),
cCE("fstmfdd", d200b00, 2, (RRnpctw, VRDLST), vfp_dp_ldstmdb),
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_v1 /* VFP V1 (Double precision). */
/* Moves and type conversions. */
cCE("fcpyd", eb00b40, 2, (RVD, RVD), vfp_dp_rd_rm),
cCE("fcvtds", eb70ac0, 2, (RVD, RVS), vfp_dp_sp_cvt),
cCE("fcvtsd", eb70bc0, 2, (RVS, RVD), vfp_sp_dp_cvt),
cCE("fmdhr", e200b10, 2, (RVD, RR), vfp_dp_rn_rd),
cCE("fmdlr", e000b10, 2, (RVD, RR), vfp_dp_rn_rd),
cCE("fmrdh", e300b10, 2, (RR, RVD), vfp_dp_rd_rn),
cCE("fmrdl", e100b10, 2, (RR, RVD), vfp_dp_rd_rn),
cCE("fsitod", eb80bc0, 2, (RVD, RVS), vfp_dp_sp_cvt),
cCE("fuitod", eb80b40, 2, (RVD, RVS), vfp_dp_sp_cvt),
cCE("ftosid", ebd0b40, 2, (RVS, RVD), vfp_sp_dp_cvt),
cCE("ftosizd", ebd0bc0, 2, (RVS, RVD), vfp_sp_dp_cvt),
cCE("ftouid", ebc0b40, 2, (RVS, RVD), vfp_sp_dp_cvt),
cCE("ftouizd", ebc0bc0, 2, (RVS, RVD), vfp_sp_dp_cvt),
/* Monadic operations. */
cCE("fabsd", eb00bc0, 2, (RVD, RVD), vfp_dp_rd_rm),
cCE("fnegd", eb10b40, 2, (RVD, RVD), vfp_dp_rd_rm),
cCE("fsqrtd", eb10bc0, 2, (RVD, RVD), vfp_dp_rd_rm),
/* Dyadic operations. */
cCE("faddd", e300b00, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fsubd", e300b40, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fmuld", e200b00, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fdivd", e800b00, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fmacd", e000b00, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fmscd", e100b00, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fnmuld", e200b40, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fnmacd", e000b40, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("fnmscd", e100b40, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
/* Comparisons. */
cCE("fcmpd", eb40b40, 2, (RVD, RVD), vfp_dp_rd_rm),
cCE("fcmpzd", eb50b40, 1, (RVD), vfp_dp_rd),
cCE("fcmped", eb40bc0, 2, (RVD, RVD), vfp_dp_rd_rm),
cCE("fcmpezd", eb50bc0, 1, (RVD), vfp_dp_rd),
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_v2
cCE("fmsrr", c400a10, 3, (VRSLST, RR, RR), vfp_sp2_from_reg2),
cCE("fmrrs", c500a10, 3, (RR, RR, VRSLST), vfp_reg2_from_sp2),
cCE("fmdrr", c400b10, 3, (RVD, RR, RR), vfp_dp_rm_rd_rn),
cCE("fmrrd", c500b10, 3, (RR, RR, RVD), vfp_dp_rd_rn_rm),
/* Instructions which may belong to either the Neon or VFP instruction sets.
Individual encoder functions perform additional architecture checks. */
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_v1xd
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_vfp_ext_v1xd
/* These mnemonics are unique to VFP. */
NCE(vsqrt, 0, 2, (RVSD, RVSD), vfp_nsyn_sqrt),
NCE(vdiv, 0, 3, (RVSD, RVSD, RVSD), vfp_nsyn_div),
nCE(vnmul, _vnmul, 3, (RVSD, RVSD, RVSD), vfp_nsyn_nmul),
nCE(vnmla, _vnmla, 3, (RVSD, RVSD, RVSD), vfp_nsyn_nmul),
nCE(vnmls, _vnmls, 3, (RVSD, RVSD, RVSD), vfp_nsyn_nmul),
nCE(vcmp, _vcmp, 2, (RVSD, RSVD_FI0), vfp_nsyn_cmp),
nCE(vcmpe, _vcmpe, 2, (RVSD, RSVD_FI0), vfp_nsyn_cmp),
NCE(vpush, 0, 1, (VRSDLST), vfp_nsyn_push),
NCE(vpop, 0, 1, (VRSDLST), vfp_nsyn_pop),
NCE(vcvtz, 0, 2, (RVSD, RVSD), vfp_nsyn_cvtz),
/* Mnemonics shared by Neon and VFP. */
nCEF(vmul, _vmul, 3, (RNSDQ, oRNSDQ, RNSDQ_RNSC), neon_mul),
nCEF(vmla, _vmla, 3, (RNSDQ, oRNSDQ, RNSDQ_RNSC), neon_mac_maybe_scalar),
nCEF(vmls, _vmls, 3, (RNSDQ, oRNSDQ, RNSDQ_RNSC), neon_mac_maybe_scalar),
nCEF(vadd, _vadd, 3, (RNSDQ, oRNSDQ, RNSDQ), neon_addsub_if_i),
nCEF(vsub, _vsub, 3, (RNSDQ, oRNSDQ, RNSDQ), neon_addsub_if_i),
NCEF(vabs, 1b10300, 2, (RNSDQ, RNSDQ), neon_abs_neg),
NCEF(vneg, 1b10380, 2, (RNSDQ, RNSDQ), neon_abs_neg),
NCE(vldm, c900b00, 2, (RRnpctw, VRSDLST), neon_ldm_stm),
NCE(vldmia, c900b00, 2, (RRnpctw, VRSDLST), neon_ldm_stm),
NCE(vldmdb, d100b00, 2, (RRnpctw, VRSDLST), neon_ldm_stm),
NCE(vstm, c800b00, 2, (RRnpctw, VRSDLST), neon_ldm_stm),
NCE(vstmia, c800b00, 2, (RRnpctw, VRSDLST), neon_ldm_stm),
NCE(vstmdb, d000b00, 2, (RRnpctw, VRSDLST), neon_ldm_stm),
NCE(vldr, d100b00, 2, (RVSD, ADDRGLDC), neon_ldr_str),
NCE(vstr, d000b00, 2, (RVSD, ADDRGLDC), neon_ldr_str),
nCEF(vcvt, _vcvt, 3, (RNSDQ, RNSDQ, oI32z), neon_cvt),
nCEF(vcvtr, _vcvt, 2, (RNSDQ, RNSDQ), neon_cvtr),
NCEF(vcvtb, eb20a40, 2, (RVSD, RVSD), neon_cvtb),
NCEF(vcvtt, eb20a40, 2, (RVSD, RVSD), neon_cvtt),
/* NOTE: All VMOV encoding is special-cased! */
NCE(vmov, 0, 1, (VMOV), neon_mov),
NCE(vmovq, 0, 1, (VMOV), neon_mov),
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_neon_ext_v1
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_neon_ext_v1
/* Data processing with three registers of the same length. */
/* integer ops, valid types S8 S16 S32 U8 U16 U32. */
NUF(vaba, 0000710, 3, (RNDQ, RNDQ, RNDQ), neon_dyadic_i_su),
NUF(vabaq, 0000710, 3, (RNQ, RNQ, RNQ), neon_dyadic_i_su),
NUF(vhadd, 0000000, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_i_su),
NUF(vhaddq, 0000000, 3, (RNQ, oRNQ, RNQ), neon_dyadic_i_su),
NUF(vrhadd, 0000100, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_i_su),
NUF(vrhaddq, 0000100, 3, (RNQ, oRNQ, RNQ), neon_dyadic_i_su),
NUF(vhsub, 0000200, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_i_su),
NUF(vhsubq, 0000200, 3, (RNQ, oRNQ, RNQ), neon_dyadic_i_su),
/* integer ops, valid types S8 S16 S32 S64 U8 U16 U32 U64. */
NUF(vqadd, 0000010, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_i64_su),
NUF(vqaddq, 0000010, 3, (RNQ, oRNQ, RNQ), neon_dyadic_i64_su),
NUF(vqsub, 0000210, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_i64_su),
NUF(vqsubq, 0000210, 3, (RNQ, oRNQ, RNQ), neon_dyadic_i64_su),
NUF(vrshl, 0000500, 3, (RNDQ, oRNDQ, RNDQ), neon_rshl),
NUF(vrshlq, 0000500, 3, (RNQ, oRNQ, RNQ), neon_rshl),
NUF(vqrshl, 0000510, 3, (RNDQ, oRNDQ, RNDQ), neon_rshl),
NUF(vqrshlq, 0000510, 3, (RNQ, oRNQ, RNQ), neon_rshl),
/* If not immediate, fall back to neon_dyadic_i64_su.
shl_imm should accept I8 I16 I32 I64,
qshl_imm should accept S8 S16 S32 S64 U8 U16 U32 U64. */
nUF(vshl, _vshl, 3, (RNDQ, oRNDQ, RNDQ_I63b), neon_shl_imm),
nUF(vshlq, _vshl, 3, (RNQ, oRNQ, RNDQ_I63b), neon_shl_imm),
nUF(vqshl, _vqshl, 3, (RNDQ, oRNDQ, RNDQ_I63b), neon_qshl_imm),
nUF(vqshlq, _vqshl, 3, (RNQ, oRNQ, RNDQ_I63b), neon_qshl_imm),
/* Logic ops, types optional & ignored. */
nUF(vand, _vand, 3, (RNDQ, oRNDQ, RNDQ_Ibig), neon_logic),
nUF(vandq, _vand, 3, (RNQ, oRNQ, RNDQ_Ibig), neon_logic),
nUF(vbic, _vbic, 3, (RNDQ, oRNDQ, RNDQ_Ibig), neon_logic),
nUF(vbicq, _vbic, 3, (RNQ, oRNQ, RNDQ_Ibig), neon_logic),
nUF(vorr, _vorr, 3, (RNDQ, oRNDQ, RNDQ_Ibig), neon_logic),
nUF(vorrq, _vorr, 3, (RNQ, oRNQ, RNDQ_Ibig), neon_logic),
nUF(vorn, _vorn, 3, (RNDQ, oRNDQ, RNDQ_Ibig), neon_logic),
nUF(vornq, _vorn, 3, (RNQ, oRNQ, RNDQ_Ibig), neon_logic),
nUF(veor, _veor, 3, (RNDQ, oRNDQ, RNDQ), neon_logic),
nUF(veorq, _veor, 3, (RNQ, oRNQ, RNQ), neon_logic),
/* Bitfield ops, untyped. */
NUF(vbsl, 1100110, 3, (RNDQ, RNDQ, RNDQ), neon_bitfield),
NUF(vbslq, 1100110, 3, (RNQ, RNQ, RNQ), neon_bitfield),
NUF(vbit, 1200110, 3, (RNDQ, RNDQ, RNDQ), neon_bitfield),
NUF(vbitq, 1200110, 3, (RNQ, RNQ, RNQ), neon_bitfield),
NUF(vbif, 1300110, 3, (RNDQ, RNDQ, RNDQ), neon_bitfield),
NUF(vbifq, 1300110, 3, (RNQ, RNQ, RNQ), neon_bitfield),
/* Int and float variants, types S8 S16 S32 U8 U16 U32 F32. */
nUF(vabd, _vabd, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_if_su),
nUF(vabdq, _vabd, 3, (RNQ, oRNQ, RNQ), neon_dyadic_if_su),
nUF(vmax, _vmax, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_if_su),
nUF(vmaxq, _vmax, 3, (RNQ, oRNQ, RNQ), neon_dyadic_if_su),
nUF(vmin, _vmin, 3, (RNDQ, oRNDQ, RNDQ), neon_dyadic_if_su),
nUF(vminq, _vmin, 3, (RNQ, oRNQ, RNQ), neon_dyadic_if_su),
/* Comparisons. Types S8 S16 S32 U8 U16 U32 F32. Non-immediate versions fall
back to neon_dyadic_if_su. */
nUF(vcge, _vcge, 3, (RNDQ, oRNDQ, RNDQ_I0), neon_cmp),
nUF(vcgeq, _vcge, 3, (RNQ, oRNQ, RNDQ_I0), neon_cmp),
nUF(vcgt, _vcgt, 3, (RNDQ, oRNDQ, RNDQ_I0), neon_cmp),
nUF(vcgtq, _vcgt, 3, (RNQ, oRNQ, RNDQ_I0), neon_cmp),
nUF(vclt, _vclt, 3, (RNDQ, oRNDQ, RNDQ_I0), neon_cmp_inv),
nUF(vcltq, _vclt, 3, (RNQ, oRNQ, RNDQ_I0), neon_cmp_inv),
nUF(vcle, _vcle, 3, (RNDQ, oRNDQ, RNDQ_I0), neon_cmp_inv),
nUF(vcleq, _vcle, 3, (RNQ, oRNQ, RNDQ_I0), neon_cmp_inv),
/* Comparison. Type I8 I16 I32 F32. */
nUF(vceq, _vceq, 3, (RNDQ, oRNDQ, RNDQ_I0), neon_ceq),
nUF(vceqq, _vceq, 3, (RNQ, oRNQ, RNDQ_I0), neon_ceq),
/* As above, D registers only. */
nUF(vpmax, _vpmax, 3, (RND, oRND, RND), neon_dyadic_if_su_d),
nUF(vpmin, _vpmin, 3, (RND, oRND, RND), neon_dyadic_if_su_d),
/* Int and float variants, signedness unimportant. */
nUF(vmlaq, _vmla, 3, (RNQ, oRNQ, RNDQ_RNSC), neon_mac_maybe_scalar),
nUF(vmlsq, _vmls, 3, (RNQ, oRNQ, RNDQ_RNSC), neon_mac_maybe_scalar),
nUF(vpadd, _vpadd, 3, (RND, oRND, RND), neon_dyadic_if_i_d),
/* Add/sub take types I8 I16 I32 I64 F32. */
nUF(vaddq, _vadd, 3, (RNQ, oRNQ, RNQ), neon_addsub_if_i),
nUF(vsubq, _vsub, 3, (RNQ, oRNQ, RNQ), neon_addsub_if_i),
/* vtst takes sizes 8, 16, 32. */
NUF(vtst, 0000810, 3, (RNDQ, oRNDQ, RNDQ), neon_tst),
NUF(vtstq, 0000810, 3, (RNQ, oRNQ, RNQ), neon_tst),
/* VMUL takes I8 I16 I32 F32 P8. */
nUF(vmulq, _vmul, 3, (RNQ, oRNQ, RNDQ_RNSC), neon_mul),
/* VQD{R}MULH takes S16 S32. */
nUF(vqdmulh, _vqdmulh, 3, (RNDQ, oRNDQ, RNDQ_RNSC), neon_qdmulh),
nUF(vqdmulhq, _vqdmulh, 3, (RNQ, oRNQ, RNDQ_RNSC), neon_qdmulh),
nUF(vqrdmulh, _vqrdmulh, 3, (RNDQ, oRNDQ, RNDQ_RNSC), neon_qdmulh),
nUF(vqrdmulhq, _vqrdmulh, 3, (RNQ, oRNQ, RNDQ_RNSC), neon_qdmulh),
NUF(vacge, 0000e10, 3, (RNDQ, oRNDQ, RNDQ), neon_fcmp_absolute),
NUF(vacgeq, 0000e10, 3, (RNQ, oRNQ, RNQ), neon_fcmp_absolute),
NUF(vacgt, 0200e10, 3, (RNDQ, oRNDQ, RNDQ), neon_fcmp_absolute),
NUF(vacgtq, 0200e10, 3, (RNQ, oRNQ, RNQ), neon_fcmp_absolute),
NUF(vaclt, 0200e10, 3, (RNDQ, oRNDQ, RNDQ), neon_fcmp_absolute_inv),
NUF(vacltq, 0200e10, 3, (RNQ, oRNQ, RNQ), neon_fcmp_absolute_inv),
NUF(vacle, 0000e10, 3, (RNDQ, oRNDQ, RNDQ), neon_fcmp_absolute_inv),
NUF(vacleq, 0000e10, 3, (RNQ, oRNQ, RNQ), neon_fcmp_absolute_inv),
NUF(vrecps, 0000f10, 3, (RNDQ, oRNDQ, RNDQ), neon_step),
NUF(vrecpsq, 0000f10, 3, (RNQ, oRNQ, RNQ), neon_step),
NUF(vrsqrts, 0200f10, 3, (RNDQ, oRNDQ, RNDQ), neon_step),
NUF(vrsqrtsq, 0200f10, 3, (RNQ, oRNQ, RNQ), neon_step),
/* Two address, int/float. Types S8 S16 S32 F32. */
NUF(vabsq, 1b10300, 2, (RNQ, RNQ), neon_abs_neg),
NUF(vnegq, 1b10380, 2, (RNQ, RNQ), neon_abs_neg),
/* Data processing with two registers and a shift amount. */
/* Right shifts, and variants with rounding.
Types accepted S8 S16 S32 S64 U8 U16 U32 U64. */
NUF(vshr, 0800010, 3, (RNDQ, oRNDQ, I64z), neon_rshift_round_imm),
NUF(vshrq, 0800010, 3, (RNQ, oRNQ, I64z), neon_rshift_round_imm),
NUF(vrshr, 0800210, 3, (RNDQ, oRNDQ, I64z), neon_rshift_round_imm),
NUF(vrshrq, 0800210, 3, (RNQ, oRNQ, I64z), neon_rshift_round_imm),
NUF(vsra, 0800110, 3, (RNDQ, oRNDQ, I64), neon_rshift_round_imm),
NUF(vsraq, 0800110, 3, (RNQ, oRNQ, I64), neon_rshift_round_imm),
NUF(vrsra, 0800310, 3, (RNDQ, oRNDQ, I64), neon_rshift_round_imm),
NUF(vrsraq, 0800310, 3, (RNQ, oRNQ, I64), neon_rshift_round_imm),
/* Shift and insert. Sizes accepted 8 16 32 64. */
NUF(vsli, 1800510, 3, (RNDQ, oRNDQ, I63), neon_sli),
NUF(vsliq, 1800510, 3, (RNQ, oRNQ, I63), neon_sli),
NUF(vsri, 1800410, 3, (RNDQ, oRNDQ, I64), neon_sri),
NUF(vsriq, 1800410, 3, (RNQ, oRNQ, I64), neon_sri),
/* QSHL{U} immediate accepts S8 S16 S32 S64 U8 U16 U32 U64. */
NUF(vqshlu, 1800610, 3, (RNDQ, oRNDQ, I63), neon_qshlu_imm),
NUF(vqshluq, 1800610, 3, (RNQ, oRNQ, I63), neon_qshlu_imm),
/* Right shift immediate, saturating & narrowing, with rounding variants.
Types accepted S16 S32 S64 U16 U32 U64. */
NUF(vqshrn, 0800910, 3, (RND, RNQ, I32z), neon_rshift_sat_narrow),
NUF(vqrshrn, 0800950, 3, (RND, RNQ, I32z), neon_rshift_sat_narrow),
/* As above, unsigned. Types accepted S16 S32 S64. */
NUF(vqshrun, 0800810, 3, (RND, RNQ, I32z), neon_rshift_sat_narrow_u),
NUF(vqrshrun, 0800850, 3, (RND, RNQ, I32z), neon_rshift_sat_narrow_u),
/* Right shift narrowing. Types accepted I16 I32 I64. */
NUF(vshrn, 0800810, 3, (RND, RNQ, I32z), neon_rshift_narrow),
NUF(vrshrn, 0800850, 3, (RND, RNQ, I32z), neon_rshift_narrow),
/* Special case. Types S8 S16 S32 U8 U16 U32. Handles max shift variant. */
nUF(vshll, _vshll, 3, (RNQ, RND, I32), neon_shll),
/* CVT with optional immediate for fixed-point variant. */
nUF(vcvtq, _vcvt, 3, (RNQ, RNQ, oI32b), neon_cvt),
nUF(vmvn, _vmvn, 2, (RNDQ, RNDQ_Ibig), neon_mvn),
nUF(vmvnq, _vmvn, 2, (RNQ, RNDQ_Ibig), neon_mvn),
/* Data processing, three registers of different lengths. */
/* Dyadic, long insns. Types S8 S16 S32 U8 U16 U32. */
NUF(vabal, 0800500, 3, (RNQ, RND, RND), neon_abal),
NUF(vabdl, 0800700, 3, (RNQ, RND, RND), neon_dyadic_long),
NUF(vaddl, 0800000, 3, (RNQ, RND, RND), neon_dyadic_long),
NUF(vsubl, 0800200, 3, (RNQ, RND, RND), neon_dyadic_long),
/* If not scalar, fall back to neon_dyadic_long.
Vector types as above, scalar types S16 S32 U16 U32. */
nUF(vmlal, _vmlal, 3, (RNQ, RND, RND_RNSC), neon_mac_maybe_scalar_long),
nUF(vmlsl, _vmlsl, 3, (RNQ, RND, RND_RNSC), neon_mac_maybe_scalar_long),
/* Dyadic, widening insns. Types S8 S16 S32 U8 U16 U32. */
NUF(vaddw, 0800100, 3, (RNQ, oRNQ, RND), neon_dyadic_wide),
NUF(vsubw, 0800300, 3, (RNQ, oRNQ, RND), neon_dyadic_wide),
/* Dyadic, narrowing insns. Types I16 I32 I64. */
NUF(vaddhn, 0800400, 3, (RND, RNQ, RNQ), neon_dyadic_narrow),
NUF(vraddhn, 1800400, 3, (RND, RNQ, RNQ), neon_dyadic_narrow),
NUF(vsubhn, 0800600, 3, (RND, RNQ, RNQ), neon_dyadic_narrow),
NUF(vrsubhn, 1800600, 3, (RND, RNQ, RNQ), neon_dyadic_narrow),
/* Saturating doubling multiplies. Types S16 S32. */
nUF(vqdmlal, _vqdmlal, 3, (RNQ, RND, RND_RNSC), neon_mul_sat_scalar_long),
nUF(vqdmlsl, _vqdmlsl, 3, (RNQ, RND, RND_RNSC), neon_mul_sat_scalar_long),
nUF(vqdmull, _vqdmull, 3, (RNQ, RND, RND_RNSC), neon_mul_sat_scalar_long),
/* VMULL. Vector types S8 S16 S32 U8 U16 U32 P8, scalar types
S16 S32 U16 U32. */
nUF(vmull, _vmull, 3, (RNQ, RND, RND_RNSC), neon_vmull),
/* Extract. Size 8. */
NUF(vext, 0b00000, 4, (RNDQ, oRNDQ, RNDQ, I15), neon_ext),
NUF(vextq, 0b00000, 4, (RNQ, oRNQ, RNQ, I15), neon_ext),
/* Two registers, miscellaneous. */
/* Reverse. Sizes 8 16 32 (must be < size in opcode). */
NUF(vrev64, 1b00000, 2, (RNDQ, RNDQ), neon_rev),
NUF(vrev64q, 1b00000, 2, (RNQ, RNQ), neon_rev),
NUF(vrev32, 1b00080, 2, (RNDQ, RNDQ), neon_rev),
NUF(vrev32q, 1b00080, 2, (RNQ, RNQ), neon_rev),
NUF(vrev16, 1b00100, 2, (RNDQ, RNDQ), neon_rev),
NUF(vrev16q, 1b00100, 2, (RNQ, RNQ), neon_rev),
/* Vector replicate. Sizes 8 16 32. */
nCE(vdup, _vdup, 2, (RNDQ, RR_RNSC), neon_dup),
nCE(vdupq, _vdup, 2, (RNQ, RR_RNSC), neon_dup),
/* VMOVL. Types S8 S16 S32 U8 U16 U32. */
NUF(vmovl, 0800a10, 2, (RNQ, RND), neon_movl),
/* VMOVN. Types I16 I32 I64. */
nUF(vmovn, _vmovn, 2, (RND, RNQ), neon_movn),
/* VQMOVN. Types S16 S32 S64 U16 U32 U64. */
nUF(vqmovn, _vqmovn, 2, (RND, RNQ), neon_qmovn),
/* VQMOVUN. Types S16 S32 S64. */
nUF(vqmovun, _vqmovun, 2, (RND, RNQ), neon_qmovun),
/* VZIP / VUZP. Sizes 8 16 32. */
NUF(vzip, 1b20180, 2, (RNDQ, RNDQ), neon_zip_uzp),
NUF(vzipq, 1b20180, 2, (RNQ, RNQ), neon_zip_uzp),
NUF(vuzp, 1b20100, 2, (RNDQ, RNDQ), neon_zip_uzp),
NUF(vuzpq, 1b20100, 2, (RNQ, RNQ), neon_zip_uzp),
/* VQABS / VQNEG. Types S8 S16 S32. */
NUF(vqabs, 1b00700, 2, (RNDQ, RNDQ), neon_sat_abs_neg),
NUF(vqabsq, 1b00700, 2, (RNQ, RNQ), neon_sat_abs_neg),
NUF(vqneg, 1b00780, 2, (RNDQ, RNDQ), neon_sat_abs_neg),
NUF(vqnegq, 1b00780, 2, (RNQ, RNQ), neon_sat_abs_neg),
/* Pairwise, lengthening. Types S8 S16 S32 U8 U16 U32. */
NUF(vpadal, 1b00600, 2, (RNDQ, RNDQ), neon_pair_long),
NUF(vpadalq, 1b00600, 2, (RNQ, RNQ), neon_pair_long),
NUF(vpaddl, 1b00200, 2, (RNDQ, RNDQ), neon_pair_long),
NUF(vpaddlq, 1b00200, 2, (RNQ, RNQ), neon_pair_long),
/* Reciprocal estimates. Types U32 F32. */
NUF(vrecpe, 1b30400, 2, (RNDQ, RNDQ), neon_recip_est),
NUF(vrecpeq, 1b30400, 2, (RNQ, RNQ), neon_recip_est),
NUF(vrsqrte, 1b30480, 2, (RNDQ, RNDQ), neon_recip_est),
NUF(vrsqrteq, 1b30480, 2, (RNQ, RNQ), neon_recip_est),
/* VCLS. Types S8 S16 S32. */
NUF(vcls, 1b00400, 2, (RNDQ, RNDQ), neon_cls),
NUF(vclsq, 1b00400, 2, (RNQ, RNQ), neon_cls),
/* VCLZ. Types I8 I16 I32. */
NUF(vclz, 1b00480, 2, (RNDQ, RNDQ), neon_clz),
NUF(vclzq, 1b00480, 2, (RNQ, RNQ), neon_clz),
/* VCNT. Size 8. */
NUF(vcnt, 1b00500, 2, (RNDQ, RNDQ), neon_cnt),
NUF(vcntq, 1b00500, 2, (RNQ, RNQ), neon_cnt),
/* Two address, untyped. */
NUF(vswp, 1b20000, 2, (RNDQ, RNDQ), neon_swp),
NUF(vswpq, 1b20000, 2, (RNQ, RNQ), neon_swp),
/* VTRN. Sizes 8 16 32. */
nUF(vtrn, _vtrn, 2, (RNDQ, RNDQ), neon_trn),
nUF(vtrnq, _vtrn, 2, (RNQ, RNQ), neon_trn),
/* Table lookup. Size 8. */
NUF(vtbl, 1b00800, 3, (RND, NRDLST, RND), neon_tbl_tbx),
NUF(vtbx, 1b00840, 3, (RND, NRDLST, RND), neon_tbl_tbx),
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_vfp_v3_or_neon_ext
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_v3_or_neon_ext
/* Neon element/structure load/store. */
nUF(vld1, _vld1, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vst1, _vst1, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vld2, _vld2, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vst2, _vst2, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vld3, _vld3, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vst3, _vst3, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vld4, _vld4, 2, (NSTRLST, ADDR), neon_ldx_stx),
nUF(vst4, _vst4, 2, (NSTRLST, ADDR), neon_ldx_stx),
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_vfp_ext_v3xd
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_v3xd
cCE("fconsts", eb00a00, 2, (RVS, I255), vfp_sp_const),
cCE("fshtos", eba0a40, 2, (RVS, I16z), vfp_sp_conv_16),
cCE("fsltos", eba0ac0, 2, (RVS, I32), vfp_sp_conv_32),
cCE("fuhtos", ebb0a40, 2, (RVS, I16z), vfp_sp_conv_16),
cCE("fultos", ebb0ac0, 2, (RVS, I32), vfp_sp_conv_32),
cCE("ftoshs", ebe0a40, 2, (RVS, I16z), vfp_sp_conv_16),
cCE("ftosls", ebe0ac0, 2, (RVS, I32), vfp_sp_conv_32),
cCE("ftouhs", ebf0a40, 2, (RVS, I16z), vfp_sp_conv_16),
cCE("ftouls", ebf0ac0, 2, (RVS, I32), vfp_sp_conv_32),
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_vfp_ext_v3
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_v3
cCE("fconstd", eb00b00, 2, (RVD, I255), vfp_dp_const),
cCE("fshtod", eba0b40, 2, (RVD, I16z), vfp_dp_conv_16),
cCE("fsltod", eba0bc0, 2, (RVD, I32), vfp_dp_conv_32),
cCE("fuhtod", ebb0b40, 2, (RVD, I16z), vfp_dp_conv_16),
cCE("fultod", ebb0bc0, 2, (RVD, I32), vfp_dp_conv_32),
cCE("ftoshd", ebe0b40, 2, (RVD, I16z), vfp_dp_conv_16),
cCE("ftosld", ebe0bc0, 2, (RVD, I32), vfp_dp_conv_32),
cCE("ftouhd", ebf0b40, 2, (RVD, I16z), vfp_dp_conv_16),
cCE("ftould", ebf0bc0, 2, (RVD, I32), vfp_dp_conv_32),
#undef ARM_VARIANT
#define ARM_VARIANT & fpu_vfp_ext_fma
#undef THUMB_VARIANT
#define THUMB_VARIANT & fpu_vfp_ext_fma
/* Mnemonics shared by Neon and VFP. These are included in the
VFP FMA variant; NEON and VFP FMA always includes the NEON
FMA instructions. */
nCEF(vfma, _vfma, 3, (RNSDQ, oRNSDQ, RNSDQ), neon_fmac),
nCEF(vfms, _vfms, 3, (RNSDQ, oRNSDQ, RNSDQ), neon_fmac),
/* ffmas/ffmad/ffmss/ffmsd are dummy mnemonics to satisfy gas;
the v form should always be used. */
cCE("ffmas", ea00a00, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("ffnmas", ea00a40, 3, (RVS, RVS, RVS), vfp_sp_dyadic),
cCE("ffmad", ea00b00, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
cCE("ffnmad", ea00b40, 3, (RVD, RVD, RVD), vfp_dp_rd_rn_rm),
nCE(vfnma, _vfnma, 3, (RVSD, RVSD, RVSD), vfp_nsyn_nmul),
nCE(vfnms, _vfnms, 3, (RVSD, RVSD, RVSD), vfp_nsyn_nmul),
#undef THUMB_VARIANT
#undef ARM_VARIANT
#define ARM_VARIANT & arm_cext_xscale /* Intel XScale extensions. */
cCE("mia", e200010, 3, (RXA, RRnpc, RRnpc), xsc_mia),
cCE("miaph", e280010, 3, (RXA, RRnpc, RRnpc), xsc_mia),
cCE("miabb", e2c0010, 3, (RXA, RRnpc, RRnpc), xsc_mia),
cCE("miabt", e2d0010, 3, (RXA, RRnpc, RRnpc), xsc_mia),
cCE("miatb", e2e0010, 3, (RXA, RRnpc, RRnpc), xsc_mia),
cCE("miatt", e2f0010, 3, (RXA, RRnpc, RRnpc), xsc_mia),
cCE("mar", c400000, 3, (RXA, RRnpc, RRnpc), xsc_mar),
cCE("mra", c500000, 3, (RRnpc, RRnpc, RXA), xsc_mra),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_cext_iwmmxt /* Intel Wireless MMX technology. */
cCE("tandcb", e13f130, 1, (RR), iwmmxt_tandorc),
cCE("tandch", e53f130, 1, (RR), iwmmxt_tandorc),
cCE("tandcw", e93f130, 1, (RR), iwmmxt_tandorc),
cCE("tbcstb", e400010, 2, (RIWR, RR), rn_rd),
cCE("tbcsth", e400050, 2, (RIWR, RR), rn_rd),
cCE("tbcstw", e400090, 2, (RIWR, RR), rn_rd),
cCE("textrcb", e130170, 2, (RR, I7), iwmmxt_textrc),
cCE("textrch", e530170, 2, (RR, I7), iwmmxt_textrc),
cCE("textrcw", e930170, 2, (RR, I7), iwmmxt_textrc),
cCE("textrmub",e100070, 3, (RR, RIWR, I7), iwmmxt_textrm),
cCE("textrmuh",e500070, 3, (RR, RIWR, I7), iwmmxt_textrm),
cCE("textrmuw",e900070, 3, (RR, RIWR, I7), iwmmxt_textrm),
cCE("textrmsb",e100078, 3, (RR, RIWR, I7), iwmmxt_textrm),
cCE("textrmsh",e500078, 3, (RR, RIWR, I7), iwmmxt_textrm),
cCE("textrmsw",e900078, 3, (RR, RIWR, I7), iwmmxt_textrm),
cCE("tinsrb", e600010, 3, (RIWR, RR, I7), iwmmxt_tinsr),
cCE("tinsrh", e600050, 3, (RIWR, RR, I7), iwmmxt_tinsr),
cCE("tinsrw", e600090, 3, (RIWR, RR, I7), iwmmxt_tinsr),
cCE("tmcr", e000110, 2, (RIWC_RIWG, RR), rn_rd),
cCE("tmcrr", c400000, 3, (RIWR, RR, RR), rm_rd_rn),
cCE("tmia", e200010, 3, (RIWR, RR, RR), iwmmxt_tmia),
cCE("tmiaph", e280010, 3, (RIWR, RR, RR), iwmmxt_tmia),
cCE("tmiabb", e2c0010, 3, (RIWR, RR, RR), iwmmxt_tmia),
cCE("tmiabt", e2d0010, 3, (RIWR, RR, RR), iwmmxt_tmia),
cCE("tmiatb", e2e0010, 3, (RIWR, RR, RR), iwmmxt_tmia),
cCE("tmiatt", e2f0010, 3, (RIWR, RR, RR), iwmmxt_tmia),
cCE("tmovmskb",e100030, 2, (RR, RIWR), rd_rn),
cCE("tmovmskh",e500030, 2, (RR, RIWR), rd_rn),
cCE("tmovmskw",e900030, 2, (RR, RIWR), rd_rn),
cCE("tmrc", e100110, 2, (RR, RIWC_RIWG), rd_rn),
cCE("tmrrc", c500000, 3, (RR, RR, RIWR), rd_rn_rm),
cCE("torcb", e13f150, 1, (RR), iwmmxt_tandorc),
cCE("torch", e53f150, 1, (RR), iwmmxt_tandorc),
cCE("torcw", e93f150, 1, (RR), iwmmxt_tandorc),
cCE("waccb", e0001c0, 2, (RIWR, RIWR), rd_rn),
cCE("wacch", e4001c0, 2, (RIWR, RIWR), rd_rn),
cCE("waccw", e8001c0, 2, (RIWR, RIWR), rd_rn),
cCE("waddbss", e300180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddb", e000180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddbus", e100180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddhss", e700180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddh", e400180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddhus", e500180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddwss", eb00180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddw", e800180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddwus", e900180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waligni", e000020, 4, (RIWR, RIWR, RIWR, I7), iwmmxt_waligni),
cCE("walignr0",e800020, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("walignr1",e900020, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("walignr2",ea00020, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("walignr3",eb00020, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wand", e200000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wandn", e300000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wavg2b", e800000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wavg2br", e900000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wavg2h", ec00000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wavg2hr", ed00000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpeqb", e000060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpeqh", e400060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpeqw", e800060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpgtub",e100060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpgtuh",e500060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpgtuw",e900060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpgtsb",e300060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpgtsh",e700060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wcmpgtsw",eb00060, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wldrb", c100000, 2, (RIWR, ADDR), iwmmxt_wldstbh),
cCE("wldrh", c500000, 2, (RIWR, ADDR), iwmmxt_wldstbh),
cCE("wldrw", c100100, 2, (RIWR_RIWC, ADDR), iwmmxt_wldstw),
cCE("wldrd", c500100, 2, (RIWR, ADDR), iwmmxt_wldstd),
cCE("wmacs", e600100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmacsz", e700100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmacu", e400100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmacuz", e500100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmadds", ea00100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaddu", e800100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaxsb", e200160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaxsh", e600160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaxsw", ea00160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaxub", e000160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaxuh", e400160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaxuw", e800160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wminsb", e300160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wminsh", e700160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wminsw", eb00160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wminub", e100160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wminuh", e500160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wminuw", e900160, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmov", e000000, 2, (RIWR, RIWR), iwmmxt_wmov),
cCE("wmulsm", e300100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulsl", e200100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulum", e100100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulul", e000100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wor", e000000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wpackhss",e700080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wpackhus",e500080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wpackwss",eb00080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wpackwus",e900080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wpackdss",ef00080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wpackdus",ed00080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wrorh", e700040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wrorhg", e700148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wrorw", eb00040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wrorwg", eb00148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wrord", ef00040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wrordg", ef00148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsadb", e000120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsadbz", e100120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsadh", e400120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsadhz", e500120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wshufh", e0001e0, 3, (RIWR, RIWR, I255), iwmmxt_wshufh),
cCE("wsllh", e500040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsllhg", e500148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsllw", e900040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsllwg", e900148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wslld", ed00040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wslldg", ed00148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsrah", e400040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsrahg", e400148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsraw", e800040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsrawg", e800148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsrad", ec00040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsradg", ec00148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsrlh", e600040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsrlhg", e600148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsrlw", ea00040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsrlwg", ea00148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wsrld", ee00040, 3, (RIWR, RIWR, RIWR_I32z),iwmmxt_wrwrwr_or_imm5),
cCE("wsrldg", ee00148, 3, (RIWR, RIWR, RIWG), rd_rn_rm),
cCE("wstrb", c000000, 2, (RIWR, ADDR), iwmmxt_wldstbh),
cCE("wstrh", c400000, 2, (RIWR, ADDR), iwmmxt_wldstbh),
cCE("wstrw", c000100, 2, (RIWR_RIWC, ADDR), iwmmxt_wldstw),
cCE("wstrd", c400100, 2, (RIWR, ADDR), iwmmxt_wldstd),
cCE("wsubbss", e3001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubb", e0001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubbus", e1001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubhss", e7001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubh", e4001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubhus", e5001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubwss", eb001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubw", e8001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubwus", e9001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wunpckehub",e0000c0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckehuh",e4000c0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckehuw",e8000c0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckehsb",e2000c0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckehsh",e6000c0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckehsw",ea000c0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckihb", e1000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wunpckihh", e5000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wunpckihw", e9000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wunpckelub",e0000e0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckeluh",e4000e0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckeluw",e8000e0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckelsb",e2000e0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckelsh",e6000e0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckelsw",ea000e0, 2, (RIWR, RIWR), rd_rn),
cCE("wunpckilb", e1000e0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wunpckilh", e5000e0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wunpckilw", e9000e0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wxor", e100000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wzero", e300000, 1, (RIWR), iwmmxt_wzero),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_cext_iwmmxt2 /* Intel Wireless MMX technology, version 2. */
cCE("torvscb", e12f190, 1, (RR), iwmmxt_tandorc),
cCE("torvsch", e52f190, 1, (RR), iwmmxt_tandorc),
cCE("torvscw", e92f190, 1, (RR), iwmmxt_tandorc),
cCE("wabsb", e2001c0, 2, (RIWR, RIWR), rd_rn),
cCE("wabsh", e6001c0, 2, (RIWR, RIWR), rd_rn),
cCE("wabsw", ea001c0, 2, (RIWR, RIWR), rd_rn),
cCE("wabsdiffb", e1001c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wabsdiffh", e5001c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wabsdiffw", e9001c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddbhusl", e2001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddbhusm", e6001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddhc", e600180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddwc", ea00180, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("waddsubhx", ea001a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wavg4", e400000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wavg4r", e500000, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaddsn", ee00100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaddsx", eb00100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaddun", ec00100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmaddux", e900100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmerge", e000080, 4, (RIWR, RIWR, RIWR, I7), iwmmxt_wmerge),
cCE("wmiabb", e0000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiabt", e1000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiatb", e2000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiatt", e3000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiabbn", e4000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiabtn", e5000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiatbn", e6000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiattn", e7000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawbb", e800120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawbt", e900120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawtb", ea00120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawtt", eb00120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawbbn", ec00120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawbtn", ed00120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawtbn", ee00120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmiawttn", ef00120, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulsmr", ef00100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulumr", ed00100, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulwumr", ec000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulwsmr", ee000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulwum", ed000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulwsm", ef000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wmulwl", eb000c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiabb", e8000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiabt", e9000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiatb", ea000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiatt", eb000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiabbn", ec000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiabtn", ed000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiatbn", ee000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmiattn", ef000a0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmulm", e100080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmulmr", e300080, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmulwm", ec000e0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wqmulwmr", ee000e0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
cCE("wsubaddhx", ed001c0, 3, (RIWR, RIWR, RIWR), rd_rn_rm),
#undef ARM_VARIANT
#define ARM_VARIANT & arm_cext_maverick /* Cirrus Maverick instructions. */
cCE("cfldrs", c100400, 2, (RMF, ADDRGLDC), rd_cpaddr),
cCE("cfldrd", c500400, 2, (RMD, ADDRGLDC), rd_cpaddr),
cCE("cfldr32", c100500, 2, (RMFX, ADDRGLDC), rd_cpaddr),
cCE("cfldr64", c500500, 2, (RMDX, ADDRGLDC), rd_cpaddr),
cCE("cfstrs", c000400, 2, (RMF, ADDRGLDC), rd_cpaddr),
cCE("cfstrd", c400400, 2, (RMD, ADDRGLDC), rd_cpaddr),
cCE("cfstr32", c000500, 2, (RMFX, ADDRGLDC), rd_cpaddr),
cCE("cfstr64", c400500, 2, (RMDX, ADDRGLDC), rd_cpaddr),
cCE("cfmvsr", e000450, 2, (RMF, RR), rn_rd),
cCE("cfmvrs", e100450, 2, (RR, RMF), rd_rn),
cCE("cfmvdlr", e000410, 2, (RMD, RR), rn_rd),
cCE("cfmvrdl", e100410, 2, (RR, RMD), rd_rn),
cCE("cfmvdhr", e000430, 2, (RMD, RR), rn_rd),
cCE("cfmvrdh", e100430, 2, (RR, RMD), rd_rn),
cCE("cfmv64lr",e000510, 2, (RMDX, RR), rn_rd),
cCE("cfmvr64l",e100510, 2, (RR, RMDX), rd_rn),
cCE("cfmv64hr",e000530, 2, (RMDX, RR), rn_rd),
cCE("cfmvr64h",e100530, 2, (RR, RMDX), rd_rn),
cCE("cfmval32",e200440, 2, (RMAX, RMFX), rd_rn),
cCE("cfmv32al",e100440, 2, (RMFX, RMAX), rd_rn),
cCE("cfmvam32",e200460, 2, (RMAX, RMFX), rd_rn),
cCE("cfmv32am",e100460, 2, (RMFX, RMAX), rd_rn),
cCE("cfmvah32",e200480, 2, (RMAX, RMFX), rd_rn),
cCE("cfmv32ah",e100480, 2, (RMFX, RMAX), rd_rn),
cCE("cfmva32", e2004a0, 2, (RMAX, RMFX), rd_rn),
cCE("cfmv32a", e1004a0, 2, (RMFX, RMAX), rd_rn),
cCE("cfmva64", e2004c0, 2, (RMAX, RMDX), rd_rn),
cCE("cfmv64a", e1004c0, 2, (RMDX, RMAX), rd_rn),
cCE("cfmvsc32",e2004e0, 2, (RMDS, RMDX), mav_dspsc),
cCE("cfmv32sc",e1004e0, 2, (RMDX, RMDS), rd),
cCE("cfcpys", e000400, 2, (RMF, RMF), rd_rn),
cCE("cfcpyd", e000420, 2, (RMD, RMD), rd_rn),
cCE("cfcvtsd", e000460, 2, (RMD, RMF), rd_rn),
cCE("cfcvtds", e000440, 2, (RMF, RMD), rd_rn),
cCE("cfcvt32s",e000480, 2, (RMF, RMFX), rd_rn),
cCE("cfcvt32d",e0004a0, 2, (RMD, RMFX), rd_rn),
cCE("cfcvt64s",e0004c0, 2, (RMF, RMDX), rd_rn),
cCE("cfcvt64d",e0004e0, 2, (RMD, RMDX), rd_rn),
cCE("cfcvts32",e100580, 2, (RMFX, RMF), rd_rn),
cCE("cfcvtd32",e1005a0, 2, (RMFX, RMD), rd_rn),
cCE("cftruncs32",e1005c0, 2, (RMFX, RMF), rd_rn),
cCE("cftruncd32",e1005e0, 2, (RMFX, RMD), rd_rn),
cCE("cfrshl32",e000550, 3, (RMFX, RMFX, RR), mav_triple),
cCE("cfrshl64",e000570, 3, (RMDX, RMDX, RR), mav_triple),
cCE("cfsh32", e000500, 3, (RMFX, RMFX, I63s), mav_shift),
cCE("cfsh64", e200500, 3, (RMDX, RMDX, I63s), mav_shift),
cCE("cfcmps", e100490, 3, (RR, RMF, RMF), rd_rn_rm),
cCE("cfcmpd", e1004b0, 3, (RR, RMD, RMD), rd_rn_rm),
cCE("cfcmp32", e100590, 3, (RR, RMFX, RMFX), rd_rn_rm),
cCE("cfcmp64", e1005b0, 3, (RR, RMDX, RMDX), rd_rn_rm),
cCE("cfabss", e300400, 2, (RMF, RMF), rd_rn),
cCE("cfabsd", e300420, 2, (RMD, RMD), rd_rn),
cCE("cfnegs", e300440, 2, (RMF, RMF), rd_rn),
cCE("cfnegd", e300460, 2, (RMD, RMD), rd_rn),
cCE("cfadds", e300480, 3, (RMF, RMF, RMF), rd_rn_rm),
cCE("cfaddd", e3004a0, 3, (RMD, RMD, RMD), rd_rn_rm),
cCE("cfsubs", e3004c0, 3, (RMF, RMF, RMF), rd_rn_rm),
cCE("cfsubd", e3004e0, 3, (RMD, RMD, RMD), rd_rn_rm),
cCE("cfmuls", e100400, 3, (RMF, RMF, RMF), rd_rn_rm),
cCE("cfmuld", e100420, 3, (RMD, RMD, RMD), rd_rn_rm),
cCE("cfabs32", e300500, 2, (RMFX, RMFX), rd_rn),
cCE("cfabs64", e300520, 2, (RMDX, RMDX), rd_rn),
cCE("cfneg32", e300540, 2, (RMFX, RMFX), rd_rn),
cCE("cfneg64", e300560, 2, (RMDX, RMDX), rd_rn),
cCE("cfadd32", e300580, 3, (RMFX, RMFX, RMFX), rd_rn_rm),
cCE("cfadd64", e3005a0, 3, (RMDX, RMDX, RMDX), rd_rn_rm),
cCE("cfsub32", e3005c0, 3, (RMFX, RMFX, RMFX), rd_rn_rm),
cCE("cfsub64", e3005e0, 3, (RMDX, RMDX, RMDX), rd_rn_rm),
cCE("cfmul32", e100500, 3, (RMFX, RMFX, RMFX), rd_rn_rm),
cCE("cfmul64", e100520, 3, (RMDX, RMDX, RMDX), rd_rn_rm),
cCE("cfmac32", e100540, 3, (RMFX, RMFX, RMFX), rd_rn_rm),
cCE("cfmsc32", e100560, 3, (RMFX, RMFX, RMFX), rd_rn_rm),
cCE("cfmadd32",e000600, 4, (RMAX, RMFX, RMFX, RMFX), mav_quad),
cCE("cfmsub32",e100600, 4, (RMAX, RMFX, RMFX, RMFX), mav_quad),
cCE("cfmadda32", e200600, 4, (RMAX, RMAX, RMFX, RMFX), mav_quad),
cCE("cfmsuba32", e300600, 4, (RMAX, RMAX, RMFX, RMFX), mav_quad),
};
#undef ARM_VARIANT
#undef THUMB_VARIANT
#undef TCE
#undef TUE
#undef TUF
#undef TCC
#undef cCE
#undef cCL
#undef C3E
#undef CE
#undef CM
#undef UE
#undef UF
#undef UT
#undef NUF
#undef nUF
#undef NCE
#undef nCE
#undef OPS0
#undef OPS1
#undef OPS2
#undef OPS3
#undef OPS4
#undef OPS5
#undef OPS6
#undef do_0
/* 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);
}
static valueT
md_chars_to_number (char * buf, int n)
{
valueT result = 0;
unsigned char * where = (unsigned char *) buf;
if (target_big_endian)
{
while (n--)
{
result <<= 8;
result |= (*where++ & 255);
}
}
else
{
while (n--)
{
result <<= 8;
result |= (where[n] & 255);
}
}
return result;
}
/* MD interface: Sections. */
/* Calculate the maximum variable size (i.e., excluding fr_fix)
that an rs_machine_dependent frag may reach. */
unsigned int
arm_frag_max_var (fragS *fragp)
{
/* We only use rs_machine_dependent for variable-size Thumb instructions,
which are either THUMB_SIZE (2) or INSN_SIZE (4).
Note that we generate relaxable instructions even for cases that don't
really need it, like an immediate that's a trivial constant. So we're
overestimating the instruction size for some of those cases. Rather
than putting more intelligence here, it would probably be better to
avoid generating a relaxation frag in the first place when it can be
determined up front that a short instruction will suffice. */
gas_assert (fragp->fr_type == rs_machine_dependent);
return INSN_SIZE;
}
/* Estimate the size of a frag before relaxing. Assume everything fits in
2 bytes. */
int
md_estimate_size_before_relax (fragS * fragp,
segT segtype ATTRIBUTE_UNUSED)
{
fragp->fr_var = 2;
return 2;
}
/* Convert a machine dependent frag. */
void
md_convert_frag (bfd *abfd, segT asec ATTRIBUTE_UNUSED, fragS *fragp)
{
unsigned long insn;
unsigned long old_op;
char *buf;
expressionS exp;
fixS *fixp;
int reloc_type;
int pc_rel;
int opcode;
buf = fragp->fr_literal + fragp->fr_fix;
old_op = bfd_get_16(abfd, buf);
if (fragp->fr_symbol)
{
exp.X_op = O_symbol;
exp.X_add_symbol = fragp->fr_symbol;
}
else
{
exp.X_op = O_constant;
}
exp.X_add_number = fragp->fr_offset;
opcode = fragp->fr_subtype;
switch (opcode)
{
case T_MNEM_ldr_pc:
case T_MNEM_ldr_pc2:
case T_MNEM_ldr_sp:
case T_MNEM_str_sp:
case T_MNEM_ldr:
case T_MNEM_ldrb:
case T_MNEM_ldrh:
case T_MNEM_str:
case T_MNEM_strb:
case T_MNEM_strh:
if (fragp->fr_var == 4)
{
insn = THUMB_OP32 (opcode);
if ((old_op >> 12) == 4 || (old_op >> 12) == 9)
{
insn |= (old_op & 0x700) << 4;
}
else
{
insn |= (old_op & 7) << 12;
insn |= (old_op & 0x38) << 13;
}
insn |= 0x00000c00;
put_thumb32_insn (buf, insn);
reloc_type = BFD_RELOC_ARM_T32_OFFSET_IMM;
}
else
{
reloc_type = BFD_RELOC_ARM_THUMB_OFFSET;
}
pc_rel = (opcode == T_MNEM_ldr_pc2);
break;
case T_MNEM_adr:
if (fragp->fr_var == 4)
{
insn = THUMB_OP32 (opcode);
insn |= (old_op & 0xf0) << 4;
put_thumb32_insn (buf, insn);
reloc_type = BFD_RELOC_ARM_T32_ADD_PC12;
}
else
{
reloc_type = BFD_RELOC_ARM_THUMB_ADD;
exp.X_add_number -= 4;
}
pc_rel = 1;
break;
case T_MNEM_mov:
case T_MNEM_movs:
case T_MNEM_cmp:
case T_MNEM_cmn:
if (fragp->fr_var == 4)
{
int r0off = (opcode == T_MNEM_mov
|| opcode == T_MNEM_movs) ? 0 : 8;
insn = THUMB_OP32 (opcode);
insn = (insn & 0xe1ffffff) | 0x10000000;
insn |= (old_op & 0x700) << r0off;
put_thumb32_insn (buf, insn);
reloc_type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
else
{
reloc_type = BFD_RELOC_ARM_THUMB_IMM;
}
pc_rel = 0;
break;
case T_MNEM_b:
if (fragp->fr_var == 4)
{
insn = THUMB_OP32(opcode);
put_thumb32_insn (buf, insn);
reloc_type = BFD_RELOC_THUMB_PCREL_BRANCH25;
}
else
reloc_type = BFD_RELOC_THUMB_PCREL_BRANCH12;
pc_rel = 1;
break;
case T_MNEM_bcond:
if (fragp->fr_var == 4)
{
insn = THUMB_OP32(opcode);
insn |= (old_op & 0xf00) << 14;
put_thumb32_insn (buf, insn);
reloc_type = BFD_RELOC_THUMB_PCREL_BRANCH20;
}
else
reloc_type = BFD_RELOC_THUMB_PCREL_BRANCH9;
pc_rel = 1;
break;
case T_MNEM_add_sp:
case T_MNEM_add_pc:
case T_MNEM_inc_sp:
case T_MNEM_dec_sp:
if (fragp->fr_var == 4)
{
/* ??? Choose between add and addw. */
insn = THUMB_OP32 (opcode);
insn |= (old_op & 0xf0) << 4;
put_thumb32_insn (buf, insn);
if (opcode == T_MNEM_add_pc)
reloc_type = BFD_RELOC_ARM_T32_IMM12;
else
reloc_type = BFD_RELOC_ARM_T32_ADD_IMM;
}
else
reloc_type = BFD_RELOC_ARM_THUMB_ADD;
pc_rel = 0;
break;
case T_MNEM_addi:
case T_MNEM_addis:
case T_MNEM_subi:
case T_MNEM_subis:
if (fragp->fr_var == 4)
{
insn = THUMB_OP32 (opcode);
insn |= (old_op & 0xf0) << 4;
insn |= (old_op & 0xf) << 16;
put_thumb32_insn (buf, insn);
if (insn & (1 << 20))
reloc_type = BFD_RELOC_ARM_T32_ADD_IMM;
else
reloc_type = BFD_RELOC_ARM_T32_IMMEDIATE;
}
else
reloc_type = BFD_RELOC_ARM_THUMB_ADD;
pc_rel = 0;
break;
default:
abort ();
}
fixp = fix_new_exp (fragp, fragp->fr_fix, fragp->fr_var, &exp, pc_rel,
(enum bfd_reloc_code_real) reloc_type);
fixp->fx_file = fragp->fr_file;
fixp->fx_line = fragp->fr_line;
fragp->fr_fix += fragp->fr_var;
/* Set whether we use thumb-2 ISA based on final relaxation results. */
if (thumb_mode && fragp->fr_var == 4 && no_cpu_selected ()
&& !ARM_CPU_HAS_FEATURE (thumb_arch_used, arm_arch_t2))
ARM_MERGE_FEATURE_SETS (arm_arch_used, thumb_arch_used, arm_ext_v6t2);
}
/* Return the size of a relaxable immediate operand instruction.
SHIFT and SIZE specify the form of the allowable immediate. */
static int
relax_immediate (fragS *fragp, int size, int shift)
{
offsetT offset;
offsetT mask;
offsetT low;
/* ??? Should be able to do better than this. */
if (fragp->fr_symbol)
return 4;
low = (1 << shift) - 1;
mask = (1 << (shift + size)) - (1 << shift);
offset = fragp->fr_offset;
/* Force misaligned offsets to 32-bit variant. */
if (offset & low)
return 4;
if (offset & ~mask)
return 4;
return 2;
}
/* Get the address of a symbol during relaxation. */
static addressT
relaxed_symbol_addr (fragS *fragp, long stretch)
{
fragS *sym_frag;
addressT addr;
symbolS *sym;
sym = fragp->fr_symbol;
sym_frag = symbol_get_frag (sym);
know (S_GET_SEGMENT (sym) != absolute_section
|| sym_frag == &zero_address_frag);
addr = S_GET_VALUE (sym) + fragp->fr_offset;
/* If frag has yet to be reached on this pass, assume it will
move by STRETCH just as we did. If this is not so, it will
be because some frag between grows, and that will force
another pass. */
if (stretch != 0
&& sym_frag->relax_marker != fragp->relax_marker)
{
fragS *f;
/* Adjust stretch for any alignment frag. Note that if have
been expanding the earlier code, the symbol may be
defined in what appears to be an earlier frag. FIXME:
This doesn't handle the fr_subtype field, which specifies
a maximum number of bytes to skip when doing an
alignment. */
for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
{
if (f->fr_type == rs_align || f->fr_type == rs_align_code)
{
if (stretch < 0)
stretch = - ((- stretch)
& ~ ((1 << (int) f->fr_offset) - 1));
else
stretch &= ~ ((1 << (int) f->fr_offset) - 1);
if (stretch == 0)
break;
}
}
if (f != NULL)
addr += stretch;
}
return addr;
}
/* Return the size of a relaxable adr pseudo-instruction or PC-relative
load. */
static int
relax_adr (fragS *fragp, asection *sec, long stretch)
{
addressT addr;
offsetT val;
/* Assume worst case for symbols not known to be in the same section. */
if (fragp->fr_symbol == NULL
|| !S_IS_DEFINED (fragp->fr_symbol)
|| sec != S_GET_SEGMENT (fragp->fr_symbol)
|| S_IS_WEAK (fragp->fr_symbol))
return 4;
val = relaxed_symbol_addr (fragp, stretch);
addr = fragp->fr_address + fragp->fr_fix;
addr = (addr + 4) & ~3;
/* Force misaligned targets to 32-bit variant. */
if (val & 3)
return 4;
val -= addr;
if (val < 0 || val > 1020)
return 4;
return 2;
}
/* Return the size of a relaxable add/sub immediate instruction. */
static int
relax_addsub (fragS *fragp, asection *sec)
{
char *buf;
int op;
buf = fragp->fr_literal + fragp->fr_fix;
op = bfd_get_16(sec->owner, buf);
if ((op & 0xf) == ((op >> 4) & 0xf))
return relax_immediate (fragp, 8, 0);
else
return relax_immediate (fragp, 3, 0);
}
/* Return TRUE iff the definition of symbol S could be pre-empted
(overridden) at link or load time. */
static bfd_boolean
symbol_preemptible (symbolS *s)
{
/* Weak symbols can always be pre-empted. */
if (S_IS_WEAK (s))
return TRUE;
/* Non-global symbols cannot be pre-empted. */
if (! S_IS_EXTERNAL (s))
return FALSE;
#ifdef OBJ_ELF
/* In ELF, a global symbol can be marked protected, or private. In that
case it can't be pre-empted (other definitions in the same link unit
would violate the ODR). */
if (ELF_ST_VISIBILITY (S_GET_OTHER (s)) > STV_DEFAULT)
return FALSE;
#endif
/* Other global symbols might be pre-empted. */
return TRUE;
}
/* Return the size of a relaxable branch instruction. BITS is the
size of the offset field in the narrow instruction. */
static int
relax_branch (fragS *fragp, asection *sec, int bits, long stretch)
{
addressT addr;
offsetT val;
offsetT limit;
/* Assume worst case for symbols not known to be in the same section. */
if (!S_IS_DEFINED (fragp->fr_symbol)
|| sec != S_GET_SEGMENT (fragp->fr_symbol)
|| S_IS_WEAK (fragp->fr_symbol))
return 4;
#ifdef OBJ_ELF
/* A branch to a function in ARM state will require interworking. */
if (S_IS_DEFINED (fragp->fr_symbol)
&& ARM_IS_FUNC (fragp->fr_symbol))
return 4;
#endif
if (symbol_preemptible (fragp->fr_symbol))
return 4;
val = relaxed_symbol_addr (fragp, stretch);
addr = fragp->fr_address + fragp->fr_fix + 4;
val -= addr;
/* Offset is a signed value *2 */
limit = 1 << bits;
if (val >= limit || val < -limit)
return 4;
return 2;
}
/* Relax a machine dependent frag. This returns the amount by which
the current size of the frag should change. */
int
arm_relax_frag (asection *sec, fragS *fragp, long stretch)
{
int oldsize;
int newsize;
oldsize = fragp->fr_var;
switch (fragp->fr_subtype)
{
case T_MNEM_ldr_pc2:
newsize = relax_adr (fragp, sec, stretch);
break;
case T_MNEM_ldr_pc:
case T_MNEM_ldr_sp:
case T_MNEM_str_sp:
newsize = relax_immediate (fragp, 8, 2);
break;
case T_MNEM_ldr:
case T_MNEM_str:
newsize = relax_immediate (fragp, 5, 2);
break;
case T_MNEM_ldrh:
case T_MNEM_strh:
newsize = relax_immediate (fragp, 5, 1);
break;
case T_MNEM_ldrb:
case T_MNEM_strb:
newsize = relax_immediate (fragp, 5, 0);
break;
case T_MNEM_adr:
newsize = relax_adr (fragp, sec, stretch);
break;
case T_MNEM_mov:
case T_MNEM_movs:
case T_MNEM_cmp:
case T_MNEM_cmn:
newsize = relax_immediate (fragp, 8, 0);
break;
case T_MNEM_b:
newsize = relax_branch (fragp, sec, 11, stretch);
break;
case T_MNEM_bcond:
newsize = relax_branch (fragp, sec, 8, stretch);
break;
case T_MNEM_add_sp:
case T_MNEM_add_pc:
newsize = relax_immediate (fragp, 8, 2);
break;
case T_MNEM_inc_sp:
case T_MNEM_dec_sp:
newsize = relax_immediate (fragp, 7, 2);
break;
case T_MNEM_addi:
case T_MNEM_addis:
case T_MNEM_subi:
case T_MNEM_subis:
newsize = relax_addsub (fragp, sec);
break;
default:
abort ();
}
fragp->fr_var = newsize;
/* Freeze wide instructions that are at or before the same location as
in the previous pass. This avoids infinite loops.
Don't freeze them unconditionally because targets may be artificially
misaligned by the expansion of preceding frags. */
if (stretch <= 0 && newsize > 2)
{
md_convert_frag (sec->owner, sec, fragp);
frag_wane (fragp);
}
return newsize - oldsize;
}
/* Round up a section size to the appropriate boundary. */
valueT
md_section_align (segT segment ATTRIBUTE_UNUSED,
valueT size)
{
#if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
if (OUTPUT_FLAVOR == bfd_target_aout_flavour)
{
/* For a.out, force the section size to be aligned. If we don't do
this, BFD will align it for us, but it will not write out the
final bytes of the section. This may be a bug in BFD, but it is
easier to fix it here since that is how the other a.out targets
work. */
int align;
align = bfd_get_section_alignment (stdoutput, segment);
size = ((size + (1 << align) - 1) & ((valueT) -1 << align));
}
#endif
return size;
}
/* This is called from HANDLE_ALIGN in write.c. Fill in the contents
of an rs_align_code fragment. */
void
arm_handle_align (fragS * fragP)
{
static char const arm_noop[2][2][4] =
{
{ /* ARMv1 */
{0x00, 0x00, 0xa0, 0xe1}, /* LE */
{0xe1, 0xa0, 0x00, 0x00}, /* BE */
},
{ /* ARMv6k */
{0x00, 0xf0, 0x20, 0xe3}, /* LE */
{0xe3, 0x20, 0xf0, 0x00}, /* BE */
},
};
static char const thumb_noop[2][2][2] =
{
{ /* Thumb-1 */
{0xc0, 0x46}, /* LE */
{0x46, 0xc0}, /* BE */
},
{ /* Thumb-2 */
{0x00, 0xbf}, /* LE */
{0xbf, 0x00} /* BE */
}
};
static char const wide_thumb_noop[2][4] =
{ /* Wide Thumb-2 */
{0xaf, 0xf3, 0x00, 0x80}, /* LE */
{0xf3, 0xaf, 0x80, 0x00}, /* BE */
};
unsigned bytes, fix, noop_size;
char * p;
const char * noop;
const char *narrow_noop = NULL;
#ifdef OBJ_ELF
enum mstate state;
#endif
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;
fix = 0;
if (bytes > MAX_MEM_FOR_RS_ALIGN_CODE)
bytes &= MAX_MEM_FOR_RS_ALIGN_CODE;
gas_assert ((fragP->tc_frag_data.thumb_mode & MODE_RECORDED) != 0);
if (fragP->tc_frag_data.thumb_mode & (~ MODE_RECORDED))
{
if (ARM_CPU_HAS_FEATURE (selected_cpu_name[0]
? selected_cpu : arm_arch_none, arm_ext_v6t2))
{
narrow_noop = thumb_noop[1][target_big_endian];
noop = wide_thumb_noop[target_big_endian];
}
else
noop = thumb_noop[0][target_big_endian];
noop_size = 2;
#ifdef OBJ_ELF
state = MAP_THUMB;
#endif
}
else
{
noop = arm_noop[ARM_CPU_HAS_FEATURE (selected_cpu_name[0]
? selected_cpu : arm_arch_none,
arm_ext_v6k) != 0]
[target_big_endian];
noop_size = 4;
#ifdef OBJ_ELF
state = MAP_ARM;
#endif
}
fragP->fr_var = noop_size;
if (bytes & (noop_size - 1))
{
fix = bytes & (noop_size - 1);
#ifdef OBJ_ELF
insert_data_mapping_symbol (state, fragP->fr_fix, fragP, fix);
#endif
memset (p, 0, fix);
p += fix;
bytes -= fix;
}
if (narrow_noop)
{
if (bytes & noop_size)
{
/* Insert a narrow noop. */
memcpy (p, narrow_noop, noop_size);
p += noop_size;
bytes -= noop_size;
fix += noop_size;
}
/* Use wide noops for the remainder */
noop_size = 4;
}
while (bytes >= noop_size)
{
memcpy (p, noop, noop_size);
p += noop_size;
bytes -= noop_size;
fix += noop_size;
}
fragP->fr_fix += fix;
}
/* Called from md_do_align. Used to create an alignment
frag in a code section. */
void
arm_frag_align_code (int n, int max)
{
char * p;
/* We assume that there will never be a requirement
to support alignments greater than MAX_MEM_FOR_RS_ALIGN_CODE bytes. */
if (max > MAX_MEM_FOR_RS_ALIGN_CODE)
{
char err_msg[128];
sprintf (err_msg,
_("alignments greater than %d bytes not supported in .text sections."),
MAX_MEM_FOR_RS_ALIGN_CODE + 1);
as_fatal ("%s", err_msg);
}
p = frag_var (rs_align_code,
MAX_MEM_FOR_RS_ALIGN_CODE,
1,
(relax_substateT) max,
(symbolS *) NULL,
(offsetT) n,
(char *) NULL);
*p = 0;
}
/* 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
arm_init_frag (fragS * fragP, int max_chars ATTRIBUTE_UNUSED)
{
/* Record whether this frag is in an ARM or a THUMB area. */
fragP->tc_frag_data.thumb_mode = thumb_mode | MODE_RECORDED;
}
#else /* OBJ_ELF is defined. */
void
arm_init_frag (fragS * fragP, int max_chars)
{
/* If the current ARM vs THUMB mode has not already
been recorded into this frag then do so now. */
if ((fragP->tc_frag_data.thumb_mode & MODE_RECORDED) == 0)
{
fragP->tc_frag_data.thumb_mode = thumb_mode | MODE_RECORDED;
/* Record a mapping symbol for alignment frags. We will delete this
later if the alignment ends up empty. */
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 (thumb_mode ? MAP_THUMB : MAP_ARM, max_chars);
break;
default:
break;
}
}
}
/* When we change sections we need to issue a new mapping symbol. */
void
arm_elf_change_section (void)
{
/* Link an unlinked unwind index table section to the .text section. */
if (elf_section_type (now_seg) == SHT_ARM_EXIDX
&& elf_linked_to_section (now_seg) == NULL)
elf_linked_to_section (now_seg) = text_section;
}
int
arm_elf_section_type (const char * str, size_t len)
{
if (len == 5 && strncmp (str, "exidx", 5) == 0)
return SHT_ARM_EXIDX;
return -1;
}
/* Code to deal with unwinding tables. */
static void add_unwind_adjustsp (offsetT);
/* Generate any deferred unwind frame offset. */
static void
flush_pending_unwind (void)
{
offsetT offset;
offset = unwind.pending_offset;
unwind.pending_offset = 0;
if (offset != 0)
add_unwind_adjustsp (offset);
}
/* Add an opcode to this list for this function. Two-byte opcodes should
be passed as op[0] << 8 | op[1]. The list of opcodes is built in reverse
order. */
static void
add_unwind_opcode (valueT op, int length)
{
/* Add any deferred stack adjustment. */
if (unwind.pending_offset)
flush_pending_unwind ();
unwind.sp_restored = 0;
if (unwind.opcode_count + length > unwind.opcode_alloc)
{
unwind.opcode_alloc += ARM_OPCODE_CHUNK_SIZE;
if (unwind.opcodes)
unwind.opcodes = (unsigned char *) xrealloc (unwind.opcodes,
unwind.opcode_alloc);
else
unwind.opcodes = (unsigned char *) xmalloc (unwind.opcode_alloc);
}
while (length > 0)
{
length--;
unwind.opcodes[unwind.opcode_count] = op & 0xff;
op >>= 8;
unwind.opcode_count++;
}
}
/* Add unwind opcodes to adjust the stack pointer. */
static void
add_unwind_adjustsp (offsetT offset)
{
valueT op;
if (offset > 0x200)
{
/* We need at most 5 bytes to hold a 32-bit value in a uleb128. */
char bytes[5];
int n;
valueT o;
/* Long form: 0xb2, uleb128. */
/* This might not fit in a word so add the individual bytes,
remembering the list is built in reverse order. */
o = (valueT) ((offset - 0x204) >> 2);
if (o == 0)
add_unwind_opcode (0, 1);
/* Calculate the uleb128 encoding of the offset. */
n = 0;
while (o)
{
bytes[n] = o & 0x7f;
o >>= 7;
if (o)
bytes[n] |= 0x80;
n++;
}
/* Add the insn. */
for (; n; n--)
add_unwind_opcode (bytes[n - 1], 1);
add_unwind_opcode (0xb2, 1);
}
else if (offset > 0x100)
{
/* Two short opcodes. */
add_unwind_opcode (0x3f, 1);
op = (offset - 0x104) >> 2;
add_unwind_opcode (op, 1);
}
else if (offset > 0)
{
/* Short opcode. */
op = (offset - 4) >> 2;
add_unwind_opcode (op, 1);
}
else if (offset < 0)
{
offset = -offset;
while (offset > 0x100)
{
add_unwind_opcode (0x7f, 1);
offset -= 0x100;
}
op = ((offset - 4) >> 2) | 0x40;
add_unwind_opcode (op, 1);
}
}
/* Finish the list of unwind opcodes for this function. */
static void
finish_unwind_opcodes (void)
{
valueT op;
if (unwind.fp_used)
{
/* Adjust sp as necessary. */
unwind.pending_offset += unwind.fp_offset - unwind.frame_size;
flush_pending_unwind ();
/* After restoring sp from the frame pointer. */
op = 0x90 | unwind.fp_reg;
add_unwind_opcode (op, 1);
}
else
flush_pending_unwind ();
}
/* Start an exception table entry. If idx is nonzero this is an index table
entry. */
static void
start_unwind_section (const segT text_seg, int idx)
{
const char * text_name;
const char * prefix;
const char * prefix_once;
const char * group_name;
size_t prefix_len;
size_t text_len;
char * sec_name;
size_t sec_name_len;
int type;
int flags;
int linkonce;
if (idx)
{
prefix = ELF_STRING_ARM_unwind;
prefix_once = ELF_STRING_ARM_unwind_once;
type = SHT_ARM_EXIDX;
}
else
{
prefix = ELF_STRING_ARM_unwind_info;
prefix_once = ELF_STRING_ARM_unwind_info_once;
type = SHT_PROGBITS;
}
text_name = segment_name (text_seg);
if (streq (text_name, ".text"))
text_name = "";
if (strncmp (text_name, ".gnu.linkonce.t.",
strlen (".gnu.linkonce.t.")) == 0)
{
prefix = prefix_once;
text_name += strlen (".gnu.linkonce.t.");
}
prefix_len = strlen (prefix);
text_len = strlen (text_name);
sec_name_len = prefix_len + text_len;
sec_name = (char *) xmalloc (sec_name_len + 1);
memcpy (sec_name, prefix, prefix_len);
memcpy (sec_name + prefix_len, text_name, text_len);
sec_name[prefix_len + text_len] = '\0';
flags = SHF_ALLOC;
linkonce = 0;
group_name = 0;
/* Handle COMDAT group. */
if (prefix != prefix_once && (text_seg->flags & SEC_LINK_ONCE) != 0)
{
group_name = elf_group_name (text_seg);
if (group_name == NULL)
{
as_bad (_("Group section `%s' has no group signature"),
segment_name (text_seg));
ignore_rest_of_line ();
return;
}
flags |= SHF_GROUP;
linkonce = 1;
}
obj_elf_change_section (sec_name, type, flags, 0, group_name, linkonce, 0);
/* Set the section link for index tables. */
if (idx)
elf_linked_to_section (now_seg) = text_seg;
}
/* Start an unwind table entry. HAVE_DATA is nonzero if we have additional
personality routine data. Returns zero, or the index table value for
an inline entry. */
static valueT
create_unwind_entry (int have_data)
{
int size;
addressT where;
char *ptr;
/* The current word of data. */
valueT data;
/* The number of bytes left in this word. */
int n;
finish_unwind_opcodes ();
/* Remember the current text section. */
unwind.saved_seg = now_seg;
unwind.saved_subseg = now_subseg;
start_unwind_section (now_seg, 0);
if (unwind.personality_routine == NULL)
{
if (unwind.personality_index == -2)
{
if (have_data)
as_bad (_("handlerdata in cantunwind frame"));
return 1; /* EXIDX_CANTUNWIND. */
}
/* Use a default personality routine if none is specified. */
if (unwind.personality_index == -1)
{
if (unwind.opcode_count > 3)
unwind.personality_index = 1;
else
unwind.personality_index = 0;
}
/* Space for the personality routine entry. */
if (unwind.personality_index == 0)
{
if (unwind.opcode_count > 3)
as_bad (_("too many unwind opcodes for personality routine 0"));
if (!have_data)
{
/* All the data is inline in the index table. */
data = 0x80;
n = 3;
while (unwind.opcode_count > 0)
{
unwind.opcode_count--;
data = (data << 8) | unwind.opcodes[unwind.opcode_count];
n--;
}
/* Pad with "finish" opcodes. */
while (n--)
data = (data << 8) | 0xb0;
return data;
}
size = 0;
}
else
/* We get two opcodes "free" in the first word. */
size = unwind.opcode_count - 2;
}
else
{
/* PR 16765: Missing or misplaced unwind directives can trigger this. */
if (unwind.personality_index != -1)
{
as_bad (_("attempt to recreate an unwind entry"));
return 1;
}
/* An extra byte is required for the opcode count. */
size = unwind.opcode_count + 1;
}
size = (size + 3) >> 2;
if (size > 0xff)
as_bad (_("too many unwind opcodes"));
frag_align (2, 0, 0);
record_alignment (now_seg, 2);
unwind.table_entry = expr_build_dot ();
/* Allocate the table entry. */
ptr = frag_more ((size << 2) + 4);
/* PR 13449: Zero the table entries in case some of them are not used. */
memset (ptr, 0, (size << 2) + 4);
where = frag_now_fix () - ((size << 2) + 4);
switch (unwind.personality_index)
{
case -1:
/* ??? Should this be a PLT generating relocation? */
/* Custom personality routine. */
fix_new (frag_now, where, 4, unwind.personality_routine, 0, 1,
BFD_RELOC_ARM_PREL31);
where += 4;
ptr += 4;
/* Set the first byte to the number of additional words. */
data = size > 0 ? size - 1 : 0;
n = 3;
break;
/* ABI defined personality routines. */
case 0:
/* Three opcodes bytes are packed into the first word. */
data = 0x80;
n = 3;
break;
case 1:
case 2:
/* The size and first two opcode bytes go in the first word. */
data = ((0x80 + unwind.personality_index) << 8) | size;
n = 2;
break;
default:
/* Should never happen. */
abort ();
}
/* Pack the opcodes into words (MSB first), reversing the list at the same
time. */
while (unwind.opcode_count > 0)
{
if (n == 0)
{
md_number_to_chars (ptr, data, 4);
ptr += 4;
n = 4;
data = 0;
}
unwind.opcode_count--;
n--;
data = (data << 8) | unwind.opcodes[unwind.opcode_count];
}
/* Finish off the last word. */
if (n < 4)
{
/* Pad with "finish" opcodes. */
while (n--)
data = (data << 8) | 0xb0;
md_number_to_chars (ptr, data, 4);
}
if (!have_data)
{
/* Add an empty descriptor if there is no user-specified data. */
ptr = frag_more (4);
md_number_to_chars (ptr, 0, 4);
}
return 0;
}
/* Initialize the DWARF-2 unwind information for this procedure. */
void
tc_arm_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_arm_regname_to_dw2regnum (char *regname)
{
int reg = arm_reg_parse (®name, REG_TYPE_RN);
if (reg != FAIL)
return reg;
/* PR 16694: Allow VFP registers as well. */
reg = arm_reg_parse (®name, REG_TYPE_VFS);
if (reg != FAIL)
return 64 + reg;
reg = arm_reg_parse (®name, REG_TYPE_VFD);
if (reg != FAIL)
return reg + 256;
return -1;
}
#ifdef TE_PE
void
tc_pe_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
{
expressionS exp;
exp.X_op = O_secrel;
exp.X_add_symbol = symbol;
exp.X_add_number = 0;
emit_expr (&exp, size);
}
#endif
/* MD interface: Symbol and relocation handling. */
/* Return the address within the segment that a PC-relative fixup is
relative to. For ARM, PC-relative fixups applied to instructions
are generally relative to the location of the fixup plus 8 bytes.
Thumb branches are offset by 4, and Thumb loads relative to PC
require special handling. */
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.
For WinCE we skip the bias for externals as well, since this
is how the MS ARM-CE assembler behaves and we want to be compatible. */
if (fixP->fx_pcrel
&& ((fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != seg)
|| (arm_force_relocation (fixP)
#ifdef TE_WINCE
&& !S_IS_EXTERNAL (fixP->fx_addsy)
#endif
)))
base = 0;
switch (fixP->fx_r_type)
{
/* PC relative addressing on the Thumb is slightly odd as the
bottom two bits of the PC are forced to zero for the
calculation. This happens *after* application of the
pipeline offset. However, Thumb adrl already adjusts for
this, so we need not do it again. */
case BFD_RELOC_ARM_THUMB_ADD:
return base & ~3;
case BFD_RELOC_ARM_THUMB_OFFSET:
case BFD_RELOC_ARM_T32_OFFSET_IMM:
case BFD_RELOC_ARM_T32_ADD_PC12:
case BFD_RELOC_ARM_T32_CP_OFF_IMM:
return (base + 4) & ~3;
/* Thumb branches are simply offset by +4. */
case BFD_RELOC_THUMB_PCREL_BRANCH7:
case BFD_RELOC_THUMB_PCREL_BRANCH9:
case BFD_RELOC_THUMB_PCREL_BRANCH12:
case BFD_RELOC_THUMB_PCREL_BRANCH20:
case BFD_RELOC_THUMB_PCREL_BRANCH25:
return base + 4;
case BFD_RELOC_THUMB_PCREL_BRANCH23:
if (fixP->fx_addsy
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& ARM_IS_FUNC (fixP->fx_addsy)
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t))
base = fixP->fx_where + fixP->fx_frag->fr_address;
return base + 4;
/* BLX is like branches above, but forces the low two bits of PC to
zero. */
case BFD_RELOC_THUMB_PCREL_BLX:
if (fixP->fx_addsy
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& THUMB_IS_FUNC (fixP->fx_addsy)
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t))
base = fixP->fx_where + fixP->fx_frag->fr_address;
return (base + 4) & ~3;
/* ARM mode branches are offset by +8. However, the Windows CE
loader expects the relocation not to take this into account. */
case BFD_RELOC_ARM_PCREL_BLX:
if (fixP->fx_addsy
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& ARM_IS_FUNC (fixP->fx_addsy)
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t))
base = fixP->fx_where + fixP->fx_frag->fr_address;
return base + 8;
case BFD_RELOC_ARM_PCREL_CALL:
if (fixP->fx_addsy
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& THUMB_IS_FUNC (fixP->fx_addsy)
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t))
base = fixP->fx_where + fixP->fx_frag->fr_address;
return base + 8;
case BFD_RELOC_ARM_PCREL_BRANCH:
case BFD_RELOC_ARM_PCREL_JUMP:
case BFD_RELOC_ARM_PLT32:
#ifdef TE_WINCE
/* When handling fixups immediately, because we have already
discovered the value of a symbol, or the address of the frag involved
we must account for the offset by +8, as the OS loader will never see the reloc.
see fixup_segment() in write.c
The S_IS_EXTERNAL test handles the case of global symbols.
Those need the calculated base, not just the pipe compensation the linker will need. */
if (fixP->fx_pcrel
&& fixP->fx_addsy != NULL
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& (S_IS_EXTERNAL (fixP->fx_addsy) || !arm_force_relocation (fixP)))
return base + 8;
return base;
#else
return base + 8;
#endif
/* ARM mode loads relative to PC are also offset by +8. Unlike
branches, the Windows CE loader *does* expect the relocation
to take this into account. */
case BFD_RELOC_ARM_OFFSET_IMM:
case BFD_RELOC_ARM_OFFSET_IMM8:
case BFD_RELOC_ARM_HWLITERAL:
case BFD_RELOC_ARM_LITERAL:
case BFD_RELOC_ARM_CP_OFF_IMM:
return base + 8;
/* Other PC-relative relocations are un-offset. */
default:
return base;
}
}
/* 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 NULL;
}
/* Subroutine of md_apply_fix. Check to see if an immediate can be
computed as two separate immediate values, added together. We
already know that this value cannot be computed by just one ARM
instruction. */
static unsigned int
validate_immediate_twopart (unsigned int val,
unsigned int * highpart)
{
unsigned int a;
unsigned int i;
for (i = 0; i < 32; i += 2)
if (((a = rotate_left (val, i)) & 0xff) != 0)
{
if (a & 0xff00)
{
if (a & ~ 0xffff)
continue;
* highpart = (a >> 8) | ((i + 24) << 7);
}
else if (a & 0xff0000)
{
if (a & 0xff000000)
continue;
* highpart = (a >> 16) | ((i + 16) << 7);
}
else
{
gas_assert (a & 0xff000000);
* highpart = (a >> 24) | ((i + 8) << 7);
}
return (a & 0xff) | (i << 7);
}
return FAIL;
}
static int
validate_offset_imm (unsigned int val, int hwse)
{
if ((hwse && val > 255) || val > 4095)
return FAIL;
return val;
}
/* Subroutine of md_apply_fix. Do those data_ops which can take a
negative immediate constant by altering the instruction. A bit of
a hack really.
MOV <-> MVN
AND <-> BIC
ADC <-> SBC
by inverting the second operand, and
ADD <-> SUB
CMP <-> CMN
by negating the second operand. */
static int
negate_data_op (unsigned long * instruction,
unsigned long value)
{
int op, new_inst;
unsigned long negated, inverted;
negated = encode_arm_immediate (-value);
inverted = encode_arm_immediate (~value);
op = (*instruction >> DATA_OP_SHIFT) & 0xf;
switch (op)
{
/* First negates. */
case OPCODE_SUB: /* ADD <-> SUB */
new_inst = OPCODE_ADD;
value = negated;
break;
case OPCODE_ADD:
new_inst = OPCODE_SUB;
value = negated;
break;
case OPCODE_CMP: /* CMP <-> CMN */
new_inst = OPCODE_CMN;
value = negated;
break;
case OPCODE_CMN:
new_inst = OPCODE_CMP;
value = negated;
break;
/* Now Inverted ops. */
case OPCODE_MOV: /* MOV <-> MVN */
new_inst = OPCODE_MVN;
value = inverted;
break;
case OPCODE_MVN:
new_inst = OPCODE_MOV;
value = inverted;
break;
case OPCODE_AND: /* AND <-> BIC */
new_inst = OPCODE_BIC;
value = inverted;
break;
case OPCODE_BIC:
new_inst = OPCODE_AND;
value = inverted;
break;
case OPCODE_ADC: /* ADC <-> SBC */
new_inst = OPCODE_SBC;
value = inverted;
break;
case OPCODE_SBC:
new_inst = OPCODE_ADC;
value = inverted;
break;
/* We cannot do anything. */
default:
return FAIL;
}
if (value == (unsigned) FAIL)
return FAIL;
*instruction &= OPCODE_MASK;
*instruction |= new_inst << DATA_OP_SHIFT;
return value;
}
/* Like negate_data_op, but for Thumb-2. */
static unsigned int
thumb32_negate_data_op (offsetT *instruction, unsigned int value)
{
int op, new_inst;
int rd;
unsigned int negated, inverted;
negated = encode_thumb32_immediate (-value);
inverted = encode_thumb32_immediate (~value);
rd = (*instruction >> 8) & 0xf;
op = (*instruction >> T2_DATA_OP_SHIFT) & 0xf;
switch (op)
{
/* ADD <-> SUB. Includes CMP <-> CMN. */
case T2_OPCODE_SUB:
new_inst = T2_OPCODE_ADD;
value = negated;
break;
case T2_OPCODE_ADD:
new_inst = T2_OPCODE_SUB;
value = negated;
break;
/* ORR <-> ORN. Includes MOV <-> MVN. */
case T2_OPCODE_ORR:
new_inst = T2_OPCODE_ORN;
value = inverted;
break;
case T2_OPCODE_ORN:
new_inst = T2_OPCODE_ORR;
value = inverted;
break;
/* AND <-> BIC. TST has no inverted equivalent. */
case T2_OPCODE_AND:
new_inst = T2_OPCODE_BIC;
if (rd == 15)
value = FAIL;
else
value = inverted;
break;
case T2_OPCODE_BIC:
new_inst = T2_OPCODE_AND;
value = inverted;
break;
/* ADC <-> SBC */
case T2_OPCODE_ADC:
new_inst = T2_OPCODE_SBC;
value = inverted;
break;
case T2_OPCODE_SBC:
new_inst = T2_OPCODE_ADC;
value = inverted;
break;
/* We cannot do anything. */
default:
return FAIL;
}
if (value == (unsigned int)FAIL)
return FAIL;
*instruction &= T2_OPCODE_MASK;
*instruction |= new_inst << T2_DATA_OP_SHIFT;
return value;
}
/* Read a 32-bit thumb instruction from buf. */
static unsigned long
get_thumb32_insn (char * buf)
{
unsigned long insn;
insn = md_chars_to_number (buf, THUMB_SIZE) << 16;
insn |= md_chars_to_number (buf + THUMB_SIZE, THUMB_SIZE);
return insn;
}
/* We usually want to set the low bit on the address of thumb function
symbols. In particular .word foo - . should have the low bit set.
Generic code tries to fold the difference of two symbols to
a constant. Prevent this and force a relocation when the first symbols
is a thumb function. */
bfd_boolean
arm_optimize_expr (expressionS *l, operatorT op, expressionS *r)
{
if (op == O_subtract
&& l->X_op == O_symbol
&& r->X_op == O_symbol
&& THUMB_IS_FUNC (l->X_add_symbol))
{
l->X_op = O_subtract;
l->X_op_symbol = r->X_add_symbol;
l->X_add_number -= r->X_add_number;
return TRUE;
}
/* Process as normal. */
return FALSE;
}
/* Encode Thumb2 unconditional branches and calls. The encoding
for the 2 are identical for the immediate values. */
static void
encode_thumb2_b_bl_offset (char * buf, offsetT value)
{
#define T2I1I2MASK ((1 << 13) | (1 << 11))
offsetT newval;
offsetT newval2;
addressT S, I1, I2, lo, hi;
S = (value >> 24) & 0x01;
I1 = (value >> 23) & 0x01;
I2 = (value >> 22) & 0x01;
hi = (value >> 12) & 0x3ff;
lo = (value >> 1) & 0x7ff;
newval = md_chars_to_number (buf, THUMB_SIZE);
newval2 = md_chars_to_number (buf + THUMB_SIZE, THUMB_SIZE);
newval |= (S << 10) | hi;
newval2 &= ~T2I1I2MASK;
newval2 |= (((I1 ^ S) << 13) | ((I2 ^ S) << 11) | lo) ^ T2I1I2MASK;
md_number_to_chars (buf, newval, THUMB_SIZE);
md_number_to_chars (buf + THUMB_SIZE, newval2, THUMB_SIZE);
}
void
md_apply_fix (fixS * fixP,
valueT * valP,
segT seg)
{
offsetT value = * valP;
offsetT newval;
unsigned int newimm;
unsigned long temp;
int sign;
char * buf = fixP->fx_where + fixP->fx_frag->fr_literal;
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;
/* On a 64-bit host, silently truncate 'value' to 32 bits for
consistency with the behaviour on 32-bit hosts. Remember value
for emit_reloc. */
value &= 0xffffffff;
value ^= 0x80000000;
value -= 0x80000000;
*valP = value;
fixP->fx_addnumber = value;
/* Same treatment for fixP->fx_offset. */
fixP->fx_offset &= 0xffffffff;
fixP->fx_offset ^= 0x80000000;
fixP->fx_offset -= 0x80000000;
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_ARM_IMMEDIATE:
/* We claim that this fixup has been processed here,
even if in fact we generate an error because we do
not have a reloc for it, so tc_gen_reloc will reject it. */
fixP->fx_done = 1;
if (fixP->fx_addsy)
{
const char *msg = 0;
if (! S_IS_DEFINED (fixP->fx_addsy))
msg = _("undefined symbol %s used as an immediate value");
else if (S_GET_SEGMENT (fixP->fx_addsy) != seg)
msg = _("symbol %s is in a different section");
else if (S_IS_WEAK (fixP->fx_addsy))
msg = _("symbol %s is weak and may be overridden later");
if (msg)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
msg, S_GET_NAME (fixP->fx_addsy));
break;
}
}
temp = md_chars_to_number (buf, INSN_SIZE);
/* If the offset is negative, we should use encoding A2 for ADR. */
if ((temp & 0xfff0000) == 0x28f0000 && value < 0)
newimm = negate_data_op (&temp, value);
else
{
newimm = encode_arm_immediate (value);
/* If the instruction will fail, see if we can fix things up by
changing the opcode. */
if (newimm == (unsigned int) FAIL)
newimm = negate_data_op (&temp, value);
}
if (newimm == (unsigned int) FAIL)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid constant (%lx) after fixup"),
(unsigned long) value);
break;
}
newimm |= (temp & 0xfffff000);
md_number_to_chars (buf, (valueT) newimm, INSN_SIZE);
break;
case BFD_RELOC_ARM_ADRL_IMMEDIATE:
{
unsigned int highpart = 0;
unsigned int newinsn = 0xe1a00000; /* nop. */
if (fixP->fx_addsy)
{
const char *msg = 0;
if (! S_IS_DEFINED (fixP->fx_addsy))
msg = _("undefined symbol %s used as an immediate value");
else if (S_GET_SEGMENT (fixP->fx_addsy) != seg)
msg = _("symbol %s is in a different section");
else if (S_IS_WEAK (fixP->fx_addsy))
msg = _("symbol %s is weak and may be overridden later");
if (msg)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
msg, S_GET_NAME (fixP->fx_addsy));
break;
}
}
newimm = encode_arm_immediate (value);
temp = md_chars_to_number (buf, INSN_SIZE);
/* If the instruction will fail, see if we can fix things up by
changing the opcode. */
if (newimm == (unsigned int) FAIL
&& (newimm = negate_data_op (& temp, value)) == (unsigned int) FAIL)
{
/* No ? OK - try using two ADD instructions to generate
the value. */
newimm = validate_immediate_twopart (value, & highpart);
/* Yes - then make sure that the second instruction is
also an add. */
if (newimm != (unsigned int) FAIL)
newinsn = temp;
/* Still No ? Try using a negated value. */
else if ((newimm = validate_immediate_twopart (- value, & highpart)) != (unsigned int) FAIL)
temp = newinsn = (temp & OPCODE_MASK) | OPCODE_SUB << DATA_OP_SHIFT;
/* Otherwise - give up. */
else
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("unable to compute ADRL instructions for PC offset of 0x%lx"),
(long) value);
break;
}
/* Replace the first operand in the 2nd instruction (which
is the PC) with the destination register. We have
already added in the PC in the first instruction and we
do not want to do it again. */
newinsn &= ~ 0xf0000;
newinsn |= ((newinsn & 0x0f000) << 4);
}
newimm |= (temp & 0xfffff000);
md_number_to_chars (buf, (valueT) newimm, INSN_SIZE);
highpart |= (newinsn & 0xfffff000);
md_number_to_chars (buf + INSN_SIZE, (valueT) highpart, INSN_SIZE);
}
break;
case BFD_RELOC_ARM_OFFSET_IMM:
if (!fixP->fx_done && seg->use_rela_p)
value = 0;
case BFD_RELOC_ARM_LITERAL:
sign = value > 0;
if (value < 0)
value = - value;
if (validate_offset_imm (value, 0) == FAIL)
{
if (fixP->fx_r_type == BFD_RELOC_ARM_LITERAL)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid literal constant: pool needs to be closer"));
else
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad immediate value for offset (%ld)"),
(long) value);
break;
}
newval = md_chars_to_number (buf, INSN_SIZE);
if (value == 0)
newval &= 0xfffff000;
else
{
newval &= 0xff7ff000;
newval |= value | (sign ? INDEX_UP : 0);
}
md_number_to_chars (buf, newval, INSN_SIZE);
break;
case BFD_RELOC_ARM_OFFSET_IMM8:
case BFD_RELOC_ARM_HWLITERAL:
sign = value > 0;
if (value < 0)
value = - value;
if (validate_offset_imm (value, 1) == FAIL)
{
if (fixP->fx_r_type == BFD_RELOC_ARM_HWLITERAL)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid literal constant: pool needs to be closer"));
else
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad immediate value for 8-bit offset (%ld)"),
(long) value);
break;
}
newval = md_chars_to_number (buf, INSN_SIZE);
if (value == 0)
newval &= 0xfffff0f0;
else
{
newval &= 0xff7ff0f0;
newval |= ((value >> 4) << 8) | (value & 0xf) | (sign ? INDEX_UP : 0);
}
md_number_to_chars (buf, newval, INSN_SIZE);
break;
case BFD_RELOC_ARM_T32_OFFSET_U8:
if (value < 0 || value > 1020 || value % 4 != 0)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad immediate value for offset (%ld)"), (long) value);
value /= 4;
newval = md_chars_to_number (buf+2, THUMB_SIZE);
newval |= value;
md_number_to_chars (buf+2, newval, THUMB_SIZE);
break;
case BFD_RELOC_ARM_T32_OFFSET_IMM:
/* This is a complicated relocation used for all varieties of Thumb32
load/store instruction with immediate offset:
1110 100P u1WL NNNN XXXX YYYY iiii iiii - +/-(U) pre/post(P) 8-bit,
*4, optional writeback(W)
(doubleword load/store)
1111 100S uTTL 1111 XXXX iiii iiii iiii - +/-(U) 12-bit PC-rel
1111 100S 0TTL NNNN XXXX 1Pu1 iiii iiii - +/-(U) pre/post(P) 8-bit
1111 100S 0TTL NNNN XXXX 1110 iiii iiii - positive 8-bit (T instruction)
1111 100S 1TTL NNNN XXXX iiii iiii iiii - positive 12-bit
1111 100S 0TTL NNNN XXXX 1100 iiii iiii - negative 8-bit
Uppercase letters indicate bits that are already encoded at
this point. Lowercase letters are our problem. For the
second block of instructions, the secondary opcode nybble
(bits 8..11) is present, and bit 23 is zero, even if this is
a PC-relative operation. */
newval = md_chars_to_number (buf, THUMB_SIZE);
newval <<= 16;
newval |= md_chars_to_number (buf+THUMB_SIZE, THUMB_SIZE);
if ((newval & 0xf0000000) == 0xe0000000)
{
/* Doubleword load/store: 8-bit offset, scaled by 4. */
if (value >= 0)
newval |= (1 << 23);
else
value = -value;
if (value % 4 != 0)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset not a multiple of 4"));
break;
}
value /= 4;
if (value > 0xff)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
break;
}
newval &= ~0xff;
}
else if ((newval & 0x000f0000) == 0x000f0000)
{
/* PC-relative, 12-bit offset. */
if (value >= 0)
newval |= (1 << 23);
else
value = -value;
if (value > 0xfff)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
break;
}
newval &= ~0xfff;
}
else if ((newval & 0x00000100) == 0x00000100)
{
/* Writeback: 8-bit, +/- offset. */
if (value >= 0)
newval |= (1 << 9);
else
value = -value;
if (value > 0xff)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
break;
}
newval &= ~0xff;
}
else if ((newval & 0x00000f00) == 0x00000e00)
{
/* T-instruction: positive 8-bit offset. */
if (value < 0 || value > 0xff)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
break;
}
newval &= ~0xff;
newval |= value;
}
else
{
/* Positive 12-bit or negative 8-bit offset. */
int limit;
if (value >= 0)
{
newval |= (1 << 23);
limit = 0xfff;
}
else
{
value = -value;
limit = 0xff;
}
if (value > limit)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
break;
}
newval &= ~limit;
}
newval |= value;
md_number_to_chars (buf, (newval >> 16) & 0xffff, THUMB_SIZE);
md_number_to_chars (buf + THUMB_SIZE, newval & 0xffff, THUMB_SIZE);
break;
case BFD_RELOC_ARM_SHIFT_IMM:
newval = md_chars_to_number (buf, INSN_SIZE);
if (((unsigned long) value) > 32
|| (value == 32
&& (((newval & 0x60) == 0) || (newval & 0x60) == 0x60)))
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("shift expression is too large"));
break;
}
if (value == 0)
/* Shifts of zero must be done as lsl. */
newval &= ~0x60;
else if (value == 32)
value = 0;
newval &= 0xfffff07f;
newval |= (value & 0x1f) << 7;
md_number_to_chars (buf, newval, INSN_SIZE);
break;
case BFD_RELOC_ARM_T32_IMMEDIATE:
case BFD_RELOC_ARM_T32_ADD_IMM:
case BFD_RELOC_ARM_T32_IMM12:
case BFD_RELOC_ARM_T32_ADD_PC12:
/* We claim that this fixup has been processed here,
even if in fact we generate an error because we do
not have a reloc for it, so tc_gen_reloc will reject it. */
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));
break;
}
newval = md_chars_to_number (buf, THUMB_SIZE);
newval <<= 16;
newval |= md_chars_to_number (buf+2, THUMB_SIZE);
newimm = FAIL;
if (fixP->fx_r_type == BFD_RELOC_ARM_T32_IMMEDIATE
|| fixP->fx_r_type == BFD_RELOC_ARM_T32_ADD_IMM)
{
newimm = encode_thumb32_immediate (value);
if (newimm == (unsigned int) FAIL)
newimm = thumb32_negate_data_op (&newval, value);
}
if (fixP->fx_r_type != BFD_RELOC_ARM_T32_IMMEDIATE
&& newimm == (unsigned int) FAIL)
{
/* Turn add/sum into addw/subw. */
if (fixP->fx_r_type == BFD_RELOC_ARM_T32_ADD_IMM)
newval = (newval & 0xfeffffff) | 0x02000000;
/* No flat 12-bit imm encoding for addsw/subsw. */
if ((newval & 0x00100000) == 0)
{
/* 12 bit immediate for addw/subw. */
if (value < 0)
{
value = -value;
newval ^= 0x00a00000;
}
if (value > 0xfff)
newimm = (unsigned int) FAIL;
else
newimm = value;
}
}
if (newimm == (unsigned int)FAIL)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid constant (%lx) after fixup"),
(unsigned long) value);
break;
}
newval |= (newimm & 0x800) << 15;
newval |= (newimm & 0x700) << 4;
newval |= (newimm & 0x0ff);
md_number_to_chars (buf, (valueT) ((newval >> 16) & 0xffff), THUMB_SIZE);
md_number_to_chars (buf+2, (valueT) (newval & 0xffff), THUMB_SIZE);
break;
case BFD_RELOC_ARM_SMC:
if (((unsigned long) value) > 0xffff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid smc expression"));
newval = md_chars_to_number (buf, INSN_SIZE);
newval |= (value & 0xf) | ((value & 0xfff0) << 4);
md_number_to_chars (buf, newval, INSN_SIZE);
break;
case BFD_RELOC_ARM_HVC:
if (((unsigned long) value) > 0xffff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid hvc expression"));
newval = md_chars_to_number (buf, INSN_SIZE);
newval |= (value & 0xf) | ((value & 0xfff0) << 4);
md_number_to_chars (buf, newval, INSN_SIZE);
break;
case BFD_RELOC_ARM_SWI:
if (fixP->tc_fix_data != 0)
{
if (((unsigned long) value) > 0xff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid swi expression"));
newval = md_chars_to_number (buf, THUMB_SIZE);
newval |= value;
md_number_to_chars (buf, newval, THUMB_SIZE);
}
else
{
if (((unsigned long) value) > 0x00ffffff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid swi expression"));
newval = md_chars_to_number (buf, INSN_SIZE);
newval |= value;
md_number_to_chars (buf, newval, INSN_SIZE);
}
break;
case BFD_RELOC_ARM_MULTI:
if (((unsigned long) value) > 0xffff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid expression in load/store multiple"));
newval = value | md_chars_to_number (buf, INSN_SIZE);
md_number_to_chars (buf, newval, INSN_SIZE);
break;
#ifdef OBJ_ELF
case BFD_RELOC_ARM_PCREL_CALL:
if (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t)
&& fixP->fx_addsy
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& THUMB_IS_FUNC (fixP->fx_addsy))
/* Flip the bl to blx. This is a simple flip
bit here because we generate PCREL_CALL for
unconditional bls. */
{
newval = md_chars_to_number (buf, INSN_SIZE);
newval = newval | 0x10000000;
md_number_to_chars (buf, newval, INSN_SIZE);
temp = 1;
fixP->fx_done = 1;
}
else
temp = 3;
goto arm_branch_common;
case BFD_RELOC_ARM_PCREL_JUMP:
if (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t)
&& fixP->fx_addsy
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& THUMB_IS_FUNC (fixP->fx_addsy))
{
/* This would map to a bl<cond>, b<cond>,
b<always> to a Thumb function. We
need to force a relocation for this particular
case. */
newval = md_chars_to_number (buf, INSN_SIZE);
fixP->fx_done = 0;
}
case BFD_RELOC_ARM_PLT32:
#endif
case BFD_RELOC_ARM_PCREL_BRANCH:
temp = 3;
goto arm_branch_common;
case BFD_RELOC_ARM_PCREL_BLX:
temp = 1;
if (ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t)
&& fixP->fx_addsy
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& ARM_IS_FUNC (fixP->fx_addsy))
{
/* Flip the blx to a bl and warn. */
const char *name = S_GET_NAME (fixP->fx_addsy);
newval = 0xeb000000;
as_warn_where (fixP->fx_file, fixP->fx_line,
_("blx to '%s' an ARM ISA state function changed to bl"),
name);
md_number_to_chars (buf, newval, INSN_SIZE);
temp = 3;
fixP->fx_done = 1;
}
#ifdef OBJ_ELF
if (EF_ARM_EABI_VERSION (meabi_flags) >= EF_ARM_EABI_VER4)
fixP->fx_r_type = BFD_RELOC_ARM_PCREL_CALL;
#endif
arm_branch_common:
/* We are going to store value (shifted right by two) in the
instruction, in a 24 bit, signed field. Bits 26 through 32 either
all clear or all set and bit 0 must be clear. For B/BL bit 1 must
also be be clear. */
if (value & temp)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("misaligned branch destination"));
if ((value & (offsetT)0xfe000000) != (offsetT)0
&& (value & (offsetT)0xfe000000) != (offsetT)0xfe000000)
as_bad_where (fixP->fx_file, fixP->fx_line, BAD_RANGE);
if (fixP->fx_done || !seg->use_rela_p)
{
newval = md_chars_to_number (buf, INSN_SIZE);
newval |= (value >> 2) & 0x00ffffff;
/* Set the H bit on BLX instructions. */
if (temp == 1)
{
if (value & 2)
newval |= 0x01000000;
else
newval &= ~0x01000000;
}
md_number_to_chars (buf, newval, INSN_SIZE);
}
break;
case BFD_RELOC_THUMB_PCREL_BRANCH7: /* CBZ */
/* CBZ can only branch forward. */
/* Attempts to use CBZ to branch to the next instruction
(which, strictly speaking, are prohibited) will be turned into
no-ops.
FIXME: It may be better to remove the instruction completely and
perform relaxation. */
if (value == -2)
{
newval = md_chars_to_number (buf, THUMB_SIZE);
newval = 0xbf00; /* NOP encoding T1 */
md_number_to_chars (buf, newval, THUMB_SIZE);
}
else
{
if (value & ~0x7e)
as_bad_where (fixP->fx_file, fixP->fx_line, BAD_RANGE);
if (fixP->fx_done || !seg->use_rela_p)
{
newval = md_chars_to_number (buf, THUMB_SIZE);
newval |= ((value & 0x3e) << 2) | ((value & 0x40) << 3);
md_number_to_chars (buf, newval, THUMB_SIZE);
}
}
break;
case BFD_RELOC_THUMB_PCREL_BRANCH9: /* Conditional branch. */
if ((value & ~0xff) && ((value & ~0xff) != ~0xff))
as_bad_where (fixP->fx_file, fixP->fx_line, BAD_RANGE);
if (fixP->fx_done || !seg->use_rela_p)
{
newval = md_chars_to_number (buf, THUMB_SIZE);
newval |= (value & 0x1ff) >> 1;
md_number_to_chars (buf, newval, THUMB_SIZE);
}
break;
case BFD_RELOC_THUMB_PCREL_BRANCH12: /* Unconditional branch. */
if ((value & ~0x7ff) && ((value & ~0x7ff) != ~0x7ff))
as_bad_where (fixP->fx_file, fixP->fx_line, BAD_RANGE);
if (fixP->fx_done || !seg->use_rela_p)
{
newval = md_chars_to_number (buf, THUMB_SIZE);
newval |= (value & 0xfff) >> 1;
md_number_to_chars (buf, newval, THUMB_SIZE);
}
break;
case BFD_RELOC_THUMB_PCREL_BRANCH20:
if (fixP->fx_addsy
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& ARM_IS_FUNC (fixP->fx_addsy)
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t))
{
/* Force a relocation for a branch 20 bits wide. */
fixP->fx_done = 0;
}
if ((value & ~0x1fffff) && ((value & ~0x0fffff) != ~0x0fffff))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("conditional branch out of range"));
if (fixP->fx_done || !seg->use_rela_p)
{
offsetT newval2;
addressT S, J1, J2, lo, hi;
S = (value & 0x00100000) >> 20;
J2 = (value & 0x00080000) >> 19;
J1 = (value & 0x00040000) >> 18;
hi = (value & 0x0003f000) >> 12;
lo = (value & 0x00000ffe) >> 1;
newval = md_chars_to_number (buf, THUMB_SIZE);
newval2 = md_chars_to_number (buf + THUMB_SIZE, THUMB_SIZE);
newval |= (S << 10) | hi;
newval2 |= (J1 << 13) | (J2 << 11) | lo;
md_number_to_chars (buf, newval, THUMB_SIZE);
md_number_to_chars (buf + THUMB_SIZE, newval2, THUMB_SIZE);
}
break;
case BFD_RELOC_THUMB_PCREL_BLX:
/* If there is a blx from a thumb state function to
another thumb function flip this to a bl and warn
about it. */
if (fixP->fx_addsy
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& THUMB_IS_FUNC (fixP->fx_addsy))
{
const char *name = S_GET_NAME (fixP->fx_addsy);
as_warn_where (fixP->fx_file, fixP->fx_line,
_("blx to Thumb func '%s' from Thumb ISA state changed to bl"),
name);
newval = md_chars_to_number (buf + THUMB_SIZE, THUMB_SIZE);
newval = newval | 0x1000;
md_number_to_chars (buf+THUMB_SIZE, newval, THUMB_SIZE);
fixP->fx_r_type = BFD_RELOC_THUMB_PCREL_BRANCH23;
fixP->fx_done = 1;
}
goto thumb_bl_common;
case BFD_RELOC_THUMB_PCREL_BRANCH23:
/* A bl from Thumb state ISA to an internal ARM state function
is converted to a blx. */
if (fixP->fx_addsy
&& (S_GET_SEGMENT (fixP->fx_addsy) == seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
&& ARM_IS_FUNC (fixP->fx_addsy)
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t))
{
newval = md_chars_to_number (buf + THUMB_SIZE, THUMB_SIZE);
newval = newval & ~0x1000;
md_number_to_chars (buf+THUMB_SIZE, newval, THUMB_SIZE);
fixP->fx_r_type = BFD_RELOC_THUMB_PCREL_BLX;
fixP->fx_done = 1;
}
thumb_bl_common:
if (fixP->fx_r_type == BFD_RELOC_THUMB_PCREL_BLX)
/* For a BLX instruction, make sure that the relocation is rounded up
to a word boundary. This follows the semantics of the instruction
which specifies that bit 1 of the target address will come from bit
1 of the base address. */
value = (value + 3) & ~ 3;
#ifdef OBJ_ELF
if (EF_ARM_EABI_VERSION (meabi_flags) >= EF_ARM_EABI_VER4
&& fixP->fx_r_type == BFD_RELOC_THUMB_PCREL_BLX)
fixP->fx_r_type = BFD_RELOC_THUMB_PCREL_BRANCH23;
#endif
if ((value & ~0x3fffff) && ((value & ~0x3fffff) != ~0x3fffff))
{
if (!(ARM_CPU_HAS_FEATURE (cpu_variant, arm_arch_t2)))
as_bad_where (fixP->fx_file, fixP->fx_line, BAD_RANGE);
else if ((value & ~0x1ffffff)
&& ((value & ~0x1ffffff) != ~0x1ffffff))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("Thumb2 branch out of range"));
}
if (fixP->fx_done || !seg->use_rela_p)
encode_thumb2_b_bl_offset (buf, value);
break;
case BFD_RELOC_THUMB_PCREL_BRANCH25:
if ((value & ~0x0ffffff) && ((value & ~0x0ffffff) != ~0x0ffffff))
as_bad_where (fixP->fx_file, fixP->fx_line, BAD_RANGE);
if (fixP->fx_done || !seg->use_rela_p)
encode_thumb2_b_bl_offset (buf, value);
break;
case BFD_RELOC_8:
if (fixP->fx_done || !seg->use_rela_p)
*buf = value;
break;
case BFD_RELOC_16:
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, value, 2);
break;
#ifdef OBJ_ELF
case BFD_RELOC_ARM_TLS_CALL:
case BFD_RELOC_ARM_THM_TLS_CALL:
case BFD_RELOC_ARM_TLS_DESCSEQ:
case BFD_RELOC_ARM_THM_TLS_DESCSEQ:
case BFD_RELOC_ARM_TLS_GOTDESC:
case BFD_RELOC_ARM_TLS_GD32:
case BFD_RELOC_ARM_TLS_LE32:
case BFD_RELOC_ARM_TLS_IE32:
case BFD_RELOC_ARM_TLS_LDM32:
case BFD_RELOC_ARM_TLS_LDO32:
S_SET_THREAD_LOCAL (fixP->fx_addsy);
break;
case BFD_RELOC_ARM_GOT32:
case BFD_RELOC_ARM_GOTOFF:
break;
case BFD_RELOC_ARM_GOT_PREL:
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, value, 4);
break;
case BFD_RELOC_ARM_TARGET2:
/* TARGET2 is not partial-inplace, so we need to write the
addend here for REL targets, because it won't be written out
during reloc processing later. */
if (fixP->fx_done || !seg->use_rela_p)
md_number_to_chars (buf, fixP->fx_offset, 4);
break;
#endif
case BFD_RELOC_RVA:
case BFD_RELOC_32:
case BFD_RELOC_ARM_TARGET1:
case BFD_RELOC_ARM_ROSEGREL32:
case BFD_RELOC_ARM_SBREL32:
case BFD_RELOC_32_PCREL:
#ifdef TE_PE
case BFD_RELOC_32_SECREL:
#endif
if (fixP->fx_done || !seg->use_rela_p)
#ifdef TE_WINCE
/* For WinCE we only do this for pcrel fixups. */
if (fixP->fx_done || fixP->fx_pcrel)
#endif
md_number_to_chars (buf, value, 4);
break;
#ifdef OBJ_ELF
case BFD_RELOC_ARM_PREL31:
if (fixP->fx_done || !seg->use_rela_p)
{
newval = md_chars_to_number (buf, 4) & 0x80000000;
if ((value ^ (value >> 1)) & 0x40000000)
{
as_bad_where (fixP->fx_file, fixP->fx_line,
_("rel31 relocation overflow"));
}
newval |= value & 0x7fffffff;
md_number_to_chars (buf, newval, 4);
}
break;
#endif
case BFD_RELOC_ARM_CP_OFF_IMM:
case BFD_RELOC_ARM_T32_CP_OFF_IMM:
if (value < -1023 || value > 1023 || (value & 3))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("co-processor offset out of range"));
cp_off_common:
sign = value > 0;
if (value < 0)
value = -value;
if (fixP->fx_r_type == BFD_RELOC_ARM_CP_OFF_IMM
|| fixP->fx_r_type == BFD_RELOC_ARM_CP_OFF_IMM_S2)
newval = md_chars_to_number (buf, INSN_SIZE);
else
newval = get_thumb32_insn (buf);
if (value == 0)
newval &= 0xffffff00;
else
{
newval &= 0xff7fff00;
newval |= (value >> 2) | (sign ? INDEX_UP : 0);
}
if (fixP->fx_r_type == BFD_RELOC_ARM_CP_OFF_IMM
|| fixP->fx_r_type == BFD_RELOC_ARM_CP_OFF_IMM_S2)
md_number_to_chars (buf, newval, INSN_SIZE);
else
put_thumb32_insn (buf, newval);
break;
case BFD_RELOC_ARM_CP_OFF_IMM_S2:
case BFD_RELOC_ARM_T32_CP_OFF_IMM_S2:
if (value < -255 || value > 255)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("co-processor offset out of range"));
value *= 4;
goto cp_off_common;
case BFD_RELOC_ARM_THUMB_OFFSET:
newval = md_chars_to_number (buf, THUMB_SIZE);
/* Exactly what ranges, and where the offset is inserted depends
on the type of instruction, we can establish this from the
top 4 bits. */
switch (newval >> 12)
{
case 4: /* PC load. */
/* Thumb PC loads are somewhat odd, bit 1 of the PC is
forced to zero for these loads; md_pcrel_from has already
compensated for this. */
if (value & 3)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid offset, target not word aligned (0x%08lX)"),
(((unsigned long) fixP->fx_frag->fr_address
+ (unsigned long) fixP->fx_where) & ~3)
+ (unsigned long) value);
if (value & ~0x3fc)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid offset, value too big (0x%08lX)"),
(long) value);
newval |= value >> 2;
break;
case 9: /* SP load/store. */
if (value & ~0x3fc)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid offset, value too big (0x%08lX)"),
(long) value);
newval |= value >> 2;
break;
case 6: /* Word load/store. */
if (value & ~0x7c)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid offset, value too big (0x%08lX)"),
(long) value);
newval |= value << 4; /* 6 - 2. */
break;
case 7: /* Byte load/store. */
if (value & ~0x1f)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid offset, value too big (0x%08lX)"),
(long) value);
newval |= value << 6;
break;
case 8: /* Halfword load/store. */
if (value & ~0x3e)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid offset, value too big (0x%08lX)"),
(long) value);
newval |= value << 5; /* 6 - 1. */
break;
default:
as_bad_where (fixP->fx_file, fixP->fx_line,
"Unable to process relocation for thumb opcode: %lx",
(unsigned long) newval);
break;
}
md_number_to_chars (buf, newval, THUMB_SIZE);
break;
case BFD_RELOC_ARM_THUMB_ADD:
/* This is a complicated relocation, since we use it for all of
the following immediate relocations:
3bit ADD/SUB
8bit ADD/SUB
9bit ADD/SUB SP word-aligned
10bit ADD PC/SP word-aligned
The type of instruction being processed is encoded in the
instruction field:
0x8000 SUB
0x00F0 Rd
0x000F Rs
*/
newval = md_chars_to_number (buf, THUMB_SIZE);
{
int rd = (newval >> 4) & 0xf;
int rs = newval & 0xf;
int subtract = !!(newval & 0x8000);
/* Check for HI regs, only very restricted cases allowed:
Adjusting SP, and using PC or SP to get an address. */
if ((rd > 7 && (rd != REG_SP || rs != REG_SP))
|| (rs > 7 && rs != REG_SP && rs != REG_PC))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid Hi register with immediate"));
/* If value is negative, choose the opposite instruction. */
if (value < 0)
{
value = -value;
subtract = !subtract;
if (value < 0)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate value out of range"));
}
if (rd == REG_SP)
{
if (value & ~0x1fc)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid immediate for stack address calculation"));
newval = subtract ? T_OPCODE_SUB_ST : T_OPCODE_ADD_ST;
newval |= value >> 2;
}
else if (rs == REG_PC || rs == REG_SP)
{
if (subtract || value & ~0x3fc)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid immediate for address calculation (value = 0x%08lX)"),
(unsigned long) value);
newval = (rs == REG_PC ? T_OPCODE_ADD_PC : T_OPCODE_ADD_SP);
newval |= rd << 8;
newval |= value >> 2;
}
else if (rs == rd)
{
if (value & ~0xff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate value out of range"));
newval = subtract ? T_OPCODE_SUB_I8 : T_OPCODE_ADD_I8;
newval |= (rd << 8) | value;
}
else
{
if (value & ~0x7)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("immediate value out of range"));
newval = subtract ? T_OPCODE_SUB_I3 : T_OPCODE_ADD_I3;
newval |= rd | (rs << 3) | (value << 6);
}
}
md_number_to_chars (buf, newval, THUMB_SIZE);
break;
case BFD_RELOC_ARM_THUMB_IMM:
newval = md_chars_to_number (buf, THUMB_SIZE);
if (value < 0 || value > 255)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid immediate: %ld is out of range"),
(long) value);
newval |= value;
md_number_to_chars (buf, newval, THUMB_SIZE);
break;
case BFD_RELOC_ARM_THUMB_SHIFT:
/* 5bit shift value (0..32). LSL cannot take 32. */
newval = md_chars_to_number (buf, THUMB_SIZE) & 0xf83f;
temp = newval & 0xf800;
if (value < 0 || value > 32 || (value == 32 && temp == T_OPCODE_LSL_I))
as_bad_where (fixP->fx_file, fixP->fx_line,
_("invalid shift value: %ld"), (long) value);
/* Shifts of zero must be encoded as LSL. */
if (value == 0)
newval = (newval & 0x003f) | T_OPCODE_LSL_I;
/* Shifts of 32 are encoded as zero. */
else if (value == 32)
value = 0;
newval |= value << 6;
md_number_to_chars (buf, newval, THUMB_SIZE);
break;
case BFD_RELOC_VTABLE_INHERIT:
case BFD_RELOC_VTABLE_ENTRY:
fixP->fx_done = 0;
return;
case BFD_RELOC_ARM_MOVW:
case BFD_RELOC_ARM_MOVT:
case BFD_RELOC_ARM_THUMB_MOVW:
case BFD_RELOC_ARM_THUMB_MOVT:
if (fixP->fx_done || !seg->use_rela_p)
{
/* REL format relocations are limited to a 16-bit addend. */
if (!fixP->fx_done)
{
if (value < -0x8000 || value > 0x7fff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("offset out of range"));
}
else if (fixP->fx_r_type == BFD_RELOC_ARM_MOVT
|| fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVT)
{
value >>= 16;
}
if (fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVW
|| fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVT)
{
newval = get_thumb32_insn (buf);
newval &= 0xfbf08f00;
newval |= (value & 0xf000) << 4;
newval |= (value & 0x0800) << 15;
newval |= (value & 0x0700) << 4;
newval |= (value & 0x00ff);
put_thumb32_insn (buf, newval);
}
else
{
newval = md_chars_to_number (buf, 4);
newval &= 0xfff0f000;
newval |= value & 0x0fff;
newval |= (value & 0xf000) << 4;
md_number_to_chars (buf, newval, 4);
}
}
return;
case BFD_RELOC_ARM_ALU_PC_G0_NC:
case BFD_RELOC_ARM_ALU_PC_G0:
case BFD_RELOC_ARM_ALU_PC_G1_NC:
case BFD_RELOC_ARM_ALU_PC_G1:
case BFD_RELOC_ARM_ALU_PC_G2:
case BFD_RELOC_ARM_ALU_SB_G0_NC:
case BFD_RELOC_ARM_ALU_SB_G0:
case BFD_RELOC_ARM_ALU_SB_G1_NC:
case BFD_RELOC_ARM_ALU_SB_G1:
case BFD_RELOC_ARM_ALU_SB_G2:
gas_assert (!fixP->fx_done);
if (!seg->use_rela_p)
{
bfd_vma insn;
bfd_vma encoded_addend;
bfd_vma addend_abs = abs (value);
/* Check that the absolute value of the addend can be
expressed as an 8-bit constant plus a rotation. */
encoded_addend = encode_arm_immediate (addend_abs);
if (encoded_addend == (unsigned int) FAIL)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("the offset 0x%08lX is not representable"),
(unsigned long) addend_abs);
/* Extract the instruction. */
insn = md_chars_to_number (buf, INSN_SIZE);
/* If the addend is positive, use an ADD instruction.
Otherwise use a SUB. Take care not to destroy the S bit. */
insn &= 0xff1fffff;
if (value < 0)
insn |= 1 << 22;
else
insn |= 1 << 23;
/* Place the encoded addend into the first 12 bits of the
instruction. */
insn &= 0xfffff000;
insn |= encoded_addend;
/* Update the instruction. */
md_number_to_chars (buf, insn, INSN_SIZE);
}
break;
case BFD_RELOC_ARM_LDR_PC_G0:
case BFD_RELOC_ARM_LDR_PC_G1:
case BFD_RELOC_ARM_LDR_PC_G2:
case BFD_RELOC_ARM_LDR_SB_G0:
case BFD_RELOC_ARM_LDR_SB_G1:
case BFD_RELOC_ARM_LDR_SB_G2:
gas_assert (!fixP->fx_done);
if (!seg->use_rela_p)
{
bfd_vma insn;
bfd_vma addend_abs = abs (value);
/* Check that the absolute value of the addend can be
encoded in 12 bits. */
if (addend_abs >= 0x1000)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad offset 0x%08lX (only 12 bits available for the magnitude)"),
(unsigned long) addend_abs);
/* Extract the instruction. */
insn = md_chars_to_number (buf, INSN_SIZE);
/* If the addend is negative, clear bit 23 of the instruction.
Otherwise set it. */
if (value < 0)
insn &= ~(1 << 23);
else
insn |= 1 << 23;
/* Place the absolute value of the addend into the first 12 bits
of the instruction. */
insn &= 0xfffff000;
insn |= addend_abs;
/* Update the instruction. */
md_number_to_chars (buf, insn, INSN_SIZE);
}
break;
case BFD_RELOC_ARM_LDRS_PC_G0:
case BFD_RELOC_ARM_LDRS_PC_G1:
case BFD_RELOC_ARM_LDRS_PC_G2:
case BFD_RELOC_ARM_LDRS_SB_G0:
case BFD_RELOC_ARM_LDRS_SB_G1:
case BFD_RELOC_ARM_LDRS_SB_G2:
gas_assert (!fixP->fx_done);
if (!seg->use_rela_p)
{
bfd_vma insn;
bfd_vma addend_abs = abs (value);
/* Check that the absolute value of the addend can be
encoded in 8 bits. */
if (addend_abs >= 0x100)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad offset 0x%08lX (only 8 bits available for the magnitude)"),
(unsigned long) addend_abs);
/* Extract the instruction. */
insn = md_chars_to_number (buf, INSN_SIZE);
/* If the addend is negative, clear bit 23 of the instruction.
Otherwise set it. */
if (value < 0)
insn &= ~(1 << 23);
else
insn |= 1 << 23;
/* Place the first four bits of the absolute value of the addend
into the first 4 bits of the instruction, and the remaining
four into bits 8 .. 11. */
insn &= 0xfffff0f0;
insn |= (addend_abs & 0xf) | ((addend_abs & 0xf0) << 4);
/* Update the instruction. */
md_number_to_chars (buf, insn, INSN_SIZE);
}
break;
case BFD_RELOC_ARM_LDC_PC_G0:
case BFD_RELOC_ARM_LDC_PC_G1:
case BFD_RELOC_ARM_LDC_PC_G2:
case BFD_RELOC_ARM_LDC_SB_G0:
case BFD_RELOC_ARM_LDC_SB_G1:
case BFD_RELOC_ARM_LDC_SB_G2:
gas_assert (!fixP->fx_done);
if (!seg->use_rela_p)
{
bfd_vma insn;
bfd_vma addend_abs = abs (value);
/* Check that the absolute value of the addend is a multiple of
four and, when divided by four, fits in 8 bits. */
if (addend_abs & 0x3)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad offset 0x%08lX (must be word-aligned)"),
(unsigned long) addend_abs);
if ((addend_abs >> 2) > 0xff)
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad offset 0x%08lX (must be an 8-bit number of words)"),
(unsigned long) addend_abs);
/* Extract the instruction. */
insn = md_chars_to_number (buf, INSN_SIZE);
/* If the addend is negative, clear bit 23 of the instruction.
Otherwise set it. */
if (value < 0)
insn &= ~(1 << 23);
else
insn |= 1 << 23;
/* Place the addend (divided by four) into the first eight
bits of the instruction. */
insn &= 0xfffffff0;
insn |= addend_abs >> 2;
/* Update the instruction. */
md_number_to_chars (buf, insn, INSN_SIZE);
}
break;
case BFD_RELOC_ARM_V4BX:
/* This will need to go in the object file. */
fixP->fx_done = 0;
break;
case BFD_RELOC_UNUSED:
default:
as_bad_where (fixP->fx_file, fixP->fx_line,
_("bad relocation fixup type (%d)"), fixP->fx_r_type);
}
}
/* 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 = (arelent *) xmalloc (sizeof (arelent));
reloc->sym_ptr_ptr = (asymbol **) 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;
switch (fixp->fx_r_type)
{
case BFD_RELOC_8:
if (fixp->fx_pcrel)
{
code = BFD_RELOC_8_PCREL;
break;
}
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_ARM_MOVW:
if (fixp->fx_pcrel)
{
code = BFD_RELOC_ARM_MOVW_PCREL;
break;
}
case BFD_RELOC_ARM_MOVT:
if (fixp->fx_pcrel)
{
code = BFD_RELOC_ARM_MOVT_PCREL;
break;
}
case BFD_RELOC_ARM_THUMB_MOVW:
if (fixp->fx_pcrel)
{
code = BFD_RELOC_ARM_THUMB_MOVW_PCREL;
break;
}
case BFD_RELOC_ARM_THUMB_MOVT:
if (fixp->fx_pcrel)
{
code = BFD_RELOC_ARM_THUMB_MOVT_PCREL;
break;
}
case BFD_RELOC_NONE:
case BFD_RELOC_ARM_PCREL_BRANCH:
case BFD_RELOC_ARM_PCREL_BLX:
case BFD_RELOC_RVA:
case BFD_RELOC_THUMB_PCREL_BRANCH7:
case BFD_RELOC_THUMB_PCREL_BRANCH9:
case BFD_RELOC_THUMB_PCREL_BRANCH12:
case BFD_RELOC_THUMB_PCREL_BRANCH20:
case BFD_RELOC_THUMB_PCREL_BRANCH23:
case BFD_RELOC_THUMB_PCREL_BRANCH25:
case BFD_RELOC_VTABLE_ENTRY:
case BFD_RELOC_VTABLE_INHERIT:
#ifdef TE_PE
case BFD_RELOC_32_SECREL:
#endif
code = fixp->fx_r_type;
break;
case BFD_RELOC_THUMB_PCREL_BLX:
#ifdef OBJ_ELF
if (EF_ARM_EABI_VERSION (meabi_flags) >= EF_ARM_EABI_VER4)
code = BFD_RELOC_THUMB_PCREL_BRANCH23;
else
#endif
code = BFD_RELOC_THUMB_PCREL_BLX;
break;
case BFD_RELOC_ARM_LITERAL:
case BFD_RELOC_ARM_HWLITERAL:
/* If this is called then the a literal has
been referenced across a section boundary. */
as_bad_where (fixp->fx_file, fixp->fx_line,
_("literal referenced across section boundary"));
return NULL;
#ifdef OBJ_ELF
case BFD_RELOC_ARM_TLS_CALL:
case BFD_RELOC_ARM_THM_TLS_CALL:
case BFD_RELOC_ARM_TLS_DESCSEQ:
case BFD_RELOC_ARM_THM_TLS_DESCSEQ:
case BFD_RELOC_ARM_GOT32:
case BFD_RELOC_ARM_GOTOFF:
case BFD_RELOC_ARM_GOT_PREL:
case BFD_RELOC_ARM_PLT32:
case BFD_RELOC_ARM_TARGET1:
case BFD_RELOC_ARM_ROSEGREL32:
case BFD_RELOC_ARM_SBREL32:
case BFD_RELOC_ARM_PREL31:
case BFD_RELOC_ARM_TARGET2:
case BFD_RELOC_ARM_TLS_LE32:
case BFD_RELOC_ARM_TLS_LDO32:
case BFD_RELOC_ARM_PCREL_CALL:
case BFD_RELOC_ARM_PCREL_JUMP:
case BFD_RELOC_ARM_ALU_PC_G0_NC:
case BFD_RELOC_ARM_ALU_PC_G0:
case BFD_RELOC_ARM_ALU_PC_G1_NC:
case BFD_RELOC_ARM_ALU_PC_G1:
case BFD_RELOC_ARM_ALU_PC_G2:
case BFD_RELOC_ARM_LDR_PC_G0:
case BFD_RELOC_ARM_LDR_PC_G1:
case BFD_RELOC_ARM_LDR_PC_G2:
case BFD_RELOC_ARM_LDRS_PC_G0:
case BFD_RELOC_ARM_LDRS_PC_G1:
case BFD_RELOC_ARM_LDRS_PC_G2:
case BFD_RELOC_ARM_LDC_PC_G0:
case BFD_RELOC_ARM_LDC_PC_G1:
case BFD_RELOC_ARM_LDC_PC_G2:
case BFD_RELOC_ARM_ALU_SB_G0_NC:
case BFD_RELOC_ARM_ALU_SB_G0:
case BFD_RELOC_ARM_ALU_SB_G1_NC:
case BFD_RELOC_ARM_ALU_SB_G1:
case BFD_RELOC_ARM_ALU_SB_G2:
case BFD_RELOC_ARM_LDR_SB_G0:
case BFD_RELOC_ARM_LDR_SB_G1:
case BFD_RELOC_ARM_LDR_SB_G2:
case BFD_RELOC_ARM_LDRS_SB_G0:
case BFD_RELOC_ARM_LDRS_SB_G1:
case BFD_RELOC_ARM_LDRS_SB_G2:
case BFD_RELOC_ARM_LDC_SB_G0:
case BFD_RELOC_ARM_LDC_SB_G1:
case BFD_RELOC_ARM_LDC_SB_G2:
case BFD_RELOC_ARM_V4BX:
code = fixp->fx_r_type;
break;
case BFD_RELOC_ARM_TLS_GOTDESC:
case BFD_RELOC_ARM_TLS_GD32:
case BFD_RELOC_ARM_TLS_IE32:
case BFD_RELOC_ARM_TLS_LDM32:
/* BFD will include the symbol's address in the addend.
But we don't want that, so subtract it out again here. */
if (!S_IS_COMMON (fixp->fx_addsy))
reloc->addend -= (*reloc->sym_ptr_ptr)->value;
code = fixp->fx_r_type;
break;
#endif
case BFD_RELOC_ARM_IMMEDIATE:
as_bad_where (fixp->fx_file, fixp->fx_line,
_("internal relocation (type: IMMEDIATE) not fixed up"));
return NULL;
case BFD_RELOC_ARM_ADRL_IMMEDIATE:
as_bad_where (fixp->fx_file, fixp->fx_line,
_("ADRL used for a symbol not defined in the same file"));
return NULL;
case BFD_RELOC_ARM_OFFSET_IMM:
if (section->use_rela_p)
{
code = fixp->fx_r_type;
break;
}
if (fixp->fx_addsy != NULL
&& !S_IS_DEFINED (fixp->fx_addsy)
&& S_IS_LOCAL (fixp->fx_addsy))
{
as_bad_where (fixp->fx_file, fixp->fx_line,
_("undefined local label `%s'"),
S_GET_NAME (fixp->fx_addsy));
return NULL;
}
as_bad_where (fixp->fx_file, fixp->fx_line,
_("internal_relocation (type: OFFSET_IMM) not fixed up"));
return NULL;
default:
{
char * type;
switch (fixp->fx_r_type)
{
case BFD_RELOC_NONE: type = "NONE"; break;
case BFD_RELOC_ARM_OFFSET_IMM8: type = "OFFSET_IMM8"; break;
case BFD_RELOC_ARM_SHIFT_IMM: type = "SHIFT_IMM"; break;
case BFD_RELOC_ARM_SMC: type = "SMC"; break;
case BFD_RELOC_ARM_SWI: type = "SWI"; break;
case BFD_RELOC_ARM_MULTI: type = "MULTI"; break;
case BFD_RELOC_ARM_CP_OFF_IMM: type = "CP_OFF_IMM"; break;
case BFD_RELOC_ARM_T32_OFFSET_IMM: type = "T32_OFFSET_IMM"; break;
case BFD_RELOC_ARM_T32_CP_OFF_IMM: type = "T32_CP_OFF_IMM"; break;
case BFD_RELOC_ARM_THUMB_ADD: type = "THUMB_ADD"; break;
case BFD_RELOC_ARM_THUMB_SHIFT: type = "THUMB_SHIFT"; break;
case BFD_RELOC_ARM_THUMB_IMM: type = "THUMB_IMM"; break;
case BFD_RELOC_ARM_THUMB_OFFSET: type = "THUMB_OFFSET"; break;
default: type = _("<unknown>"); break;
}
as_bad_where (fixp->fx_file, fixp->fx_line,
_("cannot represent %s relocation in this object file format"),
type);
return NULL;
}
}
#ifdef OBJ_ELF
if ((code == BFD_RELOC_32_PCREL || code == BFD_RELOC_32)
&& GOT_symbol
&& fixp->fx_addsy == GOT_symbol)
{
code = BFD_RELOC_ARM_GOTPC;
reloc->addend = fixp->fx_offset = reloc->address;
}
#endif
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;
}
/* HACK: Since arm ELF uses Rel instead of Rela, encode the
vtable entry to be used in the relocation's section offset. */
if (fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
reloc->address = fixp->fx_offset;
return reloc;
}
/* This fix_new is called by cons via TC_CONS_FIX_NEW. */
void
cons_fix_new_arm (fragS * frag,
int where,
int size,
expressionS * exp,
bfd_reloc_code_real_type reloc)
{
int pcrel = 0;
/* Pick a reloc.
FIXME: @@ Should look at CPU word size. */
switch (size)
{
case 1:
reloc = BFD_RELOC_8;
break;
case 2:
reloc = BFD_RELOC_16;
break;
case 4:
default:
reloc = BFD_RELOC_32;
break;
case 8:
reloc = BFD_RELOC_64;
break;
}
#ifdef TE_PE
if (exp->X_op == O_secrel)
{
exp->X_op = O_symbol;
reloc = BFD_RELOC_32_SECREL;
}
#endif
fix_new_exp (frag, where, size, exp, pcrel, reloc);
}
#if defined (OBJ_COFF)
void
arm_validate_fix (fixS * fixP)
{
/* If the destination of the branch is a defined symbol which does not have
the THUMB_FUNC attribute, then we must be calling a function which has
the (interfacearm) attribute. We look for the Thumb entry point to that
function and change the branch to refer to that function instead. */
if (fixP->fx_r_type == BFD_RELOC_THUMB_PCREL_BRANCH23
&& fixP->fx_addsy != NULL
&& S_IS_DEFINED (fixP->fx_addsy)
&& ! THUMB_IS_FUNC (fixP->fx_addsy))
{
fixP->fx_addsy = find_real_start (fixP->fx_addsy);
}
}
#endif
int
arm_force_relocation (struct fix * fixp)
{
#if defined (OBJ_COFF) && defined (TE_PE)
if (fixp->fx_r_type == BFD_RELOC_RVA)
return 1;
#endif
/* In case we have a call or a branch to a function in ARM ISA mode from
a thumb function or vice-versa force the relocation. These relocations
are cleared off for some cores that might have blx and simple transformations
are possible. */
#ifdef OBJ_ELF
switch (fixp->fx_r_type)
{
case BFD_RELOC_ARM_PCREL_JUMP:
case BFD_RELOC_ARM_PCREL_CALL:
case BFD_RELOC_THUMB_PCREL_BLX:
if (THUMB_IS_FUNC (fixp->fx_addsy))
return 1;
break;
case BFD_RELOC_ARM_PCREL_BLX:
case BFD_RELOC_THUMB_PCREL_BRANCH25:
case BFD_RELOC_THUMB_PCREL_BRANCH20:
case BFD_RELOC_THUMB_PCREL_BRANCH23:
if (ARM_IS_FUNC (fixp->fx_addsy))
return 1;
break;
default:
break;
}
#endif
/* Resolve these relocations even if the symbol is extern or weak.
Technically this is probably wrong due to symbol preemption.
In practice these relocations do not have enough range to be useful
at dynamic link time, and some code (e.g. in the Linux kernel)
expects these references to be resolved. */
if (fixp->fx_r_type == BFD_RELOC_ARM_IMMEDIATE
|| fixp->fx_r_type == BFD_RELOC_ARM_OFFSET_IMM
|| fixp->fx_r_type == BFD_RELOC_ARM_OFFSET_IMM8
|| fixp->fx_r_type == BFD_RELOC_ARM_ADRL_IMMEDIATE
|| fixp->fx_r_type == BFD_RELOC_ARM_CP_OFF_IMM
|| fixp->fx_r_type == BFD_RELOC_ARM_CP_OFF_IMM_S2
|| fixp->fx_r_type == BFD_RELOC_ARM_THUMB_OFFSET
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_ADD_IMM
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_IMMEDIATE
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_IMM12
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_OFFSET_IMM
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_ADD_PC12
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_CP_OFF_IMM
|| fixp->fx_r_type == BFD_RELOC_ARM_T32_CP_OFF_IMM_S2)
return 0;
/* Always leave these relocations for the linker. */
if ((fixp->fx_r_type >= BFD_RELOC_ARM_ALU_PC_G0_NC
&& fixp->fx_r_type <= BFD_RELOC_ARM_LDC_SB_G2)
|| fixp->fx_r_type == BFD_RELOC_ARM_LDR_PC_G0)
return 1;
/* Always generate relocations against function symbols. */
if (fixp->fx_r_type == BFD_RELOC_32
&& fixp->fx_addsy
&& (symbol_get_bfdsym (fixp->fx_addsy)->flags & BSF_FUNCTION))
return 1;
return generic_force_reloc (fixp);
}
#if defined (OBJ_ELF) || defined (OBJ_COFF)
/* Relocations against function names must be left unadjusted,
so that the linker can use this information to generate interworking
stubs. The MIPS version of this function
also prevents relocations that are mips-16 specific, but I do not
know why it does this.
FIXME:
There is one other problem that ought to be addressed here, but
which currently is not: Taking the address of a label (rather
than a function) and then later jumping to that address. Such
addresses also ought to have their bottom bit set (assuming that
they reside in Thumb code), but at the moment they will not. */
bfd_boolean
arm_fix_adjustable (fixS * fixP)
{
if (fixP->fx_addsy == NULL)
return 1;
/* Preserve relocations against symbols with function type. */
if (symbol_get_bfdsym (fixP->fx_addsy)->flags & BSF_FUNCTION)
return FALSE;
if (THUMB_IS_FUNC (fixP->fx_addsy)
&& fixP->fx_subsy == NULL)
return FALSE;
/* We need the symbol name for the VTABLE entries. */
if ( fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
|| fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
return FALSE;
/* Don't allow symbols to be discarded on GOT related relocs. */
if (fixP->fx_r_type == BFD_RELOC_ARM_PLT32
|| fixP->fx_r_type == BFD_RELOC_ARM_GOT32
|| fixP->fx_r_type == BFD_RELOC_ARM_GOTOFF
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_GD32
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_LE32
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_IE32
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_LDM32
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_LDO32
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_GOTDESC
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_CALL
|| fixP->fx_r_type == BFD_RELOC_ARM_THM_TLS_CALL
|| fixP->fx_r_type == BFD_RELOC_ARM_TLS_DESCSEQ
|| fixP->fx_r_type == BFD_RELOC_ARM_THM_TLS_DESCSEQ
|| fixP->fx_r_type == BFD_RELOC_ARM_TARGET2)
return FALSE;
/* Similarly for group relocations. */
if ((fixP->fx_r_type >= BFD_RELOC_ARM_ALU_PC_G0_NC
&& fixP->fx_r_type <= BFD_RELOC_ARM_LDC_SB_G2)
|| fixP->fx_r_type == BFD_RELOC_ARM_LDR_PC_G0)
return FALSE;
/* MOVW/MOVT REL relocations have limited offsets, so keep the symbols. */
if (fixP->fx_r_type == BFD_RELOC_ARM_MOVW
|| fixP->fx_r_type == BFD_RELOC_ARM_MOVT
|| fixP->fx_r_type == BFD_RELOC_ARM_MOVW_PCREL
|| fixP->fx_r_type == BFD_RELOC_ARM_MOVT_PCREL
|| fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVW
|| fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVT
|| fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVW_PCREL
|| fixP->fx_r_type == BFD_RELOC_ARM_THUMB_MOVT_PCREL)
return FALSE;
return TRUE;
}
#endif /* defined (OBJ_ELF) || defined (OBJ_COFF) */
#ifdef OBJ_ELF
const char *
elf32_arm_target_format (void)
{
#ifdef TE_SYMBIAN
return (target_big_endian
? "elf32-bigarm-symbian"
: "elf32-littlearm-symbian");
#elif defined (TE_VXWORKS)
return (target_big_endian
? "elf32-bigarm-vxworks"
: "elf32-littlearm-vxworks");
#elif defined (TE_NACL)
return (target_big_endian
? "elf32-bigarm-nacl"
: "elf32-littlearm-nacl");
#else
if (target_big_endian)
return "elf32-bigarm";
else
return "elf32-littlearm";
#endif
}
void
armelf_frob_symbol (symbolS * symp,
int * puntp)
{
elf_frob_symbol (symp, puntp);
}
#endif
/* MD interface: Finalization. */
void
arm_cleanup (void)
{
literal_pool * pool;
/* Ensure that all the IT blocks are properly closed. */
check_it_blocks_finished ();
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);
#ifdef OBJ_ELF
arm_elf_change_section ();
#endif
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. This marks Thumb symbols as distinct from
ARM ones. */
void
arm_adjust_symtab (void)
{
#ifdef OBJ_COFF
symbolS * sym;
for (sym = symbol_rootP; sym != NULL; sym = symbol_next (sym))
{
if (ARM_IS_THUMB (sym))
{
if (THUMB_IS_FUNC (sym))
{
/* Mark the symbol as a Thumb function. */
if ( S_GET_STORAGE_CLASS (sym) == C_STAT
|| S_GET_STORAGE_CLASS (sym) == C_LABEL) /* This can happen! */
S_SET_STORAGE_CLASS (sym, C_THUMBSTATFUNC);
else if (S_GET_STORAGE_CLASS (sym) == C_EXT)
S_SET_STORAGE_CLASS (sym, C_THUMBEXTFUNC);
else
as_bad (_("%s: unexpected function type: %d"),
S_GET_NAME (sym), S_GET_STORAGE_CLASS (sym));
}
else switch (S_GET_STORAGE_CLASS (sym))
{
case C_EXT:
S_SET_STORAGE_CLASS (sym, C_THUMBEXT);
break;
case C_STAT:
S_SET_STORAGE_CLASS (sym, C_THUMBSTAT);
break;
case C_LABEL:
S_SET_STORAGE_CLASS (sym, C_THUMBLABEL);
break;
default:
/* Do nothing. */
break;
}
}
if (ARM_IS_INTERWORK (sym))
coffsymbol (symbol_get_bfdsym (sym))->native->u.syment.n_flags = 0xFF;
}
#endif
#ifdef OBJ_ELF
symbolS * sym;
char bind;
for (sym = symbol_rootP; sym != NULL; sym = symbol_next (sym))
{
if (ARM_IS_THUMB (sym))
{
elf_symbol_type * elf_sym;
elf_sym = elf_symbol (symbol_get_bfdsym (sym));
bind = ELF_ST_BIND (elf_sym->internal_elf_sym.st_info);
if (! bfd_is_arm_special_symbol_name (elf_sym->symbol.name,
BFD_ARM_SPECIAL_SYM_TYPE_ANY))
{
/* If it's a .thumb_func, declare it as so,
otherwise tag label as .code 16. */
if (THUMB_IS_FUNC (sym))
elf_sym->internal_elf_sym.st_target_internal
= ST_BRANCH_TO_THUMB;
else if (EF_ARM_EABI_VERSION (meabi_flags) < EF_ARM_EABI_VER4)
elf_sym->internal_elf_sym.st_info =
ELF_ST_INFO (bind, STT_ARM_16BIT);
}
}
}
/* 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
}
/* MD interface: Initialization. */
static void
set_constant_flonums (void)
{
int i;
for (i = 0; i < NUM_FLOAT_VALS; i++)
if (atof_ieee ((char *) fp_const[i], 'x', fp_values[i]) == NULL)
abort ();
}
/* Auto-select Thumb mode if it's the only available instruction set for the
given architecture. */
static void
autoselect_thumb_from_cpu_variant (void)
{
if (!ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v1))
opcode_select (16);
}
void
md_begin (void)
{
unsigned mach;
unsigned int i;
if ( (arm_ops_hsh = hash_new ()) == NULL
|| (arm_cond_hsh = hash_new ()) == NULL
|| (arm_shift_hsh = hash_new ()) == NULL
|| (arm_psr_hsh = hash_new ()) == NULL
|| (arm_v7m_psr_hsh = hash_new ()) == NULL
|| (arm_reg_hsh = hash_new ()) == NULL
|| (arm_reloc_hsh = hash_new ()) == NULL
|| (arm_barrier_opt_hsh = hash_new ()) == NULL)
as_fatal (_("virtual memory exhausted"));
for (i = 0; i < sizeof (insns) / sizeof (struct asm_opcode); i++)
hash_insert (arm_ops_hsh, insns[i].template_name, (void *) (insns + i));
for (i = 0; i < sizeof (conds) / sizeof (struct asm_cond); i++)
hash_insert (arm_cond_hsh, conds[i].template_name, (void *) (conds + i));
for (i = 0; i < sizeof (shift_names) / sizeof (struct asm_shift_name); i++)
hash_insert (arm_shift_hsh, shift_names[i].name, (void *) (shift_names + i));
for (i = 0; i < sizeof (psrs) / sizeof (struct asm_psr); i++)
hash_insert (arm_psr_hsh, psrs[i].template_name, (void *) (psrs + i));
for (i = 0; i < sizeof (v7m_psrs) / sizeof (struct asm_psr); i++)
hash_insert (arm_v7m_psr_hsh, v7m_psrs[i].template_name,
(void *) (v7m_psrs + i));
for (i = 0; i < sizeof (reg_names) / sizeof (struct reg_entry); i++)
hash_insert (arm_reg_hsh, reg_names[i].name, (void *) (reg_names + i));
for (i = 0;
i < sizeof (barrier_opt_names) / sizeof (struct asm_barrier_opt);
i++)
hash_insert (arm_barrier_opt_hsh, barrier_opt_names[i].template_name,
(void *) (barrier_opt_names + i));
#ifdef OBJ_ELF
for (i = 0; i < ARRAY_SIZE (reloc_names); i++)
{
struct reloc_entry * entry = reloc_names + i;
if (arm_is_eabi() && entry->reloc == BFD_RELOC_ARM_PLT32)
/* This makes encode_branch() use the EABI versions of this relocation. */
entry->reloc = BFD_RELOC_UNUSED;
hash_insert (arm_reloc_hsh, entry->name, (void *) entry);
}
#endif
set_constant_flonums ();
/* Set the cpu variant based on the command-line options. We prefer
-mcpu= over -march= if both are set (as for GCC); and we prefer
-mfpu= over any other way of setting the floating point unit.
Use of legacy options with new options are faulted. */
if (legacy_cpu)
{
if (mcpu_cpu_opt || march_cpu_opt)
as_bad (_("use of old and new-style options to set CPU type"));
mcpu_cpu_opt = legacy_cpu;
}
else if (!mcpu_cpu_opt)
mcpu_cpu_opt = march_cpu_opt;
if (legacy_fpu)
{
if (mfpu_opt)
as_bad (_("use of old and new-style options to set FPU type"));
mfpu_opt = legacy_fpu;
}
else if (!mfpu_opt)
{
#if !(defined (EABI_DEFAULT) || defined (TE_LINUX) \
|| defined (TE_NetBSD) || defined (TE_VXWORKS))
/* Some environments specify a default FPU. If they don't, infer it
from the processor. */
if (mcpu_fpu_opt)
mfpu_opt = mcpu_fpu_opt;
else
mfpu_opt = march_fpu_opt;
#else
mfpu_opt = &fpu_default;
#endif
}
if (!mfpu_opt)
{
if (mcpu_cpu_opt != NULL)
mfpu_opt = &fpu_default;
else if (mcpu_fpu_opt != NULL && ARM_CPU_HAS_FEATURE (*mcpu_fpu_opt, arm_ext_v5))
mfpu_opt = &fpu_arch_vfp_v2;
else
mfpu_opt = &fpu_arch_fpa;
}
#ifdef CPU_DEFAULT
if (!mcpu_cpu_opt)
{
mcpu_cpu_opt = &cpu_default;
selected_cpu = cpu_default;
}
else if (no_cpu_selected ())
selected_cpu = cpu_default;
#else
if (mcpu_cpu_opt)
selected_cpu = *mcpu_cpu_opt;
else
mcpu_cpu_opt = &arm_arch_any;
#endif
ARM_MERGE_FEATURE_SETS (cpu_variant, *mcpu_cpu_opt, *mfpu_opt);
autoselect_thumb_from_cpu_variant ();
arm_arch_used = thumb_arch_used = arm_arch_none;
#if defined OBJ_COFF || defined OBJ_ELF
{
unsigned int flags = 0;
#if defined OBJ_ELF
flags = meabi_flags;
switch (meabi_flags)
{
case EF_ARM_EABI_UNKNOWN:
#endif
/* Set the flags in the private structure. */
if (uses_apcs_26) flags |= F_APCS26;
if (support_interwork) flags |= F_INTERWORK;
if (uses_apcs_float) flags |= F_APCS_FLOAT;
if (pic_code) flags |= F_PIC;
if (!ARM_CPU_HAS_FEATURE (cpu_variant, fpu_any_hard))
flags |= F_SOFT_FLOAT;
switch (mfloat_abi_opt)
{
case ARM_FLOAT_ABI_SOFT:
case ARM_FLOAT_ABI_SOFTFP:
flags |= F_SOFT_FLOAT;
break;
case ARM_FLOAT_ABI_HARD:
if (flags & F_SOFT_FLOAT)
as_bad (_("hard-float conflicts with specified fpu"));
break;
}
/* Using pure-endian doubles (even if soft-float). */
if (ARM_CPU_HAS_FEATURE (cpu_variant, fpu_endian_pure))
flags |= F_VFP_FLOAT;
#if defined OBJ_ELF
if (ARM_CPU_HAS_FEATURE (cpu_variant, fpu_arch_maverick))
flags |= EF_ARM_MAVERICK_FLOAT;
break;
case EF_ARM_EABI_VER4:
case EF_ARM_EABI_VER5:
/* No additional flags to set. */
break;
default:
abort ();
}
#endif
bfd_set_private_flags (stdoutput, flags);
/* We have run out flags in the COFF header to encode the
status of ATPCS support, so instead we create a dummy,
empty, debug section called .arm.atpcs. */
if (atpcs)
{
asection * sec;
sec = bfd_make_section (stdoutput, ".arm.atpcs");
if (sec != NULL)
{
bfd_set_section_flags
(stdoutput, sec, SEC_READONLY | SEC_DEBUGGING /* | SEC_HAS_CONTENTS */);
bfd_set_section_size (stdoutput, sec, 0);
bfd_set_section_contents (stdoutput, sec, NULL, 0, 0);
}
}
}
#endif
/* Record the CPU type as well. */
if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_cext_iwmmxt2))
mach = bfd_mach_arm_iWMMXt2;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_cext_iwmmxt))
mach = bfd_mach_arm_iWMMXt;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_cext_xscale))
mach = bfd_mach_arm_XScale;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_cext_maverick))
mach = bfd_mach_arm_ep9312;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v5e))
mach = bfd_mach_arm_5TE;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v5))
{
if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v4t))
mach = bfd_mach_arm_5T;
else
mach = bfd_mach_arm_5;
}
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v4))
{
if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v4t))
mach = bfd_mach_arm_4T;
else
mach = bfd_mach_arm_4;
}
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v3m))
mach = bfd_mach_arm_3M;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v3))
mach = bfd_mach_arm_3;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v2s))
mach = bfd_mach_arm_2a;
else if (ARM_CPU_HAS_FEATURE (cpu_variant, arm_ext_v2))
mach = bfd_mach_arm_2;
else
mach = bfd_mach_arm_unknown;
bfd_set_arch_mach (stdoutput, TARGET_ARCH, mach);
}
/* Command line processing. */
/* md_parse_option
Invocation line includes a switch not recognized by the base assembler.
See if it's a processor-specific option.
This routine is somewhat complicated by the need for backwards
compatibility (since older releases of gcc can't be changed).
The new options try to make the interface as compatible as
possible with GCC.
New options (supported) are:
-mcpu=<cpu name> Assemble for selected processor
-march=<architecture name> Assemble for selected architecture
-mfpu=<fpu architecture> Assemble for selected FPU.
-EB/-mbig-endian Big-endian
-EL/-mlittle-endian Little-endian
-k Generate PIC code
-mthumb Start in Thumb mode
-mthumb-interwork Code supports ARM/Thumb interworking
-m[no-]warn-deprecated Warn about deprecated features
For now we will also provide support for:
-mapcs-32 32-bit Program counter
-mapcs-26 26-bit Program counter
-macps-float Floats passed in FP registers
-mapcs-reentrant Reentrant code
-matpcs
(sometime these will probably be replaced with -mapcs=<list of options>
and -matpcs=<list of options>)
The remaining options are only supported for back-wards compatibility.
Cpu variants, the arm part is optional:
-m[arm]1 Currently not supported.
-m[arm]2, -m[arm]250 Arm 2 and Arm 250 processor
-m[arm]3 Arm 3 processor
-m[arm]6[xx], Arm 6 processors
-m[arm]7[xx][t][[d]m] Arm 7 processors
-m[arm]8[10] Arm 8 processors
-m[arm]9[20][tdmi] Arm 9 processors
-mstrongarm[110[0]] StrongARM processors
-mxscale XScale processors
-m[arm]v[2345[t[e]]] Arm architectures
-mall All (except the ARM1)
FP variants:
-mfpa10, -mfpa11 FPA10 and 11 co-processor instructions
-mfpe-old (No float load/store multiples)
-mvfpxd VFP Single precision
-mvfp All VFP
-mno-fpu Disable all floating point instructions
The following CPU names are recognized:
arm1, arm2, arm250, arm3, arm6, arm600, arm610, arm620,
arm7, arm7m, arm7d, arm7dm, arm7di, arm7dmi, arm70, arm700,
arm700i, arm710 arm710t, arm720, arm720t, arm740t, arm710c,
arm7100, arm7500, arm7500fe, arm7tdmi, arm8, arm810, arm9,
arm920, arm920t, arm940t, arm946, arm966, arm9tdmi, arm9e,
arm10t arm10e, arm1020t, arm1020e, arm10200e,
strongarm, strongarm110, strongarm1100, strongarm1110, xscale.
*/
const char * md_shortopts = "m:k";
#ifdef ARM_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
#define OPTION_FIX_V4BX (OPTION_MD_BASE + 2)
struct option md_longopts[] =
{
#ifdef OPTION_EB
{"EB", no_argument, NULL, OPTION_EB},
#endif
#ifdef OPTION_EL
{"EL", no_argument, NULL, OPTION_EL},
#endif
{"fix-v4bx", no_argument, NULL, OPTION_FIX_V4BX},
{NULL, no_argument, NULL, 0}
};
size_t md_longopts_size = sizeof (md_longopts);
struct arm_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. */
};
struct arm_option_table arm_opts[] =
{
{"k", N_("generate PIC code"), &pic_code, 1, NULL},
{"mthumb", N_("assemble Thumb code"), &thumb_mode, 1, NULL},
{"mthumb-interwork", N_("support ARM/Thumb interworking"),
&support_interwork, 1, NULL},
{"mapcs-32", N_("code uses 32-bit program counter"), &uses_apcs_26, 0, NULL},
{"mapcs-26", N_("code uses 26-bit program counter"), &uses_apcs_26, 1, NULL},
{"mapcs-float", N_("floating point args are in fp regs"), &uses_apcs_float,
1, NULL},
{"mapcs-reentrant", N_("re-entrant code"), &pic_code, 1, NULL},
{"matpcs", N_("code is ATPCS conformant"), &atpcs, 1, NULL},
{"mbig-endian", N_("assemble for big-endian"), &target_big_endian, 1, NULL},
{"mlittle-endian", N_("assemble for little-endian"), &target_big_endian, 0,
NULL},
/* These are recognized by the assembler, but have no affect on code. */
{"mapcs-frame", N_("use frame pointer"), NULL, 0, NULL},
{"mapcs-stack-check", N_("use stack size checking"), NULL, 0, NULL},
{"mwarn-deprecated", NULL, &warn_on_deprecated, 1, NULL},
{"mno-warn-deprecated", N_("do not warn on use of deprecated feature"),
&warn_on_deprecated, 0, NULL},
{NULL, NULL, NULL, 0, NULL}
};
struct arm_legacy_option_table
{
char *option; /* Option name to match. */
const arm_feature_set **var; /* Variable to change. */
const arm_feature_set value; /* What to change it to. */
char *deprecated; /* If non-null, print this message. */
};
const struct arm_legacy_option_table arm_legacy_opts[] =
{
/* DON'T add any new processors to this list -- we want the whole list
to go away... Add them to the processors table instead. */
{"marm1", &legacy_cpu, ARM_ARCH_V1, N_("use -mcpu=arm1")},
{"m1", &legacy_cpu, ARM_ARCH_V1, N_("use -mcpu=arm1")},
{"marm2", &legacy_cpu, ARM_ARCH_V2, N_("use -mcpu=arm2")},
{"m2", &legacy_cpu, ARM_ARCH_V2, N_("use -mcpu=arm2")},
{"marm250", &legacy_cpu, ARM_ARCH_V2S, N_("use -mcpu=arm250")},
{"m250", &legacy_cpu, ARM_ARCH_V2S, N_("use -mcpu=arm250")},
{"marm3", &legacy_cpu, ARM_ARCH_V2S, N_("use -mcpu=arm3")},
{"m3", &legacy_cpu, ARM_ARCH_V2S, N_("use -mcpu=arm3")},
{"marm6", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm6")},
{"m6", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm6")},
{"marm600", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm600")},
{"m600", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm600")},
{"marm610", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm610")},
{"m610", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm610")},
{"marm620", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm620")},
{"m620", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm620")},
{"marm7", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7")},
{"m7", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7")},
{"marm70", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm70")},
{"m70", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm70")},
{"marm700", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm700")},
{"m700", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm700")},
{"marm700i", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm700i")},
{"m700i", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm700i")},
{"marm710", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm710")},
{"m710", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm710")},
{"marm710c", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm710c")},
{"m710c", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm710c")},
{"marm720", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm720")},
{"m720", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm720")},
{"marm7d", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7d")},
{"m7d", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7d")},
{"marm7di", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7di")},
{"m7di", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7di")},
{"marm7m", &legacy_cpu, ARM_ARCH_V3M, N_("use -mcpu=arm7m")},
{"m7m", &legacy_cpu, ARM_ARCH_V3M, N_("use -mcpu=arm7m")},
{"marm7dm", &legacy_cpu, ARM_ARCH_V3M, N_("use -mcpu=arm7dm")},
{"m7dm", &legacy_cpu, ARM_ARCH_V3M, N_("use -mcpu=arm7dm")},
{"marm7dmi", &legacy_cpu, ARM_ARCH_V3M, N_("use -mcpu=arm7dmi")},
{"m7dmi", &legacy_cpu, ARM_ARCH_V3M, N_("use -mcpu=arm7dmi")},
{"marm7100", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7100")},
{"m7100", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7100")},
{"marm7500", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7500")},
{"m7500", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7500")},
{"marm7500fe", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7500fe")},
{"m7500fe", &legacy_cpu, ARM_ARCH_V3, N_("use -mcpu=arm7500fe")},
{"marm7t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm7tdmi")},
{"m7t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm7tdmi")},
{"marm7tdmi", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm7tdmi")},
{"m7tdmi", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm7tdmi")},
{"marm710t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm710t")},
{"m710t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm710t")},
{"marm720t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm720t")},
{"m720t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm720t")},
{"marm740t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm740t")},
{"m740t", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm740t")},
{"marm8", &legacy_cpu, ARM_ARCH_V4, N_("use -mcpu=arm8")},
{"m8", &legacy_cpu, ARM_ARCH_V4, N_("use -mcpu=arm8")},
{"marm810", &legacy_cpu, ARM_ARCH_V4, N_("use -mcpu=arm810")},
{"m810", &legacy_cpu, ARM_ARCH_V4, N_("use -mcpu=arm810")},
{"marm9", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm9")},
{"m9", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm9")},
{"marm9tdmi", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm9tdmi")},
{"m9tdmi", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm9tdmi")},
{"marm920", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm920")},
{"m920", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm920")},
{"marm940", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm940")},
{"m940", &legacy_cpu, ARM_ARCH_V4T, N_("use -mcpu=arm940")},
{"mstrongarm", &legacy_cpu, ARM_ARCH_V4, N_("use -mcpu=strongarm")},
{"mstrongarm110", &legacy_cpu, ARM_ARCH_V4,
N_("use -mcpu=strongarm110")},
{"mstrongarm1100", &legacy_cpu, ARM_ARCH_V4,
N_("use -mcpu=strongarm1100")},
{"mstrongarm1110", &legacy_cpu, ARM_ARCH_V4,
N_("use -mcpu=strongarm1110")},
{"mxscale", &legacy_cpu, ARM_ARCH_XSCALE, N_("use -mcpu=xscale")},
{"miwmmxt", &legacy_cpu, ARM_ARCH_IWMMXT, N_("use -mcpu=iwmmxt")},
{"mall", &legacy_cpu, ARM_ANY, N_("use -mcpu=all")},
/* Architecture variants -- don't add any more to this list either. */
{"mv2", &legacy_cpu, ARM_ARCH_V2, N_("use -march=armv2")},
{"marmv2", &legacy_cpu, ARM_ARCH_V2, N_("use -march=armv2")},
{"mv2a", &legacy_cpu, ARM_ARCH_V2S, N_("use -march=armv2a")},
{"marmv2a", &legacy_cpu, ARM_ARCH_V2S, N_("use -march=armv2a")},
{"mv3", &legacy_cpu, ARM_ARCH_V3, N_("use -march=armv3")},
{"marmv3", &legacy_cpu, ARM_ARCH_V3, N_("use -march=armv3")},
{"mv3m", &legacy_cpu, ARM_ARCH_V3M, N_("use -march=armv3m")},
{"marmv3m", &legacy_cpu, ARM_ARCH_V3M, N_("use -march=armv3m")},
{"mv4", &legacy_cpu, ARM_ARCH_V4, N_("use -march=armv4")},
{"marmv4", &legacy_cpu, ARM_ARCH_V4, N_("use -march=armv4")},
{"mv4t", &legacy_cpu, ARM_ARCH_V4T, N_("use -march=armv4t")},
{"marmv4t", &legacy_cpu, ARM_ARCH_V4T, N_("use -march=armv4t")},
{"mv5", &legacy_cpu, ARM_ARCH_V5, N_("use -march=armv5")},
{"marmv5", &legacy_cpu, ARM_ARCH_V5, N_("use -march=armv5")},
{"mv5t", &legacy_cpu, ARM_ARCH_V5T, N_("use -march=armv5t")},
{"marmv5t", &legacy_cpu, ARM_ARCH_V5T, N_("use -march=armv5t")},
{"mv5e", &legacy_cpu, ARM_ARCH_V5TE, N_("use -march=armv5te")},
{"marmv5e", &legacy_cpu, ARM_ARCH_V5TE, N_("use -march=armv5te")},
/* Floating point variants -- don't add any more to this list either. */
{"mfpe-old", &legacy_fpu, FPU_ARCH_FPE, N_("use -mfpu=fpe")},
{"mfpa10", &legacy_fpu, FPU_ARCH_FPA, N_("use -mfpu=fpa10")},
{"mfpa11", &legacy_fpu, FPU_ARCH_FPA, N_("use -mfpu=fpa11")},
{"mno-fpu", &legacy_fpu, ARM_ARCH_NONE,
N_("use either -mfpu=softfpa or -mfpu=softvfp")},
{NULL, NULL, ARM_ARCH_NONE, NULL}
};
struct arm_cpu_option_table
{
char *name;
size_t name_len;
const arm_feature_set value;
/* For some CPUs we assume an FPU unless the user explicitly sets
-mfpu=... */
const arm_feature_set default_fpu;
/* 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. */
#define ARM_CPU_OPT(N, V, DF, CN) { N, sizeof (N) - 1, V, DF, CN }
static const struct arm_cpu_option_table arm_cpus[] =
{
ARM_CPU_OPT ("all", ARM_ANY, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm1", ARM_ARCH_V1, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm2", ARM_ARCH_V2, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm250", ARM_ARCH_V2S, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm3", ARM_ARCH_V2S, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm6", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm60", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm600", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm610", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm620", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7m", ARM_ARCH_V3M, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7d", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7dm", ARM_ARCH_V3M, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7di", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7dmi", ARM_ARCH_V3M, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm70", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm700", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm700i", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm710", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm710t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm720", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm720t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm740t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm710c", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7100", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7500", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7500fe", ARM_ARCH_V3, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7tdmi", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm7tdmi-s", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm8", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm810", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("strongarm", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("strongarm1", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("strongarm110", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("strongarm1100", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("strongarm1110", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm9", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm920", ARM_ARCH_V4T, FPU_ARCH_FPA, "ARM920T"),
ARM_CPU_OPT ("arm920t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm922t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm940t", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("arm9tdmi", ARM_ARCH_V4T, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("fa526", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
ARM_CPU_OPT ("fa626", ARM_ARCH_V4, FPU_ARCH_FPA, NULL),
/* For V5 or later processors we default to using VFP; but the user
should really set the FPU type explicitly. */
ARM_CPU_OPT ("arm9e-r0", ARM_ARCH_V5TExP, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm9e", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm926ej", ARM_ARCH_V5TEJ, FPU_ARCH_VFP_V2, "ARM926EJ-S"),
ARM_CPU_OPT ("arm926ejs", ARM_ARCH_V5TEJ, FPU_ARCH_VFP_V2, "ARM926EJ-S"),
ARM_CPU_OPT ("arm926ej-s", ARM_ARCH_V5TEJ, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm946e-r0", ARM_ARCH_V5TExP, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm946e", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, "ARM946E-S"),
ARM_CPU_OPT ("arm946e-s", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm966e-r0", ARM_ARCH_V5TExP, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm966e", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, "ARM966E-S"),
ARM_CPU_OPT ("arm966e-s", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm968e-s", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm10t", ARM_ARCH_V5T, FPU_ARCH_VFP_V1, NULL),
ARM_CPU_OPT ("arm10tdmi", ARM_ARCH_V5T, FPU_ARCH_VFP_V1, NULL),
ARM_CPU_OPT ("arm10e", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm1020", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, "ARM1020E"),
ARM_CPU_OPT ("arm1020t", ARM_ARCH_V5T, FPU_ARCH_VFP_V1, NULL),
ARM_CPU_OPT ("arm1020e", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm1022e", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm1026ejs", ARM_ARCH_V5TEJ, FPU_ARCH_VFP_V2,
"ARM1026EJ-S"),
ARM_CPU_OPT ("arm1026ej-s", ARM_ARCH_V5TEJ, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("fa606te", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("fa616te", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("fa626te", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("fmp626", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("fa726te", ARM_ARCH_V5TE, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm1136js", ARM_ARCH_V6, FPU_NONE, "ARM1136J-S"),
ARM_CPU_OPT ("arm1136j-s", ARM_ARCH_V6, FPU_NONE, NULL),
ARM_CPU_OPT ("arm1136jfs", ARM_ARCH_V6, FPU_ARCH_VFP_V2,
"ARM1136JF-S"),
ARM_CPU_OPT ("arm1136jf-s", ARM_ARCH_V6, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("mpcore", ARM_ARCH_V6K, FPU_ARCH_VFP_V2, "MPCore"),
ARM_CPU_OPT ("mpcorenovfp", ARM_ARCH_V6K, FPU_NONE, "MPCore"),
ARM_CPU_OPT ("arm1156t2-s", ARM_ARCH_V6T2, FPU_NONE, NULL),
ARM_CPU_OPT ("arm1156t2f-s", ARM_ARCH_V6T2, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("arm1176jz-s", ARM_ARCH_V6ZK, FPU_NONE, NULL),
ARM_CPU_OPT ("arm1176jzf-s", ARM_ARCH_V6ZK, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("cortex-a5", ARM_ARCH_V7A_MP_SEC,
FPU_NONE, "Cortex-A5"),
ARM_CPU_OPT ("cortex-a7", ARM_ARCH_V7VE, FPU_ARCH_NEON_VFP_V4,
"Cortex-A7"),
ARM_CPU_OPT ("cortex-a8", ARM_ARCH_V7A_SEC,
ARM_FEATURE (0, FPU_VFP_V3
| FPU_NEON_EXT_V1),
"Cortex-A8"),
ARM_CPU_OPT ("cortex-a9", ARM_ARCH_V7A_MP_SEC,
ARM_FEATURE (0, FPU_VFP_V3
| FPU_NEON_EXT_V1),
"Cortex-A9"),
ARM_CPU_OPT ("cortex-a12", ARM_ARCH_V7VE, FPU_ARCH_NEON_VFP_V4,
"Cortex-A12"),
ARM_CPU_OPT ("cortex-a15", ARM_ARCH_V7VE, FPU_ARCH_NEON_VFP_V4,
"Cortex-A15"),
ARM_CPU_OPT ("cortex-a17", ARM_ARCH_V7VE, FPU_ARCH_NEON_VFP_V4,
"Cortex-A17"),
ARM_CPU_OPT ("cortex-a53", ARM_ARCH_V8A, FPU_ARCH_CRYPTO_NEON_VFP_ARMV8,
"Cortex-A53"),
ARM_CPU_OPT ("cortex-a57", ARM_ARCH_V8A, FPU_ARCH_CRYPTO_NEON_VFP_ARMV8,
"Cortex-A57"),
ARM_CPU_OPT ("cortex-a72", ARM_ARCH_V8A, FPU_ARCH_CRYPTO_NEON_VFP_ARMV8,
"Cortex-A72"),
ARM_CPU_OPT ("cortex-r4", ARM_ARCH_V7R, FPU_NONE, "Cortex-R4"),
ARM_CPU_OPT ("cortex-r4f", ARM_ARCH_V7R, FPU_ARCH_VFP_V3D16,
"Cortex-R4F"),
ARM_CPU_OPT ("cortex-r5", ARM_ARCH_V7R_IDIV,
FPU_NONE, "Cortex-R5"),
ARM_CPU_OPT ("cortex-r7", ARM_ARCH_V7R_IDIV,
FPU_ARCH_VFP_V3D16,
"Cortex-R7"),
ARM_CPU_OPT ("cortex-m7", ARM_ARCH_V7EM, FPU_NONE, "Cortex-M7"),
ARM_CPU_OPT ("cortex-m4", ARM_ARCH_V7EM, FPU_NONE, "Cortex-M4"),
ARM_CPU_OPT ("cortex-m3", ARM_ARCH_V7M, FPU_NONE, "Cortex-M3"),
ARM_CPU_OPT ("cortex-m1", ARM_ARCH_V6SM, FPU_NONE, "Cortex-M1"),
ARM_CPU_OPT ("cortex-m0", ARM_ARCH_V6SM, FPU_NONE, "Cortex-M0"),
ARM_CPU_OPT ("cortex-m0plus", ARM_ARCH_V6SM, FPU_NONE, "Cortex-M0+"),
/* ??? XSCALE is really an architecture. */
ARM_CPU_OPT ("xscale", ARM_ARCH_XSCALE, FPU_ARCH_VFP_V2, NULL),
/* ??? iwmmxt is not a processor. */
ARM_CPU_OPT ("iwmmxt", ARM_ARCH_IWMMXT, FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("iwmmxt2", ARM_ARCH_IWMMXT2,FPU_ARCH_VFP_V2, NULL),
ARM_CPU_OPT ("i80200", ARM_ARCH_XSCALE, FPU_ARCH_VFP_V2, NULL),
/* Maverick */
ARM_CPU_OPT ("ep9312", ARM_FEATURE (ARM_AEXT_V4T, ARM_CEXT_MAVERICK),
FPU_ARCH_MAVERICK, "ARM920T"),
/* Marvell processors. */
ARM_CPU_OPT ("marvell-pj4", ARM_FEATURE (ARM_AEXT_V7A | ARM_EXT_MP | ARM_EXT_SEC, 0),
FPU_ARCH_VFP_V3D16, NULL),
ARM_CPU_OPT ("marvell-whitney", ARM_FEATURE (ARM_AEXT_V7A | ARM_EXT_MP
| ARM_EXT_SEC, 0),
FPU_ARCH_NEON_VFP_V4, NULL),
/* APM X-Gene family. */
ARM_CPU_OPT ("xgene1", ARM_ARCH_V8A, FPU_ARCH_CRYPTO_NEON_VFP_ARMV8,
"APM X-Gene 1"),
ARM_CPU_OPT ("xgene2", ARM_ARCH_V8A, FPU_ARCH_CRYPTO_NEON_VFP_ARMV8,
"APM X-Gene 2"),
{ NULL, 0, ARM_ARCH_NONE, ARM_ARCH_NONE, NULL }
};
#undef ARM_CPU_OPT
struct arm_arch_option_table
{
char *name;
size_t name_len;
const arm_feature_set value;
const arm_feature_set default_fpu;
};
/* This list should, at a minimum, contain all the architecture names
recognized by GCC. */
#define ARM_ARCH_OPT(N, V, DF) { N, sizeof (N) - 1, V, DF }
static const struct arm_arch_option_table arm_archs[] =
{
ARM_ARCH_OPT ("all", ARM_ANY, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv1", ARM_ARCH_V1, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv2", ARM_ARCH_V2, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv2a", ARM_ARCH_V2S, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv2s", ARM_ARCH_V2S, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv3", ARM_ARCH_V3, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv3m", ARM_ARCH_V3M, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv4", ARM_ARCH_V4, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv4xm", ARM_ARCH_V4xM, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv4t", ARM_ARCH_V4T, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv4txm", ARM_ARCH_V4TxM, FPU_ARCH_FPA),
ARM_ARCH_OPT ("armv5", ARM_ARCH_V5, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv5t", ARM_ARCH_V5T, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv5txm", ARM_ARCH_V5TxM, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv5te", ARM_ARCH_V5TE, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv5texp", ARM_ARCH_V5TExP, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv5tej", ARM_ARCH_V5TEJ, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6", ARM_ARCH_V6, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6j", ARM_ARCH_V6, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6k", ARM_ARCH_V6K, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6z", ARM_ARCH_V6Z, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6zk", ARM_ARCH_V6ZK, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6t2", ARM_ARCH_V6T2, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6kt2", ARM_ARCH_V6KT2, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6zt2", ARM_ARCH_V6ZT2, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6zkt2", ARM_ARCH_V6ZKT2, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6-m", ARM_ARCH_V6M, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv6s-m", ARM_ARCH_V6SM, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7", ARM_ARCH_V7, FPU_ARCH_VFP),
/* The official spelling of the ARMv7 profile variants is the dashed form.
Accept the non-dashed form for compatibility with old toolchains. */
ARM_ARCH_OPT ("armv7a", ARM_ARCH_V7A, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7ve", ARM_ARCH_V7VE, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7r", ARM_ARCH_V7R, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7m", ARM_ARCH_V7M, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7-a", ARM_ARCH_V7A, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7-r", ARM_ARCH_V7R, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7-m", ARM_ARCH_V7M, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv7e-m", ARM_ARCH_V7EM, FPU_ARCH_VFP),
ARM_ARCH_OPT ("armv8-a", ARM_ARCH_V8A, FPU_ARCH_VFP),
ARM_ARCH_OPT ("xscale", ARM_ARCH_XSCALE, FPU_ARCH_VFP),
ARM_ARCH_OPT ("iwmmxt", ARM_ARCH_IWMMXT, FPU_ARCH_VFP),
ARM_ARCH_OPT ("iwmmxt2", ARM_ARCH_IWMMXT2,FPU_ARCH_VFP),
{ NULL, 0, ARM_ARCH_NONE, ARM_ARCH_NONE }
};
#undef ARM_ARCH_OPT
/* ISA extensions in the co-processor and main instruction set space. */
struct arm_option_extension_value_table
{
char *name;
size_t name_len;
const arm_feature_set merge_value;
const arm_feature_set clear_value;
const arm_feature_set allowed_archs;
};
/* The following table must be in alphabetical order with a NULL last entry.
*/
#define ARM_EXT_OPT(N, M, C, AA) { N, sizeof (N) - 1, M, C, AA }
static const struct arm_option_extension_value_table arm_extensions[] =
{
ARM_EXT_OPT ("crc", ARCH_CRC_ARMV8, ARM_FEATURE (0, CRC_EXT_ARMV8),
ARM_FEATURE (ARM_EXT_V8, 0)),
ARM_EXT_OPT ("crypto", FPU_ARCH_CRYPTO_NEON_VFP_ARMV8,
ARM_FEATURE (0, FPU_CRYPTO_ARMV8),
ARM_FEATURE (ARM_EXT_V8, 0)),
ARM_EXT_OPT ("fp", FPU_ARCH_VFP_ARMV8, ARM_FEATURE (0, FPU_VFP_ARMV8),
ARM_FEATURE (ARM_EXT_V8, 0)),
ARM_EXT_OPT ("idiv", ARM_FEATURE (ARM_EXT_ADIV | ARM_EXT_DIV, 0),
ARM_FEATURE (ARM_EXT_ADIV | ARM_EXT_DIV, 0),
ARM_FEATURE (ARM_EXT_V7A | ARM_EXT_V7R, 0)),
ARM_EXT_OPT ("iwmmxt",ARM_FEATURE (0, ARM_CEXT_IWMMXT),
ARM_FEATURE (0, ARM_CEXT_IWMMXT), ARM_ANY),
ARM_EXT_OPT ("iwmmxt2", ARM_FEATURE (0, ARM_CEXT_IWMMXT2),
ARM_FEATURE (0, ARM_CEXT_IWMMXT2), ARM_ANY),
ARM_EXT_OPT ("maverick", ARM_FEATURE (0, ARM_CEXT_MAVERICK),
ARM_FEATURE (0, ARM_CEXT_MAVERICK), ARM_ANY),
ARM_EXT_OPT ("mp", ARM_FEATURE (ARM_EXT_MP, 0),
ARM_FEATURE (ARM_EXT_MP, 0),
ARM_FEATURE (ARM_EXT_V7A | ARM_EXT_V7R, 0)),
ARM_EXT_OPT ("simd", FPU_ARCH_NEON_VFP_ARMV8,
ARM_FEATURE(0, FPU_NEON_ARMV8),
ARM_FEATURE (ARM_EXT_V8, 0)),
ARM_EXT_OPT ("os", ARM_FEATURE (ARM_EXT_OS, 0),
ARM_FEATURE (ARM_EXT_OS, 0),
ARM_FEATURE (ARM_EXT_V6M, 0)),
ARM_EXT_OPT ("sec", ARM_FEATURE (ARM_EXT_SEC, 0),
ARM_FEATURE (ARM_EXT_SEC, 0),
ARM_FEATURE (ARM_EXT_V6K | ARM_EXT_V7A, 0)),
ARM_EXT_OPT ("virt", ARM_FEATURE (ARM_EXT_VIRT | ARM_EXT_ADIV
| ARM_EXT_DIV, 0),
ARM_FEATURE (ARM_EXT_VIRT, 0),
ARM_FEATURE (ARM_EXT_V7A, 0)),
ARM_EXT_OPT ("xscale",ARM_FEATURE (0, ARM_CEXT_XSCALE),
ARM_FEATURE (0, ARM_CEXT_XSCALE), ARM_ANY),
{ NULL, 0, ARM_ARCH_NONE, ARM_ARCH_NONE, ARM_ARCH_NONE }
};
#undef ARM_EXT_OPT
/* ISA floating-point and Advanced SIMD extensions. */
struct arm_option_fpu_value_table
{
char *name;
const arm_feature_set value;
};
/* This list should, at a minimum, contain all the fpu names
recognized by GCC. */
static const struct arm_option_fpu_value_table arm_fpus[] =
{
{"softfpa", FPU_NONE},
{"fpe", FPU_ARCH_FPE},
{"fpe2", FPU_ARCH_FPE},
{"fpe3", FPU_ARCH_FPA}, /* Third release supports LFM/SFM. */
{"fpa", FPU_ARCH_FPA},
{"fpa10", FPU_ARCH_FPA},
{"fpa11", FPU_ARCH_FPA},
{"arm7500fe", FPU_ARCH_FPA},
{"softvfp", FPU_ARCH_VFP},
{"softvfp+vfp", FPU_ARCH_VFP_V2},
{"vfp", FPU_ARCH_VFP_V2},
{"vfp9", FPU_ARCH_VFP_V2},
{"vfp3", FPU_ARCH_VFP_V3}, /* For backwards compatbility. */
{"vfp10", FPU_ARCH_VFP_V2},
{"vfp10-r0", FPU_ARCH_VFP_V1},
{"vfpxd", FPU_ARCH_VFP_V1xD},
{"vfpv2", FPU_ARCH_VFP_V2},
{"vfpv3", FPU_ARCH_VFP_V3},
{"vfpv3-fp16", FPU_ARCH_VFP_V3_FP16},
{"vfpv3-d16", FPU_ARCH_VFP_V3D16},
{"vfpv3-d16-fp16", FPU_ARCH_VFP_V3D16_FP16},
{"vfpv3xd", FPU_ARCH_VFP_V3xD},
{"vfpv3xd-fp16", FPU_ARCH_VFP_V3xD_FP16},
{"arm1020t", FPU_ARCH_VFP_V1},
{"arm1020e", FPU_ARCH_VFP_V2},
{"arm1136jfs", FPU_ARCH_VFP_V2},
{"arm1136jf-s", FPU_ARCH_VFP_V2},
{"maverick", FPU_ARCH_MAVERICK},
{"neon", FPU_ARCH_VFP_V3_PLUS_NEON_V1},
{"neon-fp16", FPU_ARCH_NEON_FP16},
{"vfpv4", FPU_ARCH_VFP_V4},
{"vfpv4-d16", FPU_ARCH_VFP_V4D16},
{"fpv4-sp-d16", FPU_ARCH_VFP_V4_SP_D16},
{"fpv5-d16", FPU_ARCH_VFP_V5D16},
{"fpv5-sp-d16", FPU_ARCH_VFP_V5_SP_D16},
{"neon-vfpv4", FPU_ARCH_NEON_VFP_V4},
{"fp-armv8", FPU_ARCH_VFP_ARMV8},
{"neon-fp-armv8", FPU_ARCH_NEON_VFP_ARMV8},
{"crypto-neon-fp-armv8",
FPU_ARCH_CRYPTO_NEON_VFP_ARMV8},
{NULL, ARM_ARCH_NONE}
};
struct arm_option_value_table
{
char *name;
long value;
};
static const struct arm_option_value_table arm_float_abis[] =
{
{"hard", ARM_FLOAT_ABI_HARD},
{"softfp", ARM_FLOAT_ABI_SOFTFP},
{"soft", ARM_FLOAT_ABI_SOFT},
{NULL, 0}
};
#ifdef OBJ_ELF
/* We only know how to output GNU and ver 4/5 (AAELF) formats. */
static const struct arm_option_value_table arm_eabis[] =
{
{"gnu", EF_ARM_EABI_UNKNOWN},
{"4", EF_ARM_EABI_VER4},
{"5", EF_ARM_EABI_VER5},
{NULL, 0}
};
#endif
struct arm_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 bfd_boolean
arm_parse_extension (char *str, const arm_feature_set **opt_p)
{
arm_feature_set *ext_set = (arm_feature_set *)
xmalloc (sizeof (arm_feature_set));
/* We insist on extensions being specified in alphabetical order, and with
extensions being added before being removed. We achieve this by having
the global ARM_EXTENSIONS table in alphabetical order, and 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. */
const struct arm_option_extension_value_table * opt = NULL;
int adding_value = -1;
/* Copy the feature set, so that we can modify it. */
*ext_set = **opt_p;
*opt_p = ext_set;
while (str != NULL && *str != 0)
{
char *ext;
size_t len;
if (*str != '+')
{
as_bad (_("invalid architectural extension"));
return FALSE;
}
str++;
ext = strchr (str, '+');
if (ext != NULL)
len = ext - str;
else
len = strlen (str);
if (len >= 2 && strncmp (str, "no", 2) == 0)
{
if (adding_value != 0)
{
adding_value = 0;
opt = arm_extensions;
}
len -= 2;
str += 2;
}
else if (len > 0)
{
if (adding_value == -1)
{
adding_value = 1;
opt = arm_extensions;
}
else if (adding_value != 1)
{
as_bad (_("must specify extensions to add before specifying "
"those to remove"));
return FALSE;
}
}
if (len == 0)
{
as_bad (_("missing architectural extension"));
return FALSE;
}
gas_assert (adding_value != -1);
gas_assert (opt != NULL);
/* Scan over the options table trying to find an exact match. */
for (; opt->name != NULL; opt++)
if (opt->name_len == len && strncmp (opt->name, str, len) == 0)
{
/* Check we can apply the extension to this architecture. */
if (!ARM_CPU_HAS_FEATURE (*ext_set, opt->allowed_archs))
{
as_bad (_("extension does not apply to the base architecture"));
return FALSE;
}
/* Add or remove the extension. */
if (adding_value)
ARM_MERGE_FEATURE_SETS (*ext_set, *ext_set, opt->merge_value);
else
ARM_CLEAR_FEATURE (*ext_set, *ext_set, opt->clear_value);
break;
}
if (opt->name == NULL)
{
/* Did we fail to find an extension because it wasn't specified in
alphabetical order, or because it does not exist? */
for (opt = arm_extensions; opt->name != NULL; opt++)
if (opt->name_len == len && strncmp (opt->name, str, len) == 0)
break;
if (opt->name == NULL)
as_bad (_("unknown architectural extension `%s'"), str);
else
as_bad (_("architectural extensions must be specified in "
"alphabetical order"));
return FALSE;
}
else
{
/* We should skip the extension we've just matched the next time
round. */
opt++;
}
str = ext;
};
return TRUE;
}
static bfd_boolean
arm_parse_cpu (char *str)
{
const struct arm_cpu_option_table *opt;
char *ext = strchr (str, '+');
size_t len;
if (ext != NULL)
len = ext - str;
else
len = strlen (str);
if (len == 0)
{
as_bad (_("missing cpu name `%s'"), str);
return FALSE;
}
for (opt = arm_cpus; opt->name != NULL; opt++)
if (opt->name_len == len && strncmp (opt->name, str, len) == 0)
{
mcpu_cpu_opt = &opt->value;
mcpu_fpu_opt = &opt->default_fpu;
if (opt->canonical_name)
strcpy (selected_cpu_name, opt->canonical_name);
else
{
size_t i;
for (i = 0; i < len; i++)
selected_cpu_name[i] = TOUPPER (opt->name[i]);
selected_cpu_name[i] = 0;
}
if (ext != NULL)
return arm_parse_extension (ext, &mcpu_cpu_opt);
return TRUE;
}
as_bad (_("unknown cpu `%s'"), str);
return FALSE;
}
static bfd_boolean
arm_parse_arch (char *str)
{
const struct arm_arch_option_table *opt;
char *ext = strchr (str, '+');
size_t len;
if (ext != NULL)
len = ext - str;
else
len = strlen (str);
if (len == 0)
{
as_bad (_("missing architecture name `%s'"), str);
return FALSE;
}
for (opt = arm_archs; opt->name != NULL; opt++)
if (opt->name_len == len && strncmp (opt->name, str, len) == 0)
{
march_cpu_opt = &opt->value;
march_fpu_opt = &opt->default_fpu;
strcpy (selected_cpu_name, opt->name);
if (ext != NULL)
return arm_parse_extension (ext, &march_cpu_opt);
return TRUE;
}
as_bad (_("unknown architecture `%s'\n"), str);
return FALSE;
}
static bfd_boolean
arm_parse_fpu (char * str)
{
const struct arm_option_fpu_value_table * opt;
for (opt = arm_fpus; opt->name != NULL; opt++)
if (streq (opt->name, str))
{
mfpu_opt = &opt->value;
return TRUE;
}
as_bad (_("unknown floating point format `%s'\n"), str);
return FALSE;
}
static bfd_boolean
arm_parse_float_abi (char * str)
{
const struct arm_option_value_table * opt;
for (opt = arm_float_abis; opt->name != NULL; opt++)
if (streq (opt->name, str))
{
mfloat_abi_opt = opt->value;
return TRUE;
}
as_bad (_("unknown floating point abi `%s'\n"), str);
return FALSE;
}
#ifdef OBJ_ELF
static bfd_boolean
arm_parse_eabi (char * str)
{
const struct arm_option_value_table *opt;
for (opt = arm_eabis; opt->name != NULL; opt++)
if (streq (opt->name, str))
{
meabi_flags = opt->value;
return TRUE;
}
as_bad (_("unknown EABI `%s'\n"), str);
return FALSE;
}
#endif
static bfd_boolean
arm_parse_it_mode (char * str)
{
bfd_boolean ret = TRUE;
if (streq ("arm", str))
implicit_it_mode = IMPLICIT_IT_MODE_ARM;
else if (streq ("thumb", str))
implicit_it_mode = IMPLICIT_IT_MODE_THUMB;
else if (streq ("always", str))
implicit_it_mode = IMPLICIT_IT_MODE_ALWAYS;
else if (streq ("never", str))
implicit_it_mode = IMPLICIT_IT_MODE_NEVER;
else
{
as_bad (_("unknown implicit IT mode `%s', should be "\
"arm, thumb, always, or never."), str);
ret = FALSE;
}
return ret;
}
static bfd_boolean
arm_ccs_mode (char * unused ATTRIBUTE_UNUSED)
{
codecomposer_syntax = TRUE;
arm_comment_chars[0] = ';';
arm_line_separator_chars[0] = 0;
return TRUE;
}
struct arm_long_option_table arm_long_opts[] =
{
{"mcpu=", N_("<cpu name>\t assemble for CPU <cpu name>"),
arm_parse_cpu, NULL},
{"march=", N_("<arch name>\t assemble for architecture <arch name>"),
arm_parse_arch, NULL},
{"mfpu=", N_("<fpu name>\t assemble for FPU architecture <fpu name>"),
arm_parse_fpu, NULL},
{"mfloat-abi=", N_("<abi>\t assemble for floating point ABI <abi>"),
arm_parse_float_abi, NULL},
#ifdef OBJ_ELF
{"meabi=", N_("<ver>\t\t assemble for eabi version <ver>"),
arm_parse_eabi, NULL},
#endif
{"mimplicit-it=", N_("<mode>\t controls implicit insertion of IT instructions"),
arm_parse_it_mode, NULL},
{"mccs", N_("\t\t\t TI CodeComposer Studio syntax compatibility mode"),
arm_ccs_mode, NULL},
{NULL, NULL, 0, NULL}
};
int
md_parse_option (int c, char * arg)
{
struct arm_option_table *opt;
const struct arm_legacy_option_table *fopt;
struct arm_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 OPTION_FIX_V4BX:
fix_v4bx = TRUE;
break;
case 'a':
/* Listing option. Just ignore these, we don't support additional
ones. */
return 0;
default:
for (opt = arm_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 (warn_on_deprecated && 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 (fopt = arm_legacy_opts; fopt->option != NULL; fopt++)
{
if (c == fopt->option[0]
&& ((arg == NULL && fopt->option[1] == 0)
|| streq (arg, fopt->option + 1)))
{
/* If the option is deprecated, tell the user. */
if (warn_on_deprecated && fopt->deprecated != NULL)
as_tsktsk (_("option `-%c%s' is deprecated: %s"), c,
arg ? arg : "", _(fopt->deprecated));
if (fopt->var != NULL)
*fopt->var = &fopt->value;
return 1;
}
}
for (lopt = arm_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 (warn_on_deprecated && 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 arm_option_table *opt;
struct arm_long_option_table *lopt;
fprintf (fp, _(" ARM-specific assembler options:\n"));
for (opt = arm_opts; opt->option != NULL; opt++)
if (opt->help != NULL)
fprintf (fp, " -%-23s%s\n", opt->option, _(opt->help));
for (lopt = arm_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
fprintf (fp, _("\
--fix-v4bx Allow BX in ARMv4 code\n"));
}
#ifdef OBJ_ELF
typedef struct
{
int val;
arm_feature_set flags;
} cpu_arch_ver_table;
/* Mapping from CPU features to EABI CPU arch values. Table must be sorted
least features first. */
static const cpu_arch_ver_table cpu_arch_ver[] =
{
{1, ARM_ARCH_V4},
{2, ARM_ARCH_V4T},
{3, ARM_ARCH_V5},
{3, ARM_ARCH_V5T},
{4, ARM_ARCH_V5TE},
{5, ARM_ARCH_V5TEJ},
{6, ARM_ARCH_V6},
{9, ARM_ARCH_V6K},
{7, ARM_ARCH_V6Z},
{11, ARM_ARCH_V6M},
{12, ARM_ARCH_V6SM},
{8, ARM_ARCH_V6T2},
{10, ARM_ARCH_V7VE},
{10, ARM_ARCH_V7R},
{10, ARM_ARCH_V7M},
{14, ARM_ARCH_V8A},
{0, ARM_ARCH_NONE}
};
/* Set an attribute if it has not already been set by the user. */
static void
aeabi_set_attribute_int (int tag, int value)
{
if (tag < 1
|| tag >= NUM_KNOWN_OBJ_ATTRIBUTES
|| !attributes_set_explicitly[tag])
bfd_elf_add_proc_attr_int (stdoutput, tag, value);
}
static void
aeabi_set_attribute_string (int tag, const char *value)
{
if (tag < 1
|| tag >= NUM_KNOWN_OBJ_ATTRIBUTES
|| !attributes_set_explicitly[tag])
bfd_elf_add_proc_attr_string (stdoutput, tag, value);
}
/* Set the public EABI object attributes. */
void
aeabi_set_public_attributes (void)
{
int arch;
char profile;
int virt_sec = 0;
int fp16_optional = 0;
arm_feature_set flags;
arm_feature_set tmp;
const cpu_arch_ver_table *p;
/* Choose the architecture based on the capabilities of the requested cpu
(if any) and/or the instructions actually used. */
ARM_MERGE_FEATURE_SETS (flags, arm_arch_used, thumb_arch_used);
ARM_MERGE_FEATURE_SETS (flags, flags, *mfpu_opt);
ARM_MERGE_FEATURE_SETS (flags, flags, selected_cpu);
if (ARM_CPU_HAS_FEATURE (arm_arch_used, arm_arch_any))
ARM_MERGE_FEATURE_SETS (flags, flags, arm_ext_v1);
if (ARM_CPU_HAS_FEATURE (thumb_arch_used, arm_arch_any))
ARM_MERGE_FEATURE_SETS (flags, flags, arm_ext_v4t);
selected_cpu = flags;
/* Allow the user to override the reported architecture. */
if (object_arch)
{
ARM_CLEAR_FEATURE (flags, flags, arm_arch_any);
ARM_MERGE_FEATURE_SETS (flags, flags, *object_arch);
}
/* We need to make sure that the attributes do not identify us as v6S-M
when the only v6S-M feature in use is the Operating System Extensions. */
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_os))
if (!ARM_CPU_HAS_FEATURE (flags, arm_arch_v6m_only))
ARM_CLEAR_FEATURE (flags, flags, arm_ext_os);
tmp = flags;
arch = 0;
for (p = cpu_arch_ver; p->val; p++)
{
if (ARM_CPU_HAS_FEATURE (tmp, p->flags))
{
arch = p->val;
ARM_CLEAR_FEATURE (tmp, tmp, p->flags);
}
}
/* The table lookup above finds the last architecture to contribute
a new feature. Unfortunately, Tag13 is a subset of the union of
v6T2 and v7-M, so it is never seen as contributing a new feature.
We can not search for the last entry which is entirely used,
because if no CPU is specified we build up only those flags
actually used. Perhaps we should separate out the specified
and implicit cases. Avoid taking this path for -march=all by
checking for contradictory v7-A / v7-M features. */
if (arch == 10
&& !ARM_CPU_HAS_FEATURE (flags, arm_ext_v7a)
&& ARM_CPU_HAS_FEATURE (flags, arm_ext_v7m)
&& ARM_CPU_HAS_FEATURE (flags, arm_ext_v6_dsp))
arch = 13;
/* Tag_CPU_name. */
if (selected_cpu_name[0])
{
char *q;
q = selected_cpu_name;
if (strncmp (q, "armv", 4) == 0)
{
int i;
q += 4;
for (i = 0; q[i]; i++)
q[i] = TOUPPER (q[i]);
}
aeabi_set_attribute_string (Tag_CPU_name, q);
}
/* Tag_CPU_arch. */
aeabi_set_attribute_int (Tag_CPU_arch, arch);
/* Tag_CPU_arch_profile. */
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_v7a))
profile = 'A';
else if (ARM_CPU_HAS_FEATURE (flags, arm_ext_v7r))
profile = 'R';
else if (ARM_CPU_HAS_FEATURE (flags, arm_ext_m))
profile = 'M';
else
profile = '\0';
if (profile != '\0')
aeabi_set_attribute_int (Tag_CPU_arch_profile, profile);
/* Tag_ARM_ISA_use. */
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_v1)
|| arch == 0)
aeabi_set_attribute_int (Tag_ARM_ISA_use, 1);
/* Tag_THUMB_ISA_use. */
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_v4t)
|| arch == 0)
aeabi_set_attribute_int (Tag_THUMB_ISA_use,
ARM_CPU_HAS_FEATURE (flags, arm_arch_t2) ? 2 : 1);
/* Tag_VFP_arch. */
if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_armv8xd))
aeabi_set_attribute_int (Tag_VFP_arch,
ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_d32)
? 7 : 8);
else if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_fma))
aeabi_set_attribute_int (Tag_VFP_arch,
ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_d32)
? 5 : 6);
else if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_d32))
{
fp16_optional = 1;
aeabi_set_attribute_int (Tag_VFP_arch, 3);
}
else if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_v3xd))
{
aeabi_set_attribute_int (Tag_VFP_arch, 4);
fp16_optional = 1;
}
else if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_v2))
aeabi_set_attribute_int (Tag_VFP_arch, 2);
else if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_v1)
|| ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_v1xd))
aeabi_set_attribute_int (Tag_VFP_arch, 1);
/* Tag_ABI_HardFP_use. */
if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_v1xd)
&& !ARM_CPU_HAS_FEATURE (flags, fpu_vfp_ext_v1))
aeabi_set_attribute_int (Tag_ABI_HardFP_use, 1);
/* Tag_WMMX_arch. */
if (ARM_CPU_HAS_FEATURE (flags, arm_cext_iwmmxt2))
aeabi_set_attribute_int (Tag_WMMX_arch, 2);
else if (ARM_CPU_HAS_FEATURE (flags, arm_cext_iwmmxt))
aeabi_set_attribute_int (Tag_WMMX_arch, 1);
/* Tag_Advanced_SIMD_arch (formerly Tag_NEON_arch). */
if (ARM_CPU_HAS_FEATURE (flags, fpu_neon_ext_armv8))
aeabi_set_attribute_int (Tag_Advanced_SIMD_arch, 3);
else if (ARM_CPU_HAS_FEATURE (flags, fpu_neon_ext_v1))
{
if (ARM_CPU_HAS_FEATURE (flags, fpu_neon_ext_fma))
{
aeabi_set_attribute_int (Tag_Advanced_SIMD_arch, 2);
}
else
{
aeabi_set_attribute_int (Tag_Advanced_SIMD_arch, 1);
fp16_optional = 1;
}
}
/* Tag_VFP_HP_extension (formerly Tag_NEON_FP16_arch). */
if (ARM_CPU_HAS_FEATURE (flags, fpu_vfp_fp16) && fp16_optional)
aeabi_set_attribute_int (Tag_VFP_HP_extension, 1);
/* Tag_DIV_use.
We set Tag_DIV_use to two when integer divide instructions have been used
in ARM state, or when Thumb integer divide instructions have been used,
but we have no architecture profile set, nor have we any ARM instructions.
For ARMv8 we set the tag to 0 as integer divide is implied by the base
architecture.
For new architectures we will have to check these tests. */
gas_assert (arch <= TAG_CPU_ARCH_V8);
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_v8))
aeabi_set_attribute_int (Tag_DIV_use, 0);
else if (ARM_CPU_HAS_FEATURE (flags, arm_ext_adiv)
|| (profile == '\0'
&& ARM_CPU_HAS_FEATURE (flags, arm_ext_div)
&& !ARM_CPU_HAS_FEATURE (arm_arch_used, arm_arch_any)))
aeabi_set_attribute_int (Tag_DIV_use, 2);
/* Tag_MP_extension_use. */
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_mp))
aeabi_set_attribute_int (Tag_MPextension_use, 1);
/* Tag Virtualization_use. */
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_sec))
virt_sec |= 1;
if (ARM_CPU_HAS_FEATURE (flags, arm_ext_virt))
virt_sec |= 2;
if (virt_sec != 0)
aeabi_set_attribute_int (Tag_Virtualization_use, virt_sec);
}
/* Add the default contents for the .ARM.attributes section. */
void
arm_md_end (void)
{
if (EF_ARM_EABI_VERSION (meabi_flags) < EF_ARM_EABI_VER4)
return;
aeabi_set_public_attributes ();
}
#endif /* OBJ_ELF */
/* Parse a .cpu directive. */
static void
s_arm_cpu (int ignored ATTRIBUTE_UNUSED)
{
const struct arm_cpu_option_table *opt;
char *name;
char saved_char;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
/* Skip the first "all" entry. */
for (opt = arm_cpus + 1; opt->name != NULL; opt++)
if (streq (opt->name, name))
{
mcpu_cpu_opt = &opt->value;
selected_cpu = opt->value;
if (opt->canonical_name)
strcpy (selected_cpu_name, opt->canonical_name);
else
{
int i;
for (i = 0; opt->name[i]; i++)
selected_cpu_name[i] = TOUPPER (opt->name[i]);
selected_cpu_name[i] = 0;
}
ARM_MERGE_FEATURE_SETS (cpu_variant, *mcpu_cpu_opt, *mfpu_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_arm_arch (int ignored ATTRIBUTE_UNUSED)
{
const struct arm_arch_option_table *opt;
char saved_char;
char *name;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
/* Skip the first "all" entry. */
for (opt = arm_archs + 1; opt->name != NULL; opt++)
if (streq (opt->name, name))
{
mcpu_cpu_opt = &opt->value;
selected_cpu = opt->value;
strcpy (selected_cpu_name, opt->name);
ARM_MERGE_FEATURE_SETS (cpu_variant, *mcpu_cpu_opt, *mfpu_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 .object_arch directive. */
static void
s_arm_object_arch (int ignored ATTRIBUTE_UNUSED)
{
const struct arm_arch_option_table *opt;
char saved_char;
char *name;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
/* Skip the first "all" entry. */
for (opt = arm_archs + 1; opt->name != NULL; opt++)
if (streq (opt->name, name))
{
object_arch = &opt->value;
*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_arm_arch_extension (int ignored ATTRIBUTE_UNUSED)
{
const struct arm_option_extension_value_table *opt;
char saved_char;
char *name;
int adding_value = 1;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
if (strlen (name) >= 2
&& strncmp (name, "no", 2) == 0)
{
adding_value = 0;
name += 2;
}
for (opt = arm_extensions; opt->name != NULL; opt++)
if (streq (opt->name, name))
{
if (!ARM_CPU_HAS_FEATURE (*mcpu_cpu_opt, opt->allowed_archs))
{
as_bad (_("architectural extension `%s' is not allowed for the "
"current base architecture"), name);
break;
}
if (adding_value)
ARM_MERGE_FEATURE_SETS (selected_cpu, selected_cpu,
opt->merge_value);
else
ARM_CLEAR_FEATURE (selected_cpu, selected_cpu, opt->clear_value);
mcpu_cpu_opt = &selected_cpu;
ARM_MERGE_FEATURE_SETS (cpu_variant, *mcpu_cpu_opt, *mfpu_opt);
*input_line_pointer = saved_char;
demand_empty_rest_of_line ();
return;
}
if (opt->name == NULL)
as_bad (_("unknown architecture extension `%s'\n"), name);
*input_line_pointer = saved_char;
ignore_rest_of_line ();
}
/* Parse a .fpu directive. */
static void
s_arm_fpu (int ignored ATTRIBUTE_UNUSED)
{
const struct arm_option_fpu_value_table *opt;
char saved_char;
char *name;
name = input_line_pointer;
while (*input_line_pointer && !ISSPACE (*input_line_pointer))
input_line_pointer++;
saved_char = *input_line_pointer;
*input_line_pointer = 0;
for (opt = arm_fpus; opt->name != NULL; opt++)
if (streq (opt->name, name))
{
mfpu_opt = &opt->value;
ARM_MERGE_FEATURE_SETS (cpu_variant, *mcpu_cpu_opt, *mfpu_opt);
*input_line_pointer = saved_char;
demand_empty_rest_of_line ();
return;
}
as_bad (_("unknown floating point format `%s'\n"), name);
*input_line_pointer = saved_char;
ignore_rest_of_line ();
}
/* Copy symbol information. */
void
arm_copy_symbol_attributes (symbolS *dest, symbolS *src)
{
ARM_GET_FLAG (dest) = ARM_GET_FLAG (src);
}
#ifdef OBJ_ELF
/* Given a symbolic attribute NAME, return the proper integer value.
Returns -1 if the attribute is not known. */
int
arm_convert_symbolic_attribute (const char *name)
{
static const struct
{
const char * name;
const int tag;
}
attribute_table[] =
{
/* When you modify this table you should
also modify the list in doc/c-arm.texi. */
#define T(tag) {#tag, tag}
T (Tag_CPU_raw_name),
T (Tag_CPU_name),
T (Tag_CPU_arch),
T (Tag_CPU_arch_profile),
T (Tag_ARM_ISA_use),
T (Tag_THUMB_ISA_use),
T (Tag_FP_arch),
T (Tag_VFP_arch),
T (Tag_WMMX_arch),
T (Tag_Advanced_SIMD_arch),
T (Tag_PCS_config),
T (Tag_ABI_PCS_R9_use),
T (Tag_ABI_PCS_RW_data),
T (Tag_ABI_PCS_RO_data),
T (Tag_ABI_PCS_GOT_use),
T (Tag_ABI_PCS_wchar_t),
T (Tag_ABI_FP_rounding),
T (Tag_ABI_FP_denormal),
T (Tag_ABI_FP_exceptions),
T (Tag_ABI_FP_user_exceptions),
T (Tag_ABI_FP_number_model),
T (Tag_ABI_align_needed),
T (Tag_ABI_align8_needed),
T (Tag_ABI_align_preserved),
T (Tag_ABI_align8_preserved),
T (Tag_ABI_enum_size),
T (Tag_ABI_HardFP_use),
T (Tag_ABI_VFP_args),
T (Tag_ABI_WMMX_args),
T (Tag_ABI_optimization_goals),
T (Tag_ABI_FP_optimization_goals),
T (Tag_compatibility),
T (Tag_CPU_unaligned_access),
T (Tag_FP_HP_extension),
T (Tag_VFP_HP_extension),
T (Tag_ABI_FP_16bit_format),
T (Tag_MPextension_use),
T (Tag_DIV_use),
T (Tag_nodefaults),
T (Tag_also_compatible_with),
T (Tag_conformance),
T (Tag_T2EE_use),
T (Tag_Virtualization_use),
/* We deliberately do not include Tag_MPextension_use_legacy. */
#undef T
};
unsigned int i;
if (name == NULL)
return -1;
for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
if (streq (name, attribute_table[i].name))
return attribute_table[i].tag;
return -1;
}
/* Apply sym value for relocations only in the case that they are for
local symbols in the same segment as the fixup and you have the
respective architectural feature for blx and simple switches. */
int
arm_apply_sym_value (struct fix * fixP, segT this_seg)
{
if (fixP->fx_addsy
&& ARM_CPU_HAS_FEATURE (selected_cpu, arm_ext_v5t)
/* PR 17444: If the local symbol is in a different section then a reloc
will always be generated for it, so applying the symbol value now
will result in a double offset being stored in the relocation. */
&& (S_GET_SEGMENT (fixP->fx_addsy) == this_seg)
&& !S_FORCE_RELOC (fixP->fx_addsy, TRUE))
{
switch (fixP->fx_r_type)
{
case BFD_RELOC_ARM_PCREL_BLX:
case BFD_RELOC_THUMB_PCREL_BRANCH23:
if (ARM_IS_FUNC (fixP->fx_addsy))
return 1;
break;
case BFD_RELOC_ARM_PCREL_CALL:
case BFD_RELOC_THUMB_PCREL_BLX:
if (THUMB_IS_FUNC (fixP->fx_addsy))
return 1;
break;
default:
break;
}
}
return 0;
}
#endif /* OBJ_ELF */
|
optimsoc/gzll-binutils
|
gas/config/tc-arm.c
|
C
|
gpl-2.0
| 748,658
|
/*
* Mach Operating System
* Copyright (c) 1993-1989 Carnegie Mellon University.
* Copyright (c) 1994 The University of Utah and
* the Computer Systems Laboratory (CSL).
* All rights reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON, THE UNIVERSITY OF UTAH AND CSL ALLOW FREE USE OF
* THIS SOFTWARE IN ITS "AS IS" CONDITION, AND DISCLAIM ANY LIABILITY
* OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF
* THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie Mellon
* the rights to redistribute these changes.
*/
#include <mach.h>
#include <device/device.h>
#include <varargs.h>
extern mach_port_t __libmach_console_port;
safe_gets(str, maxlen)
char *str;
int maxlen;
{
register char *lp;
register int c;
char inbuf[IO_INBAND_MAX];
mach_msg_type_number_t count;
register char *ip;
char *strmax = str + maxlen - 1; /* allow space for trailing 0 */
lp = str;
for (;;) {
count = IO_INBAND_MAX;
(void) device_read_inband(__libmach_console_port,
(dev_mode_t)0, (recnum_t)0,
sizeof(inbuf), inbuf, &count);
for (ip = inbuf; ip < &inbuf[count]; ip++) {
c = *ip;
switch (c) {
case '\n':
case '\r':
printf("\n");
*lp++ = 0;
return;
case '\b':
case '#':
case '\177':
if (lp > str) {
printf("\b \b");
lp--;
}
continue;
case '@':
case 'u'&037:
lp = str;
printf("\n\r");
continue;
default:
if (c >= ' ' && c < '\177') {
if (lp < strmax) {
*lp++ = c;
printf("%c", c);
}
else {
printf("%c", '\007'); /* beep */
}
}
}
}
}
}
|
diegonc/console-xkb-support
|
serverboot/gets.c
|
C
|
gpl-2.0
| 2,236
|
/* libdiskfs implementation of fs.defs: dir_link
Copyright (C) 1992,93,94,95,96,97,99 Free Software Foundation, Inc.
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, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */
#include "priv.h"
#include "fs_S.h"
/* Implement dir_link as described in <hurd/fs.defs>. */
kern_return_t
diskfs_S_dir_link (struct protid *dircred,
struct protid *filecred,
char *name,
int excl)
{
struct node *np; /* node being linked */
struct node *tnp; /* node being deleted implicitly */
struct node *dnp; /* directory of new entry */
struct dirstat *ds = alloca (diskfs_dirstat_size);
error_t error;
if (!dircred)
return EOPNOTSUPP;
if (diskfs_check_readonly ())
return EROFS;
if (!filecred)
return EXDEV;
np = filecred->po->np;
mutex_lock (&np->lock);
if (S_ISDIR (np->dn_stat.st_mode))
{
mutex_unlock (&np->lock);
return EISDIR;
}
mutex_unlock (&np->lock);
dnp = dircred->po->np;
mutex_lock (&dnp->lock);
/* Lookup new location */
error = diskfs_lookup (dnp, name, RENAME, &tnp, ds, dircred);
if (!error && excl)
{
error = EEXIST;
diskfs_nput (tnp);
}
if (error && error != ENOENT)
{
if (error == EAGAIN)
error = EINVAL;
diskfs_drop_dirstat (dnp, ds);
mutex_unlock (&dnp->lock);
return error;
}
if (np == tnp)
{
diskfs_drop_dirstat (dnp, ds);
mutex_unlock (&dnp->lock);
mutex_unlock (&tnp->lock);
mach_port_deallocate (mach_task_self (), filecred->pi.port_right);
return 0;
}
if (tnp && S_ISDIR (tnp->dn_stat.st_mode))
{
diskfs_drop_dirstat (dnp, ds);
mutex_unlock (&dnp->lock);
mutex_unlock (&tnp->lock);
return EISDIR;
}
/* Create new entry for NP */
/* This is safe because NP is not a directory (thus not DNP) and
not TNP and is a leaf. */
mutex_lock (&np->lock);
/* Increment link count */
if (np->dn_stat.st_nlink == diskfs_link_max - 1)
{
diskfs_drop_dirstat (dnp, ds);
mutex_unlock (&np->lock);
mutex_unlock (&dnp->lock);
return EMLINK;
}
np->dn_stat.st_nlink++;
np->dn_set_ctime = 1;
diskfs_node_update (np, 1);
/* Attach it */
if (tnp)
{
assert (!excl);
error = diskfs_dirrewrite (dnp, tnp, np, name, ds);
if (!error)
{
/* Deallocate link on TNP */
tnp->dn_stat.st_nlink--;
tnp->dn_set_ctime = 1;
if (diskfs_synchronous)
diskfs_node_update (tnp, 1);
}
diskfs_nput (tnp);
}
else
error = diskfs_direnter (dnp, name, np, ds, dircred);
if (diskfs_synchronous)
diskfs_node_update (dnp, 1);
mutex_unlock (&dnp->lock);
mutex_unlock (&np->lock);
if (!error)
/* MiG won't do this for us, which it ought to. */
mach_port_deallocate (mach_task_self (), filecred->pi.port_right);
return error;
}
|
diegonc/console-xkb-support
|
libdiskfs/dir-link.c
|
C
|
gpl-2.0
| 3,470
|
<?php
/**
* @version $Id: mod_tppoplogin.php 2.0 - December 2011
* @converted by Rony S Y Zebua
* @www.templateplazza.com
* @package Joomla.Site
* @joomla version: Joomla 1.7.x
* @subpackage mod_tppoplogin
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__).'/helper.php';
$params->def('greeting', 1);
$type = modTpPopLoginHelper::getType();
$return = modTpPopLoginHelper::getReturnURL($params, $type);
$user = JFactory::getUser();
require JModuleHelper::getLayoutPath('mod_tppoplogin', $params->get('layout', 'default'));
|
viollarr/alab
|
tmp/install_4fead4e40c97c/Pop Login Module 1/mod_tppoplogin.php
|
PHP
|
gpl-2.0
| 798
|
<?php
/*
* Plugin Name: Max Mega Menu
* Plugin URI: https://maxmegamenu.com
* Description: Mega Menu for WordPress.
* Version: 1.7.3.1
* Author: Tom Hemsley
* Author URI: https://maxmegamenu.com
* License: GPL-2.0+
* Copyright: 2015 Tom Hemsley (https://maxmegamenu.com)
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // disable direct access
}
if ( ! class_exists( 'Mega_Menu' ) ) :
/**
* Main plugin class
*/
final class Mega_Menu {
/**
* @var string
*/
public $version = '1.7.3.1';
/**
* Init
*
* @since 1.0
*/
public static function init() {
$plugin = new self();
}
/**
* Constructor
*
* @since 1.0
*/
public function __construct() {
$this->define_constants();
$this->includes();
add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
add_action( 'admin_init', array( $this, 'install_upgrade_check' ) );
add_action( 'admin_notices', array( $this, 'admin_notices' ) );
add_filter( 'wp_nav_menu_args', array( $this, 'modify_nav_menu_args' ), 9999 );
add_filter( 'wp_nav_menu', array( $this, 'add_responsive_toggle' ), 10, 2 );
add_filter( 'wp_nav_menu_objects', array( $this, 'add_widgets_to_menu' ), 10, 2 );
add_filter( 'megamenu_nav_menu_css_class', array( $this, 'prefix_menu_classes' ) );
register_deactivation_hook( __FILE__, array( $this, 'delete_version_number') );
add_shortcode( 'maxmenu', array( $this, 'register_shortcode' ) );
if ( is_admin() && current_user_can('edit_theme_options') ) {
new Mega_Menu_Nav_Menus();
new Mega_Menu_Widget_Manager();
new Mega_Menu_Menu_Item_Manager();
new Mega_Menu_Settings();
}
$mega_menu_style_manager = new Mega_Menu_Style_Manager();
$mega_menu_style_manager->setup_actions();
}
/**
* Detect new or updated installations and run actions accordingly.
*
* @since 1.3
*/
public function install_upgrade_check() {
if ( $version = get_option( "megamenu_version" ) ) {
if ( version_compare( $this->version, $version, '!=' ) ) {
update_option( "megamenu_version", $this->version );
do_action( "megamenu_after_update" );
}
} else {
add_option( "megamenu_version", $this->version );
do_action( "megamenu_after_install" );
}
}
/**
* Store the current version number
*
* @since 1.3
*/
public function delete_version_number() {
delete_option( "megamenu_version", $this->version );
}
/**
* Shortcode used to display a menu
*
* @since 1.3
* @return string
*/
public function register_shortcode( $atts ) {
if ( ! isset( $atts['location'] ) ) {
return false;
}
if ( has_nav_menu( $atts['location'] ) ) {
return wp_nav_menu( array( 'theme_location' => $atts['location'], 'echo' => false ) );
}
return "<!-- menu not found [maxmenu location={$atts['location']}] -->";
}
/**
* Initialise translations
*
* @since 1.0
*/
public function load_plugin_textdomain() {
load_plugin_textdomain( 'megamenu', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/**
* Define Mega Menu constants
*
* @since 1.0
*/
private function define_constants() {
define( 'MEGAMENU_VERSION', $this->version );
define( 'MEGAMENU_BASE_URL', trailingslashit( plugins_url( 'megamenu' ) ) );
define( 'MEGAMENU_PATH', plugin_dir_path( __FILE__ ) );
}
/**
* All Mega Menu classes
*
* @since 1.0
*/
private function plugin_classes() {
return array(
'mega_menu_walker' => MEGAMENU_PATH . 'classes/walker.class.php',
'mega_menu_widget_manager' => MEGAMENU_PATH . 'classes/widget-manager.class.php',
'mega_menu_menu_item_manager' => MEGAMENU_PATH . 'classes/menu-item-manager.class.php',
'mega_menu_nav_menus' => MEGAMENU_PATH . 'classes/nav-menus.class.php',
'mega_menu_style_manager' => MEGAMENU_PATH . 'classes/style-manager.class.php',
'mega_menu_settings' => MEGAMENU_PATH . 'classes/settings.class.php',
'scssc' => MEGAMENU_PATH . 'classes/scssc.inc.php',
);
}
/**
* Load required classes
*
* @since 1.0
*/
private function includes() {
$autoload_is_disabled = defined( 'MEGAMENU_AUTOLOAD_CLASSES' ) && MEGAMENU_AUTOLOAD_CLASSES === false;
if ( function_exists( "spl_autoload_register" ) && ! $autoload_is_disabled ) {
// >= PHP 5.2 - Use auto loading
if ( function_exists( "__autoload" ) ) {
spl_autoload_register( "__autoload" );
}
spl_autoload_register( array( $this, 'autoload' ) );
} else {
// < PHP5.2 - Require all classes
foreach ( $this->plugin_classes() as $id => $path ) {
if ( is_readable( $path ) && ! class_exists( $id ) ) {
require_once $path;
}
}
}
}
/**
* Autoload classes to reduce memory consumption
*
* @since 1.0
* @param string $class
*/
public function autoload( $class ) {
$classes = $this->plugin_classes();
$class_name = strtolower( $class );
if ( isset( $classes[ $class_name ] ) && is_readable( $classes[ $class_name ] ) ) {
require_once $classes[ $class_name ];
}
}
/**
* Appends "mega-" to all menu classes.
* This is to help avoid theme CSS conflicts.
*
* @since 1.0
* @param array $classes
* @return array
*/
public function prefix_menu_classes( $classes ) {
$return = array();
foreach ( $classes as $class ) {
$return[] = 'mega-' . $class;
}
return $return;
}
/**
* Add the html for the responsive toggle box to the menu
*
* @param string $nav_menu
* @param object $args
* @return string
* @since 1.3
*/
public function add_responsive_toggle( $nav_menu, $args ) {
// make sure we're working with a Mega Menu
if ( ! is_a( $args->walker, 'Mega_Menu_Walker' ) )
return $nav_menu;
$toggle_id = apply_filters("megamenu_toggle_id", "mega-menu-toggle-{$args->theme_location}", $args->menu, $args->theme_location );
$toggle_class = 'mega-menu-toggle';
$find = 'class="' . $args->container_class . '">';
$replace = $find . '<div class="' . $toggle_class . '"></div>';
return str_replace( $find, $replace, $nav_menu );
}
/**
* Append the widget objects to the menu array before the
* menu is processed by the walker.
*
* @since 1.0
* @param array $items - All menu item objects
* @param object $args
* @return array - Menu objects including widgets
*/
public function add_widgets_to_menu( $items, $args ) {
// make sure we're working with a Mega Menu
if ( ! is_a( $args->walker, 'Mega_Menu_Walker' ) )
return $items;
$widget_manager = new Mega_Menu_Widget_Manager();
$default_columns = apply_filters("megamenu_default_columns", 1);
// apply saved metadata to each menu item
foreach ( $items as $item ) {
$saved_settings = array_filter( (array) get_post_meta( $item->ID, '_megamenu', true ) );
$item->megamenu_settings = array_merge( Mega_Menu_Nav_Menus::get_menu_item_defaults(), $saved_settings );
}
$items = apply_filters( "megamenu_nav_menu_objects_before", $items, $args );
foreach ( $items as $item ) {
// only look for widgets on top level items
if ( $item->menu_item_parent == 0 && $item->megamenu_settings['type'] == 'megamenu' ) {
$panel_widgets = $widget_manager->get_widgets_for_menu_id( $item->ID );
if ( count( $panel_widgets) ) {
if ( ! in_array( 'menu-item-has-children', $item->classes ) ) {
$item->classes[] = 'menu-item-has-children';
}
$cols = 0;
foreach ( $panel_widgets as $widget ) {
$menu_item = array(
'type' => 'widget',
'title' => '',
'content' => $widget_manager->show_widget( $widget['widget_id'] ),
'menu_item_parent' => $item->ID,
'db_id' => 0, // This menu item does not have any childen
'ID' => $widget['widget_id'],
'classes' => array(
"menu-item",
"menu-item-type-widget",
"menu-columns-{$widget['mega_columns']}-of-{$item->megamenu_settings['panel_columns']}"
)
);
if ( $cols == 0 ) {
$menu_item['classes'][] = "menu-clear";
}
$cols = $cols + $widget['mega_columns'];
if ( $cols > $item->megamenu_settings['panel_columns'] ) {
$menu_item['classes'][] = "menu-clear";
$cols = $widget['mega_columns'];
}
$items[] = (object) $menu_item;
}
}
}
}
$items = apply_filters( "megamenu_nav_menu_objects_after", $items, $args );
return $items;
}
/**
* Use the Mega Menu walker to output the menu
* Resets all parameters used in the wp_nav_menu call
* Wraps the menu in mega-menu IDs and classes
*
* @since 1.0
* @param $args array
* @return array
*/
public function modify_nav_menu_args( $args ) {
$settings = get_option( 'megamenu_settings' );
$current_theme_location = $args['theme_location'];
$locations = get_nav_menu_locations();
if ( isset ( $settings[ $current_theme_location ]['enabled'] ) && $settings[ $current_theme_location ]['enabled'] == true ) {
if ( ! isset( $locations[ $current_theme_location ] ) ) {
return $args;
}
$menu_id = $locations[ $current_theme_location ];
if ( ! $menu_id ) {
return $args;
}
$style_manager = new Mega_Menu_Style_Manager();
$themes = $style_manager->get_themes();
$menu_theme = $themes[ $settings[ $current_theme_location ]['theme'] ];
$menu_settings = $settings[ $current_theme_location ];
$wrap_attributes = apply_filters("megamenu_wrap_attributes", array(
"id" => '%1$s',
"class" => '%2$s mega-no-js',
"data-event" => isset( $menu_settings['event'] ) ? $menu_settings['event'] : 'hover',
"data-effect" => isset( $menu_settings['effect'] ) ? $menu_settings['effect'] : 'disabled',
"data-panel-width" => preg_match('/^\d/', $menu_theme['panel_width']) !== 1 ? $menu_theme['panel_width'] : '',
"data-second-click" => isset( $settings['second_click'] ) ? $settings['second_click'] : 'close',
"data-breakpoint" => absint( $menu_theme['responsive_breakpoint'] )
), $menu_id, $menu_settings, $settings, $current_theme_location );
$attributes = "";
foreach( $wrap_attributes as $attribute => $value ) {
if ( strlen( $value ) ) {
$attributes .= " " . $attribute . '="' . $value . '"';
}
}
$sanitized_location = str_replace( apply_filters("megamenu_location_replacements", array("-", " ") ), "-", $current_theme_location );
$defaults = array(
'menu' => $menu_id,
'container' => 'div',
'container_class' => 'mega-menu-wrap',
'container_id' => 'mega-menu-wrap-' . $sanitized_location,
'menu_class' => 'mega-menu mega-menu-horizontal',
'menu_id' => 'mega-menu-' . $sanitized_location,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul' . $attributes . '>%3$s</ul>',
'depth' => 0,
'walker' => new Mega_Menu_Walker()
);
$args = array_merge( $args, apply_filters( "megamenu_nav_menu_args", $defaults, $menu_id, $current_theme_location ) );
}
return $args;
}
/**
* Display admin notices.
*/
public function admin_notices() {
if ( ! $this->is_compatible_wordpress_version() ) :
?>
<div class="error">
<p><?php _e( 'Max Mega Menu is not compatible with your version of WordPress. Please upgrade WordPress to the latest version or disable Max Mega Menu.', 'megamenu' ); ?></p>
</div>
<?php
endif;
if ( is_plugin_active('ubermenu/ubermenu.php') ) :
?>
<div class="error">
<p><?php _e( 'Max Mega Menu is not compatible with Uber Menu. Please disable Uber Menu.', 'megamenu' ); ?></p>
</div>
<?php
endif;
if ( did_action('megamenu_after_install') === 1 ) :
?>
<div class="updated">
<?php
$link = "<a href='" . admin_url("themes.php?page=megamenu_settings") . "'>" . __( "click here", 'megamenu' ) . "</a>";
?>
<p><?php echo sprintf( __( 'Thanks for installing Max Mega Menu! Please %s to get started.', 'megamenu' ), $link); ?></p>
</div>
<?php
endif;
$css_version = get_transient("megamenu_css_version");
$css = get_transient("megamenu_css");
if ( $css && version_compare( $this->version, $css_version, '!=' ) ) :
?>
<div class="updated">
<?php
$link = "<a href='" . admin_url("themes.php?page=megamenu_settings&tab=tools") . "'>" . __( "regenerate the CSS", 'megamenu' ) . "</a>";
?>
<p><?php echo sprintf( __( 'Max Mega Menu has been updated. Please %s to ensure maximum compatibility with the latest version.', 'megamenu' ), $link); ?></p>
</div>
<?php
endif;
}
/**
* Checks this WordPress installation is v3.8 or above.
* 3.8 is needed for dashicons.
*/
public function is_compatible_wordpress_version() {
global $wp_version;
return $wp_version >= 3.8;
}
}
add_action( 'plugins_loaded', array( 'Mega_Menu', 'init' ), 10 );
endif;
|
Saurabh2711/wordpress
|
wp-content/plugins/megamenu/megamenu.php
|
PHP
|
gpl-2.0
| 13,280
|
/* Extended Module Player
* Copyright (C) 1996-2006 Claudio Matsuoka and Hipolito Carraro Jr
*
* $Id: liq.h,v 1.2 2006/02/12 16:58:48 cmatsuoka Exp $
*
* This file is part of the Extended Module Player and is distributed
* under the terms of the GNU General Public License. See doc/COPYING
* for more information.
*/
struct liq_header {
uint8 magic[14]; /* "Liquid Module:" */
uint8 name[30]; /* ASCIIZ module name */
uint8 author[20]; /* Author name */
uint8 _0x1a; /* 0x1a */
uint8 tracker[20]; /* Tracker name */
uint16 version; /* Format version */
uint16 speed; /* Initial speed */
uint16 bpm; /* Initial bpm */
uint16 low; /* Lowest note (Amiga Period*4) */
uint16 high; /* Uppest note (Amiga Period*4) */
uint16 chn; /* Number of channels */
uint32 flags; /* Module flags */
uint16 pat; /* Number of patterns saved */
uint16 ins; /* Number of instruments */
uint16 len; /* Module length */
uint16 hdrsz; /* Header size */
};
struct liq_instrument {
#if 0
uint8 magic[4]; /* 'L', 'D', 'S', 'S' */
#endif
uint16 version; /* LDSS header version */
uint8 name[30]; /* Instrument name */
uint8 editor[20]; /* Generator name */
uint8 author[20]; /* Author name */
uint8 hw_id; /* Hardware used to record the sample */
uint32 length; /* Sample length */
uint32 loopstart; /* Sample loop start */
uint32 loopend; /* Sample loop end */
uint32 c2spd; /* C2SPD */
uint8 vol; /* Volume */
uint8 flags; /* Flags */
uint8 pan; /* Pan */
uint8 midi_ins; /* General MIDI instrument */
uint8 gvl; /* Global volume */
uint8 chord; /* Chord type */
uint16 hdrsz; /* LDSS header size */
uint16 comp; /* Compression algorithm */
uint32 crc; /* CRC */
uint8 midi_ch; /* MIDI channel */
uint8 rsvd[11]; /* Reserved */
uint8 filename[25]; /* DOS file name */
};
struct liq_pattern {
#if 0
uint8 magic[4]; /* 'L', 'P', 0, 0 */
#endif
uint8 name[30]; /* ASCIIZ pattern name */
uint16 rows; /* Number of rows */
uint32 size; /* Size of packed pattern */
uint32 reserved; /* Reserved */
};
|
ipwndev/DSLinux-Mirror
|
user/xmp/src/src/loaders/include/liq.h
|
C
|
gpl-2.0
| 2,206
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><link rel="stylesheet" type="text/css" href="homepagestylenotes.css"/><script type="text/javascript" src="js/main.js"></script><title>Greek - Grade 9</title></head><body><table height=30px width=299px cellspacing=0px><tr><td class="subjectslistheadergrades"><p class="headertext">Greek - Grade 9</p></td></tr></table><div class="divnotes"><div class="example"><div class="post_results" id="post_results1" rss_num="15" rss_url="http://onstudynotes.com/notes/category/greek-grade-9/feed/"><div class="loading_rss"><img alt="Loading..." src="images/loading.gif" align="center"/></div></div></div></body></html>
|
onstudynotes/onstudynotes
|
wp-content/themes/justaskkim-twentyeleven/greek9.html
|
HTML
|
gpl-2.0
| 845
|
<?php
/**
* @package WPSEO\Admin
*/
/**
* This class generates the metabox on the edit post / page as well as contains all page analysis functionality.
*/
class WPSEO_Metabox extends WPSEO_Meta {
/**
* @var array
*/
private $options;
/**
* @var WPSEO_Social_Admin
*/
protected $social_admin;
/**
* @var WPSEO_Metabox_Analysis_SEO
*/
protected $analysis_seo;
/**
* @var WPSEO_Metabox_Analysis_Readability
*/
protected $analysis_readability;
/**
* Class constructor.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
add_action( 'wp_insert_post', array( $this, 'save_postdata' ) );
add_action( 'edit_attachment', array( $this, 'save_postdata' ) );
add_action( 'add_attachment', array( $this, 'save_postdata' ) );
add_action( 'post_submitbox_start', array( $this, 'publish_box' ) );
add_action( 'admin_init', array( $this, 'setup_page_analysis' ) );
add_action( 'admin_init', array( $this, 'translate_meta_boxes' ) );
add_action( 'admin_footer', array( $this, 'template_keyword_tab' ) );
add_action( 'admin_footer', array( $this, 'template_generic_tab' ) );
$this->options = WPSEO_Options::get_options( array( 'wpseo', 'wpseo_social' ) );
// Check if one of the social settings is checked in the options, if so, initialize the social_admin object.
if ( $this->options['opengraph'] === true || $this->options['twitter'] === true ) {
$this->social_admin = new WPSEO_Social_Admin( $this->options );
}
$this->editor = new WPSEO_Metabox_Editor();
$this->editor->register_hooks();
$this->analysis_seo = new WPSEO_Metabox_Analysis_SEO();
$this->analysis_readability = new WPSEO_Metabox_Analysis_Readability();
}
/**
* Translate text strings for use in the meta box.
*
* IMPORTANT: if you want to add a new string (option) somewhere, make sure you add that array key to
* the main meta box definition array in the class WPSEO_Meta() as well!!!!
*/
public static function translate_meta_boxes() {
self::$meta_fields['general']['snippetpreview']['title'] = __( 'Snippet editor', 'wordpress-seo' );
/* translators: 1: link open tag; 2: link close tag. */
self::$meta_fields['general']['snippetpreview']['help'] = sprintf( __( 'This is a rendering of what this post might look like in Google\'s search results. %1$sLearn more about the Snippet Preview%2$s.', 'wordpress-seo' ), '<a target="_blank" href="' . WPSEO_Shortlinker::get( 'https://yoa.st/snippet-preview' ) . '">', '</a>' );
self::$meta_fields['general']['snippetpreview']['help-button'] = __( 'Show information about the snippet editor', 'wordpress-seo' );
self::$meta_fields['general']['pageanalysis']['title'] = __( 'Analysis', 'wordpress-seo' );
/* translators: 1: link open tag; 2: link close tag. */
self::$meta_fields['general']['pageanalysis']['help'] = sprintf( __( 'This is the content analysis, a collection of content checks that analyze the content of your page. %1$sLearn more about the Content Analysis Tool%2$s.', 'wordpress-seo' ), '<a target="_blank" href="' . WPSEO_Shortlinker::get( 'https://yoa.st/content-analysis' ) . '">', '</a>' );
self::$meta_fields['general']['pageanalysis']['help-button'] = __( 'Show information about the content analysis', 'wordpress-seo' );
self::$meta_fields['general']['focuskw_text_input']['title'] = __( 'Focus keyword', 'wordpress-seo' );
self::$meta_fields['general']['focuskw_text_input']['label'] = __( 'Enter a focus keyword', 'wordpress-seo' );
/* translators: 1: link open tag; 2: link close tag. */
self::$meta_fields['general']['focuskw_text_input']['help'] = sprintf( __( 'Pick the main keyword or keyphrase that this post/page is about. %1$sLearn more about the Focus Keyword%2$s.', 'wordpress-seo' ), '<a target="_blank" href="' . WPSEO_Shortlinker::get( 'https://yoa.st/focus-keyword' ) . '">', '</a>' );
self::$meta_fields['general']['focuskw_text_input']['help-button'] = __( 'Show information about the focus keyword', 'wordpress-seo' );
self::$meta_fields['general']['title']['title'] = __( 'SEO title', 'wordpress-seo' );
self::$meta_fields['general']['metadesc']['title'] = __( 'Meta description', 'wordpress-seo' );
self::$meta_fields['general']['metakeywords']['title'] = __( 'Meta keywords', 'wordpress-seo' );
self::$meta_fields['general']['metakeywords']['label'] = __( 'Enter the meta keywords', 'wordpress-seo' );
/* translators: 1: link open tag; 2: link close tag. */
self::$meta_fields['general']['metakeywords']['description'] = __( 'If you type something above it will override your %1$smeta keywords template%2$s.', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-noindex']['title'] = __( 'Meta robots index', 'wordpress-seo' );
if ( '0' === (string) get_option( 'blog_public' ) ) {
self::$meta_fields['advanced']['meta-robots-noindex']['description'] = '<p class="error-message">' . __( 'Warning: even though you can set the meta robots setting here, the entire site is set to noindex in the sitewide privacy settings, so these settings won\'t have an effect.', 'wordpress-seo' ) . '</p>';
}
/* translators: %s expands to the robots (no)index setting default as set in the site-wide settings.*/
self::$meta_fields['advanced']['meta-robots-noindex']['options']['0'] = __( 'Default for this post type, currently: %s', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-noindex']['options']['2'] = 'index';
self::$meta_fields['advanced']['meta-robots-noindex']['options']['1'] = 'noindex';
self::$meta_fields['advanced']['meta-robots-nofollow']['title'] = __( 'Meta robots follow', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-nofollow']['options']['0'] = 'follow';
self::$meta_fields['advanced']['meta-robots-nofollow']['options']['1'] = 'nofollow';
self::$meta_fields['advanced']['meta-robots-adv']['title'] = __( 'Meta robots advanced', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-adv']['description'] = __( 'Advanced <code>meta</code> robots settings for this page.', 'wordpress-seo' );
/* translators: %s expands to the advanced robots settings default as set in the site-wide settings.*/
self::$meta_fields['advanced']['meta-robots-adv']['options']['-'] = __( 'Site-wide default: %s', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-adv']['options']['none'] = __( 'None', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-adv']['options']['noimageindex'] = __( 'No Image Index', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-adv']['options']['noarchive'] = __( 'No Archive', 'wordpress-seo' );
self::$meta_fields['advanced']['meta-robots-adv']['options']['nosnippet'] = __( 'No Snippet', 'wordpress-seo' );
self::$meta_fields['advanced']['bctitle']['title'] = __( 'Breadcrumbs Title', 'wordpress-seo' );
self::$meta_fields['advanced']['bctitle']['description'] = __( 'Title to use for this page in breadcrumb paths', 'wordpress-seo' );
self::$meta_fields['advanced']['canonical']['title'] = __( 'Canonical URL', 'wordpress-seo' );
/* translators: 1: link open tag; 2: link close tag. */
self::$meta_fields['advanced']['canonical']['description'] = sprintf( __( 'The canonical URL that this page should point to, leave empty to default to permalink. %1$sCross domain canonical%2$s supported too.', 'wordpress-seo' ), '<a target="_blank" href="http://googlewebmastercentral.blogspot.com/2009/12/handling-legitimate-cross-domain.html">', '</a>' );
self::$meta_fields['advanced']['redirect']['title'] = __( '301 Redirect', 'wordpress-seo' );
self::$meta_fields['advanced']['redirect']['description'] = __( 'The URL that this page should redirect to.', 'wordpress-seo' );
do_action( 'wpseo_tab_translate' );
}
/**
* Test whether the metabox should be hidden either by choice of the admin or because
* the post type is not a public post type.
*
* @since 1.5.0
*
* @param string $post_type Optional. The post type to test, defaults to the current post post_type.
*
* @return bool Whether or not the meta box (and associated columns etc) should be hidden.
*/
public function is_metabox_hidden( $post_type = null ) {
if ( ! isset( $post_type ) && ( isset( $GLOBALS['post'] ) && ( is_object( $GLOBALS['post'] ) && isset( $GLOBALS['post']->post_type ) ) ) ) {
$post_type = $GLOBALS['post']->post_type;
}
if ( isset( $post_type ) ) {
// Don't make static as post_types may still be added during the run.
$post_types = WPSEO_Post_Type::get_accessible_post_types();
$options = get_option( 'wpseo_titles' );
return ( ( isset( $options[ 'hideeditbox-' . $post_type ] ) && $options[ 'hideeditbox-' . $post_type ] === true ) || in_array( $post_type, $post_types, true ) === false );
}
return false;
}
/**
* Sets up all the functionality related to the prominence of the page analysis functionality.
*/
public function setup_page_analysis() {
if ( apply_filters( 'wpseo_use_page_analysis', true ) === true ) {
add_action( 'post_submitbox_start', array( $this, 'publish_box' ) );
}
}
/**
* Outputs the page analysis score in the Publish Box.
*/
public function publish_box() {
if ( $this->is_metabox_hidden() === true ) {
return;
}
$post = $this->get_metabox_post();
if ( self::get_value( 'meta-robots-noindex', $post->ID ) === '1' ) {
$score_label = 'noindex';
$title = __( 'Post is set to noindex.', 'wordpress-seo' );
$score_title = $title;
}
else {
$score = self::get_value( 'linkdex', $post->ID );
if ( $score === '' ) {
$score_label = 'na';
$title = __( 'No focus keyword set.', 'wordpress-seo' );
}
else {
$score_label = WPSEO_Utils::translate_score( $score );
}
$score_title = WPSEO_Utils::translate_score( $score, false );
if ( ! isset( $title ) ) {
$title = $score_title;
}
}
}
/**
* Adds the Yoast SEO meta box to the edit boxes in the edit post, page,
* attachment, and custom post types pages.
*/
public function add_meta_box() {
$post_types = WPSEO_Post_Type::get_accessible_post_types();
if ( is_array( $post_types ) && $post_types !== array() ) {
foreach ( $post_types as $post_type ) {
if ( $this->is_metabox_hidden( $post_type ) === false ) {
$product_title = 'Yoast SEO';
if ( file_exists( WPSEO_PATH . 'premium/' ) ) {
$product_title .= ' Premium';
}
if ( null !== get_current_screen() ) {
$screen_id = get_current_screen()->id;
add_filter( "postbox_classes_{$screen_id}_wpseo_meta", array( $this, 'wpseo_metabox_class' ) );
}
add_meta_box( 'wpseo_meta', $product_title, array(
$this,
'meta_box',
), $post_type, 'normal', apply_filters( 'wpseo_metabox_prio', 'high' ) );
}
}
}
}
/**
* Adds CSS classes to the meta box.
*
* @param array $classes An array of postbox CSS classes.
*
* @return array
*/
public function wpseo_metabox_class( $classes ) {
$classes[] = 'yoast wpseo-metabox';
return $classes;
}
/**
* Pass variables to js for use with the post-scraper.
*
* @return array
*/
public function localize_post_scraper_script() {
$post = $this->get_metabox_post();
$permalink = '';
if ( is_object( $post ) ) {
$permalink = get_sample_permalink( $post->ID );
$permalink = $permalink[0];
}
$post_formatter = new WPSEO_Metabox_Formatter(
new WPSEO_Post_Metabox_Formatter( $post, WPSEO_Options::get_option( 'wpseo_titles' ), $permalink )
);
return $post_formatter->get_values();
}
/**
* Pass some variables to js for replacing variables.
*/
public function localize_replace_vars_script() {
return array(
'no_parent_text' => __( '(no parent)', 'wordpress-seo' ),
'replace_vars' => $this->get_replace_vars(),
'scope' => $this->determine_scope(),
);
}
/**
* Determines the scope based on the post type.
* This can be used by the replacevar plugin to determine if a replacement needs to be executed.
*
* @return string String decribing the current scope.
*/
private function determine_scope() {
$post_type = get_post_type( $this->get_metabox_post() );
if ( $post_type === 'page' ) {
return 'page';
}
return 'post';
}
/**
* Pass some variables to js for the edit / post page overview, snippet preview, etc.
*
* @return array
*/
public function localize_shortcode_plugin_script() {
return array(
'wpseo_filter_shortcodes_nonce' => wp_create_nonce( 'wpseo-filter-shortcodes' ),
'wpseo_shortcode_tags' => $this->get_valid_shortcode_tags(),
);
}
/**
* Output a tab in the Yoast SEO Metabox.
*
* @param string $id CSS ID of the tab.
* @param string $heading Heading for the tab.
* @param string $content Content of the tab. This content should be escaped.
*/
public function do_tab( $id, $heading, $content ) {
?>
<div id="<?php echo esc_attr( 'wpseo_' . $id ); ?>" class="wpseotab <?php echo esc_attr( $id ); ?>">
<?php echo $content; ?>
</div>
<?php
}
/**
* Output the meta box.
*/
public function meta_box() {
$content_sections = $this->get_content_sections();
$helpcenter_tab = new WPSEO_Option_Tab( 'metabox', __( 'Meta box', 'wordpress-seo' ),
array( 'video_url' => WPSEO_Shortlinker::get( 'https://yoa.st/metabox-screencast' ) ) );
$help_center = new WPSEO_Help_Center( '', $helpcenter_tab, WPSEO_Utils::is_yoast_seo_premium() );
$help_center->localize_data();
$help_center->mount();
if ( ! defined( 'WPSEO_PREMIUM_FILE' ) ) {
echo $this->get_buy_premium_link();
}
echo '<div class="wpseo-metabox-content">';
echo '<div class="wpseo-metabox-sidebar"><ul>';
foreach ( $content_sections as $content_section ) {
if ( $content_section->name === 'premium' ) {
continue;
}
$content_section->display_link();
}
echo '</ul></div>';
foreach ( $content_sections as $content_section ) {
$content_section->display_content();
}
echo '</div>';
}
/**
* Returns the relevant metabox sections for the current view.
*
* @return WPSEO_Metabox_Section[]
*/
private function get_content_sections() {
$content_sections = array( $this->get_content_meta_section() );
// Check if social_admin is an instance of WPSEO_Social_Admin.
if ( $this->social_admin instanceof WPSEO_Social_Admin ) {
$content_sections[] = $this->social_admin->get_meta_section();
}
if ( WPSEO_Capability_Utils::current_user_can( 'wpseo_edit_advanced_metadata' ) || $this->options['disableadvanced_meta'] === false ) {
$content_sections[] = $this->get_advanced_meta_section();
}
if ( ! defined( 'WPSEO_PREMIUM_FILE' ) ) {
$content_sections[] = $this->get_buy_premium_section();
}
if ( has_action( 'wpseo_tab_header' ) || has_action( 'wpseo_tab_content' ) ) {
$content_sections[] = $this->get_addons_meta_section();
}
return $content_sections;
}
/**
* Returns the metabox section for the content analysis.
*
* @return WPSEO_Metabox_Section
*/
private function get_content_meta_section() {
$content = $this->get_tab_content( 'general' );
$tabs = array();
$tabs[] = new WPSEO_Metabox_Form_Tab(
'content',
$content,
'',
array(
'tab_class' => 'yoast-seo__remove-tab',
)
);
$tabs[] = new WPSEO_Metabox_Add_Keyword_Tab();
return new WPSEO_Metabox_Tab_Section(
'content',
'<span class="screen-reader-text">' . __( 'Content optimization', 'wordpress-seo' ) . '</span><span class="yst-traffic-light-container">' . $this->traffic_light_svg() . '</span>',
$tabs,
array(
'link_aria_label' => __( 'Content optimization', 'wordpress-seo' ),
'link_class' => 'yoast-tooltip yoast-tooltip-e',
)
);
}
/**
* Returns the metabox section for the advanced settings.
*
* @return WPSEO_Metabox_Section
*/
private function get_advanced_meta_section() {
$content = $this->get_tab_content( 'advanced' );
$tab = new WPSEO_Metabox_Form_Tab(
'advanced',
$content,
__( 'Advanced', 'wordpress-seo' ),
array(
'single' => true,
)
);
return new WPSEO_Metabox_Tab_Section(
'advanced',
'<span class="screen-reader-text">' . __( 'Advanced', 'wordpress-seo' ) . '</span><span class="dashicons dashicons-admin-generic"></span>',
array( $tab ),
array(
'link_aria_label' => __( 'Advanced', 'wordpress-seo' ),
'link_class' => 'yoast-tooltip yoast-tooltip-e',
)
);
}
/**
* Returns a link to activate the Buy Premium tab.
*
* @return string
*/
private function get_buy_premium_link() {
return sprintf( "<div class='%s'><a href='#wpseo-meta-section-premium' class='wpseo-meta-section-link'><span class='dashicons dashicons-star-filled wpseo-buy-premium'></span>%s</a></div>",
'wpseo-metabox-buy-premium',
__( 'Go Premium', 'wordpress-seo' )
);
}
/**
* Returns the metabox section for the Premium section.
*
* @return WPSEO_Metabox_Section
*/
private function get_buy_premium_section() {
$content = sprintf( "<div class='wpseo-premium-description'>
%s
<ul class='wpseo-premium-advantages-list'>
<li>
<strong>%s</strong> - %s
</li>
<li>
<strong>%s</strong> - %s
</li>
<li>
<strong>%s</strong> - %s
</li>
<li>
<strong>%s</strong> - %s
</li>
</ul>
<a target='_blank' id='wpseo-buy-premium-popup-button' class='button button-buy-premium wpseo-metabox-go-to' href='%s'>
%s
</a>
<p><a target='_blank' class='wpseo-metabox-go-to' href='%s'>%s</a></p>
</div>",
/* translators: %1$s expands to Yoast SEO Premium. */
sprintf( __( 'You\'re not getting the benefits of %1$s yet. If you had %1$s, you could use its awesome features:', 'wordpress-seo' ), 'Yoast SEO Premium' ),
__( 'Redirect manager', 'wordpress-seo' ),
__( 'Create and manage redirects within your WordPress install.', 'wordpress-seo' ),
__( 'Multiple focus keywords', 'wordpress-seo' ),
__( 'Optimize a single post for up to 5 keywords.', 'wordpress-seo' ),
__( 'Social Previews', 'wordpress-seo' ),
__( 'Check what your Facebook or Twitter post will look like.', 'wordpress-seo' ),
__( 'Premium support', 'wordpress-seo' ),
__( 'Gain access to our 24/7 support team.', 'wordpress-seo' ),
WPSEO_Shortlinker::get( 'https://yoa.st/pe-buy-premium' ),
/* translators: %s expands to Yoast SEO Premium. */
sprintf( __( 'Get %s now!', 'wordpress-seo' ), 'Yoast SEO Premium' ),
WPSEO_Shortlinker::get( 'https://yoa.st/pe-premium-page' ),
__( 'More info', 'wordpress-seo' )
);
$tab = new WPSEO_Metabox_Form_Tab(
'premium',
$content,
'Yoast SEO Premium',
array(
'single' => true,
)
);
return new WPSEO_Metabox_Tab_Section(
'premium',
'<span class="dashicons dashicons-star-filled wpseo-buy-premium"></span>',
array( $tab ),
array(
'link_aria_label' => 'Yoast SEO Premium',
'link_class' => 'yoast-tooltip yoast-tooltip-e',
)
);
}
/**
* Returns a metabox section dedicated to hosting metabox tabs that have been added by other plugins through the
* `wpseo_tab_header` and `wpseo_tab_content` actions.
*
* @return WPSEO_Metabox_Section
*/
private function get_addons_meta_section() {
return new WPSEO_Metabox_Addon_Tab_Section(
'addons',
'<span class="screen-reader-text">' . __( 'Add-ons', 'wordpress-seo' ) . '</span><span class="dashicons dashicons-admin-plugins"></span>',
array(),
array(
'link_aria_label' => __( 'Add-ons', 'wordpress-seo' ),
'link_class' => 'yoast-tooltip yoast-tooltip-e',
)
);
}
/**
* Gets the contents for the metabox tab.
*
* @param string $tab_name Tab for which to retrieve the field definitions.
*
* @return string
*/
private function get_tab_content( $tab_name ) {
$content = '';
foreach ( $this->get_meta_field_defs( $tab_name ) as $key => $meta_field ) {
$content .= $this->do_meta_box( $meta_field, $key );
}
unset( $key, $meta_field );
return $content;
}
/**
* Adds a line in the meta box.
*
* @todo [JRF] Check if $class is added appropriately everywhere.
*
* @param array $meta_field_def Contains the vars based on which output is generated.
* @param string $key Internal key (without prefix).
*
* @return string
*/
public function do_meta_box( $meta_field_def, $key = '' ) {
$content = '';
$esc_form_key = esc_attr( self::$form_prefix . $key );
$meta_value = self::get_value( $key, $this->get_metabox_post()->ID );
$class = '';
if ( isset( $meta_field_def['class'] ) && $meta_field_def['class'] !== '' ) {
$class = ' ' . $meta_field_def['class'];
}
$placeholder = '';
if ( isset( $meta_field_def['placeholder'] ) && $meta_field_def['placeholder'] !== '' ) {
$placeholder = $meta_field_def['placeholder'];
}
$aria_describedby = '';
$description = '';
if ( isset( $meta_field_def['description'] ) ) {
$aria_describedby = ' aria-describedby="' . $esc_form_key . '-desc"';
$description = '<p id="' . $esc_form_key . '-desc" class="yoast-metabox__description">' . $meta_field_def['description'] . '</p>';
}
switch ( $meta_field_def['type'] ) {
case 'pageanalysis':
$content_analysis_active = $this->options['content_analysis_active'];
$keyword_analysis_active = $this->options['keyword_analysis_active'];
if ( $content_analysis_active === false && $keyword_analysis_active === false ) {
break;
}
$content .= '<div id="pageanalysis">';
$content .= '<section class="yoast-section" id="wpseo-pageanalysis-section">';
$content .= '<h3 class="yoast-section__heading yoast-section__heading-icon yoast-section__heading-icon-list">' . __( 'Analysis', 'wordpress-seo' ) . '</h3>';
$content .= '<div id="wpseo-pageanalysis"></div>';
$content .= '<div id="yoast-seo-content-analysis"></div>';
$content .= '</section>';
$content .= '</div>';
break;
case 'snippetpreview':
$content .= '<div id="wpseosnippet" class="wpseosnippet"></div>';
break;
case 'focuskeyword':
if ( $placeholder !== '' ) {
$placeholder = ' placeholder="' . esc_attr( $placeholder ) . '"';
}
$content .= '<div id="wpseofocuskeyword">';
$content .= '<section class="yoast-section" id="wpseo-focuskeyword-section">';
$content .= '<h3 class="yoast-section__heading yoast-section__heading-icon yoast-section__heading-icon-key">' . esc_html( $meta_field_def['title'] ) . '</h3>';
$content .= '<label for="' . $esc_form_key . '" class="screen-reader-text">' . esc_html( $meta_field_def['label'] ) . '</label>';
$content .= '<input type="text"' . $placeholder . ' id="' . $esc_form_key . '" autocomplete="off" name="' . $esc_form_key . '" value="' . esc_attr( $meta_value ) . '" class="large-text' . $class . '"/>';
if ( $this->options['enable_cornerstone_content'] ) {
$cornerstone_field = new WPSEO_Cornerstone_Field();
$content .= $cornerstone_field->get_html( $this->get_metabox_post() );
}
$content .= '</section>';
$content .= '</div>';
break;
case 'metakeywords':
$content .= '<div id="wpseometakeywords">';
$content .= '<section class="yoast-section" id="wpseo-metakeywords-section">';
$content .= '<h3 class="yoast-section__heading yoast-section__heading-icon yoast-section__heading-icon-edit">' . esc_html( $meta_field_def['title'] ) . '</h3>';
$content .= '<label for="' . $esc_form_key . '" class="screen-reader-text">' . esc_html( $meta_field_def['label'] ) . '</label>';
$content .= '<input type="text" id="' . $esc_form_key . '" name="' . $esc_form_key . '" value="' . esc_attr( $meta_value ) . '" class="large-text' . $class . '"' . $aria_describedby . '/>';
$content .= $description;
$content .= '</section>';
$content .= '</div>';
break;
case 'text':
$ac = '';
if ( isset( $meta_field_def['autocomplete'] ) && $meta_field_def['autocomplete'] === false ) {
$ac = 'autocomplete="off" ';
}
if ( $placeholder !== '' ) {
$placeholder = ' placeholder="' . esc_attr( $placeholder ) . '"';
}
$content .= '<input type="text"' . $placeholder . ' id="' . $esc_form_key . '" ' . $ac . 'name="' . $esc_form_key . '" value="' . esc_attr( $meta_value ) . '" class="large-text' . $class . '"' . $aria_describedby . '/>';
break;
case 'textarea':
$rows = 3;
if ( isset( $meta_field_def['rows'] ) && $meta_field_def['rows'] > 0 ) {
$rows = $meta_field_def['rows'];
}
$content .= '<textarea class="large-text' . $class . '" rows="' . esc_attr( $rows ) . '" id="' . $esc_form_key . '" name="' . $esc_form_key . '"' . $aria_describedby . '>' . esc_textarea( $meta_value ) . '</textarea>';
break;
case 'hidden':
$content .= '<input type="hidden" id="' . $esc_form_key . '" name="' . $esc_form_key . '" value="' . esc_attr( $meta_value ) . '"/>' . "\n";
break;
case 'select':
if ( isset( $meta_field_def['options'] ) && is_array( $meta_field_def['options'] ) && $meta_field_def['options'] !== array() ) {
$content .= '<select name="' . $esc_form_key . '" id="' . $esc_form_key . '" class="yoast' . $class . '">';
foreach ( $meta_field_def['options'] as $val => $option ) {
$selected = selected( $meta_value, $val, false );
$content .= '<option ' . $selected . ' value="' . esc_attr( $val ) . '">' . esc_html( $option ) . '</option>';
}
unset( $val, $option, $selected );
$content .= '</select>';
}
break;
case 'multiselect':
if ( isset( $meta_field_def['options'] ) && is_array( $meta_field_def['options'] ) && $meta_field_def['options'] !== array() ) {
// Set $meta_value as $selected_arr.
$selected_arr = $meta_value;
// If the multiselect field is 'meta-robots-adv' we should explode on ,.
if ( 'meta-robots-adv' === $key ) {
$selected_arr = explode( ',', $meta_value );
}
if ( ! is_array( $selected_arr ) ) {
$selected_arr = (array) $selected_arr;
}
$options_count = count( $meta_field_def['options'] );
// This select now uses Select2.
$content .= '<select multiple="multiple" size="' . esc_attr( $options_count ) . '" name="' . $esc_form_key . '[]" id="' . $esc_form_key . '" class="yoast' . $class . '"' . $aria_describedby . '>';
foreach ( $meta_field_def['options'] as $val => $option ) {
$selected = '';
if ( in_array( $val, $selected_arr ) ) {
$selected = ' selected="selected"';
}
$content .= '<option ' . $selected . ' value="' . esc_attr( $val ) . '">' . esc_html( $option ) . '</option>';
}
$content .= '</select>';
unset( $val, $option, $selected, $selected_arr, $options_count );
}
break;
case 'checkbox':
$checked = checked( $meta_value, 'on', false );
$expl = ( isset( $meta_field_def['expl'] ) ) ? esc_html( $meta_field_def['expl'] ) : '';
$content .= '<input type="checkbox" id="' . $esc_form_key . '" name="' . $esc_form_key . '" ' . $checked . ' value="on" class="yoast' . $class . '"' . $aria_describedby . '/> <label for="' . $esc_form_key . '">' . $expl . '</label>';
unset( $checked, $expl );
break;
case 'radio':
if ( isset( $meta_field_def['options'] ) && is_array( $meta_field_def['options'] ) && $meta_field_def['options'] !== array() ) {
foreach ( $meta_field_def['options'] as $val => $option ) {
$checked = checked( $meta_value, $val, false );
$content .= '<input type="radio" ' . $checked . ' id="' . $esc_form_key . '_' . esc_attr( $val ) . '" name="' . $esc_form_key . '" value="' . esc_attr( $val ) . '"/> <label for="' . $esc_form_key . '_' . esc_attr( $val ) . '">' . esc_html( $option ) . '</label> ';
}
unset( $val, $option, $checked );
}
break;
case 'upload':
$content .= '<input id="' . $esc_form_key . '" type="text" size="36" class="' . $class . '" name="' . $esc_form_key . '" value="' . esc_attr( $meta_value ) . '"' . $aria_describedby . ' />';
$content .= '<input id="' . $esc_form_key . '_button" class="wpseo_image_upload_button button" type="button" value="' . esc_attr__( 'Upload Image', 'wordpress-seo' ) . '" />';
break;
}
$html = '';
if ( $content === '' ) {
$content = apply_filters( 'wpseo_do_meta_box_field_' . $key, $content, $meta_value, $esc_form_key, $meta_field_def, $key );
}
if ( $content !== '' ) {
$title = esc_html( $meta_field_def['title'] );
// By default, use the field title as a label element.
$label = '<label for="' . $esc_form_key . '">' . $title . '</label>';
// Set the inline help and help panel, if any.
$help_button = '';
$help_panel = '';
if ( isset( $meta_field_def['help'] ) && $meta_field_def['help'] !== '' ) {
$help = new WPSEO_Admin_Help_Panel( $key, $meta_field_def['help-button'], $meta_field_def['help'] );
$help_button = $help->get_button_html();
$help_panel = $help->get_panel_html();
}
// If it's a set of radio buttons, output proper fieldset and legend.
if ( 'radio' === $meta_field_def['type'] ) {
return '<fieldset><legend>' . $title . '</legend>' . $help_button . $help_panel . $content . $description . '</fieldset>';
}
// If it's a single checkbox, ignore the title.
if ( 'checkbox' === $meta_field_def['type'] ) {
$label = '';
}
// Special meta box sections such as the Snippet Preview, the Analysis, etc.
if ( in_array( $meta_field_def['type'], array(
'snippetpreview',
'pageanalysis',
'focuskeyword',
'metakeywords',
), true )
) {
return $this->create_content_box( $content, $meta_field_def['type'], $help_button, $help_panel );
}
// Other meta box content or form fields.
if ( $meta_field_def['type'] === 'hidden' ) {
$html = $content;
}
else {
$html = $label . $help_button . $help_panel . $content . $description;
}
}
return $html;
}
/**
* Creates a sections specific row.
*
* @param string $content The content to show.
* @param string $hidden_help_name Escaped form key name.
* @param string $help_button The help button.
* @param string $help_panel The help text.
*
* @return string
*/
private function create_content_box( $content, $hidden_help_name, $help_button, $help_panel ) {
$html = $content;
$html .= '<div class="wpseo_hidden" id="help-yoast-' . $hidden_help_name . '">' . $help_button . $help_panel . '</div>';
return $html;
}
/**
* Save the WP SEO metadata for posts.
*
* {@internal $_POST parameters are validated via sanitize_post_meta().}}
*
* @param int $post_id Post ID.
*
* @return bool|void Boolean false if invalid save post request.
*/
public function save_postdata( $post_id ) {
// Bail if this is a multisite installation and the site has been switched.
if ( is_multisite() && ms_is_switched() ) {
return false;
}
if ( $post_id === null ) {
return false;
}
if ( wp_is_post_revision( $post_id ) ) {
$post_id = wp_is_post_revision( $post_id );
}
/**
* Determine we're not accidentally updating a different post.
* We can't use filter_input here as the ID isn't available at this point, other than in the $_POST data.
*/
// @codingStandardsIgnoreStart
if ( ! isset( $_POST['ID'] ) || $post_id !== (int) $_POST['ID'] ) {
return false;
}
// @codingStandardsIgnoreEnd
clean_post_cache( $post_id );
$post = get_post( $post_id );
if ( ! is_object( $post ) ) {
// Non-existent post.
return false;
}
do_action( 'wpseo_save_compare_data', $post );
$meta_boxes = apply_filters( 'wpseo_save_metaboxes', array() );
$meta_boxes = array_merge( $meta_boxes, $this->get_meta_field_defs( 'general', $post->post_type ), $this->get_meta_field_defs( 'advanced' ) );
foreach ( $meta_boxes as $key => $meta_box ) {
// If analysis is disabled remove that analysis score value from the DB.
if ( $this->is_meta_value_disabled( $key ) ) {
self::delete( $key, $post_id );
continue;
}
$data = null;
if ( 'checkbox' === $meta_box['type'] ) {
// @codingStandardsIgnoreLine
$data = isset( $_POST[ self::$form_prefix . $key ] ) ? 'on' : 'off';
}
else {
// @codingStandardsIgnoreLine
if ( isset( $_POST[ self::$form_prefix . $key ] ) ) {
// @codingStandardsIgnoreLine
$data = $_POST[ self::$form_prefix . $key ];
}
}
if ( isset( $data ) ) {
self::set_value( $key, $data, $post_id );
}
}
do_action( 'wpseo_saved_postdata' );
}
/**
* Determines if the given meta value key is disabled.
*
* @param string $key The key of the meta value.
* @return bool Whether the given meta value key is disabled.
*/
public function is_meta_value_disabled( $key ) {
if ( 'linkdex' === $key && ! $this->analysis_seo->is_enabled() ) {
return true;
}
if ( 'content_score' === $key && ! $this->analysis_readability->is_enabled() ) {
return true;
}
return false;
}
/**
* Enqueues all the needed JS and CSS.
*
* @todo [JRF => whomever] Create css/metabox-mp6.css file and add it to the below allowed colors array when done.
*/
public function enqueue() {
global $pagenow;
$asset_manager = new WPSEO_Admin_Asset_Manager();
$is_editor = self::is_post_overview( $pagenow ) || self::is_post_edit( $pagenow );
/* Filter 'wpseo_always_register_metaboxes_on_admin' documented in wpseo-main.php */
if ( ( ! $is_editor && apply_filters( 'wpseo_always_register_metaboxes_on_admin', false ) === false ) || $this->is_metabox_hidden() === true
) {
return;
}
if ( self::is_post_overview( $pagenow ) ) {
$asset_manager->enqueue_style( 'edit-page' );
$asset_manager->enqueue_script( 'edit-page-script' );
}
else {
if ( 0 !== get_queried_object_id() ) {
wp_enqueue_media( array( 'post' => get_queried_object_id() ) ); // Enqueue files needed for upload functionality.
}
$asset_manager->enqueue_style( 'metabox-css' );
$asset_manager->enqueue_style( 'scoring' );
$asset_manager->enqueue_style( 'snippet' );
$asset_manager->enqueue_style( 'select2' );
$asset_manager->enqueue_script( 'metabox' );
$asset_manager->enqueue_script( 'help-center' );
$asset_manager->enqueue_script( 'admin-media' );
$asset_manager->enqueue_script( 'post-scraper' );
$asset_manager->enqueue_script( 'replacevar-plugin' );
$asset_manager->enqueue_script( 'shortcode-plugin' );
wp_enqueue_script( 'jquery-ui-autocomplete' );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'admin-media', 'wpseoMediaL10n', $this->localize_media_script() );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'post-scraper', 'wpseoPostScraperL10n', $this->localize_post_scraper_script() );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'replacevar-plugin', 'wpseoReplaceVarsL10n', $this->localize_replace_vars_script() );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'shortcode-plugin', 'wpseoShortcodePluginL10n', $this->localize_shortcode_plugin_script() );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'metabox', 'wpseoAdminL10n', WPSEO_Help_Center::get_translated_texts() );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'metabox', 'wpseoSelect2Locale', WPSEO_Utils::get_language( WPSEO_Utils::get_user_locale() ) );
if ( post_type_supports( get_post_type(), 'thumbnail' ) ) {
$asset_manager->enqueue_style( 'featured-image' );
$asset_manager->enqueue_script( 'featured-image' );
$featured_image_l10 = array( 'featured_image_notice' => __( 'SEO issue: The featured image should be at least 200 by 200 pixels to be picked up by Facebook and other social media sites.', 'wordpress-seo' ) );
wp_localize_script( WPSEO_Admin_Asset_Manager::PREFIX . 'metabox', 'wpseoFeaturedImageL10n', $featured_image_l10 );
}
}
}
/**
* Pass some variables to js for upload module.
*
* @return array
*/
public function localize_media_script() {
return array(
'choose_image' => __( 'Use Image', 'wordpress-seo' ),
);
}
/**
* Returns post in metabox context.
*
* @returns WP_Post|array
*/
protected function get_metabox_post() {
$post = filter_input( INPUT_GET, 'post' );
if ( ! empty( $post ) ) {
$post_id = (int) WPSEO_Utils::validate_int( $post );
return get_post( $post_id );
}
if ( isset( $GLOBALS['post'] ) ) {
return $GLOBALS['post'];
}
return array();
}
/**
* Returns an array with shortcode tags for all registered shortcodes.
*
* @return array
*/
private function get_valid_shortcode_tags() {
$shortcode_tags = array();
foreach ( $GLOBALS['shortcode_tags'] as $tag => $description ) {
array_push( $shortcode_tags, $tag );
}
return $shortcode_tags;
}
/**
* Prepares the replace vars for localization.
*
* @return array replace vars
*/
private function get_replace_vars() {
$post = $this->get_metabox_post();
$cached_replacement_vars = array();
$vars_to_cache = array(
'date',
'id',
'sitename',
'sitedesc',
'sep',
'page',
'currenttime',
'currentdate',
'currentday',
'currentmonth',
'currentyear',
);
foreach ( $vars_to_cache as $var ) {
$cached_replacement_vars[ $var ] = wpseo_replace_vars( '%%' . $var . '%%', $post );
}
// Merge custom replace variables with the WordPress ones.
return array_merge( $cached_replacement_vars, $this->get_custom_replace_vars( $post ) );
}
/**
* Gets the custom replace variables for custom taxonomies and fields.
*
* @param WP_Post $post The post to check for custom taxonomies and fields.
*
* @return array Array containing all the replacement variables.
*/
private function get_custom_replace_vars( $post ) {
return array(
'custom_fields' => $this->get_custom_fields_replace_vars( $post ),
'custom_taxonomies' => $this->get_custom_taxonomies_replace_vars( $post ),
);
}
/**
* Gets the custom replace variables for custom taxonomies.
*
* @param WP_Post $post The post to check for custom taxonomies.
*
* @return array Array containing all the replacement variables.
*/
private function get_custom_taxonomies_replace_vars( $post ) {
$taxonomies = get_object_taxonomies( $post, 'objects' );
$custom_replace_vars = array();
foreach ( $taxonomies as $taxonomy_name => $taxonomy ) {
if ( is_string( $taxonomy ) ) { // If attachment, see https://core.trac.wordpress.org/ticket/37368 .
$taxonomy_name = $taxonomy;
$taxonomy = get_taxonomy( $taxonomy_name );
}
if ( $taxonomy->_builtin && $taxonomy->public ) {
continue;
}
$custom_replace_vars[ $taxonomy_name ] = array(
'name' => $taxonomy->name,
'description' => $taxonomy->description,
);
}
return $custom_replace_vars;
}
/**
* Gets the custom replace variables for custom fields.
*
* @param WP_Post $post The post to check for custom fields.
*
* @return array Array containing all the replacement variables.
*/
private function get_custom_fields_replace_vars( $post ) {
$custom_replace_vars = array();
// If no post object is passed, return the empty custom_replace_vars array.
if ( ! is_object( $post ) ) {
return $custom_replace_vars;
}
$custom_fields = get_post_custom( $post->ID );
foreach ( $custom_fields as $custom_field_name => $custom_field ) {
if ( substr( $custom_field_name, 0, 1 ) === '_' ) {
continue;
}
$custom_replace_vars[ $custom_field_name ] = $custom_field[0];
}
return $custom_replace_vars;
}
/**
* Return the SVG for the traffic light in the metabox.
*/
public function traffic_light_svg() {
return <<<SVG
<svg class="yst-traffic-light init" version="1.1" xmlns:x="&ns_extend;" xmlns:i="&ns_ai;" xmlns:graph="&ns_graphs;"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
x="0px" y="0px" viewBox="0 0 30 47" enable-background="new 0 0 30 47" xml:space="preserve">
<g id="BG_1_">
</g>
<g id="traffic_light">
<g>
<g>
<g>
<path fill="#5B2942" d="M22,0H8C3.6,0,0,3.6,0,7.9v31.1C0,43.4,3.6,47,8,47h14c4.4,0,8-3.6,8-7.9V7.9C30,3.6,26.4,0,22,0z
M27.5,38.8c0,3.1-2.6,5.7-5.8,5.7H8.3c-3.2,0-5.8-2.5-5.8-5.7V8.3c0-1.5,0.6-2.9,1.7-4c1.1-1,2.5-1.6,4.1-1.6h13.4
c1.5,0,3,0.6,4.1,1.6c1.1,1.1,1.7,2.5,1.7,4V38.8z"/>
</g>
<g class="traffic-light-color traffic-light-red">
<ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
<ellipse fill="#DC3232" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
<ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
</g>
<g class="traffic-light-color traffic-light-orange">
<ellipse fill="#F49A00" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
<ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
<ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
</g>
<g class="traffic-light-color traffic-light-green">
<ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
<ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
<ellipse fill="#63B22B" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
</g>
<g class="traffic-light-color traffic-light-empty">
<ellipse fill="#C8C8C8" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
<ellipse fill="#C8C8C8" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
<ellipse fill="#C8C8C8" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
</g>
<g class="traffic-light-color traffic-light-init">
<ellipse fill="#5B2942" cx="15" cy="23.5" rx="5.7" ry="5.6"/>
<ellipse fill="#5B2942" cx="15" cy="10.9" rx="5.7" ry="5.6"/>
<ellipse fill="#5B2942" cx="15" cy="36.1" rx="5.7" ry="5.6"/>
</g>
</g>
</g>
</g>
</svg>
SVG;
}
/**
* Generic tab.
*/
public function template_generic_tab() {
// This template belongs to the post scraper so don't echo it if it isn't enqueued.
if ( ! wp_script_is( WPSEO_Admin_Asset_Manager::PREFIX . 'post-scraper' ) ) {
return;
}
echo '<script type="text/html" id="tmpl-generic_tab">
<li class="<# if ( data.classes ) { #>{{data.classes}}<# } #><# if ( data.active ) { #> active<# } #>">
<a class="wpseo_tablink" href="#wpseo_generic" data-score="{{data.score}}">
<span class="wpseo-score-icon {{data.score}}"></span>
<span class="wpseo-tab-prefix">{{data.prefix}}</span>
<span class="wpseo-tab-label">{{data.label}}</span>
<span class="screen-reader-text wpseo-generic-tab-textual-score">{{data.scoreText}}</span>
</a>
<# if ( data.hideable ) { #>
<button type="button" class="remove-tab" aria-label="{{data.removeLabel}}"><span>x</span></button>
<# } #>
</li>
</script>';
}
/**
* Keyword tab for enabling analysis of multiple keywords.
*/
public function template_keyword_tab() {
// This template belongs to the post scraper so don't echo it if it isn't enqueued.
if ( ! wp_script_is( WPSEO_Admin_Asset_Manager::PREFIX . 'post-scraper' ) ) {
return;
}
echo '<script type="text/html" id="tmpl-keyword_tab">
<li class="<# if ( data.classes ) { #>{{data.classes}}<# } #><# if ( data.active ) { #> active<# } #>">
<a class="wpseo_tablink" href="#wpseo_content" data-keyword="{{data.keyword}}" data-score="{{data.score}}">
<span class="wpseo-score-icon {{data.score}}"></span>
<span class="wpseo-tab-prefix">{{data.prefix}}</span>
<em class="wpseo-keyword">{{data.label}}</em>
<span class="screen-reader-text wpseo-keyword-tab-textual-score">{{data.scoreText}}</span>
</a>
<# if ( data.hideable ) { #>
<button type="button" class="remove-keyword" aria-label="{{data.removeLabel}}"><span>x</span></button>
<# } #>
</li>
</script>';
}
/**
* @param string $page The page to check for the post overview page.
*
* @return bool Whether or not the given page is the post overview page.
*/
public static function is_post_overview( $page ) {
return 'edit.php' === $page;
}
/**
* @param string $page The page to check for the post edit page.
*
* @return bool Whether or not the given page is the post edit page.
*/
public static function is_post_edit( $page ) {
return 'post.php' === $page
|| 'post-new.php' === $page;
}
/********************** DEPRECATED METHODS **********************/
// @codeCoverageIgnoreStart
/**
* Adds the Yoast SEO box.
*
* @deprecated 1.4.24
* @deprecated use WPSEO_Metabox::add_meta_box()
* @see WPSEO_Meta::add_meta_box()
*/
public function add_custom_box() {
_deprecated_function( __METHOD__, 'WPSEO 1.4.24', 'WPSEO_Metabox::add_meta_box()' );
$this->add_meta_box();
}
/**
* Retrieve the meta boxes for the given post type.
*
* @deprecated 1.5.0
* @deprecated use WPSEO_Meta::get_meta_field_defs()
* @see WPSEO_Meta::get_meta_field_defs()
*
* @param string $post_type The post type for which to get the meta fields.
*
* @return array
*/
public function get_meta_boxes( $post_type = 'post' ) {
_deprecated_function( __METHOD__, 'WPSEO 1.5.0', 'WPSEO_Meta::get_meta_field_defs()' );
return $this->get_meta_field_defs( 'general', $post_type );
}
/**
* Pass some variables to js.
*
* @deprecated 1.5.0
* @deprecated use WPSEO_Meta::localize_script()
* @see WPSEO_Meta::localize_script()
*/
public function script() {
_deprecated_function( __METHOD__, 'WPSEO 1.5.0', 'WPSEO_Meta::localize_script()' );
return $this->localize_script();
}
/**
* @deprecated 3.0 Removed, use javascript functions instead.
*
* @param string $string Deprecated.
*
* @return string
*/
public function strtolower_utf8( $string ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', esc_html__( 'Use javascript instead.', 'wordpress-seo' ) );
return $string;
}
/**
* @deprecated 3.0 Removed.
*
* @return array
*/
public function localize_script() {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0 Removed, use javascript functions instead.
*
* @return string
*/
public function snippet() {
_deprecated_function( __METHOD__, 'WPSEO 3.0', esc_html__( 'Use javascript instead.', 'wordpress-seo' ) );
return '';
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::posts_filter_dropdown instead.
*/
public function posts_filter_dropdown() {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::posts_filter_dropdown' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
$meta_columns->posts_filter_dropdown();
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::column_heading instead.
*
* @param array $columns Already existing columns.
*
* @return array
*/
public function column_heading( $columns ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::column_heading' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
return $meta_columns->column_heading( $columns );
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::column_content instead.
*
* @param string $column_name Column to display the content for.
* @param int $post_id Post to display the column content for.
*/
public function column_content( $column_name, $post_id ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::column_content' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
$meta_columns->column_content( $column_name, $post_id );
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::column_sort instead.
*
* @param array $columns Columns appended with their orderby variable.
*
* @return array
*/
public function column_sort( $columns ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::column_sort' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
return $meta_columns->column_sort( $columns );
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::column_sort_orderby instead.
*
* @param array $vars Query variables.
*
* @return array
*/
public function column_sort_orderby( $vars ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::column_sort_orderby' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
return $meta_columns->column_sort_orderby( $vars );
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::column_hidden instead.
*
* @param array|false $result The hidden columns.
* @param string $option The option name used to set which columns should be hidden.
* @param WP_User $user The User.
*
* @return array|false $result
*/
public function column_hidden( $result, $option, $user ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::column_hidden' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
return $meta_columns->column_hidden( $result, $option, $user );
}
/**
* @deprecated 3.0 Use WPSEO_Meta_Columns::seo_score_posts_where instead.
*
* @param string $where Where clause.
*
* @return string
*/
public function seo_score_posts_where( $where ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0', 'WPSEO_Metabox_Columns::seo_score_posts_where' );
/** @var WPSEO_Meta_Columns $meta_columns */
$meta_columns = $GLOBALS['wpseo_meta_columns'];
return $meta_columns->seo_score_posts_where( $where );
}
/**
* @deprecated 3.0 Removed.
*
* @param int $post_id Post to retrieve the title for.
*
* @return string
*/
public function page_title( $post_id ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return '';
}
/**
* @deprecated 3.0
*
* @param array $array Array to sort, array is returned sorted.
* @param string $key Key to sort array by.
*/
public function aasort( &$array, $key ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param object $post Post to output the page analysis results for.
*
* @return string
*/
public function linkdex_output( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return '';
}
/**
* @deprecated 3.0
*
* @param object $post Post to calculate the results for.
*
* @return array|WP_Error
*/
public function calculate_results( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0
*
* @param WP_Post $post Post object instance.
*
* @return array
*/
public function get_sample_permalink( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0
*
* @param array $results The results array used to store results.
* @param int $score_value The score value.
* @param string $score_message The score message.
* @param string $score_label The label of the score to use in the results array.
* @param string $raw_score The raw score, to be used by other filters.
*/
public function save_score_result( &$results, $score_value, $score_message, $score_label, $raw_score = null ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param string $input_string String to clean up.
* @param bool $remove_optional_characters Whether or not to do a cleanup of optional chars too.
*
* @return string
*/
public function strip_separators_and_fold( $input_string, $remove_optional_characters ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return '';
}
/**
* @deprecated 3.0
*
* @param array $job Job data array.
* @param array $results Results set by reference.
*/
public function check_double_focus_keyword( $job, &$results ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param string $keyword The keyword to check for stopwords.
* @param array $results The results array.
*/
public function score_keyword( $keyword, &$results ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param array $job The job array holding both the keyword and the URLs.
* @param array $results The results array.
*/
public function score_url( $job, &$results ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param array $job The job array holding both the keyword versions.
* @param array $results The results array.
*/
public function score_title( $job, &$results ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param array $job The job array holding both the keyword versions.
* @param array $results The results array.
* @param array $anchor_texts The array holding all anchors in the document.
* @param array $count The number of anchors in the document, grouped by type.
*/
public function score_anchor_texts( $job, &$results, $anchor_texts, $count ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param object $xpath An XPATH object of the current document.
*
* @return array
*/
public function get_anchor_texts( &$xpath ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0
*
* @param object $xpath An XPATH object of the current document.
*
* @return array
*/
public function get_anchor_count( &$xpath ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0
*
* @param array $job The job array holding both the keyword versions.
* @param array $results The results array.
* @param array $imgs The array with images alt texts.
*/
public function score_images_alt_text( $job, &$results, $imgs ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param int $post_id The post to find images in.
* @param string $body The post content to find images in.
* @param array $imgs The array holding the image information.
*
* @return array The updated images array.
*/
public function get_images_alt_text( $post_id, $body, $imgs ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0
*
* @param array $job The array holding the keywords.
* @param array $results The results array.
* @param array $headings The headings found in the document.
*/
public function score_headings( $job, &$results, $headings ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param string $postcontent Post content to find headings in.
*
* @return array Array of heading texts.
*/
public function get_headings( $postcontent ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return array();
}
/**
* @deprecated 3.0
*
* @param array $job The array holding the keywords.
* @param array $results The results array.
* @param string $description The meta description.
* @param int $maxlength The maximum length of the meta description.
*/
public function score_description( $job, &$results, $description, $maxlength = 155 ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param array $job The array holding the keywords.
* @param array $results The results array.
* @param string $body The body.
* @param string $firstp The first paragraph.
*/
public function score_body( $job, &$results, $body, $firstp ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
}
/**
* @deprecated 3.0
*
* @param object $post The post object.
*
* @return string The post content.
*/
public function get_body( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return '';
}
/**
* @deprecated 3.0
*
* @param string $body The post content to retrieve the first paragraph from.
*
* @return string
*/
public function get_first_paragraph( $body ) {
_deprecated_function( __METHOD__, 'WPSEO 3.0' );
return '';
}
/**
* @deprecated 3.2
*
* Retrieves the title template.
*
* @param object $post Metabox post.
*
* @return string
*/
public static function get_title_template( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.2', 'WPSEO_Post_Scraper::get_title_template' );
return '';
}
/**
* @deprecated 3.2
*
* Retrieves the metadesc template.
*
* @param object $post Metabox post.
*
* @return string
*/
public static function get_metadesc_template( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.2', 'WPSEO_Post_Scraper::get_metadesc_template' );
return '';
}
/**
* @deprecated 3.2
* Retrieve a post date when post is published, or return current date when it's not.
*
* @param WP_Post $post The post for which to retrieve the post date.
*
* @return string
*/
public function get_post_date( $post ) {
_deprecated_function( __METHOD__, 'WPSEO 3.2', 'WPSEO_Post_Scraper::get_post_date' );
return '';
}
// @codeCoverageIgnoreEnd
}
|
overstreetce/Portfolio-Site
|
wp-content/plugins/wordpress-seo/admin/metabox/class-metabox.php
|
PHP
|
gpl-2.0
| 57,389
|
#ifndef NODECACHE_H_
#define NODECACHE_H_
#include <vector>
#include <string>
#include "node.h"
/*!
Caches string values per node based on the node.index().
The node index guaranteed to be unique per node tree since the index is reset
every time a new tree is generated.
*/
class NodeCache
{
public:
NodeCache() { }
virtual ~NodeCache() { }
bool contains(const AbstractNode &node) const {
return !(*this)[node].empty();
}
/*! Returns a reference to the cached string copy. NB! don't rely on
* this reference to be valid for long - if the cache is resized
* internally, existing values are lost. */
const std::string & operator[](const AbstractNode &node) const {
if (this->cache.size() > node.index()) return this->cache[node.index()];
else return this->nullvalue;
}
/*! Returns a reference to the cached string copy. NB! don't rely on
* this reference to be valid for long - if the cache is resized
* internally, existing values are lost. */
const std::string &insert(const class AbstractNode &node, const std::string & value) {
if (this->cache.size() <= node.index()) this->cache.resize(node.index() + 1);
return this->cache[node.index()] = value;
}
void remove(const class AbstractNode &node) {
if (this->cache.size() > node.index()) this->cache[node.index()] = std::string();
}
void clear() {
this->cache.clear();
}
private:
std::vector<std::string> cache;
std::string nullvalue;
};
#endif
|
battlesnake/OpenSCAD
|
src/nodecache.h
|
C
|
gpl-2.0
| 1,471
|
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# 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.
#
# Copyright Buildbot Team Members
import weakref
from twisted.application import internet
from twisted.application import service
from twisted.internet import defer
from twisted.python import failure
from twisted.python import log
from twisted.spread import pb
from zope.interface import implements
from buildbot import config
from buildbot import interfaces
from buildbot.process import buildrequest
from buildbot.process import slavebuilder
from buildbot.process.build import Build
from buildbot.process.properties import Properties
from buildbot.process.slavebuilder import BUILDING
from buildbot.status.builder import RETRY
from buildbot.status.buildrequest import BuildRequestStatus
from buildbot.status.progress import Expectations
def enforceChosenSlave(bldr, slavebuilder, breq):
if 'slavename' in breq.properties:
slavename = breq.properties['slavename']
if isinstance(slavename, basestring):
return slavename == slavebuilder.slave.slavename
return True
class Builder(config.ReconfigurableServiceMixin,
pb.Referenceable,
service.MultiService):
# reconfigure builders before slaves
reconfig_priority = 196
def __init__(self, name, _addServices=True):
service.MultiService.__init__(self)
self.name = name
# this is created the first time we get a good build
self.expectations = None
# build/wannabuild slots: Build objects move along this sequence
self.building = []
# old_building holds active builds that were stolen from a predecessor
self.old_building = weakref.WeakKeyDictionary()
# buildslaves which have connected but which are not yet available.
# These are always in the ATTACHING state.
self.attaching_slaves = []
# buildslaves at our disposal. Each SlaveBuilder instance has a
# .state that is IDLE, PINGING, or BUILDING. "PINGING" is used when a
# Build is about to start, to make sure that they're still alive.
self.slaves = []
self.config = None
self.builder_status = None
if _addServices:
self.reclaim_svc = internet.TimerService(10 * 60,
self.reclaimAllBuilds)
self.reclaim_svc.setServiceParent(self)
# update big status every 30 minutes, working around #1980
self.updateStatusService = internet.TimerService(30 * 60,
self.updateBigStatus)
self.updateStatusService.setServiceParent(self)
def reconfigService(self, new_config):
# find this builder in the config
for builder_config in new_config.builders:
if builder_config.name == self.name:
break
else:
assert 0, "no config found for builder '%s'" % self.name
# set up a builder status object on the first reconfig
if not self.builder_status:
self.builder_status = self.master.status.builderAdded(
builder_config.name,
builder_config.builddir,
builder_config.category,
builder_config.description)
self.config = builder_config
self.builder_status.setDescription(builder_config.description)
self.builder_status.setCategory(builder_config.category)
self.builder_status.setSlavenames(self.config.slavenames)
self.builder_status.setCacheSize(new_config.caches['Builds'])
# if we have any slavebuilders attached which are no longer configured,
# drop them.
new_slavenames = set(builder_config.slavenames)
self.slaves = [s for s in self.slaves
if s.slave.slavename in new_slavenames]
return defer.succeed(None)
def stopService(self):
d = defer.maybeDeferred(lambda:
service.MultiService.stopService(self))
return d
def __repr__(self):
return "<Builder '%r' at %d>" % (self.name, id(self))
@defer.inlineCallbacks
def getOldestRequestTime(self):
"""Returns the submitted_at of the oldest unclaimed build request for
this builder, or None if there are no build requests.
@returns: datetime instance or None, via Deferred
"""
unclaimed = yield self.master.db.buildrequests.getBuildRequests(
buildername=self.name, claimed=False)
if unclaimed:
unclaimed = sorted([brd['submitted_at'] for brd in unclaimed])
defer.returnValue(unclaimed[0])
else:
defer.returnValue(None)
def reclaimAllBuilds(self):
brids = set()
for b in self.building:
brids.update([br.id for br in b.requests])
for b in self.old_building:
brids.update([br.id for br in b.requests])
if not brids:
return defer.succeed(None)
d = self.master.db.buildrequests.reclaimBuildRequests(brids)
d.addErrback(log.err, 'while re-claiming running BuildRequests')
return d
def getBuild(self, number):
for b in self.building:
if b.build_status and b.build_status.number == number:
return b
for b in self.old_building.keys():
if b.build_status and b.build_status.number == number:
return b
return None
def addLatentSlave(self, slave):
assert interfaces.ILatentBuildSlave.providedBy(slave)
for s in self.slaves:
if s == slave:
break
else:
sb = slavebuilder.LatentSlaveBuilder(slave, self)
self.builder_status.addPointEvent(
['added', 'latent', slave.slavename])
self.slaves.append(sb)
self.botmaster.maybeStartBuildsForBuilder(self.name)
def attached(self, slave, remote, commands):
"""This is invoked by the BuildSlave when the self.slavename bot
registers their builder.
@type slave: L{buildbot.buildslave.BuildSlave}
@param slave: the BuildSlave that represents the buildslave as a whole
@type remote: L{twisted.spread.pb.RemoteReference}
@param remote: a reference to the L{buildbot.slave.bot.SlaveBuilder}
@type commands: dict: string -> string, or None
@param commands: provides the slave's version of each RemoteCommand
@rtype: L{twisted.internet.defer.Deferred}
@return: a Deferred that fires (with 'self') when the slave-side
builder is fully attached and ready to accept commands.
"""
for s in self.attaching_slaves + self.slaves:
if s.slave == slave:
# already attached to them. This is fairly common, since
# attached() gets called each time we receive the builder
# list from the slave, and we ask for it each time we add or
# remove a builder. So if the slave is hosting builders
# A,B,C, and the config file changes A, we'll remove A and
# re-add it, triggering two builder-list requests, getting
# two redundant calls to attached() for B, and another two
# for C.
#
# Therefore, when we see that we're already attached, we can
# just ignore it.
return defer.succeed(self)
sb = slavebuilder.SlaveBuilder()
sb.setBuilder(self)
self.attaching_slaves.append(sb)
d = sb.attached(slave, remote, commands)
d.addCallback(self._attached)
d.addErrback(self._not_attached, slave)
return d
def _attached(self, sb):
self.builder_status.addPointEvent(['connect', sb.slave.slavename])
self.attaching_slaves.remove(sb)
self.slaves.append(sb)
self.updateBigStatus()
return self
def _not_attached(self, why, slave):
# already log.err'ed by SlaveBuilder._attachFailure
# TODO: remove from self.slaves (except that detached() should get
# run first, right?)
log.err(why, 'slave failed to attach')
self.builder_status.addPointEvent(['failed', 'connect',
slave.slavename])
# TODO: add an HTMLLogFile of the exception
def detached(self, slave):
"""This is called when the connection to the bot is lost."""
for sb in self.attaching_slaves + self.slaves:
if sb.slave == slave:
break
else:
log.msg("WEIRD: Builder.detached(%s) (%s)"
" not in attaching_slaves(%s)"
" or slaves(%s)" % (slave, slave.slavename,
self.attaching_slaves,
self.slaves))
return
if sb.state == BUILDING:
# the Build's .lostRemote method (invoked by a notifyOnDisconnect
# handler) will cause the Build to be stopped, probably right
# after the notifyOnDisconnect that invoked us finishes running.
pass
if sb in self.attaching_slaves:
self.attaching_slaves.remove(sb)
if sb in self.slaves:
self.slaves.remove(sb)
self.builder_status.addPointEvent(['disconnect', slave.slavename])
sb.detached() # inform the SlaveBuilder that their slave went away
self.updateBigStatus()
def updateBigStatus(self):
try:
# Catch exceptions here, since this is called in a LoopingCall.
if not self.builder_status:
return
if not self.slaves:
self.builder_status.setBigState("offline")
elif self.building or self.old_building:
self.builder_status.setBigState("building")
else:
self.builder_status.setBigState("idle")
except Exception:
log.err(None, "while trying to update status of builder '%s'" % (self.name,))
def getAvailableSlaves(self):
return [sb for sb in self.slaves if sb.isAvailable()]
def canStartWithSlavebuilder(self, slavebuilder):
locks = [(self.botmaster.getLockFromLockAccess(access), access)
for access in self.config.locks]
return Build.canStartWithSlavebuilder(locks, slavebuilder)
def canStartBuild(self, slavebuilder, breq):
if callable(self.config.canStartBuild):
return defer.maybeDeferred(self.config.canStartBuild, self, slavebuilder, breq)
return defer.succeed(True)
@defer.inlineCallbacks
def _startBuildFor(self, slavebuilder, buildrequests):
"""Start a build on the given slave.
@param build: the L{base.Build} to start
@param sb: the L{SlaveBuilder} which will host this build
@return: (via Deferred) boolean indicating that the build was
succesfully started.
"""
# as of the Python versions supported now, try/finally can't be used
# with a generator expression. So instead, we push cleanup functions
# into a list so that, at any point, we can abort this operation.
cleanups = []
def run_cleanups():
try:
while cleanups:
fn = cleanups.pop()
fn()
except:
log.err(failure.Failure(), "while running %r" % (run_cleanups,))
# the last cleanup we want to perform is to update the big
# status based on any other cleanup
cleanups.append(lambda: self.updateBigStatus())
build = self.config.factory.newBuild(buildrequests)
build.setBuilder(self)
log.msg("starting build %s using slave %s" % (build, slavebuilder))
# set up locks
build.setLocks(self.config.locks)
cleanups.append(lambda: slavebuilder.slave.releaseLocks())
if len(self.config.env) > 0:
build.setSlaveEnvironment(self.config.env)
# append the build to self.building
self.building.append(build)
cleanups.append(lambda: self.building.remove(build))
# update the big status accordingly
self.updateBigStatus()
try:
ready = yield slavebuilder.prepare(self.builder_status, build)
except:
log.err(failure.Failure(), 'while preparing slavebuilder:')
ready = False
# If prepare returns True then it is ready and we start a build
# If it returns false then we don't start a new build.
if not ready:
log.msg("slave %s can't build %s after all; re-queueing the "
"request" % (build, slavebuilder))
run_cleanups()
defer.returnValue(False)
return
# ping the slave to make sure they're still there. If they've
# fallen off the map (due to a NAT timeout or something), this
# will fail in a couple of minutes, depending upon the TCP
# timeout.
#
# TODO: This can unnecessarily suspend the starting of a build, in
# situations where the slave is live but is pushing lots of data to
# us in a build.
log.msg("starting build %s.. pinging the slave %s"
% (build, slavebuilder))
try:
ping_success = yield slavebuilder.ping()
except:
log.err(failure.Failure(), 'while pinging slave before build:')
ping_success = False
if not ping_success:
log.msg("slave ping failed; re-queueing the request")
run_cleanups()
defer.returnValue(False)
return
# The buildslave is ready to go. slavebuilder.buildStarted() sets its
# state to BUILDING (so we won't try to use it for any other builds).
# This gets set back to IDLE by the Build itself when it finishes.
slavebuilder.buildStarted()
cleanups.append(lambda: slavebuilder.buildFinished())
# tell the remote that it's starting a build, too
try:
yield slavebuilder.remote.callRemote("startBuild")
except:
log.err(failure.Failure(), 'while calling remote startBuild:')
run_cleanups()
defer.returnValue(False)
return
# create the BuildStatus object that goes with the Build
bs = self.builder_status.newBuild()
# record the build in the db - one row per buildrequest
try:
bids = []
for req in build.requests:
bid = yield self.master.db.builds.addBuild(req.id, bs.number)
bids.append(bid)
except:
log.err(failure.Failure(), 'while adding rows to build table:')
run_cleanups()
defer.returnValue(False)
return
# IMPORTANT: no yielding is allowed from here to the startBuild call!
# it's possible that we lost the slave remote between the ping above
# and now. If so, bail out. The build.startBuild call below transfers
# responsibility for monitoring this connection to the Build instance,
# so this check ensures we hand off a working connection.
if not slavebuilder.remote:
log.msg("slave disappeared before build could start")
run_cleanups()
defer.returnValue(False)
return
# let status know
self.master.status.build_started(req.id, self.name, bs)
# start the build. This will first set up the steps, then tell the
# BuildStatus that it has started, which will announce it to the world
# (through our BuilderStatus object, which is its parent). Finally it
# will start the actual build process. This is done with a fresh
# Deferred since _startBuildFor should not wait until the build is
# finished. This uses `maybeDeferred` to ensure that any exceptions
# raised by startBuild are treated as deferred errbacks (see
# http://trac.buildbot.net/ticket/2428).
d = defer.maybeDeferred(build.startBuild,
bs, self.expectations, slavebuilder)
d.addCallback(self.buildFinished, slavebuilder, bids)
# this shouldn't happen. if it does, the slave will be wedged
d.addErrback(log.err, 'from a running build; this is a '
'serious error - please file a bug at http://buildbot.net')
# make sure the builder's status is represented correctly
self.updateBigStatus()
defer.returnValue(True)
def setupProperties(self, props):
props.setProperty("buildername", self.name, "Builder")
if len(self.config.properties) > 0:
for propertyname in self.config.properties:
props.setProperty(propertyname,
self.config.properties[propertyname],
"Builder")
def buildFinished(self, build, sb, bids):
"""This is called when the Build has finished (either success or
failure). Any exceptions during the build are reported with
results=FAILURE, not with an errback."""
# by the time we get here, the Build has already released the slave,
# which will trigger a check for any now-possible build requests
# (maybeStartBuilds)
# mark the builds as finished, although since nothing ever reads this
# table, it's not too important that it complete successfully
d = self.master.db.builds.finishBuilds(bids)
d.addErrback(log.err, 'while marking builds as finished (ignored)')
results = build.build_status.getResults()
self.building.remove(build)
if results == RETRY:
self._resubmit_buildreqs(build).addErrback(log.err)
else:
brids = [br.id for br in build.requests]
db = self.master.db
d = db.buildrequests.completeBuildRequests(brids, results)
d.addCallback(
lambda _: self._maybeBuildsetsComplete(build.requests))
# nothing in particular to do with this deferred, so just log it if
# it fails..
d.addErrback(log.err, 'while marking build requests as completed')
if sb.slave:
sb.slave.releaseLocks()
self.updateBigStatus()
@defer.inlineCallbacks
def _maybeBuildsetsComplete(self, requests):
# inform the master that we may have completed a number of buildsets
for br in requests:
yield self.master.maybeBuildsetComplete(br.bsid)
def _resubmit_buildreqs(self, build):
brids = [br.id for br in build.requests]
return self.master.db.buildrequests.unclaimBuildRequests(brids)
def setExpectations(self, progress):
"""Mark the build as successful and update expectations for the next
build. Only call this when the build did not fail in any way that
would invalidate the time expectations generated by it. (if the
compile failed and thus terminated early, we can't use the last
build to predict how long the next one will take).
"""
if self.expectations:
self.expectations.update(progress)
else:
# the first time we get a good build, create our Expectations
# based upon its results
self.expectations = Expectations(progress)
log.msg("new expectations: %s seconds" %
self.expectations.expectedBuildTime())
# Build Creation
@defer.inlineCallbacks
def maybeStartBuild(self, slavebuilder, breqs):
# This method is called by the botmaster whenever this builder should
# start a set of buildrequests on a slave. Do not call this method
# directly - use master.botmaster.maybeStartBuildsForBuilder, or one of
# the other similar methods if more appropriate
# first, if we're not running, then don't start builds; stopService
# uses this to ensure that any ongoing maybeStartBuild invocations
# are complete before it stops.
if not self.running:
defer.returnValue(False)
return
# If the build fails from here on out (e.g., because a slave has failed),
# it will be handled outside of this function. TODO: test that!
build_started = yield self._startBuildFor(slavebuilder, breqs)
defer.returnValue(build_started)
# a few utility functions to make the maybeStartBuild a bit shorter and
# easier to read
def getMergeRequestsFn(self):
"""Helper function to determine which mergeRequests function to use
from L{_mergeRequests}, or None for no merging"""
# first, seek through builder, global, and the default
mergeRequests_fn = self.config.mergeRequests
if mergeRequests_fn is None:
mergeRequests_fn = self.master.config.mergeRequests
if mergeRequests_fn is None:
mergeRequests_fn = True
# then translate False and True properly
if mergeRequests_fn is False:
mergeRequests_fn = None
elif mergeRequests_fn is True:
mergeRequests_fn = Builder._defaultMergeRequestFn
return mergeRequests_fn
def _defaultMergeRequestFn(self, req1, req2):
return req1.canBeMergedWith(req2)
class BuilderControl:
implements(interfaces.IBuilderControl)
def __init__(self, builder, control):
self.original = builder
self.control = control
def submitBuildRequest(self, ss, reason, props=None):
d = ss.getSourceStampSetId(self.control.master)
def add_buildset(sourcestampsetid):
return self.control.master.addBuildset(
builderNames=[self.original.name],
sourcestampsetid=sourcestampsetid, reason=reason, properties=props)
d.addCallback(add_buildset)
def get_brs(xxx_todo_changeme):
(bsid, brids) = xxx_todo_changeme
brs = BuildRequestStatus(self.original.name,
brids[self.original.name],
self.control.master.status)
return brs
d.addCallback(get_brs)
return d
@defer.inlineCallbacks
def rebuildBuild(self, bs, reason="<rebuild, no reason given>", extraProperties=None, absolute=True):
if not bs.isFinished():
return
# Make a copy of the properties so as not to modify the original build.
properties = Properties()
# Don't include runtime-set properties in a rebuild request
properties.updateFromPropertiesNoRuntime(bs.getProperties())
if extraProperties is None:
properties.updateFromProperties(extraProperties)
properties_dict = dict((k, (v, s)) for (k, v, s) in properties.asList())
ssList = bs.getSourceStamps(absolute=absolute)
if ssList:
sourcestampsetid = yield ssList[0].getSourceStampSetId(self.control.master)
dl = []
for ss in ssList[1:]:
# add deferred to the list
dl.append(ss.addSourceStampToDatabase(self.control.master, sourcestampsetid))
yield defer.gatherResults(dl)
bsid, brids = yield self.control.master.addBuildset(
builderNames=[self.original.name],
sourcestampsetid=sourcestampsetid,
reason=reason,
properties=properties_dict)
defer.returnValue((bsid, brids))
else:
log.msg('Cannot start rebuild, rebuild has no sourcestamps for a new build')
defer.returnValue(None)
@defer.inlineCallbacks
def getPendingBuildRequestControls(self):
master = self.original.master
brdicts = yield master.db.buildrequests.getBuildRequests(
buildername=self.original.name,
claimed=False)
# convert those into BuildRequest objects
buildrequests = []
for brdict in brdicts:
br = yield buildrequest.BuildRequest.fromBrdict(
self.control.master, brdict)
buildrequests.append(br)
# and return the corresponding control objects
defer.returnValue([buildrequest.BuildRequestControl(self.original, r)
for r in buildrequests])
def getBuild(self, number):
return self.original.getBuild(number)
def ping(self):
if not self.original.slaves:
self.original.builder_status.addPointEvent(["ping", "no slave"])
return defer.succeed(False) # interfaces.NoSlaveError
dl = []
for s in self.original.slaves:
dl.append(s.ping(self.original.builder_status))
d = defer.DeferredList(dl)
d.addCallback(self._gatherPingResults)
return d
def _gatherPingResults(self, res):
for ignored, success in res:
if not success:
return False
return True
|
mitya57/debian-buildbot
|
buildbot/process/builder.py
|
Python
|
gpl-2.0
| 25,892
|
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
* ShareThis Integration
*
* Enables ShareThis integration.
*
* @class WC_ShareThis
* @extends WC_Integration
* @version 1.6.4
* @package WooCommerce/Classes/Integrations
* @author WooThemes
*/
class WC_ShareThis extends WC_Integration {
/** @var string Default code for share this */
var $default_code;
/**
* Init and hook in the integration.
*
* @access public
* @return void
*/
public function __construct() {
$this->id = 'sharethis';
$this->method_title = __( 'ShareThis', 'woocommerce' );
$this->method_description = __( 'ShareThis offers a sharing widget which will allow customers to share links to products with their friends.', 'woocommerce' );
$this->default_code = '<div class="social">
<iframe src="https://www.facebook.com/plugins/like.php?href={permalink}&layout=button_count&show_faces=false&width=100&action=like&colorscheme=light&height=21" style="border:none; overflow:hidden; width:100px; height:21px;"></iframe>
<span class="st_twitter"></span><span class="st_email"></span><span class="st_sharethis" st_image="{image}"></span><span class="st_plusone_button"></span>
</div>';
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->publisher_id = $this->get_option( 'publisher_id' );
$this->sharethis_code = $this->get_option( 'sharethis_code', $this->default_code );
// Actions
add_action( 'woocommerce_update_options_integration_sharethis', array( $this, 'process_admin_options' ) );
// Share widget
add_action( 'woocommerce_share', array( $this, 'sharethis_code' ) );
}
/**
* Initialise Settings Form Fields
*
* @access public
* @return void
*/
function init_form_fields() {
$this->form_fields = array(
'publisher_id' => array(
'title' => __( 'ShareThis Publisher ID', 'woocommerce' ),
'description' => sprintf( __( 'Enter your %1$sShareThis publisher ID%2$s to show social sharing buttons on product pages.', 'woocommerce' ), '<a href="http://sharethis.com/account/">', '</a>' ),
'type' => 'text',
'default' => get_option('woocommerce_sharethis')
),
'sharethis_code' => array(
'title' => __( 'ShareThis Code', 'woocommerce' ),
'description' => __( 'You can tweak the ShareThis code by editing this option.', 'woocommerce' ),
'type' => 'textarea',
'default' => $this->default_code
)
);
}
/**
* Output share code.
*
* @access public
* @return void
*/
function sharethis_code() {
global $post;
if ( $this->publisher_id ) {
$attachment_image_src = wp_get_attachment_image_src( $thumbnail_id, 'large' );
$thumbnail = ( $thumbnail_id = get_post_thumbnail_id( $post->ID ) ) ? current( $attachment_image_src ) : '';
$sharethis = ( is_ssl() ) ? 'https://ws.sharethis.com/button/buttons.js' : 'http://w.sharethis.com/button/buttons.js';
$sharethis_code = str_replace( '{permalink}', urlencode( get_permalink( $post->ID ) ), $this->sharethis_code );
if ( isset( $thumbnail ) ) $sharethis_code = str_replace( '{image}', urlencode( $thumbnail ), $sharethis_code );
echo str_replace( '&', '&', $sharethis_code );
echo '<script type="text/javascript">var switchTo5x=true;</script><script type="text/javascript" src="' . $sharethis . '"></script>';
echo '<script type="text/javascript">stLight.options({publisher:"' . $this->publisher_id . '"});</script>';
}
}
}
/**
* Add the integration to WooCommerce.
*
* @package WooCommerce/Classes/Integrations
* @access public
* @param array $integrations
* @return array
*/
function add_sharethis_integration( $integrations ) {
$integrations[] = 'WC_ShareThis';
return $integrations;
}
add_filter('woocommerce_integrations', 'add_sharethis_integration' );
|
rongandat/sallumeh
|
wp-content/plugins/woocommerce/classes/integrations/sharethis/class-wc-sharethis.php
|
PHP
|
gpl-2.0
| 4,086
|
#include <iostream>
#include "converter.hpp"
#include "STL.hpp"
#include "holder.hpp"
#include <CXX/Objects.hxx>
using namespace std;
using namespace Py;
using ConvertXY::PyTuple;
using ConvertXY::PySet;
using ConvertXY::PyString;
void initialize() {
Py_Initialize();
//import_array();
}
int main() {
initialize();
List list;
list.append(Long(1));
list.append(Long(2));
cout << list << endl;
vector <int> v;
ConvertXY::convert(list.ptr(), v);
Long el(5);
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << ",";
}
cout << endl;
PyObject *list2(0);
list2 = ConvertXY::convert(v);
Py::List list3(list2);
cout << list3 << endl;
vector<string> string_vec;
string_vec.push_back("foo");
string_vec.push_back("bar");
PyObject *string_list = ConvertXY::convert(string_vec);
Py::List pstring_list(string_list);
cout << pstring_list << endl;
PyObject *string_tuple = ConvertXY::convert_override<PyTuple<PyString> >(string_vec);
Py::Tuple pstring_tuple(string_tuple);
cout << pstring_tuple << endl;
PyObject *string_set = ConvertXY::convert_override<PySet<PyString> >(string_vec);
Py::Object pstring_set(string_set);
cout << pstring_set << endl;
vector <string> get_set_back_as_vec;
ConvertXY::convert(string_set, get_set_back_as_vec);
for (size_t i = 0; i < v.size(); i++) {
cout << get_set_back_as_vec[i] << ",";
}
cout << endl;
Dict d;
d["hi"] = Py::String("3");
d["hello"] = Py::Int(4);
d["apple"] = Py::Float(4.4);
d["banana"] = Py::String("8.8");
map<string, int> mymap;
ConvertXY::convert(d.ptr(), mymap);
for (map<string, int>::iterator it(mymap.begin()); it != mymap.end(); it++) {
cout << "key: " << it->first << " value: " << it->second << endl;
}
PyObject *dict_back = ConvertXY::convert(mymap);
cout << Py::Object(dict_back) << endl;
//long y;
//ConvertXY::convert(el.ptr(), y);
return 1;
}
|
fubincom/convert-xy
|
2.x/ConvertXY/example.cpp
|
C++
|
gpl-2.0
| 1,932
|
/*
* Generic pidhash and scalable, time-bounded PID allocator
*
* (C) 2002-2003 William Irwin, IBM
* (C) 2004 William Irwin, Oracle
* (C) 2002-2004 Ingo Molnar, Red Hat
*
* pid-structures are backing objects for tasks sharing a given ID to chain
* against. There is very little to them aside from hashing them and
* parking tasks using given ID's on a list.
*
* The hash is always changed with the tasklist_lock write-acquired,
* and the hash is only accessed with the tasklist_lock at least
* read-acquired, so there's no additional SMP locking needed here.
*
* We have a list of bitmap pages, which bitmaps represent the PID space.
* Allocating and freeing PIDs is completely lockless. The worst-case
* allocation scenario when all but one out of 1 million PIDs possible are
* allocated already: the scanning of 32 list entries and at most PAGE_SIZE
* bytes. The typical fastpath is a single successful setbit. Freeing is O(1).
*
* Pid namespaces:
* (C) 2007 Pavel Emelyanov <xemul@openvz.org>, OpenVZ, SWsoft Inc.
* (C) 2007 Sukadev Bhattiprolu <sukadev@us.ibm.com>, IBM
* Many thanks to Oleg Nesterov for comments and help
*
*/
#include <linux/mm.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/rculist.h>
#include <linux/bootmem.h>
#include <linux/hash.h>
#include <linux/pid_namespace.h>
#include <linux/init_task.h>
#include <linux/syscalls.h>
#define pid_hashfn(nr, ns) \
hash_long((unsigned long)nr + (unsigned long)ns, pidhash_shift)
static struct hlist_head *pid_hash;
static unsigned int pidhash_shift = 4;
struct pid init_struct_pid = INIT_STRUCT_PID;
int pid_max = PID_MAX_DEFAULT;
#define RESERVED_PIDS 300
int pid_max_min = RESERVED_PIDS + 1;
int pid_max_max = PID_MAX_LIMIT;
#define BITS_PER_PAGE (PAGE_SIZE*8)
#define BITS_PER_PAGE_MASK (BITS_PER_PAGE-1)
static inline int mk_pid(struct pid_namespace *pid_ns,
struct pidmap *map, int off)
{
return (map - pid_ns->pidmap)*BITS_PER_PAGE + off;
}
#define find_next_offset(map, off) \
find_next_zero_bit((map)->page, BITS_PER_PAGE, off)
/*
* PID-map pages start out as NULL, they get allocated upon
* first use and are never deallocated. This way a low pid_max
* value does not cause lots of bitmaps to be allocated, but
* the scheme scales to up to 4 million PIDs, runtime.
*/
struct pid_namespace init_pid_ns = {
.kref = {
.refcount = ATOMIC_INIT(2),
},
.pidmap = {
[ 0 ... PIDMAP_ENTRIES-1] = { ATOMIC_INIT(BITS_PER_PAGE), NULL }
},
.last_pid = 0,
.level = 0,
.child_reaper = &init_task,
};
EXPORT_SYMBOL_GPL(init_pid_ns);
int is_container_init(struct task_struct *tsk)
{
int ret = 0;
struct pid *pid;
rcu_read_lock();
pid = task_pid(tsk);
if (pid != NULL && pid->numbers[pid->level].nr == 1)
ret = 1;
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(is_container_init);
/*
* Note: disable interrupts while the pidmap_lock is held as an
* interrupt might come in and do read_lock(&tasklist_lock).
*
* If we don't disable interrupts there is a nasty deadlock between
* detach_pid()->free_pid() and another cpu that does
* spin_lock(&pidmap_lock) followed by an interrupt routine that does
* read_lock(&tasklist_lock);
*
* After we clean up the tasklist_lock and know there are no
* irq handlers that take it we can leave the interrupts enabled.
* For now it is easier to be safe than to prove it can't happen.
*/
static __cacheline_aligned_in_smp DEFINE_SPINLOCK(pidmap_lock);
static void free_pidmap(struct upid *upid)
{
int nr = upid->nr;
struct pidmap *map = upid->ns->pidmap + nr / BITS_PER_PAGE;
int offset = nr & BITS_PER_PAGE_MASK;
clear_bit(offset, map->page);
atomic_inc(&map->nr_free);
}
/*
* If we started walking pids at 'base', is 'a' seen before 'b'?
*/
static int pid_before(int base, int a, int b)
{
/*
* This is the same as saying
*
* (a - base + MAXUINT) % MAXUINT < (b - base + MAXUINT) % MAXUINT
* and that mapping orders 'a' and 'b' with respect to 'base'.
*/
return (unsigned)(a - base) < (unsigned)(b - base);
}
/*
* We might be racing with someone else trying to set pid_ns->last_pid.
* We want the winner to have the "later" value, because if the
* "earlier" value prevails, then a pid may get reused immediately.
*
* Since pids rollover, it is not sufficient to just pick the bigger
* value. We have to consider where we started counting from.
*
* 'base' is the value of pid_ns->last_pid that we observed when
* we started looking for a pid.
*
* 'pid' is the pid that we eventually found.
*/
static void set_last_pid(struct pid_namespace *pid_ns, int base, int pid)
{
int prev;
int last_write = base;
do {
prev = last_write;
last_write = cmpxchg(&pid_ns->last_pid, prev, pid);
} while ((prev != last_write) && (pid_before(base, last_write, pid)));
}
static int alloc_pidmap(struct pid_namespace *pid_ns)
{
int i, offset, max_scan, pid, last = pid_ns->last_pid;
struct pidmap *map;
pid = last + 1;
if (pid >= pid_max)
pid = RESERVED_PIDS;
offset = pid & BITS_PER_PAGE_MASK;
map = &pid_ns->pidmap[pid/BITS_PER_PAGE];
/*
* If last_pid points into the middle of the map->page we
* want to scan this bitmap block twice, the second time
* we start with offset == 0 (or RESERVED_PIDS).
*/
max_scan = DIV_ROUND_UP(pid_max, BITS_PER_PAGE) - !offset;
for (i = 0; i <= max_scan; ++i) {
if (unlikely(!map->page)) {
void *page = kzalloc(PAGE_SIZE, GFP_KERNEL);
/*
* Free the page if someone raced with us
* installing it:
*/
spin_lock_irq(&pidmap_lock);
if (!map->page) {
map->page = page;
page = NULL;
}
spin_unlock_irq(&pidmap_lock);
kfree(page);
if (unlikely(!map->page))
break;
}
if (likely(atomic_read(&map->nr_free))) {
do {
if (!test_and_set_bit(offset, map->page)) {
atomic_dec(&map->nr_free);
set_last_pid(pid_ns, last, pid);
return pid;
}
offset = find_next_offset(map, offset);
pid = mk_pid(pid_ns, map, offset);
} while (offset < BITS_PER_PAGE && pid < pid_max);
}
if (map < &pid_ns->pidmap[(pid_max-1)/BITS_PER_PAGE]) {
++map;
offset = 0;
} else {
map = &pid_ns->pidmap[0];
offset = RESERVED_PIDS;
if (unlikely(last == offset))
break;
}
pid = mk_pid(pid_ns, map, offset);
}
return -1;
}
int next_pidmap(struct pid_namespace *pid_ns, unsigned int last)
{
int offset;
struct pidmap *map, *end;
if (last >= PID_MAX_LIMIT)
return -1;
offset = (last + 1) & BITS_PER_PAGE_MASK;
map = &pid_ns->pidmap[(last + 1)/BITS_PER_PAGE];
end = &pid_ns->pidmap[PIDMAP_ENTRIES];
for (; map < end; map++, offset = 0) {
if (unlikely(!map->page))
continue;
offset = find_next_bit((map)->page, BITS_PER_PAGE, offset);
if (offset < BITS_PER_PAGE)
return mk_pid(pid_ns, map, offset);
}
return -1;
}
void put_pid(struct pid *pid)
{
struct pid_namespace *ns;
if (!pid)
return;
ns = pid->numbers[pid->level].ns;
if ((atomic_read(&pid->count) == 1) ||
atomic_dec_and_test(&pid->count)) {
kmem_cache_free(ns->pid_cachep, pid);
put_pid_ns(ns);
}
}
EXPORT_SYMBOL_GPL(put_pid);
static void delayed_put_pid(struct rcu_head *rhp)
{
struct pid *pid = container_of(rhp, struct pid, rcu);
put_pid(pid);
}
void free_pid(struct pid *pid)
{
/* We can be called with write_lock_irq(&tasklist_lock) held */
int i;
unsigned long flags;
spin_lock_irqsave(&pidmap_lock, flags);
for (i = 0; i <= pid->level; i++)
hlist_del_rcu(&pid->numbers[i].pid_chain);
spin_unlock_irqrestore(&pidmap_lock, flags);
for (i = 0; i <= pid->level; i++)
free_pidmap(pid->numbers + i);
call_rcu(&pid->rcu, delayed_put_pid);
}
struct pid *alloc_pid(struct pid_namespace *ns)
{
struct pid *pid;
enum pid_type type;
int i, nr;
struct pid_namespace *tmp;
struct upid *upid;
pid = kmem_cache_alloc(ns->pid_cachep, GFP_KERNEL);
if (!pid)
goto out;
tmp = ns;
for (i = ns->level; i >= 0; i--) {
nr = alloc_pidmap(tmp);
if (nr < 0)
goto out_free;
pid->numbers[i].nr = nr;
pid->numbers[i].ns = tmp;
tmp = tmp->parent;
}
get_pid_ns(ns);
pid->level = ns->level;
atomic_set(&pid->count, 1);
for (type = 0; type < PIDTYPE_MAX; ++type)
INIT_HLIST_HEAD(&pid->tasks[type]);
upid = pid->numbers + ns->level;
spin_lock_irq(&pidmap_lock);
for ( ; upid >= pid->numbers; --upid)
hlist_add_head_rcu(&upid->pid_chain,
&pid_hash[pid_hashfn(upid->nr, upid->ns)]);
spin_unlock_irq(&pidmap_lock);
out:
return pid;
out_free:
while (++i <= ns->level)
free_pidmap(pid->numbers + i);
kmem_cache_free(ns->pid_cachep, pid);
pid = NULL;
goto out;
}
struct pid *find_pid_ns(int nr, struct pid_namespace *ns)
{
struct hlist_node *elem;
struct upid *pnr;
hlist_for_each_entry_rcu(pnr, elem,
&pid_hash[pid_hashfn(nr, ns)], pid_chain)
if (pnr->nr == nr && pnr->ns == ns)
return container_of(pnr, struct pid,
numbers[ns->level]);
return NULL;
}
EXPORT_SYMBOL_GPL(find_pid_ns);
struct pid *find_vpid(int nr)
{
return find_pid_ns(nr, current->nsproxy->pid_ns);
}
EXPORT_SYMBOL_GPL(find_vpid);
/*
* attach_pid() must be called with the tasklist_lock write-held.
*/
void attach_pid(struct task_struct *task, enum pid_type type,
struct pid *pid)
{
struct pid_link *link;
link = &task->pids[type];
link->pid = pid;
hlist_add_head_rcu(&link->node, &pid->tasks[type]);
}
static void __change_pid(struct task_struct *task, enum pid_type type,
struct pid *new)
{
struct pid_link *link;
struct pid *pid;
int tmp;
link = &task->pids[type];
pid = link->pid;
hlist_del_rcu(&link->node);
link->pid = new;
for (tmp = PIDTYPE_MAX; --tmp >= 0; )
if (!hlist_empty(&pid->tasks[tmp]))
return;
free_pid(pid);
}
void detach_pid(struct task_struct *task, enum pid_type type)
{
__change_pid(task, type, NULL);
}
void change_pid(struct task_struct *task, enum pid_type type,
struct pid *pid)
{
__change_pid(task, type, pid);
attach_pid(task, type, pid);
}
/* transfer_pid is an optimization of attach_pid(new), detach_pid(old) */
void transfer_pid(struct task_struct *old, struct task_struct *new,
enum pid_type type)
{
new->pids[type].pid = old->pids[type].pid;
hlist_replace_rcu(&old->pids[type].node, &new->pids[type].node);
}
struct task_struct *pid_task(struct pid *pid, enum pid_type type)
{
struct task_struct *result = NULL;
if (pid) {
struct hlist_node *first;
first = rcu_dereference_check(hlist_first_rcu(&pid->tasks[type]),
rcu_read_lock_held() ||
lockdep_tasklist_lock_is_held());
if (first)
result = hlist_entry(first, struct task_struct, pids[(type)].node);
}
return result;
}
EXPORT_SYMBOL(pid_task);
/*
* Must be called under rcu_read_lock().
*/
struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns)
{
rcu_lockdep_assert(rcu_read_lock_held());
return pid_task(find_pid_ns(nr, ns), PIDTYPE_PID);
}
struct task_struct *find_task_by_vpid(pid_t vnr)
{
return find_task_by_pid_ns(vnr, current->nsproxy->pid_ns);
}
struct pid *get_task_pid(struct task_struct *task, enum pid_type type)
{
struct pid *pid;
rcu_read_lock();
if (type != PIDTYPE_PID)
task = task->group_leader;
pid = get_pid(task->pids[type].pid);
rcu_read_unlock();
return pid;
}
EXPORT_SYMBOL_GPL(get_task_pid);
struct task_struct *get_pid_task(struct pid *pid, enum pid_type type)
{
struct task_struct *result;
rcu_read_lock();
result = pid_task(pid, type);
if (result)
get_task_struct(result);
rcu_read_unlock();
return result;
}
EXPORT_SYMBOL_GPL(get_pid_task);
struct pid *find_get_pid(pid_t nr)
{
struct pid *pid;
rcu_read_lock();
pid = get_pid(find_vpid(nr));
rcu_read_unlock();
return pid;
}
EXPORT_SYMBOL_GPL(find_get_pid);
pid_t pid_nr_ns(struct pid *pid, struct pid_namespace *ns)
{
struct upid *upid;
pid_t nr = 0;
if (pid && ns->level <= pid->level) {
upid = &pid->numbers[ns->level];
if (upid->ns == ns)
nr = upid->nr;
}
return nr;
}
pid_t pid_vnr(struct pid *pid)
{
return pid_nr_ns(pid, current->nsproxy->pid_ns);
}
EXPORT_SYMBOL_GPL(pid_vnr);
pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
struct pid_namespace *ns)
{
pid_t nr = 0;
rcu_read_lock();
if (!ns)
ns = current->nsproxy->pid_ns;
if (likely(pid_alive(task))) {
if (type != PIDTYPE_PID)
task = task->group_leader;
nr = pid_nr_ns(task->pids[type].pid, ns);
}
rcu_read_unlock();
return nr;
}
EXPORT_SYMBOL(__task_pid_nr_ns);
pid_t task_tgid_nr_ns(struct task_struct *tsk, struct pid_namespace *ns)
{
return pid_nr_ns(task_tgid(tsk), ns);
}
EXPORT_SYMBOL(task_tgid_nr_ns);
struct pid_namespace *task_active_pid_ns(struct task_struct *tsk)
{
return ns_of_pid(task_pid(tsk));
}
EXPORT_SYMBOL_GPL(task_active_pid_ns);
/*
* Used by proc to find the first pid that is greater than or equal to nr.
*
* If there is a pid at nr this function is exactly the same as find_pid_ns.
*/
struct pid *find_ge_pid(int nr, struct pid_namespace *ns)
{
struct pid *pid;
do {
pid = find_pid_ns(nr, ns);
if (pid)
break;
nr = next_pidmap(ns, nr);
} while (nr > 0);
return pid;
}
/*
* The pid hash table is scaled according to the amount of memory in the
* machine. From a minimum of 16 slots up to 4096 slots at one gigabyte or
* more.
*/
void __init pidhash_init(void)
{
int i, pidhash_size;
pid_hash = alloc_large_system_hash("PID", sizeof(*pid_hash), 0, 18,
HASH_EARLY | HASH_SMALL,
&pidhash_shift, NULL, 4096);
pidhash_size = 1 << pidhash_shift;
for (i = 0; i < pidhash_size; i++)
INIT_HLIST_HEAD(&pid_hash[i]);
}
void __init pidmap_init(void)
{
/* bump default and minimum pid_max based on number of cpus */
pid_max = min(pid_max_max, max_t(int, pid_max,
PIDS_PER_CPU_DEFAULT * num_possible_cpus()));
pid_max_min = max_t(int, pid_max_min,
PIDS_PER_CPU_MIN * num_possible_cpus());
pr_info("pid_max: default: %u minimum: %u\n", pid_max, pid_max_min);
init_pid_ns.pidmap[0].page = kzalloc(PAGE_SIZE, GFP_KERNEL);
/* Reserve PID 0. We never call free_pidmap(0) */
set_bit(0, init_pid_ns.pidmap[0].page);
atomic_dec(&init_pid_ns.pidmap[0].nr_free);
init_pid_ns.pid_cachep = KMEM_CACHE(pid,
SLAB_HWCACHE_ALIGN | SLAB_PANIC);
}
|
kenkit/AndromadusMod-New
|
kernel/pid.c
|
C
|
gpl-2.0
| 14,165
|
module Katello
# rubocop:disable Metrics/ClassLength
class Repository < Katello::Model
self.include_root_in_json = false
validates_lengths_from_database :except => [:label]
before_destroy :assert_deletable
before_create :downcase_pulp_id
include ForemanTasks::Concerns::ActionSubject
include Glue::Candlepin::Content if (SETTINGS[:katello][:use_cp] && SETTINGS[:katello][:use_pulp])
include Glue::Pulp::Repo if SETTINGS[:katello][:use_pulp]
include Glue if (SETTINGS[:katello][:use_cp] || SETTINGS[:katello][:use_pulp])
include Authorization::Repository
include Ext::LabelFromName
include Katello::Engine.routes.url_helpers
YUM_TYPE = 'yum'.freeze
FILE_TYPE = 'file'.freeze
PUPPET_TYPE = 'puppet'.freeze
DOCKER_TYPE = 'docker'.freeze
OSTREE_TYPE = 'ostree'.freeze
CHECKSUM_TYPES = %w(sha1 sha256).freeze
belongs_to :environment, :inverse_of => :repositories, :class_name => "Katello::KTEnvironment"
belongs_to :product, :inverse_of => :repositories
belongs_to :gpg_key, :inverse_of => :repositories
belongs_to :library_instance, :class_name => "Katello::Repository", :inverse_of => :library_instances_inverse
has_many :library_instances_inverse, # TODO: what is the proper name?
:class_name => 'Katello::Repository',
:dependent => :restrict_with_exception,
:foreign_key => :library_instance_id
has_many :content_view_repositories, :class_name => "Katello::ContentViewRepository",
:dependent => :destroy, :inverse_of => :repository
has_many :content_views, :through => :content_view_repositories
has_many :repository_errata, :class_name => "Katello::RepositoryErratum", :dependent => :destroy
has_many :errata, :through => :repository_errata
has_many :repository_rpms, :class_name => "Katello::RepositoryRpm", :dependent => :destroy
has_many :rpms, :through => :repository_rpms
has_many :repository_puppet_modules, :class_name => "Katello::RepositoryPuppetModule", :dependent => :destroy
has_many :puppet_modules, :through => :repository_puppet_modules
has_many :repository_docker_manifests, :class_name => "Katello::RepositoryDockerManifest", :dependent => :destroy
has_many :docker_manifests, :through => :repository_docker_manifests
has_many :docker_tags, :dependent => :destroy, :class_name => "Katello::DockerTag"
has_many :repository_ostree_branches, :class_name => "Katello::RepositoryOstreeBranch", :dependent => :destroy
has_many :ostree_branches, :through => :repository_ostree_branches
has_many :system_repositories, :class_name => "Katello::SystemRepository", :dependent => :destroy
has_many :systems, :through => :system_repositories
has_many :content_facet_repositories, :class_name => "Katello::ContentFacetRepository", :dependent => :destroy
has_many :content_facets, :through => :content_facet_repositories
has_many :repository_package_groups, :class_name => "Katello::RepositoryPackageGroup", :dependent => :destroy
has_many :package_groups, :through => :repository_package_groups
has_many :kickstart_content_facets, :class_name => "Katello::Host::ContentFacet", :foreign_key => :kickstart_repository_id,
:inverse_of => :kickstart_repository, :dependent => :nullify
# rubocop:disable HasAndBelongsToMany
# TODO: change this into has_many :through association
has_and_belongs_to_many :filters, :class_name => "Katello::ContentViewFilter",
:join_table => :katello_content_view_filters_repositories,
:foreign_key => :content_view_filter_id
belongs_to :content_view_version, :inverse_of => :repositories, :class_name => "Katello::ContentViewVersion"
validates :product_id, :presence => true
validates :pulp_id, :presence => true, :uniqueness => true, :if => proc { |r| r.name.present? }
validates :checksum_type, :inclusion => {:in => CHECKSUM_TYPES, :allow_blank => true}
validates :docker_upstream_name, :allow_blank => true, :if => :docker?, :format => {
:with => /\A([a-z0-9\-_]{4,30}\/)?[a-z0-9\-_\.]{3,30}\z/,
:message => _("must be a valid docker name")
}
#validates :content_id, :presence => true #add back after fixing add_repo orchestration
validates_with Validators::KatelloLabelFormatValidator, :attributes => :label
validates_with Validators::KatelloNameFormatValidator, :attributes => :name
validates_with Validators::RepositoryUniqueAttributeValidator, :attributes => :label
validates_with Validators::RepositoryUniqueAttributeValidator, :attributes => :name
validates_with Validators::KatelloUrlFormatValidator,
:attributes => :url, :nil_allowed => proc { |repo| repo.custom? }, :field_name => :url,
:if => proc { |repo| repo.in_default_view? }
validates :content_type, :inclusion => {
:in => ->(_) { Katello::RepositoryTypeManager.repository_types.keys },
:allow_blank => false,
:message => ->(_, _) { _("must be one of the following: %s") % Katello::RepositoryTypeManager.repository_types.keys.join(', ') }
}
validates :download_policy, inclusion: {
:in => ::Runcible::Models::YumImporter::DOWNLOAD_POLICIES,
:message => _("must be one of the following: %s") % ::Runcible::Models::YumImporter::DOWNLOAD_POLICIES.join(', ')
}, if: :yum?
validate :ensure_no_download_policy, if: ->(repo) { !repo.yum? }
validate :ensure_valid_docker_attributes, :if => :docker?
validate :ensure_docker_repo_unprotected, :if => :docker?
validate :ensure_has_url_for_ostree, :if => :ostree?
validate :ensure_ostree_repo_protected, :if => :ostree?
scope :has_url, -> { where('url IS NOT NULL') }
scope :in_default_view, -> { joins(:content_view_version => :content_view).where("#{Katello::ContentView.table_name}.default" => true) }
scope :yum_type, -> { where(:content_type => YUM_TYPE) }
scope :file_type, -> { where(:content_type => FILE_TYPE) }
scope :puppet_type, -> { where(:content_type => PUPPET_TYPE) }
scope :docker_type, -> { where(:content_type => DOCKER_TYPE) }
scope :ostree_type, -> { where(:content_type => OSTREE_TYPE) }
scope :non_puppet, -> { where("content_type != ?", PUPPET_TYPE) }
scope :non_archived, -> { where('environment_id is not NULL') }
scope :archived, -> { where('environment_id is NULL') }
scoped_search :on => :name, :complete_value => true
scoped_search :rename => :product, :on => :name, :in => :product, :complete_value => true
scoped_search :on => :content_type, :complete_value => -> do
Katello::RepositoryTypeManager.repository_types.keys.each_with_object({}) { |value, hash| hash[value.to_sym] = value }
end
scoped_search :on => :content_view_id, :in => :content_view_repositories
scoped_search :on => :distribution_version, :complete_value => true
scoped_search :on => :distribution_arch, :complete_value => true
scoped_search :on => :distribution_family, :complete_value => true
scoped_search :on => :distribution_variant, :complete_value => true
scoped_search :on => :distribution_bootable, :complete_value => true
scoped_search :on => :distribution_uuid, :complete_value => true
def organization
if self.environment
self.environment.organization
else
self.content_view.organization
end
end
def content_view
self.content_view_version.content_view
end
def self.in_organization(org)
where("#{Repository.table_name}.environment_id" => org.kt_environments.pluck("#{KTEnvironment.table_name}.id"))
end
def self.in_environment(env_id)
where(environment_id: env_id)
end
def self.in_product(prod)
where(product_id: prod)
end
def self.in_content_views(views)
joins(:content_view_version)
.where("#{Katello::ContentViewVersion.table_name}.content_view_id" => views.map(&:id))
end
def archive?
self.environment.nil?
end
def in_default_view?
content_view_version && content_view_version.default_content_view?
end
def self.in_environments_products(env_ids, product_ids)
in_environment(env_ids).in_product(product_ids)
end
def other_repos_with_same_product_and_content
Repository.in_product(Product.find(self.product.id)).where(:content_id => self.content_id)
.where("#{self.class.table_name}.id != #{self.id}")
end
def other_repos_with_same_content
Repository.where(:content_id => self.content_id).where("#{self.class.table_name}.id != #{self.id}")
end
def yum_gpg_key_url
# if the repo has a gpg key return a url to access it
if (self.gpg_key && self.gpg_key.content.present?)
"../..#{gpg_key_content_api_repository_url(self, :only_path => true)}"
end
end
def product_type
redhat? ? "redhat" : "custom"
end
delegate :redhat?, to: :product
def custom?
!redhat?
end
def empty_errata
repository_rpm = Katello::RepositoryRpm.table_name
repository_errata = Katello::RepositoryErratum.table_name
rpm = Katello::Rpm.table_name
errata = Katello::Erratum.table_name
erratum_package = Katello::ErratumPackage.table_name
errata_with_packages = Erratum.joins(
"INNER JOIN #{erratum_package} on #{erratum_package}.erratum_id = #{errata}.id",
"INNER JOIN #{repository_errata} on #{repository_errata}.erratum_id = #{errata}.id",
"INNER JOIN #{rpm} on #{rpm}.filename = #{erratum_package}.filename",
"INNER JOIN #{repository_rpm} on #{repository_rpm}.rpm_id = #{rpm}.id").
where("#{repository_rpm}.repository_id" => self.id).
where("#{repository_errata}.repository_id" => self.id)
if errata_with_packages.any?
self.errata.where("#{Katello::Erratum.table_name}.id NOT IN (?)", errata_with_packages.pluck("#{errata}.id"))
else
self.errata
end
end
def library_instance?
library_instance.nil?
end
def clones
lib_id = self.library_instance_id || self.id
Repository.where(:library_instance_id => lib_id)
end
def group
library_repo = library_instance? ? self : library_instance
clones << library_repo
end
#is the repo cloned in the specified environment
def cloned_in?(env)
!get_clone(env).nil?
end
def promoted?
if environment && environment.library? && Repository.where(:library_instance_id => self.id).any?
true
else
false
end
end
def get_clone(env)
if self.content_view.default
# this repo is part of a default content view
lib_id = self.library_instance_id || self.id
Repository.in_environment(env).where(:library_instance_id => lib_id).
joins(:content_view_version => :content_view).where("#{Katello::ContentView.table_name}.default" => true).first
else
# this repo is part of a content view that was published from a user created view
self.content_view.get_repo_clone(env, self).first
end
end
def gpg_key_name=(name)
if name.blank?
self.gpg_key = nil
else
self.gpg_key = GpgKey.readable.find_by!(:name => name)
end
end
# Returns true if the pulp_task_id was triggered by the last synchronization
# action for the repository. Dynflow action handles the synchronization
# by it's own so no need to synchronize it again in this callback. Since the
# callbacks are run just after synchronization is finished, it should be enough
# to check for the last synchronization task.
def dynflow_handled_last_sync?(pulp_task_id)
task = ForemanTasks::Task::DynflowTask.for_action(::Actions::Katello::Repository::Sync).
for_resource(self).order(:started_at).last
return task && task.main_action.pulp_task_id == pulp_task_id
end
def as_json(*args)
ret = super
ret["gpg_key_name"] = gpg_key ? gpg_key.name : ""
ret["package_count"] = package_count rescue nil
ret["last_sync"] = last_sync rescue nil
ret["puppet_module_count"] = self.puppet_modules.count rescue nil
ret
end
def self.clone_repo_path(options)
repo = options[:repository]
repo_lib = repo.library_instance ? repo.library_instance : repo
org, _, content_path = repo_lib.relative_path.split("/", 3)
if options[:environment]
cve = ContentViewEnvironment.where(:environment_id => options[:environment],
:content_view_id => options[:content_view]).first
"#{org}/#{cve.label}/#{content_path}"
else
"#{org}/#{ContentView::CONTENT_DIR}/#{options[:content_view].label}/#{options[:version].version}/#{content_path}"
end
end
def self.clone_docker_repo_path(options)
repo = options[:repository]
org = repo.organization.label.downcase
if options[:environment]
cve = ContentViewEnvironment.where(:environment_id => options[:environment],
:content_view_id => options[:content_view]).first
view = repo.content_view.label
product = repo.product.label
env = cve.label.split('/').first
"#{org}-#{env.downcase}-#{view}-#{product}-#{repo.label}"
else
content_path = repo.relative_path.gsub("#{org}-", '')
"#{org}-#{options[:content_view].label}-#{options[:version].version}-#{content_path}"
end
end
def self.repo_id(product_label, repo_label, env_label, organization_label,
view_label, version, docker_repo_name = nil)
actual_repo_id = [organization_label,
env_label,
view_label,
version,
product_label,
repo_label,
docker_repo_name].compact.join("-").gsub(/[^-\w]/, "_")
# docker repo names need to be in lower case
actual_repo_id = actual_repo_id.downcase if docker_repo_name
actual_repo_id
end
def clone_id(env, content_view, version = nil)
Repository.repo_id(self.product.label, self.label, env.try(:label),
organization.label, content_view.label,
version)
end
def packages_without_errata
if errata_filenames.any?
self.rpms.where("#{Rpm.table_name}.filename NOT in (?)", errata_filenames)
else
self.rpms
end
end
def self.with_errata(errata)
joins(:repository_errata).where("#{Katello::RepositoryErratum.table_name}.erratum_id" => errata)
end
def errata_filenames
Katello::ErratumPackage.joins(:erratum => :repository_errata).
where("#{RepositoryErratum.table_name}.repository_id" => self.id).pluck("#{Katello::ErratumPackage.table_name}.filename")
end
def container_repository_name
pulp_id if docker?
end
# TODO: break up method
# rubocop:disable MethodLength
def build_clone(options)
to_env = options[:environment]
version = options[:version]
content_view = options[:content_view] || to_env.default_content_view
to_version = version || content_view.version(to_env)
library = self.library_instance ? self.library_instance : self
if to_env && version
fail "Cannot clone into both an environment and a content view version archive"
end
if to_version.nil?
fail _("View %{view} has not been promoted to %{env}") %
{:view => content_view.name, :env => to_env.name}
end
if content_view.default?
fail _("Cannot clone repository from %{from_env} to %{to_env}. They are not sequential.") %
{:from_env => self.environment.name, :to_env => to_env.name} if to_env.prior != self.environment
fail _("Repository has already been promoted to %{to_env}") %
{:to_env => to_env} if self.cloned_in?(to_env)
else
fail _("Repository has already been cloned to %{cv_name} in environment %{to_env}") %
{:to_env => to_env, :cv_name => content_view.name} if to_env &&
content_view.repos(to_env).where(:library_instance_id => library.id).count > 0
end
Repository.new(:environment => to_env,
:product => self.product,
:cp_label => self.cp_label,
:library_instance => library,
:label => self.label,
:name => self.name,
:arch => self.arch,
:major => self.major,
:minor => self.minor,
:content_id => self.content_id,
:content_view_version => to_version,
:content_type => self.content_type,
:download_policy => download_policy,
:unprotected => self.unprotected) do |clone|
clone.checksum_type = self.checksum_type
clone.pulp_id = clone.clone_id(to_env, content_view, version.try(:version))
options = {
:repository => self,
:environment => to_env,
:content_view => content_view,
:version => version
}
clone.relative_path = if clone.docker?
Repository.clone_docker_repo_path(options)
else
Repository.clone_repo_path(options)
end
end
end
def cancel_dynflow_sync
if latest_dynflow_sync
plan = latest_dynflow_sync.execution_plan
plan.steps.each_pair do |_number, step|
if step.cancellable? && step.is_a?(Dynflow::ExecutionPlan::Steps::RunStep)
::ForemanTasks.dynflow.world.event(plan.id, step.id, Dynflow::Action::Cancellable::Cancel)
end
end
end
end
def latest_dynflow_sync
@latest_dynflow_sync ||= ForemanTasks::Task::DynflowTask.for_action(::Actions::Katello::Repository::Sync).
for_resource(self).order(:started_at).last
end
def create_clone(options)
clone = build_clone(options)
clone.save!
return clone
end
# returns other instances of this repo with the same library
# equivalent of repo
def environmental_instances(view)
repo = self.library_instance || self
search = Repository.non_archived.where("library_instance_id=%s or #{Katello::Repository.table_name}.id=%s" % [repo.id, repo.id])
search.in_content_views([view])
end
def url?
url.present?
end
def name_conflicts
if puppet?
modules = PuppetModule.search("*", :repoids => self.pulp_id,
:fields => [:name],
:page_size => self.puppet_modules.count)
modules.map(&:name).group_by(&:to_s).select { |_, v| v.size > 1 }.keys
else
[]
end
end
def related_resources
self.product
end
def node_syncable?
environment
end
def exist_for_environment?(environment, content_view, attribute = nil)
if environment.present?
repos = content_view.version(environment).repos(environment)
repos.any? do |repo|
not_self = (repo.id != self.id)
same_product = (repo.product.id == self.product.id)
repo_exists = same_product && not_self
if repo_exists && attribute
same_attribute = repo.send(attribute) == self.send(attribute)
repo_exists = same_attribute
end
repo_exists
end
else
false
end
end
def ostree_branch_names
self.ostree_branches.map(&:name)
end
def units_for_removal(ids)
table_name = removable_unit_association.table_name
is_integer = Integer(ids.first) rescue false #assume all ids are either integers or not
if is_integer
self.removable_unit_association.where("#{table_name}.id in (?)", ids)
else
self.removable_unit_association.where("#{table_name}.uuid in (?)", ids)
end
end
def self.import_distributions
self.all.each do |repo|
repo.import_distribution_data
end
end
def import_distribution_data
distribution = Katello.pulp_server.extensions.repository.distributions(self.pulp_id).first
if distribution
self.update_attributes!(
:distribution_version => distribution["version"],
:distribution_arch => distribution["arch"],
:distribution_family => distribution["family"],
:distribution_variant => distribution["variant"],
:distribution_uuid => distribution["_id"],
:distribution_bootable => ::Katello::Repository.distribution_bootable?(distribution)
)
end
end
def check_duplicate_branch_names(branch_names)
dupe_branch_checker = {}
dupe_branch_checker.default = 0
branch_names.each do |branch|
dupe_branch_checker[branch] += 1
end
duplicate_branch_names = dupe_branch_checker.select { |_, value| value > 1 }.keys
unless duplicate_branch_names.empty?
fail ::Katello::Errors::ConflictException,
_("Duplicate branches specified - %{branches}") % { branches: duplicate_branch_names.join(", ")}
end
end
def remove_content(units)
if yum?
self.rpms -= units
elsif puppet?
self.puppet_modules -= units
elsif ostree?
self.ostree_branches -= units
elsif docker?
remove_docker_content(units)
end
end
def assert_deletable
if self.environment.try(:library?) && self.content_view.default?
if self.environment.organization.being_deleted?
return true
elsif self.custom? && self.deletable?
return true
elsif !self.custom? && self.redhat_deletable?
return true
else
errors.add(:base, _("Repository cannot be deleted since it has already been included in a published Content View. " \
"Please delete all Content View versions containing this repository before attempting to delete it."))
return false
end
end
end
def hosts_with_applicability
::Host.joins(:content_facet => :bound_repositories).where("#{Katello::Repository.table_name}.id" => (self.clones.pluck(:id) + [self.id]))
end
protected
def removable_unit_association
if yum?
self.rpms
elsif docker?
self.docker_manifests
elsif puppet?
self.puppet_modules
elsif ostree?
self.ostree_branches
else
fail "Content type not supported for removal"
end
end
def downcase_pulp_id
# Docker doesn't support uppercase letters in repository names. Since the pulp_id
# is currently being used for the name, it will be downcased for this content type.
if self.content_type == Repository::DOCKER_TYPE
self.pulp_id = self.pulp_id.downcase
end
end
def ensure_valid_docker_attributes
if library_instance? && (url.blank? || docker_upstream_name.blank?)
errors.add(:base, N_("Repository URL or Upstream Name is empty. Both are required for syncing from the upstream."))
end
end
def ensure_docker_repo_unprotected
unless unprotected
errors.add(:base, N_("Docker Repositories are not protected at this time. " \
"They need to be published via http to be available to containers."))
end
end
def ensure_no_download_policy
if !yum? && download_policy.present?
errors.add(:download_policy, N_("cannot be set for non-yum repositories."))
end
end
def ensure_has_url_for_ostree
return true if url.present? || library_instance_id
errors.add(:url, N_("cannot be blank. RPM OSTree Repository URL required for syncing from the upstream."))
end
def ensure_ostree_repo_protected
if unprotected
errors.add(:base, N_("OSTree Repositories cannot be unprotected."))
end
end
def remove_docker_content(manifests)
self.docker_tags.where(:docker_manifest_id => manifests.map(&:id)).destroy_all
self.docker_manifests -= manifests
# destroy any orphan docker manifests
manifests.each do |manifest|
manifest.destroy if manifest.repositories.empty?
end
end
end
end
|
omaciel/katello
|
app/models/katello/repository.rb
|
Ruby
|
gpl-2.0
| 24,798
|
/*
Unix SMB/CIFS implementation.
nss tester for winbindd
Copyright (C) Andrew Tridgell 2001
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "includes.h"
static const char *so_path = "/lib/libnss_winbind.so";
static const char *nss_name = "winbind";
static int nss_errno;
static NSS_STATUS last_error;
static int total_errors;
static void *find_fn(const char *name)
{
char s[1024];
static void *h;
void *res;
snprintf(s,sizeof(s), "_nss_%s_%s", nss_name, name);
if (!h) {
h = sys_dlopen(so_path, RTLD_LAZY);
}
if (!h) {
printf("Can't open shared library %s\n", so_path);
exit(1);
}
res = sys_dlsym(h, s);
if (!res) {
printf("Can't find function %s\n", s);
return NULL;
}
return res;
}
static void report_nss_error(const char *who, NSS_STATUS status)
{
last_error = status;
total_errors++;
printf("ERROR %s: NSS_STATUS=%d %d (nss_errno=%d)\n",
who, status, NSS_STATUS_SUCCESS, nss_errno);
}
static struct passwd *nss_getpwent(void)
{
NSS_STATUS (*_nss_getpwent_r)(struct passwd *, char *,
size_t , int *) = find_fn("getpwent_r");
static struct passwd pwd;
static char buf[1000];
NSS_STATUS status;
status = _nss_getpwent_r(&pwd, buf, sizeof(buf), &nss_errno);
if (status == NSS_STATUS_NOTFOUND) {
return NULL;
}
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("getpwent", status);
return NULL;
}
return &pwd;
}
static struct passwd *nss_getpwnam(const char *name)
{
NSS_STATUS (*_nss_getpwnam_r)(const char *, struct passwd *, char *,
size_t , int *) = find_fn("getpwnam_r");
static struct passwd pwd;
static char buf[1000];
NSS_STATUS status;
status = _nss_getpwnam_r(name, &pwd, buf, sizeof(buf), &nss_errno);
if (status == NSS_STATUS_NOTFOUND) {
return NULL;
}
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("getpwnam", status);
return NULL;
}
return &pwd;
}
static struct passwd *nss_getpwuid(uid_t uid)
{
NSS_STATUS (*_nss_getpwuid_r)(uid_t , struct passwd *, char *,
size_t , int *) = find_fn("getpwuid_r");
static struct passwd pwd;
static char buf[1000];
NSS_STATUS status;
status = _nss_getpwuid_r(uid, &pwd, buf, sizeof(buf), &nss_errno);
if (status == NSS_STATUS_NOTFOUND) {
return NULL;
}
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("getpwuid", status);
return NULL;
}
return &pwd;
}
static void nss_setpwent(void)
{
NSS_STATUS (*_nss_setpwent)(void) = find_fn("setpwent");
NSS_STATUS status;
status = _nss_setpwent();
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("setpwent", status);
}
}
static void nss_endpwent(void)
{
NSS_STATUS (*_nss_endpwent)(void) = find_fn("endpwent");
NSS_STATUS status;
status = _nss_endpwent();
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("endpwent", status);
}
}
static struct group *nss_getgrent(void)
{
NSS_STATUS (*_nss_getgrent_r)(struct group *, char *,
size_t , int *) = find_fn("getgrent_r");
static struct group grp;
static char *buf;
static int buflen = 1024;
NSS_STATUS status;
if (!buf) buf = malloc(buflen);
again:
status = _nss_getgrent_r(&grp, buf, buflen, &nss_errno);
if (status == NSS_STATUS_TRYAGAIN) {
buflen *= 2;
buf = realloc(buf, buflen);
goto again;
}
if (status == NSS_STATUS_NOTFOUND) {
return NULL;
}
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("getgrent", status);
return NULL;
}
return &grp;
}
static struct group *nss_getgrnam(const char *name)
{
NSS_STATUS (*_nss_getgrnam_r)(const char *, struct group *, char *,
size_t , int *) = find_fn("getgrnam_r");
static struct group grp;
static char *buf;
static int buflen = 1000;
NSS_STATUS status;
if (!buf) buf = malloc(buflen);
again:
status = _nss_getgrnam_r(name, &grp, buf, buflen, &nss_errno);
if (status == NSS_STATUS_TRYAGAIN) {
buflen *= 2;
buf = realloc(buf, buflen);
goto again;
}
if (status == NSS_STATUS_NOTFOUND) {
return NULL;
}
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("getgrnam", status);
return NULL;
}
return &grp;
}
static struct group *nss_getgrgid(gid_t gid)
{
NSS_STATUS (*_nss_getgrgid_r)(gid_t , struct group *, char *,
size_t , int *) = find_fn("getgrgid_r");
static struct group grp;
static char *buf;
static int buflen = 1000;
NSS_STATUS status;
if (!buf) buf = malloc(buflen);
again:
status = _nss_getgrgid_r(gid, &grp, buf, buflen, &nss_errno);
if (status == NSS_STATUS_TRYAGAIN) {
buflen *= 2;
buf = realloc(buf, buflen);
goto again;
}
if (status == NSS_STATUS_NOTFOUND) {
return NULL;
}
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("getgrgid", status);
return NULL;
}
return &grp;
}
static void nss_setgrent(void)
{
NSS_STATUS (*_nss_setgrent)(void) = find_fn("setgrent");
NSS_STATUS status;
status = _nss_setgrent();
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("setgrent", status);
}
}
static void nss_endgrent(void)
{
NSS_STATUS (*_nss_endgrent)(void) = find_fn("endgrent");
NSS_STATUS status;
status = _nss_endgrent();
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("endgrent", status);
}
}
static int nss_initgroups(char *user, gid_t group, gid_t **groups, long int *start, long int *size)
{
NSS_STATUS (*_nss_initgroups)(char *, gid_t , long int *,
long int *, gid_t **, long int , int *) =
find_fn("initgroups_dyn");
NSS_STATUS status;
if (!_nss_initgroups) return NSS_STATUS_UNAVAIL;
status = _nss_initgroups(user, group, start, size, groups, 0, &nss_errno);
if (status != NSS_STATUS_SUCCESS) {
report_nss_error("initgroups", status);
}
return status;
}
static void print_passwd(struct passwd *pwd)
{
printf("%s:%s:%d:%d:%s:%s:%s\n",
pwd->pw_name,
pwd->pw_passwd,
pwd->pw_uid,
pwd->pw_gid,
pwd->pw_gecos,
pwd->pw_dir,
pwd->pw_shell);
}
static void print_group(struct group *grp)
{
int i;
printf("%s:%s:%d: ",
grp->gr_name,
grp->gr_passwd,
grp->gr_gid);
if (!grp->gr_mem[0]) {
printf("\n");
return;
}
for (i=0; grp->gr_mem[i+1]; i++) {
printf("%s, ", grp->gr_mem[i]);
}
printf("%s\n", grp->gr_mem[i]);
}
static void nss_test_initgroups(char *name, gid_t gid)
{
long int size = 16;
long int start = 1;
gid_t *groups = NULL;
int i;
NSS_STATUS status;
groups = (gid_t *)malloc_array_p(gid_t, size);
groups[0] = gid;
status = nss_initgroups(name, gid, &groups, &start, &size);
if (status == NSS_STATUS_UNAVAIL) {
printf("No initgroups fn\n");
return;
}
for (i=0; i<start-1; i++) {
printf("%d, ", groups[i]);
}
printf("%d\n", groups[i]);
}
static void nss_test_users(void)
{
struct passwd *pwd;
nss_setpwent();
/* loop over all users */
while ((pwd = nss_getpwent())) {
printf("Testing user %s\n", pwd->pw_name);
printf("getpwent: "); print_passwd(pwd);
pwd = nss_getpwuid(pwd->pw_uid);
if (!pwd) {
total_errors++;
printf("ERROR: can't getpwuid\n");
continue;
}
printf("getpwuid: "); print_passwd(pwd);
pwd = nss_getpwnam(pwd->pw_name);
if (!pwd) {
total_errors++;
printf("ERROR: can't getpwnam\n");
continue;
}
printf("getpwnam: "); print_passwd(pwd);
printf("initgroups: "); nss_test_initgroups(pwd->pw_name, pwd->pw_gid);
printf("\n");
}
nss_endpwent();
}
static void nss_test_groups(void)
{
struct group *grp;
nss_setgrent();
/* loop over all groups */
while ((grp = nss_getgrent())) {
printf("Testing group %s\n", grp->gr_name);
printf("getgrent: "); print_group(grp);
grp = nss_getgrnam(grp->gr_name);
if (!grp) {
total_errors++;
printf("ERROR: can't getgrnam\n");
continue;
}
printf("getgrnam: "); print_group(grp);
grp = nss_getgrgid(grp->gr_gid);
if (!grp) {
total_errors++;
printf("ERROR: can't getgrgid\n");
continue;
}
printf("getgrgid: "); print_group(grp);
printf("\n");
}
nss_endgrent();
}
static void nss_test_errors(void)
{
struct passwd *pwd;
struct group *grp;
pwd = getpwnam("nosuchname");
if (pwd || last_error != NSS_STATUS_NOTFOUND) {
total_errors++;
printf("ERROR Non existant user gave error %d\n", last_error);
}
pwd = getpwuid(0xFFF0);
if (pwd || last_error != NSS_STATUS_NOTFOUND) {
total_errors++;
printf("ERROR Non existant uid gave error %d\n", last_error);
}
grp = getgrnam("nosuchgroup");
if (grp || last_error != NSS_STATUS_NOTFOUND) {
total_errors++;
printf("ERROR Non existant group gave error %d\n", last_error);
}
grp = getgrgid(0xFFF0);
if (grp || last_error != NSS_STATUS_NOTFOUND) {
total_errors++;
printf("ERROR Non existant gid gave error %d\n", last_error);
}
}
int main(int argc, char *argv[])
{
if (argc > 1) so_path = argv[1];
if (argc > 2) nss_name = argv[2];
nss_test_users();
nss_test_groups();
nss_test_errors();
printf("total_errors=%d\n", total_errors);
return total_errors;
}
|
racemidev/WMI_cmd
|
Samba/source/torture/nsstest.c
|
C
|
gpl-2.0
| 9,525
|
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2013 Google Inc.
* Copyright (C) 2015 Intel Corp.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <cpu/x86/msr.h>
#include <cpu/x86/tsc.h>
#include <rules.h>
#include <soc/msr.h>
#include <console/console.h>
#if ENV_RAMSTAGE
#include <soc/ramstage.h>
#else
#include <soc/romstage.h>
#endif
#include <stdint.h>
static const unsigned int cpu_bus_clk_freq_table[] = {
83333,
100000,
133333,
116666,
80000,
93333,
90000,
88900,
87500
};
unsigned int cpu_bus_freq_khz(void)
{
msr_t clk_info = rdmsr(MSR_BSEL_CR_OVERCLOCK_CONTROL);
if((clk_info.lo & 0xF) < (sizeof(cpu_bus_clk_freq_table)/sizeof(unsigned int)))
{
return(cpu_bus_clk_freq_table[clk_info.lo & 0xF]);
}
return 0;
}
unsigned long tsc_freq_mhz(void)
{
msr_t platform_info;
unsigned int bclk_khz = cpu_bus_freq_khz();
if (!bclk_khz)
return 0;
platform_info = rdmsr(MSR_PLATFORM_INFO);
return (bclk_khz * ((platform_info.lo >> 8) & 0xff)) / 1000;
}
#if !ENV_SMM
void set_max_freq(void)
{
msr_t perf_ctl;
msr_t msr;
/* Enable speed step. */
msr = rdmsr(MSR_IA32_MISC_ENABLES);
msr.lo |= (1 << 16);
wrmsr(MSR_IA32_MISC_ENABLES, msr);
/* Enable Burst Mode */
msr = rdmsr(MSR_IA32_MISC_ENABLES);
msr.hi = 0;
wrmsr(MSR_IA32_MISC_ENABLES, msr);
/*
* Set guranteed ratio [21:16] from IACORE_RATIOS to bits [15:8] of
* the PERF_CTL.
*/
msr = rdmsr(MSR_IACORE_TURBO_RATIOS);
perf_ctl.lo = (msr.lo & 0x3f0000) >> 8;
/*
* Set guranteed vid [21:16] from IACORE_VIDS to bits [7:0] of
* the PERF_CTL.
*/
msr = rdmsr(MSR_IACORE_TURBO_VIDS);
perf_ctl.lo |= (msr.lo & 0x7f0000) >> 16;
perf_ctl.hi = 0;
wrmsr(MSR_IA32_PERF_CTL, perf_ctl);
}
#endif /* ENV_SMM */
|
latelee/coreboot
|
src/soc/intel/braswell/tsc_freq.c
|
C
|
gpl-2.0
| 2,156
|
/**
* $Id$
*
* Copyright (C) 2012 Daniel-Constantin Mierla (asipto.com)
*
* This file is part of Kamailio, a free SIP server.
*
* This file 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 file 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
*
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "../../dprint.h"
#include "../../globals.h"
#include "../../ut.h"
#include "../../dset.h"
#include "msrp_parser.h"
#include "msrp_netio.h"
#include "msrp_env.h"
extern int msrp_param_sipmsg;
static msrp_env_t _msrp_env = {0};
/**
*
*/
msrp_env_t *msrp_get_env(void)
{
return &_msrp_env;
}
/**
*
*/
void msrp_reset_env(void)
{
memset(&_msrp_env, 0, sizeof(struct msrp_env));
}
/**
*
*/
msrp_frame_t *msrp_get_current_frame(void)
{
return _msrp_env.msrp;
}
/**
*
*/
int msrp_set_current_frame(msrp_frame_t *mf)
{
_msrp_env.msrp = mf;
init_dst_from_rcv(&_msrp_env.srcinfo, mf->tcpinfo->rcv);
_msrp_env.envflags |= MSRP_ENV_SRCINFO;
return 0;
}
/**
*
*/
int msrp_env_set_dstinfo(msrp_frame_t *mf, str *addr, str *fsock, int flags)
{
struct socket_info *si = NULL;
snd_flags_t sflags = {0};
if(fsock!=NULL && fsock->len>0)
{
si = msrp_get_local_socket(fsock);
if(si==NULL)
{
LM_DBG("local socket not found [%.*s] - trying to continue\n",
fsock->len, fsock->s);
}
}
sflags.f = flags;
if(si==NULL)
{
sflags.f &= ~SND_F_FORCE_SOCKET;
} else {
sflags.f |= SND_F_FORCE_SOCKET;
}
sflags.f |= _msrp_env.sndflags;
memset(&_msrp_env.dstinfo, 0, sizeof(struct dest_info));
if(msrp_uri_to_dstinfo(NULL, &_msrp_env.dstinfo, si, sflags, addr)==NULL)
{
LM_ERR("failed to set destination address [%.*s]\n",
addr->len, addr->s);
return -1;
}
_msrp_env.envflags |= MSRP_ENV_DSTINFO;
return 0;
}
/**
*
*/
int msrp_env_set_sndflags(msrp_frame_t *mf, int flags)
{
_msrp_env.sndflags |= (flags & (~SND_F_FORCE_SOCKET));
if(_msrp_env.envflags & MSRP_ENV_DSTINFO)
{
_msrp_env.dstinfo.send_flags.f |= _msrp_env.sndflags;
}
return 0;
}
/**
*
*/
int msrp_env_set_rplflags(msrp_frame_t *mf, int flags)
{
_msrp_env.rplflags |= (flags & (~SND_F_FORCE_SOCKET));
if(_msrp_env.envflags & MSRP_ENV_SRCINFO)
{
_msrp_env.srcinfo.send_flags.f |= _msrp_env.rplflags;
}
return 0;
}
/**
*
*/
#define MSRP_FAKED_SIPMSG_START "MSRP sip:a@127.0.0.1 SIP/2.0\r\nVia: SIP/2.0/UDP 127.0.0.1:9;branch=z9hG4bKa\r\nFrom: <b@127.0.0.1>;tag=a\r\nTo: <a@127.0.0.1>\r\nCall-ID: a\r\nCSeq: 1 MSRP\r\nContent-Length: 0\r\nMSRP-First-Line: "
#define MSRP_FAKED_SIPMSG_EXTRA 11240
#define MSRP_FAKED_SIPMSG_SIZE (sizeof(MSRP_FAKED_SIPMSG_START)+MSRP_FAKED_SIPMSG_EXTRA)
static char _msrp_faked_sipmsg_buf[MSRP_FAKED_SIPMSG_SIZE];
static sip_msg_t _msrp_faked_sipmsg;
static unsigned int _msrp_faked_sipmsg_no = 0;
sip_msg_t *msrp_fake_sipmsg(msrp_frame_t *mf)
{
int len;
if(msrp_param_sipmsg==0)
return NULL;
if(mf->buf.len >= MSRP_FAKED_SIPMSG_EXTRA-1)
return NULL;
len = sizeof(MSRP_FAKED_SIPMSG_START)-1;
memcpy(_msrp_faked_sipmsg_buf, MSRP_FAKED_SIPMSG_START, len);
memcpy(_msrp_faked_sipmsg_buf + len, mf->buf.s,
mf->fline.buf.len + mf->hbody.len);
len += mf->fline.buf.len + mf->hbody.len;
memcpy(_msrp_faked_sipmsg_buf + len, "\r\n", 2);
len += 2;
_msrp_faked_sipmsg_buf[len] = '\0';
memset(&_msrp_faked_sipmsg, 0, sizeof(sip_msg_t));
_msrp_faked_sipmsg.buf=_msrp_faked_sipmsg_buf;
_msrp_faked_sipmsg.len=len;
_msrp_faked_sipmsg.set_global_address=default_global_address;
_msrp_faked_sipmsg.set_global_port=default_global_port;
if (parse_msg(_msrp_faked_sipmsg.buf, _msrp_faked_sipmsg.len,
&_msrp_faked_sipmsg)!=0)
{
LM_ERR("parse_msg failed\n");
return NULL;
}
_msrp_faked_sipmsg.id = 1 + _msrp_faked_sipmsg_no++;
_msrp_faked_sipmsg.pid = my_pid();
clear_branches();
return &_msrp_faked_sipmsg;
}
|
gbour/kamailio
|
modules/msrp/msrp_env.c
|
C
|
gpl-2.0
| 4,430
|
VERSION = 3
PATCHLEVEL = 13
SUBLEVEL = 0
EXTRAVERSION = +PE
NAME = One Giant Leap for Frogkind
# *DOCUMENTATION*
# To see a list of typical targets execute "make help"
# More info can be located in ./README
# Comments in this file are targeted only to the developer, do not
# expect to learn how to build the kernel reading this file.
# Do not:
# o use make's built-in rules and variables
# (this increases performance and avoids hard-to-debug behaviour);
# o print "Entering directory ...";
MAKEFLAGS += -rR --no-print-directory
# Avoid funny character set dependencies
unexport LC_ALL
LC_COLLATE=C
LC_NUMERIC=C
export LC_COLLATE LC_NUMERIC
# Avoid interference with shell env settings
unexport GREP_OPTIONS
# We are using a recursive build, so we need to do a little thinking
# to get the ordering right.
#
# Most importantly: sub-Makefiles should only ever modify files in
# their own directory. If in some directory we have a dependency on
# a file in another dir (which doesn't happen often, but it's often
# unavoidable when linking the built-in.o targets which finally
# turn into vmlinux), we will call a sub make in that other dir, and
# after that we are sure that everything which is in that other dir
# is now up to date.
#
# The only cases where we need to modify files which have global
# effects are thus separated out and done before the recursive
# descending is started. They are now explicitly listed as the
# prepare rule.
# To put more focus on warnings, be less verbose as default
# Use 'make V=1' to see the full commands
ifeq ("$(origin V)", "command line")
KBUILD_VERBOSE = $(V)
endif
ifndef KBUILD_VERBOSE
KBUILD_VERBOSE = 0
endif
# Call a source code checker (by default, "sparse") as part of the
# C compilation.
#
# Use 'make C=1' to enable checking of only re-compiled files.
# Use 'make C=2' to enable checking of *all* source files, regardless
# of whether they are re-compiled or not.
#
# See the file "Documentation/sparse.txt" for more details, including
# where to get the "sparse" utility.
ifeq ("$(origin C)", "command line")
KBUILD_CHECKSRC = $(C)
endif
ifndef KBUILD_CHECKSRC
KBUILD_CHECKSRC = 0
endif
# Use make M=dir to specify directory of external module to build
# Old syntax make ... SUBDIRS=$PWD is still supported
# Setting the environment variable KBUILD_EXTMOD take precedence
ifdef SUBDIRS
KBUILD_EXTMOD ?= $(SUBDIRS)
endif
ifeq ("$(origin M)", "command line")
KBUILD_EXTMOD := $(M)
endif
# kbuild supports saving output files in a separate directory.
# To locate output files in a separate directory two syntaxes are supported.
# In both cases the working directory must be the root of the kernel src.
# 1) O=
# Use "make O=dir/to/store/output/files/"
#
# 2) Set KBUILD_OUTPUT
# Set the environment variable KBUILD_OUTPUT to point to the directory
# where the output files shall be placed.
# export KBUILD_OUTPUT=dir/to/store/output/files/
# make
#
# The O= assignment takes precedence over the KBUILD_OUTPUT environment
# variable.
# KBUILD_SRC is set on invocation of make in OBJ directory
# KBUILD_SRC is not intended to be used by the regular user (for now)
ifeq ($(KBUILD_SRC),)
# OK, Make called in directory where kernel src resides
# Do we want to locate output files in a separate directory?
ifeq ("$(origin O)", "command line")
KBUILD_OUTPUT := $(O)
endif
ifeq ("$(origin W)", "command line")
export KBUILD_ENABLE_EXTRA_GCC_CHECKS := $(W)
endif
# That's our default target when none is given on the command line
PHONY := _all
_all:
# Cancel implicit rules on top Makefile
$(CURDIR)/Makefile Makefile: ;
ifneq ($(KBUILD_OUTPUT),)
# Invoke a second make in the output directory, passing relevant variables
# check that the output directory actually exists
saved-output := $(KBUILD_OUTPUT)
KBUILD_OUTPUT := $(shell cd $(KBUILD_OUTPUT) && /bin/pwd)
$(if $(KBUILD_OUTPUT),, \
$(error output directory "$(saved-output)" does not exist))
PHONY += $(MAKECMDGOALS) sub-make
$(filter-out _all sub-make $(CURDIR)/Makefile, $(MAKECMDGOALS)) _all: sub-make
@:
sub-make: FORCE
$(if $(KBUILD_VERBOSE:1=),@)$(MAKE) -C $(KBUILD_OUTPUT) \
KBUILD_SRC=$(CURDIR) \
KBUILD_EXTMOD="$(KBUILD_EXTMOD)" -f $(CURDIR)/Makefile \
$(filter-out _all sub-make,$(MAKECMDGOALS))
# Leave processing to above invocation of make
skip-makefile := 1
endif # ifneq ($(KBUILD_OUTPUT),)
endif # ifeq ($(KBUILD_SRC),)
# We process the rest of the Makefile if this is the final invocation of make
ifeq ($(skip-makefile),)
# If building an external module we do not care about the all: rule
# but instead _all depend on modules
PHONY += all
ifeq ($(KBUILD_EXTMOD),)
_all: all
else
_all: modules
endif
srctree := $(if $(KBUILD_SRC),$(KBUILD_SRC),$(CURDIR))
objtree := $(CURDIR)
src := $(srctree)
obj := $(objtree)
VPATH := $(srctree)$(if $(KBUILD_EXTMOD),:$(KBUILD_EXTMOD))
export srctree objtree VPATH
# SUBARCH tells the usermode build what the underlying arch is. That is set
# first, and if a usermode build is happening, the "ARCH=um" on the command
# line overrides the setting of ARCH below. If a native build is happening,
# then ARCH is assigned, getting whatever value it gets normally, and
# SUBARCH is subsequently ignored.
SUBARCH := $(shell uname -m | sed -e s/i.86/x86/ -e s/x86_64/x86/ \
-e s/sun4u/sparc64/ \
-e s/arm.*/arm/ -e s/sa110/arm/ \
-e s/s390x/s390/ -e s/parisc64/parisc/ \
-e s/ppc.*/powerpc/ -e s/mips.*/mips/ \
-e s/sh[234].*/sh/ -e s/aarch64.*/arm64/ )
# Cross compiling and selecting different set of gcc/bin-utils
# ---------------------------------------------------------------------------
#
# When performing cross compilation for other architectures ARCH shall be set
# to the target architecture. (See arch/* for the possibilities).
# ARCH can be set during invocation of make:
# make ARCH=ia64
# Another way is to have ARCH set in the environment.
# The default ARCH is the host where make is executed.
# CROSS_COMPILE specify the prefix used for all executables used
# during compilation. Only gcc and related bin-utils executables
# are prefixed with $(CROSS_COMPILE).
# CROSS_COMPILE can be set on the command line
# make CROSS_COMPILE=ia64-linux-
# Alternatively CROSS_COMPILE can be set in the environment.
# A third alternative is to store a setting in .config so that plain
# "make" in the configured kernel build directory always uses that.
# Default value for CROSS_COMPILE is not to prefix executables
# Note: Some architectures assign CROSS_COMPILE in their arch/*/Makefile
ARCH ?= $(SUBARCH)
CROSS_COMPILE ?= $(CONFIG_CROSS_COMPILE:"%"=%)
# Architecture as present in compile.h
UTS_MACHINE := $(ARCH)
SRCARCH := $(ARCH)
# Additional ARCH settings for x86
ifeq ($(ARCH),i386)
SRCARCH := x86
endif
ifeq ($(ARCH),x86_64)
SRCARCH := x86
endif
# Additional ARCH settings for sparc
ifeq ($(ARCH),sparc32)
SRCARCH := sparc
endif
ifeq ($(ARCH),sparc64)
SRCARCH := sparc
endif
# Additional ARCH settings for sh
ifeq ($(ARCH),sh64)
SRCARCH := sh
endif
# Additional ARCH settings for tile
ifeq ($(ARCH),tilepro)
SRCARCH := tile
endif
ifeq ($(ARCH),tilegx)
SRCARCH := tile
endif
# Where to locate arch specific headers
hdr-arch := $(SRCARCH)
KCONFIG_CONFIG ?= .config
export KCONFIG_CONFIG
# SHELL used by kbuild
CONFIG_SHELL := $(shell if [ -x "$$BASH" ]; then echo $$BASH; \
else if [ -x /bin/bash ]; then echo /bin/bash; \
else echo sh; fi ; fi)
HOSTCC = gcc
HOSTCXX = g++
HOSTCFLAGS = -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer
HOSTCXXFLAGS = -O2
# Decide whether to build built-in, modular, or both.
# Normally, just do built-in.
KBUILD_MODULES :=
KBUILD_BUILTIN := 1
# If we have only "make modules", don't compile built-in objects.
# When we're building modules with modversions, we need to consider
# the built-in objects during the descend as well, in order to
# make sure the checksums are up to date before we record them.
ifeq ($(MAKECMDGOALS),modules)
KBUILD_BUILTIN := $(if $(CONFIG_MODVERSIONS),1)
endif
# If we have "make <whatever> modules", compile modules
# in addition to whatever we do anyway.
# Just "make" or "make all" shall build modules as well
ifneq ($(filter all _all modules,$(MAKECMDGOALS)),)
KBUILD_MODULES := 1
endif
ifeq ($(MAKECMDGOALS),)
KBUILD_MODULES := 1
endif
export KBUILD_MODULES KBUILD_BUILTIN
export KBUILD_CHECKSRC KBUILD_SRC KBUILD_EXTMOD
# Beautify output
# ---------------------------------------------------------------------------
#
# Normally, we echo the whole command before executing it. By making
# that echo $($(quiet)$(cmd)), we now have the possibility to set
# $(quiet) to choose other forms of output instead, e.g.
#
# quiet_cmd_cc_o_c = Compiling $(RELDIR)/$@
# cmd_cc_o_c = $(CC) $(c_flags) -c -o $@ $<
#
# If $(quiet) is empty, the whole command will be printed.
# If it is set to "quiet_", only the short version will be printed.
# If it is set to "silent_", nothing will be printed at all, since
# the variable $(silent_cmd_cc_o_c) doesn't exist.
#
# A simple variant is to prefix commands with $(Q) - that's useful
# for commands that shall be hidden in non-verbose mode.
#
# $(Q)ln $@ :<
#
# If KBUILD_VERBOSE equals 0 then the above command will be hidden.
# If KBUILD_VERBOSE equals 1 then the above command is displayed.
ifeq ($(KBUILD_VERBOSE),1)
quiet =
Q =
else
quiet=quiet_
Q = @
endif
# If the user is running make -s (silent mode), suppress echoing of
# commands
ifneq ($(filter s% -s%,$(MAKEFLAGS)),)
quiet=silent_
endif
export quiet Q KBUILD_VERBOSE
# Look for make include files relative to root of kernel src
MAKEFLAGS += --include-dir=$(srctree)
# We need some generic definitions (do not try to remake the file).
$(srctree)/scripts/Kbuild.include: ;
include $(srctree)/scripts/Kbuild.include
# Make variables (CC, etc...)
AS = $(CROSS_COMPILE)as
LD = $(CROSS_COMPILE)ld
CC = $(CROSS_COMPILE)gcc
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar
NM = $(CROSS_COMPILE)nm
STRIP = $(CROSS_COMPILE)strip
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump
AWK = awk
GENKSYMS = scripts/genksyms/genksyms
INSTALLKERNEL := installkernel
DEPMOD = /sbin/depmod
PERL = perl
CHECK = sparse
CHECKFLAGS := -D__linux__ -Dlinux -D__STDC__ -Dunix -D__unix__ \
-Wbitwise -Wno-return-void $(CF)
CFLAGS_MODULE =
AFLAGS_MODULE =
LDFLAGS_MODULE =
CFLAGS_KERNEL =
AFLAGS_KERNEL =
CFLAGS_GCOV = -fprofile-arcs -ftest-coverage
# Use USERINCLUDE when you must reference the UAPI directories only.
USERINCLUDE := \
-I$(srctree)/arch/$(hdr-arch)/include/uapi \
-Iarch/$(hdr-arch)/include/generated/uapi \
-I$(srctree)/include/uapi \
-Iinclude/generated/uapi \
-include $(srctree)/include/linux/kconfig.h
# Use LINUXINCLUDE when you must reference the include/ directory.
# Needed to be compatible with the O= option
LINUXINCLUDE := \
-I$(srctree)/arch/$(hdr-arch)/include \
-Iarch/$(hdr-arch)/include/generated \
$(if $(KBUILD_SRC), -I$(srctree)/include) \
-Iinclude \
$(USERINCLUDE)
KBUILD_CPPFLAGS := -D__KERNEL__
KBUILD_CFLAGS := -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs \
-fno-strict-aliasing -fno-common \
-Werror-implicit-function-declaration \
-Wno-format-security \
-fno-delete-null-pointer-checks
KBUILD_AFLAGS_KERNEL :=
KBUILD_CFLAGS_KERNEL :=
KBUILD_AFLAGS := -D__ASSEMBLY__
KBUILD_AFLAGS_MODULE := -DMODULE
KBUILD_CFLAGS_MODULE := -DMODULE
KBUILD_LDFLAGS_MODULE := -T $(srctree)/scripts/module-common.lds
# Read KERNELRELEASE from include/config/kernel.release (if it exists)
KERNELRELEASE = $(shell cat include/config/kernel.release 2> /dev/null)
KERNELVERSION = $(VERSION)$(if $(PATCHLEVEL),.$(PATCHLEVEL)$(if $(SUBLEVEL),.$(SUBLEVEL)))$(EXTRAVERSION)
export VERSION PATCHLEVEL SUBLEVEL KERNELRELEASE KERNELVERSION
export ARCH SRCARCH CONFIG_SHELL HOSTCC HOSTCFLAGS CROSS_COMPILE AS LD CC
export CPP AR NM STRIP OBJCOPY OBJDUMP
export MAKE AWK GENKSYMS INSTALLKERNEL PERL UTS_MACHINE
export HOSTCXX HOSTCXXFLAGS LDFLAGS_MODULE CHECK CHECKFLAGS
export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS LDFLAGS
export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE CFLAGS_GCOV
export KBUILD_AFLAGS AFLAGS_KERNEL AFLAGS_MODULE
export KBUILD_AFLAGS_MODULE KBUILD_CFLAGS_MODULE KBUILD_LDFLAGS_MODULE
export KBUILD_AFLAGS_KERNEL KBUILD_CFLAGS_KERNEL
export KBUILD_ARFLAGS
# When compiling out-of-tree modules, put MODVERDIR in the module
# tree rather than in the kernel tree. The kernel tree might
# even be read-only.
export MODVERDIR := $(if $(KBUILD_EXTMOD),$(firstword $(KBUILD_EXTMOD))/).tmp_versions
# Files to ignore in find ... statements
RCS_FIND_IGNORE := \( -name SCCS -o -name BitKeeper -o -name .svn -o -name CVS \
-o -name .pc -o -name .hg -o -name .git \) -prune -o
export RCS_TAR_IGNORE := --exclude SCCS --exclude BitKeeper --exclude .svn \
--exclude CVS --exclude .pc --exclude .hg --exclude .git
# ===========================================================================
# Rules shared between *config targets and build targets
# Basic helpers built in scripts/
PHONY += scripts_basic
scripts_basic:
$(Q)$(MAKE) $(build)=scripts/basic
$(Q)rm -f .tmp_quiet_recordmcount
# To avoid any implicit rule to kick in, define an empty command.
scripts/basic/%: scripts_basic ;
PHONY += outputmakefile
# outputmakefile generates a Makefile in the output directory, if using a
# separate output directory. This allows convenient use of make in the
# output directory.
outputmakefile:
ifneq ($(KBUILD_SRC),)
$(Q)ln -fsn $(srctree) source
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/mkmakefile \
$(srctree) $(objtree) $(VERSION) $(PATCHLEVEL)
endif
# Support for using generic headers in asm-generic
PHONY += asm-generic
asm-generic:
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.asm-generic \
src=asm obj=arch/$(SRCARCH)/include/generated/asm
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.asm-generic \
src=uapi/asm obj=arch/$(SRCARCH)/include/generated/uapi/asm
# To make sure we do not include .config for any of the *config targets
# catch them early, and hand them over to scripts/kconfig/Makefile
# It is allowed to specify more targets when calling make, including
# mixing *config targets and build targets.
# For example 'make oldconfig all'.
# Detect when mixed targets is specified, and make a second invocation
# of make so .config is not included in this case either (for *config).
version_h := include/generated/uapi/linux/version.h
no-dot-config-targets := clean mrproper distclean \
cscope gtags TAGS tags help %docs check% coccicheck \
$(version_h) headers_% archheaders archscripts \
kernelversion %src-pkg
config-targets := 0
mixed-targets := 0
dot-config := 1
ifneq ($(filter $(no-dot-config-targets), $(MAKECMDGOALS)),)
ifeq ($(filter-out $(no-dot-config-targets), $(MAKECMDGOALS)),)
dot-config := 0
endif
endif
ifeq ($(KBUILD_EXTMOD),)
ifneq ($(filter config %config,$(MAKECMDGOALS)),)
config-targets := 1
ifneq ($(filter-out config %config,$(MAKECMDGOALS)),)
mixed-targets := 1
endif
endif
endif
ifeq ($(mixed-targets),1)
# ===========================================================================
# We're called with mixed targets (*config and build targets).
# Handle them one by one.
%:: FORCE
$(Q)$(MAKE) -C $(srctree) KBUILD_SRC= $@
else
ifeq ($(config-targets),1)
# ===========================================================================
# *config targets only - make sure prerequisites are updated, and descend
# in scripts/kconfig to make the *config target
# Read arch specific Makefile to set KBUILD_DEFCONFIG as needed.
# KBUILD_DEFCONFIG may point out an alternative default configuration
# used for 'make defconfig'
include $(srctree)/arch/$(SRCARCH)/Makefile
export KBUILD_DEFCONFIG KBUILD_KCONFIG
config: scripts_basic outputmakefile FORCE
$(Q)mkdir -p include/linux include/config
$(Q)$(MAKE) $(build)=scripts/kconfig $@
%config: scripts_basic outputmakefile FORCE
$(Q)mkdir -p include/linux include/config
$(Q)$(MAKE) $(build)=scripts/kconfig $@
else
# ===========================================================================
# Build targets only - this includes vmlinux, arch specific targets, clean
# targets and others. In general all targets except *config targets.
ifeq ($(KBUILD_EXTMOD),)
# Additional helpers built in scripts/
# Carefully list dependencies so we do not try to build scripts twice
# in parallel
PHONY += scripts
scripts: scripts_basic include/config/auto.conf include/config/tristate.conf \
asm-generic
$(Q)$(MAKE) $(build)=$(@)
# Objects we will link into vmlinux / subdirs we need to visit
init-y := init/
drivers-y := drivers/ sound/ firmware/
net-y := net/
libs-y := lib/
core-y := usr/
endif # KBUILD_EXTMOD
ifeq ($(dot-config),1)
# Read in config
-include include/config/auto.conf
ifeq ($(KBUILD_EXTMOD),)
# Read in dependencies to all Kconfig* files, make sure to run
# oldconfig if changes are detected.
-include include/config/auto.conf.cmd
# To avoid any implicit rule to kick in, define an empty command
$(KCONFIG_CONFIG) include/config/auto.conf.cmd: ;
# If .config is newer than include/config/auto.conf, someone tinkered
# with it and forgot to run make oldconfig.
# if auto.conf.cmd is missing then we are probably in a cleaned tree so
# we execute the config step to be sure to catch updated Kconfig files
include/config/%.conf: $(KCONFIG_CONFIG) include/config/auto.conf.cmd
$(Q)$(MAKE) -f $(srctree)/Makefile silentoldconfig
else
# external modules needs include/generated/autoconf.h and include/config/auto.conf
# but do not care if they are up-to-date. Use auto.conf to trigger the test
PHONY += include/config/auto.conf
include/config/auto.conf:
$(Q)test -e include/generated/autoconf.h -a -e $@ || ( \
echo >&2; \
echo >&2 " ERROR: Kernel configuration is invalid."; \
echo >&2 " include/generated/autoconf.h or $@ are missing.";\
echo >&2 " Run 'make oldconfig && make prepare' on kernel src to fix it."; \
echo >&2 ; \
/bin/false)
endif # KBUILD_EXTMOD
else
# Dummy target needed, because used as prerequisite
include/config/auto.conf: ;
endif # $(dot-config)
# The all: target is the default when no target is given on the
# command line.
# This allow a user to issue only 'make' to build a kernel including modules
# Defaults to vmlinux, but the arch makefile usually adds further targets
all: vmlinux
ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE
KBUILD_CFLAGS += -Os $(call cc-disable-warning,maybe-uninitialized,)
else
KBUILD_CFLAGS += -O2
endif
include $(srctree)/arch/$(SRCARCH)/Makefile
ifdef CONFIG_READABLE_ASM
# Disable optimizations that make assembler listings hard to read.
# reorder blocks reorders the control in the function
# ipa clone creates specialized cloned functions
# partial inlining inlines only parts of functions
KBUILD_CFLAGS += $(call cc-option,-fno-reorder-blocks,) \
$(call cc-option,-fno-ipa-cp-clone,) \
$(call cc-option,-fno-partial-inlining)
endif
ifneq ($(CONFIG_FRAME_WARN),0)
KBUILD_CFLAGS += $(call cc-option,-Wframe-larger-than=${CONFIG_FRAME_WARN})
endif
# Force gcc to behave correct even for buggy distributions
ifndef CONFIG_CC_STACKPROTECTOR
KBUILD_CFLAGS += $(call cc-option, -fno-stack-protector)
endif
# This warning generated too much noise in a regular build.
# Use make W=1 to enable this warning (see scripts/Makefile.build)
KBUILD_CFLAGS += $(call cc-disable-warning, unused-but-set-variable)
ifdef CONFIG_FRAME_POINTER
KBUILD_CFLAGS += -fno-omit-frame-pointer -fno-optimize-sibling-calls
else
# Some targets (ARM with Thumb2, for example), can't be built with frame
# pointers. For those, we don't have FUNCTION_TRACER automatically
# select FRAME_POINTER. However, FUNCTION_TRACER adds -pg, and this is
# incompatible with -fomit-frame-pointer with current GCC, so we don't use
# -fomit-frame-pointer with FUNCTION_TRACER.
ifndef CONFIG_FUNCTION_TRACER
KBUILD_CFLAGS += -fomit-frame-pointer
endif
endif
ifdef CONFIG_DEBUG_INFO
KBUILD_CFLAGS += -g
KBUILD_AFLAGS += -gdwarf-2
endif
ifdef CONFIG_DEBUG_INFO_REDUCED
KBUILD_CFLAGS += $(call cc-option, -femit-struct-debug-baseonly) \
$(call cc-option,-fno-var-tracking)
endif
ifdef CONFIG_FUNCTION_TRACER
ifdef CONFIG_HAVE_FENTRY
CC_USING_FENTRY := $(call cc-option, -mfentry -DCC_USING_FENTRY)
endif
KBUILD_CFLAGS += -pg $(CC_USING_FENTRY)
KBUILD_AFLAGS += $(CC_USING_FENTRY)
ifdef CONFIG_DYNAMIC_FTRACE
ifdef CONFIG_HAVE_C_RECORDMCOUNT
BUILD_C_RECORDMCOUNT := y
export BUILD_C_RECORDMCOUNT
endif
endif
endif
# We trigger additional mismatches with less inlining
ifdef CONFIG_DEBUG_SECTION_MISMATCH
KBUILD_CFLAGS += $(call cc-option, -fno-inline-functions-called-once)
endif
# arch Makefile may override CC so keep this after arch Makefile is included
NOSTDINC_FLAGS += -nostdinc -isystem $(shell $(CC) -print-file-name=include)
CHECKFLAGS += $(NOSTDINC_FLAGS)
# warn about C99 declaration after statement
KBUILD_CFLAGS += $(call cc-option,-Wdeclaration-after-statement,)
# disable pointer signed / unsigned warnings in gcc 4.0
KBUILD_CFLAGS += $(call cc-disable-warning, pointer-sign)
# disable invalid "can't wrap" optimizations for signed / pointers
KBUILD_CFLAGS += $(call cc-option,-fno-strict-overflow)
# conserve stack if available
KBUILD_CFLAGS += $(call cc-option,-fconserve-stack)
# disallow errors like 'EXPORT_GPL(foo);' with missing header
KBUILD_CFLAGS += $(call cc-option,-Werror=implicit-int)
# require functions to have arguments in prototypes, not empty 'int foo()'
KBUILD_CFLAGS += $(call cc-option,-Werror=strict-prototypes)
# use the deterministic mode of AR if available
KBUILD_ARFLAGS := $(call ar-option,D)
# check for 'asm goto'
ifeq ($(shell $(CONFIG_SHELL) $(srctree)/scripts/gcc-goto.sh $(CC)), y)
KBUILD_CFLAGS += -DCC_HAVE_ASM_GOTO
endif
# Add user supplied CPPFLAGS, AFLAGS and CFLAGS as the last assignments
KBUILD_CPPFLAGS += $(KCPPFLAGS)
KBUILD_AFLAGS += $(KAFLAGS)
KBUILD_CFLAGS += $(KCFLAGS)
# Use --build-id when available.
LDFLAGS_BUILD_ID = $(patsubst -Wl$(comma)%,%,\
$(call cc-ldoption, -Wl$(comma)--build-id,))
KBUILD_LDFLAGS_MODULE += $(LDFLAGS_BUILD_ID)
LDFLAGS_vmlinux += $(LDFLAGS_BUILD_ID)
ifeq ($(CONFIG_STRIP_ASM_SYMS),y)
LDFLAGS_vmlinux += $(call ld-option, -X,)
endif
# Default kernel image to build when no specific target is given.
# KBUILD_IMAGE may be overruled on the command line or
# set in the environment
# Also any assignments in arch/$(ARCH)/Makefile take precedence over
# this default value
export KBUILD_IMAGE ?= vmlinux
#
# INSTALL_PATH specifies where to place the updated kernel and system map
# images. Default is /boot, but you can set it to other values
export INSTALL_PATH ?= /boot
#
# INSTALL_MOD_PATH specifies a prefix to MODLIB for module directory
# relocations required by build roots. This is not defined in the
# makefile but the argument can be passed to make if needed.
#
MODLIB = $(INSTALL_MOD_PATH)/lib/modules/$(KERNELRELEASE)
export MODLIB
#
# INSTALL_MOD_STRIP, if defined, will cause modules to be
# stripped after they are installed. If INSTALL_MOD_STRIP is '1', then
# the default option --strip-debug will be used. Otherwise,
# INSTALL_MOD_STRIP value will be used as the options to the strip command.
ifdef INSTALL_MOD_STRIP
ifeq ($(INSTALL_MOD_STRIP),1)
mod_strip_cmd = $(STRIP) --strip-debug
else
mod_strip_cmd = $(STRIP) $(INSTALL_MOD_STRIP)
endif # INSTALL_MOD_STRIP=1
else
mod_strip_cmd = true
endif # INSTALL_MOD_STRIP
export mod_strip_cmd
# Select initial ramdisk compression format, default is gzip(1).
# This shall be used by the dracut(8) tool while creating an initramfs image.
#
INITRD_COMPRESS-y := gzip
INITRD_COMPRESS-$(CONFIG_RD_BZIP2) := bzip2
INITRD_COMPRESS-$(CONFIG_RD_LZMA) := lzma
INITRD_COMPRESS-$(CONFIG_RD_XZ) := xz
INITRD_COMPRESS-$(CONFIG_RD_LZO) := lzo
INITRD_COMPRESS-$(CONFIG_RD_LZ4) := lz4
# do not export INITRD_COMPRESS, since we didn't actually
# choose a sane default compression above.
# export INITRD_COMPRESS := $(INITRD_COMPRESS-y)
ifdef CONFIG_MODULE_SIG_ALL
MODSECKEY = ./signing_key.priv
MODPUBKEY = ./signing_key.x509
export MODPUBKEY
mod_sign_cmd = perl $(srctree)/scripts/sign-file $(CONFIG_MODULE_SIG_HASH) $(MODSECKEY) $(MODPUBKEY)
else
mod_sign_cmd = true
endif
export mod_sign_cmd
ifeq ($(KBUILD_EXTMOD),)
core-y += kernel/ mm/ fs/ ipc/ security/ crypto/ block/
vmlinux-dirs := $(patsubst %/,%,$(filter %/, $(init-y) $(init-m) \
$(core-y) $(core-m) $(drivers-y) $(drivers-m) \
$(net-y) $(net-m) $(libs-y) $(libs-m)))
vmlinux-alldirs := $(sort $(vmlinux-dirs) $(patsubst %/,%,$(filter %/, \
$(init-n) $(init-) \
$(core-n) $(core-) $(drivers-n) $(drivers-) \
$(net-n) $(net-) $(libs-n) $(libs-))))
init-y := $(patsubst %/, %/built-in.o, $(init-y))
core-y := $(patsubst %/, %/built-in.o, $(core-y))
drivers-y := $(patsubst %/, %/built-in.o, $(drivers-y))
net-y := $(patsubst %/, %/built-in.o, $(net-y))
libs-y1 := $(patsubst %/, %/lib.a, $(libs-y))
libs-y2 := $(patsubst %/, %/built-in.o, $(libs-y))
libs-y := $(libs-y1) $(libs-y2)
# Externally visible symbols (used by link-vmlinux.sh)
export KBUILD_VMLINUX_INIT := $(head-y) $(init-y)
export KBUILD_VMLINUX_MAIN := $(core-y) $(libs-y) $(drivers-y) $(net-y)
export KBUILD_LDS := arch/$(SRCARCH)/kernel/vmlinux.lds
export LDFLAGS_vmlinux
# used by scripts/pacmage/Makefile
export KBUILD_ALLDIRS := $(sort $(filter-out arch/%,$(vmlinux-alldirs)) arch Documentation include samples scripts tools virt)
vmlinux-deps := $(KBUILD_LDS) $(KBUILD_VMLINUX_INIT) $(KBUILD_VMLINUX_MAIN)
# Final link of vmlinux
cmd_link-vmlinux = $(CONFIG_SHELL) $< $(LD) $(LDFLAGS) $(LDFLAGS_vmlinux)
quiet_cmd_link-vmlinux = LINK $@
# Include targets which we want to
# execute if the rest of the kernel build went well.
vmlinux: scripts/link-vmlinux.sh $(vmlinux-deps) FORCE
ifdef CONFIG_HEADERS_CHECK
$(Q)$(MAKE) -f $(srctree)/Makefile headers_check
endif
ifdef CONFIG_SAMPLES
$(Q)$(MAKE) $(build)=samples
endif
ifdef CONFIG_BUILD_DOCSRC
$(Q)$(MAKE) $(build)=Documentation
endif
+$(call if_changed,link-vmlinux)
# The actual objects are generated when descending,
# make sure no implicit rule kicks in
$(sort $(vmlinux-deps)): $(vmlinux-dirs) ;
# Handle descending into subdirectories listed in $(vmlinux-dirs)
# Preset locale variables to speed up the build process. Limit locale
# tweaks to this spot to avoid wrong language settings when running
# make menuconfig etc.
# Error messages still appears in the original language
PHONY += $(vmlinux-dirs)
$(vmlinux-dirs): prepare scripts
$(Q)$(MAKE) $(build)=$@
define filechk_kernel.release
echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"
endef
# Store (new) KERNELRELEASE string in include/config/kernel.release
include/config/kernel.release: include/config/auto.conf FORCE
$(call filechk,kernel.release)
# Things we need to do before we recursively start building the kernel
# or the modules are listed in "prepare".
# A multi level approach is used. prepareN is processed before prepareN-1.
# archprepare is used in arch Makefiles and when processed asm symlink,
# version.h and scripts_basic is processed / created.
# Listed in dependency order
PHONY += prepare archprepare prepare0 prepare1 prepare2 prepare3
# prepare3 is used to check if we are building in a separate output directory,
# and if so do:
# 1) Check that make has not been executed in the kernel src $(srctree)
prepare3: include/config/kernel.release
ifneq ($(KBUILD_SRC),)
@$(kecho) ' Using $(srctree) as source for kernel'
$(Q)if [ -f $(srctree)/.config -o -d $(srctree)/include/config ]; then \
echo >&2 " $(srctree) is not clean, please run 'make mrproper'"; \
echo >&2 " in the '$(srctree)' directory.";\
/bin/false; \
fi;
endif
# prepare2 creates a makefile if using a separate output directory
prepare2: prepare3 outputmakefile asm-generic
prepare1: prepare2 $(version_h) include/generated/utsrelease.h \
include/config/auto.conf
$(cmd_crmodverdir)
archprepare: archheaders archscripts prepare1 scripts_basic
prepare0: archprepare FORCE
$(Q)$(MAKE) $(build)=.
# All the preparing..
prepare: prepare0
# Generate some files
# ---------------------------------------------------------------------------
# KERNELRELEASE can change from a few different places, meaning version.h
# needs to be updated, so this check is forced on all builds
uts_len := 64
define filechk_utsrelease.h
if [ `echo -n "$(KERNELRELEASE)" | wc -c ` -gt $(uts_len) ]; then \
echo '"$(KERNELRELEASE)" exceeds $(uts_len) characters' >&2; \
exit 1; \
fi; \
(echo \#define UTS_RELEASE \"$(KERNELRELEASE)\";)
endef
define filechk_version.h
(echo \#define LINUX_VERSION_CODE $(shell \
expr $(VERSION) \* 65536 + 0$(PATCHLEVEL) \* 256 + 0$(SUBLEVEL)); \
echo '#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))';)
endef
$(version_h): $(srctree)/Makefile FORCE
$(call filechk,version.h)
include/generated/utsrelease.h: include/config/kernel.release FORCE
$(call filechk,utsrelease.h)
PHONY += headerdep
headerdep:
$(Q)find $(srctree)/include/ -name '*.h' | xargs --max-args 1 \
$(srctree)/scripts/headerdep.pl -I$(srctree)/include
# ---------------------------------------------------------------------------
PHONY += depend dep
depend dep:
@echo '*** Warning: make $@ is unnecessary now.'
# ---------------------------------------------------------------------------
# Firmware install
INSTALL_FW_PATH=$(INSTALL_MOD_PATH)/lib/firmware
export INSTALL_FW_PATH
PHONY += firmware_install
firmware_install: FORCE
@mkdir -p $(objtree)/firmware
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_install
# ---------------------------------------------------------------------------
# Kernel headers
#Default location for installed headers
export INSTALL_HDR_PATH = $(objtree)/usr
hdr-inst := -rR -f $(srctree)/scripts/Makefile.headersinst obj
# If we do an all arch process set dst to asm-$(hdr-arch)
hdr-dst = $(if $(KBUILD_HEADERS), dst=include/asm-$(hdr-arch), dst=include/asm)
PHONY += archheaders
archheaders:
PHONY += archscripts
archscripts:
PHONY += __headers
__headers: $(version_h) scripts_basic asm-generic archheaders archscripts FORCE
$(Q)$(MAKE) $(build)=scripts build_unifdef
PHONY += headers_install_all
headers_install_all:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/headers.sh install
PHONY += headers_install
headers_install: __headers
$(if $(wildcard $(srctree)/arch/$(hdr-arch)/include/uapi/asm/Kbuild),, \
$(error Headers not exportable for the $(SRCARCH) architecture))
$(Q)$(MAKE) $(hdr-inst)=include/uapi
$(Q)$(MAKE) $(hdr-inst)=arch/$(hdr-arch)/include/uapi/asm $(hdr-dst)
PHONY += headers_check_all
headers_check_all: headers_install_all
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/headers.sh check
PHONY += headers_check
headers_check: headers_install
$(Q)$(MAKE) $(hdr-inst)=include/uapi HDRCHECK=1
$(Q)$(MAKE) $(hdr-inst)=arch/$(hdr-arch)/include/uapi/asm $(hdr-dst) HDRCHECK=1
# ---------------------------------------------------------------------------
# Modules
ifdef CONFIG_MODULES
# By default, build modules as well
all: modules
# Build modules
#
# A module can be listed more than once in obj-m resulting in
# duplicate lines in modules.order files. Those are removed
# using awk while concatenating to the final file.
PHONY += modules
modules: $(vmlinux-dirs) $(if $(KBUILD_BUILTIN),vmlinux) modules.builtin
$(Q)$(AWK) '!x[$$0]++' $(vmlinux-dirs:%=$(objtree)/%/modules.order) > $(objtree)/modules.order
@$(kecho) ' Building modules, stage 2.';
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_modbuild
modules.builtin: $(vmlinux-dirs:%=%/modules.builtin)
$(Q)$(AWK) '!x[$$0]++' $^ > $(objtree)/modules.builtin
%/modules.builtin: include/config/auto.conf
$(Q)$(MAKE) $(modbuiltin)=$*
# Target to prepare building external modules
PHONY += modules_prepare
modules_prepare: prepare scripts
# Target to install modules
PHONY += modules_install
modules_install: _modinst_ _modinst_post
PHONY += _modinst_
_modinst_:
@rm -rf $(MODLIB)/kernel
@rm -f $(MODLIB)/source
@mkdir -p $(MODLIB)/kernel
@ln -s $(srctree) $(MODLIB)/source
@if [ ! $(objtree) -ef $(MODLIB)/build ]; then \
rm -f $(MODLIB)/build ; \
ln -s $(objtree) $(MODLIB)/build ; \
fi
@cp -f $(objtree)/modules.order $(MODLIB)/
@cp -f $(objtree)/modules.builtin $(MODLIB)/
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modinst
# This depmod is only for convenience to give the initial
# boot a modules.dep even before / is mounted read-write. However the
# boot script depmod is the master version.
PHONY += _modinst_post
_modinst_post: _modinst_
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_modinst
$(call cmd,depmod)
ifeq ($(CONFIG_MODULE_SIG), y)
PHONY += modules_sign
modules_sign:
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modsign
endif
else # CONFIG_MODULES
# Modules not configured
# ---------------------------------------------------------------------------
modules modules_install: FORCE
@echo >&2
@echo >&2 "The present kernel configuration has modules disabled."
@echo >&2 "Type 'make config' and enable loadable module support."
@echo >&2 "Then build a kernel with module support enabled."
@echo >&2
@exit 1
endif # CONFIG_MODULES
###
# Cleaning is done on three levels.
# make clean Delete most generated files
# Leave enough to build external modules
# make mrproper Delete the current configuration, and all generated files
# make distclean Remove editor backup files, patch leftover files and the like
# Directories & files removed with 'make clean'
CLEAN_DIRS += $(MODVERDIR)
# Directories & files removed with 'make mrproper'
MRPROPER_DIRS += include/config usr/include include/generated \
arch/*/include/generated
MRPROPER_FILES += .config .config.old .version .old_version $(version_h) \
Module.symvers tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS \
signing_key.priv signing_key.x509 x509.genkey \
extra_certificates signing_key.x509.keyid \
signing_key.x509.signer
# clean - Delete most, but leave enough to build external modules
#
clean: rm-dirs := $(CLEAN_DIRS)
clean: rm-files := $(CLEAN_FILES)
clean-dirs := $(addprefix _clean_, . $(vmlinux-alldirs) Documentation samples)
PHONY += $(clean-dirs) clean archclean vmlinuxclean
$(clean-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
vmlinuxclean:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/link-vmlinux.sh clean
clean: archclean vmlinuxclean
# mrproper - Delete all generated files, including .config
#
mrproper: rm-dirs := $(wildcard $(MRPROPER_DIRS))
mrproper: rm-files := $(wildcard $(MRPROPER_FILES))
mrproper-dirs := $(addprefix _mrproper_,Documentation/DocBook scripts)
PHONY += $(mrproper-dirs) mrproper archmrproper
$(mrproper-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _mrproper_%,%,$@)
mrproper: clean archmrproper $(mrproper-dirs)
$(call cmd,rmdirs)
$(call cmd,rmfiles)
# distclean
#
PHONY += distclean
distclean: mrproper
@find $(srctree) $(RCS_FIND_IGNORE) \
\( -name '*.orig' -o -name '*.rej' -o -name '*~' \
-o -name '*.bak' -o -name '#*#' -o -name '.*.orig' \
-o -name '.*.rej' \
-o -name '*%' -o -name '.*.cmd' -o -name 'core' \) \
-type f -print | xargs rm -f
# Packaging of the kernel to various formats
# ---------------------------------------------------------------------------
# rpm target kept for backward compatibility
package-dir := $(srctree)/scripts/package
%src-pkg: FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
%pkg: include/config/kernel.release FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
rpm: include/config/kernel.release FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
# Brief documentation of the typical targets used
# ---------------------------------------------------------------------------
boards := $(wildcard $(srctree)/arch/$(SRCARCH)/configs/*_defconfig)
boards := $(notdir $(boards))
board-dirs := $(dir $(wildcard $(srctree)/arch/$(SRCARCH)/configs/*/*_defconfig))
board-dirs := $(sort $(notdir $(board-dirs:/=)))
help:
@echo 'Cleaning targets:'
@echo ' clean - Remove most generated files but keep the config and'
@echo ' enough build support to build external modules'
@echo ' mrproper - Remove all generated files + config + various backup files'
@echo ' distclean - mrproper + remove editor backup and patch files'
@echo ''
@echo 'Configuration targets:'
@$(MAKE) -f $(srctree)/scripts/kconfig/Makefile help
@echo ''
@echo 'Other generic targets:'
@echo ' all - Build all targets marked with [*]'
@echo '* vmlinux - Build the bare kernel'
@echo '* modules - Build all modules'
@echo ' modules_install - Install all modules to INSTALL_MOD_PATH (default: /)'
@echo ' firmware_install- Install all firmware to INSTALL_FW_PATH'
@echo ' (default: $$(INSTALL_MOD_PATH)/lib/firmware)'
@echo ' dir/ - Build all files in dir and below'
@echo ' dir/file.[oisS] - Build specified target only'
@echo ' dir/file.lst - Build specified mixed source/assembly target only'
@echo ' (requires a recent binutils and recent build (System.map))'
@echo ' dir/file.ko - Build module including final link'
@echo ' modules_prepare - Set up for building external modules'
@echo ' tags/TAGS - Generate tags file for editors'
@echo ' cscope - Generate cscope index'
@echo ' gtags - Generate GNU GLOBAL index'
@echo ' kernelrelease - Output the release version string'
@echo ' kernelversion - Output the version stored in Makefile'
@echo ' image_name - Output the image name'
@echo ' headers_install - Install sanitised kernel headers to INSTALL_HDR_PATH'; \
echo ' (default: $(INSTALL_HDR_PATH))'; \
echo ''
@echo 'Static analysers'
@echo ' checkstack - Generate a list of stack hogs'
@echo ' namespacecheck - Name space analysis on compiled kernel'
@echo ' versioncheck - Sanity check on version.h usage'
@echo ' includecheck - Check for duplicate included header files'
@echo ' export_report - List the usages of all exported symbols'
@echo ' headers_check - Sanity check on exported headers'
@echo ' headerdep - Detect inclusion cycles in headers'
@$(MAKE) -f $(srctree)/scripts/Makefile.help checker-help
@echo ''
@echo 'Kernel packaging:'
@$(MAKE) $(build)=$(package-dir) help
@echo ''
@echo 'Documentation targets:'
@$(MAKE) -f $(srctree)/Documentation/DocBook/Makefile dochelp
@echo ''
@echo 'Architecture specific targets ($(SRCARCH)):'
@$(if $(archhelp),$(archhelp),\
echo ' No architecture specific help defined for $(SRCARCH)')
@echo ''
@$(if $(boards), \
$(foreach b, $(boards), \
printf " %-24s - Build for %s\\n" $(b) $(subst _defconfig,,$(b));) \
echo '')
@$(if $(board-dirs), \
$(foreach b, $(board-dirs), \
printf " %-16s - Show %s-specific targets\\n" help-$(b) $(b);) \
printf " %-16s - Show all of the above\\n" help-boards; \
echo '')
@echo ' make V=0|1 [targets] 0 => quiet build (default), 1 => verbose build'
@echo ' make V=2 [targets] 2 => give reason for rebuild of target'
@echo ' make O=dir [targets] Locate all output files in "dir", including .config'
@echo ' make C=1 [targets] Check all c source with $$CHECK (sparse by default)'
@echo ' make C=2 [targets] Force check of all c source with $$CHECK'
@echo ' make RECORDMCOUNT_WARN=1 [targets] Warn about ignored mcount sections'
@echo ' make W=n [targets] Enable extra gcc checks, n=1,2,3 where'
@echo ' 1: warnings which may be relevant and do not occur too often'
@echo ' 2: warnings which occur quite often but may still be relevant'
@echo ' 3: more obscure warnings, can most likely be ignored'
@echo ' Multiple levels can be combined with W=12 or W=123'
@echo ''
@echo 'Execute "make" or "make all" to build all targets marked with [*] '
@echo 'For further info see the ./README file'
help-board-dirs := $(addprefix help-,$(board-dirs))
help-boards: $(help-board-dirs)
boards-per-dir = $(notdir $(wildcard $(srctree)/arch/$(SRCARCH)/configs/$*/*_defconfig))
$(help-board-dirs): help-%:
@echo 'Architecture specific targets ($(SRCARCH) $*):'
@$(if $(boards-per-dir), \
$(foreach b, $(boards-per-dir), \
printf " %-24s - Build for %s\\n" $*/$(b) $(subst _defconfig,,$(b));) \
echo '')
# Documentation targets
# ---------------------------------------------------------------------------
%docs: scripts_basic FORCE
$(Q)$(MAKE) $(build)=scripts build_docproc
$(Q)$(MAKE) $(build)=Documentation/DocBook $@
else # KBUILD_EXTMOD
###
# External module support.
# When building external modules the kernel used as basis is considered
# read-only, and no consistency checks are made and the make
# system is not used on the basis kernel. If updates are required
# in the basis kernel ordinary make commands (without M=...) must
# be used.
#
# The following are the only valid targets when building external
# modules.
# make M=dir clean Delete all automatically generated files
# make M=dir modules Make all modules in specified dir
# make M=dir Same as 'make M=dir modules'
# make M=dir modules_install
# Install the modules built in the module directory
# Assumes install directory is already created
# We are always building modules
KBUILD_MODULES := 1
PHONY += crmodverdir
crmodverdir:
$(cmd_crmodverdir)
PHONY += $(objtree)/Module.symvers
$(objtree)/Module.symvers:
@test -e $(objtree)/Module.symvers || ( \
echo; \
echo " WARNING: Symbol version dump $(objtree)/Module.symvers"; \
echo " is missing; modules will have no dependencies and modversions."; \
echo )
module-dirs := $(addprefix _module_,$(KBUILD_EXTMOD))
PHONY += $(module-dirs) modules
$(module-dirs): crmodverdir $(objtree)/Module.symvers
$(Q)$(MAKE) $(build)=$(patsubst _module_%,%,$@)
modules: $(module-dirs)
@$(kecho) ' Building modules, stage 2.';
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
PHONY += modules_install
modules_install: _emodinst_ _emodinst_post
install-dir := $(if $(INSTALL_MOD_DIR),$(INSTALL_MOD_DIR),extra)
PHONY += _emodinst_
_emodinst_:
$(Q)mkdir -p $(MODLIB)/$(install-dir)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modinst
PHONY += _emodinst_post
_emodinst_post: _emodinst_
$(call cmd,depmod)
clean-dirs := $(addprefix _clean_,$(KBUILD_EXTMOD))
PHONY += $(clean-dirs) clean
$(clean-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
clean: rm-dirs := $(MODVERDIR)
clean: rm-files := $(KBUILD_EXTMOD)/Module.symvers
help:
@echo ' Building external modules.'
@echo ' Syntax: make -C path/to/kernel/src M=$$PWD target'
@echo ''
@echo ' modules - default target, build the module(s)'
@echo ' modules_install - install the module'
@echo ' clean - remove generated files in module directory only'
@echo ''
# Dummies...
PHONY += prepare scripts
prepare: ;
scripts: ;
endif # KBUILD_EXTMOD
clean: $(clean-dirs)
$(call cmd,rmdirs)
$(call cmd,rmfiles)
@find $(if $(KBUILD_EXTMOD), $(KBUILD_EXTMOD), .) $(RCS_FIND_IGNORE) \
\( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' \
-o -name '*.ko.*' \
-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \
-o -name '*.symtypes' -o -name 'modules.order' \
-o -name modules.builtin -o -name '.tmp_*.o.*' \
-o -name '*.gcno' \) -type f -print | xargs rm -f
# Generate tags for editors
# ---------------------------------------------------------------------------
quiet_cmd_tags = GEN $@
cmd_tags = $(CONFIG_SHELL) $(srctree)/scripts/tags.sh $@
tags TAGS cscope gtags: FORCE
$(call cmd,tags)
# Scripts to check various things for consistency
# ---------------------------------------------------------------------------
PHONY += includecheck versioncheck coccicheck namespacecheck export_report
includecheck:
find $(srctree)/* $(RCS_FIND_IGNORE) \
-name '*.[hcS]' -type f -print | sort \
| xargs $(PERL) -w $(srctree)/scripts/checkincludes.pl
versioncheck:
find $(srctree)/* $(RCS_FIND_IGNORE) \
-name '*.[hcS]' -type f -print | sort \
| xargs $(PERL) -w $(srctree)/scripts/checkversion.pl
coccicheck:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/$@
namespacecheck:
$(PERL) $(srctree)/scripts/namespace.pl
export_report:
$(PERL) $(srctree)/scripts/export_report.pl
endif #ifeq ($(config-targets),1)
endif #ifeq ($(mixed-targets),1)
PHONY += checkstack kernelrelease kernelversion image_name
# UML needs a little special treatment here. It wants to use the host
# toolchain, so needs $(SUBARCH) passed to checkstack.pl. Everyone
# else wants $(ARCH), including people doing cross-builds, which means
# that $(SUBARCH) doesn't work here.
ifeq ($(ARCH), um)
CHECKSTACK_ARCH := $(SUBARCH)
else
CHECKSTACK_ARCH := $(ARCH)
endif
checkstack:
$(OBJDUMP) -d vmlinux $$(find . -name '*.ko') | \
$(PERL) $(src)/scripts/checkstack.pl $(CHECKSTACK_ARCH)
kernelrelease:
@echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"
kernelversion:
@echo $(KERNELVERSION)
image_name:
@echo $(KBUILD_IMAGE)
# Clear a bunch of variables before executing the submake
tools/: FORCE
$(Q)mkdir -p $(objtree)/tools
$(Q)$(MAKE) LDFLAGS= MAKEFLAGS="$(filter --j% -j,$(MAKEFLAGS))" O=$(objtree) subdir=tools -C $(src)/tools/
tools/%: FORCE
$(Q)mkdir -p $(objtree)/tools
$(Q)$(MAKE) LDFLAGS= MAKEFLAGS="$(filter --j% -j,$(MAKEFLAGS))" O=$(objtree) subdir=tools -C $(src)/tools/ $*
# Single targets
# ---------------------------------------------------------------------------
# Single targets are compatible with:
# - build with mixed source and output
# - build with separate output dir 'make O=...'
# - external modules
#
# target-dir => where to store outputfile
# build-dir => directory in kernel source tree to use
ifeq ($(KBUILD_EXTMOD),)
build-dir = $(patsubst %/,%,$(dir $@))
target-dir = $(dir $@)
else
zap-slash=$(filter-out .,$(patsubst %/,%,$(dir $@)))
build-dir = $(KBUILD_EXTMOD)$(if $(zap-slash),/$(zap-slash))
target-dir = $(if $(KBUILD_EXTMOD),$(dir $<),$(dir $@))
endif
%.s: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.i: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.o: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.lst: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.s: %.S prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.o: %.S prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.symtypes: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
# Modules
/: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir)
%/: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir)
%.ko: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir) $(@:.ko=.o)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
# FIXME Should go into a make.lib or something
# ===========================================================================
quiet_cmd_rmdirs = $(if $(wildcard $(rm-dirs)),CLEAN $(wildcard $(rm-dirs)))
cmd_rmdirs = rm -rf $(rm-dirs)
quiet_cmd_rmfiles = $(if $(wildcard $(rm-files)),CLEAN $(wildcard $(rm-files)))
cmd_rmfiles = rm -f $(rm-files)
# Run depmod only if we have System.map and depmod is executable
quiet_cmd_depmod = DEPMOD $(KERNELRELEASE)
cmd_depmod = $(CONFIG_SHELL) $(srctree)/scripts/depmod.sh $(DEPMOD) \
$(KERNELRELEASE) "$(patsubst y,_,$(CONFIG_HAVE_UNDERSCORE_SYMBOL_PREFIX))"
# Create temporary dir for module support files
# clean it up only when building all modules
cmd_crmodverdir = $(Q)mkdir -p $(MODVERDIR) \
$(if $(KBUILD_MODULES),; rm -f $(MODVERDIR)/*)
# read all saved command lines
targets := $(wildcard $(sort $(targets)))
cmd_files := $(wildcard .*.cmd $(foreach f,$(targets),$(dir $(f)).$(notdir $(f)).cmd))
ifneq ($(cmd_files),)
$(cmd_files): ; # Do not try to update included dependency files
include $(cmd_files)
endif
# Shorthand for $(Q)$(MAKE) -f scripts/Makefile.clean obj=dir
# Usage:
# $(Q)$(MAKE) $(clean)=dir
clean := -f $(if $(KBUILD_SRC),$(srctree)/)scripts/Makefile.clean obj
endif # skip-makefile
PHONY += FORCE
FORCE:
# Declare the contents of the .PHONY variable as phony. We keep that
# information in a variable so we can use it in if_changed and friends.
.PHONY: $(PHONY)
|
MichaelQQ/Linux_PE
|
Makefile
|
Makefile
|
gpl-2.0
| 49,452
|
require_dependency 'user_destroyer'
require_dependency 'admin_user_index_query'
class Admin::UsersController < Admin::AdminController
before_filter :fetch_user, only: [:suspend,
:unsuspend,
:refresh_browsers,
:log_out,
:revoke_admin,
:grant_admin,
:revoke_moderation,
:grant_moderation,
:approve,
:activate,
:deactivate,
:block,
:unblock,
:trust_level,
:primary_group,
:generate_api_key,
:revoke_api_key]
def index
query = ::AdminUserIndexQuery.new(params)
render_serialized(query.find_users, AdminUserSerializer)
end
def show
@user = User.find_by(username_lower: params[:id])
raise Discourse::NotFound.new unless @user
render_serialized(@user, AdminDetailedUserSerializer, root: false)
end
def delete_all_posts
@user = User.find_by(id: params[:user_id])
@user.delete_all_posts!(guardian)
render nothing: true
end
def suspend
guardian.ensure_can_suspend!(@user)
@user.suspended_till = params[:duration].to_i.days.from_now
@user.suspended_at = DateTime.now
@user.save!
StaffActionLogger.new(current_user).log_user_suspend(@user, params[:reason])
render nothing: true
end
def unsuspend
guardian.ensure_can_suspend!(@user)
@user.suspended_till = nil
@user.suspended_at = nil
@user.save!
StaffActionLogger.new(current_user).log_user_unsuspend(@user)
render nothing: true
end
def log_out
@user.auth_token = nil
@user.save!
render nothing: true
end
def refresh_browsers
refresh_browser @user
render nothing: true
end
def revoke_admin
guardian.ensure_can_revoke_admin!(@user)
@user.revoke_admin!
render nothing: true
end
def generate_api_key
api_key = @user.generate_api_key(current_user)
render_serialized(api_key, ApiKeySerializer)
end
def revoke_api_key
@user.revoke_api_key
render nothing: true
end
def grant_admin
guardian.ensure_can_grant_admin!(@user)
@user.grant_admin!
render_serialized(@user, AdminUserSerializer)
end
def revoke_moderation
guardian.ensure_can_revoke_moderation!(@user)
@user.revoke_moderation!
render nothing: true
end
def grant_moderation
guardian.ensure_can_grant_moderation!(@user)
@user.grant_moderation!
render_serialized(@user, AdminUserSerializer)
end
def primary_group
guardian.ensure_can_change_primary_group!(@user)
@user.primary_group_id = params[:primary_group_id]
@user.save!
render nothing: true
end
def trust_level
guardian.ensure_can_change_trust_level!(@user)
level = TrustLevel.levels[params[:level].to_i]
@user.change_trust_level!(level, log_action_for: current_user)
render_serialized(@user, AdminUserSerializer)
end
def approve
guardian.ensure_can_approve!(@user)
@user.approve(current_user)
render nothing: true
end
def approve_bulk
User.where(id: params[:users]).each do |u|
u.approve(current_user) if guardian.can_approve?(u)
end
render nothing: true
end
def activate
guardian.ensure_can_activate!(@user)
@user.activate
render nothing: true
end
def deactivate
guardian.ensure_can_deactivate!(@user)
@user.deactivate
refresh_browser @user
render nothing: true
end
def block
guardian.ensure_can_block_user! @user
UserBlocker.block(@user, current_user)
render nothing: true
end
def unblock
guardian.ensure_can_unblock_user! @user
UserBlocker.unblock(@user, current_user)
render nothing: true
end
def reject_bulk
d = UserDestroyer.new(current_user)
success_count = 0
User.where(id: params[:users]).each do |u|
success_count += 1 if guardian.can_delete_user?(u) and d.destroy(u, params.slice(:context)) rescue UserDestroyer::PostsExistError
end
render json: {success: success_count, failed: (params[:users].try(:size) || 0) - success_count}
end
def destroy
user = User.find_by(id: params[:id])
guardian.ensure_can_delete_user!(user)
begin
if UserDestroyer.new(current_user).destroy(user, params.slice(:delete_posts, :block_email, :block_urls, :block_ip, :context))
render json: {deleted: true}
else
render json: {deleted: false, user: AdminDetailedUserSerializer.new(user, root: false).as_json}
end
rescue UserDestroyer::PostsExistError
raise Discourse::InvalidAccess.new("User #{user.username} has #{user.post_count} posts, so can't be deleted.")
end
end
def badges
end
def leader_requirements
end
private
def fetch_user
@user = User.find_by(id: params[:user_id])
end
def refresh_browser(user)
MessageBus.publish "/file-change", ["refresh"], user_ids: [user.id]
end
end
|
vipuldadhich/discourse
|
app/controllers/admin/users_controller.rb
|
Ruby
|
gpl-2.0
| 5,315
|
/*
* pxa2xx_udc_gpio.c: Generic driver for GPIO-controlled PXA2xx UDC.
*
* */
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dpm.h>
#include <asm/arch/udc.h>
#include <asm/arch/pxa2xx_udc_gpio.h>
static struct pxa2xx_udc_gpio_info *pdata;
static void pda_udc_command(int cmd)
{
switch (cmd) {
case PXA2XX_UDC_CMD_DISCONNECT:
DPM_DEBUG("pda_udc: Turning off port\n");
dpm_power(&pdata->power_ctrl, 0);
break;
case PXA2XX_UDC_CMD_CONNECT:
DPM_DEBUG("pda_udc: Turning on port\n");
dpm_power(&pdata->power_ctrl, 1);
break;
default:
printk("pda_udc: unknown command!\n");
break;
}
}
static int pda_udc_is_connected(void)
{
int status = !!gpiodev_get_value(&pdata->detect_gpio) ^ pdata->detect_gpio_negative;
return status;
}
static struct pxa2xx_udc_mach_info pda_udc_info __initdata = {
.udc_is_connected = pda_udc_is_connected,
.udc_command = pda_udc_command,
};
static int pda_udc_probe(struct platform_device * pdev)
{
printk("pxa2xx-udc-gpio: Generic driver for GPIO-controlled PXA2xx UDC\n");
pdata = pdev->dev.platform_data;
pxa_set_udc_info(&pda_udc_info);
return 0;
}
static struct platform_driver pda_udc_driver = {
.driver = {
.name = "pxa2xx-udc-gpio",
},
.probe = pda_udc_probe,
};
static int __init pda_udc_init(void)
{
return platform_driver_register(&pda_udc_driver);
}
#ifdef MODULE
module_init(pda_udc_init);
#else /* start early for dependencies */
fs_initcall(pda_udc_init);
#endif
MODULE_AUTHOR("Paul Sokolovsky <pmiscml@gmail.com>");
MODULE_DESCRIPTION("Generic driver for GPIO-controlled PXA2xx UDC");
MODULE_LICENSE("GPL");
|
janrinze/loox7xxport.loox2-6-22
|
drivers/usb/gadget/pxa2xx_udc_gpio.c
|
C
|
gpl-2.0
| 1,679
|
<?php
/**
Extends the SimplePie library.
*
* @package Fetch Tweets
* @copyright Copyright (c) 2013, Michael Uno
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 1.0.0
*/
/*
* Custom Hooks
* - fetch_tweets_action_simplepie_renew_cache : the event action that renew caches in the background.
* - SimplePie_filter_cache_transient_lifetime_{FileID} : applies to cache transients. FileID is md5( $url ).
*
* Global Variables
* - $arrSimplePieCacheModTimestamps : stores mod timestamps of cached data. This will be stored in a transient when WordPress exits,
* which prevents multiple calls of get_transiet() that performs a database query ( slows down the page load ).
* - $arrSimplePieCacheExpiredItems : stores expired cache items' file IDs ( md5( $url ) ). This will be saved in the transient at the WordPress shutdown action event.
* the separate cache renewal event with WP Cron will read it and renew the expired caches.
*
* */
// Make sure that SimplePie has been already loaded. This is very important. Without this line, the cache setting breaks.
// Do not include class-simplepie.php, which causes the unknown class warning.
if ( ! class_exists( 'SimplePie' ) ) include_once( ABSPATH . WPINC . '/class-feed.php' );
// If the WordPress version is below 3.5, which uses SimplePie below 1.3,
if ( version_compare( get_bloginfo( 'version' ) , '3.5', "<" ) ) {
class FetchTweets_SimplePie__ extends SimplePie {
public static $sortorder = 'random';
public function sort_items( $a, $b ) {
// Sort
// by date
if ( self::$sortorder == 'date' )
return $a->get_date( 'U' ) <= $b->get_date( 'U' );
// by title ascending
if ( self::$sortorder == 'title' )
return self::sort_items_by_title( $a, $b );
// by title decending
if ( self::$sortorder == 'title_descending' )
return self::sort_items_by_title_descending( $a, $b );
// by random
return rand( -1, 1 );
}
}
} else {
class FetchTweets_SimplePie__ extends SimplePie {
public static $sortorder = 'random';
public static function sort_items( $a, $b ) {
// Sort
// by date
if ( self::$sortorder == 'date' )
return $a->get_date( 'U' ) <= $b->get_date( 'U' );
// by title ascending
if ( self::$sortorder == 'title' )
return self::sort_items_by_title( $a, $b );
// by title decending
if ( self::$sortorder == 'title_descending' )
return self::sort_items_by_title_descending( $a, $b );
// by random
return rand( -1, 1 );
}
}
}
class FetchTweets_SimplePie extends FetchTweets_SimplePie__ {
public static $sortorder = 'random';
public static $bKeepRawTitle = false;
public static $strCharEncoding = 'UTF-8';
var $vSetURL; // stores the feed url(s) set by the user.
var $fIsBackgroundProcess = false; // indicates whether it is from the event action ( background call )
var $numCacheLifetimeExpand = 100;
protected $strPluginKey = 'FTWSFeedMs';
public function __construct() {
// Set up the global arrays. Consider the cases that multiple instances of this object are created so the arrays may have been already created.
// - This stores real mod timestamps.
$GLOBALS['arrSimplePieCacheModTimestamps'] = isset( $GLOBALS['arrSimplePieCacheModTimestamps'] ) && is_array( $GLOBALS['arrSimplePieCacheModTimestamps'] ) ? $GLOBALS['arrSimplePieCacheModTimestamps'] : array();
$GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ] = isset( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ] ) && is_array( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ] )
? $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ]
: ( array ) get_transient( $this->strPluginKey ) ;
// - this stores expired cache items.
$GLOBALS['arrSimplePieCacheExpiredItems'] = isset( $GLOBALS['arrSimplePieCacheExpiredItems'] ) && is_array( $GLOBALS['arrSimplePieCacheExpiredItems'] ) ? $GLOBALS['arrSimplePieCacheExpiredItems'] : array();
$GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] = isset( $GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] ) && is_array( $GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] ) ? $GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] : array();
// Schedule the transient update task.
add_action( 'shutdown', array( $this, 'updateCacheItems' ) );
parent::__construct();
}
public function updateCacheItems() {
// Saves the global array, $arrSimplePieCacheModTimestamps, into the transient of the option table.
// This is used to avoid multiple calls of set_transient() by the cache class.
if ( ! ( isset( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ]['bIsCacheTransientSet'] ) && $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ]['bIsCacheTransientSet'] ) ) {
unset( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ]['bIsCacheTransientSet'] ); // remove the unnecessary data.
set_transient( $this->strPluginKey, $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ], $this->cache_duration * $this->numCacheLifetimeExpand );
$GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ]['bIsCacheTransientSet'] = true;
}
$GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] = array_unique( $GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] );
if ( count( $GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] ) > 0 )
$this->scheduleCacheRenewal( $GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ] );
}
protected function scheduleCacheRenewal( $arrURLs ) {
// Schedules the action to run in the background with WP Cron.
if ( wp_next_scheduled( 'fetch_tweets_action_simplepie_renew_cache', array( $arrURLs ) ) ) return;
wp_schedule_single_event( time() , 'fetch_tweets_action_simplepie_renew_cache', array( $arrURLs ) );
}
public function setCacheTransientLifetime( $intLifespan, $strFileID=null ) {
// This is a callback for the filter that sets cache duration for the SimplePie cache object.
return isset( $this->cache_duration ) ? $this->cache_duration : 0;
}
public function setCacheTransientLifetimeByGlobalKey( $intLifespan, $strKey=null ) {
// This is a callback for the filter that sets cache duration for the SimplePie cache object.
// If the key is not the one set by this class, it could be some other script's ( plugin's ) filtering item.
if ( $strKey != $this->strPluginKey ) return $intLifespan;
return isset( $this->cache_duration ) ? $this->cache_duration : 0;
}
/*
* For background cache renewal task.
* */
public function set_feed_url( $vURL ) {
$this->vSetURL = $vURL; // array or string
// Hook the cache lifetime filter
foreach( ( array ) $vURL as $strURL )
add_filter( 'SimplePie_filter_cache_transient_lifetime_' . md5( $strURL ), array( $this, 'setCacheTransientLifetime' ) );
add_filter( 'SimplePie_filter_cache_transient_lifetime_' . $this->strPluginKey, array( $this, 'setCacheTransientLifetimeByGlobalKey' ) );
return parent::set_feed_url( $vURL );
}
public function init() {
// Setup Caches
$this->enable_cache( true );
// force the cache class to the custom plugin cache class
$this->set_cache_class( 'FetchTweets_Cache' );
$this->set_file_class( 'WP_SimplePie_File' );
if ( isset( $this->vSetURL ) && ! $this->fIsBackgroundProcess ) {
foreach ( ( array) $this->vSetURL as $strURL ) {
$strFileID = md5( $strURL );
$intModTimestamp = isset( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ][ $strFileID ] ) ? $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ][ $strFileID ] : 0;
if ( $intModTimestamp + $this->cache_duration < time() )
$GLOBALS['arrSimplePieCacheExpiredItems'][ $this->strPluginKey ][] = $strURL;
}
}
return parent::init();
}
public function setBackground( $fIsBackgroundProcess=false ) {
$this->fIsBackgroundProcess = $fIsBackgroundProcess;
}
/*
* For sort
* */
public function set_sortorder( $sortorder ) {
self::$sortorder = $sortorder;
}
public function set_keeprawtitle( $bKeepRawTitle ) {
self::$bKeepRawTitle = $bKeepRawTitle;
}
public function set_charset_for_sort( $strCharEncoding ) {
self::$strCharEncoding = $strCharEncoding;
}
public static function sort_items_by_title( $a, $b ) {
$a_title = ( self::$bKeepRawTitle ) ? $a->get_title() : preg_replace('/#\d+?:\s?/i', '', $a->get_title());
$b_title = ( self::$bKeepRawTitle ) ? $b->get_title() : preg_replace('/#\d+?:\s?/i', '', $b->get_title());
$a_title = html_entity_decode( trim( strip_tags( $a_title ) ), ENT_COMPAT | ENT_HTML401, self::$strCharEncoding );
$b_title = html_entity_decode( trim( strip_tags( $b_title ) ), ENT_COMPAT | ENT_HTML401, self::$strCharEncoding );
return strnatcasecmp( $a_title, $b_title );
}
public static function sort_items_by_title_descending( $a, $b ) {
$a_title = ( self::$bKeepRawTitle ) ? $a->get_title() : preg_replace('/#\d+?:\s?/i', '', $a->get_title());
$b_title = ( self::$bKeepRawTitle ) ? $b->get_title() : preg_replace('/#\d+?:\s?/i', '', $b->get_title());
$a_title = html_entity_decode( trim( strip_tags( $a_title ) ), ENT_COMPAT | ENT_HTML402, self::$strCharEncoding );
$b_title = html_entity_decode( trim( strip_tags( $b_title ) ), ENT_COMPAT | ENT_HTML402, self::$strCharEncoding );
return strnatcasecmp( $b_title, $a_title );
}
function set_force_cache_class( $class = 'FetchTweets_Cache' ) {
$this->cache_class = $class;
}
function set_force_file_class( $class = 'SimplePie_File' ) {
$this->file_class = $class;
}
}
class FetchTweets_Cache extends SimplePie_Cache {
/**
* Create a new SimplePie_Cache object
*
* @static
* @access public
*/
function create( $location, $filename, $extension ) {
return new FetchTweets_Feed_Cache_Transient( $location, $filename, $extension );
}
}
class FetchTweets_Feed_Cache_Transient {
var $strTransientName;
var $iLifetime = 43200; // Default cache lifetime of 12 hours. This should be overridden by the filter callback function.
var $numExpand = 100;
var $strPluginKey = 'FTWSFeedMs';
protected $strFileID; // stores the file name given to the constructor.
public function __construct( $location, $strFileID, $extension ) {
/*
* Parameters:
* - $location ( not used in this class ) : './cache'
* - $strFileID : md5( $url ) e.g. b22d9dad80577a8e66a230777d91cc6e // <-- the hash type may be changed by the user.
* - $extension ( not used in this class ) : spc
*/
// $strFileID should not be empty but I've seen a case that happened with v3.4.x or below.
$this->strFileID = empty( $strFileID ) ? $this->strPluginKey . '_a_file' : $strFileID;
$this->strTransientName = $this->strPluginKey . '_' . $this->strFileID;
$this->iLifetime = apply_filters(
'SimplePie_filter_cache_transient_lifetime_' . $this->strFileID,
$this->iLifetime, // it barely expires by itself
$this->strFileID
);
}
public function save( $data ) {
if ( is_a( $data, 'SimplePie' ) )
$data = $data->data;
// $GLOBALS['arrSimplePieCacheModTimestamps'] should be already created by the caller (parent) custom SimplePie class.
$GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ][ $this->strFileID ] = time();
// make it 100 times longer so that it barely gets expires by itself
set_transient( $this->strTransientName, $data, $this->iLifetime * $this->numExpand );
return true;
}
public function load() {
// If this returns an empty value, SimplePie will fetch the feed.
if ( $this->iLifetime == 0 ) return null;
return get_transient( $this->strTransientName ); // the stored cache data
}
public function mtime() {
// Here we are going to deceive SimplePie in order to force it to use the remaining cache and renew the cache in the background, not doing it right away.
return isset( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ][ $this->strFileID ] )
? time() // return the current time so that SimplePie believes it's not expired yet.
: 0; // if the array key is not set, So pass 0 to tell that the cache needs to be created.
}
public function touch() {
$GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ][ $this->strFileID ] = time();
return true;
}
public function unlink() {
unset( $GLOBALS['arrSimplePieCacheModTimestamps'][ $this->strPluginKey ][ $this->strFileID ] );
delete_transient( $this->strTransientName );
return true;
}
}
|
rodrigocollavo/wordpress-mytweets
|
wp-content/plugins/fetch-tweets/include/class/backend/FetchTweets_SimplePie.php
|
PHP
|
gpl-2.0
| 13,052
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Jul 28 10:40:40 BST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class net.sf.sparql.benchmarking.operations.query.DatasetSizeOperation (SPARQL Query Benchmarker - Core API 2.0.1 API)</title>
<meta name="date" content="2014-07-28">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sf.sparql.benchmarking.operations.query.DatasetSizeOperation (SPARQL Query Benchmarker - Core API 2.0.1 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../net/sf/sparql/benchmarking/operations/query/DatasetSizeOperation.html" title="class in net.sf.sparql.benchmarking.operations.query">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sf/sparql/benchmarking/operations/query/class-use/DatasetSizeOperation.html" target="_top">Frames</a></li>
<li><a href="DatasetSizeOperation.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class net.sf.sparql.benchmarking.operations.query.DatasetSizeOperation" class="title">Uses of Class<br>net.sf.sparql.benchmarking.operations.query.DatasetSizeOperation</h2>
</div>
<div class="classUseContainer">No usage of net.sf.sparql.benchmarking.operations.query.DatasetSizeOperation</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../net/sf/sparql/benchmarking/operations/query/DatasetSizeOperation.html" title="class in net.sf.sparql.benchmarking.operations.query">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sf/sparql/benchmarking/operations/query/class-use/DatasetSizeOperation.html" target="_top">Frames</a></li>
<li><a href="DatasetSizeOperation.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014. All Rights Reserved.</small></p>
</body>
</html>
|
mielvds/distributed-tests
|
benchmark/single_endpoint/config_direct/sparql-query-bm-2.0.1/api/apidocs/net/sf/sparql/benchmarking/operations/query/class-use/DatasetSizeOperation.html
|
HTML
|
gpl-2.0
| 4,768
|
/*
* 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 net.rptools.lib.swing.preference;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.prefs.Preferences;
import net.rptools.lib.swing.TaskPanel;
import net.rptools.lib.swing.TaskPanelGroup;
public class TaskPanelGroupPreferences implements PropertyChangeListener {
private TaskPanelGroup group;
private Preferences prefs;
private boolean restoringState; // I don't like this, rethink it later.
private static final String PREF_KEY = "state_list";
public TaskPanelGroupPreferences(String appName, String controlName, TaskPanelGroup group) {
this.group = group;
prefs = Preferences.userRoot().node(appName + "/control/" + controlName);
restoreTaskPanelStates();
connect();
}
protected void connect() {
for (TaskPanel taskPanel : group.getTaskPanels()) {
connectToTaskPanel(taskPanel);
}
// Make sure to get all future task panels
group.addPropertyChangeListener(TaskPanelGroup.TASK_PANEL_LIST, this);
}
private void connectToTaskPanel(TaskPanel taskPanel) {
taskPanel.addPropertyChangeListener(TaskPanel.TASK_PANEL_STATE, this);
}
public void disconnect() {
group.removePropertyChangeListener(TaskPanelGroup.TASK_PANEL_LIST, this);
for (TaskPanel taskPanel : group.getTaskPanels()) {
disconnectFromTaskPanel(taskPanel);
}
group = null;
prefs = null;
}
private void disconnectFromTaskPanel(TaskPanel taskPanel) {
taskPanel.removePropertyChangeListener(TaskPanel.TASK_PANEL_STATE, this);
}
private void saveTaskPanelStates() {
List<String> stateList = new ArrayList<String>();
for (TaskPanel taskPanel : group.getTaskPanels()) {
stateList.add(taskPanel.getTitle());
stateList.add(taskPanel.getState().name());
}
saveStates(stateList);
}
private void restoreTaskPanelState(TaskPanel taskPanel) {
List<String> states = loadStates();
try {
restoringState = true;
for (Iterator<String> iter = states.iterator(); iter.hasNext();) {
String title = iter.next();
String state = iter.next();
if (taskPanel.getTitle().equals(title)) {
taskPanel.setState(TaskPanel.State.valueOf(state));
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
restoringState = false;
}
}
private void restoreTaskPanelStates() {
List<String> states = loadStates();
try {
restoringState = true;
for (Iterator<String> iter = states.iterator(); iter.hasNext();) {
String title = iter.next();
String state = iter.next();
TaskPanel taskPanel = group.getTaskPanel(title);
if (taskPanel == null) {
continue;
}
taskPanel.setState(TaskPanel.State.valueOf(state));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
restoringState = false;
}
}
private List<String> loadStates() {
String stateList = prefs.get(PREF_KEY, null);
if (stateList == null) {
return new ArrayList<String>();
}
String[] states = stateList.split("\\|");
return Arrays.asList(states);
}
private void saveStates(List<String> stateList) {
StringBuilder builder = new StringBuilder();
for (Iterator<String> iter = stateList.iterator(); iter.hasNext();) {
builder.append(iter.next()).append("|").append(iter.next());
if (iter.hasNext()) {
builder.append("|");
}
}
prefs.put(PREF_KEY, builder.toString());
}
////
// PROPERTY CHANGE LISTENER
public void propertyChange(PropertyChangeEvent evt) {
if (restoringState) {
return;
}
if (TaskPanelGroup.TASK_PANEL_LIST.equals(evt.getPropertyName())) {
TaskPanel taskPanel = (TaskPanel) evt.getNewValue();
connectToTaskPanel(taskPanel);
restoreTaskPanelState(taskPanel);
} else {
saveTaskPanelStates();
}
}
}
|
RPTools/rplib
|
src/main/java/net/rptools/lib/swing/preference/TaskPanelGroupPreferences.java
|
Java
|
gpl-2.0
| 4,400
|
var source= ('http://www.google.com/uds/api?file=uds.js&v=1.0&source=uds-vbw');
document.write ("<scr"+"ipt type='text/javascript' src='"+source);
document.write ("'><\/scr"+"ipt>");
|
ramsalt/kr
|
sites/all/modules/morelikethis/contrib/morelikethis_googlevideo/api.js
|
JavaScript
|
gpl-2.0
| 183
|
#! /usr/bin/env python
#
# test_errors.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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.
#
# NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
"""
Tests for error handling
"""
import unittest
import nest
import sys
class ErrorTestCase(unittest.TestCase):
"""Tests if errors are handled correctly"""
def test_Raise(self):
"""Error raising"""
nest.ResetKernel()
try:
raise nest.NESTError('test')
self.fail('an error should have risen!') # should not be reached
except nest.NESTError:
info = sys.exc_info()[1]
if not "test" in info.__str__():
self.fail('could not pass error message to NEST!')
# another error has been thrown, this is wrong
except:
self.fail('wrong error has been thrown')
def test_StackUnderFlow(self):
"""Stack underflow"""
nest.ResetKernel()
try:
nest.sr('clear ;')
self.fail('an error should have risen!') # should not be reached
except nest.NESTError:
info = sys.exc_info()[1]
if not "StackUnderflow" in info.__str__():
self.fail('wrong error message')
# another error has been thrown, this is wrong
except:
self.fail('wrong error has been thrown')
def test_DivisionByZero(self):
"""Division by zero"""
nest.ResetKernel()
try:
nest.sr('1 0 div')
self.fail('an error should have risen!') # should not be reached
except nest.NESTError:
info = sys.exc_info()[1]
if not "DivisionByZero" in info.__str__():
self.fail('wrong error message')
# another error has been thrown, this is wrong
except:
self.fail('wrong error has been thrown')
def test_UnknownNode(self):
"""Unknown node"""
nest.ResetKernel()
try:
nest.Connect([99],[99])
self.fail('an error should have risen!') # should not be reached
except nest.NESTError:
info = sys.exc_info()[1]
if not "UnknownNode" in info.__str__():
self.fail('wrong error message')
# another error has been thrown, this is wrong
except:
self.fail('wrong error has been thrown')
def test_UnknownModel(self):
"""Unknown model name"""
nest.ResetKernel()
try:
nest.Create(-1)
self.fail('an error should have risen!') # should not be reached
except nest.NESTError:
info = sys.exc_info()[1]
if not "UnknownModelName" in info.__str__():
self.fail('wrong error message')
# another error has been thrown, this is wrong
except:
self.fail('wrong error has been thrown')
def suite():
suite = unittest.makeSuite(ErrorTestCase,'test')
return suite
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())
|
gewaltig/cython-neuron
|
pynest/nest/tests/test_errors.py
|
Python
|
gpl-2.0
| 3,727
|
/* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/bootmem.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_memtypes.h>
#include <mach/board.h>
#include <mach/gpiomux.h>
#include <mach/socinfo.h>
#include <linux/msm_ion.h>
#include <mach/ion.h>
#include "devices.h"
#include "board-8930.h"
#ifdef CONFIG_FB_MSM_TRIPLE_BUFFER
#define MSM_FB_PRIM_BUF_SIZE \
(roundup((1920 * 1088 * 4), 4096) * 3) /* 4 bpp x 3 pages */
#else
#define MSM_FB_PRIM_BUF_SIZE \
(roundup((1920 * 1088 * 4), 4096) * 2) /* 4 bpp x 2 pages */
#endif
/* Note: must be multiple of 4096 */
#define MSM_FB_SIZE roundup(MSM_FB_PRIM_BUF_SIZE, 4096)
#ifdef CONFIG_FB_MSM_OVERLAY0_WRITEBACK
#define MSM_FB_OVERLAY0_WRITEBACK_SIZE roundup((1376 * 768 * 3 * 2), 4096)
#else
#define MSM_FB_OVERLAY0_WRITEBACK_SIZE (0)
#endif /* CONFIG_FB_MSM_OVERLAY0_WRITEBACK */
#ifdef CONFIG_FB_MSM_OVERLAY1_WRITEBACK
#define MSM_FB_OVERLAY1_WRITEBACK_SIZE roundup((1920 * 1088 * 3 * 2), 4096)
#else
#define MSM_FB_OVERLAY1_WRITEBACK_SIZE (0)
#endif /* CONFIG_FB_MSM_OVERLAY1_WRITEBACK */
#define MDP_VSYNC_GPIO 0
#define MIPI_CMD_NOVATEK_QHD_PANEL_NAME "mipi_cmd_novatek_qhd"
#define MIPI_VIDEO_NOVATEK_QHD_PANEL_NAME "mipi_video_novatek_qhd"
#define MIPI_VIDEO_TOSHIBA_WSVGA_PANEL_NAME "mipi_video_toshiba_wsvga"
#define MIPI_VIDEO_CHIMEI_WXGA_PANEL_NAME "mipi_video_chimei_wxga"
#define MIPI_VIDEO_SIMULATOR_VGA_PANEL_NAME "mipi_video_simulator_vga"
#define MIPI_CMD_RENESAS_FWVGA_PANEL_NAME "mipi_cmd_renesas_fwvga"
#define HDMI_PANEL_NAME "hdmi_msm"
#define TVOUT_PANEL_NAME "tvout_msm"
static struct resource msm_fb_resources[] = {
{
.flags = IORESOURCE_DMA,
}
};
static int msm_fb_detect_panel(const char *name)
{
if (!strncmp(name, MIPI_CMD_NOVATEK_QHD_PANEL_NAME,
strnlen(MIPI_CMD_NOVATEK_QHD_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
#if !defined(CONFIG_FB_MSM_LVDS_MIPI_PANEL_DETECT) && \
!defined(CONFIG_FB_MSM_MIPI_PANEL_DETECT)
if (!strncmp(name, MIPI_VIDEO_NOVATEK_QHD_PANEL_NAME,
strnlen(MIPI_VIDEO_NOVATEK_QHD_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
if (!strncmp(name, MIPI_VIDEO_TOSHIBA_WSVGA_PANEL_NAME,
strnlen(MIPI_VIDEO_TOSHIBA_WSVGA_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
if (!strncmp(name, MIPI_VIDEO_SIMULATOR_VGA_PANEL_NAME,
strnlen(MIPI_VIDEO_SIMULATOR_VGA_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
if (!strncmp(name, MIPI_CMD_RENESAS_FWVGA_PANEL_NAME,
strnlen(MIPI_CMD_RENESAS_FWVGA_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
#endif
if (!strncmp(name, HDMI_PANEL_NAME,
strnlen(HDMI_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
if (!strncmp(name, TVOUT_PANEL_NAME,
strnlen(TVOUT_PANEL_NAME,
PANEL_NAME_MAX_LEN)))
return 0;
pr_warning("%s: not supported '%s'", __func__, name);
return -ENODEV;
}
static struct msm_fb_platform_data msm_fb_pdata = {
.detect_client = msm_fb_detect_panel,
};
static struct platform_device msm_fb_device = {
.name = "msm_fb",
.id = 0,
.num_resources = ARRAY_SIZE(msm_fb_resources),
.resource = msm_fb_resources,
.dev.platform_data = &msm_fb_pdata,
};
static bool dsi_power_on;
/*
* TODO: When physical 8930/PM8038 hardware becomes
* available, replace mipi_dsi_cdp_panel_power with
* appropriate function.
*/
#define DISP_RST_GPIO 58
static int mipi_dsi_cdp_panel_power(int on)
{
static struct regulator *reg_l8, *reg_l23, *reg_l2;
int rc;
pr_debug("%s: state : %d\n", __func__, on);
if (!dsi_power_on) {
reg_l8 = regulator_get(&msm_mipi_dsi1_device.dev,
"dsi_vdc");
if (IS_ERR(reg_l8)) {
pr_err("could not get 8038_l8, rc = %ld\n",
PTR_ERR(reg_l8));
return -ENODEV;
}
reg_l23 = regulator_get(&msm_mipi_dsi1_device.dev,
"dsi_vddio");
if (IS_ERR(reg_l23)) {
pr_err("could not get 8038_l23, rc = %ld\n",
PTR_ERR(reg_l23));
return -ENODEV;
}
reg_l2 = regulator_get(&msm_mipi_dsi1_device.dev,
"dsi_vdda");
if (IS_ERR(reg_l2)) {
pr_err("could not get 8038_l2, rc = %ld\n",
PTR_ERR(reg_l2));
return -ENODEV;
}
rc = regulator_set_voltage(reg_l8, 2800000, 3000000);
if (rc) {
pr_err("set_voltage l8 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_set_voltage(reg_l23, 1800000, 1800000);
if (rc) {
pr_err("set_voltage l23 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_set_voltage(reg_l2, 1200000, 1200000);
if (rc) {
pr_err("set_voltage l2 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = gpio_request(DISP_RST_GPIO, "disp_rst_n");
if (rc) {
pr_err("request gpio DISP_RST_GPIO failed, rc=%d\n",
rc);
gpio_free(DISP_RST_GPIO);
return -ENODEV;
}
dsi_power_on = true;
}
if (on) {
rc = regulator_set_optimum_mode(reg_l8, 100000);
if (rc < 0) {
pr_err("set_optimum_mode l8 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_set_optimum_mode(reg_l23, 100000);
if (rc < 0) {
pr_err("set_optimum_mode l23 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_set_optimum_mode(reg_l2, 100000);
if (rc < 0) {
pr_err("set_optimum_mode l2 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_enable(reg_l8);
if (rc) {
pr_err("enable l8 failed, rc=%d\n", rc);
return -ENODEV;
}
rc = regulator_enable(reg_l23);
if (rc) {
pr_err("enable l8 failed, rc=%d\n", rc);
return -ENODEV;
}
rc = regulator_enable(reg_l2);
if (rc) {
pr_err("enable l2 failed, rc=%d\n", rc);
return -ENODEV;
}
usleep(10000);
gpio_set_value(DISP_RST_GPIO, 1);
usleep(10);
gpio_set_value(DISP_RST_GPIO, 0);
usleep(20);
gpio_set_value(DISP_RST_GPIO, 1);
} else {
gpio_set_value(DISP_RST_GPIO, 0);
rc = regulator_disable(reg_l2);
if (rc) {
pr_err("disable reg_l2 failed, rc=%d\n", rc);
return -ENODEV;
}
rc = regulator_disable(reg_l8);
if (rc) {
pr_err("disable reg_l8 failed, rc=%d\n", rc);
return -ENODEV;
}
rc = regulator_disable(reg_l23);
if (rc) {
pr_err("disable reg_l23 failed, rc=%d\n", rc);
return -ENODEV;
}
rc = regulator_set_optimum_mode(reg_l8, 100);
if (rc < 0) {
pr_err("set_optimum_mode l8 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_set_optimum_mode(reg_l23, 100);
if (rc < 0) {
pr_err("set_optimum_mode l23 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_set_optimum_mode(reg_l2, 100);
if (rc < 0) {
pr_err("set_optimum_mode l2 failed, rc=%d\n", rc);
return -EINVAL;
}
}
return 0;
}
static int mipi_dsi_panel_power(int on)
{
pr_debug("%s: on=%d\n", __func__, on);
return mipi_dsi_cdp_panel_power(on);
}
static struct mipi_dsi_platform_data mipi_dsi_pdata = {
.vsync_gpio = MDP_VSYNC_GPIO,
.dsi_power_save = mipi_dsi_panel_power,
};
#ifdef CONFIG_MSM_BUS_SCALING
static struct msm_bus_vectors mdp_init_vectors[] = {
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
#ifdef CONFIG_FB_MSM_HDMI_AS_PRIMARY
static struct msm_bus_vectors hdmi_as_primary_vectors[] = {
/* If HDMI is used as primary */
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2000000000,
.ib = 2000000000,
},
};
static struct msm_bus_paths mdp_bus_scale_usecases[] = {
{
ARRAY_SIZE(mdp_init_vectors),
mdp_init_vectors,
},
{
ARRAY_SIZE(hdmi_as_primary_vectors),
hdmi_as_primary_vectors,
},
{
ARRAY_SIZE(hdmi_as_primary_vectors),
hdmi_as_primary_vectors,
},
{
ARRAY_SIZE(hdmi_as_primary_vectors),
hdmi_as_primary_vectors,
},
{
ARRAY_SIZE(hdmi_as_primary_vectors),
hdmi_as_primary_vectors,
},
{
ARRAY_SIZE(hdmi_as_primary_vectors),
hdmi_as_primary_vectors,
},
};
#else
static struct msm_bus_vectors mdp_ui_vectors[] = {
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 216000000 * 2,
.ib = 270000000 * 2,
},
};
static struct msm_bus_vectors mdp_vga_vectors[] = {
/* VGA and less video */
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 216000000 * 2,
.ib = 270000000 * 2,
},
};
static struct msm_bus_vectors mdp_720p_vectors[] = {
/* 720p and less video */
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 230400000 * 2,
.ib = 288000000 * 2,
},
};
static struct msm_bus_vectors mdp_1080p_vectors[] = {
/* 1080p and less video */
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 334080000 * 2,
.ib = 417600000 * 2,
},
};
static struct msm_bus_paths mdp_bus_scale_usecases[] = {
{
ARRAY_SIZE(mdp_init_vectors),
mdp_init_vectors,
},
{
ARRAY_SIZE(mdp_ui_vectors),
mdp_ui_vectors,
},
{
ARRAY_SIZE(mdp_ui_vectors),
mdp_ui_vectors,
},
{
ARRAY_SIZE(mdp_vga_vectors),
mdp_vga_vectors,
},
{
ARRAY_SIZE(mdp_720p_vectors),
mdp_720p_vectors,
},
{
ARRAY_SIZE(mdp_1080p_vectors),
mdp_1080p_vectors,
},
};
#endif
static struct msm_bus_scale_pdata mdp_bus_scale_pdata = {
mdp_bus_scale_usecases,
ARRAY_SIZE(mdp_bus_scale_usecases),
.name = "mdp",
};
#endif
static struct msm_panel_common_pdata mdp_pdata = {
.gpio = MDP_VSYNC_GPIO,
.mdp_max_clk = 200000000,
.mdp_max_bw = 2000000000,
.mdp_bw_ab_factor = 115,
.mdp_bw_ib_factor = 125,
#ifdef CONFIG_MSM_BUS_SCALING
.mdp_bus_scale_table = &mdp_bus_scale_pdata,
#endif
.mdp_rev = MDP_REV_42,
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
.mem_hid = BIT(ION_CP_MM_HEAP_ID),
#else
.mem_hid = MEMTYPE_EBI1,
#endif
.mdp_iommu_split_domain = 0,
};
void __init msm8930_mdp_writeback(struct memtype_reserve* reserve_table)
{
mdp_pdata.ov0_wb_size = MSM_FB_OVERLAY0_WRITEBACK_SIZE;
mdp_pdata.ov1_wb_size = MSM_FB_OVERLAY1_WRITEBACK_SIZE;
#if defined(CONFIG_ANDROID_PMEM) && !defined(CONFIG_MSM_MULTIMEDIA_USE_ION)
reserve_table[mdp_pdata.mem_hid].size +=
mdp_pdata.ov0_wb_size;
reserve_table[mdp_pdata.mem_hid].size +=
mdp_pdata.ov1_wb_size;
#endif
}
#define LPM_CHANNEL0 0
static int toshiba_gpio[] = {LPM_CHANNEL0};
static struct mipi_dsi_panel_platform_data toshiba_pdata = {
.gpio = toshiba_gpio,
};
static struct platform_device mipi_dsi_toshiba_panel_device = {
.name = "mipi_toshiba",
.id = 0,
.dev = {
.platform_data = &toshiba_pdata,
}
};
#define FPGA_3D_GPIO_CONFIG_ADDR 0xB5
static struct mipi_dsi_phy_ctrl dsi_novatek_cmd_mode_phy_db = {
/* DSI_BIT_CLK at 500MHz, 2 lane, RGB888 */
{0x0F, 0x0a, 0x04, 0x00, 0x20}, /* regulator */
/* timing */
{0xab, 0x8a, 0x18, 0x00, 0x92, 0x97, 0x1b, 0x8c,
0x0c, 0x03, 0x04, 0xa0},
{0x5f, 0x00, 0x00, 0x10}, /* phy ctrl */
{0xff, 0x00, 0x06, 0x00}, /* strength */
/* pll control */
{0x40, 0xf9, 0x30, 0xda, 0x00, 0x40, 0x03, 0x62,
0x40, 0x07, 0x03,
0x00, 0x1a, 0x00, 0x00, 0x02, 0x00, 0x20, 0x00, 0x01},
};
static struct mipi_dsi_panel_platform_data novatek_pdata = {
.fpga_3d_config_addr = FPGA_3D_GPIO_CONFIG_ADDR,
.fpga_ctrl_mode = FPGA_SPI_INTF,
.phy_ctrl_settings = &dsi_novatek_cmd_mode_phy_db,
.dlane_swap = 0x1,
.enable_wled_bl_ctrl = 0x1,
};
static struct platform_device mipi_dsi_novatek_panel_device = {
.name = "mipi_novatek",
.id = 0,
.dev = {
.platform_data = &novatek_pdata,
}
};
#ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL
static struct resource hdmi_msm_resources[] = {
{
.name = "hdmi_msm_qfprom_addr",
.start = 0x00700000,
.end = 0x007060FF,
.flags = IORESOURCE_MEM,
},
{
.name = "hdmi_msm_hdmi_addr",
.start = 0x04A00000,
.end = 0x04A00FFF,
.flags = IORESOURCE_MEM,
},
{
.name = "hdmi_msm_irq",
.start = HDMI_IRQ,
.end = HDMI_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static int hdmi_enable_5v(int on);
static int hdmi_core_power(int on, int show);
static int hdmi_cec_power(int on);
static int hdmi_gpio_config(int on);
static int hdmi_panel_power(int on);
static struct msm_hdmi_platform_data hdmi_msm_data = {
.irq = HDMI_IRQ,
.enable_5v = hdmi_enable_5v,
.core_power = hdmi_core_power,
.cec_power = hdmi_cec_power,
.panel_power = hdmi_panel_power,
.gpio_config = hdmi_gpio_config,
};
static struct platform_device hdmi_msm_device = {
.name = "hdmi_msm",
.id = 0,
.num_resources = ARRAY_SIZE(hdmi_msm_resources),
.resource = hdmi_msm_resources,
.dev.platform_data = &hdmi_msm_data,
};
#endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL */
#ifdef CONFIG_FB_MSM_WRITEBACK_MSM_PANEL
static struct platform_device wfd_panel_device = {
.name = "wfd_panel",
.id = 0,
.dev.platform_data = NULL,
};
static struct platform_device wfd_device = {
.name = "msm_wfd",
.id = -1,
};
#endif
#ifdef CONFIG_MSM_BUS_SCALING
static struct msm_bus_vectors dtv_bus_init_vectors[] = {
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
#ifdef CONFIG_FB_MSM_HDMI_AS_PRIMARY
static struct msm_bus_vectors dtv_bus_def_vectors[] = {
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2000000000,
.ib = 2000000000,
},
};
#else
static struct msm_bus_vectors dtv_bus_def_vectors[] = {
{
.src = MSM_BUS_MASTER_MDP_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 566092800 * 2,
.ib = 707616000 * 2,
},
};
#endif
static struct msm_bus_paths dtv_bus_scale_usecases[] = {
{
ARRAY_SIZE(dtv_bus_init_vectors),
dtv_bus_init_vectors,
},
{
ARRAY_SIZE(dtv_bus_def_vectors),
dtv_bus_def_vectors,
},
};
static struct msm_bus_scale_pdata dtv_bus_scale_pdata = {
dtv_bus_scale_usecases,
ARRAY_SIZE(dtv_bus_scale_usecases),
.name = "dtv",
};
static struct lcdc_platform_data dtv_pdata = {
.bus_scale_table = &dtv_bus_scale_pdata,
.lcdc_power_save = hdmi_panel_power,
};
static int hdmi_panel_power(int on)
{
int rc;
pr_debug("%s: HDMI Core: %s\n", __func__, (on ? "ON" : "OFF"));
rc = hdmi_core_power(on, 1);
if (rc)
rc = hdmi_cec_power(on);
pr_debug("%s: HDMI Core: %s Success\n", __func__, (on ? "ON" : "OFF"));
return rc;
}
#endif
#ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL
static int hdmi_enable_5v(int on)
{
static struct regulator *reg_ext_5v; /* HDMI_5V */
static int prev_on;
int rc;
if (on == prev_on)
return 0;
if (!reg_ext_5v) {
reg_ext_5v = regulator_get(&hdmi_msm_device.dev, "hdmi_mvs");
if (IS_ERR(reg_ext_5v)) {
pr_err("'%s' regulator not found, rc=%ld\n",
"hdmi_mvs", IS_ERR(reg_ext_5v));
reg_ext_5v = NULL;
return -ENODEV;
}
}
if (on) {
rc = regulator_enable(reg_ext_5v);
if (rc) {
pr_err("'%s' regulator enable failed, rc=%d\n",
"reg_ext_5v", rc);
return rc;
}
pr_debug("%s(on): success\n", __func__);
} else {
rc = regulator_disable(reg_ext_5v);
if (rc)
pr_warning("'%s' regulator disable failed, rc=%d\n",
"reg_ext_5v", rc);
pr_debug("%s(off): success\n", __func__);
}
prev_on = on;
return 0;
}
static int hdmi_core_power(int on, int show)
{
/* Both HDMI "avdd" and "vcc" are powered by 8038_l23 regulator */
static struct regulator *reg_8038_l23;
static int prev_on;
int rc;
if (on == prev_on)
return 0;
if (!reg_8038_l23) {
reg_8038_l23 = regulator_get(&hdmi_msm_device.dev, "hdmi_avdd");
if (IS_ERR(reg_8038_l23)) {
pr_err("could not get reg_8038_l23, rc = %ld\n",
PTR_ERR(reg_8038_l23));
return -ENODEV;
}
rc = regulator_set_voltage(reg_8038_l23, 1800000, 1800000);
if (rc) {
pr_err("set_voltage failed for 8921_l23, rc=%d\n", rc);
return -EINVAL;
}
}
if (on) {
rc = regulator_set_optimum_mode(reg_8038_l23, 100000);
if (rc < 0) {
pr_err("set_optimum_mode l23 failed, rc=%d\n", rc);
return -EINVAL;
}
rc = regulator_enable(reg_8038_l23);
if (rc) {
pr_err("'%s' regulator enable failed, rc=%d\n",
"hdmi_avdd", rc);
return rc;
}
pr_debug("%s(on): success\n", __func__);
} else {
rc = regulator_disable(reg_8038_l23);
if (rc) {
pr_err("disable reg_8038_l23 failed, rc=%d\n", rc);
return -ENODEV;
}
rc = regulator_set_optimum_mode(reg_8038_l23, 100);
if (rc < 0) {
pr_err("set_optimum_mode l23 failed, rc=%d\n", rc);
return -EINVAL;
}
pr_debug("%s(off): success\n", __func__);
}
prev_on = on;
return 0;
}
static int hdmi_gpio_config(int on)
{
int rc = 0;
static int prev_on;
if (on == prev_on)
return 0;
if (on) {
rc = gpio_request(100, "HDMI_DDC_CLK");
if (rc) {
pr_err("'%s'(%d) gpio_request failed, rc=%d\n",
"HDMI_DDC_CLK", 100, rc);
return rc;
}
rc = gpio_request(101, "HDMI_DDC_DATA");
if (rc) {
pr_err("'%s'(%d) gpio_request failed, rc=%d\n",
"HDMI_DDC_DATA", 101, rc);
goto error1;
}
rc = gpio_request(102, "HDMI_HPD");
if (rc) {
pr_err("'%s'(%d) gpio_request failed, rc=%d\n",
"HDMI_HPD", 102, rc);
goto error2;
}
pr_debug("%s(on): success\n", __func__);
} else {
gpio_free(100);
gpio_free(101);
gpio_free(102);
pr_debug("%s(off): success\n", __func__);
}
prev_on = on;
return 0;
error2:
gpio_free(101);
error1:
gpio_free(100);
return rc;
}
static int hdmi_cec_power(int on)
{
static int prev_on;
int rc;
if (on == prev_on)
return 0;
if (on) {
rc = gpio_request(99, "HDMI_CEC_VAR");
if (rc) {
pr_err("'%s'(%d) gpio_request failed, rc=%d\n",
"HDMI_CEC_VAR", 99, rc);
goto error;
}
pr_debug("%s(on): success\n", __func__);
} else {
gpio_free(99);
pr_debug("%s(off): success\n", __func__);
}
prev_on = on;
return 0;
error:
return rc;
}
#endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL */
void __init msm8930_init_fb(void)
{
platform_device_register(&msm_fb_device);
#ifdef CONFIG_FB_MSM_WRITEBACK_MSM_PANEL
platform_device_register(&wfd_panel_device);
platform_device_register(&wfd_device);
#endif
platform_device_register(&mipi_dsi_novatek_panel_device);
#ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL
platform_device_register(&hdmi_msm_device);
#endif
platform_device_register(&mipi_dsi_toshiba_panel_device);
msm_fb_register_device("mdp", &mdp_pdata);
msm_fb_register_device("mipi_dsi", &mipi_dsi_pdata);
#ifdef CONFIG_MSM_BUS_SCALING
msm_fb_register_device("dtv", &dtv_pdata);
#endif
}
void __init msm8930_allocate_fb_region(void)
{
void *addr;
unsigned long size;
size = MSM_FB_SIZE;
addr = alloc_bootmem_align(size, 0x1000);
msm_fb_resources[0].start = __pa(addr);
msm_fb_resources[0].end = msm_fb_resources[0].start + size - 1;
pr_info("allocating %lu bytes at %p (%lx physical) for fb\n",
size, addr, __pa(addr));
}
|
MoKee/android_kernel_sony_fuji-common
|
arch/arm/mach-msm/board-8930-display.c
|
C
|
gpl-2.0
| 18,755
|
// Replacement for sys/mman.h which factors out platform differences.
#include <sys/mman.h>
#if defined(VGO_darwin) || defined(VGO_freebsd)
# define MAP_ANONYMOUS MAP_ANON
#endif
#include <assert.h>
#include <unistd.h>
// Map a page, then unmap it, then return that address. That
// guarantees to give an address which will fault when accessed,
// without making any assumptions about the layout of the address
// space.
__attribute__((unused))
static void* get_unmapped_page(void)
{
void* ptr;
int r;
long pagesz = sysconf(_SC_PAGE_SIZE);
assert(pagesz == 4096 || pagesz == 16384 || pagesz == 65536);
ptr = mmap(0, pagesz, PROT_READ, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
assert(ptr != (void*)-1);
r = munmap(ptr, pagesz);
assert(r == 0);
return ptr;
}
|
CTSRD-SOAAP/valgrind-freebsd
|
tests/sys_mman.h
|
C
|
gpl-2.0
| 787
|
/******************************************************************************
* Warmux is a convivial mass murder game.
* Copyright (C) 2001-2011 Warmux Team.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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
******************************************************************************
* Mouse management
*****************************************************************************/
#include "interface/mouse.h"
#include "interface/cursor.h"
#include "interface/interface.h"
#include "interface/mouse_cursor.h"
#include "character/character.h"
#include "game/config.h"
#include "game/game_mode.h"
#include "game/game.h"
#include "graphic/video.h"
#include "include/app.h"
#include "include/action_handler.h"
#include "map/camera.h"
#include "map/map.h"
#include "team/macro.h"
#include "team/team.h"
#include <WARMUX_point.h>
#include "tool/resource_manager.h"
#include "weapon/weapon.h"
#include "game/game_time.h"
#define MOUSE_CLICK_SQUARE_DISTANCE 5*5
#define LONG_CLICK_DURATION 600
std::string __pointers[] = {
"mouse/pointer_standard",
"mouse/pointer_select",
"mouse/pointer_move",
"mouse/pointer_arrow_up",
"mouse/pointer_arrow_up_right",
"mouse/pointer_arrow_up_left",
"mouse/pointer_arrow_down",
"mouse/pointer_arrow_down_right",
"mouse/pointer_arrow_down_left",
"mouse/pointer_arrow_right",
"mouse/pointer_arrow_left",
"mouse/pointer_aim",
"mouse/pointer_attack_from_left",
"mouse/pointer_attack_from_right",
};
std::map<Mouse::pointer_t, MouseCursor> Mouse::cursors;
Mouse::Mouse()
: lastpos(-1,-1)
, last_hide_time(0)
, long_click_timer(0)
, click_pos(-1,-1)
, is_long_click(false)
, was_long_click(false)
{
visible = MOUSE_VISIBLE;
// Load the different pointers
Profile *res = GetResourceManager().LoadXMLProfile("cursors.xml", false);
for (int i=POINTER_SELECT; i < POINTER_ATTACK; i++) {
cursors.insert(std::make_pair(Mouse::pointer_t(i),
GetResourceManager().LoadMouseCursor(res, __pointers[i],
Mouse::pointer_t(i))));
}
current_pointer = POINTER_STANDARD;
GetResourceManager().UnLoadXMLProfile(res);
#ifdef HAVE_TOUCHSCREEN
SDL_ShowCursor(false);
#endif
}
void Mouse::EndLongClickTimer()
{
if (long_click_timer) {
SDL_RemoveTimer(long_click_timer);
long_click_timer = 0;
}
is_long_click = false;
was_long_click = false;
}
bool Mouse::HasFocus() const
{
Uint8 state = SDL_GetAppState();
if ((state & SDL_APPMOUSEFOCUS) &&
(state & SDL_APPINPUTFOCUS) &&
(state & SDL_APPACTIVE)) {
return true;
}
return false;
}
void Mouse::ActionLeftClick(bool /*shift*/) const
{
const Point2i pos_monde = GetWorldPosition();
//Change character by mouse click only if the choosen weapon allows it
if (GameMode::GetConstInstance()->AllowCharacterSelection() &&
ActiveTeam().GetWeapon().mouse_character_selection) {
// Choose a character of our own team
bool character_found = false;
Team::iterator it = ActiveTeam().begin(),
end = ActiveTeam().end();
for (; it != end; ++it) {
if (&(*it) != &ActiveCharacter()
&& !it -> IsDead()
&& it->GetRect().Contains(pos_monde)) {
character_found = true;
break;
}
}
if (character_found) {
ActiveTeam().SelectCharacter(&(*it));
ActionHandler::GetInstance()->NewActionActiveCharacter();
return;
}
if (ActiveCharacter().GetRect().Contains(pos_monde)) {
CharacterCursor::GetInstance()->FollowActiveCharacter();
return;
}
}
// Choosing target for a weapon, many posibilities :
// - Do nothing
// - Choose a target but don't fire
// - Choose a target and fire it !
Action* a = new Action(Action::ACTION_WEAPON_SET_TARGET);
a->Push(GetWorldPosition());
ActionHandler::GetInstance()->NewAction (a);
}
void Mouse::ActionRightClick(bool /*shift*/) const
{
Interface::GetInstance()->weapons_menu.SwitchDisplay(GetPosition());
}
void Mouse::ActionWheelUp(bool shift) const
{
ActiveTeam().AccessWeapon().HandleMouseWheelUp(shift);
}
void Mouse::ActionWheelDown(bool shift) const
{
ActiveTeam().AccessWeapon().HandleMouseWheelDown(shift);
}
bool Mouse::IS_CLICK_BUTTON(uint button)
{
return (button==SDL_BUTTON_LEFT || button==SDL_BUTTON_RIGHT || button==SDL_BUTTON_MIDDLE);
}
Uint8 Mouse::BUTTON_RIGHT() // static method
{
return Config::GetConstRef().GetLeftHandedMouse() ? SDL_BUTTON_LEFT : SDL_BUTTON_RIGHT;
}
Uint8 Mouse::BUTTON_LEFT() // static method
{
return Config::GetConstRef().GetLeftHandedMouse() ? SDL_BUTTON_RIGHT : SDL_BUTTON_LEFT;
}
static Uint32 HandleLongClick(Uint32 /*interval*/, void *param)
{
((Mouse*)param)->SetLongClick();
return 0;
}
bool Mouse::HandleEvent(const SDL_Event& evnt)
{
if (!HasFocus()) {
return false;
}
Point2i pos = GetPosition();
if (click_pos.SquareDistance(pos) > MOUSE_CLICK_SQUARE_DISTANCE) {
// We have moved too much, consider we are not long-clicking
EndLongClickTimer();
}
if (is_long_click) {
is_long_click = false;
was_long_click = true;
if (Interface::GetInstance()->ActionLongClick(pos, click_pos))
return true;
return false;
}
if (evnt.type != SDL_MOUSEBUTTONDOWN && evnt.type != SDL_MOUSEBUTTONUP) {
return false;
}
if (evnt.type==SDL_MOUSEBUTTONDOWN && evnt.button.button==BUTTON_LEFT()) {
click_pos = pos;
if (Interface::GetInstance()->ActionClickDown(pos))
return true;
// Either it's out of the menu, or we want to know how long the click was
long_click_timer = SDL_AddTimer(LONG_CLICK_DURATION, HandleLongClick, this);
return true;
}
if (evnt.type==SDL_MOUSEBUTTONUP && evnt.button.button==BUTTON_LEFT()) {
// Ignore click-ups from long clicks
if (was_long_click) {
was_long_click = false;
return true;
} else {
EndLongClickTimer();
if (Interface::GetInstance()->ActionClickUp(pos, click_pos))
return true;
if (click_pos.SquareDistance(pos) > MOUSE_CLICK_SQUARE_DISTANCE)
return true;
}
}
if (Game::GetInstance()->ReadState() != Game::PLAYING)
return true;
if (!ActiveTeam().IsLocalHuman())
return true;
bool shift = !!(SDL_GetModState() & KMOD_SHIFT);
if (evnt.type == SDL_MOUSEBUTTONUP) {
if (evnt.button.button == Mouse::BUTTON_RIGHT())
ActionRightClick(shift);
else if (evnt.button.button == Mouse::BUTTON_LEFT())
ActionLeftClick(shift);
else if (evnt.button.button == SDL_BUTTON_WHEELDOWN)
ActionWheelDown(shift);
else if (evnt.button.button == SDL_BUTTON_WHEELUP)
ActionWheelUp(shift);
}
return true;
}
void Mouse::GetDesignatedCharacter() const
{
if (Game::GetInstance()->ReadState() != Game::PLAYING)
return;
const Point2i pos_monde = GetWorldPosition();
// Which character is pointed by the mouse ? (appart from the active one)
Interface::GetInstance()->character_under_cursor = NULL;
FOR_ALL_LIVING_CHARACTERS(team, character) {
if (&(*character) != &ActiveCharacter()
&& character->GetRect().Contains(pos_monde)) {
Interface::GetInstance()->character_under_cursor = &(*character);
}
}
// No character is pointed... what about the active one ?
if (Interface::GetConstInstance()->character_under_cursor
&& ActiveCharacter().GetRect().Contains(pos_monde)) {
Interface::GetInstance()->character_under_cursor = &ActiveCharacter();
}
}
void Mouse::Refresh()
{
/* FIXME the 200 is hardcoded because I cannot find where the main loop
* refresh rate is set... */
#define NB_LOOP_BEFORE_HIDE 200
static int counter = 0;
GetDesignatedCharacter();
Point2i pos = GetPosition();
if (lastpos != pos) {
Show();
lastpos = pos;
counter = NB_LOOP_BEFORE_HIDE;
ShowGameInterface();
} else if (visible == MOUSE_VISIBLE) {
/* The mouse is hidden after a while when not moving */
if (--counter <= 0)
Hide();
}
}
Point2i Mouse::GetPosition() const
{
int x, y;
SDL_GetMouseState(&x, &y);
return Point2i(x, y);
}
Point2i Mouse::GetWorldPosition() const
{
return GetPosition() + Camera::GetConstInstance()->GetPosition();
}
MouseCursor& Mouse::GetCursor(pointer_t pointer) const
{
ASSERT(pointer != POINTER_STANDARD);
if (pointer == POINTER_ATTACK) {
if (ActiveCharacter().GetDirection() == DIRECTION_RIGHT)
return GetCursor(POINTER_ATTACK_FROM_LEFT);
else
return GetCursor(POINTER_ATTACK_FROM_RIGHT);
}
return (*cursors.find(pointer)).second;
}
// set the new pointer type and return the previous one
Mouse::pointer_t Mouse::SetPointer(pointer_t pointer)
{
if (Config::GetConstInstance()->GetDefaultMouseCursor()) {
Show(); // be sure cursor is visible
return Mouse::POINTER_STANDARD;
}
if (current_pointer == pointer) return pointer;
if (pointer == POINTER_STANDARD)
#ifndef HAVE_TOUCHSCREEN
SDL_ShowCursor(true);
#else
SDL_ShowCursor(false);
#endif
else
SDL_ShowCursor(false);
pointer_t old_pointer = current_pointer;
current_pointer = pointer;
return old_pointer;
}
void Mouse::Draw() const
{
if (visible != MOUSE_VISIBLE)
return;
if (current_pointer == POINTER_STANDARD)
return; // use standard SDL cursor
const MouseCursor& cursor = GetCursor(current_pointer);
const Surface& surf = cursor.GetSurface();
Point2i pos = GetPosition() - cursor.GetClicPos();
GetMainWindow().Blit(surf, pos);
GetWorld().ToRedrawOnScreen(Rectanglei(pos, surf.GetSize()));
}
void Mouse::Show()
{
#ifndef HAVE_TOUCHSCREEN
if (Time::GetConstInstance()->Read()-last_hide_time > 10000 && visible == MOUSE_HIDDEN) {
CenterPointer();
}
#endif
visible = MOUSE_VISIBLE;
if (Config::GetConstInstance()->GetDefaultMouseCursor()) {
SDL_ShowCursor(true); // be sure cursor is visible
}
}
void Mouse::Hide()
{
if (visible == MOUSE_VISIBLE)
{
last_hide_time = Time::GetConstInstance()->Read();
}
visible = MOUSE_HIDDEN;
SDL_ShowCursor(false); // be sure cursor is invisible
}
// Center the pointer on the screen
void Mouse::CenterPointer()
{
SetPosition(GetMainWindow().GetSize() / 2);
}
void Mouse::SetPosition(Point2i pos)
{
if (!HasFocus()) // The application has not the focus, don't move the mouse cursor!
return;
MSG_DEBUG("mouse", "1) %d, %d\n", GetPosition().GetX(), GetPosition().GetY());
SDL_WarpMouse(pos.x, pos.y);
SDL_PumpEvents(); // force new position else GetPosition does not return new position
lastpos = GetPosition();
MSG_DEBUG("mouse", "2) %d, %d\n", GetPosition().GetX(), GetPosition().GetY());
}
|
yeKcim/warmux
|
old/warmux-11.01/src/interface/mouse.cpp
|
C++
|
gpl-2.0
| 11,366
|
<?php
/**
* @package AcyMailing for Joomla!
* @version 4.8.0
* @author acyba.com
* @copyright (C) 2009-2014 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><div id="acy_content">
<script language="javascript" type="text/javascript">
<!--
var selectedContents = new Array();
var allElements = <?php echo count($this->rows);?>;
<?php
foreach($this->rows as $oneRow){
if(!empty($oneRow->selected)){
echo "selectedContents['".$oneRow->namekey."'] = 'content';";
}
}
?>
function applyContent(contentid,rowClass){
if(selectedContents[contentid]){
window.document.getElementById('content'+contentid).className = rowClass;
delete selectedContents[contentid];
}else{
window.document.getElementById('content'+contentid).className = 'selectedrow';
selectedContents[contentid] = 'content';
}
}
function insertTag(){
var tag = '';
for(var i in selectedContents){
if(selectedContents[i] == 'content'){
allElements--;
if(tag != '') tag += ',';
tag = tag + i;
}
}
window.top.document.getElementById('<?php echo $this->controlName; ?>customfields').value = tag;
window.top.document.getElementById('link<?php echo $this->controlName; ?>customfields').href = 'index.php?option=com_acymailing&tmpl=component&ctrl=chooselist&task=customfields&control=<?php echo $this->controlName; ?>&values='+tag;
acymailing_js.closeBox(true);
}
//-->
</script>
<style type="text/css">
table.adminlist tr.selectedrow td{
background-color:#FDE2BA;
}
</style>
<form action="index.php?option=<?php echo ACYMAILING_COMPONENT ?>" method="post" name="adminForm" id="adminForm" >
<div style="float:right;margin-bottom : 10px">
<button class="btn" id="insertButton" onclick="insertTag(); return false;"><?php echo JText::_('ACY_APPLY'); ?></button>
</div>
<div style="clear:both"/>
<table class="adminlist table table-striped table-hover" cellpadding="1">
<thead>
<tr>
<th class="title">
</th>
<th class="title">
<?php echo JText::_('FIELD_COLUMN'); ?>
</th>
<th class="title">
<?php echo JText::_('FIELD_LABEL'); ?>
</th>
<th class="title titleid">
<?php echo JText::_('ACY_ID'); ?>
</th>
</tr>
</thead>
<tbody>
<?php
$k = 0;
foreach($this->rows as $row){
?>
<tr class="<?php echo empty($row->selected) ? "row$k" : 'selectedrow'; ?>" id="content<?php echo $row->namekey; ?>" onclick="applyContent('<?php echo $row->namekey."','row$k'"?>);" style="cursor:pointer;">
<td class="acytdcheckbox"></td>
<td>
<?php echo $row->namekey; ?>
</td>
<td>
<?php echo $this->fieldsClass->trans($row->fieldname); ?>
</td>
<td align="center" style="text-align:center" >
<?php echo $row->fieldid; ?>
</td>
</tr>
<?php
$k = 1-$k;
}
?>
</tbody>
</table>
</form>
</div>
|
ranrolls/ras-full-portal
|
administrator/components/com_acymailing/views/chooselist/tmpl/customfields.php
|
PHP
|
gpl-2.0
| 2,944
|
//
// LQAnalyzeForYearUseItemModel.h
// 朝阳能源结算
//
// Created by admin on 15/9/4.
// Copyright (c) 2015年 dieshang. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface LQAnalyzeForYearUseItemModel : NSObject
@property (nonatomic, copy ) NSString *accountId;
@property (nonatomic, copy ) NSString *recvalues;
@property (nonatomic, assign) int recyear;
@property (nonatomic, assign) int recmonth;
@end
|
daqiangge/ChaoYangNengYuan
|
朝阳能源结算/朝阳能源--代码/朝阳能源结算/Classes/Account(账户户头)/Model/LQAnalyzeForYearUseItemModel.h
|
C
|
gpl-2.0
| 449
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
// Experimental unified task-data parallel manycore LDRD
#ifndef KOKKOS_QTHREAD_TASKPOLICY_HPP
#define KOKKOS_QTHREAD_TASKPOLICY_HPP
#include <string>
#include <typeinfo>
#include <stdexcept>
//----------------------------------------------------------------------------
// Defines to enable experimental Qthread functionality
#define QTHREAD_LOCAL_PRIORITY
#define CLONED_TASKS
#include <qthread.h>
#undef QTHREAD_LOCAL_PRIORITY
#undef CLONED_TASKS
//----------------------------------------------------------------------------
#include <Kokkos_Qthread.hpp>
#include <Kokkos_TaskPolicy.hpp>
#include <Kokkos_View.hpp>
#include <impl/Kokkos_FunctorAdapter.hpp>
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Experimental {
namespace Impl {
template<>
class TaskMember< Kokkos::Qthread , void , void >
{
public:
typedef void (* function_apply_single_type) ( TaskMember * );
typedef void (* function_apply_team_type) ( TaskMember * , Kokkos::Impl::QthreadTeamPolicyMember & );
typedef void (* function_dealloc_type)( TaskMember * );
typedef TaskMember * (* function_verify_type) ( TaskMember * );
private:
const function_dealloc_type m_dealloc ; ///< Deallocation
const function_verify_type m_verify ; ///< Result type verification
const function_apply_single_type m_apply_single ; ///< Apply function
const function_apply_team_type m_apply_team ; ///< Apply function
int volatile * const m_active_count ; ///< Count of active tasks on this policy
aligned_t m_qfeb ; ///< Qthread full/empty bit
TaskMember ** const m_dep ; ///< Dependences
const int m_dep_capacity ; ///< Capacity of dependences
int m_dep_size ; ///< Actual count of dependences
int m_ref_count ; ///< Reference count
int m_state ; ///< State of the task
TaskMember() /* = delete */ ;
TaskMember( const TaskMember & ) /* = delete */ ;
TaskMember & operator = ( const TaskMember & ) /* = delete */ ;
static aligned_t qthread_func( void * arg );
static void * allocate( const unsigned arg_sizeof_derived , const unsigned arg_dependence_capacity );
static void deallocate( void * );
void throw_error_add_dependence() const ;
static void throw_error_verify_type();
template < class DerivedTaskType >
static
void deallocate( TaskMember * t )
{
DerivedTaskType * ptr = static_cast< DerivedTaskType * >(t);
ptr->~DerivedTaskType();
deallocate( (void *) ptr );
}
void schedule();
protected :
~TaskMember();
// Used by TaskMember< Qthread , ResultType , void >
TaskMember( const function_verify_type arg_verify
, const function_dealloc_type arg_dealloc
, const function_apply_single_type arg_apply_single
, const function_apply_team_type arg_apply_team
, volatile int & arg_active_count
, const unsigned arg_sizeof_derived
, const unsigned arg_dependence_capacity
);
// Used for TaskMember< Qthread , void , void >
TaskMember( const function_dealloc_type arg_dealloc
, const function_apply_single_type arg_apply_single
, const function_apply_team_type arg_apply_team
, volatile int & arg_active_count
, const unsigned arg_sizeof_derived
, const unsigned arg_dependence_capacity
);
public:
template< typename ResultType >
KOKKOS_FUNCTION static
TaskMember * verify_type( TaskMember * t )
{
enum { check_type = ! Kokkos::Impl::is_same< ResultType , void >::value };
if ( check_type && t != 0 ) {
// Verify that t->m_verify is this function
const function_verify_type self = & TaskMember::template verify_type< ResultType > ;
if ( t->m_verify != self ) {
t = 0 ;
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
throw_error_verify_type();
#endif
}
}
return t ;
}
//----------------------------------------
/* Inheritence Requirements on task types:
* typedef FunctorType::value_type value_type ;
* class DerivedTaskType
* : public TaskMember< Qthread , value_type , FunctorType >
* { ... };
* class TaskMember< Qthread , value_type , FunctorType >
* : public TaskMember< Qthread , value_type , void >
* , public Functor
* { ... };
* If value_type != void
* class TaskMember< Qthread , value_type , void >
* : public TaskMember< Qthread , void , void >
*
* Allocate space for DerivedTaskType followed by TaskMember*[ dependence_capacity ]
*
*/
/** \brief Allocate and construct a single-thread task */
template< class DerivedTaskType >
static
TaskMember * create_single( const typename DerivedTaskType::functor_type & arg_functor
, volatile int & arg_active_count
, const unsigned arg_dependence_capacity )
{
typedef typename DerivedTaskType::functor_type functor_type ;
typedef typename functor_type::value_type value_type ;
DerivedTaskType * const task =
new( allocate( sizeof(DerivedTaskType) , arg_dependence_capacity ) )
DerivedTaskType( & TaskMember::template deallocate< DerivedTaskType >
, & TaskMember::template apply_single< functor_type , value_type >
, 0
, arg_active_count
, sizeof(DerivedTaskType)
, arg_dependence_capacity
, arg_functor );
return static_cast< TaskMember * >( task );
}
/** \brief Allocate and construct a team-thread task */
template< class DerivedTaskType >
static
TaskMember * create_team( const typename DerivedTaskType::functor_type & arg_functor
, volatile int & arg_active_count
, const unsigned arg_dependence_capacity
, const bool arg_is_team )
{
typedef typename DerivedTaskType::functor_type functor_type ;
typedef typename functor_type::value_type value_type ;
const function_apply_single_type flag = reinterpret_cast<function_apply_single_type>( arg_is_team ? 0 : 1 );
DerivedTaskType * const task =
new( allocate( sizeof(DerivedTaskType) , arg_dependence_capacity ) )
DerivedTaskType( & TaskMember::template deallocate< DerivedTaskType >
, flag
, & TaskMember::template apply_team< functor_type , value_type >
, arg_active_count
, sizeof(DerivedTaskType)
, arg_dependence_capacity
, arg_functor );
return static_cast< TaskMember * >( task );
}
void respawn();
void spawn()
{
m_state = Kokkos::Experimental::TASK_STATE_WAITING ;
schedule();
}
//----------------------------------------
typedef FutureValueTypeIsVoidError get_result_type ;
KOKKOS_INLINE_FUNCTION
get_result_type get() const { return get_result_type() ; }
KOKKOS_INLINE_FUNCTION
Kokkos::Experimental::TaskState get_state() const { return Kokkos::Experimental::TaskState( m_state ); }
//----------------------------------------
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
static
void assign( TaskMember ** const lhs , TaskMember * const rhs , const bool no_throw = false );
#else
KOKKOS_INLINE_FUNCTION static
void assign( TaskMember ** const lhs , TaskMember * const rhs , const bool no_throw = false ) {}
#endif
KOKKOS_INLINE_FUNCTION
TaskMember * get_dependence( int i ) const
{ return ( Kokkos::Experimental::TASK_STATE_EXECUTING == m_state && 0 <= i && i < m_dep_size ) ? m_dep[i] : (TaskMember*) 0 ; }
KOKKOS_INLINE_FUNCTION
int get_dependence() const
{ return m_dep_size ; }
KOKKOS_INLINE_FUNCTION
void clear_dependence()
{
for ( int i = 0 ; i < m_dep_size ; ++i ) assign( m_dep + i , 0 );
m_dep_size = 0 ;
}
KOKKOS_INLINE_FUNCTION
void add_dependence( TaskMember * before )
{
if ( ( Kokkos::Experimental::TASK_STATE_CONSTRUCTING == m_state ||
Kokkos::Experimental::TASK_STATE_EXECUTING == m_state ) &&
m_dep_size < m_dep_capacity ) {
assign( m_dep + m_dep_size , before );
++m_dep_size ;
}
else {
throw_error_add_dependence();
}
}
//----------------------------------------
template< class FunctorType , class ResultType >
KOKKOS_INLINE_FUNCTION static
void apply_single( typename Kokkos::Impl::enable_if< ! Kokkos::Impl::is_same< ResultType , void >::value , TaskMember * >::type t )
{
typedef TaskMember< Kokkos::Qthread , ResultType , FunctorType > derived_type ;
// TaskMember< Kokkos::Qthread , ResultType , FunctorType >
// : public TaskMember< Kokkos::Qthread , ResultType , void >
// , public FunctorType
// { ... };
derived_type & m = * static_cast< derived_type * >( t );
Kokkos::Impl::FunctorApply< FunctorType , void , ResultType & >::apply( (FunctorType &) m , & m.m_result );
}
template< class FunctorType , class ResultType >
KOKKOS_INLINE_FUNCTION static
void apply_single( typename Kokkos::Impl::enable_if< Kokkos::Impl::is_same< ResultType , void >::value , TaskMember * >::type t )
{
typedef TaskMember< Kokkos::Qthread , ResultType , FunctorType > derived_type ;
// TaskMember< Kokkos::Qthread , ResultType , FunctorType >
// : public TaskMember< Kokkos::Qthread , ResultType , void >
// , public FunctorType
// { ... };
derived_type & m = * static_cast< derived_type * >( t );
Kokkos::Impl::FunctorApply< FunctorType , void , void >::apply( (FunctorType &) m );
}
//----------------------------------------
template< class FunctorType , class ResultType >
KOKKOS_INLINE_FUNCTION static
void apply_team( typename Kokkos::Impl::enable_if< ! Kokkos::Impl::is_same< ResultType , void >::value , TaskMember * >::type t
, Kokkos::Impl::QthreadTeamPolicyMember & member )
{
typedef TaskMember< Kokkos::Qthread , ResultType , FunctorType > derived_type ;
derived_type & m = * static_cast< derived_type * >( t );
m.FunctorType::apply( member , m.m_result );
}
template< class FunctorType , class ResultType >
KOKKOS_INLINE_FUNCTION static
void apply_team( typename Kokkos::Impl::enable_if< Kokkos::Impl::is_same< ResultType , void >::value , TaskMember * >::type t
, Kokkos::Impl::QthreadTeamPolicyMember & member )
{
typedef TaskMember< Kokkos::Qthread , ResultType , FunctorType > derived_type ;
derived_type & m = * static_cast< derived_type * >( t );
m.FunctorType::apply( member );
}
};
//----------------------------------------------------------------------------
/** \brief Base class for tasks with a result value in the Qthread execution space.
*
* The FunctorType must be void because this class is accessed by the
* Future class for the task and result value.
*
* Must be derived from TaskMember<S,void,void> 'root class' so the Future class
* can correctly static_cast from the 'root class' to this class.
*/
template < class ResultType >
class TaskMember< Kokkos::Qthread , ResultType , void >
: public TaskMember< Kokkos::Qthread , void , void >
{
public:
ResultType m_result ;
typedef const ResultType & get_result_type ;
KOKKOS_INLINE_FUNCTION
get_result_type get() const { return m_result ; }
protected:
typedef TaskMember< Kokkos::Qthread , void , void > task_root_type ;
typedef task_root_type::function_dealloc_type function_dealloc_type ;
typedef task_root_type::function_apply_single_type function_apply_single_type ;
typedef task_root_type::function_apply_team_type function_apply_team_type ;
inline
TaskMember( const function_dealloc_type arg_dealloc
, const function_apply_single_type arg_apply_single
, const function_apply_team_type arg_apply_team
, volatile int & arg_active_count
, const unsigned arg_sizeof_derived
, const unsigned arg_dependence_capacity
)
: task_root_type( & task_root_type::template verify_type< ResultType >
, arg_dealloc
, arg_apply_single
, arg_apply_team
, arg_active_count
, arg_sizeof_derived
, arg_dependence_capacity )
, m_result()
{}
};
template< class ResultType , class FunctorType >
class TaskMember< Kokkos::Qthread , ResultType , FunctorType >
: public TaskMember< Kokkos::Qthread , ResultType , void >
, public FunctorType
{
public:
typedef FunctorType functor_type ;
typedef TaskMember< Kokkos::Qthread , void , void > task_root_type ;
typedef TaskMember< Kokkos::Qthread , ResultType , void > task_base_type ;
typedef task_root_type::function_dealloc_type function_dealloc_type ;
typedef task_root_type::function_apply_single_type function_apply_single_type ;
typedef task_root_type::function_apply_team_type function_apply_team_type ;
inline
TaskMember( const function_dealloc_type arg_dealloc
, const function_apply_single_type arg_apply_single
, const function_apply_team_type arg_apply_team
, volatile int & arg_active_count
, const unsigned arg_sizeof_derived
, const unsigned arg_dependence_capacity
, const functor_type & arg_functor
)
: task_base_type( arg_dealloc
, arg_apply_single
, arg_apply_team
, arg_active_count
, arg_sizeof_derived
, arg_dependence_capacity )
, functor_type( arg_functor )
{}
};
} /* namespace Impl */
} /* namespace Experimental */
} /* namespace Kokkos */
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Experimental {
void wait( TaskPolicy< Kokkos::Qthread > & );
template<>
class TaskPolicy< Kokkos::Qthread >
{
public:
typedef Kokkos::Qthread execution_space ;
typedef Kokkos::Impl::QthreadTeamPolicyMember member_type ;
private:
typedef Impl::TaskMember< execution_space , void , void > task_root_type ;
TaskPolicy & operator = ( const TaskPolicy & ) /* = delete */ ;
template< class FunctorType >
static inline
const task_root_type * get_task_root( const FunctorType * f )
{
typedef Impl::TaskMember< execution_space , typename FunctorType::value_type , FunctorType > task_type ;
return static_cast< const task_root_type * >( static_cast< const task_type * >(f) );
}
template< class FunctorType >
static inline
task_root_type * get_task_root( FunctorType * f )
{
typedef Impl::TaskMember< execution_space , typename FunctorType::value_type , FunctorType > task_type ;
return static_cast< task_root_type * >( static_cast< task_type * >(f) );
}
const unsigned m_default_dependence_capacity ;
const unsigned m_team_size ;
volatile int m_active_count_root ;
volatile int & m_active_count ;
public:
explicit
TaskPolicy( const unsigned arg_default_dependence_capacity = 4
, const unsigned arg_team_size = 0 /* assign default */ );
KOKKOS_INLINE_FUNCTION
TaskPolicy( const TaskPolicy & rhs )
: m_default_dependence_capacity( rhs.m_default_dependence_capacity )
, m_team_size( m_team_size )
, m_active_count_root(0)
, m_active_count( rhs.m_active_count )
{}
KOKKOS_INLINE_FUNCTION
TaskPolicy( const TaskPolicy & rhs
, const unsigned arg_default_dependence_capacity )
: m_default_dependence_capacity( arg_default_dependence_capacity )
, m_team_size( m_team_size )
, m_active_count_root(0)
, m_active_count( rhs.m_active_count )
{}
//----------------------------------------
template< class ValueType >
const Future< ValueType , execution_space > &
spawn( const Future< ValueType , execution_space > & f ) const
{
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
f.m_task->spawn();
#endif
return f ;
}
// Create single-thread task
template< class FunctorType >
Future< typename FunctorType::value_type , execution_space >
create( const FunctorType & functor
, const unsigned dependence_capacity = ~0u ) const
{
typedef typename FunctorType::value_type value_type ;
typedef Impl::TaskMember< execution_space , value_type , FunctorType > task_type ;
return Future< value_type , execution_space >(
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
task_root_type::create_single< task_type >
( functor
, m_active_count
, ( ~0u == dependence_capacity ? m_default_dependence_capacity : dependence_capacity )
)
#endif
);
}
// Create thread-team task
template< class FunctorType >
KOKKOS_INLINE_FUNCTION
Future< typename FunctorType::value_type , execution_space >
create_team( const FunctorType & functor
, const unsigned dependence_capacity = ~0u ) const
{
typedef typename FunctorType::value_type value_type ;
typedef Impl::TaskMember< execution_space , value_type , FunctorType > task_type ;
return Future< value_type , execution_space >(
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
task_root_type::create_team< task_type >
( functor
, m_active_count
, ( ~0u == dependence_capacity ? m_default_dependence_capacity : dependence_capacity )
, 1 < m_team_size
)
#endif
);
}
// Add dependence
template< class A1 , class A2 , class A3 , class A4 >
void add_dependence( const Future<A1,A2> & after
, const Future<A3,A4> & before
, typename Kokkos::Impl::enable_if
< Kokkos::Impl::is_same< typename Future<A1,A2>::execution_space , execution_space >::value
&&
Kokkos::Impl::is_same< typename Future<A3,A4>::execution_space , execution_space >::value
>::type * = 0
)
{
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
after.m_task->add_dependence( before.m_task );
#endif
}
//----------------------------------------
// Functions for an executing task functor to query dependences,
// set new dependences, and respawn itself.
template< class FunctorType >
Future< void , execution_space >
get_dependence( const FunctorType * task_functor , int i ) const
{
return Future<void,execution_space>(
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
get_task_root(task_functor)->get_dependence(i)
#endif
);
}
template< class FunctorType >
int get_dependence( const FunctorType * task_functor ) const
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
{ return get_task_root(task_functor)->get_dependence(); }
#else
{ return 0 ; }
#endif
template< class FunctorType >
void clear_dependence( FunctorType * task_functor ) const
{
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
get_task_root(task_functor)->clear_dependence();
#endif
}
template< class FunctorType , class A3 , class A4 >
void add_dependence( FunctorType * task_functor
, const Future<A3,A4> & before
, typename Kokkos::Impl::enable_if
< Kokkos::Impl::is_same< typename Future<A3,A4>::execution_space , execution_space >::value
>::type * = 0
)
{
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
get_task_root(task_functor)->add_dependence( before.m_task );
#endif
}
template< class FunctorType >
void respawn( FunctorType * task_functor ) const
#if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST )
{ get_task_root(task_functor)->respawn(); }
#else
{}
#endif
static member_type & member_single();
friend void wait( TaskPolicy< Kokkos::Qthread > & );
};
} /* namespace Experimental */
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#endif /* #define KOKKOS_QTHREAD_TASK_HPP */
|
qipa/lammps
|
lib/kokkos/core/src/Qthread/Kokkos_Qthread_TaskPolicy.hpp
|
C++
|
gpl-2.0
| 23,470
|
<?php
/* Icon with text shortcode */
if(!function_exists('icon_text')) {
function icon_text($atts, $content = null) {
global $qodeIconCollections;
$default_atts = array(
"icon_size" => "",
"use_custom_icon_size" => "",
"custom_icon_size" => "",
"custom_icon_size_inner" => "",
"custom_icon_margin" => "",
"icon_animation" => "",
"icon_animation_delay" => "",
"image" => "",
"icon_type" => "",
"icon_position" => "",
"icon_border_color" => "",
"icon_margin" => "",
"icon_color" => "",
"icon_hover_color" => "",
"icon_background_color" => "",
"icon_hover_background_color" => "",
"box_type" => "",
"box_border_color" => "",
"box_background_color" => "",
"title" => "",
"title_tag" => "h5",
"title_color" => "",
"title_font_weight" => "",
"separator" => "",
"separator_color" => "",
"separator_top_margin" => "0",
"separator_bottom_margin" => "15",
"separator_width" => "20",
"text" => "",
"text_color" => "",
"link" => "",
"link_text" => "",
"link_color" => "",
"link_icon" => "",
"target" => ""
);
$default_atts = array_merge($default_atts, $qodeIconCollections->getShortcodeParams());
extract(shortcode_atts($default_atts, $atts));
$headings_array = array('h2', 'h3', 'h4', 'h5', 'h6');
//get correct heading value. If provided heading isn't valid get the default one
$title_tag = (in_array($title_tag, $headings_array)) ? $title_tag : $args['title_tag'];
//init icon styles
$style = '';
$icon_stack_classes = '';
//init icon stack styles
$icon_margin_style = '';
$icon_stack_square_style = '';
$icon_stack_base_style = '';
$icon_stack_style = '';
$img_styles = '';
$animation_delay_style = '';
$icon_text_holder_styles = '';
//generate inline icon styles
if($use_custom_icon_size == "yes") {
if($custom_icon_size != "") {
//remove px if user has entered it
$custom_icon_size = strstr($custom_icon_size, 'px', true) ? strstr($custom_icon_size, 'px', true) : $custom_icon_size;
$icon_stack_style .= 'font-size: '.$custom_icon_size.'px;';
}
if($custom_icon_margin != "") {
//remove px if user has entered it
$custom_icon_margin = strstr($custom_icon_margin, 'px', true) ? strstr($custom_icon_margin, 'px', true) : $custom_icon_margin;
$custom_icon_margin = $custom_icon_size + $custom_icon_margin;
if($icon_position !== 'right') {
$icon_text_holder_styles .= 'padding-left:'.$custom_icon_margin.'px;';
} else {
$icon_text_holder_styles .= 'padding-right:'.$custom_icon_margin.'px;';
}
}
if($custom_icon_size_inner != '' && in_array($icon_type, array('circle', 'square'))) {
$style .= 'font-size: '.$custom_icon_size_inner.'px;';
}
}
if($icon_color != "") {
$style .= 'color: '.$icon_color.';';
}
//generate icon stack styles
if($icon_background_color != "") {
$icon_stack_base_style .= 'background-color: '.$icon_background_color.';';
$icon_stack_square_style .= 'background-color: '.$icon_background_color.';';
}
if($icon_border_color != "") {
$icon_stack_style .= 'border-color: '.$icon_border_color.';';
}
if($icon_margin != "" && ($icon_position == "" || $icon_position == "top")) {
$icon_margin_style .= "margin: ".$icon_margin.";";
$img_styles .= "margin: ".$icon_margin.";";
}
if($icon_animation_delay != ""){
$animation_delay_style .= 'transition-delay: '.$icon_animation_delay.'ms; -webkit-transition-delay: '.$icon_animation_delay.'ms; -moz-transition-delay: '.$icon_animation_delay.'ms; -o-transition-delay: '.$icon_animation_delay.'ms;';
}
$box_size = '';
//generate icon text holder styles and classes
//map value of the field to the actual class value
switch ($icon_size) {
case 'large': //smallest icon size
$box_size = 'tiny';
break;
case 'fa-2x':
$box_size = 'small';
break;
case 'fa-3x':
$box_size = 'medium';
break;
case 'fa-4x':
$box_size = 'large';
break;
case 'fa-5x':
$box_size = 'very_large';
break;
default:
$box_size = 'tiny';
}
if($image != "") {
$icon_type = 'image';
}
$box_icon_type = '';
switch ($icon_type) {
case 'normal':
$box_icon_type = 'normal_icon';
break;
case 'square':
$box_icon_type = 'square';
break;
case 'circle':
$box_icon_type = 'circle';
break;
case 'image':
if($box_type == 'normal') {
$box_icon_type = 'custom_icon_image';
} else {
$box_icon_type = 'image';
}
break;
}
/* Generate text styles */
$title_style = "";
if($title_color != "") {
$title_style .= "color: ".$title_color.";";
}
if($title_font_weight !== "") {
$title_style .= "font-weight: ".$title_font_weight.";";
}
$text_style = "";
if($text_color != "") {
$text_style .= "color: ".$text_color;
}
$link_style = "";
if($link_color != "") {
$link_style .= "color: ".$link_color.";";
}
$html = "";
$html_icon = "";
if($link_icon == 'yes' && $link !== '') {
$html_icon .= '<a href="'.$link.'" target="'.$target.'" class="q_icon_link">';
}
//have to set default because of already created shortcodes
$icon_pack = $icon_pack == '' ? 'font_awesome' : $icon_pack;
if($image == "") {
//genererate icon html
switch ($icon_type) {
case 'circle':
$html_icon .= '<span '.qode_get_inline_attr($icon_type, 'data-icon-type').' '.qode_get_inline_attr($icon_hover_color, 'data-icon-hover-color').' '.qode_get_inline_attr($icon_hover_background_color, 'data-icon-hover-bg-color').' class="qode_iwt_icon_holder fa-stack '.$icon_size.' '.$icon_stack_classes.'" style="'.$icon_stack_style . $icon_stack_base_style .'">';
$html_icon .= $qodeIconCollections->getIconHTML(
${$qodeIconCollections->getIconCollectionParamNameByKey($icon_pack)},
$icon_pack,
array('icon_attributes' => array('style' => $style, 'class' => 'qode_iwt_icon_element')));
$html_icon .= '</span>';
break;
case 'square':
$html_icon .= '<span '.qode_get_inline_attr($icon_type, 'data-icon-type').' '.qode_get_inline_attr($icon_hover_color, 'data-icon-hover-color').' '.qode_get_inline_attr($icon_hover_background_color, 'data-icon-hover-bg-color').' class="qode_iwt_icon_holder fa-stack '.$icon_size.' '.$icon_stack_classes.'" style="'.$icon_stack_style.$icon_stack_square_style.'">';
$html_icon .= $qodeIconCollections->getIconHTML(
${$qodeIconCollections->getIconCollectionParamNameByKey($icon_pack)},
$icon_pack,
array('icon_attributes' => array('style' => $style, 'class' => 'qode_iwt_icon_element')));
$html_icon .= '</span>';
break;
default:
$html_icon .= '<span '.qode_get_inline_attr($icon_type, 'data-icon-type').' '.qode_get_inline_attr($icon_hover_color, 'data-icon-hover-color').' style="'.$icon_stack_style.'" class="qode_iwt_icon_holder q_font_awsome_icon '.$icon_size.' '.$icon_stack_classes.'">';
$html_icon .= $qodeIconCollections->getIconHTML(
${$qodeIconCollections->getIconCollectionParamNameByKey($icon_pack)},
$icon_pack,
array('icon_attributes' => array('style' => $style, 'class' => 'qode_iwt_icon_element')));
$html_icon .= '</span>';
break;
}
} else {
if(is_numeric($image)) {
$image_src = wp_get_attachment_url( $image );
}else {
$image_src = $image;
}
$html_icon = '<img style="'.$img_styles.'" src="'.$image_src.'" alt="">';
}
if($link_icon == 'yes' && $link !== '') {
$html_icon .= '</a>';
}
//generate normal type of a box html
if($box_type == "normal") {
//init icon text wrapper styles
$icon_with_text_clasess = '';
$icon_with_text_style = '';
$icon_text_inner_style = '';
$icon_with_text_clasess .= $box_size;
$icon_with_text_clasess .= ' '.$box_icon_type;
if($box_border_color != "") {
$icon_text_inner_style .= 'border-color: '.$box_border_color;
}
if($icon_position == "" || $icon_position == "top") {
$icon_with_text_clasess .= " center";
}
if($icon_position == "left_from_title"){
$icon_with_text_clasess .= " left_from_title";
}
if($icon_position == 'right') {
$icon_with_text_clasess .= ' right';
}
$html .= "<div class='q_icon_with_title ".$icon_with_text_clasess."'>";
if($icon_position != "left_from_title") {
//generate icon holder html part with icon
$html .= '<div class="icon_holder '.$icon_animation.'" style="'.$icon_margin_style.' '.$animation_delay_style.'">';
$html .= $html_icon;
$html .= '</div>'; //close icon_holder
}
//generate text html
$html .= '<div class="icon_text_holder" style="'.$icon_text_holder_styles.'">';
$html .= '<div class="icon_text_inner" style="'.$icon_text_inner_style.'">';
if($icon_position == "left_from_title") {
$html .= '<div class="icon_title_holder">'; //generate icon_title holder for icon from title
//generate icon holder html part with icon
$html .= '<div class="icon_holder '.$icon_animation.'" style="'.$icon_margin_style.' '.$animation_delay_style.'">';
$html .= $html_icon;
$html .= '</div>'; //close icon_holder
}
$html .= '<'.$title_tag.' class="icon_title" style="'.$title_style.'">'.$title.'</'.$title_tag.'>';
if($icon_position == "left_from_title") {
$html .= '</div>'; //close icon_title holder for icon from title
}
if($separator == "yes") {
$html .= do_shortcode('[vc_separator type="small" position="left" color="'.$separator_color.'" thickness="2" width="'.$separator_width.'" up="'.$separator_top_margin.'" down="'.$separator_bottom_margin.'"]');
}
$html .= "<p style='".$text_style."'>".$text."</p>";
if($link != ""){
if($target == ""){
$target = "_self";
}
if($link_text == ""){
$link_text = "Read More";
}
$html .= "<a class='icon_with_title_link' href='".$link."' target='".$target."' style='".$link_style."'>".$link_text."</a>";
}
$html .= '</div>'; //close icon_text_inner
$html .= '</div>'; //close icon_text_holder
$html.= '</div>'; //close icon_with_title
} else {
//init icon text wrapper styles
$icon_with_text_clasess = '';
$box_holder_styles = '';
if($box_border_color != "") {
$box_holder_styles .= 'border-color: '.$box_border_color.';';
}
if($box_background_color != "") {
$box_holder_styles .= 'background-color: '.$box_background_color.';';
}
$icon_with_text_clasess .= $box_size;
$icon_with_text_clasess .= ' '.$box_icon_type;
$html .= '<div class="q_box_holder with_icon" style="'.$box_holder_styles.'">';
$html .= '<div class="box_holder_icon">';
$html .= '<div class="box_holder_icon_inner '.$icon_with_text_clasess.' '.$icon_animation.'" style="'.$animation_delay_style.'">';
$html .= $html_icon;
$html .= '</div>'; //close box_holder_icon_inner
$html .= '</div>'; //close box_holder_icon
//generate text html
$html .= '<div class="box_holder_inner '.$box_size.' center">';
$html .= '<'.$title_tag.' class="icon_title" style="'.$title_style.'">'.$title.'</'.$title_tag.'>';
if($separator == "yes") {
$html .= do_shortcode('[vc_separator type="small" position="left" color="'.$separator_color.'" thickness="2" width="'.$separator_width.'" up="'.$separator_top_margin.'" down="'.$separator_bottom_margin.'"]');
}else{
$html .= '<span class="separator transparent" style="margin: 8px 0;"></span>';
}
$html .= '<p style="'.$text_style.'">'.$text.'</p>';
$html .= '</div>'; //close box_holder_inner
$html .= '</div>'; //close box_holder
}
return $html;
}
add_shortcode('icon_text', 'icon_text');
}
|
hslincoln/reflex
|
wp-content/themes/reflex/includes/shortcodes/shortcode-elements/icon-text.php
|
PHP
|
gpl-2.0
| 15,110
|
<?php
namespace TYPO3\CMS\Backend\Form\Container;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface;
use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Resource\ProcessedFile;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Utility\StringUtility;
use TYPO3\CMS\Lang\LanguageService;
use TYPO3\CMS\Backend\Utility\IconUtility;
use TYPO3\CMS\Core\Type\Bitmask\Permission;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Database\RelationHandler;
use TYPO3\CMS\Core\Database\DatabaseConnection;
use TYPO3\CMS\Backend\Form\InlineStackProcessor;
use TYPO3\CMS\Backend\Form\InlineRelatedRecordResolver;
use TYPO3\CMS\Backend\Form\Exception\AccessDeniedException;
use TYPO3\CMS\Backend\Form\NodeFactory;
/**
* Render a single inline record relation.
*
* This container is called by InlineControlContainer to render single existing records.
* Furthermore it is called by FormEngine for an incoming ajax request to expand an existing record
* or to create a new one.
*
* This container creates the outer HTML of single inline records - eg. drag and drop and delete buttons.
* For rendering of the record itself processing is handed over to FullRecordContainer.
*/
class InlineRecordContainer extends AbstractContainer {
/**
* Inline data array used for JSON output
*
* @var array
*/
protected $inlineData = array();
/**
* @var InlineStackProcessor
*/
protected $inlineStackProcessor;
/**
* Array containing instances of hook classes called once for IRRE objects
*
* @var array
*/
protected $hookObjects = array();
/**
* Entry method
*
* @return array As defined in initializeResultArray() of AbstractNode
*/
public function render() {
$this->inlineData = $this->globalOptions['inlineData'];
/** @var InlineStackProcessor $inlineStackProcessor */
$inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
$this->inlineStackProcessor = $inlineStackProcessor;
$inlineStackProcessor->initializeByGivenStructure($this->globalOptions['inlineStructure']);
$this->initHookObjects();
$row = $this->globalOptions['databaseRow'];
$parentUid = $row['uid'];
$record = $this->globalOptions['inlineRelatedRecordToRender'];
$config = $this->globalOptions['inlineRelatedRecordConfig'];
$foreign_table = $config['foreign_table'];
$foreign_selector = $config['foreign_selector'];
$resultArray = $this->initializeResultArray();
$html = '';
// Send a mapping information to the browser via JSON:
// e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
$formPrefix = $inlineStackProcessor->getCurrentStructureFormPrefix();
$domObjectId = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->globalOptions['inlineFirstPid']);
$this->inlineData['map'][$formPrefix] = $domObjectId;
$resultArray['inlineData'] = $this->inlineData;
// Set this variable if we handle a brand new unsaved record:
$isNewRecord = !MathUtility::canBeInterpretedAsInteger($record['uid']);
// Set this variable if the record is virtual and only show with header and not editable fields:
$isVirtualRecord = isset($record['__virtual']) && $record['__virtual'];
// If there is a selector field, normalize it:
if ($foreign_selector) {
$record[$foreign_selector] = $this->normalizeUid($record[$foreign_selector]);
}
if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $record['uid'])) {
// This is caught by InlineControlContainer or FormEngine, they need to handle this case differently
throw new AccessDeniedException('Access denied', 1437081986);
}
// Get the current naming scheme for DOM name/id attributes:
$appendFormFieldNames = '[' . $foreign_table . '][' . $record['uid'] . ']';
$objectId = $domObjectId . '-' . $foreign_table . '-' . $record['uid'];
$class = '';
$html = '';
$combinationHtml = '';
if (!$isVirtualRecord) {
// Get configuration:
$collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
$expandAll = isset($config['appearance']['collapseAll']) && !$config['appearance']['collapseAll'];
$ajaxLoad = !isset($config['appearance']['ajaxLoad']) || $config['appearance']['ajaxLoad'];
if ($isNewRecord) {
// Show this record expanded or collapsed
$isExpanded = $expandAll || (!$collapseAll ? 1 : 0);
} else {
$isExpanded = $config['renderFieldsOnly'] || !$collapseAll && $this->getExpandedCollapsedState($foreign_table, $record['uid']) || $expandAll;
}
// Render full content ONLY IF this is an AJAX request, a new record, the record is not collapsed or AJAX loading is explicitly turned off
if ($isNewRecord || $isExpanded || !$ajaxLoad) {
$combinationChildArray = $this->renderCombinationTable($record, $appendFormFieldNames, $config);
$combinationHtml = $combinationChildArray['html'];
$resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $combinationChildArray);
$overruleTypesArray = isset($config['foreign_types']) ? $config['foreign_types'] : array();
$childArray = $this->renderRecord($foreign_table, $record, $overruleTypesArray);
$html = $childArray['html'];
$childArray['html'] = '';
$resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray);
// Replace returnUrl in Wizard-Code, if this is an AJAX call
$ajaxArguments = GeneralUtility::_GP('ajax');
if (isset($ajaxArguments[2]) && trim($ajaxArguments[2]) != '') {
$html = str_replace('P[returnUrl]=%2F' . rawurlencode(TYPO3_mainDir) . 'ajax.php', 'P[returnUrl]=' . rawurlencode($ajaxArguments[2]), $html);
}
} else {
// This string is the marker for the JS-function to check if the full content has already been loaded
$html = '<!--notloaded-->';
}
if ($isNewRecord) {
// Get the top parent table
$top = $this->inlineStackProcessor->getStructureLevel(0);
$ucFieldName = 'uc[inlineView][' . $top['table'] . '][' . $top['uid'] . ']' . $appendFormFieldNames;
// Set additional fields for processing for saving
$html .= '<input type="hidden" name="data' . $appendFormFieldNames . '[pid]" value="' . $record['pid'] . '"/>';
$html .= '<input type="hidden" name="' . $ucFieldName . '" value="' . $isExpanded . '" />';
} else {
// Set additional field for processing for saving
$html .= '<input type="hidden" name="cmd' . $appendFormFieldNames . '[delete]" value="1" disabled="disabled" />';
if (!$isExpanded
&& !empty($GLOBALS['TCA'][$foreign_table]['ctrl']['enablecolumns']['disabled'])
&& $ajaxLoad
) {
$checked = !empty($record['hidden']) ? ' checked="checked"' : '';
$html .= '<input type="checkbox" name="data' . $appendFormFieldNames . '[hidden]_0" value="1"' . $checked . ' />';
$html .= '<input type="input" name="data' . $appendFormFieldNames . '[hidden]" value="' . $record['hidden'] . '" />';
}
}
// If this record should be shown collapsed
$class = $isExpanded ? 'panel-visible' : 'panel-collapsed';
}
if ($config['renderFieldsOnly']) {
$html = $html . $combinationHtml;
} else {
// Set the record container with data for output
if ($isVirtualRecord) {
$class .= ' t3-form-field-container-inline-placeHolder';
}
if (isset($record['hidden']) && (int)$record['hidden']) {
$class .= ' t3-form-field-container-inline-hidden';
}
$class .= ($isNewRecord ? ' inlineIsNewRecord' : '');
$html = '
<div class="panel panel-default panel-condensed ' . trim($class) . '" id="' . $objectId . '_div">
<div class="panel-heading" data-toggle="formengine-inline" id="' . $objectId . '_header" data-expandSingle="' . ($config['appearance']['expandSingle'] ? 1 : 0) . '">
<div class="form-irre-header">
<div class="form-irre-header-cell form-irre-header-icon">
<span class="caret"></span>
</div>
' . $this->renderForeignRecordHeader($parentUid, $foreign_table, $record, $config, $isVirtualRecord) . '
</div>
</div>
<div class="panel-collapse" id="' . $objectId . '_fields" data-expandSingle="' . ($config['appearance']['expandSingle'] ? 1 : 0) . '" data-returnURL="' . htmlspecialchars(GeneralUtility::getIndpEnv('REQUEST_URI')) . '">' . $html . $combinationHtml . '</div>
</div>';
}
$resultArray['html'] = $html;
return $resultArray;
}
/**
* Creates main container for foreign record and renders it
*
* @param string $table The table name
* @param array $row The record to be rendered
* @param array $overruleTypesArray Overrule TCA [types] array, e.g to override [showitem] configuration of a particular type
* @return string The rendered form
*/
protected function renderRecord($table, array $row, array $overruleTypesArray = array()) {
$domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->globalOptions['inlineFirstPid']);
$options = $this->globalOptions;
$options['inlineData'] = $this->inlineData;
$options['databaseRow'] = $row;
$options['table'] = $table;
$options['tabAndInlineStack'][] = array(
'inline',
$domObjectId . '-' . $table . '-' . $row['uid'],
);
$options['overruleTypesArray'] = $overruleTypesArray;
$options['renderType'] = 'fullRecordContainer';
/** @var NodeFactory $nodeFactory */
$nodeFactory = $this->globalOptions['nodeFactory'];
return $nodeFactory->create($options)->render();
}
/**
* Render a table with FormEngine, that occurs on an intermediate table but should be editable directly,
* so two tables are combined (the intermediate table with attributes and the sub-embedded table).
* -> This is a direct embedding over two levels!
*
* @param array $record The table record of the child/embedded table (normaly post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor)
* @param string $appendFormFieldNames The [<table>][<uid>] of the parent record (the intermediate table)
* @param array $config content of $PA['fieldConf']['config']
* @return array As defined in initializeResultArray() of AbstractNode
* @todo: Maybe create another container from this?
*/
protected function renderCombinationTable($record, $appendFormFieldNames, $config = array()) {
$resultArray = $this->initializeResultArray();
$foreign_table = $config['foreign_table'];
$foreign_selector = $config['foreign_selector'];
if ($foreign_selector && $config['appearance']['useCombination']) {
$comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
// If record does already exist, load it:
if ($record[$foreign_selector] && MathUtility::canBeInterpretedAsInteger($record[$foreign_selector])) {
$inlineRelatedRecordResolver = GeneralUtility::makeInstance(InlineRelatedRecordResolver::class);
$comboRecord = $inlineRelatedRecordResolver->getRecord($comboConfig['foreign_table'], $record[$foreign_selector]);
$isNewRecord = FALSE;
} else {
$inlineRelatedRecordResolver = GeneralUtility::makeInstance(InlineRelatedRecordResolver::class);
$comboRecord = $inlineRelatedRecordResolver->getNewRecord($this->globalOptions['inlineFirstPid'], $comboConfig['foreign_table']);
$isNewRecord = TRUE;
}
// Display Warning FlashMessage if it is not suppressed
if (!isset($config['appearance']['suppressCombinationWarning']) || empty($config['appearance']['suppressCombinationWarning'])) {
$combinationWarningMessage = 'LLL:EXT:lang/locallang_core.xlf:warning.inline_use_combination';
if (!empty($config['appearance']['overwriteCombinationWarningMessage'])) {
$combinationWarningMessage = $config['appearance']['overwriteCombinationWarningMessage'];
}
$flashMessage = GeneralUtility::makeInstance(
FlashMessage::class,
$this->getLanguageService()->sL($combinationWarningMessage),
'',
FlashMessage::WARNING
);
$resultArray['html'] = $flashMessage->render();
}
// Get the FormEngine interpretation of the TCA of the child table
$childArray = $this->renderRecord($comboConfig['foreign_table'], $comboRecord);
$resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray);
// If this is a new record, add a pid value to store this record and the pointer value for the intermediate table
if ($isNewRecord) {
$comboFormFieldName = 'data[' . $comboConfig['foreign_table'] . '][' . $comboRecord['uid'] . '][pid]';
$resultArray['html'] .= '<input type="hidden" name="' . $comboFormFieldName . '" value="' . $comboRecord['pid'] . '" />';
}
// If the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
if ($isNewRecord || $config['foreign_unique'] === $foreign_selector) {
$parentFormFieldName = 'data' . $appendFormFieldNames . '[' . $foreign_selector . ']';
$resultArray['html'] .= '<input type="hidden" name="' . $parentFormFieldName . '" value="' . $comboRecord['uid'] . '" />';
}
}
return $resultArray;
}
/**
* Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
* Later on the command-icons are inserted here.
*
* @param string $parentUid The uid of the parent (embedding) record (uid or NEW...)
* @param string $foreign_table The foreign_table we create a header for
* @param array $rec The current record of that foreign_table
* @param array $config content of $PA['fieldConf']['config']
* @param bool $isVirtualRecord
* @return string The HTML code of the header
*/
protected function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord = FALSE) {
// Init:
$domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->globalOptions['inlineFirstPid']);
$objectId = $domObjectId . '-' . $foreign_table . '-' . $rec['uid'];
// We need the returnUrl of the main script when loading the fields via AJAX-call (to correct wizard code, so include it as 3rd parameter)
// Pre-Processing:
$isOnSymmetricSide = RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
$hasForeignLabel = (bool)(!$isOnSymmetricSide && $config['foreign_label']);
$hasSymmetricLabel = (bool)$isOnSymmetricSide && $config['symmetric_label'];
// Get the record title/label for a record:
// Try using a self-defined user function only for formatted labels
if (isset($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc'])) {
$params = array(
'table' => $foreign_table,
'row' => $rec,
'title' => '',
'isOnSymmetricSide' => $isOnSymmetricSide,
'options' => isset($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc_options'])
? $GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc_options']
: array(),
'parent' => array(
'uid' => $parentUid,
'config' => $config
)
);
// callUserFunction requires a third parameter, but we don't want to give $this as reference!
$null = NULL;
GeneralUtility::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc'], $params, $null);
$recTitle = $params['title'];
// Try using a normal self-defined user function
} elseif (isset($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'])) {
$params = array(
'table' => $foreign_table,
'row' => $rec,
'title' => '',
'isOnSymmetricSide' => $isOnSymmetricSide,
'parent' => array(
'uid' => $parentUid,
'config' => $config
)
);
// callUserFunction requires a third parameter, but we don't want to give $this as reference!
$null = NULL;
GeneralUtility::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
$recTitle = $params['title'];
} elseif ($hasForeignLabel || $hasSymmetricLabel) {
$titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
$foreignConfig = FormEngineUtility::getInlinePossibleRecordsSelectorConfig($config, $titleCol);
// Render title for everything else than group/db:
if ($foreignConfig['type'] !== 'groupdb') {
$recTitle = BackendUtility::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, FALSE);
} else {
// $recTitle could be something like: "tx_table_123|...",
$valueParts = GeneralUtility::trimExplode('|', $rec[$titleCol]);
$itemParts = GeneralUtility::revExplode('_', $valueParts[0], 2);
$recTemp = BackendUtility::getRecordWSOL($itemParts[0], $itemParts[1]);
$recTitle = BackendUtility::getRecordTitle($itemParts[0], $recTemp, FALSE);
}
$recTitle = BackendUtility::getRecordTitlePrep($recTitle);
if (trim($recTitle) === '') {
$recTitle = BackendUtility::getNoRecordTitle(TRUE);
}
} else {
$recTitle = BackendUtility::getRecordTitle($foreign_table, $rec, TRUE);
}
$altText = BackendUtility::getRecordIconAltText($rec, $foreign_table);
$iconImg = IconUtility::getSpriteIconForRecord($foreign_table, $rec, array('title' => htmlspecialchars($altText), 'id' => $objectId . '_icon'));
$label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
$ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
$thumbnail = FALSE;
// Renders a thumbnail for the header
if (!empty($config['appearance']['headerThumbnail']['field'])) {
$fieldValue = $rec[$config['appearance']['headerThumbnail']['field']];
$firstElement = array_shift(GeneralUtility::trimExplode(',', $fieldValue));
$fileUid = array_pop(BackendUtility::splitTable_Uid($firstElement));
if (!empty($fileUid)) {
$fileObject = ResourceFactory::getInstance()->getFileObject($fileUid);
if ($fileObject && $fileObject->isMissing()) {
$flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
$thumbnail = $flashMessage->render();
} elseif ($fileObject) {
$imageSetup = $config['appearance']['headerThumbnail'];
unset($imageSetup['field']);
if (!empty($rec['crop'])) {
$imageSetup['crop'] = $rec['crop'];
}
$imageSetup = array_merge(array('width' => '45', 'height' => '45c'), $imageSetup);
$processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $imageSetup);
// Only use a thumbnail if the processing process was successful by checking if image width is set
if ($processedImage->getProperty('width')) {
$imageUrl = $processedImage->getPublicUrl(TRUE);
$thumbnail = '<img src="' . $imageUrl . '" ' .
'width="' . $processedImage->getProperty('width') . '" ' .
'height="' . $processedImage->getProperty('height') . '" ' .
'alt="' . htmlspecialchars($altText) . '" ' .
'title="' . htmlspecialchars($altText) . '">';
}
}
}
}
if (!empty($config['appearance']['headerThumbnail']['field']) && $thumbnail) {
$mediaContainer = '<div class="form-irre-header-cell form-irre-header-thumbnail" id="' . $objectId . '_thumbnailcontainer">' . $thumbnail . '</div>';
} else {
$mediaContainer = '<div class="form-irre-header-cell form-irre-header-icon" id="' . $objectId . '_iconcontainer">' . $iconImg . '</div>';
}
$header = $mediaContainer . '
<div class="form-irre-header-cell form-irre-header-body">' . $label . '</div>
<div class="form-irre-header-cell form-irre-header-control t3js-formengine-irre-control">' . $ctrl . '</div>';
return $header;
}
/**
* Render the control-icons for a record header (create new, sorting, delete, disable/enable).
* Most of the parts are copy&paste from TYPO3\CMS\Recordlist\RecordList\DatabaseRecordList and
* modified for the JavaScript calls here
*
* @param string $parentUid The uid of the parent (embedding) record (uid or NEW...)
* @param string $foreign_table The table (foreign_table) we create control-icons for
* @param array $rec The current record of that foreign_table
* @param array $config (modified) TCA configuration of the field
* @param bool $isVirtualRecord TRUE if the current record is virtual, FALSE otherwise
* @return string The HTML code with the control-icons
*/
protected function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config = array(), $isVirtualRecord = FALSE) {
$languageService = $this->getLanguageService();
$backendUser = $this->getBackendUserAuthentication();
// Initialize:
$cells = array();
$additionalCells = array();
$isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
$isParentExisting = MathUtility::canBeInterpretedAsInteger($parentUid);
$tcaTableCtrl = &$GLOBALS['TCA'][$foreign_table]['ctrl'];
$tcaTableCols = &$GLOBALS['TCA'][$foreign_table]['columns'];
$isPagesTable = $foreign_table === 'pages';
$isSysFileReferenceTable = $foreign_table === 'sys_file_reference';
$isOnSymmetricSide = RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
$enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || !$isOnSymmetricSide && $config['foreign_sortby'] || $isOnSymmetricSide && $config['symmetric_sortby'];
$nameObject = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->globalOptions['inlineFirstPid']);
$nameObjectFt = $nameObject . '-' . $foreign_table;
$nameObjectFtId = $nameObjectFt . '-' . $rec['uid'];
$calcPerms = $backendUser->calcPerms(BackendUtility::readPageAccess($rec['pid'], $backendUser->getPagePermsClause(1)));
// If the listed table is 'pages' we have to request the permission settings for each page:
$localCalcPerms = FALSE;
if ($isPagesTable) {
$localCalcPerms = $backendUser->calcPerms(BackendUtility::getRecord('pages', $rec['uid']));
}
// This expresses the edit permissions for this particular element:
$permsEdit = $isPagesTable && $localCalcPerms & Permission::PAGE_EDIT || !$isPagesTable && $calcPerms & Permission::CONTENT_EDIT;
// Controls: Defines which controls should be shown
$enabledControls = $config['appearance']['enabledControls'];
// Hook: Can disable/enable single controls for specific child records:
foreach ($this->hookObjects as $hookObj) {
/** @var InlineElementHookInterface $hookObj */
$hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $enabledControls);
}
if (isset($rec['__create'])) {
$cells['localize.isLocalizable'] = IconUtility::getSpriteIcon('actions-edit-localize-status-low', array('title' => $languageService->sL('LLL:EXT:lang/locallang_misc.xlf:localize.isLocalizable', TRUE)));
} elseif (isset($rec['__remove'])) {
$cells['localize.wasRemovedInOriginal'] = IconUtility::getSpriteIcon('actions-edit-localize-status-high', array('title' => $languageService->sL('LLL:EXT:lang/locallang_misc.xlf:localize.wasRemovedInOriginal', TRUE)));
}
// "Info": (All records)
if ($enabledControls['info'] && !$isNewItem) {
if ($rec['table_local'] === 'sys_file') {
$uid = (int)substr($rec['uid_local'], 9);
$table = '_FILE';
} else {
$uid = $rec['uid'];
$table = $foreign_table;
}
$cells['info'] = '
<a class="btn btn-default" href="#" onclick="' . htmlspecialchars(('top.launchView(' . GeneralUtility::quoteJSvalue($table) . ', ' . GeneralUtility::quoteJSvalue($uid) . '); return false;')) . '">
' . IconUtility::getSpriteIcon('status-dialog-information', array('title' => $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:showInfo', TRUE))) . '
</a>';
}
// If the table is NOT a read-only table, then show these links:
if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord) {
// "New record after" link (ONLY if the records in the table are sorted by a "sortby"-row or if default values can depend on previous record):
if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
if (!$isPagesTable && $calcPerms & Permission::CONTENT_EDIT || $isPagesTable && $calcPerms & Permission::PAGE_NEW) {
$onClick = 'return inline.createNewRecord(' . GeneralUtility::quoteJSvalue($nameObjectFt) . ',' . GeneralUtility::quoteJSvalue($rec['uid']) . ')';
$style = '';
if ($config['inline']['inlineNewButtonStyle']) {
$style = ' style="' . $config['inline']['inlineNewButtonStyle'] . '"';
}
$cells['new'] = '
<a class="btn btn-default inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'] . '" href="#" onclick="' . htmlspecialchars($onClick) . '"' . $style . '>
' . IconUtility::getSpriteIcon(('actions-' . ($isPagesTable ? 'page' : 'document') . '-new'), array('title' => $languageService->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:new' . ($isPagesTable ? 'Page' : 'Record')), TRUE))) . '
</a>';
}
}
// "Up/Down" links
if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
// Up
$onClick = 'return inline.changeSorting(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ', \'1\')';
$style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
$cells['sort.up'] = '
<a class="btn btn-default sortingUp" href="#" onclick="' . htmlspecialchars($onClick) . '" ' . $style . '>
' . IconUtility::getSpriteIcon('actions-move-up', array('title' => $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:moveUp', TRUE))) . '
</a>';
// Down
$onClick = 'return inline.changeSorting(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ', \'-1\')';
$style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
$cells['sort.down'] = '
<a class="btn btn-default sortingDown" href="#" onclick="' . htmlspecialchars($onClick) . '" ' . $style . '>
' . IconUtility::getSpriteIcon('actions-move-down', array('title' => $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:moveDown', TRUE))) . '
</a>';
}
// "Edit" link:
if (($rec['table_local'] === 'sys_file') && !$isNewItem) {
$recordInDatabase = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
'uid',
'sys_file_metadata',
'file = ' . (int)substr($rec['uid_local'], 9) . ' AND sys_language_uid = ' . $rec['sys_language_uid']
);
if ($backendUser->check('tables_modify', 'sys_file_metadata')) {
$url = BackendUtility::getModuleUrl('record_edit', array(
'edit[sys_file_metadata][' . (int)$recordInDatabase['uid'] . ']' => 'edit'
));
$editOnClick = 'if (top.content.list_frame) {' .
'top.content.list_frame.location.href=' .
GeneralUtility::quoteJSvalue($url . '&returnUrl=') .
'+top.rawurlencode(top.content.list_frame.document.location.pathname+top.content.list_frame.document.location.search)' .
';' .
'}';
$title = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:cm.editMetadata');
$cells['editmetadata'] = '
<a class="btn btn-default" href="#" class="btn" onclick="' . htmlspecialchars($editOnClick) . '" title="' . htmlspecialchars($title) . '">
' . IconUtility::getSpriteIcon('actions-document-open') . '
</a>';
}
}
// "Delete" link:
if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms & Permission::PAGE_DELETE
|| !$isPagesTable && $calcPerms & Permission::CONTENT_EDIT
|| $isSysFileReferenceTable && $calcPerms & Permission::PAGE_EDIT)) {
$onClick = 'inline.deleteRecord(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ');';
$cells['delete'] = '
<a class="btn btn-default" href="#" onclick="' . htmlspecialchars(('if (confirm(' . GeneralUtility::quoteJSvalue($languageService->getLL('deleteWarning')) . ')) { ' . $onClick . ' } return false;')) . '">
' . IconUtility::getSpriteIcon('actions-edit-delete', array('title' => $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:delete', TRUE))) . '
</a>';
}
// "Hide/Unhide" links:
$hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $backendUser->check('non_exclude_fields', $foreign_table . ':' . $hiddenField))) {
$onClick = 'return inline.enableDisableRecord(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ')';
if ($rec[$hiddenField]) {
$cells['hide.unhide'] = '
<a class="btn btn-default hiddenHandle" href="#" onclick="' . htmlspecialchars($onClick) . '">
' . IconUtility::getSpriteIcon('actions-edit-unhide', array('title' => $languageService->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:unHide' . ($isPagesTable ? 'Page' : '')), TRUE), 'id' => ($nameObjectFtId . '_disabled'))) . '
</a>';
} else {
$cells['hide.hide'] = '
<a class="btn btn-default hiddenHandle" href="#" onclick="' . htmlspecialchars($onClick) . '">
' . IconUtility::getSpriteIcon('actions-edit-hide', array('title' => $languageService->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:hide' . ($isPagesTable ? 'Page' : '')), TRUE), 'id' => ($nameObjectFtId . '_disabled'))) . '
</a>';
}
}
// Drag&Drop Sorting: Sortable handler for script.aculo.us
if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
$additionalCells['dragdrop'] = '
<span class="btn btn-default">
' . IconUtility::getSpriteIcon('actions-move-move', array('data-id' => $rec['uid'], 'class' => 'sortableHandle', 'title' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.move', TRUE))) . '
</span>';
}
} elseif ($isVirtualRecord && $isParentExisting) {
if ($enabledControls['localize'] && isset($rec['__create'])) {
$onClick = 'inline.synchronizeLocalizeRecords(' . GeneralUtility::quoteJSvalue($nameObjectFt) . ', ' . GeneralUtility::quoteJSvalue($rec['uid']) . ');';
$cells['localize'] = '
<a class="btn btn-default" href="#" onclick="' . htmlspecialchars($onClick) . '">
' . IconUtility::getSpriteIcon('actions-document-localize', array('title' => $languageService->sL('LLL:EXT:lang/locallang_misc.xlf:localize', TRUE))) . '
</a>';
}
}
// If the record is edit-locked by another user, we will show a little warning sign:
if ($lockInfo = BackendUtility::isRecordLocked($foreign_table, $rec['uid'])) {
$cells['locked'] = '
<a class="btn btn-default" href="#" onclick="alert(' . GeneralUtility::quoteJSvalue($lockInfo['msg']) . ');return false;">
' . IconUtility::getSpriteIcon('status-warning-in-use', array('title' => $lockInfo['msg'])) . '
</a>';
}
// Hook: Post-processing of single controls for specific child records:
foreach ($this->hookObjects as $hookObj) {
$hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $cells);
}
$out = '';
if (!empty($cells)) {
$out .= ' <div class="btn-group btn-group-sm" role="group">' . implode('', $cells) . '</div>';
}
if (!empty($additionalCells)) {
$out .= ' <div class="btn-group btn-group-sm" role="group">' . implode('', $additionalCells) . '</div>';
}
return $out;
}
/**
* Checks the page access rights (Code for access check mostly taken from alt_doc.php)
* as well as the table access rights of the user.
*
* @param string $cmd The command that should be performed ('new' or 'edit')
* @param string $table The table to check access for
* @param string $theUid The record uid of the table
* @return bool Returns TRUE is the user has access, or FALSE if not
*/
protected function checkAccess($cmd, $table, $theUid) {
$backendUser = $this->getBackendUserAuthentication();
// Checking if the user has permissions? (Only working as a precaution, because the final permission check is always down in TCE. But it's good to notify the user on beforehand...)
// First, resetting flags.
$hasAccess = FALSE;
// Admin users always have access:
if ($backendUser->isAdmin()) {
return TRUE;
}
// If the command is to create a NEW record...:
if ($cmd === 'new') {
// If the pid is numerical, check if it's possible to write to this page:
if (MathUtility::canBeInterpretedAsInteger($this->globalOptions['inlineFirstPid'])) {
$calcPRec = BackendUtility::getRecord('pages', $this->globalOptions['inlineFirstPid']);
if (!is_array($calcPRec)) {
return FALSE;
}
// Permissions for the parent page
$CALC_PERMS = $backendUser->calcPerms($calcPRec);
// If pages:
if ($table === 'pages') {
// Are we allowed to create new subpages?
$hasAccess = (bool)($CALC_PERMS & Permission::PAGE_NEW);
} else {
// Are we allowed to edit the page?
if ($table === 'sys_file_reference' && $this->isMediaOnPages($theUid)) {
$hasAccess = (bool)($CALC_PERMS & Permission::PAGE_EDIT);
}
if (!$hasAccess) {
// Are we allowed to edit content on this page?
$hasAccess = (bool)($CALC_PERMS & Permission::CONTENT_EDIT);
}
}
} else {
$hasAccess = TRUE;
}
} else {
// Edit:
$calcPRec = BackendUtility::getRecord($table, $theUid);
BackendUtility::fixVersioningPid($table, $calcPRec);
if (is_array($calcPRec)) {
// If pages:
if ($table === 'pages') {
$CALC_PERMS = $backendUser->calcPerms($calcPRec);
$hasAccess = (bool)($CALC_PERMS & Permission::PAGE_EDIT);
} else {
// Fetching pid-record first.
$CALC_PERMS = $backendUser->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
if ($table === 'sys_file_reference' && $this->isMediaOnPages($theUid)) {
$hasAccess = (bool)($CALC_PERMS & Permission::PAGE_EDIT);
}
if (!$hasAccess) {
$hasAccess = (bool)($CALC_PERMS & Permission::CONTENT_EDIT);
}
}
// Check internals regarding access
$isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
if ($hasAccess|| (int)$calcPRec['pid'] === 0 && $isRootLevelRestrictionIgnored) {
$hasAccess = (bool)$backendUser->recordEditAccessInternals($table, $calcPRec);
}
}
}
if (!$backendUser->check('tables_modify', $table)) {
$hasAccess = FALSE;
}
if (
!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'])
&& is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'])
) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'] as $_funcRef) {
$_params = array(
'table' => $table,
'uid' => $theUid,
'cmd' => $cmd,
'hasAccess' => $hasAccess
);
$hasAccess = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
}
}
if (!$hasAccess) {
$deniedAccessReason = $backendUser->errorMsg;
if ($deniedAccessReason) {
debug($deniedAccessReason);
}
}
return $hasAccess;
}
/**
* Checks if a uid of a child table is in the inline view settings.
*
* @param string $table Name of the child table
* @param int $uid uid of the the child record
* @return bool TRUE=expand, FALSE=collapse
*/
protected function getExpandedCollapsedState($table, $uid) {
$inlineView = $this->globalOptions['inlineExpandCollapseStateArray'];
// @todo Add checking/cleaning for unused tables, records, etc. to save space in uc-field
if (isset($inlineView[$table]) && is_array($inlineView[$table])) {
if (in_array($uid, $inlineView[$table]) !== FALSE) {
return TRUE;
}
}
return FALSE;
}
/**
* Normalize a relation "uid" published by transferData, like "1|Company%201"
*
* @param string $string A transferData reference string, containing the uid
* @return string The normalized uid
*/
protected function normalizeUid($string) {
$parts = explode('|', $string);
return $parts[0];
}
/**
* Initialized the hook objects for this class.
* Each hook object has to implement the interface
* \TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface
*
* @throws \UnexpectedValueException
* @return void
*/
protected function initHookObjects() {
$this->hookObjects = array();
if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
$tceformsInlineHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
if (is_array($tceformsInlineHook)) {
foreach ($tceformsInlineHook as $classData) {
$processObject = GeneralUtility::getUserObj($classData);
if (!$processObject instanceof InlineElementHookInterface) {
throw new \UnexpectedValueException('$processObject must implement interface ' . InlineElementHookInterface::class, 1202072000);
}
$this->hookObjects[] = $processObject;
}
}
}
}
/**
* Check if the record is a media element on a page.
*
* @param string $theUid Uid of the sys_file_reference record to be checked
* @return bool TRUE if the record has media in the column 'fieldname' and pages in the column 'tablenames'
*/
protected function isMediaOnPages($theUid) {
if (StringUtility::beginsWith($theUid, 'NEW')) {
return TRUE;
}
$row = BackendUtility::getRecord('sys_file_reference', $theUid);
return ($row['fieldname'] === 'media') && ($row['tablenames'] === 'pages');
}
/**
* @return BackendUserAuthentication
*/
protected function getBackendUserAuthentication() {
return $GLOBALS['BE_USER'];
}
/**
* @return DatabaseConnection
*/
protected function getDatabaseConnection() {
return $GLOBALS['TYPO3_DB'];
}
/**
* @return LanguageService
*/
protected function getLanguageService() {
return $GLOBALS['LANG'];
}
}
|
mneuhaus/TYPO3.CMS
|
typo3/sysext/backend/Classes/Form/Container/InlineRecordContainer.php
|
PHP
|
gpl-2.0
| 38,431
|
/*
Copyright (C) 2013 Rainmeter Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 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.
*/
#include "StdAfx.h"
#include "SkinRegistry.h"
#include "../Common/UnitTest.h"
TEST_CLASS(Library_SkinRegistry_Test)
{
public:
Library_SkinRegistry_Test()
{
std::vector<std::wstring> favorites;
m_SkinRegistry.Populate(L"..\\..\\..\\Library\\Test\\SkinRegistry\\", favorites);
}
TEST_METHOD(TestContents)
{
std::vector<SkinRegistry::File> files1;
files1.emplace_back(L"1.ini");
files1.emplace_back(L"1.ini");
std::vector<SkinRegistry::File> files3;
files3.emplace_back(L"1.ini");
files3.emplace_back(L"2.ini");
files3.emplace_back(L"3.ini");
Assert::AreEqual(5, m_SkinRegistry.GetFolderCount());
const auto& folderA1 = m_SkinRegistry.GetFolder(0);
Assert::AreEqual(L"A1", folderA1.name.c_str());
Assert::AreEqual((int16_t)1, folderA1.level);
Assert::IsTrue(folderA1.files.empty());
const auto& folderA1_B1 = m_SkinRegistry.GetFolder(1);
Assert::AreEqual(L"B1", folderA1_B1.name.c_str());
Assert::AreEqual((int16_t)2, folderA1_B1.level);
Assert::IsTrue(files1 == folderA1_B1.files);
const auto& folderA1_B2 = m_SkinRegistry.GetFolder(2);
Assert::AreEqual(L"B2", folderA1_B2.name.c_str());
Assert::AreEqual((int16_t)2, folderA1_B2.level);
Assert::IsTrue(files1 == folderA1_B2.files);
const auto& folderA1_B2_C1 = m_SkinRegistry.GetFolder(3);
Assert::AreEqual(L"C1", folderA1_B2_C1.name.c_str());
Assert::AreEqual((int16_t)3, folderA1_B2_C1.level);
Assert::IsTrue(files1 == folderA1_B2_C1.files);
const auto& folderA2 = m_SkinRegistry.GetFolder(4);
Assert::AreEqual(L"A2", folderA2.name.c_str());
Assert::AreEqual((int16_t)1, folderA2.level);
Assert::IsTrue(files3 == folderA2.files);
}
TEST_METHOD(TestFindFolderIndex)
{
Assert::AreEqual(3, m_SkinRegistry.FindFolderIndex(L"A1\\B2\\C1"));
Assert::AreEqual(-1, m_SkinRegistry.FindFolderIndex(L"A1\\B5\\C1"));
}
TEST_METHOD(TestFindIndexes)
{
const auto indexes1 = m_SkinRegistry.FindIndexes(L"A1\\B2", L"1.ini");
Assert::IsTrue(indexes1.folder == 2 && indexes1.file == 0);
const auto indexes2 = m_SkinRegistry.FindIndexes(L"A2", L"2.ini");
Assert::IsTrue(indexes2.folder == 4 && indexes2.file == 1);
const auto indexes3 = m_SkinRegistry.FindIndexes(L"A3", L"1.ini");
Assert::IsFalse(indexes3.IsValid());
}
TEST_METHOD(TestFindIndexesForID)
{
const auto indexes1 = m_SkinRegistry.FindIndexesForID(30002);
Assert::IsTrue(indexes1.folder == 2 && indexes1.file == 0);
const auto indexes2 = m_SkinRegistry.FindIndexesForID(30005);
Assert::IsTrue(indexes2.folder == 4 && indexes2.file == 1);
}
TEST_METHOD(TestGetFolderPath)
{
Assert::AreEqual(L"A1\\B2\\C1", m_SkinRegistry.GetFolderPath(3).c_str());
Assert::AreEqual(L"A2", m_SkinRegistry.GetFolderPath(4).c_str());
}
private:
SkinRegistry m_SkinRegistry;
};
|
pyq881120/rainmeter
|
Library/SkinRegistry_Test.cpp
|
C++
|
gpl-2.0
| 3,629
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.4">
<title>git-bisect(1)</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */
/* Remove comment around @import statement below when using as a custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}
audio,canvas,video{display:inline-block}
audio:not([controls]){display:none;height:0}
[hidden],template{display:none}
script{display:none!important}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body{margin:0}
a{background:transparent}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
body{-webkit-font-smoothing:antialiased}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.spread{width:100%}
p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:none}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ul.no-bullet{list-style:none}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite:before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7;font-weight:bold}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
body{tab-size:4}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}
.clearfix:after,.float-group:after{clear:both}
*:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed}
pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menu{color:rgba(0,0,0,.8)}
b.button:before,b.button:after{position:relative;top:-1px;font-weight:400}
b.button:before{content:"[";padding:0 3px 0 2px}
b.button:after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}
#header:after,#content:after,#footnotes:after,#footer:after{clear:both}
#content{margin-top:1.25em}
#content:before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}
#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span:before{content:"\00a0\2013\00a0"}
#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark:before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber:after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #efefed;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media only screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}
@media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
.sect1{padding-bottom:.625em}
@media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}}
.sect1+.sect1{border-top:1px solid #efefed}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0}
.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8}
.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1}
.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em}
.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal}
@media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}
@media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}
.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.listingblock>.content{position:relative}
.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999}
.listingblock:hover code[data-lang]:before{display:block}
.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999}
.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}
table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}
table.pyhltable td.code{padding-left:.75em;padding-right:0}
pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}
pre.pygments .lineno{display:inline-block;margin-right:.25em}
table.pyhltable .linenodiv{background:none!important;padding-right:0!important}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right}
.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)}
.quoteblock .quoteblock blockquote{padding:0 0 0 .75em}
.quoteblock .quoteblock blockquote:before{display:none}
.verseblock{margin:0 1em 1.25em 1em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract{margin:0 0 1.25em 0;display:block}
.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}
.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}
table.tableblock{max-width:100%;border-collapse:separate}
table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}
table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}
table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}
table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}
table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}
table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}
table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot{border-width:1px 0}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
td>div.verse{white-space:pre}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}
ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}
ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}
ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}
ul.inline>li>*{display:block}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist>table tr>td:first-of-type{padding:0 .75em;line-height:1}
.colist>table tr>td:last-of-type{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0}
.imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background-color:#00fafa}
.black{color:#000}
.black-background{background-color:#000}
.blue{color:#0000bf}
.blue-background{background-color:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background-color:#fa00fa}
.gray{color:#606060}
.gray-background{background-color:#7d7d7d}
.green{color:#006000}
.green-background{background-color:#007d00}
.lime{color:#00bf00}
.lime-background{background-color:#00fa00}
.maroon{color:#600000}
.maroon-background{background-color:#7d0000}
.navy{color:#000060}
.navy-background{background-color:#00007d}
.olive{color:#606000}
.olive-background{background-color:#7d7d00}
.purple{color:#600060}
.purple-background{background-color:#7d007d}
.red{color:#bf0000}
.red-background{background-color:#fa0000}
.silver{color:#909090}
.silver-background{background-color:#bcbcbc}
.teal{color:#006060}
.teal-background{background-color:#007d7d}
.white{color:#bfbfbf}
.white-background{background-color:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background-color:#fafa00}
span.icon>.fa{cursor:default}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]:after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@media print{@page{margin:1.25cm .75cm}
*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]:after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important}
.sect1{padding-bottom:0!important}
.sect1+.sect1{border:0!important}
#header>h1:first-child{margin-top:1.25rem}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span:before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]:before{display:block}
#footer{background:none!important;padding:0 .9375em}
#footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
</style>
</head>
<body class="manpage">
<div id="header">
<h1>git-bisect(1) Manual Page</h1>
<h2>NAME</h2>
<div class="sectionbody">
<p>git-bisect - Use binary search to find the commit that introduced a bug</p>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="_synopsis">SYNOPSIS</h2>
<div class="sectionbody">
<div class="verseblock">
<pre class="content"><em>git bisect</em> <subcommand> <options></pre>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_description">DESCRIPTION</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The command takes various subcommands, and different options depending
on the subcommand:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>git bisect start [--term-{old,good}=<term> --term-{new,bad}=<term>]
[--no-checkout] [<bad> [<good>...]] [--] [<paths>...]
git bisect (bad|new) [<rev>]
git bisect (good|old) [<rev>...]
git bisect terms [--term-good | --term-bad]
git bisect skip [(<rev>|<range>)...]
git bisect reset [<commit>]
git bisect visualize
git bisect replay <logfile>
git bisect log
git bisect run <cmd>...
git bisect help</pre>
</div>
</div>
<div class="paragraph">
<p>This command uses a binary search algorithm to find which commit in
your project’s history introduced a bug. You use it by first telling
it a "bad" commit that is known to contain the bug, and a "good"
commit that is known to be before the bug was introduced. Then <code>git
bisect</code> picks a commit between those two endpoints and asks you
whether the selected commit is "good" or "bad". It continues narrowing
down the range until it finds the exact commit that introduced the
change.</p>
</div>
<div class="paragraph">
<p>In fact, <code>git bisect</code> can be used to find the commit that changed
<strong>any</strong> property of your project; e.g., the commit that fixed a bug, or
the commit that caused a benchmark’s performance to improve. To
support this more general usage, the terms "old" and "new" can be used
in place of "good" and "bad", or you can choose your own terms. See
section "Alternate terms" below for more information.</p>
</div>
<div class="sect2">
<h3 id="_basic_bisect_commands_start_bad_good">Basic bisect commands: start, bad, good</h3>
<div class="paragraph">
<p>As an example, suppose you are trying to find the commit that broke a
feature that was known to work in version <code>v2.6.13-rc2</code> of your
project. You start a bisect session as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start
$ git bisect bad # Current version is bad
$ git bisect good v2.6.13-rc2 # v2.6.13-rc2 is known to be good</pre>
</div>
</div>
<div class="paragraph">
<p>Once you have specified at least one bad and one good commit, <code>git
bisect</code> selects a commit in the middle of that range of history,
checks it out, and outputs something similar to the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>Bisecting: 675 revisions left to test after this (roughly 10 steps)</pre>
</div>
</div>
<div class="paragraph">
<p>You should now compile the checked-out version and test it. If that
version works correctly, type</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect good</pre>
</div>
</div>
<div class="paragraph">
<p>If that version is broken, type</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect bad</pre>
</div>
</div>
<div class="paragraph">
<p>Then <code>git bisect</code> will respond with something like</p>
</div>
<div class="listingblock">
<div class="content">
<pre>Bisecting: 337 revisions left to test after this (roughly 9 steps)</pre>
</div>
</div>
<div class="paragraph">
<p>Keep repeating the process: compile the tree, test it, and depending
on whether it is good or bad run <code>git bisect good</code> or <code>git bisect bad</code>
to ask for the next commit that needs testing.</p>
</div>
<div class="paragraph">
<p>Eventually there will be no more revisions left to inspect, and the
command will print out a description of the first bad commit. The
reference <code>refs/bisect/bad</code> will be left pointing at that commit.</p>
</div>
</div>
<div class="sect2">
<h3 id="_bisect_reset">Bisect reset</h3>
<div class="paragraph">
<p>After a bisect session, to clean up the bisection state and return to
the original HEAD, issue the following command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect reset</pre>
</div>
</div>
<div class="paragraph">
<p>By default, this will return your tree to the commit that was checked
out before <code>git bisect start</code>. (A new <code>git bisect start</code> will also do
that, as it cleans up the old bisection state.)</p>
</div>
<div class="paragraph">
<p>With an optional argument, you can return to a different commit
instead:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect reset <commit></pre>
</div>
</div>
<div class="paragraph">
<p>For example, <code>git bisect reset bisect/bad</code> will check out the first
bad revision, while <code>git bisect reset HEAD</code> will leave you on the
current bisection commit and avoid switching commits at all.</p>
</div>
</div>
<div class="sect2">
<h3 id="_alternate_terms">Alternate terms</h3>
<div class="paragraph">
<p>Sometimes you are not looking for the commit that introduced a
breakage, but rather for a commit that caused a change between some
other "old" state and "new" state. For example, you might be looking
for the commit that introduced a particular fix. Or you might be
looking for the first commit in which the source-code filenames were
finally all converted to your company’s naming standard. Or whatever.</p>
</div>
<div class="paragraph">
<p>In such cases it can be very confusing to use the terms "good" and
"bad" to refer to "the state before the change" and "the state after
the change". So instead, you can use the terms "old" and "new",
respectively, in place of "good" and "bad". (But note that you cannot
mix "good" and "bad" with "old" and "new" in a single session.)</p>
</div>
<div class="paragraph">
<p>In this more general usage, you provide <code>git bisect</code> with a "new"
commit has some property and an "old" commit that doesn’t have that
property. Each time <code>git bisect</code> checks out a commit, you test if that
commit has the property. If it does, mark the commit as "new";
otherwise, mark it as "old". When the bisection is done, <code>git bisect</code>
will report which commit introduced the property.</p>
</div>
<div class="paragraph">
<p>To use "old" and "new" instead of "good" and bad, you must run <code>git
bisect start</code> without commits as argument and then run the following
commands to add the commits:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>git bisect old [<rev>]</pre>
</div>
</div>
<div class="paragraph">
<p>to indicate that a commit was before the sought change, or</p>
</div>
<div class="listingblock">
<div class="content">
<pre>git bisect new [<rev>...]</pre>
</div>
</div>
<div class="paragraph">
<p>to indicate that it was after.</p>
</div>
<div class="paragraph">
<p>To get a reminder of the currently used terms, use</p>
</div>
<div class="listingblock">
<div class="content">
<pre>git bisect terms</pre>
</div>
</div>
<div class="paragraph">
<p>You can get just the old (respectively new) term with <code>git bisect term
--term-old</code> or <code>git bisect term --term-good</code>.</p>
</div>
<div class="paragraph">
<p>If you would like to use your own terms instead of "bad"/"good" or
"new"/"old", you can choose any names you like (except existing bisect
subcommands like <code>reset</code>, <code>start</code>, …​) by starting the
bisection using</p>
</div>
<div class="listingblock">
<div class="content">
<pre>git bisect start --term-old <term-old> --term-new <term-new></pre>
</div>
</div>
<div class="paragraph">
<p>For example, if you are looking for a commit that introduced a
performance regression, you might use</p>
</div>
<div class="listingblock">
<div class="content">
<pre>git bisect start --term-old fast --term-new slow</pre>
</div>
</div>
<div class="paragraph">
<p>Or if you are looking for the commit that fixed a bug, you might use</p>
</div>
<div class="listingblock">
<div class="content">
<pre>git bisect start --term-new fixed --term-old broken</pre>
</div>
</div>
<div class="paragraph">
<p>Then, use <code>git bisect <term-old></code> and <code>git bisect <term-new></code> instead
of <code>git bisect good</code> and <code>git bisect bad</code> to mark commits.</p>
</div>
</div>
<div class="sect2">
<h3 id="_bisect_visualize">Bisect visualize</h3>
<div class="paragraph">
<p>To see the currently remaining suspects in <em>gitk</em>, issue the following
command during the bisection process:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect visualize</pre>
</div>
</div>
<div class="paragraph">
<p><code>view</code> may also be used as a synonym for <code>visualize</code>.</p>
</div>
<div class="paragraph">
<p>If the <code>DISPLAY</code> environment variable is not set, <em>git log</em> is used
instead. You can also give command-line options such as <code>-p</code> and
<code>--stat</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect view --stat</pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_bisect_log_and_bisect_replay">Bisect log and bisect replay</h3>
<div class="paragraph">
<p>After having marked revisions as good or bad, issue the following
command to show what has been done so far:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect log</pre>
</div>
</div>
<div class="paragraph">
<p>If you discover that you made a mistake in specifying the status of a
revision, you can save the output of this command to a file, edit it to
remove the incorrect entries, and then issue the following commands to
return to a corrected state:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect reset
$ git bisect replay that-file</pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_avoiding_testing_a_commit">Avoiding testing a commit</h3>
<div class="paragraph">
<p>If, in the middle of a bisect session, you know that the suggested
revision is not a good one to test (e.g. it fails to build and you
know that the failure does not have anything to do with the bug you
are chasing), you can manually select a nearby commit and test that
one instead.</p>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect good/bad # previous round was good or bad.
Bisecting: 337 revisions left to test after this (roughly 9 steps)
$ git bisect visualize # oops, that is uninteresting.
$ git reset --hard HEAD~3 # try 3 revisions before what
# was suggested</pre>
</div>
</div>
<div class="paragraph">
<p>Then compile and test the chosen revision, and afterwards mark
the revision as good or bad in the usual manner.</p>
</div>
</div>
<div class="sect2">
<h3 id="_bisect_skip">Bisect skip</h3>
<div class="paragraph">
<p>Instead of choosing a nearby commit by yourself, you can ask Git to do
it for you by issuing the command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect skip # Current version cannot be tested</pre>
</div>
</div>
<div class="paragraph">
<p>However, if you skip a commit adjacent to the one you are looking for,
Git will be unable to tell exactly which of those commits was the
first bad one.</p>
</div>
<div class="paragraph">
<p>You can also skip a range of commits, instead of just one commit,
using range notation. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect skip v2.5..v2.6</pre>
</div>
</div>
<div class="paragraph">
<p>This tells the bisect process that no commit after <code>v2.5</code>, up to and
including <code>v2.6</code>, should be tested.</p>
</div>
<div class="paragraph">
<p>Note that if you also want to skip the first commit of the range you
would issue the command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect skip v2.5 v2.5..v2.6</pre>
</div>
</div>
<div class="paragraph">
<p>This tells the bisect process that the commits between <code>v2.5</code> and
<code>v2.6</code> (inclusive) should be skipped.</p>
</div>
</div>
<div class="sect2">
<h3 id="_cutting_down_bisection_by_giving_more_parameters_to_bisect_start">Cutting down bisection by giving more parameters to bisect start</h3>
<div class="paragraph">
<p>You can further cut down the number of trials, if you know what part of
the tree is involved in the problem you are tracking down, by specifying
path parameters when issuing the <code>bisect start</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start -- arch/i386 include/asm-i386</pre>
</div>
</div>
<div class="paragraph">
<p>If you know beforehand more than one good commit, you can narrow the
bisect space down by specifying all of the good commits immediately after
the bad commit when issuing the <code>bisect start</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start v2.6.20-rc6 v2.6.20-rc4 v2.6.20-rc1 --
# v2.6.20-rc6 is bad
# v2.6.20-rc4 and v2.6.20-rc1 are good</pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_bisect_run">Bisect run</h3>
<div class="paragraph">
<p>If you have a script that can tell if the current source code is good
or bad, you can bisect by issuing the command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect run my_script arguments</pre>
</div>
</div>
<div class="paragraph">
<p>Note that the script (<code>my_script</code> in the above example) should exit
with code 0 if the current source code is good/old, and exit with a
code between 1 and 127 (inclusive), except 125, if the current source
code is bad/new.</p>
</div>
<div class="paragraph">
<p>Any other exit code will abort the bisect process. It should be noted
that a program that terminates via <code>exit(-1)</code> leaves $? = 255, (see the
exit(3) manual page), as the value is chopped with <code>& 0377</code>.</p>
</div>
<div class="paragraph">
<p>The special exit code 125 should be used when the current source code
cannot be tested. If the script exits with this code, the current
revision will be skipped (see <code>git bisect skip</code> above). 125 was chosen
as the highest sensible value to use for this purpose, because 126 and 127
are used by POSIX shells to signal specific error status (127 is for
command not found, 126 is for command found but not executable—​these
details do not matter, as they are normal errors in the script, as far as
<code>bisect run</code> is concerned).</p>
</div>
<div class="paragraph">
<p>You may often find that during a bisect session you want to have
temporary modifications (e.g. s/#define DEBUG 0/#define DEBUG 1/ in a
header file, or "revision that does not have this commit needs this
patch applied to work around another problem this bisection is not
interested in") applied to the revision being tested.</p>
</div>
<div class="paragraph">
<p>To cope with such a situation, after the inner <em>git bisect</em> finds the
next revision to test, the script can apply the patch
before compiling, run the real test, and afterwards decide if the
revision (possibly with the needed patch) passed the test and then
rewind the tree to the pristine state. Finally the script should exit
with the status of the real test to let the <code>git bisect run</code> command loop
determine the eventual outcome of the bisect session.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_options">OPTIONS</h2>
<div class="sectionbody">
<div class="dlist">
<dl>
<dt class="hdlist1">--no-checkout</dt>
<dd>
<div class="paragraph">
<p>Do not checkout the new working tree at each iteration of the bisection
process. Instead just update a special reference named <code>BISECT_HEAD</code> to make
it point to the commit that should be tested.</p>
</div>
<div class="paragraph">
<p>This option may be useful when the test you would perform in each step
does not require a checked out tree.</p>
</div>
<div class="paragraph">
<p>If the repository is bare, <code>--no-checkout</code> is assumed.</p>
</div>
</dd>
</dl>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_examples">EXAMPLES</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p>Automatically bisect a broken build between v1.2 and HEAD:</p>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start HEAD v1.2 -- # HEAD is bad, v1.2 is good
$ git bisect run make # "make" builds the app
$ git bisect reset # quit the bisect session</pre>
</div>
</div>
</li>
<li>
<p>Automatically bisect a test failure between origin and HEAD:</p>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start HEAD origin -- # HEAD is bad, origin is good
$ git bisect run make test # "make test" builds and tests
$ git bisect reset # quit the bisect session</pre>
</div>
</div>
</li>
<li>
<p>Automatically bisect a broken test case:</p>
<div class="listingblock">
<div class="content">
<pre>$ cat ~/test.sh
#!/bin/sh
make || exit 125 # this skips broken builds
~/check_test_case.sh # does the test case pass?
$ git bisect start HEAD HEAD~10 -- # culprit is among the last 10
$ git bisect run ~/test.sh
$ git bisect reset # quit the bisect session</pre>
</div>
</div>
<div class="paragraph">
<p>Here we use a <code>test.sh</code> custom script. In this script, if <code>make</code>
fails, we skip the current commit.
<code>check_test_case.sh</code> should <code>exit 0</code> if the test case passes,
and <code>exit 1</code> otherwise.</p>
</div>
<div class="paragraph">
<p>It is safer if both <code>test.sh</code> and <code>check_test_case.sh</code> are
outside the repository to prevent interactions between the bisect,
make and test processes and the scripts.</p>
</div>
</li>
<li>
<p>Automatically bisect with temporary modifications (hot-fix):</p>
<div class="listingblock">
<div class="content">
<pre>$ cat ~/test.sh
#!/bin/sh
# tweak the working tree by merging the hot-fix branch
# and then attempt a build
if git merge --no-commit hot-fix &&
make
then
# run project specific test and report its status
~/check_test_case.sh
status=$?
else
# tell the caller this is untestable
status=125
fi
# undo the tweak to allow clean flipping to the next commit
git reset --hard
# return control
exit $status</pre>
</div>
</div>
<div class="paragraph">
<p>This applies modifications from a hot-fix branch before each test run,
e.g. in case your build or test environment changed so that older
revisions may need a fix which newer ones have already. (Make sure the
hot-fix branch is based off a commit which is contained in all revisions
which you are bisecting, so that the merge does not pull in too much, or
use <code>git cherry-pick</code> instead of <code>git merge</code>.)</p>
</div>
</li>
<li>
<p>Automatically bisect a broken test case:</p>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start HEAD HEAD~10 -- # culprit is among the last 10
$ git bisect run sh -c "make || exit 125; ~/check_test_case.sh"
$ git bisect reset # quit the bisect session</pre>
</div>
</div>
<div class="paragraph">
<p>This shows that you can do without a run script if you write the test
on a single line.</p>
</div>
</li>
<li>
<p>Locate a good region of the object graph in a damaged repository</p>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start HEAD <known-good-commit> [ <boundary-commit> ... ] --no-checkout
$ git bisect run sh -c '
GOOD=$(git for-each-ref "--format=%(objectname)" refs/bisect/good-*) &&
git rev-list --objects BISECT_HEAD --not $GOOD >tmp.$$ &&
git pack-objects --stdout >/dev/null <tmp.$$
rc=$?
rm -f tmp.$$
test $rc = 0'
$ git bisect reset # quit the bisect session</pre>
</div>
</div>
<div class="paragraph">
<p>In this case, when <em>git bisect run</em> finishes, bisect/bad will refer to a commit that
has at least one parent whose reachable graph is fully traversable in the sense
required by <em>git pack objects</em>.</p>
</div>
</li>
<li>
<p>Look for a fix instead of a regression in the code</p>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start
$ git bisect new HEAD # current commit is marked as new
$ git bisect old HEAD~10 # the tenth commit from now is marked as old</pre>
</div>
</div>
<div class="paragraph">
<p>or:</p>
</div>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre>$ git bisect start --term-old broken --term-new fixed
$ git bisect fixed
$ git bisect broken HEAD~10</pre>
</div>
</div>
<div class="sect2">
<h3 id="_getting_help">Getting help</h3>
<div class="paragraph">
<p>Use <code>git bisect</code> to get a short usage description, and <code>git bisect
help</code> or <code>git bisect -h</code> to get a long usage description.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_see_also">SEE ALSO</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="git-bisect-lk2009.html">Fighting regressions with git bisect</a>,
<a href="git-blame.html">git-blame</a>(1).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_git">GIT</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Part of the <a href="git.html">git</a>(1) suite</p>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2016-11-02 12:15:32 W. Europe Standard Time
</div>
</div>
</body>
</html>
|
arpitdwivedi/testproject
|
mingw64/share/doc/git-doc/git-bisect.html
|
HTML
|
gpl-2.0
| 52,147
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Qt 4.3: puzzlewidget.cpp Example File (draganddrop/puzzle/puzzlewidget.cpp)</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 class="title">puzzlewidget.cpp Example File<br /><span class="small-subtitle">draganddrop/puzzle/puzzlewidget.cpp</span>
</h1>
<pre><span class="comment"> /****************************************************************************
**
** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved.
**
** This file is part of the example classes of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Alternatively you may (at
** your option) use any later version of the GNU General Public
** License if such license has been publicly approved by Trolltech ASA
** (or its successors, if any) and the KDE Free Qt Foundation. In
** addition, as a special exception, Trolltech gives you certain
** additional rights. These rights are described in the Trolltech GPL
** Exception version 1.2, which can be found at
** http://www.trolltech.com/products/qt/gplexception/ and in the file
** GPL_EXCEPTION.txt in this package.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/. If
** you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** In addition, as a special exception, Trolltech, as the sole
** copyright holder for Qt Designer, grants users of the Qt/Eclipse
** Integration plug-in the right for the Qt/Eclipse Integration to
** link to functionality provided by Qt Designer and its related
** libraries.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly
** granted herein.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/</span>
#include <QtGui>
#include "puzzlewidget.h"
PuzzleWidget::PuzzleWidget(QWidget *parent)
: QWidget(parent)
{
setAcceptDrops(true);
setMinimumSize(400, 400);
setMaximumSize(400, 400);
}
void PuzzleWidget::clear()
{
pieceLocations.clear();
piecePixmaps.clear();
pieceRects.clear();
highlightedRect = QRect();
inPlace = 0;
update();
}
void PuzzleWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("image/x-puzzle-piece"))
event->accept();
else
event->ignore();
}
void PuzzleWidget::dragLeaveEvent(QDragLeaveEvent *event)
{
QRect updateRect = highlightedRect;
highlightedRect = QRect();
update(updateRect);
event->accept();
}
void PuzzleWidget::dragMoveEvent(QDragMoveEvent *event)
{
QRect updateRect = highlightedRect.unite(targetSquare(event->pos()));
if (event->mimeData()->hasFormat("image/x-puzzle-piece")
&& findPiece(targetSquare(event->pos())) == -1) {
highlightedRect = targetSquare(event->pos());
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
highlightedRect = QRect();
event->ignore();
}
update(updateRect);
}
void PuzzleWidget::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat("image/x-puzzle-piece")
&& findPiece(targetSquare(event->pos())) == -1) {
QByteArray pieceData = event->mimeData()->data("image/x-puzzle-piece");
QDataStream dataStream(&pieceData, QIODevice::ReadOnly);
QRect square = targetSquare(event->pos());
QPixmap pixmap;
QPoint location;
dataStream >> pixmap >> location;
pieceLocations.append(location);
piecePixmaps.append(pixmap);
pieceRects.append(square);
highlightedRect = QRect();
update(square);
event->setDropAction(Qt::MoveAction);
event->accept();
if (location == QPoint(square.x()/80, square.y()/80)) {
inPlace++;
if (inPlace == 25)
emit puzzleCompleted();
}
} else {
highlightedRect = QRect();
event->ignore();
}
}
int PuzzleWidget::findPiece(const QRect &pieceRect) const
{
for (int i = 0; i < pieceRects.size(); ++i) {
if (pieceRect == pieceRects[i]) {
return i;
}
}
return -1;
}
void PuzzleWidget::mousePressEvent(QMouseEvent *event)
{
QRect square = targetSquare(event->pos());
int found = findPiece(square);
if (found == -1)
return;
QPoint location = pieceLocations[found];
QPixmap pixmap = piecePixmaps[found];
pieceLocations.removeAt(found);
piecePixmaps.removeAt(found);
pieceRects.removeAt(found);
if (location == QPoint(square.x()/80, square.y()/80))
inPlace--;
update(square);
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << pixmap << location;
QMimeData *mimeData = new QMimeData;
mimeData->setData("image/x-puzzle-piece", itemData);
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setHotSpot(event->pos() - square.topLeft());
drag->setPixmap(pixmap);
if (!(drag->exec(Qt::MoveAction) == Qt::MoveAction)) {
pieceLocations.insert(found, location);
piecePixmaps.insert(found, pixmap);
pieceRects.insert(found, square);
update(targetSquare(event->pos()));
if (location == QPoint(square.x()/80, square.y()/80))
inPlace++;
}
}
void PuzzleWidget::paintEvent(QPaintEvent *event)
{
QPainter painter;
painter.begin(this);
painter.fillRect(event->rect(), Qt::white);
if (highlightedRect.isValid()) {
painter.setBrush(QColor("#ffcccc"));
painter.setPen(Qt::NoPen);
painter.drawRect(highlightedRect.adjusted(0, 0, -1, -1));
}
for (int i = 0; i < pieceRects.size(); ++i) {
painter.drawPixmap(pieceRects[i], piecePixmaps[i]);
}
painter.end();
}
const QRect PuzzleWidget::targetSquare(const QPoint &position) const
{
return QRect(position.x()/80 * 80, position.y()/80 * 80, 80, 80);
}</pre>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright © 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.6</div></td>
</tr></table></div></address></body>
</html>
|
muromec/qtopia-ezx
|
qtopiacore/qt/doc/html/draganddrop-puzzle-puzzlewidget-cpp.html
|
HTML
|
gpl-2.0
| 8,664
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WikipediaMetroTest</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- WikipediaMetroTest references -->
<link href="/css/default.css" rel="stylesheet">
<link href="/css/target.css" rel="stylesheet">
<script src="/js/jquery-1.7.2.js"></script>
<script src="/js/mediawiki.js"></script>
<script src="/js/jquery.localize.js"></script>
<script src="/js/propertiesFileReader.js"></script>
<script src="/js/l10n-setup.js"></script>
<script src="/js/default.js"></script>
<script src="/js/wikiview.js"></script>
</head>
<body>
<div class="header">
<h1 id="title">Wikipedia</h1>
</div>
<progress id="spinner"></progress>
<div class="hub" id="hub">
<div id="hubItemTemplate" data-win-control="WinJS.Binding.Template">
<div data-win-bind="className: style">
<img src="#" data-win-bind="src: image; id: imageid" />
<h5 data-win-bind="innerText: heading"></h5>
<h6 data-win-bind="innerText: snippet"></h6>
<h4 data-win-bind="innerText: title" style="font-weight: bold"></h4>
</div>
</div>
<div id="headerTemplate" data-win-control="WinJS.Binding.Template" style="display: none">
<div class="simpleHeaderItem">
<h2 data-win-bind="innerText: title"></h2>
</div>
</div>
<div id="hub-list"
data-win-control="WinJS.UI.ListView"
data-win-options="{
itemDataSource: HubContents.groupedList.dataSource,
itemTemplate: select('#hubItemTemplate'),
groupHeaderTemplate: headerTemplate,
selectionMode: 'none',
swipeBehavior: 'none',
groupDataSource: HubContents.groupedList.groups.dataSource
}">
</div>
</div>
<div class="page" id="reader">
<div id="tocItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="tocItemTemplate">
<h4 data-win-bind="innerText: title; className: style"></h4>
</div>
</div>
<div id="semanticZoomer"
data-win-control="WinJS.UI.SemanticZoom"
data-win-options="{ zoomFactor: 0.5, initiallyZoomedOut: false }"
style="height: 600px"
>
<div id="content"
data-win-control="WikiControls.WikiView"
data-win-options="{}"
><div id="subcontent"></div></div>
<div id="toc"
data-win-control="WinJS.UI.ListView"
data-win-options="{
itemDataSource : TocSections.itemList.dataSource,
itemTemplate: select('#tocItemTemplate'),
selectionMode: 'none',
swipeBehavior: 'none'
}">
</div>
</div>
</div>
<div class="page" id="search">
<div id="search-results">
<div id="searchItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="searchItemTemplate" style="">
<h4 data-win-bind="innerText: title" style="font-weight: bold"></h4>
<h6 data-win-bind="innerText: snippet"></h6>
</div>
</div>
<div id="resultlist"
data-win-control="WinJS.UI.ListView"
data-win-options="{
itemDataSource : SearchResults.itemList.dataSource,
itemTemplate: select('#searchItemTemplate'),
selectionMode: 'none',
swipeBehavior: 'none'
}">
</div>
</div>
</div>
<div class="page" id="offline">
<msg key="error-not-available"></msg>
<msg key="error-offline-prompt"></msg>
</div>
</body>
</html>
|
jeesmon/WikipediaMobile
|
WikipediaMetro/WikipediaMetroTest/target.html
|
HTML
|
gpl-2.0
| 4,137
|
/* Copyright 2013 David Axmark
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _SYMBIAN9_INJECTOR_H_
#define _SYMBIAN9_INJECTOR_H_
#include "Injector.h"
namespace MoSync {
class Symbian9Injector : public Injector {
public:
void inject(const Icon* icon, const std::map<std::string, std::string>& params);
};
}
#endif // _SYMBIAN9_INJECTOR_H_
|
tybor/MoSync
|
tools/icon-injector/Symbian9Injector.h
|
C
|
gpl-2.0
| 831
|
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.hotspot.nodes;
import com.oracle.graal.nodeinfo.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.extended.*;
/**
* The {@code G1ReferentFieldReadBarrier} is added when a read access is performed to the referent
* field of a {@link java.lang.ref.Reference} object (through a {@code LoadFieldNode} or an
* {@code UnsafeLoadNode}). The return value of the read is passed to the snippet implementing the
* read barrier and consequently is added to the SATB queue if the concurrent marker is enabled.
*/
@NodeInfo
public class G1ReferentFieldReadBarrier extends WriteBarrier {
protected final boolean doLoad;
public static G1ReferentFieldReadBarrier create(ValueNode object, ValueNode expectedObject, LocationNode location, boolean doLoad) {
return new G1ReferentFieldReadBarrier(object, expectedObject, location, doLoad);
}
protected G1ReferentFieldReadBarrier(ValueNode object, ValueNode expectedObject, LocationNode location, boolean doLoad) {
super(object, expectedObject, location, true);
this.doLoad = doLoad;
}
public ValueNode getExpectedObject() {
return getValue();
}
public boolean doLoad() {
return doLoad;
}
}
|
smarr/graal
|
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/nodes/G1ReferentFieldReadBarrier.java
|
Java
|
gpl-2.0
| 2,299
|
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import joomla controller library
jimport('joomla.application.component.controller');
// Get an instance of the controller prefixed by HelloWorld
$controller = JController::getInstance('HelloWorld');
// Perform the Request task
$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));
// Redirect if set by the controller
$controller->redirect();
|
soul290502/joomla2.5
|
components/com_helloworld/helloworld.php
|
PHP
|
gpl-2.0
| 476
|
<?php
include_once("RowListener.php");
include_once("GroupsExportingRowListener.php");
class ExcludingReadersGroupsExportingRowListener extends GroupsExportingRowListener implements RowListener {
private $excludeRowsFrom = array();
private $additionalExcludedGroupId;
function __construct(HashCalculator $hashCalculator, WriterFactory $factory, $excludeRowsFrom, $excludedGroupId = ".excluded"){
parent::__construct($hashCalculator, $factory);
$this->additionalExcludedGroupId = $excludedGroupId;
foreach ($excludeRowsFrom as $reader){
$this->addExclusion($reader);
}
}
private function addExclusion(RandomReader $reader){
$this->excludeRowsFrom[] = $reader;
}
protected function getGroupId(RandomReader $reader, $rowIndex, $rowHash){
$groupId = $rowHash;
if (in_array($reader, $this->excludeRowsFrom)){
$groupId .= $this->additionalExcludedGroupId;
}
return $groupId;
}
}
|
demonh3x/tanchi-bunshin
|
src/RowListeners/ExcludingReadersGroupsExportingRowListener.php
|
PHP
|
gpl-2.0
| 1,006
|
#ifndef KVM__VESA_H
#define KVM__VESA_H
#define VESA_WIDTH 640
#define VESA_HEIGHT 480
#define VESA_MEM_ADDR 0xd0000000
#define VESA_BPP 32
/*
* We actually only need VESA_BPP/8*VESA_WIDTH*VESA_HEIGHT bytes. But the memory
* size must be a power of 2, so we round up.
*/
#define VESA_MEM_SIZE (1 << 21)
struct kvm;
struct biosregs;
struct framebuffer *vesa__init(struct kvm *self);
#endif
|
kvmtool/kvmtool
|
include/kvm/vesa.h
|
C
|
gpl-2.0
| 397
|
<?php
define('EmpireCMSAdmin','1');
require("../../class/connect.php");
require("../../class/db_sql.php");
require("../../class/functions.php");
require "../".LoadLang("pub/fun.php");
$link=db_connect();
$empire=new mysqlquery();
$editor=1;
//验证用户
$lur=is_login();
$logininid=$lur['userid'];
$loginin=$lur['username'];
$loginrnd=$lur['rnd'];
$loginlevel=$lur['groupid'];
$loginadminstyleid=$lur['adminstyleid'];
//验证权限
CheckLevel($logininid,$loginin,$classid,"template");
//增加搜索模板
function AddMSearchtemp($add,$userid,$username){
global $empire,$dbtbpre;
if(!$add[tempname]||!$add[temptext]||!$add[listvar]||!$add[modid])
{printerror("EmptySearchTempname","history.go(-1)");}
//操作权限
CheckLevel($userid,$username,$classid,"template");
$classid=(int)$add['classid'];
$add[tempname]=hRepPostStr($add[tempname],1);
$add[temptext]=RepPhpAspJspcode($add[temptext]);
$add[listvar]=RepPhpAspJspcode($add[listvar]);
if($add['autorownum'])
{
$add[rownum]=substr_count($add[temptext],'<!--list.var');
}
//变量处理
$add[subnews]=(int)$add[subnews];
$add[rownum]=(int)$add[rownum];
$add[modid]=(int)$add[modid];
$add[subtitle]=(int)$add[subtitle];
$docode=(int)$add[docode];
$gid=(int)$add['gid'];
$sql=$empire->query("insert into ".GetDoTemptb("enewssearchtemp",$gid)."(tempname,temptext,subnews,isdefault,listvar,rownum,modid,showdate,subtitle,classid,docode) values('$add[tempname]','".eaddslashes2($add[temptext])."',$add[subnews],0,'".eaddslashes2($add[listvar])."',$add[rownum],$add[modid],'$add[showdate]',$add[subtitle],$classid,'$docode');");
$tempid=$empire->lastid();
//备份模板
AddEBakTemp('searchtemp',$gid,$tempid,$add[tempname],$add[temptext],$add[subnews],0,$add[listvar],$add[rownum],$add[modid],$add[showdate],$add[subtitle],$classid,$docode,$userid,$username);
if($sql)
{
//操作日志
insert_dolog("tempid=".$tempid."<br>tempname=".$add[tempname]."&gid=$gid");
printerror("AddMSearchTempSuccess","AddSearchtemp.php?enews=AddMSearchtemp&gid=$gid");
}
else
{
printerror("DbError","history.go(-1)");
}
}
//修改搜索模板
function EditMSearchtemp($add,$userid,$username){
global $empire,$dbtbpre;
$add[tempid]=(int)$add[tempid];
if(!$add[tempname]||!$add[temptext]||!$add[listvar]||!$add[modid]||!$add[tempid])
{printerror("EmptySearchTempname","history.go(-1)");}
//操作权限
CheckLevel($userid,$username,$classid,"template");
$classid=(int)$add['classid'];
$add[tempname]=hRepPostStr($add[tempname],1);
$add[temptext]=RepPhpAspJspcode($add[temptext]);
$add[listvar]=RepPhpAspJspcode($add[listvar]);
if($add['autorownum'])
{
$add[rownum]=substr_count($add[temptext],'<!--list.var');
}
//变量处理
$add[subnews]=(int)$add[subnews];
$add[rownum]=(int)$add[rownum];
$add[modid]=(int)$add[modid];
$add[subtitle]=(int)$add[subtitle];
$docode=(int)$add[docode];
$gid=(int)$add['gid'];
$sql=$empire->query("update ".GetDoTemptb("enewssearchtemp",$gid)." set subnews=$add[subnews],tempname='$add[tempname]',temptext='".eaddslashes2($add[temptext])."',listvar='".eaddslashes2($add[listvar])."',rownum=$add[rownum],modid=$add[modid],showdate='$add[showdate]',subtitle=$add[subtitle],classid=$classid,docode='$docode' where tempid='$add[tempid]'");
//备份模板
AddEBakTemp('searchtemp',$gid,$add[tempid],$add[tempname],$add[temptext],$add[subnews],0,$add[listvar],$add[rownum],$add[modid],$add[showdate],$add[subtitle],$classid,$docode,$userid,$username);
if($sql)
{
//操作日志
insert_dolog("tempid=".$add[tempid]."<br>tempname=".$add[tempname]."&gid=$gid");
printerror("EditMSearchTempSuccess","ListSearchtemp.php?classid=$add[cid]&modid=$add[mid]&gid=$gid");
}
else
{
printerror("DbError","history.go(-1)");
}
}
//删除搜索模板
function DelMSearchtemp($tempid,$add,$userid,$username){
global $empire,$dbtbpre;
$tempid=(int)$tempid;
if(!$tempid)
{printerror("NotDelTemplateid","history.go(-1)");}
//操作权限
CheckLevel($userid,$username,$classid,"template");
$gid=(int)$add['gid'];
$tr=$empire->fetch1("select tempname,isdefault from ".GetDoTemptb("enewssearchtemp",$gid)." where tempid='$tempid'");
if($tr[isdefault])
{printerror("NotDelDefaultTemp","history.go(-1)");}
$sql=$empire->query("delete from ".GetDoTemptb("enewssearchtemp",$gid)." where tempid='$tempid'");
$usql=$empire->query("update {$dbtbpre}enewsclass set searchtempid=0 where searchtempid='$tempid'");
GetClass();
//删除备份记录
DelEbakTempAll('searchtemp',$gid,$tempid);
if($sql)
{
//操作日志
insert_dolog("tempid=".$tempid."<br>tempname=".$tr[tempname]."&gid=$gid");
printerror("DelMSearchTempSuccess","ListSearchtemp.php?classid=$add[cid]&modid=$add[mid]&gid=$gid");
}
else
{
printerror("DbError","history.go(-1)");
}
}
//设为默认搜索模板
function DefaultMSearchtemp($tempid,$add,$userid,$username){
global $empire,$dbtbpre;
$tempid=(int)$tempid;
if(!$tempid)
{printerror("EmptyDefaultSearchtempid","history.go(-1)");}
//操作权限
CheckLevel($userid,$username,$classid,"template");
$gid=(int)$add['gid'];
$tr=$empire->fetch1("select tempname from ".GetDoTemptb("enewssearchtemp",$gid)." where tempid='$tempid'");
$usql=$empire->query("update ".GetDoTemptb("enewssearchtemp",$gid)." set isdefault=0");
$sql=$empire->query("update ".GetDoTemptb("enewssearchtemp",$gid)." set isdefault=1 where tempid='$tempid'");
if($sql)
{
//操作日志
insert_dolog("tempid=".$tempid."<br>tempname=".$tr[tempname]."&gid=$gid");
printerror("DefaultMSearchtempSuccess","ListSearchtemp.php?classid=$add[cid]&modid=$add[mid]&gid=$gid");
}
else
{
printerror("DbError","history.go(-1)");
}
}
$enews=$_POST['enews'];
if(empty($enews))
{$enews=$_GET['enews'];}
if($enews)
{
include("../../class/tempfun.php");
}
//增加搜索模板
if($enews=="AddMSearchtemp")
{
AddMSearchtemp($_POST,$logininid,$loginin);
}
//修改搜索模板
elseif($enews=="EditMSearchtemp")
{
EditMSearchtemp($_POST,$logininid,$loginin);
}
//删除搜索模板
elseif($enews=="DelMSearchtemp")
{
$tempid=$_GET['tempid'];
DelMSearchtemp($tempid,$_GET,$logininid,$loginin);
}
//默认搜索模板
elseif($enews=="DefaultMSearchtemp")
{
$tempid=$_GET['tempid'];
DefaultMSearchtemp($tempid,$_GET,$logininid,$loginin);
}
$gid=(int)$_GET['gid'];
$gname=CheckTempGroup($gid);
$urlgname=$gname." > ";
$url=$urlgname."<a href=ListSearchtemp.php?gid=$gid>管理搜索模板</a>";
$search="&gid=$gid";
$page=(int)$_GET['page'];
$page=RepPIntvar($page);
$start=0;
$line=25;//每页显示条数
$page_line=12;//每页显示链接数
$offset=$page*$line;//总偏移量
$query="select tempid,tempname,modid,isdefault from ".GetDoTemptb("enewssearchtemp",$gid);
$totalquery="select count(*) as total from ".GetDoTemptb("enewssearchtemp",$gid);
//类别
$add="";
$classid=(int)$_GET['classid'];
if($classid)
{
$add=" where classid=$classid";
$search.="&classid=$classid";
}
//模型
$modid=(int)$_GET['modid'];
if($modid)
{
if(empty($add))
{
$add=" where modid=$modid";
}
else
{
$add.=" and modid=$modid";
}
$search.="&modid=$modid";
}
$query.=$add;
$totalquery.=$add;
$num=$empire->gettotal($totalquery);//取得总条数
$query=$query." order by tempid desc limit $offset,$line";
$sql=$empire->query($query);
$returnpage=page2($num,$line,$page_line,$start,$page,$search);
//分类
$cstr="";
$csql=$empire->query("select classid,classname from {$dbtbpre}enewssearchtempclass order by classid");
while($cr=$empire->fetch($csql))
{
$select="";
if($cr[classid]==$classid)
{
$select=" selected";
}
$cstr.="<option value='".$cr[classid]."'".$select.">".$cr[classname]."</option>";
}
//模型
$mstr="";
$msql=$empire->query("select mid,mname from {$dbtbpre}enewsmod where usemod=0 order by myorder,mid");
while($mr=$empire->fetch($msql))
{
$select="";
if($mr[mid]==$modid)
{
$select=" selected";
}
$mstr.="<option value='".$mr[mid]."'".$select.">".$mr[mname]."</option>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>管理搜索模板</title>
<link href="../adminstyle/<?=$loginadminstyleid?>/adminstyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td width="50%">位置:
<?=$url?>
</td>
<td> <div align="right" class="emenubutton">
<input type="button" name="Submit5" value="增加搜索模板" onclick="self.location.href='AddSearchtemp.php?enews=AddMSearchtemp&gid=<?=$gid?>';">
<input type="button" name="Submit5" value="管理搜索模板分类" onclick="self.location.href='SearchtempClass.php?gid=<?=$gid?>';">
</div></td>
</tr>
</table>
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<form name="form1" method="get" action="ListSearchtemp.php">
<input type=hidden name=gid value="<?=$gid?>">
<tr>
<td height="25">限制显示:
<select name="classid" id="classid" onchange="document.form1.submit()">
<option value="0">显示所有分类</option>
<?=$cstr?>
</select>
<select name="modid" id="modid" onchange="document.form1.submit()">
<option value="0">显示所有系统模型</option>
<?=$mstr?>
</select>
</td>
</tr>
</form>
</table>
<br>
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1" class="tableborder">
<tr class="header">
<td width="8%" height="25"><div align="center">ID</div></td>
<td width="41%" height="25"><div align="center">模板名</div></td>
<td width="27%"><div align="center">所属系统模型</div></td>
<td width="24%" height="25"><div align="center">操作</div></td>
</tr>
<?
while($r=$empire->fetch($sql))
{
$modr=$empire->fetch1("select mid,mname from {$dbtbpre}enewsmod where mid=$r[modid]");
$color="#ffffff";
$movejs=' onmouseout="this.style.backgroundColor=\'#ffffff\'" onmouseover="this.style.backgroundColor=\'#C3EFFF\'"';
if($r[isdefault])
{
$color="#DBEAF5";
$movejs='';
}
?>
<tr bgcolor="<?=$color?>"<?=$movejs?>>
<td height="25"><div align="center">
<?=$r[tempid]?>
</div></td>
<td height="25"><div align="center">
<?=$r[tempname]?>
</div></td>
<td><div align="center">[<a href="ListSearchtemp.php?classid=<?=$classid?>&modid=<?=$modr[mid]?>&gid=<?=$gid?>"><?=$modr[mname]?></a>]</div></td>
<td height="25"><div align="center"> [<a href="AddSearchtemp.php?enews=EditMSearchtemp&tempid=<?=$r[tempid]?>&cid=<?=$classid?>&mid=<?=$modid?>&gid=<?=$gid?>">修改</a>]
[<a href="AddSearchtemp.php?enews=AddMSearchtemp&docopy=1&tempid=<?=$r[tempid]?>&cid=<?=$classid?>&mid=<?=$modid?>&gid=<?=$gid?>">复制</a>]
[<a href="ListSearchtemp.php?enews=DefaultMSearchtemp&tempid=<?=$r[tempid]?>&cid=<?=$classid?>&mid=<?=$modid?>&gid=<?=$gid?>" onclick="return confirm('确认要设为默认?');">设为默认</a>]
[<a href="ListSearchtemp.php?enews=DelMSearchtemp&tempid=<?=$r[tempid]?>&cid=<?=$classid?>&mid=<?=$modid?>&gid=<?=$gid?>" onclick="return confirm('确认要删除?');">删除</a>]</div></td>
</tr>
<?
}
?>
<tr bgcolor="ffffff">
<td height="25" colspan="4"> <?=$returnpage?></td>
</tr>
</table>
</body>
</html>
<?
db_close();
$empire=null;
?>
|
306076197/hudson
|
e/admin/template/ListSearchtemp.php
|
PHP
|
gpl-2.0
| 11,442
|
/** @jsx React.DOM */
(function( module, undefined) {
var React = require('react');
var CanvasApp = require('./components/Canvas.js');
var FormApp = require('./components/Form.js');
var FormParametroApp = require('./components/FormParametro.js');
var PendulumStore = require('./stores/Pendulum.js');
var Base = React.createClass({
_onChange: function() {
this.setState(PendulumStore.get());
},
componentDidMount: function() {
PendulumStore.addChangeListener(this._onChange);
},
getInitialState: function() {
return PendulumStore.get();
},
componentWillUnmount: function() {
PendulumStore.removeChangeListener(this._onChange);
},
//salvar:function(){
//Acao.salvar();
//Acao.abrirModal('dialogo');
//},
//editor:function(){
//if (this.state.editor=='fechado'){
//Acao.abrirModal('senha');
//}else{
//Acao.editor();
//}
//},
//limpar:function(){
//Acao.abrirModal('restaurar');
//},
render: function() {
return(<div>
<CanvasApp pendulum={this.state}/>
<FormApp pendulum={this.state}/>
<FormParametroApp />
</div>)
}
});
React.render( <Base/> ,document.getElementById('react'));
}( module));
|
messias-physics/fuzzy-flux-react
|
appReact/app.js
|
JavaScript
|
gpl-2.0
| 1,488
|
<?php
namespace Drupal\google_analytics_reports\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Number;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ViewExecutable;
/**
* Provides base field functionality for Google Analytics fields.
*
* @ingroup views_field_handlers
*
* @ViewsField("google_analytics_standard")
*/
class GoogleAnalyticsStandard extends FieldPluginBase {
protected $isCustom = NULL;
/**
* {@inheritdoc}
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$this->isCustom = google_analytics_reports_is_custom($this->realField);
}
/**
* {@inheritdoc}
*/
public function query() {
parent::query();
if ($this->isCustom) {
$this->realField = google_analytics_reports_custom_to_variable_field($this->realField, $this->options['custom_field_number']);
}
}
/**
* {@inheritdoc}
*/
public function defineOptions() {
$options = parent::defineOptions();
if ($this->isCustom) {
$options['custom_field_number'] = ['default' => 1];
}
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
if ($this->isCustom) {
$form['custom_field_number'] = [
'#type' => 'textfield',
'#title' => t('Custom field number'),
'#default_value' => isset($this->options['custom_field_number']) ? $this->options['custom_field_number'] : 1,
'#size' => 2,
'#maxlength' => 2,
'#required' => TRUE,
'#element_validate' => [Number::class, 'validateNumber'],
];
}
parent::buildOptionsForm($form, $form_state);
}
}
|
jagnoha/website
|
profiles/varbase/profiles/varbase/modules/contrib/google_analytics_reports/src/Plugin/views/field/GoogleAnalyticsStandard.php
|
PHP
|
gpl-2.0
| 1,857
|
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest12227")
public class BenchmarkTest12227 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar = new Test().doSomething(param);
String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
java.sql.ResultSet rs = statement.executeQuery( sql );
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = param.split(" ")[0];
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
|
iammyr/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest12227.java
|
Java
|
gpl-2.0
| 2,317
|
/*
Copyright (C) 2008-2016 Vana Development Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#pragma once
#include "common/types.hpp"
namespace vana {
namespace constant {
namespace mob {
enum mob_id : game_mob_id {
high_darkstar = 8500003,
low_darkstar = 8500004,
zakum_body1 = 8800000,
zakum_arm1 = 8800003,
zakum_arm2 = 8800004,
zakum_arm3 = 8800005,
zakum_arm4 = 8800006,
zakum_arm5 = 8800007,
zakum_arm6 = 8800008,
zakum_arm7 = 8800009,
zakum_arm8 = 8800010,
horntail_head_a = 8810002,
horntail_head_b = 8810003,
horntail_head_c = 8810004,
horntail_left_hand = 8810005,
horntail_right_hand = 8810006,
horntail_wings = 8810007,
horntail_legs = 8810008,
horntail_tail = 8810009,
dead_horntail_head_a = 8810010,
dead_horntail_head_b = 8810011,
dead_horntail_head_c = 8810012,
dead_horntail_left_hand = 8810013,
dead_horntail_right_hand = 8810014,
dead_horntail_wings = 8810015,
dead_horntail_legs = 8810016,
dead_horntail_tail = 8810017,
horntail_sponge = 8810018,
summon_horntail = 8810026,
docile_pink_bean = 8820000,
pink_bean = 8820001,
ariel = 8820002,
solomon_the_wise1 = 8820003,
rex_the_wise1 = 8820004,
hugin1 = 8820005,
munin1 = 8820006,
mini_bean = 8820007,
summon_pink_bean = 8820008,
summon_pink_bean_phase1 = 8820009,
pink_bean_sponge1 = 8820010,
pink_bean_sponge2 = 8820011,
pink_bean_sponge3 = 8820012,
pink_bean_sponge4 = 8820013,
pink_bean_sponge5 = 8820014,
solomon_the_wise2 = 8820015,
rex_the_wise2 = 8820016,
hugin2 = 8820017,
munin2 = 8820018,
inactive_ariel = 8820019,
inactive_solomon_the_wise1 = 8820020,
inactive_rex_the_wise1 = 8820021,
inactive_hugin1 = 8820022,
inactive_munin1 = 8820023,
inactive_solomon_the_wise2 = 8820024,
inactive_rex_the_wise2 = 8820025,
inactive_hugin2 = 8820026,
inactive_munin2 = 8820027,
no_mob = 9999999,
};
}
}
}
|
diamondo25/Vana
|
src/common/constant/mob.hpp
|
C++
|
gpl-2.0
| 2,619
|
using System;
using Server.Items;
using Server.Mobiles;
using Server.Targeting;
namespace Server.Engines.Harvest
{
public class DeathHarvest : HarvestSystem
{
private static DeathHarvest m_System;
public static DeathHarvest System
{
get
{
if (m_System == null)
m_System = new DeathHarvest();
return m_System;
}
}
private readonly HarvestDefinition m_GravesAndMounds;
private readonly HarvestDefinition m_TombsAndCoffins;
public HarvestDefinition GravesAndMounds
{
get
{
return this.m_GravesAndMounds;
}
}
public HarvestDefinition TombsAndCoffins
{
get
{
return this.m_TombsAndCoffins;
}
}
private DeathHarvest()
{
HarvestResource[] res;
HarvestVein[] veins;
#region Harvesting graves
HarvestDefinition gravesAndMounds = this.m_GravesAndMounds = new HarvestDefinition();
// Resource banks are every 8x8 tiles
gravesAndMounds.BankWidth = 8;
gravesAndMounds.BankHeight = 8;
// Every bank holds from 10 to 34 ore
gravesAndMounds.MinTotal = 10;
gravesAndMounds.MaxTotal = 34;
// A resource bank will respawn its content every 10 to 20 minutes
gravesAndMounds.MinRespawn = TimeSpan.FromMinutes(10.0);
gravesAndMounds.MaxRespawn = TimeSpan.FromMinutes(20.0);
// Skill checking is done on the Mining skill
gravesAndMounds.Skill = SkillName.Mining;
// Set the list of harvestable tiles
gravesAndMounds.Tiles = m_GravesAndMoundsTiles;
// Players must be within 2 tiles to harvest
gravesAndMounds.MaxRange = 2;
// One ore per harvest action
gravesAndMounds.ConsumedPerHarvest = 1;
gravesAndMounds.ConsumedPerFeluccaHarvest = 2;
// The digging effect
gravesAndMounds.EffectActions = new int[] { 11 };
gravesAndMounds.EffectSounds = new int[] { 0x125, 0x126 };
gravesAndMounds.EffectCounts = new int[] { 1 };
gravesAndMounds.EffectDelay = TimeSpan.FromSeconds(1.6);
gravesAndMounds.EffectSoundDelay = TimeSpan.FromSeconds(0.9);
gravesAndMounds.NoResourcesMessage = 503040; // There is no metal here to mine.
gravesAndMounds.DoubleHarvestMessage = 503042; // Someone has gotten to the metal before you.
gravesAndMounds.TimedOutOfRangeMessage = 503041; // You have moved too far away to continue mining.
gravesAndMounds.OutOfRangeMessage = 500446; // That is too far away.
gravesAndMounds.FailMessage = 503043; // You loosen some rocks but fail to find any useable ore.
gravesAndMounds.PackFullMessage = 1010481; // Your backpack is full, so the ore you mined is lost.
gravesAndMounds.ToolBrokeMessage = 1044038; // You have worn out your tool!
res = new HarvestResource[]
{
new HarvestResource(00.0, 00.0, 100.0, 1007072, typeof(IronOre), typeof(Granite)),
new HarvestResource(65.0, 25.0, 105.0, 1007073, typeof(DullCopperOre), typeof(DullCopperGranite), typeof(DullCopperElemental)),
new HarvestResource(70.0, 30.0, 110.0, 1007074, typeof(ShadowIronOre), typeof(ShadowIronGranite), typeof(ShadowIronElemental)),
new HarvestResource(75.0, 35.0, 115.0, 1007075, typeof(CopperOre), typeof(CopperGranite), typeof(CopperElemental)),
new HarvestResource(80.0, 40.0, 120.0, 1007076, typeof(BronzeOre), typeof(BronzeGranite), typeof(BronzeElemental)),
new HarvestResource(85.0, 45.0, 125.0, 1007077, typeof(GoldOre), typeof(GoldGranite), typeof(GoldenElemental)),
new HarvestResource(90.0, 50.0, 130.0, 1007078, typeof(AgapiteOre), typeof(AgapiteGranite), typeof(AgapiteElemental)),
new HarvestResource(95.0, 55.0, 135.0, 1007079, typeof(VeriteOre), typeof(VeriteGranite), typeof(VeriteElemental)),
new HarvestResource(99.0, 59.0, 139.0, 1007080, typeof(ValoriteOre), typeof(ValoriteGranite), typeof(ValoriteElemental))
};
veins = new HarvestVein[]
{
new HarvestVein(49.6, 0.0, res[0], null), // Iron
new HarvestVein(11.2, 0.5, res[1], res[0]), // Dull Copper
new HarvestVein(09.8, 0.5, res[2], res[0]), // Shadow Iron
new HarvestVein(08.4, 0.5, res[3], res[0]), // Copper
new HarvestVein(07.0, 0.5, res[4], res[0]), // Bronze
new HarvestVein(05.6, 0.5, res[5], res[0]), // Gold
new HarvestVein(04.2, 0.5, res[6], res[0]), // Agapite
new HarvestVein(02.8, 0.5, res[7], res[0]), // Verite
new HarvestVein(01.4, 0.5, res[8], res[0])// Valorite
};
gravesAndMounds.Resources = res;
gravesAndMounds.Veins = veins;
if (Core.ML)
{
gravesAndMounds.BonusResources = new BonusHarvestResource[]
{
new BonusHarvestResource(0, 99.4, null, null), //Nothing
new BonusHarvestResource(100, .1, 1072562, typeof(BlueDiamond)),
new BonusHarvestResource(100, .1, 1072567, typeof(DarkSapphire)),
new BonusHarvestResource(100, .1, 1072570, typeof(EcruCitrine)),
new BonusHarvestResource(100, .1, 1072564, typeof(FireRuby)),
new BonusHarvestResource(100, .1, 1072566, typeof(PerfectEmerald)),
new BonusHarvestResource(100, .1, 1072568, typeof(Turquoise))
};
}
gravesAndMounds.RaceBonus = Core.ML;
gravesAndMounds.RandomizeVeins = Core.ML;
this.Definitions.Add(gravesAndMounds);
#endregion
#region Mining for sand
HarvestDefinition tombsAndCoffins = this.m_TombsAndCoffins = new HarvestDefinition();
// Resource banks are every 8x8 tiles
tombsAndCoffins.BankWidth = 8;
tombsAndCoffins.BankHeight = 8;
// Every bank holds from 6 to 12
tombsAndCoffins.MinTotal = 6;
tombsAndCoffins.MaxTotal = 12;
// A resource bank will respawn its content every 10 to 20 minutes
tombsAndCoffins.MinRespawn = TimeSpan.FromMinutes(10.0);
tombsAndCoffins.MaxRespawn = TimeSpan.FromMinutes(20.0);
// Skill checking is done on the Mining skill
tombsAndCoffins.Skill = SkillName.Mining;
// Set the list of harvestable tiles
tombsAndCoffins.Tiles = m_TombsAndCoffinsTiles;
// Players must be within 2 tiles to harvest
tombsAndCoffins.MaxRange = 2;
// One tombsAndCoffins per harvest action
tombsAndCoffins.ConsumedPerHarvest = 1;
tombsAndCoffins.ConsumedPerFeluccaHarvest = 1;
// The digging effect
tombsAndCoffins.EffectActions = new int[] { 11 };
tombsAndCoffins.EffectSounds = new int[] { 0x125, 0x126 };
tombsAndCoffins.EffectCounts = new int[] { 6 };
tombsAndCoffins.EffectDelay = TimeSpan.FromSeconds(1.6);
tombsAndCoffins.EffectSoundDelay = TimeSpan.FromSeconds(0.9);
tombsAndCoffins.NoResourcesMessage = 1044629; // There is no tombsAndCoffins here to mine.
tombsAndCoffins.DoubleHarvestMessage = 1044629; // There is no tombsAndCoffins here to mine.
tombsAndCoffins.TimedOutOfRangeMessage = 503041; // You have moved too far away to continue mining.
tombsAndCoffins.OutOfRangeMessage = 500446; // That is too far away.
tombsAndCoffins.FailMessage = 1044630; // You dig for a while but fail to find any of sufficient quality for glassblowing.
tombsAndCoffins.PackFullMessage = 1044632; // Your backpack can't hold the tombsAndCoffins, and it is lost!
tombsAndCoffins.ToolBrokeMessage = 1044038; // You have worn out your tool!
res = new HarvestResource[]
{
new HarvestResource(100.0, 70.0, 400.0, 1044631, typeof(Sand))
};
veins = new HarvestVein[]
{
new HarvestVein(100.0, 0.0, res[0], null)
};
tombsAndCoffins.Resources = res;
tombsAndCoffins.Veins = veins;
this.Definitions.Add(tombsAndCoffins);
#endregion
}
public override bool BeginHarvesting(Mobile from, Item tool)
{
if (!base.BeginHarvesting(from, tool))
return false;
from.SendLocalizedMessage(503033); // Where do you wish to dig?
return true;
}
public override void OnHarvestStarted(Mobile from, Item tool, HarvestDefinition def, object toHarvest)
{
base.OnHarvestStarted(from, tool, def, toHarvest);
if (Core.ML)
from.RevealingAction();
}
public override void OnBadHarvestTarget(Mobile from, Item tool, object toHarvest)
{
if (toHarvest is LandTarget)
from.SendLocalizedMessage(501862); // You can't mine there.
else
from.SendLocalizedMessage(501863); // You can't mine that.
}
#region Tile lists
private static readonly int[] m_TombsAndCoffinsTiles = new int[]
{
//Graves, coffins, bones, body parts, etc, the dead stuff :)
0x4ECA, 0x4ECB, 0x4ECC, 0x4ECD, 0x4ECE, 0x4ECF, 0x4ED0, 0x4ED1, 0x4ED2,
0x4ED4, 0x4ED5, 0x4ED6, 0x4ED7, 0x4ED8, 0x4ED9, 0x4EDA, 0x4EDB, 0x4EDC,
0x4EDD, 0x4EDE, 0x4ED3, 0x4EDF, 0x4EE0, 0x4EE1, 0x4EE2, 0x4EE8, 0x5165,
0x5166, 0x5167, 0x5168, 0x5169, 0x516A, 0x516B, 0x516C, 0x516D,
0x516E, 0x516F, 0x5170, 0x5171, 0x5172, 0x5173, 0x5174, 0x5175,
0x5176, 0x5177, 0x5178, 0x5179, 0x517A, 0x517B, 0x517C, 0x517D,
0x517E, 0x517F, 0x5180, 0x5181, 0x5182, 0x5183, 0x5184, 0x5C22,
0x5C23, 0x5C24, 0x5C25, 0x5C26, 0x5C27, 0x5C28, 0x5C29, 0x5C2A,
0x5C2B, 0x5C2C, 0x5C2D, 0x5C2E, 0x5C2F, 0x5C30, 0x5C31, 0x5C32,
0x5C33, 0x5C34, 0x5C35, 0x5C36, 0x5C37, 0x5C38, 0x5C39, 0x5C3A,
0x5C3B, 0x5C3C, 0x5C3D, 0x5C3E, 0x5C3F, 0x5C40, 0x5C41, 0x5C42,
0x5C43, 0x5C44, 0x5C45, 0x5C46, 0x5C47, 0x5C48, 0x5C49, 0x5C4A,
0x5C4B, 0x5C4C, 0x5C4D, 0x5C4E, 0x5C4F, 0x5C50, 0x5C51, 0x5C52,
0x5C53, 0x5C54, 0x5C55, 0x5C56, 0x5C57, 0x5C58, 0x5C59, 0x5C5A,
0x5C5B, 0x5C5C, 0x5C5D, 0x5C5E, 0x5C5F, 0x6FF9, 0x6FFA, 0x7048,
0x7049, 0x704A, 0x704B, 0x5C60, 0x5C61, 0x5C62, 0x5C63, 0x5C64,
0x5C65, 0x5C66, 0x5C67, 0x5C68, 0x5C69, 0x5C6A, 0x5C6B, 0x5C6C,
0x5C6D, 0x5C6E, 0x5C6F, 0x5C70, 0x5C71, 0x5C72, 0x5C73, 0x5C74,
0x5C75, 0x5C76, 0x5C77, 0x5C78, 0x5C79, 0x5C7A, 0x5C7B, 0x5C7C,
0x5C7D, 0x5C7E, 0x5C7F, 0x5C80, 0x5C81, 0x5C82, 0x5C83, 0x5C84,
0x5C85, 0x5C86, 0x5C87, 0x5C88, 0x5C89, 0x5C8A, 0x5C8B, 0x5C8C,
0x5C8D, 0x5C8E, 0x5C8F, 0x5C90, 0x5C91, 0x5C92, 0x5C93, 0x5C94,
0x5C95, 0x5C96, 0x5C97, 0x5C98, 0x5C99, 0x5C9A, 0x5C9B, 0x5C9C,
0x5C9D, 0x5C9E, 0x5C9F, 0x5CA0, 0x5CA1, 0x5CA2, 0x5CA3, 0x5CA4,
0x5CA5, 0x5CA6, 0x5CA7, 0x5CA8, 0x5CA9, 0x5CAA, 0x5CAB, 0x5CAC,
0x5CAD, 0x5CAE, 0x5CAF, 0x5CB0, 0x5CB1, 0x5CB2, 0x5CB3, 0x5CB4,
0x5CB5, 0x5CB6, 0x5CB7, 0x5CB8, 0x5CB9, 0x5CBA, 0x5CBB, 0x5CBC,
0x5CBD, 0x5CBE, 0x5CBF, 0x4F7E, 0x5B09, 0x5B0A, 0x5B0B, 0x5B0C,
0x5B0D, 0x5B0E, 0x5B0F, 0x5B10, 0x5B11, 0x5B12, 0x5B13, 0x5B14,
0x5B15, 0x5B16, 0x5B17, 0x5B18, 0x5B19, 0x5B1A, 0x5B1B, 0x5B1C,
0x5B1D, 0x5B1E, 0x5AD8, 0x5AD9, 0x5ADA, 0x5ADB, 0x5ADC, 0x5ADD,
0x5ADE, 0x5ADF, 0x5AE0, 0x5AE1, 0x5AE2, 0x5AE3, 0x5AE4, 0x5853,
0x5854, 0x5855, 0x5856, 0x5857, 0x5858, 0x5859, 0x585A, 0x61FC,
0x6203, 0x6204, 0x624E, 0x624F, 0x6250, 0x6251, 0x5CDD, 0x5CDE,
0x5CDF, 0x5CE0, 0x5CE1, 0x5CE2, 0x5CE3, 0x5CE4, 0x5CE5, 0x5CE6,
0x5CE7, 0x5CE8, 0x5CE9, 0x5CEA, 0x5CEB, 0x5CEC, 0x5CED, 0x5CEE,
0x5CEF, 0x5CF0, 0x5D9F, 0x5DA0, 0x5DA1, 0x5DA2, 0x5DA3, 0x5DA4,
0x5D4C, 0x5D4D, 0x5D4E, 0x5D4F, 0x5D50, 0x5D51, 0x5D52, 0x5D53,
0x5D54, 0x5D55, 0x5D56, 0x5D57, 0x5D58, 0x5D59, 0x5D5A, 0x5D5B,
0x5D5C, 0x5D5D, 0x5D5E, 0x5D5F, 0x5D60, 0x5D61, 0x5D62, 0x5D63,
0x5D64, 0x5D65, 0x5D66, 0x5D67, 0x5D68, 0x5D69, 0x5D6A, 0x5D6B,
0x5D6C, 0x5D6D, 0x5D6E, 0x5D6F, 0x5D70, 0x5D71, 0x5D72, 0x5D73,
0x5D74, 0x5D75, 0x5D76, 0x5D77, 0x5D78, 0x5D79, 0x5D7A, 0x5D7B,
0x5D7C, 0x5D7D, 0x5D7E, 0x5D7F, 0x5D80, 0x5D81, 0x5D82, 0x5D83,
0x5D84, 0x5D85, 0x5D86, 0x5D87, 0x5D88, 0x5D89, 0x5D8E, 0x5D8F,
0x5D90, 0x5D91, 0x5DAE, 0x5DAF, 0x5DB0, 0x5DB1, 0x5DB2
};
private static readonly int[] m_GravesAndMoundsTiles = new int[]
{
//Graves, coffins, bones, body parts, etc, the dead stuff :)
0x4ECA, 0x4ECB, 0x4ECC, 0x4ECD, 0x4ECE, 0x4ECF, 0x4ED0, 0x4ED1, 0x4ED2,
0x4ED4, 0x4ED5, 0x4ED6, 0x4ED7, 0x4ED8, 0x4ED9, 0x4EDA, 0x4EDB, 0x4EDC,
0x4EDD, 0x4EDE, 0x4ED3, 0x4EDF, 0x4EE0, 0x4EE1, 0x4EE2, 0x4EE8, 0x5165,
0x5166, 0x5167, 0x5168, 0x5169, 0x516A, 0x516B, 0x516C, 0x516D,
0x516E, 0x516F, 0x5170, 0x5171, 0x5172, 0x5173, 0x5174, 0x5175,
0x5176, 0x5177, 0x5178, 0x5179, 0x517A, 0x517B, 0x517C, 0x517D,
0x517E, 0x517F, 0x5180, 0x5181, 0x5182, 0x5183, 0x5184, 0x5C22,
0x5C23, 0x5C24, 0x5C25, 0x5C26, 0x5C27, 0x5C28, 0x5C29, 0x5C2A,
0x5C2B, 0x5C2C, 0x5C2D, 0x5C2E, 0x5C2F, 0x5C30, 0x5C31, 0x5C32,
0x5C33, 0x5C34, 0x5C35, 0x5C36, 0x5C37, 0x5C38, 0x5C39, 0x5C3A,
0x5C3B, 0x5C3C, 0x5C3D, 0x5C3E, 0x5C3F, 0x5C40, 0x5C41, 0x5C42,
0x5C43, 0x5C44, 0x5C45, 0x5C46, 0x5C47, 0x5C48, 0x5C49, 0x5C4A,
0x5C4B, 0x5C4C, 0x5C4D, 0x5C4E, 0x5C4F, 0x5C50, 0x5C51, 0x5C52,
0x5C53, 0x5C54, 0x5C55, 0x5C56, 0x5C57, 0x5C58, 0x5C59, 0x5C5A,
0x5C5B, 0x5C5C, 0x5C5D, 0x5C5E, 0x5C5F, 0x6FF9, 0x6FFA, 0x7048,
0x7049, 0x704A, 0x704B, 0x5C60, 0x5C61, 0x5C62, 0x5C63, 0x5C64,
0x5C65, 0x5C66, 0x5C67, 0x5C68, 0x5C69, 0x5C6A, 0x5C6B, 0x5C6C,
0x5C6D, 0x5C6E, 0x5C6F, 0x5C70, 0x5C71, 0x5C72, 0x5C73, 0x5C74,
0x5C75, 0x5C76, 0x5C77, 0x5C78, 0x5C79, 0x5C7A, 0x5C7B, 0x5C7C,
0x5C7D, 0x5C7E, 0x5C7F, 0x5C80, 0x5C81, 0x5C82, 0x5C83, 0x5C84,
0x5C85, 0x5C86, 0x5C87, 0x5C88, 0x5C89, 0x5C8A, 0x5C8B, 0x5C8C,
0x5C8D, 0x5C8E, 0x5C8F, 0x5C90, 0x5C91, 0x5C92, 0x5C93, 0x5C94,
0x5C95, 0x5C96, 0x5C97, 0x5C98, 0x5C99, 0x5C9A, 0x5C9B, 0x5C9C,
0x5C9D, 0x5C9E, 0x5C9F, 0x5CA0, 0x5CA1, 0x5CA2, 0x5CA3, 0x5CA4,
0x5CA5, 0x5CA6, 0x5CA7, 0x5CA8, 0x5CA9, 0x5CAA, 0x5CAB, 0x5CAC,
0x5CAD, 0x5CAE, 0x5CAF, 0x5CB0, 0x5CB1, 0x5CB2, 0x5CB3, 0x5CB4,
0x5CB5, 0x5CB6, 0x5CB7, 0x5CB8, 0x5CB9, 0x5CBA, 0x5CBB, 0x5CBC,
0x5CBD, 0x5CBE, 0x5CBF, 0x4F7E, 0x5B09, 0x5B0A, 0x5B0B, 0x5B0C,
0x5B0D, 0x5B0E, 0x5B0F, 0x5B10, 0x5B11, 0x5B12, 0x5B13, 0x5B14,
0x5B15, 0x5B16, 0x5B17, 0x5B18, 0x5B19, 0x5B1A, 0x5B1B, 0x5B1C,
0x5B1D, 0x5B1E, 0x5AD8, 0x5AD9, 0x5ADA, 0x5ADB, 0x5ADC, 0x5ADD,
0x5ADE, 0x5ADF, 0x5AE0, 0x5AE1, 0x5AE2, 0x5AE3, 0x5AE4, 0x5853,
0x5854, 0x5855, 0x5856, 0x5857, 0x5858, 0x5859, 0x585A, 0x61FC,
0x6203, 0x6204, 0x624E, 0x624F, 0x6250, 0x6251, 0x5CDD, 0x5CDE,
0x5CDF, 0x5CE0, 0x5CE1, 0x5CE2, 0x5CE3, 0x5CE4, 0x5CE5, 0x5CE6,
0x5CE7, 0x5CE8, 0x5CE9, 0x5CEA, 0x5CEB, 0x5CEC, 0x5CED, 0x5CEE,
0x5CEF, 0x5CF0, 0x5D9F, 0x5DA0, 0x5DA1, 0x5DA2, 0x5DA3, 0x5DA4,
0x5D4C, 0x5D4D, 0x5D4E, 0x5D4F, 0x5D50, 0x5D51, 0x5D52, 0x5D53,
0x5D54, 0x5D55, 0x5D56, 0x5D57, 0x5D58, 0x5D59, 0x5D5A, 0x5D5B,
0x5D5C, 0x5D5D, 0x5D5E, 0x5D5F, 0x5D60, 0x5D61, 0x5D62, 0x5D63,
0x5D64, 0x5D65, 0x5D66, 0x5D67, 0x5D68, 0x5D69, 0x5D6A, 0x5D6B,
0x5D6C, 0x5D6D, 0x5D6E, 0x5D6F, 0x5D70, 0x5D71, 0x5D72, 0x5D73,
0x5D74, 0x5D75, 0x5D76, 0x5D77, 0x5D78, 0x5D79, 0x5D7A, 0x5D7B,
0x5D7C, 0x5D7D, 0x5D7E, 0x5D7F, 0x5D80, 0x5D81, 0x5D82, 0x5D83,
0x5D84, 0x5D85, 0x5D86, 0x5D87, 0x5D88, 0x5D89, 0x5D8E, 0x5D8F,
0x5D90, 0x5D91, 0x5DAE, 0x5DAF, 0x5DB0, 0x5DB1, 0x5DB2
};
#endregion
}
}
|
Ultima-Lokai/ServUO-Lokai
|
Scripts/Custom Systems/Mine/Custom Harvest/Death Harvesting/DeathHarvest.cs
|
C#
|
gpl-2.0
| 17,567
|
/*
* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package test.com.sun.javafx.css;
import com.sun.javafx.css.ParsedValueImpl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import javafx.css.ParsedValue;
import javafx.css.SizeUnits;
import javafx.css.StyleConverter;
import javafx.scene.text.Font;
import org.junit.Test;
import javafx.css.converter.EnumConverter;
public class EnumTypeTest {
public EnumTypeTest() {
}
/**
* Test of convert method, of class EnumType.
*/
@Test
public void testConvert() {
StyleConverter sizeUnitsType = new EnumConverter(SizeUnits.class);
ParsedValue<String,Enum> value =
new ParsedValueImpl<String,Enum>("percent", sizeUnitsType);
Font font = null;
Enum expResult = SizeUnits.PERCENT;
Enum result = value.convert(font);
assertEquals(expResult, result);
value = new ParsedValueImpl<String,Enum>("SizeUnits.PERCENT", sizeUnitsType);
result = value.convert(font);
assertEquals(expResult, result);
try {
value = new ParsedValueImpl<String,Enum>("fubar", sizeUnitsType);
result = value.convert(font);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
}
}
}
|
teamfx/openjfx-10-dev-rt
|
modules/javafx.graphics/src/test/java/test/com/sun/javafx/css/EnumTypeTest.java
|
Java
|
gpl-2.0
| 2,511
|
-- $Id: Ribbons.lua 3171 2008-11-06 09:06:29Z det $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local Ribbon = {}
Ribbon.__index = Ribbon
local RibbonShader
local widthLoc, quadsLoc
local oldPosUniform = {}
local lastTexture
local DLists = {}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon.GetInfo()
return {
name = "Ribbon",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "",
layer = 1, --// extreme simply z-ordering :x
--// gfx requirement
fbo = false,
shader = true,
rtt = false,
ctt = false,
}
end
Ribbon.Default = {
layer = 1,
life = math.huge,
unit = nil,
projectile=nil,
piece = 0,
width = 1,
size = 24, --//max 256
color = {0.9,0.9,1,1},
texture = "bitmaps/GPL/Lups/jet.bmp",
decayRate = 0.01,
worldspace = true,
repeatEffect = true,
dieGameFrame = math.huge,
isvalid = true,
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitIsDead = Spring.GetUnitIsDead
local spIsUnitValid = Spring.IsUnitValid
local spIsSphereInView = Spring.IsSphereInView
local spGetUnitVelocity = Spring.GetUnitVelocity
local spGetUnitPiecePosition = Spring.GetUnitPiecePosition
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spGetUnitPiecePosDir = Spring.GetUnitPiecePosDir
local spGetUnitVectors = Spring.GetUnitVectors
local spGetProjectilePosition = Spring.GetProjectilePosition
local spGetProjectileVelocity = Spring.GetProjectileVelocity
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glUseShader = gl.UseShader
local glColor = gl.Color
local glCallList = gl.CallList
local glTexture = gl.Texture
local glBlending = gl.Blending
local GL_ONE = GL.ONE
local GL_SRC_ALPHA = GL.SRC_ALPHA
local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA
local function GetPiecePos(unit,piece)
local x,y,z = spGetUnitViewPosition(unit,false)
local front,up,right = spGetUnitVectors(unit)
local px,py,pz = spGetUnitPiecePosition(unit,piece)
return x + (pz*front[1] + py*up[1] + px*right[1]),
y + (pz*front[2] + py*up[2] + px*right[2]),
z + (pz*front[3] + py*up[3] + px*right[3])
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon:BeginDraw()
glUseShader(RibbonShader)
glBlending(GL_SRC_ALPHA,GL_ONE)
end
function Ribbon:EndDraw()
glUseShader(0)
glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glTexture(0,false)
lastTexture = nil
glColor(1,1,1,1)
end
function Ribbon:Draw()
local quads0 = self.quads0
if self.texture ~= lastTexture then
glTexture(0,":c:"..self.texture)
lastTexture = self.texture
end
glUniform(widthLoc, self.width )
glUniformInt(quadsLoc, quads0 )
--// insert old pos
local j = ((self.posIdx==self.size) and 1) or (self.posIdx+1)
for i=1,quads0 do
local dir = self.oldPos[j]
j = ((j==self.size) and 1) or (j+1)
glUniform( oldPosUniform[i] , dir[1], dir[2], dir[3] )
end
--// insert interpolated current unit pos
if (self.isvalid) then
--local x,y,z = GetPiecePos(self.unit,self.piecenum)
local x,y,z
if self.unit then
x,y,z = spGetUnitPiecePosDir(self.unit,self.piecenum)
elseif self.projectile then
x,y,z = spGetProjectilePosition(self.projectile)
end
if x and y and z then
glUniform( oldPosUniform[quads0+1] , x,y,z )
end
else
local dir = self.oldPos[j]
glUniform( oldPosUniform[quads0+1] , dir[1], dir[2], dir[3] )
end
--// define color and add speed blending (don't show ribbon for slow/landing units!)
if (self.blendfactor<1) then
local clr = self.color
glColor(clr[1],clr[2],clr[3],clr[4]*self.blendfactor)
else
glColor(self.color)
end
glCallList(DLists[quads0])
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon.Initialize()
RibbonShader = gl.CreateShader({
vertex = [[
uniform float width;
uniform int quads;
uniform vec3 oldPos[256];
varying vec2 texCoord;
void main()
{
vec3 updir,right;
vec3 vertex = oldPos[int(gl_MultiTexCoord0.w)];
gl_Position = gl_ModelViewMatrix * vec4(vertex,1.0);
vec3 vertex2,pos2;
if (int(gl_MultiTexCoord0.w) == quads) {
vertex2 = oldPos[int(gl_MultiTexCoord0.w)-1];
pos2 = (gl_ModelViewMatrix * vec4(vertex2,1.0)).xyz;
updir = gl_Position.xyz - pos2.xyz;
}else{
vertex2 = oldPos[int(gl_MultiTexCoord0.w)+1];
pos2 = (gl_ModelViewMatrix * vec4(vertex2,1.0)).xyz;
updir = pos2.xyz - gl_Position.xyz;
}
right = normalize( cross(updir,gl_Position.xyz) );
gl_Position.xyz += right * gl_MultiTexCoord0.x * width;
gl_Position = gl_ProjectionMatrix * gl_Position;
texCoord = gl_MultiTexCoord0.pt;
gl_FrontColor = gl_Color;
}
]],
fragment = [[
uniform sampler2D ribbonTex;
varying vec2 texCoord;
void main()
{
gl_FragColor = texture2D(ribbonTex, texCoord )*gl_Color;
}
]],
uniformInt={
ribbonTex = 0,
},
})
if (RibbonShader == nil) then
print(PRIO_MAJOR,"LUPS->Ribbon: critical shader error: "..gl.GetShaderLog())
return false
end
widthLoc = gl.GetUniformLocation(RibbonShader, 'width')
quadsLoc = gl.GetUniformLocation(RibbonShader, 'quads')
for i=1,256 do
oldPosUniform[i] = gl.GetUniformLocation(RibbonShader,"oldPos["..(i-1).."]")
end
end
function Ribbon.Finalize()
if (gl.DeleteShader) then
gl.DeleteShader(RibbonShader)
end
while (next(DLists)) do
local i,v = next(DLists)
DLists[i] = nil
gl.DeleteList(v)
end
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon:Update(n)
self.isvalid = (self.unit and spGetUnitIsDead(self.unit) == false) or (self.projectile and Spring.GetProjectileDefID(self.projectile))
if (self.isvalid) then
local x,y,z
if self.unit then
x, y, z = spGetUnitPiecePosDir(self.unit,self.piecenum)
elseif self.projectile then
x,y,z = spGetProjectilePosition(self.projectile)
end
if x and y and z then
self.posIdx = (self.posIdx % self.size)+1
self.oldPos[self.posIdx] = {x,y,z}
local vx,vy,vz
if self.unit then
vx, vy, vz = spGetUnitVelocity(self.unit)
elseif self.projectile then
vx, vy, vz = spGetProjectileVelocity(self.projectile)
end
if vx and vy and vz then
self.blendfactor = (vx*vx+vy*vy+vz*vz)/30
end
end
else
local lastIndex = self.posIdx
self.posIdx = (self.posIdx % self.size)+1
self.oldPos[self.posIdx] = self.oldPos[lastIndex]
self.blendfactor = self.blendfactor - n * self.decayRate
end
end
function Ribbon:Visible()
self.isvalid = (self.unit and spGetUnitIsDead(self.unit) == false) or (self.projectile and Spring.GetProjectileDefID(self.projectile))
local pos = self.oldPos[self.posIdx]
return (self.blendfactor>0) and (spIsSphereInView(pos[1],pos[2],pos[3], self.radius))
end
function Ribbon:Valid()
return self.isvalid or (self.blendfactor>0)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local function CreateDList(quads0)
for i=0,quads0-1 do
local tex_t = i/quads0
local tex_t_next = (i+1)/quads0
gl.TexCoord(-1,tex_t_next,0,i+1)
gl.Vertex(0,0,0)
gl.TexCoord(1,tex_t_next,1,i+1)
gl.Vertex(0,0,0)
gl.TexCoord(1,tex_t,1,i)
gl.Vertex(0,0,0)
gl.TexCoord(-1,tex_t,0,i)
gl.Vertex(0,0,0)
end
end
-- used if repeatEffect=true;
function Ribbon:ReInitialize()
self.dieGameFrame = self.dieGameFrame + self.life
end
function Ribbon:CreateParticle()
if (self.size>256) then self.size=256
elseif (self.size<2) then self.size=2 end
self.posIdx = 1
self.quads0 = self.size-1
self.blendfactor = 1
local x,y,z
if self.unit then
x,y,z = spGetUnitPiecePosDir(self.unit,self.piecenum)
elseif self.projectile then
x,y,z = spGetProjectilePosition(self.projectile)
end
local curpos = {x,y,z}
self.oldPos = {}
for i=1,self.size do
self.oldPos[i] = curpos
end
local udid = self.unit and spGetUnitDefID(self.unit)
local weapon = self.weapon
local speed = self.speed or (UnitDefs[udid] and UnitDefs[udid].speed) or (weapon and WeaponDefs[weapon] and WeaponDefs[weapon].projectilespeed*30) or 100
self.radius = (speed/30.0)*self.size
if (not DLists[self.quads0]) then
DLists[self.quads0] = gl.CreateList(gl.BeginEnd,GL.QUADS,CreateDList,self.quads0)
end
self.startGameFrame = thisGameFrame
self.dieGameFrame = self.startGameFrame + self.life
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local MergeTable = MergeTable
local setmetatable = setmetatable
function Ribbon.Create(Options)
local newObject = MergeTable(Options, Ribbon.Default)
setmetatable(newObject,Ribbon) -- make handle lookup
newObject:CreateParticle()
return newObject
end
function Ribbon:Destroy()
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return Ribbon
|
Zero-K-Experiments/Zero-K-Experiments
|
lups/ParticleClasses/Ribbons.lua
|
Lua
|
gpl-2.0
| 10,821
|
<?php
/**
* @package Gantry5
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC
* @license Dual License: MIT or GNU/GPLv2 and later
*
* http://opensource.org/licenses/MIT
* http://www.gnu.org/licenses/gpl-2.0.html
*
* Gantry Framework code that extends GPL code is considered GNU/GPLv2 and later
*/
namespace Gantry\Component\Twig;
class TwigNodeStyles extends TwigNodeScripts {
protected $tagName = 'styles';
}
|
joseclavijo/gsclube
|
wp-content/plugins/gantry5/src/classes/Gantry/Component/Twig/TwigNodeStyles.php
|
PHP
|
gpl-2.0
| 490
|
DELETE FROM `spell_script_names` WHERE `ScriptName`='spell_pal_righteous_defense';
INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES
(31789,'spell_pal_righteous_defense');
|
avalonfr/avalon_core_v1
|
sql/avalon/version_1/44 - Fix spell Defense vertueuse.sql
|
SQL
|
gpl-2.0
| 187
|
/*
* Copyright (C) 2013-2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.DashboardView = class DashboardView extends WebInspector.Object
{
constructor(representedObject, identifier)
{
console.assert(identifier);
super();
this._representedObject = representedObject;
this._element = document.createElement("div");
this._element.classList.add("dashboard");
this._element.classList.add(identifier);
}
// Static
static create(representedObject)
{
console.assert(representedObject);
if (representedObject instanceof WebInspector.DefaultDashboard)
return new WebInspector.DefaultDashboardView(representedObject);
if (representedObject instanceof WebInspector.DebuggerDashboard)
return new WebInspector.DebuggerDashboardView(representedObject);
if (representedObject instanceof WebInspector.ReplayDashboard)
return new WebInspector.ReplayDashboardView(representedObject);
throw "Can't make a DashboardView for an unknown representedObject.";
}
// Public
get element()
{
return this._element;
}
get representedObject()
{
return this._representedObject;
}
shown()
{
// Implemented by subclasses.
}
hidden()
{
// Implemented by subclasses.
}
closed()
{
// Implemented by subclasses.
}
};
|
qtproject/qtwebkit
|
Source/WebInspectorUI/UserInterface/Views/DashboardView.js
|
JavaScript
|
gpl-2.0
| 2,750
|
/* ------------------------------------------------------------------
* Copyright (C) 2008 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.073
ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
Available from http://www.3gpp.org
(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
------------------------------------------------------------------------------
Filename: /audio/gsm_amr/c/include/q_plsf.h
Date: 02/04/2002
------------------------------------------------------------------------------
REVISION HISTORY
Description: Placed header file in the proper template format. Added
parameter pOverflow for the basic math ops.
Description: Replaced "int" and/or "char" with OSCL defined types.
Description: Moved _cplusplus #ifdef after Include section.
Description:
------------------------------------------------------------------------------
INCLUDE DESCRIPTION
This file contains all the constant definitions and prototype definitions
needed by the q_plsf_3.c and q_plsf_5.c
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; CONTINUE ONLY IF NOT ALREADY DEFINED
----------------------------------------------------------------------------*/
#ifndef q_plsf_h
#define q_plsf_h "$Id $"
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "typedef.h"
#include "cnst.h"
#include "mode.h"
/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C"
{
#endif
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here.
----------------------------------------------------------------------------*/
#define MR795_1_SIZE 512
#define PAST_RQ_INIT_SIZE 8
#define DICO1_SIZE 256
#define DICO2_SIZE 512
#define DICO3_SIZE 512
#define DICO1_5_SIZE 128
#define DICO2_5_SIZE 256
#define DICO3_5_SIZE 256
#define DICO4_5_SIZE 256
#define DICO5_5_SIZE 64
#define MR515_3_SIZE 128
/*----------------------------------------------------------------------------
; EXTERNAL VARIABLES REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; SIMPLE TYPEDEF'S
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; ENUMERATED TYPEDEF'S
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; STRUCTURES TYPEDEF'S
----------------------------------------------------------------------------*/
typedef struct
{
Word16 past_rq[M]; /* Past quantized prediction error, Q15 */
} Q_plsfState;
/*----------------------------------------------------------------------------
; GLOBAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
Word16 Q_plsf_init(Q_plsfState **st);
/* initialize one instance of the state.
Stores pointer to filter status struct in *st. This pointer has to
be passed to Q_plsf_5 / Q_plsf_3 in each call.
returns 0 on success
*/
Word16 Q_plsf_reset(Q_plsfState *st);
/* reset of state (i.e. set state memory to zero)
returns 0 on success
*/
void Q_plsf_exit(Q_plsfState **st);
/* de-initialize state (i.e. free status struct)
stores NULL in *st
*/
void Q_plsf_3(
Q_plsfState *st, /* i/o: state struct */
enum Mode mode, /* i : coder mode */
Word16 *lsp1, /* i : 1st LSP vector Q15 */
Word16 *lsp1_q, /* o : quantized 1st LSP vector Q15 */
Word16 *indice, /* o : quantization indices of 3 vectors Q0 */
Word16 *pred_init_i,/* o : init index for MA prediction in DTX mode */
Flag *pOverflow /* o : Flag set when overflow occurs */
);
void Q_plsf_5(
Q_plsfState *st,
Word16 *lsp1, /* i : 1st LSP vector, Q15 */
Word16 *lsp2, /* i : 2nd LSP vector, Q15 */
Word16 *lsp1_q, /* o : quantized 1st LSP vector, Q15 */
Word16 *lsp2_q, /* o : quantized 2nd LSP vector, Q15 */
Word16 *indice, /* o : quantization indices of 5 matrices, Q0 */
Flag *pOverflow /* o : Flag set when overflow occurs */
);
/*----------------------------------------------------------------------------
; END
----------------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif /* _Q_PLSF_H_ */
|
MoSync/MoSync
|
intlibs/gsm_amr/amr_nb/common/include/q_plsf.h
|
C
|
gpl-2.0
| 6,518
|
/* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Code Aurora Forum nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* Alternatively, provided that this notice is retained in full, this software
* may be relicensed by the recipient under the terms of the GNU General Public
* License version 2 ("GPL") and only version 2, in which case the provisions of
* the GPL apply INSTEAD OF those given above. If the recipient relicenses the
* software under the GPL, then the identification text in the MODULE_LICENSE
* macro must be changed to reflect "GPLv2" instead of "Dual BSD/GPL". Once a
* recipient changes the license terms to the GPL, subsequent recipients shall
* not relicense under alternate licensing terms, including the BSD or dual
* BSD/GPL terms. In addition, the following license statement immediately
* below and between the words START and END shall also then apply when this
* software is relicensed under the GPL:
*
* START
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 and only version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* END
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/i2c.h>
#include <linux/uaccess.h>
#include <linux/miscdevice.h>
#include <media/msm_camera.h>
#include <mach/gpio.h>
#include <mach/camera.h>
#include "mt9t013.h"
#ifdef CONFIG_HUAWEI_CAMERA
#undef CDBG
#define CDBG(fmt, args...) printk(KERN_INFO "mt9t013_byd.c: " fmt, ## args)
#endif
/*Micron settings from Applications for lower power consumption.*/
static struct reg_struct const mt9t013_byd_reg_pat[2] = {
{ /* Preview 2x2 binning 20fps, pclk MHz, MCLK 24MHz */
/* vt_pix_clk_div:REG=0x0300 update get_snapshot_fps
* if this change */
8,
/* vt_sys_clk_div: REG=0x0302 update get_snapshot_fps
* if this change */
1,
/* pre_pll_clk_div REG=0x0304 update get_snapshot_fps
* if this change */
2,
/* pll_multiplier REG=0x0306 60 for 30fps preview, 40
* for 20fps preview
* 46 for 30fps preview, try 47/48 to increase further */
32,
/* op_pix_clk_div REG=0x0308 */
8,
/* op_sys_clk_div REG=0x030A */
1,
/* scale_m REG=0x0404 */
16,
/* row_speed REG=0x3016 */
0x0111,
/* x_addr_start REG=0x3004 */
8,
/* x_addr_end REG=0x3008 */
2053,
/* y_addr_start REG=0x3002 */
8,
/* y_addr_end REG=0x3006 */
1541,
/* read_mode REG=0x3040 */
#ifndef CONFIG_HUAWEI_CAMERA
0x046C,
#else
0x046F,
#endif
/* x_output_size REG=0x034C */
1024,
/* y_output_size REG=0x034E */
768,
/* line_length_pck REG=0x300C */
2616,
/* frame_length_lines REG=0x300A */
916,
/* coarse_int_time REG=0x3012 */
16,
/* fine_int_time REG=0x3014 */
1461
},
{ /*Snapshot */
/* vt_pix_clk_div REG=0x0300 update get_snapshot_fps
* if this change */
8,
/* vt_sys_clk_div REG=0x0302 update get_snapshot_fps
* if this change */
1,
/* pre_pll_clk_div REG=0x0304 update get_snapshot_fps
* if this change */
2,
/* pll_multiplier REG=0x0306 50 for 15fps snapshot,
* 40 for 10fps snapshot
* 46 for 30fps snapshot, try 47/48 to increase further */
32,
/* op_pix_clk_div REG=0x0308 */
8,
/* op_sys_clk_div REG=0x030A */
1,
/* scale_m REG=0x0404 */
16,
/* row_speed REG=0x3016 */
0x0111,
/* x_addr_start REG=0x3004 */
8,
/* x_addr_end REG=0x3008 */
2071,
/* y_addr_start REG=0x3002 */
8,
/* y_addr_end REG=0x3006 */
1551,
/* read_mode REG=0x3040 */
#ifndef CONFIG_HUAWEI_CAMERA
0x0024,
#else
0x0027,
#endif
/* x_output_size REG=0x034C */
2064,
/* y_output_size REG=0x034E */
1544,
/* line_length_pck REG=0x300C */
2954,
/* frame_length_lines REG=0x300A */
1629,
/* coarse_int_time REG=0x3012 */
16,
/* fine_int_time REG=0x3014 */
733
}
};
static struct mt9t013_i2c_reg_conf const mt9t013_byd_test_tbl[] = {
{ 0x3044, 0x0544 & 0xFBFF },
{ 0x30CA, 0x0004 | 0x0001 },
{ 0x30D4, 0x9020 & 0x7FFF },
{ 0x31E0, 0x0003 & 0xFFFE },
{ 0x3180, 0x91FF & 0x7FFF },
{ 0x301A, (0x10CC | 0x8000) & 0xFFF7 },
{ 0x301E, 0x0000 },
{ 0x3780, 0x0000 },
};
/* [Lens shading 85 Percent TL84] */
static struct mt9t013_i2c_reg_conf const mt9t013_byd_lc_tbl[] = {
{ 0x360A, 0x00F0 },
{ 0x360C, 0x9A4D },
{ 0x360E, 0x6891 },
{ 0x3610, 0x5F4B },
{ 0x3612, 0x8670 },
{ 0x364A, 0x154B },
{ 0x364C, 0xCC2B },
{ 0x364E, 0x030F },
{ 0x3650, 0xC40F },
{ 0x3652, 0xD6EF },
{ 0x368A, 0x3331 },
{ 0x368C, 0x8830 },
{ 0x368E, 0x2453 },
{ 0x3690, 0x4252 },
{ 0x3692, 0x8E56 },
{ 0x36CA, 0x4AEE },
{ 0x36CC, 0xD36F },
{ 0x36CE, 0x9A31 },
{ 0x36D0, 0x2632 },
{ 0x36D2, 0x0732 },
{ 0x370A, 0x6EF0 },
{ 0x370C, 0x4531 },
{ 0x370E, 0xE276 },
{ 0x3710, 0x9C34 },
{ 0x3712, 0x1C79 },
{ 0x3600, 0x0190 },
{ 0x3602, 0x138E },
{ 0x3604, 0x4E91 },
{ 0x3606, 0x298F },
{ 0x3608, 0x8D6E },
{ 0x3640, 0xA748 },
{ 0x3642, 0x07AC },
{ 0x3644, 0xBE6E },
{ 0x3646, 0xBE50 },
{ 0x3648, 0x14CD },
{ 0x3680, 0x1691 },
{ 0x3682, 0x088F },
{ 0x3684, 0x04D3 },
{ 0x3686, 0xA0CF },
{ 0x3688, 0xE515 },
{ 0x36C0, 0x964D },
{ 0x36C2, 0x9B10 },
{ 0x36C4, 0x8D92 },
{ 0x36C6, 0x4532 },
{ 0x36C8, 0x46B4 },
{ 0x3700, 0x8D0D },
{ 0x3702, 0xDE6B },
{ 0x3704, 0xAB96 },
{ 0x3706, 0xBDD3 },
{ 0x3708, 0x7338 },
{ 0x3614, 0x0190 },
{ 0x3616, 0x7C0D },
{ 0x3618, 0x3391 },
{ 0x361A, 0x2BCE },
{ 0x361C, 0xF24E },
{ 0x3654, 0x844D },
{ 0x3656, 0xC56D },
{ 0x3658, 0x140E },
{ 0x365A, 0x9DED },
{ 0x365C, 0x104E },
{ 0x3694, 0x0831 },
{ 0x3696, 0x6A8E },
{ 0x3698, 0x4991 },
{ 0x369A, 0xBE6F },
{ 0x369C, 0x98B5 },
{ 0x36D4, 0x2E8D },
{ 0x36D6, 0x474B },
{ 0x36D8, 0x8571 },
{ 0x36DA, 0x1FD0 },
{ 0x36DC, 0x16B2 },
{ 0x3714, 0x476E },
{ 0x3716, 0xA7F1 },
{ 0x3718, 0xE855 },
{ 0x371A, 0x7412 },
{ 0x371C, 0x5658 },
{ 0x361E, 0x0170 },
{ 0x3620, 0xFAAD },
{ 0x3622, 0x3F31 },
{ 0x3624, 0x0ACD },
{ 0x3626, 0xE4EF },
{ 0x365E, 0xB3EC },
{ 0x3660, 0x3D0D },
{ 0x3662, 0x4A4C },
{ 0x3664, 0xFEAF },
{ 0x3666, 0x0AEE },
{ 0x369E, 0x1AD1 },
{ 0x36A0, 0x8CD0 },
{ 0x36A2, 0x20F2 },
{ 0x36A4, 0x3A12 },
{ 0x36A6, 0xACF5 },
{ 0x36DE, 0xDD4C },
{ 0x36E0, 0x9C2F },
{ 0x36E2, 0xBEF1 },
{ 0x36E4, 0x0C11 },
{ 0x36E6, 0x7313 },
{ 0x371E, 0xB86F },
{ 0x3720, 0x7531 },
{ 0x3722, 0x9076 },
{ 0x3724, 0x9DF4 },
{ 0x3726, 0x60D8 },
{ 0x3782, 0x0400 },
{ 0x3784, 0x0300 },
{ 0x3780, 0x8000 },
};
static struct mt9t013_reg mt9t013_byd_regs = {
.reg_pat = &mt9t013_byd_reg_pat[0],
.reg_pat_size = ARRAY_SIZE(mt9t013_byd_reg_pat),
.ttbl = &mt9t013_byd_test_tbl[0],
.ttbl_size = ARRAY_SIZE(mt9t013_byd_test_tbl),
.lctbl = &mt9t013_byd_lc_tbl[0],
.lctbl_size = ARRAY_SIZE(mt9t013_byd_lc_tbl),
.rftbl = &mt9t013_byd_lc_tbl[0], /* &mt9t013_byd_rolloff_tbl[0], */
.rftbl_size = ARRAY_SIZE(mt9t013_byd_lc_tbl)
};
/*=============================================================
SENSOR REGISTER DEFINES
==============================================================*/
#define MT9T013_REG_MODEL_ID 0x0000
#define MT9T013_MODEL_ID 0x2600
#define REG_GROUPED_PARAMETER_HOLD 0x0104
#define GROUPED_PARAMETER_HOLD 0x0100
#define GROUPED_PARAMETER_UPDATE 0x0000
#define REG_COARSE_INT_TIME 0x3012
#define REG_VT_PIX_CLK_DIV 0x0300
#define REG_VT_SYS_CLK_DIV 0x0302
#define REG_PRE_PLL_CLK_DIV 0x0304
#define REG_PLL_MULTIPLIER 0x0306
#define REG_OP_PIX_CLK_DIV 0x0308
#define REG_OP_SYS_CLK_DIV 0x030A
#define REG_SCALE_M 0x0404
#define REG_FRAME_LENGTH_LINES 0x300A
#define REG_LINE_LENGTH_PCK 0x300C
#define REG_X_ADDR_START 0x3004
#define REG_Y_ADDR_START 0x3002
#define REG_X_ADDR_END 0x3008
#define REG_Y_ADDR_END 0x3006
#define REG_X_OUTPUT_SIZE 0x034C
#define REG_Y_OUTPUT_SIZE 0x034E
#define REG_FINE_INT_TIME 0x3014
#define REG_ROW_SPEED 0x3016
#define MT9T013_REG_RESET_REGISTER 0x301A
#define MT9T013_RESET_REGISTER_PWON 0x10CC
#define MT9T013_RESET_REGISTER_PWOFF 0x1008 /* 0x10C8 stop streaming*/
#define REG_READ_MODE 0x3040
#define REG_GLOBAL_GAIN 0x305E
#define REG_TEST_PATTERN_MODE 0x3070
#define BYD_3M_MODE_ID 0xF2
enum mt9t013_test_mode_t {
TEST_OFF,
TEST_1,
TEST_2,
TEST_3
};
enum mt9t013_resolution_t {
QTR_SIZE,
FULL_SIZE,
INVALID_SIZE
};
enum mt9t013_reg_update_t {
/* Sensor egisters that need to be updated during initialization */
REG_INIT,
/* Sensor egisters that needs periodic I2C writes */
UPDATE_PERIODIC,
/* All the sensor Registers will be updated */
UPDATE_ALL,
/* Not valid update */
UPDATE_INVALID
};
enum mt9t013_setting_t {
RES_PREVIEW,
RES_CAPTURE
};
/* actuator's Slave Address */
#define MT9T013_AF_I2C_ADDR 0x18
/*
* AF Total steps parameters
*/
#define MT9T013_TOTAL_STEPS_NEAR_TO_FAR 28 /* 28 */
#define MT9T013_POSITION_MAX 1023
#define MT9T013_ONE_STEP_POSITION ((MT9T013_POSITION_MAX+1)/MT9T013_TOTAL_STEPS_NEAR_TO_FAR)
/*
* Time in milisecs for waiting for the sensor to reset.
*/
#define MT9T013_RESET_DELAY_MSECS 66
/* for 30 fps preview */
#define MT9T013_DEFAULT_CLOCK_RATE 24000000
#define MT9T013_DEFAULT_MAX_FPS 26
/* FIXME: Changes from here */
struct mt9t013_work_t {
struct work_struct work;
};
static struct mt9t013_work_t *mt9t013_sensorw;
static struct i2c_client *mt9t013_client;
struct mt9t013_ctrl_t {
const struct msm_camera_sensor_info *sensordata;
int sensormode;
uint32_t fps_divider; /* init to 1 * 0x00000400 */
uint32_t pict_fps_divider; /* init to 1 * 0x00000400 */
uint16_t curr_lens_pos;
uint16_t init_curr_lens_pos;
uint16_t my_reg_gain;
uint32_t my_reg_line_count;
enum mt9t013_resolution_t prev_res;
enum mt9t013_resolution_t pict_res;
enum mt9t013_resolution_t curr_res;
enum mt9t013_test_mode_t set_test;
unsigned short imgaddr;
};
static struct mt9t013_ctrl_t *mt9t013_ctrl;
static DECLARE_WAIT_QUEUE_HEAD(mt9t013_wait_queue);
DECLARE_MUTEX(mt9t013_byd_sem);
/*=============================================================*/
static int mt9t013_i2c_rxdata(unsigned short saddr,
unsigned char *rxdata, int length)
{
struct i2c_msg msgs[] = {
{
.addr = saddr,
.flags = 0,
.len = 2,
.buf = rxdata,
},
{
.addr = saddr,
.flags = I2C_M_RD,
.len = length,
.buf = rxdata,
},
};
if (i2c_transfer(mt9t013_client->adapter, msgs, 2) < 0) {
CDBG("mt9t013_i2c_rxdata failed!\n");
return -EIO;
}
return 0;
}
static int32_t mt9t013_i2c_read_w(unsigned short saddr,
unsigned short raddr, unsigned short *rdata)
{
int32_t rc = 0;
unsigned char buf[4];
if (!rdata)
return -EIO;
memset(buf, 0, sizeof(buf));
buf[0] = (raddr & 0xFF00)>>8;
buf[1] = (raddr & 0x00FF);
rc = mt9t013_i2c_rxdata(saddr, buf, 2);
if (rc < 0)
return rc;
*rdata = buf[0] << 8 | buf[1];
if (rc < 0)
CDBG("mt9t013_i2c_read failed!\n");
return rc;
}
static int32_t mt9t013_i2c_txdata(unsigned short saddr,
unsigned char *txdata, int length)
{
struct i2c_msg msg[] = {
{
.addr = saddr,
.flags = 0,
.len = length,
.buf = txdata,
},
};
if (i2c_transfer(mt9t013_client->adapter, msg, 1) < 0) {
CDBG("mt9t013_i2c_txdata faild\n");
return -EIO;
}
return 0;
}
static int32_t mt9t013_i2c_write_b(unsigned short saddr,
unsigned short waddr, unsigned short wdata)
{
int32_t rc = -EFAULT;
unsigned char buf[2];
memset(buf, 0, sizeof(buf));
buf[0] = waddr;
buf[1] = wdata;
rc = mt9t013_i2c_txdata(saddr, buf, 2);
if (rc < 0)
CDBG("i2c_write failed, addr = 0x%x, val = 0x%x!\n",
waddr, wdata);
return rc;
}
static int32_t mt9t013_i2c_write_w(unsigned short saddr,
unsigned short waddr, unsigned short wdata)
{
int32_t rc = -EFAULT;
unsigned char buf[4];
memset(buf, 0, sizeof(buf));
buf[0] = (waddr & 0xFF00)>>8;
buf[1] = (waddr & 0x00FF);
buf[2] = (wdata & 0xFF00)>>8;
buf[3] = (wdata & 0x00FF);
rc = mt9t013_i2c_txdata(saddr, buf, 4);
if (rc < 0)
CDBG("i2c_write_w failed, addr = 0x%x, val = 0x%x!\n",
waddr, wdata);
return rc;
}
static int32_t mt9t013_i2c_write_w_table(
struct mt9t013_i2c_reg_conf const *reg_conf_tbl,
int num_of_items_in_table)
{
int i;
int32_t rc = -EFAULT;
for (i = 0; i < num_of_items_in_table; i++) {
rc = mt9t013_i2c_write_w(mt9t013_client->addr,
reg_conf_tbl->waddr, reg_conf_tbl->wdata);
if (rc < 0)
break;
reg_conf_tbl++;
}
return rc;
}
static int32_t mt9t013_test(enum mt9t013_test_mode_t mo)
{
int32_t rc = 0;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (rc < 0)
return rc;
if (mo == TEST_OFF)
return 0;
else {
rc = mt9t013_i2c_write_w_table(mt9t013_regs.ttbl,
mt9t013_regs.ttbl_size);
if (rc < 0)
return rc;
rc = mt9t013_i2c_write_w(mt9t013_client->addr,
REG_TEST_PATTERN_MODE, (uint16_t)mo);
if (rc < 0)
return rc;
}
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_UPDATE);
if (rc < 0)
return rc;
return rc;
}
static int32_t mt9t013_set_lc(void)
{
int32_t rc;
/* rc = mt9t013_i2c_write_w_table(mt9t013_regs.lctbl,
* ARRAY_SIZE(mt9t013_regs.lctbl)); */
rc = mt9t013_i2c_write_w_table(mt9t013_regs.lctbl,
mt9t013_regs.lctbl_size);
if (rc < 0)
return rc;
return rc;
}
static int32_t mt9t013_set_default_focus(uint8_t af_step)
{
#ifndef CONFIG_HUAWEI_CAMERA
int32_t rc = 0;
uint8_t code_val_msb, code_val_lsb;
code_val_msb = 0x01;
code_val_lsb = af_step;
/* Write the digital code for current to the actuator */
rc =
mt9t013_i2c_write_b(MT9T013_AF_I2C_ADDR>>1,
code_val_msb, code_val_lsb);
mt9t013_ctrl->curr_lens_pos = 0;
mt9t013_ctrl->init_curr_lens_pos = 0;
return rc;
#else
int32_t rc = 0;
uint8_t code_val_msb, code_val_lsb;
int16_t next_position;
CDBG("mt9t013_set_default_focus,af_step:%d\n", af_step);
next_position = MT9T013_ONE_STEP_POSITION * af_step;
code_val_msb =
((next_position >> 4) & 0x3f);
code_val_lsb =
((next_position & 0x0f) << 4);
/* Write the digital code for current to the actuator */
rc = mt9t013_i2c_write_b(MT9T013_AF_I2C_ADDR >> 1,
code_val_msb, code_val_lsb);
mt9t013_ctrl->curr_lens_pos = next_position;
mt9t013_ctrl->init_curr_lens_pos = next_position;
return rc;
#endif
}
static void mt9t013_get_pict_fps(uint16_t fps, uint16_t *pfps)
{
/* input fps is preview fps in Q8 format */
uint32_t divider; /*Q10 */
uint32_t pclk_mult; /*Q10 */
if (mt9t013_ctrl->prev_res == QTR_SIZE) {
divider =
(uint32_t)(
((mt9t013_regs.reg_pat[RES_PREVIEW].frame_length_lines *
mt9t013_regs.reg_pat[RES_PREVIEW].line_length_pck) *
0x00000400) /
(mt9t013_regs.reg_pat[RES_CAPTURE].frame_length_lines *
mt9t013_regs.reg_pat[RES_CAPTURE].line_length_pck));
pclk_mult =
(uint32_t) ((mt9t013_regs.reg_pat[RES_CAPTURE].pll_multiplier *
0x00000400) /
(mt9t013_regs.reg_pat[RES_PREVIEW].pll_multiplier));
} else {
/* full size resolution used for preview. */
divider = 0x00000400; /*1.0 */
pclk_mult = 0x00000400; /*1.0 */
}
/* Verify PCLK settings and frame sizes. */
*pfps =
(uint16_t) (fps * divider * pclk_mult /
0x00000400 / 0x00000400);
}
static uint16_t mt9t013_get_prev_lines_pf(void)
{
if (mt9t013_ctrl->prev_res == QTR_SIZE)
return mt9t013_regs.reg_pat[RES_PREVIEW].frame_length_lines;
else
return mt9t013_regs.reg_pat[RES_CAPTURE].frame_length_lines;
}
static uint16_t mt9t013_get_prev_pixels_pl(void)
{
if (mt9t013_ctrl->prev_res == QTR_SIZE)
return mt9t013_regs.reg_pat[RES_PREVIEW].line_length_pck;
else
return mt9t013_regs.reg_pat[RES_CAPTURE].line_length_pck;
}
static uint16_t mt9t013_get_pict_lines_pf(void)
{
return mt9t013_regs.reg_pat[RES_CAPTURE].frame_length_lines;
}
static uint16_t mt9t013_get_pict_pixels_pl(void)
{
return mt9t013_regs.reg_pat[RES_CAPTURE].line_length_pck;
}
static uint32_t mt9t013_get_pict_max_exp_lc(void)
{
uint16_t snapshot_lines_per_frame;
if (mt9t013_ctrl->pict_res == QTR_SIZE) {
snapshot_lines_per_frame =
mt9t013_regs.reg_pat[RES_PREVIEW].frame_length_lines - 1;
} else {
snapshot_lines_per_frame =
mt9t013_regs.reg_pat[RES_CAPTURE].frame_length_lines - 1;
}
return snapshot_lines_per_frame * 24;
}
static int32_t mt9t013_set_fps(struct fps_cfg *fps)
{
/* input is new fps in Q8 format */
int32_t rc = 0;
mt9t013_ctrl->fps_divider = fps->fps_div;
mt9t013_ctrl->pict_fps_divider = fps->pict_fps_div;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (rc < 0)
return -EBUSY;
CDBG("mt9t013_set_fps: fps_div is %d, frame_rate is %d\n",
fps->fps_div,
(uint16_t) (
mt9t013_regs.reg_pat[RES_PREVIEW].frame_length_lines *
fps->fps_div/0x00000400));
CDBG("mt9t013_set_fps: fps_mult is %d, frame_rate is %d\n",
fps->f_mult,
(uint16_t) (
mt9t013_regs.reg_pat[RES_PREVIEW].line_length_pck *
fps->f_mult / 0x00000400));
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_LINE_LENGTH_PCK,
(uint16_t) (
mt9t013_regs.reg_pat[RES_PREVIEW].line_length_pck *
fps->f_mult / 0x00000400));
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_UPDATE);
if (rc < 0)
return rc;
return rc;
}
static int32_t mt9t013_write_exp_gain(uint16_t gain, uint32_t line)
{
uint16_t max_legal_gain = 0x01FF;
enum mt9t013_setting_t setting;
int32_t rc = 0;
if (mt9t013_ctrl->sensormode ==
SENSOR_PREVIEW_MODE) {
mt9t013_ctrl->my_reg_gain = gain;
mt9t013_ctrl->my_reg_line_count = (uint16_t) line;
}
if (gain > 0x00000400)
gain = max_legal_gain;
/* Verify no overflow */
if (mt9t013_ctrl->sensormode != SENSOR_SNAPSHOT_MODE) {
line =
(uint32_t) (line * mt9t013_ctrl->fps_divider /
0x00000400);
setting = RES_PREVIEW;
} else {
line =
(uint32_t) (line * mt9t013_ctrl->pict_fps_divider /
0x00000400);
setting = RES_CAPTURE;
}
/*Set digital gain to 1 */
gain |= 0x0200;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GLOBAL_GAIN, gain);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_COARSE_INT_TIME,
line );
if (rc < 0)
return rc;
return rc;
}
static int32_t mt9t013_set_pict_exp_gain(uint16_t gain, uint32_t line)
{
int32_t rc = 0;
rc =
mt9t013_write_exp_gain(gain, line);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
0x10CC | 0x0002);
mdelay(5);
/* camera_timed_wait(snapshot_wait*exposure_ratio); */
return rc;
}
static int32_t mt9t013_setting(enum mt9t013_reg_update_t rupdate,
enum mt9t013_setting_t rt)
{
int32_t rc = 0;
switch (rupdate) {
case UPDATE_PERIODIC: {
if (rt == RES_PREVIEW ||
rt == RES_CAPTURE) {
#if 0
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
MT9T013_RESET_REGISTER_PWOFF);
if (rc < 0)
return rc;
#endif
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_VT_PIX_CLK_DIV,
mt9t013_regs.reg_pat[rt].vt_pix_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_VT_SYS_CLK_DIV,
mt9t013_regs.reg_pat[rt].vt_sys_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_PRE_PLL_CLK_DIV,
mt9t013_regs.reg_pat[rt].pre_pll_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_PLL_MULTIPLIER,
mt9t013_regs.reg_pat[rt].pll_multiplier);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_OP_PIX_CLK_DIV,
mt9t013_regs.reg_pat[rt].op_pix_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_OP_SYS_CLK_DIV,
mt9t013_regs.reg_pat[rt].op_sys_clk_div);
if (rc < 0)
return rc;
mdelay(5);
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_ROW_SPEED,
mt9t013_regs.reg_pat[rt].row_speed);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_X_ADDR_START,
mt9t013_regs.reg_pat[rt].x_addr_start);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_X_ADDR_END,
mt9t013_regs.reg_pat[rt].x_addr_end);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_Y_ADDR_START,
mt9t013_regs.reg_pat[rt].y_addr_start);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_Y_ADDR_END,
mt9t013_regs.reg_pat[rt].y_addr_end);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_READ_MODE,
mt9t013_regs.reg_pat[rt].read_mode);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_SCALE_M,
mt9t013_regs.reg_pat[rt].scale_m);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_X_OUTPUT_SIZE,
mt9t013_regs.reg_pat[rt].x_output_size);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_Y_OUTPUT_SIZE,
mt9t013_regs.reg_pat[rt].y_output_size);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_LINE_LENGTH_PCK,
mt9t013_regs.reg_pat[rt].line_length_pck);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_FRAME_LENGTH_LINES,
(mt9t013_regs.reg_pat[rt].frame_length_lines *
mt9t013_ctrl->fps_divider / 0x00000400));
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_COARSE_INT_TIME,
mt9t013_regs.reg_pat[rt].coarse_int_time);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_FINE_INT_TIME,
mt9t013_regs.reg_pat[rt].fine_int_time);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_UPDATE);
if (rc < 0)
return rc;
rc = mt9t013_test(mt9t013_ctrl->set_test);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
MT9T013_RESET_REGISTER_PWON);
if (rc < 0)
return rc;
mdelay(5);
return rc;
}
}
break;
/*CAMSENSOR_REG_UPDATE_PERIODIC */
case REG_INIT: {
if (rt == RES_PREVIEW ||
rt == RES_CAPTURE) {
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
MT9T013_RESET_REGISTER_PWOFF);
if (rc < 0)
/* MODE_SELECT, stop streaming */
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_VT_PIX_CLK_DIV,
mt9t013_regs.reg_pat[rt].vt_pix_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_VT_SYS_CLK_DIV,
mt9t013_regs.reg_pat[rt].vt_sys_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_PRE_PLL_CLK_DIV,
mt9t013_regs.reg_pat[rt].pre_pll_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_PLL_MULTIPLIER,
mt9t013_regs.reg_pat[rt].pll_multiplier);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_OP_PIX_CLK_DIV,
mt9t013_regs.reg_pat[rt].op_pix_clk_div);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_OP_SYS_CLK_DIV,
mt9t013_regs.reg_pat[rt].op_sys_clk_div);
if (rc < 0)
return rc;
mdelay(5);
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (rc < 0)
return rc;
/* additional power saving mode ok around 38.2MHz */
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
0x3084, 0x2409);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
0x3092, 0x0A49);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
0x3094, 0x4949);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
0x3096, 0x4949);
if (rc < 0)
return rc;
/* Set preview or snapshot mode */
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_ROW_SPEED,
mt9t013_regs.reg_pat[rt].row_speed);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_X_ADDR_START,
mt9t013_regs.reg_pat[rt].x_addr_start);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_X_ADDR_END,
mt9t013_regs.reg_pat[rt].x_addr_end);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_Y_ADDR_START,
mt9t013_regs.reg_pat[rt].y_addr_start);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_Y_ADDR_END,
mt9t013_regs.reg_pat[rt].y_addr_end);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_READ_MODE,
mt9t013_regs.reg_pat[rt].read_mode);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_SCALE_M,
mt9t013_regs.reg_pat[rt].scale_m);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_X_OUTPUT_SIZE,
mt9t013_regs.reg_pat[rt].x_output_size);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_Y_OUTPUT_SIZE,
mt9t013_regs.reg_pat[rt].y_output_size);
if (rc < 0)
return 0;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_LINE_LENGTH_PCK,
mt9t013_regs.reg_pat[rt].line_length_pck);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_FRAME_LENGTH_LINES,
mt9t013_regs.reg_pat[rt].frame_length_lines);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_COARSE_INT_TIME,
mt9t013_regs.reg_pat[rt].coarse_int_time);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_FINE_INT_TIME,
mt9t013_regs.reg_pat[rt].fine_int_time);
if (rc < 0)
return rc;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_UPDATE);
if (rc < 0)
return rc;
/* load lens shading */
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (rc < 0)
return rc;
/* most likely needs to be written only once. */
rc = mt9t013_set_lc();
if (rc < 0)
return -EBUSY;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_UPDATE);
if (rc < 0)
return rc;
rc = mt9t013_test(mt9t013_ctrl->set_test);
if (rc < 0)
return rc;
mdelay(5);
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
MT9T013_RESET_REGISTER_PWON);
if (rc < 0)
/* MODE_SELECT, stop streaming */
return rc;
CDBG("!!! mt9t013 !!! PowerOn is done!\n");
mdelay(5);
return rc;
}
} /* case CAMSENSOR_REG_INIT: */
break;
/*CAMSENSOR_REG_INIT */
default:
rc = -EFAULT;
break;
} /* switch (rupdate) */
return rc;
}
static int32_t mt9t013_video_config(int mode, int res)
{
int32_t rc;
switch (res) {
case QTR_SIZE:
rc = mt9t013_setting(UPDATE_PERIODIC, RES_PREVIEW);
if (rc < 0)
return rc;
CDBG("sensor configuration done!\n");
break;
case FULL_SIZE:
rc = mt9t013_setting(UPDATE_PERIODIC, RES_CAPTURE);
if (rc < 0)
return rc;
break;
default:
return 0;
} /* switch */
mt9t013_ctrl->prev_res = res;
mt9t013_ctrl->curr_res = res;
mt9t013_ctrl->sensormode = mode;
rc =
mt9t013_write_exp_gain(mt9t013_ctrl->my_reg_gain,
mt9t013_ctrl->my_reg_line_count);
return rc;
}
static int32_t mt9t013_snapshot_config(int mode)
{
int32_t rc = 0;
rc =
mt9t013_setting(UPDATE_PERIODIC, RES_CAPTURE);
if (rc < 0)
return rc;
mt9t013_ctrl->curr_res = mt9t013_ctrl->pict_res;
mt9t013_ctrl->sensormode = mode;
return rc;
}
static int32_t mt9t013_raw_snapshot_config(int mode)
{
int32_t rc = 0;
rc = mt9t013_setting(UPDATE_PERIODIC, RES_CAPTURE);
if (rc < 0)
return rc;
mt9t013_ctrl->curr_res = mt9t013_ctrl->pict_res;
mt9t013_ctrl->sensormode = mode;
return rc;
}
static int32_t mt9t013_power_down(void)
{
int32_t rc = 0;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
MT9T013_RESET_REGISTER_PWOFF);
mdelay(5);
return rc;
}
static int32_t mt9t013_move_focus(int direction,
int32_t num_steps)
{
#ifndef CONFIG_HUAWEI_CAMERA
int16_t step_direction;
int16_t actual_step;
int16_t next_position;
int16_t break_steps[4];
uint8_t code_val_msb, code_val_lsb;
int16_t i;
if (num_steps > MT9T013_TOTAL_STEPS_NEAR_TO_FAR)
num_steps = MT9T013_TOTAL_STEPS_NEAR_TO_FAR;
else if (num_steps == 0)
return -EINVAL;
if (direction == MOVE_NEAR)
step_direction = 4;
else if (direction == MOVE_FAR)
step_direction = -4;
else
return -EINVAL;
if (mt9t013_ctrl->curr_lens_pos < mt9t013_ctrl->init_curr_lens_pos)
mt9t013_ctrl->curr_lens_pos = mt9t013_ctrl->init_curr_lens_pos;
actual_step =
(int16_t) (step_direction *
(int16_t) num_steps);
for (i = 0; i < 4; i++)
break_steps[i] =
actual_step / 4 * (i + 1) - actual_step / 4 * i;
for (i = 0; i < 4; i++) {
next_position =
(int16_t)
(mt9t013_ctrl->curr_lens_pos + break_steps[i]);
if (next_position > 255)
next_position = 255;
else if (next_position < 0)
next_position = 0;
code_val_msb =
((next_position >> 4) << 2) |
((next_position << 4) >> 6);
code_val_lsb =
((next_position & 0x03) << 6);
/* Writing the digital code for current to the actuator */
if (mt9t013_i2c_write_b(MT9T013_AF_I2C_ADDR>>1,
code_val_msb, code_val_lsb) < 0)
return -EBUSY;
/* Storing the current lens Position */
mt9t013_ctrl->curr_lens_pos = next_position;
if (i < 3)
mdelay(1);
} /* for */
return 0;
#else
int16_t step_direction;
int16_t actual_step;
int16_t next_position;
uint8_t code_val_msb, code_val_lsb;
if (num_steps > MT9T013_TOTAL_STEPS_NEAR_TO_FAR)
num_steps = MT9T013_TOTAL_STEPS_NEAR_TO_FAR;
else if (num_steps == 0)
return -EINVAL;
if (direction == MOVE_NEAR)
step_direction = MT9T013_ONE_STEP_POSITION;
else if (direction == MOVE_FAR)
step_direction = -1 * MT9T013_ONE_STEP_POSITION;
else
return -EINVAL;
if (mt9t013_ctrl->curr_lens_pos < mt9t013_ctrl->init_curr_lens_pos)
mt9t013_ctrl->curr_lens_pos = mt9t013_ctrl->init_curr_lens_pos;
actual_step = (int16_t)(step_direction * (int16_t)num_steps);
next_position = (int16_t)(mt9t013_ctrl->curr_lens_pos + actual_step);
if (next_position > MT9T013_POSITION_MAX)
{
next_position = MT9T013_POSITION_MAX;
}
else if (next_position < 0)
{
next_position = 0;
}
code_val_msb =
((next_position >> 4) & 0x3f);
code_val_lsb =
((next_position & 0x0f) << 4);
/* Writing the digital code for current to the actuator */
if (mt9t013_i2c_write_b(MT9T013_AF_I2C_ADDR>>1,
code_val_msb, code_val_lsb) < 0)
{
CDBG("mt9t013_i2c_write_b is failed in mt9t013_move_focus\n");
return -EBUSY;
}
/* Storing the current lens Position */
mt9t013_ctrl->curr_lens_pos = next_position;
mdelay(1);
return 0;
#endif
}
static int mt9t013_sensor_init_done(const struct msm_camera_sensor_info *data)
{
gpio_direction_output(data->sensor_reset, 0);
gpio_free(data->sensor_reset);
#ifdef CONFIG_HUAWEI_CAMERA
gpio_direction_output(data->sensor_pwd, 1);
gpio_free(data->sensor_pwd);
gpio_direction_output(data->vcm_pwd, 0);
gpio_free(data->vcm_pwd);
if (data->vreg_disable_func)
{
data->vreg_disable_func(data->sensor_vreg, data->vreg_num);
}
#endif
return 0;
}
static int mt9t013_probe_init_sensor(const struct msm_camera_sensor_info *data)
{
int rc;
uint16_t chipid;
uint16_t mode_id;
#ifndef CONFIG_HUAWEI_CAMERA
rc = gpio_request(data->sensor_reset, "mt9t013");
if (!rc)
gpio_direction_output(data->sensor_reset, 1);
else
goto init_probe_done;
msleep(20);
#else
/* pull down power down */
rc = gpio_request(data->sensor_pwd, "mt9t013");
if (!rc || rc == -EBUSY)
gpio_direction_output(data->sensor_pwd, 1);
else
goto init_probe_fail;
rc = gpio_request(data->sensor_reset, "mt9t013");
if (!rc) {
rc = gpio_direction_output(data->sensor_reset, 0);
}
else
goto init_probe_fail;
mdelay(5);
if (data->vreg_enable_func)
{
rc = data->vreg_enable_func(data->sensor_vreg, data->vreg_num);
if (rc < 0)
{
goto init_probe_fail;
}
}
mdelay(20);
if(data->master_init_control_slave == NULL
|| data->master_init_control_slave(data) != 0
)
{
rc = gpio_direction_output(data->sensor_pwd, 0);
if (rc < 0)
goto init_probe_fail;
mdelay(20);
/*hardware reset*/
rc = gpio_direction_output(data->sensor_reset, 1);
if (rc < 0)
goto init_probe_fail;
mdelay(20);
}
/* pull down power down */
rc = gpio_request(data->vcm_pwd, "mt9t013");
if (!rc || rc == -EBUSY)
gpio_direction_output(data->vcm_pwd, 1);
else
goto init_probe_fail;
mdelay(2);
#endif
/* RESET the sensor image part via I2C command */
rc = mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER, 0x1009);
if (rc < 0)
goto init_probe_fail;
msleep(10);
/* 3. Read sensor Model ID: */
rc = mt9t013_i2c_read_w(mt9t013_client->addr,
MT9T013_REG_MODEL_ID, &chipid);
if (rc < 0)
goto init_probe_fail;
CDBG("mt9t013_byd chipid = 0x%x\n", chipid);
/* 4. Compare sensor ID to MT9T012VC ID: */
if (chipid != MT9T013_MODEL_ID) {
rc = -ENODEV;
goto init_probe_fail;
}
rc = mt9t013_i2c_write_w(mt9t013_client->addr,
0x3064, 0x0805);
if (rc < 0)
goto init_probe_fail;
mdelay(MT9T013_RESET_DELAY_MSECS);
/*ÔÚ¶ÁÈ¡GPIO״̬֮ǰ£¬0x301A¼Ä´æÆ÷µÄbit8±ØÐëÏÈд1£¬È»ºó²ÅÄÜÕýÈ·¶ÁÈ¡*/
rc = mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER, MT9T013_RESET_REGISTER_PWON | 0x0100);
if (rc < 0)
goto init_probe_fail;
/*¶ÁÈ¡GPIO״̬¼Ä´æÆ÷£¬µÍËÄλ±êʾGPIO״̬£¬¸ß12λĬÈÏֵΪ0xFFF£¬
ΪÁ˱ãÓÚºÍSOC2030Çø±ð£¬3MÉãÏñÍ·ÌáÈ¡µÍ°ËλÀ´Ê¶±ð²»Í¬µÄÄ£×é*/
rc = mt9t013_i2c_read_w(mt9t013_client->addr,
0x3026, &mode_id);
CDBG("mt9t013_byd model_id = 0x%x\n", mode_id);
if (rc < 0)
goto init_probe_fail;
/*ÌáÈ¡±êʶλ*/
mode_id = mode_id & 0xff;
if(BYD_3M_MODE_ID != mode_id)
{
rc = -ENODEV;
goto init_probe_fail;
}
goto init_probe_done;
/* sensor: output enable */
#if 0
rc = mt9t013_i2c_write_w(mt9t013_client->addr,
MT9T013_REG_RESET_REGISTER,
MT9T013_RESET_REGISTER_PWON);
/* if this fails, the sensor is not the MT9T013 */
rc = mt9t013_set_default_focus(0);
#endif
init_probe_fail:
#ifndef CONFIG_HUAWEI_CAMERA
gpio_direction_output(data->sensor_reset, 0);
gpio_free(data->sensor_reset);
#else
mt9t013_sensor_init_done(data);
#endif
init_probe_done:
return rc;
}
static int mt9t013_sensor_open_init(const struct msm_camera_sensor_info *data)
{
int32_t rc;
mt9t013_ctrl = kzalloc(sizeof(struct mt9t013_ctrl_t), GFP_KERNEL);
if (!mt9t013_ctrl) {
CDBG("mt9t013_init failed!\n");
rc = -ENOMEM;
goto init_done;
}
mt9t013_ctrl->fps_divider = 1 * 0x00000400;
mt9t013_ctrl->pict_fps_divider = 1 * 0x00000400;
mt9t013_ctrl->set_test = TEST_OFF;
mt9t013_ctrl->prev_res = QTR_SIZE;
mt9t013_ctrl->pict_res = FULL_SIZE;
if (data)
mt9t013_ctrl->sensordata = data;
/* enable mclk first */
msm_camio_clk_rate_set(MT9T013_DEFAULT_CLOCK_RATE);
mdelay(20);
msm_camio_camif_pad_reg_reset();
mdelay(20);
rc = mt9t013_probe_init_sensor(data);
if (rc < 0)
goto init_fail;
if (mt9t013_ctrl->prev_res == QTR_SIZE)
rc = mt9t013_setting(REG_INIT, RES_PREVIEW);
else
rc = mt9t013_setting(REG_INIT, RES_CAPTURE);
if (rc < 0)
goto init_fail;
else
goto init_done;
#ifdef CONFIG_HUAWEI_CAMERA
rc = mt9t013_set_default_focus(1);
if (rc < 0)
goto init_fail;
else
goto init_done;
#endif
init_fail:
kfree(mt9t013_ctrl);
init_done:
return rc;
}
static int mt9t013_init_client(struct i2c_client *client)
{
/* Initialize the MSM_CAMI2C Chip */
init_waitqueue_head(&mt9t013_wait_queue);
return 0;
}
static int32_t mt9t013_set_sensor_mode(int mode, int res)
{
int32_t rc = 0;
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (rc < 0)
return rc;
switch (mode) {
case SENSOR_PREVIEW_MODE:
rc = mt9t013_video_config(mode, res);
break;
case SENSOR_SNAPSHOT_MODE:
rc = mt9t013_snapshot_config(mode);
break;
case SENSOR_RAW_SNAPSHOT_MODE:
rc = mt9t013_raw_snapshot_config(mode);
break;
default:
rc = -EINVAL;
break;
}
rc =
mt9t013_i2c_write_w(mt9t013_client->addr,
REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_UPDATE);
return rc;
}
static int mt9t013_sensor_config(void __user *argp)
{
struct sensor_cfg_data cdata;
long rc = 0;
if (copy_from_user(&cdata,
(void *)argp,
sizeof(struct sensor_cfg_data)))
return -EFAULT;
down(&mt9t013_byd_sem);
switch (cdata.cfgtype) {
case CFG_GET_PICT_FPS:
mt9t013_get_pict_fps(
cdata.cfg.gfps.prevfps,
&(cdata.cfg.gfps.pictfps));
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PREV_L_PF:
cdata.cfg.prevl_pf =
mt9t013_get_prev_lines_pf();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PREV_P_PL:
cdata.cfg.prevp_pl =
mt9t013_get_prev_pixels_pl();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_L_PF:
cdata.cfg.pictl_pf =
mt9t013_get_pict_lines_pf();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_P_PL:
cdata.cfg.pictp_pl =
mt9t013_get_pict_pixels_pl();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_MAX_EXP_LC:
cdata.cfg.pict_max_exp_lc =
mt9t013_get_pict_max_exp_lc();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_SET_FPS:
case CFG_SET_PICT_FPS:
rc = mt9t013_set_fps(&(cdata.cfg.fps));
break;
case CFG_SET_EXP_GAIN:
rc =
mt9t013_write_exp_gain(
cdata.cfg.exp_gain.gain,
cdata.cfg.exp_gain.line);
break;
case CFG_SET_PICT_EXP_GAIN:
rc =
mt9t013_set_pict_exp_gain(
cdata.cfg.exp_gain.gain,
cdata.cfg.exp_gain.line);
break;
case CFG_SET_MODE:
rc = mt9t013_set_sensor_mode(cdata.mode,
cdata.rs);
break;
case CFG_PWR_DOWN:
rc = mt9t013_power_down();
break;
case CFG_MOVE_FOCUS:
rc =
mt9t013_move_focus(
cdata.cfg.focus.dir,
cdata.cfg.focus.steps);
break;
case CFG_SET_DEFAULT_FOCUS:
rc =
mt9t013_set_default_focus(
cdata.cfg.focus.steps);
break;
case CFG_SET_EFFECT:
rc = mt9t013_set_default_focus(
cdata.cfg.effect);
break;
default:
rc = -EFAULT;
break;
}
up(&mt9t013_byd_sem);
return rc;
}
static int mt9t013_sensor_release(void)
{
int rc = -EBADF;
down(&mt9t013_byd_sem);
mt9t013_power_down();
#ifndef CONFIG_HUAWEI_CAMERA
gpio_direction_output(mt9t013_ctrl->sensordata->sensor_reset,
0);
gpio_free(mt9t013_ctrl->sensordata->sensor_reset);
#else
mt9t013_sensor_init_done(mt9t013_ctrl->sensordata);
#endif
kfree(mt9t013_ctrl);
up(&mt9t013_byd_sem);
CDBG("mt9t013_release completed!\n");
return rc;
}
static int mt9t013_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
rc = -ENOTSUPP;
goto probe_failure;
}
mt9t013_sensorw =
kzalloc(sizeof(struct mt9t013_work_t), GFP_KERNEL);
if (!mt9t013_sensorw) {
rc = -ENOMEM;
goto probe_failure;
}
i2c_set_clientdata(client, mt9t013_sensorw);
mt9t013_init_client(client);
mt9t013_client = client;
mt9t013_client->addr = mt9t013_client->addr >> 1;
mdelay(50);
CDBG("i2c probe ok\n");
return 0;
probe_failure:
kfree(mt9t013_sensorw);
mt9t013_sensorw = NULL;
pr_err("i2c probe failure %d\n", rc);
return rc;
}
static const struct i2c_device_id mt9t013_i2c_id[] = {
{ "mt9t013_byd", 0},
{ }
};
static struct i2c_driver mt9t013_i2c_driver = {
.id_table = mt9t013_i2c_id,
.probe = mt9t013_i2c_probe,
.remove = __exit_p(mt9t013_i2c_remove),
.driver = {
.name = "mt9t013_byd",
},
};
static int mt9t013_sensor_probe(
const struct msm_camera_sensor_info *info,
struct msm_sensor_ctrl *s)
{
/* We expect this driver to match with the i2c device registered
* in the board file immediately. */
int rc = i2c_add_driver(&mt9t013_i2c_driver);
if (rc < 0 || mt9t013_client == NULL) {
rc = -ENOTSUPP;
goto probe_done;
}
/* enable mclk first */
msm_camio_clk_rate_set(MT9T013_DEFAULT_CLOCK_RATE);
mdelay(20);
rc = mt9t013_probe_init_sensor(info);
if (rc < 0) {
i2c_del_driver(&mt9t013_i2c_driver);
goto probe_done;
}
mt9t013_regs = mt9t013_byd_regs;
s->s_init = mt9t013_sensor_open_init;
s->s_release = mt9t013_sensor_release;
s->s_config = mt9t013_sensor_config;
mt9t013_sensor_init_done(info);
probe_done:
return rc;
}
static int __mt9t013_probe(struct platform_device *pdev)
{
return msm_camera_drv_start(pdev, mt9t013_sensor_probe);
}
static struct platform_driver msm_camera_driver = {
.probe = __mt9t013_probe,
.driver = {
.name = "msm_camera_byd3m",
.owner = THIS_MODULE,
},
};
static int __init mt9t013_byd_init(void)
{
return platform_driver_register(&msm_camera_driver);
}
late_initcall(mt9t013_byd_init);
|
mtuton/linux_u82x0
|
drivers/media/video/msm/mt9t013_byd.c
|
C
|
gpl-2.0
| 44,180
|
<?php
/**
* Eds autocomplete test class.
*
* PHP version 7
*
* Copyright (C) Villanova University 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Tests
* @author Demian Katz <demian.katz@villanova.edu>
* @author Jochen Lienhard <jochen.lienhard@ub.uni-freiburg.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFindTest\Autocomplete;
use VuFind\Autocomplete\Eds;
/**
* Eds autocomplete test class.
*
* @category VuFind
* @package Tests
* @author Demian Katz <demian.katz@villanova.edu>
* @author Jochen Lienhard <jochen.lienhard@ub.uni-freiburg.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class EdsTest extends \PHPUnit\Framework\TestCase
{
/**
* Get a mock backend
*
* @param string $id ID of fake backend.
*
* @return \VuFindSearch\Backend\EDS\Backend
*/
protected function getMockBackend($id = 'EDS')
{
return $this->getMockBuilder(\VuFindSearch\Backend\EDS\Backend::class)
->onlyMethods(['autocomplete'])
->disableOriginalConstructor()->getMock();
}
/**
* Test getSuggestions.
*
* @return void
*/
public function testGetSuggestions()
{
$backend = $this->getMockBackend();
$eds = new Eds($backend);
$backend->expects($this->once())
->method('autocomplete')
->with($this->equalTo('query'), $this->equalTo('rawqueries'))
->will($this->returnValue([1, 2, 3]));
$this->assertEquals([1, 2, 3], $eds->getSuggestions('query'));
}
/**
* Test getSuggestions with non-default configuration.
*
* @return void
*/
public function testGetSuggestionsWithNonDefaultConfiguration()
{
$backend = $this->getMockBackend();
$eds = new Eds($backend);
$eds->setConfig('holdings');
$backend->expects($this->once())
->method('autocomplete')
->with($this->equalTo('query'), $this->equalTo('holdings'))
->will($this->returnValue([4, 5]));
$this->assertEquals([4, 5], $eds->getSuggestions('query'));
}
}
|
stweil/vufind
|
module/VuFind/tests/unit-tests/src/VuFindTest/Autocomplete/EdsTest.php
|
PHP
|
gpl-2.0
| 2,934
|
<?php
/*-----------------------------------------------------------------
!!!!警告!!!!
以下为系统文件,请勿修改
-----------------------------------------------------------------*/
//不能非法包含或直接执行
if(!defined("IN_BAIGO")) {
exit("Access Denied");
}
include_once(BG_PATH_INC . "common_admin_ajax.inc.php"); //管理员通用
include_once(BG_PATH_CONTROL_ADMIN . "ajax/user.class.php"); //载入用户控制器
$ajax_user = new AJAX_USER(); //初始化用户
switch ($GLOBALS["act_post"]) {
case "submit":
$ajax_user->ajax_submit(); //创建、编辑
break;
case "enable":
case "wait":
case "disable":
$ajax_user->ajax_status(); //状态
break;
case "del":
$ajax_user->ajax_del(); //删除
break;
default:
switch ($GLOBALS["act_get"]) {
case "chkname":
$ajax_user->ajax_chkname(); //验证用户名
break;
case "chkmail":
$ajax_user->ajax_chkmail(); //验证 email
break;
}
break;
}
|
KangbingZhao/baigoSSO
|
core/module/admin/ajax/user.php
|
PHP
|
gpl-2.0
| 979
|
/**
* Theme Customizer enhancements for a better user experience.
*
* Contains handlers to make Theme Customizer preview reload changes asynchronously.
*/
( function( $ ) {
// Site title and description.
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( '.site-title a' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.site-description' ).text( to );
} );
} );
//Logo size
wp.customize('logo_size',function( value ) {
value.bind( function( newval ) {
$('.site-logo').css('max-width', newval + 'px' );
} );
});
// Font sizes
wp.customize('site_title_size',function( value ) {
value.bind( function( newval ) {
$('.site-title').css('font-size', newval + 'px' );
} );
});
wp.customize('site_desc_size',function( value ) {
value.bind( function( newval ) {
$('.site-description').css('font-size', newval + 'px' );
} );
});
wp.customize('body_size',function( value ) {
value.bind( function( newval ) {
$('body').css('font-size', newval + 'px' );
} );
});
//Site title
wp.customize('site_title_color',function( value ) {
value.bind( function( newval ) {
$('.site-title a').css('color', newval );
} );
});
//Site desc
wp.customize('site_desc_color',function( value ) {
value.bind( function( newval ) {
$('.site-description').css('color', newval );
} );
});
// Body text color
wp.customize('body_text_color',function( value ) {
value.bind( function( newval ) {
$('body, .widget a').css('color', newval );
} );
});
} )( jQuery );
|
christiannwamba/codedevfolks
|
wp-content/themes/oria/js/customizer.js
|
JavaScript
|
gpl-2.0
| 1,755
|
/*
* Copyright (c) 2012 Denis Solonenko.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
package ru.orangesoftware.financisto.activity;
import ru.orangesoftware.financisto.R;
import ru.orangesoftware.financisto.model.Total;
/**
* Created by IntelliJ IDEA.
* User: denis.solonenko
* Date: 3/15/12 16:40 PM
*/
public class AccountListTotalsDetailsActivity extends AbstractTotalsDetailsActivity {
public AccountListTotalsDetailsActivity() {
super(R.string.account_total_in_currency);
}
protected Total getTotalInHomeCurrency() {
return db.getAccountsTotalInHomeCurrency();
}
protected Total[] getTotals() {
return db.getAccountsTotal();
}
}
|
liquidmetal/financisto
|
src/ru/orangesoftware/financisto/activity/AccountListTotalsDetailsActivity.java
|
Java
|
gpl-2.0
| 942
|
<!-- INCLUDE overall_header.html -->
<h2>{L_TITLE}</h2>
<!-- IF S_TICKET_REPLY -->
<p>{L_TITLE_EXPLAIN}</p>
<!-- ENDIF -->
<!-- IF TICKET_HIDDEN or TICKET_SECURITY -->
<div class="rules" align="center">
<div class="inner"><span class="corners-top"><span></span></span>
<!-- IF TICKET_HIDDEN -->{L_TRACKER_TICKET_HIDDEN_FROM_VIEW}<!-- ENDIF -->
<!-- IF TICKET_HIDDEN and TICKET_SECURITY --><br /><!-- ENDIF -->
<!-- IF TICKET_SECURITY -->{L_TRACKER_TICKET_SECURITY_FROM_VIEW}<!-- ENDIF -->
<span class="corners-bottom"><span></span></span></div>
</div>
<br />
<!-- ENDIF -->
<div id="col1">
<!-- IF not S_TICKET_REPLY -->
<h3 style="color: #D21A4E;<!-- IF TICKET_CLOSED --> text-decoration: line-through;<!-- ENDIF -->">{TICKET_TITLE}<span style="color: black;"> {TICKET_STATUS}</span></h3>
<div class="post bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<div class="postbody" style="width: auto; float: none; margin: 0; height: auto;">
<!-- IF not S_IS_BOT -->
<!-- IF S_CAN_DELETE or S_CAN_EDIT -->
<ul class="profile-icons">
<!-- IF S_CAN_EDIT --><li class="edit-icon"><a href="{U_EDIT}" title="{L_EDIT_POST}"><span>{L_EDIT_POST}</span></a></li><!-- ENDIF -->
<!-- IF S_CAN_DELETE --><li class="delete-icon"><a href="{U_DELETE}" title="{L_DELETE_POST}"><span>{L_DELETE_POST}</span></a></li><!-- ENDIF -->
</ul>
<!-- ENDIF -->
<!-- ENDIF -->
<p class="author"> </p>
<div class="content">{TICKET_DESC}</div>
<!-- IF S_TICKET_HAS_ATTACHMENTS -->
<dl class="attachbox">
<dt>{L_ATTACHMENTS}</dt>
<!-- BEGIN attachment -->
<dd>{attachment.DISPLAY_ATTACHMENT}</dd>
<!-- END attachment -->
</dl>
<!-- ENDIF -->
<!-- IF S_DISPLAY_NOTICE --><div class="rules">{L_DOWNLOAD_NOTICE}</div><!-- ENDIF -->
<!-- IF EDITED_MESSAGE or EDIT_REASON -->
<div class="notice">{EDITED_MESSAGE}
<!-- IF EDIT_REASON --><br /><strong>{L_REASON}:</strong> <em>{EDIT_REASON}</em><!-- ENDIF -->
</div>
<!-- ENDIF -->
</div>
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- IF S_DISPLAY_COMMENTS -->
<h3>{L_TRACKER_TICKET_COMMENTS}</h3>
<!-- BEGIN comments -->
<div id="p{comments.POST_ID}" class="post <!-- IF comments.S_ROW_COUNT is odd --> bg1<!-- ELSE --> bg2<!-- ENDIF -->">
<div class="inner"><span class="corners-top"><span></span></span>
<div class="postbody" style="width: auto; float: none; margin: 0; height: auto;">
<!-- IF not S_IS_BOT -->
<!-- IF comments.S_CAN_DELETE or comments.S_CAN_EDIT -->
<ul class="profile-icons">
<!-- IF comments.S_CAN_EDIT --><li class="edit-icon"><a href="{comments.U_EDIT}" title="{L_EDIT_POST}"><span>{L_EDIT_POST}</span></a></li><!-- ENDIF -->
<!-- IF comments.S_CAN_DELETE --><li class="delete-icon"><a href="{comments.U_DELETE}" title="{L_DELETE_POST}"><span>{L_DELETE_POST}</span></a></li><!-- ENDIF -->
</ul>
<!-- ENDIF -->
<!-- ENDIF -->
<p class="author"><a href="#p{comments.POST_ID}">{POST_IMG}</a> <strong>{comments.COMMENT_POSTER}</strong></p>
<div class="content">{comments.COMMENT_DESC}</div>
<!-- IF comments.S_HAS_ATTACHMENTS -->
<dl class="attachbox">
<dt>{L_ATTACHMENTS}</dt>
<!-- BEGIN attachment -->
<dd>{comments.attachment.DISPLAY_ATTACHMENT}</dd>
<!-- END attachment -->
</dl>
<!-- ENDIF -->
<!-- IF comments.S_DISPLAY_NOTICE --><div class="rules">{L_DOWNLOAD_NOTICE}</div><!-- ENDIF -->
<!-- IF comments.EDITED_MESSAGE or comments.EDIT_REASON -->
<div class="notice">{comments.EDITED_MESSAGE}
<!-- IF comments.EDIT_REASON --><br /><strong>{L_REASON}:</strong> <em>{comments.EDIT_REASON}</em><!-- ENDIF -->
</div>
<!-- ENDIF -->
</div>
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- BEGINELSE -->
<div class="post bg1">
<div class="inner"><span class="corners-top"><span></span></span>
{L_TRACKER_TICKET_NO_COMMENTS}
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- END -->
<!-- ENDIF -->
<!-- IF S_DISPLAY_HISTORY -->
<h3>{L_TRACKER_TICKET_HISTORY}</h3>
<!-- BEGIN history -->
<div class="post <!-- IF history.S_ROW_COUNT is odd --> bg1<!-- ELSE --> bg2<!-- ENDIF -->">
<div class="inner"><span class="corners-top"><span></span></span>
<strong>{history.HISTORY_ACTION}</strong>
<div style="margin-top: 10px; padding-top: 2px; border-top: 1px dashed #CCCCCC;">{history.HISTORY_ACTION_BY}</div>
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- BEGINELSE -->
<div class="post bg1">
<div class="inner"><span class="corners-top"><span></span></span>
{L_TRACKER_TICKET_NO_HISTORY}
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- END -->
<!-- ENDIF -->
<!-- IF S_CAN_POST_TRACKER or PAGINATION or TOTAL_POSTS -->
<div class="topic-actions">
<!-- IF S_CAN_POST_TRACKER and not S_IS_BOT -->
<div class="buttons">
<div class="<!-- IF S_IS_LOCKED -->locked-icon<!-- ELSE -->reply-icon<!-- ENDIF -->"><a href="{U_POST_REPLY_TICKET}" title="<!-- IF S_IS_LOCKED -->{L_TOPIC_LOCKED}<!-- ELSE -->{L_POST_REPLY}<!-- ENDIF -->"><span></span><!-- IF S_IS_LOCKED -->{L_TOPIC_LOCKED_SHORT}<!-- ELSE -->{L_POST_REPLY}<!-- ENDIF --></a></div>
</div>
<!-- ENDIF -->
<!-- IF PAGINATION or TOTAL_POSTS -->
<div class="pagination">
{TOTAL_POSTS}
<!-- IF PAGE_NUMBER --><!-- IF PAGINATION --> • <a href="#" onclick="jumpto(); return false;" title="{L_JUMP_TO_PAGE}">{PAGE_NUMBER}</a> • <span>{PAGINATION}</span><!-- ELSE --> • {PAGE_NUMBER}<!-- ENDIF --><!-- ENDIF -->
</div>
<!-- ENDIF -->
</div>
<!-- ENDIF -->
<!-- ELSE -->
<!-- IF S_PREVIEW -->
<h3>{L_TRACKER_PREVIEW}</h3>
<div class="panel bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<div class="postbody" style="width: auto; float: none; margin: 0; height: auto;">
<div class="content">{REPLY_PREVIEW}</div>
<!-- IF .attachment -->
<dl class="attachbox">
<dt>{L_ATTACHMENTS}</dt>
<!-- BEGIN attachment -->
<dd>{attachment.DISPLAY_ATTACHMENT}</dd>
<!-- END attachment -->
</dl>
<!-- ENDIF -->
</div>
<span class="corners-bottom"><span></span></span></div>
</div>
<br />
<!-- ENDIF -->
<form id="postform" action="{U_ACTION}" method="post"{S_FORM_ENCTYPE}>
<div class="panel bg2">
<span class="corners-top"><span></span></span>
<h3>{L_MESSAGE}</h3>
<fieldset class="fields1">
<!-- IF ERROR --><p class="error">{ERROR}</p><!-- ENDIF -->
<!-- IF S_DISPLAY_USERNAME -->
<dl style="clear: left;">
<dt><label for="username">{L_USERNAME}:</label></dt>
<dd><input type="text" tabindex="1" name="username" id="username" size="25" value="{USERNAME}" class="inputbox autowidth" /></dd>
</dl>
<!-- ENDIF -->
<!-- IF S_EDIT_REASON -->
<dl>
<dt><label for="edit_reason">{L_TRACKER_EDIT_REASON}:</label><br /><span>{L_TRACKER_EDIT_REASON_EXPLAIN}</span></dt>
<dd><input type="text" id="edit_reason" name="edit_reason" value="{EDIT_REASON_TEXT}" class="inputbox medium" /></dd>
</dl>
<!-- ENDIF -->
<!-- INCLUDE posting_buttons.html -->
<div id="smiley-box">
<!-- IF S_SMILIES_ALLOWED and .smiley -->
<strong>{L_SMILIES}</strong><br />
<!-- BEGIN smiley -->
<a href="#" onclick="insert_text('{smiley.A_SMILEY_CODE}', true); return false;"><img src="{smiley.SMILEY_IMG}" width="{smiley.SMILEY_WIDTH}" height="{smiley.SMILEY_HEIGHT}" alt="{smiley.SMILEY_CODE}" title="{smiley.SMILEY_DESC}" /></a>
<!-- END smiley -->
<!-- ENDIF -->
<!-- IF S_SHOW_SMILEY_LINK and S_SMILIES_ALLOWED-->
<br /><a href="{U_MORE_SMILIES}" onclick="popup(this.href, 300, 350, '_phpbbsmilies'); return false;">{L_MORE_SMILIES}</a>
<!-- ENDIF -->
</div>
<div id="message-box">
<textarea name="message" id="message" rows="15" cols="76" tabindex="4" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onfocus="initInsertions();" class="inputbox">{REPLY_DESC}</textarea>
</div>
</fieldset>
<span class="corners-bottom"><span></span></span>
</div>
<!-- IF S_CAN_ATTACH --><!-- INCLUDE posting_attach_body.html --><!-- ENDIF -->
<!-- IF S_HAS_ATTACHMENTS -->
<div class="panel bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<h3>{L_POSTED_ATTACHMENTS}</h3>
<fieldset class="fields2">
<!-- BEGIN attach_row -->
<dl>
<dt><label for="comment_list[{attach_row.ASSOC_INDEX}]">{L_FILE_COMMENT}:</label></dt>
<dd><textarea name="comment_list[{attach_row.ASSOC_INDEX}]" id="comment_list[{attach_row.ASSOC_INDEX}]" rows="1" cols="35" class="inputbox">{attach_row.FILE_COMMENT}</textarea></dd>
<dd><a href="{attach_row.U_VIEW_ATTACHMENT}" class="{S_CONTENT_FLOW_END}">{attach_row.FILENAME}</a></dd>
<dd style="margin-top: 5px;">
<!-- IF S_INLINE_ATTACHMENT_OPTIONS --><input type="button" value="{L_PLACE_INLINE}" onclick="attach_inline({attach_row.ASSOC_INDEX}, '{attach_row.A_FILENAME}');" class="button2" /> <!-- ENDIF -->
<input type="submit" name="delete_file[{attach_row.ASSOC_INDEX}]" value="{L_DELETE_FILE}" class="button2" />
</dd>
</dl>
{attach_row.S_HIDDEN}
<!-- IF not attach_row.S_LAST_ROW --><hr class="dashed" /><!-- ENDIF -->
<!-- END attach_row -->
</fieldset>
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- ENDIF -->
<!-- IF S_MANAGE_TICKET -->
<div class="panel bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<h3>{L_OPTIONS}</h3>
<fieldset class="fields2">
<!-- IF S_MANAGE_TICKET and S_ASSIGN_USER_OPTIONS -->
<dl>
<dt><label for="au"><strong>{L_TRACKER_ASSIGN_USER}:</strong></label></dt>
<dd><select id="au" name="au">{S_ASSIGN_USER_OPTIONS}</select></dd>
</dl>
<!-- ENDIF -->
<!-- IF S_MANAGE_TICKET and S_STATUS_OPTIONS -->
<dl>
<dt><label for="cs"><strong>{L_TRACKER_CHANGE_STATUS}:</strong></label></dt>
<dd><select id="cs" name="cs">{S_STATUS_OPTIONS}</select></dd>
</dl>
<!-- ENDIF -->
<!-- IF S_MANAGE_TICKET and S_PRIORITY_OPTIONS -->
<dl>
<dt><label for="pr"><strong>{L_TRACKER_CHANGE_PRIORITY}:</strong></label></dt>
<dd><select id="pr" name="pr">{S_PRIORITY_OPTIONS}</select></dd>
</dl>
<!-- ENDIF -->
<!-- IF S_MANAGE_TICKET and S_SEVERITY_OPTIONS -->
<dl>
<dt><label for="s"><strong>{L_TRACKER_CHANGE_SEVERITY}:</strong></label></dt>
<dd><select id="s" name="s">{S_SEVERITY_OPTIONS}</select></dd>
</dl>
<!-- ENDIF -->
<!-- IF S_TICKET_SECURITY -->
<dl>
<dt><label for="ticket_security">{L_TRACKER_SECURITY_TICKET}:</label></dt>
<dd><input type="checkbox" name="ticket_security" id="ticket_security" value="1"<!-- IF TICKET_SECURITY --> checked="checked"<!-- ENDIF --> /></dd>
</dl>
<!-- ENDIF -->
<dl>
<dt><label for="ticket_hidden">{L_TRACKER_HIDE_TICKET}:</label></dt>
<dd><input type="checkbox" name="ticket_hidden" id="ticket_hidden" value="1"<!-- IF TICKET_HIDDEN --> checked="checked"<!-- ENDIF --> /></dd>
</dl>
<dl>
<dt><label for="ticket_status">{L_TRACKER_LOCK_TICKET}:</label></dt>
<dd><input type="checkbox" name="ticket_status" id="ticket_status" value="1"<!-- IF S_IS_LOCKED --> checked="checked"<!-- ENDIF --> /></dd>
</dl>
</fieldset>
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- ENDIF -->
<div class="panel bg2">
<span class="corners-top"><span></span></span>
<fieldset>
<p>{TRACKER_REPLY_DETAIL}</p>
<!-- IF CAPTCHA_TEMPLATE and S_CONFIRM_CODE -->
<!-- DEFINE $CAPTCHA_TAB_INDEX = 3 -->
<!-- INCLUDE {CAPTCHA_TEMPLATE} -->
<!-- ENDIF -->
<input type="submit" name="preview" value="{L_TRACKER_PREVIEW_REPLY}" class="button2" /> <input type="submit" name="submit" value="{L_TRACKER_SUBMIT_REPLY}" class="button1" />
{S_HIDDEN_FIELDS_CONFIRM}
{S_FORM_TOKEN}
</fieldset>
<span class="corners-bottom"><span></span></span>
</div>
</form>
<!-- IF S_DISPLAY_REVIEW -->
<h3>{L_TRACKER_PREVIOUS_POSTS}</h3>
<div id="topicreview">
<div class="post bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<!-- BEGIN review -->
<div class="postbody">
<p class="author<!-- IF review.S_LAST_ROW --> current<!-- ENDIF -->">{POST_IMG} <strong>{review.POST_USER}</strong></p>
<div class="content<!-- IF review.S_LAST_ROW --> current<!-- ENDIF -->">{review.POST_TEXT}</div>
</div>
<!-- IF not review.S_LAST_ROW --><hr /><!-- ENDIF -->
<!-- END -->
<span class="corners-bottom"><span></span></span></div>
</div>
</div>
<!-- ENDIF -->
<!-- ENDIF -->
</div>
<div id="col2">
<div class="post bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<h3 style="border-bottom: none; margin-top: 5px;">{L_TRACKER_TICKET_DETAILS}</h3>
<ul class="menu">
<li><strong>{L_TRACKER_TICKET_ID}:</strong> {TICKET_ID}</li>
<li><strong>{L_TRACKER_PROJECT_NAME}:</strong> {PROJECT_NAME}</li>
<li><strong>{L_TRACKER_STATUS}:</strong> {TICKET_STATUS_DETAILS}</li>
<!-- IF S_TICKET_COMPONENT --><li><strong>{L_TRACKER_COMPONENT}:</strong> {TICKET_COMPONENT}</li><!-- ENDIF -->
<!-- IF S_TICKET_VERSION --><li><strong>{L_TRACKER_DETAILS_VERSION}:</strong> {TICKET_VERSION}</li><!-- ENDIF -->
<!-- IF S_TICKET_PRIORITY --><li><strong>{L_TRACKER_PRIORITY}:</strong> {TICKET_PRIORITY}</li><!-- ENDIF -->
<!-- IF S_TICKET_SEVERITY --><li><strong>{L_TRACKER_SEVERITY}:</strong> {TICKET_SEVERITY}</li><!-- ENDIF -->
<!-- IF S_TICKET_ENVIRONMENT -->
<!-- IF S_SHOW_PHP --><li><strong>{L_TRACKER_TICKET_PHP_DETAIL}:</strong> {TICKET_PHP}</li><!-- ENDIF -->
<!-- IF S_SHOW_DBMS --><li><strong>{L_TRACKER_TICKET_DBMS_DETAIL}:</strong> {TICKET_DBMS}</li><!-- ENDIF -->
<!-- ENDIF -->
<li><strong>{L_TRACKER_ASSIGNED_TO}:</strong> {TICKET_ASSIGNED_TO}</li>
<li><strong>{L_TRACKER_REPORTED_BY}:</strong> {TICKET_REPORTED_BY} <!-- IF S_SEND_PM -->(<a href="{U_SEND_PM}">{L_TRACKER_SEND_PM}</a>)<!-- ENDIF --></li>
<li><strong>{L_TRACKER_REPORTERS_TICKETS}:</strong> <a href="{U_REPORTERS_TICKETS}">{L_TRACKER_LIST_ALL_TICKETS}</a></li>
<li<!-- IF not TICKET_LAST_VISIT --> class="last"<!-- ENDIF -->><strong>{L_TRACKER_REPORTED_ON}:</strong> {TICKET_TIME}</li>
<!-- IF TICKET_LAST_VISIT --><li class="last">{TICKET_LAST_VISIT}</li><!-- ENDIF -->
</ul>
<span class="corners-bottom"><span></span></span></div>
</div>
<!-- IF S_MANAGE_TICKET --><form id="assign_user_form" action="{U_UPDATE_ACTION}" method="post"><!-- ENDIF -->
<div class="post bg2">
<div class="inner"><span class="corners-top"><span></span></span>
<h3 style="border-bottom: none; margin-top: 5px;">{L_OPTIONS}</h3>
<ul class="menu">
<li<!-- IF not S_MANAGE_TICKET or S_TICKET_REPLY and (not S_USER_LOGGED_IN and S_IS_BOT) --> class="last"<!-- ENDIF -->><a href="{U_VIEW_TICKET_HISTORY}">{L_TICKET_HISTORY}</a></li>
<!-- IF S_USER_LOGGED_IN and not S_IS_BOT -->
<li<!-- IF not S_MANAGE_TICKET or S_TICKET_REPLY --> class="last"<!-- ENDIF -->><a href="{U_WATCH_TICKET}">{L_WATCH_TICKET}</a></li>
<!-- ENDIF -->
<!-- IF not S_TICKET_REPLY -->
<!-- IF S_MANAGE_TICKET and S_ASSIGN_USER_OPTIONS --><li><label for="au"><strong>{L_TRACKER_ASSIGN_USER}:</strong></label><select id="au" name="au" style="width: 150px;">{S_ASSIGN_USER_OPTIONS}</select></li><!-- ENDIF -->
<!-- IF S_MANAGE_TICKET and S_STATUS_OPTIONS --><li><label for="cs"><strong>{L_TRACKER_CHANGE_STATUS}:</strong></label><select id="cs" name="cs" style="width: 125px;">{S_STATUS_OPTIONS}</select></li><!-- ENDIF -->
<!-- IF S_MANAGE_TICKET and S_PRIORITY_OPTIONS --><li><label for="pr"><strong>{L_TRACKER_CHANGE_PRIORITY}:</strong></label><select id="pr" name="pr" style="width: 125px;">{S_PRIORITY_OPTIONS}</select></li><!-- ENDIF -->
<!-- IF S_MANAGE_TICKET and S_SEVERITY_OPTIONS --><li><label for="s"><strong>{L_TRACKER_CHANGE_SEVERITY}:</strong></label><select id="s" name="s" style="width: 125px;">{S_SEVERITY_OPTIONS}</select></li><!-- ENDIF -->
<!-- IF S_MANAGE_TICKET --><li class="last"><input type="submit" name="update" value="{L_SUBMIT}" class="button2" /></li><!-- ENDIF -->
<!-- ENDIF -->
</ul>
<span class="corners-bottom"><span></span></span></div>
<!-- IF S_MANAGE_TICKET -->{S_FORM_TOKEN}<!-- ENDIF -->
</div>
<!-- IF S_MANAGE_TICKET --></form><!-- ENDIF -->
</div>
<div class="cleaner"> </div>
<!-- IF S_MANAGE_TICKET_MOD and not S_TICKET_REPLY -->
<br />
<form method="post" action="{S_MOD_ACTION}">
<fieldset class="quickmod">
<label>{L_QUICK_MOD}: {S_TICKET_MOD}</label> <input name="submit_mod" type="submit" value="{L_GO}" class="button2" />
{S_FORM_TOKEN}
</fieldset>
</form>
<div class="cleaner"> </div>
<!-- ENDIF -->
<!-- INCLUDE tracker/tracker_footer.html -->
<!-- INCLUDE overall_footer.html -->
|
phpbbmodders-30x-mods/phpbb-tracker
|
root/styles/prosilver_se/template/tracker/tracker_tickets_view_body.html
|
HTML
|
gpl-2.0
| 17,180
|
''' Crawl the running Docker site and verify all links give a 200 OK '''
import unittest
import subprocess
# Placeholder for future python based codi/TURFF
class BasicTests(unittest.TestCase):
''' Base class for testing '''
def setUp(self):
''' Define some unique data for validation '''
pass
def tearDown(self):
''' Destroy unique data '''
pass
|
todorez/crops
|
tests/unit/test_basic.py
|
Python
|
gpl-2.0
| 397
|
<?php
/**
* @version 1.0.2 Stable $Id$
* @package Joomla
* @subpackage EventList
* @copyright (C) 2005 - 2009 Christoph Lukes
* @license GNU/GPL, see LICENSE.php
* EventList is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
* EventList 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 EventList; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
/**
* EventList Component Venue Model
*
* @package Joomla
* @subpackage EventList
* @since 0.9
*/
class EventListModelVenue extends JModel
{
/**
* venue id
*
* @var int
*/
var $_id = null;
/**
* venue data array
*
* @var array
*/
var $_data = null;
/**
* Constructor
*
* @since 0.9
*/
function __construct()
{
parent::__construct();
$array = JRequest::getVar('cid', 0, '', 'array');
$this->setId((int)$array[0]);
}
/**
* Method to set the identifier
*
* @access public
* @param int event identifier
*/
function setId($id)
{
// Set venue id and wipe data
$this->_id = $id;
$this->_data = null;
}
/**
* Logic for the event edit screen
*
* @access public
* @return array
* @since 0.9
*/
function &getData()
{
if ($this->_loadData())
{
}
else $this->_initData();
return $this->_data;
}
/**
* Method to load content event data
*
* @access private
* @return boolean True on success
* @since 0.9
*/
function _loadData()
{
// Lets load the content if it doesn't already exist
if (empty($this->_data))
{
$query = 'SELECT *'
. ' FROM #__eventlist_venues'
. ' WHERE id = '.$this->_id
;
$this->_db->setQuery($query);
$this->_data = $this->_db->loadObject();
return (boolean) $this->_data;
}
return true;
}
/**
* Method to initialise the venue data
*
* @access private
* @return boolean True on success
* @since 0.9
*/
function _initData()
{
// Lets load the content if it doesn't already exist
if (empty($this->_data))
{
$venue = new stdClass();
$venue->id = 0;
$venue->venue = null;
$venue->alias = null;
$venue->url = null;
$venue->street = null;
$venue->city = null;
$venue->plz = null;
$venue->state = null;
$venue->country = null;
$venue->locimage = JText::_('COM_EVENTLIST_SELECTIMAGE');
$venue->map = 1;
$venue->published = 1;
$venue->locdescription = null;
$venue->meta_keywords = null;
$venue->meta_description = null;
$venue->created = null;
$venue->author_ip = null;
$venue->created_by = null;
$this->_data = $venue;
return (boolean) $this->_data;
}
return true;
}
/**
* Method to checkin/unlock the item
*
* @access public
* @return boolean True on success
* @since 0.9
*/
function checkin()
{
if ($this->_id)
{
$venue = & JTable::getInstance('eventlist_venues', '');
return $venue->checkin($this->_id);
}
return false;
}
/**
* Method to checkout/lock the item
*
* @access public
* @param int $uid User ID of the user checking the item out
* @return boolean True on success
* @since 0.9
*/
function checkout($uid = null)
{
if ($this->_id)
{
// Make sure we have a user id to checkout the venue with
if (is_null($uid)) {
$user =& JFactory::getUser();
$uid = $user->get('id');
}
// Lets get to it and checkout the thing...
$venue = & JTable::getInstance('eventlist_venues', '');
return $venue->checkout($uid, $this->_id);
}
return false;
}
/**
* Tests if the venue is checked out
*
* @access public
* @param int A user id
* @return boolean True if checked out
* @since 0.9
*/
function isCheckedOut( $uid=0 )
{
if ($this->_loadData())
{
if ($uid) {
return ($this->_data->checked_out && $this->_data->checked_out != $uid);
} else {
return $this->_data->checked_out;
}
} elseif ($this->_id < 1) {
return false;
} else {
JError::raiseWarning( 0, 'Unable to Load Data');
return false;
}
}
/**
* Method to store the venue
*
* @access public
* @return boolean True on success
* @since 1.5
*/
function store($data)
{
$elsettings = ELAdmin::config();
$user = & JFactory::getUser();
$config = & JFactory::getConfig();
$tzoffset = $config->getValue('config.offset');
$row =& $this->getTable('eventlist_venues', '');
// bind it to the table
if (!$row->bind($data)) {
JError::raiseError(500, $this->_db->getErrorMsg() );
return false;
}
// Check if image was selected
jimport('joomla.filesystem.file');
$format = JFile::getExt(JPATH_SITE.'/images/eventlist/venues/'.$row->locimage);
$allowable = array ('gif', 'jpg', 'png');
if (in_array($format, $allowable)) {
$row->locimage = $row->locimage;
} else {
$row->locimage = '';
}
// sanitise id field
$row->id = (int) $row->id;
$nullDate = $this->_db->getNullDate();
// Are we saving from an item edit?
if ($row->id) {
$row->modified = gmdate('Y-m-d H:i:s');
$row->modified_by = $user->get('id');
} else {
$row->modified = $nullDate;
$row->modified_by = '';
//get IP, time and userid
$row->created = gmdate('Y-m-d H:i:s');
$row->author_ip = $elsettings->storeip ? getenv('REMOTE_ADDR') : 'COM_EVENTLIST_DISABLED';
$row->created_by = $user->get('id');
}
//uppercase needed by mapservices
if ($row->country) {
$row->country = JString::strtoupper($row->country);
}
//update item order
if (!$row->id) {
$row->ordering = $row->getNextOrder();
}
// Make sure the data is valid
if (!$row->check($elsettings)) {
$this->setError($row->getError());
return false;
}
// Store it in the db
if (!$row->store()) {
JError::raiseError(500, $this->_db->getErrorMsg() );
return false;
}
return $row->id;
}
}
?>
|
jotweh/svaegirtriathlon
|
administrator/components/com_eventlist/models/venue.php
|
PHP
|
gpl-2.0
| 6,358
|
/**
* @file
*
* @brief SD Card LibI2C driver.
*/
/*
* Copyright (c) 2008
* Embedded Brains GmbH
* Obere Lagerstr. 30
* D-82178 Puchheim
* Germany
* rtems@embedded-brains.de
*
* The license and distribution terms for this file may be found in the file
* LICENSE in this distribution or at http://www.rtems.com/license/LICENSE.
*/
#include <stdio.h>
#include <errno.h>
#include <inttypes.h>
#include <rtems.h>
#include <rtems/libi2c.h>
#include <rtems/libio.h>
#include <rtems/diskdevs.h>
#include <rtems/blkdev.h>
#include <libchip/spi-sd-card.h>
#include <rtems/status-checks.h>
/**
* @name Integer to and from Byte-Stream Converter
* @{
*/
static inline uint16_t sd_card_get_uint16( const uint8_t *s)
{
return (uint16_t) ((s [0] << 8) | s [1]);
}
static inline uint32_t sd_card_get_uint32( const uint8_t *s)
{
return ((uint32_t) s [0] << 24) | ((uint32_t) s [1] << 16) | ((uint32_t) s [2] << 8) | (uint32_t) s [3];
}
static inline void sd_card_put_uint16( uint16_t v, uint8_t *s)
{
*s++ = (uint8_t) (v >> 8);
*s = (uint8_t) (v);
}
static inline void sd_card_put_uint32( uint32_t v, uint8_t *s)
{
*s++ = (uint8_t) (v >> 24);
*s++ = (uint8_t) (v >> 16);
*s++ = (uint8_t) (v >> 8);
*s = (uint8_t) (v);
}
/** @} */
#define SD_CARD_BUSY_TOKEN 0
#define SD_CARD_BLOCK_SIZE_DEFAULT 512
#define SD_CARD_COMMAND_RESPONSE_START 7
/**
* @name Commands
* @{
*/
#define SD_CARD_CMD_GO_IDLE_STATE 0
#define SD_CARD_CMD_SEND_OP_COND 1
#define SD_CARD_CMD_SEND_IF_COND 8
#define SD_CARD_CMD_SEND_CSD 9
#define SD_CARD_CMD_SEND_CID 10
#define SD_CARD_CMD_STOP_TRANSMISSION 12
#define SD_CARD_CMD_SEND_STATUS 13
#define SD_CARD_CMD_SET_BLOCKLEN 16
#define SD_CARD_CMD_READ_SINGLE_BLOCK 17
#define SD_CARD_CMD_READ_MULTIPLE_BLOCK 18
#define SD_CARD_CMD_SET_BLOCK_COUNT 23
#define SD_CARD_CMD_WRITE_BLOCK 24
#define SD_CARD_CMD_WRITE_MULTIPLE_BLOCK 25
#define SD_CARD_CMD_PROGRAM_CSD 27
#define SD_CARD_CMD_SET_WRITE_PROT 28
#define SD_CARD_CMD_CLR_WRITE_PROT 29
#define SD_CARD_CMD_SEND_WRITE_PROT 30
#define SD_CARD_CMD_TAG_SECTOR_START 32
#define SD_CARD_CMD_TAG_SECTOR_END 33
#define SD_CARD_CMD_UNTAG_SECTOR 34
#define SD_CARD_CMD_TAG_ERASE_GROUP_START 35
#define SD_CARD_CMD_TAG_ERASE_GROUP_END 36
#define SD_CARD_CMD_UNTAG_ERASE_GROUP 37
#define SD_CARD_CMD_ERASE 38
#define SD_CARD_CMD_LOCK_UNLOCK 42
#define SD_CARD_CMD_APP_CMD 55
#define SD_CARD_CMD_GEN_CND 56
#define SD_CARD_CMD_READ_OCR 58
#define SD_CARD_CMD_CRC_ON_OFF 59
/** @} */
/**
* @name Application Commands
* @{
*/
#define SD_CARD_ACMD_SD_SEND_OP_COND 41
/** @} */
/**
* @name Command Flags
* @{
*/
#define SD_CARD_FLAG_HCS 0x40000000U
#define SD_CARD_FLAG_VHS_2_7_TO_3_3 0x00000100U
#define SD_CARD_FLAG_CHECK_PATTERN 0x000000aaU
/** @} */
/**
* @name Command Fields
* @{
*/
#define SD_CARD_COMMAND_SET_COMMAND( c, cmd) (c) [1] = (uint8_t) (0x40 + ((cmd) & 0x3f))
#define SD_CARD_COMMAND_SET_ARGUMENT( c, arg) sd_card_put_uint32( (arg), &((c) [2]))
#define SD_CARD_COMMAND_SET_CRC7( c, crc7) ((c) [6] = ((crc7) << 1) | 1U)
#define SD_CARD_COMMAND_GET_CRC7( c) ((c) [6] >> 1)
/** @} */
/**
* @name Response Fields
* @{
*/
#define SD_CARD_IS_RESPONSE( r) (((r) & 0x80) == 0)
#define SD_CARD_IS_ERRORLESS_RESPONSE( r) (((r) & 0x7e) == 0)
#define SD_CARD_IS_NOT_IDLE_RESPONSE( r) (((r) & 0x81) == 0)
#define SD_CARD_IS_DATA_ERROR( r) (((r) & 0xe0) == 0)
#define SD_CARD_IS_DATA_REJECTED( r) (((r) & 0x1f) != 0x05)
/** @} */
/**
* @name Card Identification
* @{
*/
#define SD_CARD_CID_SIZE 16
#define SD_CARD_CID_GET_MID( cid) ((cid) [0])
#define SD_CARD_CID_GET_OID( cid) sd_card_get_uint16( cid + 1)
#define SD_CARD_CID_GET_PNM( cid, i) ((char) (cid) [3 + (i)])
#define SD_CARD_CID_GET_PRV( cid) ((cid) [9])
#define SD_CARD_CID_GET_PSN( cid) sd_card_get_uint32( cid + 10)
#define SD_CARD_CID_GET_MDT( cid) ((cid) [14])
#define SD_CARD_CID_GET_CRC7( cid) ((cid) [15] >> 1)
/** @} */
/**
* @name Card Specific Data
* @{
*/
#define SD_CARD_CSD_SIZE 16
#define SD_CARD_CSD_GET_CSD_STRUCTURE( csd) ((csd) [0] >> 6)
#define SD_CARD_CSD_GET_SPEC_VERS( csd) (((csd) [0] >> 2) & 0xf)
#define SD_CARD_CSD_GET_TAAC( csd) ((csd) [1])
#define SD_CARD_CSD_GET_NSAC( csd) ((uint32_t) (csd) [2])
#define SD_CARD_CSD_GET_TRAN_SPEED( csd) ((csd) [3])
#define SD_CARD_CSD_GET_C_SIZE( csd) ((((uint32_t) (csd) [6] & 0x3) << 10) + (((uint32_t) (csd) [7]) << 2) + ((((uint32_t) (csd) [8]) >> 6) & 0x3))
#define SD_CARD_CSD_GET_C_SIZE_MULT( csd) ((((csd) [9] & 0x3) << 1) + (((csd) [10] >> 7) & 0x1))
#define SD_CARD_CSD_GET_READ_BLK_LEN( csd) ((uint32_t) (csd) [5] & 0xf)
#define SD_CARD_CSD_GET_WRITE_BLK_LEN( csd) ((((uint32_t) (csd) [12] & 0x3) << 2) + ((((uint32_t) (csd) [13]) >> 6) & 0x3))
#define SD_CARD_CSD_1_GET_C_SIZE( csd) ((((uint32_t) (csd) [7] & 0x3f) << 16) + (((uint32_t) (csd) [8]) << 8) + (uint32_t) (csd) [9])
/** @} */
#define SD_CARD_INVALIDATE_RESPONSE_INDEX( e) e->response_index = SD_CARD_COMMAND_SIZE
/**
* @name Data Start and Stop Tokens
* @{
*/
#define SD_CARD_START_BLOCK_SINGLE_BLOCK_READ 0xfe
#define SD_CARD_START_BLOCK_MULTIPLE_BLOCK_READ 0xfe
#define SD_CARD_START_BLOCK_SINGLE_BLOCK_WRITE 0xfe
#define SD_CARD_START_BLOCK_MULTIPLE_BLOCK_WRITE 0xfc
#define SD_CARD_STOP_TRANSFER_MULTIPLE_BLOCK_WRITE 0xfd
/** @} */
/**
* @name Card Specific Data Functions
* @{
*/
static inline uint32_t sd_card_block_number( const uint8_t *csd)
{
uint32_t size = SD_CARD_CSD_GET_C_SIZE( csd);
uint32_t mult = 1U << (SD_CARD_CSD_GET_C_SIZE_MULT( csd) + 2);
return (size + 1) * mult;
}
static inline uint32_t sd_card_capacity( const uint8_t *csd)
{
uint32_t block_size = 1U << SD_CARD_CSD_GET_READ_BLK_LEN( csd);
return sd_card_block_number( csd) * block_size;
}
static inline uint32_t sd_card_transfer_speed( const uint8_t *csd)
{
uint32_t s = SD_CARD_CSD_GET_TRAN_SPEED( csd);
uint32_t e = s & 0x7;
uint32_t m = s >> 3;
switch (e) {
case 0: s = 10000; break;
case 1: s = 100000; break;
case 2: s = 1000000; break;
case 3: s = 10000000; break;
default: s = 0; break;
}
switch (m) {
case 1: s *= 10; break;
case 2: s *= 12; break;
case 3: s *= 13; break;
case 4: s *= 15; break;
case 5: s *= 20; break;
case 6: s *= 25; break;
case 7: s *= 30; break;
case 8: s *= 35; break;
case 9: s *= 40; break;
case 10: s *= 45; break;
case 11: s *= 50; break;
case 12: s *= 55; break;
case 13: s *= 60; break;
case 14: s *= 70; break;
case 15: s *= 80; break;
default: s *= 0; break;
}
return s;
}
static inline uint32_t sd_card_access_time( const uint8_t *csd)
{
uint32_t ac = SD_CARD_CSD_GET_TAAC( csd);
uint32_t e = ac & 0x7;
uint32_t m = ac >> 3;
switch (e) {
case 0: ac = 1; break;
case 1: ac = 10; break;
case 2: ac = 100; break;
case 3: ac = 1000; break;
case 4: ac = 10000; break;
case 5: ac = 100000; break;
case 6: ac = 1000000; break;
case 7: ac = 10000000; break;
default: ac = 0; break;
}
switch (m) {
case 1: ac *= 10; break;
case 2: ac *= 12; break;
case 3: ac *= 13; break;
case 4: ac *= 15; break;
case 5: ac *= 20; break;
case 6: ac *= 25; break;
case 7: ac *= 30; break;
case 8: ac *= 35; break;
case 9: ac *= 40; break;
case 10: ac *= 45; break;
case 11: ac *= 50; break;
case 12: ac *= 55; break;
case 13: ac *= 60; break;
case 14: ac *= 70; break;
case 15: ac *= 80; break;
default: ac *= 0; break;
}
return ac / 10;
}
static inline uint32_t sd_card_max_access_time( const uint8_t *csd, uint32_t transfer_speed)
{
uint64_t ac = sd_card_access_time( csd);
uint32_t ac_100ms = transfer_speed / 80;
uint32_t n = SD_CARD_CSD_GET_NSAC( csd) * 100;
/* ac is in ns, transfer_speed in bps, max_access_time in bytes.
max_access_time is 100 times typical access time (taac+nsac) */
ac = ac * transfer_speed / 80000000;
ac = ac + 100*n;
if ((uint32_t)ac > ac_100ms)
return ac_100ms;
else
return (uint32_t)ac;
}
/** @} */
/**
* @name CRC functions
*
* Based on http://en.wikipedia.org/wiki/Computation_of_CRC
*
* @{
*/
static uint8_t sd_card_compute_crc7 (uint8_t *data, size_t len)
{
uint8_t e, f, crc;
size_t i;
crc = 0;
for (i = 0; i < len; i++) {
e = crc ^ data[i];
f = e ^ (e >> 4) ^ (e >> 7);
crc = (f << 1) ^ (f << 4);
}
return crc >> 1;
}
static uint16_t sd_card_compute_crc16 (uint8_t *data, size_t len)
{
uint8_t s, t;
uint16_t crc;
size_t i;
crc = 0;
for (i = 0; i < len; i++) {
s = data[i] ^ (crc >> 8);
t = s ^ (s >> 4);
crc = (crc << 8) ^ t ^ (t << 5) ^ (t << 12);
}
return crc;
}
/** @} */
/**
* @name Communication Functions
* @{
*/
static inline int sd_card_query( sd_card_driver_entry *e, uint8_t *in, int n)
{
return rtems_libi2c_read_bytes( e->bus, in, n);
}
static int sd_card_wait( sd_card_driver_entry *e)
{
int rv = 0;
int r = 0;
int n = 2;
/* For writes, the timeout is 2.5 times that of reads; since we
don't know if it is a write or read, assume write.
FIXME should actually look at R2W_FACTOR for non-HC cards. */
int retries = e->n_ac_max * 25 / 10;
/* n_ac_max/100 is supposed to be the average waiting time. To
approximate this, we start with waiting n_ac_max/150 and
gradually increase the waiting time. */
int wait_time_bytes = (retries + 149) / 150;
while (e->busy) {
/* Query busy tokens */
rv = sd_card_query( e, e->response, n);
RTEMS_CHECK_RV( rv, "Busy");
/* Search for non busy tokens */
for (r = 0; r < n; ++r) {
if (e->response [r] != SD_CARD_BUSY_TOKEN) {
e->busy = false;
return 0;
}
}
retries -= n;
if (retries <= 0) {
return -RTEMS_TIMEOUT;
}
if (e->schedule_if_busy) {
uint64_t wait_time_us = wait_time_bytes;
wait_time_us *= 8000000;
wait_time_us /= e->transfer_mode.baudrate;
rtems_task_wake_after( RTEMS_MICROSECONDS_TO_TICKS(wait_time_us));
retries -= wait_time_bytes;
wait_time_bytes = wait_time_bytes * 15 / 10;
} else {
n = SD_CARD_COMMAND_SIZE;
}
}
return 0;
}
static int sd_card_send_command( sd_card_driver_entry *e, uint32_t command, uint32_t argument)
{
int rv = 0;
rtems_libi2c_read_write_t rw = {
.rd_buf = e->response,
.wr_buf = e->command,
.byte_cnt = SD_CARD_COMMAND_SIZE
};
int r = 0;
uint8_t crc7;
SD_CARD_INVALIDATE_RESPONSE_INDEX( e);
/* Wait until card is not busy */
rv = sd_card_wait( e);
RTEMS_CHECK_RV( rv, "Wait");
/* Write command and read response */
SD_CARD_COMMAND_SET_COMMAND( e->command, command);
SD_CARD_COMMAND_SET_ARGUMENT( e->command, argument);
crc7 = sd_card_compute_crc7( e->command + 1, 5);
SD_CARD_COMMAND_SET_CRC7( e->command, crc7);
rv = rtems_libi2c_ioctl( e->bus, RTEMS_LIBI2C_IOCTL_READ_WRITE, &rw);
RTEMS_CHECK_RV( rv, "Write command and read response");
/* Check respose */
for (r = SD_CARD_COMMAND_RESPONSE_START; r < SD_CARD_COMMAND_SIZE; ++r) {
RTEMS_DEBUG_PRINT( "Token [%02u]: 0x%02x\n", r, e->response [r]);
e->response_index = r;
if (SD_CARD_IS_RESPONSE( e->response [r])) {
if (SD_CARD_IS_ERRORLESS_RESPONSE( e->response [r])) {
return 0;
} else {
RTEMS_SYSLOG_ERROR( "Command error [%02i]: 0x%02" PRIx8 "\n", r, e->response [r]);
goto sd_card_send_command_error;
}
} else if (e->response [r] != SD_CARD_IDLE_TOKEN) {
RTEMS_SYSLOG_ERROR( "Unexpected token [%02i]: 0x%02" PRIx8 "\n", r, e->response [r]);
goto sd_card_send_command_error;
}
}
RTEMS_SYSLOG_ERROR( "Timeout\n");
sd_card_send_command_error:
RTEMS_SYSLOG_ERROR( "Response:");
for (r = 0; r < SD_CARD_COMMAND_SIZE; ++r) {
if (e->response_index == r) {
RTEMS_SYSLOG_PRINT( " %02" PRIx8 ":[%02" PRIx8 "]", e->command [r], e->response [r]);
} else {
RTEMS_SYSLOG_PRINT( " %02" PRIx8 ":%02" PRIx8 "", e->command [r], e->response [r]);
}
}
RTEMS_SYSLOG_PRINT( "\n");
return -RTEMS_IO_ERROR;
}
static int sd_card_send_register_command( sd_card_driver_entry *e, uint32_t command, uint32_t argument, uint32_t *reg)
{
int rv = 0;
uint8_t crc7;
rv = sd_card_send_command( e, command, argument);
RTEMS_CHECK_RV( rv, "Send command");
if (e->response_index + 5 > SD_CARD_COMMAND_SIZE) {
/*
* TODO: If this happens in the wild we need to implement a
* more sophisticated response query.
*/
RTEMS_SYSLOG_ERROR( "Unexpected response position\n");
return -RTEMS_IO_ERROR;
}
crc7 = sd_card_compute_crc7( e->response + e->response_index, 5);
if (crc7 != SD_CARD_COMMAND_GET_CRC7( e->response + e->response_index) &&
SD_CARD_COMMAND_GET_CRC7( e->response + e->response_index) != 0x7f) {
RTEMS_SYSLOG_ERROR( "CRC check failed on register command\n");
return -RTEMS_IO_ERROR;
}
*reg = sd_card_get_uint32( e->response + e->response_index + 1);
return 0;
}
static int sd_card_stop_multiple_block_read( sd_card_driver_entry *e)
{
int rv = 0;
SD_CARD_COMMAND_SET_COMMAND( e->command, SD_CARD_CMD_STOP_TRANSMISSION);
rv = rtems_libi2c_write_bytes( e->bus, e->command, SD_CARD_COMMAND_SIZE);
RTEMS_CHECK_RV( rv, "Write stop transfer token");
return 0;
}
static int sd_card_stop_multiple_block_write( sd_card_driver_entry *e)
{
int rv = 0;
uint8_t stop_transfer [3] = { SD_CARD_IDLE_TOKEN, SD_CARD_STOP_TRANSFER_MULTIPLE_BLOCK_WRITE, SD_CARD_IDLE_TOKEN };
/* Wait until card is not busy */
rv = sd_card_wait( e);
RTEMS_CHECK_RV( rv, "Wait");
/* Send stop token */
rv = rtems_libi2c_write_bytes( e->bus, stop_transfer, 3);
RTEMS_CHECK_RV( rv, "Write stop transfer token");
/* Card is now busy */
e->busy = true;
return 0;
}
static int sd_card_read( sd_card_driver_entry *e, uint8_t start_token, uint8_t *in, int n)
{
int rv = 0;
/* Discard command response */
int r = e->response_index + 1;
/* Standard response size */
int response_size = SD_CARD_COMMAND_SIZE;
/* Where the response is stored */
uint8_t *response = e->response;
/* Data input index */
int i = 0;
/* CRC check of data */
uint16_t crc16;
/* Maximum number of tokens to read. */
int retries = e->n_ac_max;
SD_CARD_INVALIDATE_RESPONSE_INDEX( e);
while (true) {
RTEMS_DEBUG_PRINT( "Search from %u to %u\n", r, response_size - 1);
/* Search the data start token in in current response buffer */
retries -= (response_size - r);
while (r < response_size) {
RTEMS_DEBUG_PRINT( "Token [%02u]: 0x%02x\n", r, response [r]);
if (response [r] == start_token) {
/* Discard data start token */
++r;
goto sd_card_read_start;
} else if (SD_CARD_IS_DATA_ERROR( response [r])) {
RTEMS_SYSLOG_ERROR( "Data error token [%02i]: 0x%02" PRIx8 "\n", r, response [r]);
return -RTEMS_IO_ERROR;
} else if (response [r] != SD_CARD_IDLE_TOKEN) {
RTEMS_SYSLOG_ERROR( "Unexpected token [%02i]: 0x%02" PRIx8 "\n", r, response [r]);
return -RTEMS_IO_ERROR;
}
++r;
}
if (retries <= 0) {
RTEMS_SYSLOG_ERROR( "Timeout\n");
return -RTEMS_IO_ERROR;
}
if (e->schedule_if_busy)
rtems_task_wake_after( RTEMS_YIELD_PROCESSOR);
/* Query more. We typically have to wait between 10 and 100
bytes. To reduce overhead, read the response in chunks of
50 bytes - this doesn't introduce too much copy overhead
but does allow SPI DMA transfers to work efficiently. */
response = in;
response_size = 50;
if (response_size > n)
response_size = n;
rv = sd_card_query( e, response, response_size);
RTEMS_CHECK_RV( rv, "Query data start token");
/* Reset start position */
r = 0;
}
sd_card_read_start:
/* Read data */
while (r < response_size && i < n) {
in [i++] = response [r++];
}
/* Read more data? */
if (i < n) {
rv = sd_card_query( e, &in [i], n - i);
RTEMS_CHECK_RV( rv, "Read data");
i += rv;
}
/* Read CRC 16 and N_RC */
rv = sd_card_query( e, e->response, 3);
RTEMS_CHECK_RV( rv, "Read CRC 16");
crc16 = sd_card_compute_crc16 (in, n);
if ((e->response[0] != ((crc16 >> 8) & 0xff)) ||
(e->response[1] != (crc16 & 0xff))) {
RTEMS_SYSLOG_ERROR( "CRC check failed on read\n");
return -RTEMS_IO_ERROR;
}
return i;
}
static int sd_card_write( sd_card_driver_entry *e, uint8_t start_token, uint8_t *out, int n)
{
int rv = 0;
uint8_t crc16_bytes [2] = { 0, 0 };
uint16_t crc16;
/* Data output index */
int o = 0;
/* Wait until card is not busy */
rv = sd_card_wait( e);
RTEMS_CHECK_RV( rv, "Wait");
/* Write data start token */
rv = rtems_libi2c_write_bytes( e->bus, &start_token, 1);
RTEMS_CHECK_RV( rv, "Write data start token");
/* Write data */
o = rtems_libi2c_write_bytes( e->bus, out, n);
RTEMS_CHECK_RV( o, "Write data");
/* Write CRC 16 */
crc16 = sd_card_compute_crc16(out, n);
crc16_bytes[0] = (crc16>>8) & 0xff;
crc16_bytes[1] = (crc16) & 0xff;
rv = rtems_libi2c_write_bytes( e->bus, crc16_bytes, 2);
RTEMS_CHECK_RV( rv, "Write CRC 16");
/* Read data response */
rv = sd_card_query( e, e->response, 2);
RTEMS_CHECK_RV( rv, "Read data response");
if (SD_CARD_IS_DATA_REJECTED( e->response [0])) {
RTEMS_SYSLOG_ERROR( "Data rejected: 0x%02" PRIx8 "\n", e->response [0]);
return -RTEMS_IO_ERROR;
}
/* Card is now busy */
e->busy = true;
return o;
}
static inline rtems_status_code sd_card_start( sd_card_driver_entry *e)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
int rv = 0;
sc = rtems_libi2c_send_start( e->bus);
RTEMS_CHECK_SC( sc, "Send start");
rv = rtems_libi2c_ioctl( e->bus, RTEMS_LIBI2C_IOCTL_SET_TFRMODE, &e->transfer_mode);
RTEMS_CHECK_RV_SC( rv, "Set transfer mode");
sc = rtems_libi2c_send_addr( e->bus, 1);
RTEMS_CHECK_SC( sc, "Send address");
return RTEMS_SUCCESSFUL;
}
static inline rtems_status_code sd_card_stop( sd_card_driver_entry *e)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
sc = rtems_libi2c_send_stop( e->bus);
RTEMS_CHECK_SC( sc, "Send stop");
return RTEMS_SUCCESSFUL;
}
static rtems_status_code sd_card_init( sd_card_driver_entry *e)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
int rv = 0;
uint8_t block [SD_CARD_BLOCK_SIZE_DEFAULT];
uint32_t transfer_speed = 0;
uint32_t read_block_size = 0;
uint32_t write_block_size = 0;
uint8_t csd_structure = 0;
uint64_t capacity = 0;
uint8_t crc7;
/* Assume first that we have a SD card and not a MMC card */
bool assume_sd = true;
/*
* Assume high capacity until proven wrong (applies to SD and not yet
* existing MMC).
*/
bool high_capacity = true;
bool do_cmd58 = true;
uint32_t cmd_arg = 0;
uint32_t if_cond_test = SD_CARD_FLAG_VHS_2_7_TO_3_3 | SD_CARD_FLAG_CHECK_PATTERN;
uint32_t if_cond_reg = if_cond_test;
/* Start */
sc = sd_card_start( e);
RTEMS_CLEANUP_SC( sc, sd_card_driver_init_cleanup, "Start");
/* Wait until card is not busy */
rv = sd_card_wait( e);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Wait");
/* Send idle tokens for at least 74 clock cycles with active chip select */
memset( block, SD_CARD_IDLE_TOKEN, SD_CARD_BLOCK_SIZE_DEFAULT);
rv = rtems_libi2c_write_bytes( e->bus, block, SD_CARD_BLOCK_SIZE_DEFAULT);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Active chip select delay");
/* Stop */
sc = sd_card_stop( e);
RTEMS_CHECK_SC( sc, "Stop");
/* Start with inactive chip select */
sc = rtems_libi2c_send_start( e->bus);
RTEMS_CHECK_SC( sc, "Send start");
/* Set transfer mode */
rv = rtems_libi2c_ioctl( e->bus, RTEMS_LIBI2C_IOCTL_SET_TFRMODE, &e->transfer_mode);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Set transfer mode");
/* Send idle tokens with inactive chip select */
rv = sd_card_query( e, e->response, SD_CARD_COMMAND_SIZE);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Inactive chip select delay");
/* Activate chip select */
sc = rtems_libi2c_send_addr( e->bus, 1);
RTEMS_CLEANUP_SC( sc, sd_card_driver_init_cleanup, "Send address");
/* Stop multiple block write */
sd_card_stop_multiple_block_write( e);
/* Get card status */
sd_card_send_command( e, SD_CARD_CMD_SEND_STATUS, 0);
/* Stop multiple block read */
sd_card_stop_multiple_block_read( e);
/* Switch to SPI mode */
rv = sd_card_send_command( e, SD_CARD_CMD_GO_IDLE_STATE, 0);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Send: SD_CARD_CMD_GO_IDLE_STATE");
/*
* Get interface condition, CMD8. This is new for SD 2.x and enables
* getting the High Capacity Support flag HCS and checks that the
* voltage is right. Some MMCs accept this command but will still fail
* on ACMD41. SD 1.x cards will fails this command and do not support
* HCS (> 2G capacity).
*/
rv = sd_card_send_register_command( e, SD_CARD_CMD_SEND_IF_COND, if_cond_reg, &if_cond_reg);
/*
* Regardless of whether CMD8 above passes or fails, send ACMD41. If
* card is MMC it will fail. But older SD < 2.0 (which fail CMD8) will
* always stay "idle" if cmd_arg is non-zero, so set to 0 above on
* fail.
*/
if (rv < 0) {
/* Failed CMD8, so SD 1.x or MMC */
cmd_arg = 0;
} else {
cmd_arg = SD_CARD_FLAG_HCS;
}
/* Enable CRC */
sd_card_send_command( e, SD_CARD_CMD_CRC_ON_OFF, 1);
/* Initialize card */
while (true) {
if (assume_sd) {
/* This command (CMD55) supported by SD and (most?) MMCs */
rv = sd_card_send_command( e, SD_CARD_CMD_APP_CMD, 0);
if (rv < 0) {
RTEMS_SYSLOG( "CMD55 failed. Assume MMC and try CMD1\n");
assume_sd = false;
continue;
}
/*
* This command (ACMD41) only supported by SD. Always
* fails if MMC.
*/
rv = sd_card_send_command( e, SD_CARD_ACMD_SD_SEND_OP_COND, cmd_arg);
if (rv < 0) {
/*
* This *will* fail for MMC. If fails, bad/no
* card or card is MMC, do CMD58 then CMD1.
*/
RTEMS_SYSLOG( "ACMD41 failed. Assume MMC and do CMD58 (once) then CMD1\n");
assume_sd = false;
cmd_arg = SD_CARD_FLAG_HCS;
do_cmd58 = true;
continue;
} else {
/*
* Passed ACMD41 so SD. It is now save to
* check if_cond_reg from CMD8. Reject the
* card in case of a indicated bad voltage.
*/
if (if_cond_reg != if_cond_test) {
RTEMS_CLEANUP_RV_SC( -1, sc, sd_card_driver_init_cleanup, "Bad voltage for SD");
}
}
} else {
/*
* Does not seem to be SD card. Do init for MMC.
* First send CMD58 once to enable check for HCS
* (similar to CMD8 of SD) with bits 30:29 set to 10b.
* This will work for MMC >= 4.2. Older cards (<= 4.1)
* may may not respond to CMD1 unless CMD58 is sent
* again with zero argument.
*/
if (do_cmd58) {
rv = sd_card_send_command( e, SD_CARD_CMD_READ_OCR, cmd_arg);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Failed CMD58 for MMC");
/* A one-shot call */
do_cmd58 = false;
}
/* Do CMD1 */
rv = sd_card_send_command( e, SD_CARD_CMD_SEND_OP_COND, 0);
if (rv < 0) {
if (cmd_arg != 0) {
/*
* Send CMD58 again with zero argument
* value. Proves card is not
* high_capacity.
*/
cmd_arg = 0;
do_cmd58 = true;
high_capacity = false;
continue;
}
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Failed to initialize MMC");
}
}
/*
* Not idle?
*
* This hangs forever if the card remains not idle and sends
* always a valid response.
*/
if (SD_CARD_IS_NOT_IDLE_RESPONSE( e->response [e->response_index])) {
break;
}
/* Invoke the scheduler */
rtems_task_wake_after( RTEMS_YIELD_PROCESSOR);
}
/* Now we know if we are SD or MMC */
if (assume_sd) {
if (cmd_arg == 0) {
/* SD is < 2.0 so never high capacity (<= 2G) */
high_capacity = 0;
} else {
uint32_t reg = 0;
/*
* SD is definitely 2.x. Now need to send CMD58 to get
* the OCR to see if the HCS bit is set (capacity > 2G)
* or if bit is off (capacity <= 2G, standard
* capacity).
*/
rv = sd_card_send_register_command( e, SD_CARD_CMD_READ_OCR, 0, ®);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Failed CMD58 for SD 2.x");
/* Check HCS bit of OCR */
high_capacity = (reg & SD_CARD_FLAG_HCS) != 0;
}
} else {
/*
* Card is MMC. Unless already proven to be not HCS (< 4.2)
* must do CMD58 again to check the OCR bits 30:29.
*/
if (high_capacity) {
uint32_t reg = 0;
/*
* The argument should still be correct since was never
* set to 0
*/
rv = sd_card_send_register_command( e, SD_CARD_CMD_READ_OCR, cmd_arg, ®);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Failed CMD58 for MMC 4.2");
/* Check HCS bit of the OCR */
high_capacity = (reg & 0x600000) == SD_CARD_FLAG_HCS;
}
}
/* Card Identification */
if (e->verbose) {
rv = sd_card_send_command( e, SD_CARD_CMD_SEND_CID, 0);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Send: SD_CARD_CMD_SEND_CID");
rv = sd_card_read( e, SD_CARD_START_BLOCK_SINGLE_BLOCK_READ, block, SD_CARD_CID_SIZE);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Read: SD_CARD_CMD_SEND_CID");
RTEMS_SYSLOG( "*** Card Identification ***\n");
RTEMS_SYSLOG( "Manufacturer ID : %" PRIu8 "\n", SD_CARD_CID_GET_MID( block));
RTEMS_SYSLOG( "OEM/Application ID : %" PRIu16 "\n", SD_CARD_CID_GET_OID( block));
RTEMS_SYSLOG(
"Product name : %c%c%c%c%c%c\n",
SD_CARD_CID_GET_PNM( block, 0),
SD_CARD_CID_GET_PNM( block, 1),
SD_CARD_CID_GET_PNM( block, 2),
SD_CARD_CID_GET_PNM( block, 3),
SD_CARD_CID_GET_PNM( block, 4),
SD_CARD_CID_GET_PNM( block, 5)
);
RTEMS_SYSLOG( "Product revision : %" PRIu8 "\n", SD_CARD_CID_GET_PRV( block));
RTEMS_SYSLOG( "Product serial number : %" PRIu32 "\n", SD_CARD_CID_GET_PSN( block));
RTEMS_SYSLOG( "Manufacturing date : %" PRIu8 "\n", SD_CARD_CID_GET_MDT( block));
RTEMS_SYSLOG( "7-bit CRC checksum : %" PRIu8 "\n", SD_CARD_CID_GET_CRC7( block));
crc7 = sd_card_compute_crc7( block, 15);
if (crc7 != SD_CARD_CID_GET_CRC7( block))
RTEMS_SYSLOG( " Failed! (computed %02" PRIx8 ")\n", crc7);
}
/* Card Specific Data */
/* Read CSD */
rv = sd_card_send_command( e, SD_CARD_CMD_SEND_CSD, 0);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Send: SD_CARD_CMD_SEND_CSD");
rv = sd_card_read( e, SD_CARD_START_BLOCK_SINGLE_BLOCK_READ, block, SD_CARD_CSD_SIZE);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Read: SD_CARD_CMD_SEND_CSD");
crc7 = sd_card_compute_crc7( block, 15);
if (crc7 != SD_CARD_CID_GET_CRC7( block)) {
RTEMS_SYSLOG( "SD_CARD_CMD_SEND_CSD CRC failed\n");
sc = RTEMS_IO_ERROR;
goto sd_card_driver_init_cleanup;
}
/* CSD Structure */
csd_structure = SD_CARD_CSD_GET_CSD_STRUCTURE( block);
/* Transfer speed and access time */
transfer_speed = sd_card_transfer_speed( block);
e->transfer_mode.baudrate = transfer_speed;
e->n_ac_max = sd_card_max_access_time( block, transfer_speed);
/* Block sizes and capacity */
if (csd_structure == 0 || !assume_sd) {
/* Treat MMC same as CSD Version 1.0 */
read_block_size = 1U << SD_CARD_CSD_GET_READ_BLK_LEN( block);
e->block_size_shift = SD_CARD_CSD_GET_WRITE_BLK_LEN( block);
write_block_size = 1U << e->block_size_shift;
if (read_block_size < write_block_size) {
RTEMS_SYSLOG_ERROR( "Read block size smaller than write block size\n");
return -RTEMS_IO_ERROR;
}
e->block_size = write_block_size;
e->block_number = sd_card_block_number( block);
capacity = sd_card_capacity( block);
} else if (csd_structure == 1) {
uint32_t c_size = SD_CARD_CSD_1_GET_C_SIZE( block);
/* Block size is fixed in CSD Version 2.0 */
e->block_size_shift = 9;
e->block_size = 512;
e->block_number = (c_size + 1) * 1024;
capacity = (c_size + 1) * 512 * 1024;
read_block_size = 512;
write_block_size = 512;
/* Timeout is fixed at 100ms in CSD Version 2.0 */
e->n_ac_max = transfer_speed / 80;
} else {
RTEMS_DO_CLEANUP_SC( RTEMS_IO_ERROR, sc, sd_card_driver_init_cleanup, "Unexpected CSD Structure number");
}
/* Print CSD information */
if (e->verbose) {
RTEMS_SYSLOG( "*** Card Specific Data ***\n");
RTEMS_SYSLOG( "CSD structure : %" PRIu8 "\n", SD_CARD_CSD_GET_CSD_STRUCTURE( block));
RTEMS_SYSLOG( "Spec version : %" PRIu8 "\n", SD_CARD_CSD_GET_SPEC_VERS( block));
RTEMS_SYSLOG( "Access time [ns] : %" PRIu32 "\n", sd_card_access_time( block));
RTEMS_SYSLOG( "Access time [N] : %" PRIu32 "\n", SD_CARD_CSD_GET_NSAC( block)*100);
RTEMS_SYSLOG( "Max access time [N] : %" PRIu32 "\n", e->n_ac_max);
RTEMS_SYSLOG( "Max read block size [B] : %" PRIu32 "\n", read_block_size);
RTEMS_SYSLOG( "Max write block size [B] : %" PRIu32 "\n", write_block_size);
RTEMS_SYSLOG( "Block size [B] : %" PRIu32 "\n", e->block_size);
RTEMS_SYSLOG( "Block number : %" PRIu32 "\n", e->block_number);
RTEMS_SYSLOG( "Capacity [B] : %" PRIu64 "\n", capacity);
RTEMS_SYSLOG( "Max transfer speed [b/s] : %" PRIu32 "\n", transfer_speed);
}
if (high_capacity) {
/* For high capacity cards the address is in blocks */
e->block_size_shift = 0;
} else if (e->block_size_shift == 10) {
/*
* Low capacity 2GByte cards with reported block size of 1024
* need to be set back to block size of 512 per 'Simplified
* Physical Layer Specification Version 2.0' section 4.3.2.
* Otherwise, CMD16 fails if set to 1024.
*/
e->block_size_shift = 9;
e->block_size = 512;
e->block_number *= 2;
}
/* Set read block size */
rv = sd_card_send_command( e, SD_CARD_CMD_SET_BLOCKLEN, e->block_size);
RTEMS_CLEANUP_RV_SC( rv, sc, sd_card_driver_init_cleanup, "Send: SD_CARD_CMD_SET_BLOCKLEN");
/* Stop */
sc = sd_card_stop( e);
RTEMS_CHECK_SC( sc, "Stop");
return RTEMS_SUCCESSFUL;
sd_card_driver_init_cleanup:
/* Stop */
sd_card_stop( e);
return sc;
}
/** @} */
/**
* @name Disk Driver Functions
* @{
*/
static int sd_card_disk_block_read( sd_card_driver_entry *e, rtems_blkdev_request *r)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
int rv = 0;
uint32_t start_address = RTEMS_BLKDEV_START_BLOCK (r) << e->block_size_shift;
uint32_t i = 0;
#ifdef DEBUG
/* Check request */
if (r->bufs[0].block >= e->block_number) {
RTEMS_SYSLOG_ERROR( "Start block number out of range");
return -RTEMS_INTERNAL_ERROR;
} else if (r->bufnum > e->block_number - RTEMS_BLKDEV_START_BLOCK (r)) {
RTEMS_SYSLOG_ERROR( "Block count out of range");
return -RTEMS_INTERNAL_ERROR;
}
#endif /* DEBUG */
/* Start */
sc = sd_card_start( e);
RTEMS_CLEANUP_SC_RV( sc, rv, sd_card_disk_block_read_cleanup, "Start");
if (r->bufnum == 1) {
#ifdef DEBUG
/* Check buffer */
if (r->bufs [0].length != e->block_size) {
RTEMS_DO_CLEANUP_RV( -RTEMS_INTERNAL_ERROR, rv, sd_card_disk_block_read_cleanup, "Buffer and disk block size are not equal");
}
RTEMS_DEBUG_PRINT( "[01:01]: buffer = 0x%08x, size = %u\n", r->bufs [0].buffer, r->bufs [0].length);
#endif /* DEBUG */
/* Single block read */
rv = sd_card_send_command( e, SD_CARD_CMD_READ_SINGLE_BLOCK, start_address);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_read_cleanup, "Send: SD_CARD_CMD_READ_SINGLE_BLOCK");
rv = sd_card_read( e, SD_CARD_START_BLOCK_SINGLE_BLOCK_READ, (uint8_t *) r->bufs [0].buffer, (int) e->block_size);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_read_cleanup, "Read: SD_CARD_CMD_READ_SINGLE_BLOCK");
} else {
/* Start multiple block read */
rv = sd_card_send_command( e, SD_CARD_CMD_READ_MULTIPLE_BLOCK, start_address);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_read_stop_cleanup, "Send: SD_CARD_CMD_READ_MULTIPLE_BLOCK");
/* Multiple block read */
for (i = 0; i < r->bufnum; ++i) {
#ifdef DEBUG
/* Check buffer */
if (r->bufs [i].length != e->block_size) {
RTEMS_DO_CLEANUP_RV( -RTEMS_INTERNAL_ERROR, rv, sd_card_disk_block_read_stop_cleanup, "Buffer and disk block size are not equal");
}
RTEMS_DEBUG_PRINT( "[%02u:%02u]: buffer = 0x%08x, size = %u\n", i + 1, r->bufnum, r->bufs [i].buffer, r->bufs [i].length);
#endif /* DEBUG */
rv = sd_card_read( e, SD_CARD_START_BLOCK_MULTIPLE_BLOCK_READ, (uint8_t *) r->bufs [i].buffer, (int) e->block_size);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_read_stop_cleanup, "Read block");
}
/* Stop multiple block read */
rv = sd_card_stop_multiple_block_read( e);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_read_cleanup, "Stop multiple block read");
}
/* Stop */
sc = sd_card_stop( e);
RTEMS_CHECK_SC_RV( sc, "Stop");
/* Done */
r->req_done( r->done_arg, RTEMS_SUCCESSFUL);
return 0;
sd_card_disk_block_read_stop_cleanup:
/* Stop multiple block read */
sd_card_stop_multiple_block_read( e);
sd_card_disk_block_read_cleanup:
/* Stop */
sd_card_stop( e);
/* Done */
r->req_done( r->done_arg, RTEMS_IO_ERROR);
return rv;
}
static int sd_card_disk_block_write( sd_card_driver_entry *e, rtems_blkdev_request *r)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
int rv = 0;
uint32_t start_address = RTEMS_BLKDEV_START_BLOCK (r) << e->block_size_shift;
uint32_t i = 0;
#ifdef DEBUG
/* Check request */
if (r->bufs[0].block >= e->block_number) {
RTEMS_SYSLOG_ERROR( "Start block number out of range");
return -RTEMS_INTERNAL_ERROR;
} else if (r->bufnum > e->block_number - RTEMS_BLKDEV_START_BLOCK (r)) {
RTEMS_SYSLOG_ERROR( "Block count out of range");
return -RTEMS_INTERNAL_ERROR;
}
#endif /* DEBUG */
/* Start */
sc = sd_card_start( e);
RTEMS_CLEANUP_SC_RV( sc, rv, sd_card_disk_block_write_cleanup, "Start");
if (r->bufnum == 1) {
#ifdef DEBUG
/* Check buffer */
if (r->bufs [0].length != e->block_size) {
RTEMS_DO_CLEANUP_RV( -RTEMS_INTERNAL_ERROR, rv, sd_card_disk_block_write_cleanup, "Buffer and disk block size are not equal");
}
RTEMS_DEBUG_PRINT( "[01:01]: buffer = 0x%08x, size = %u\n", r->bufs [0].buffer, r->bufs [0].length);
#endif /* DEBUG */
/* Single block write */
rv = sd_card_send_command( e, SD_CARD_CMD_WRITE_BLOCK, start_address);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_write_cleanup, "Send: SD_CARD_CMD_WRITE_BLOCK");
rv = sd_card_write( e, SD_CARD_START_BLOCK_SINGLE_BLOCK_WRITE, (uint8_t *) r->bufs [0].buffer, (int) e->block_size);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_write_cleanup, "Write: SD_CARD_CMD_WRITE_BLOCK");
} else {
/* Start multiple block write */
rv = sd_card_send_command( e, SD_CARD_CMD_WRITE_MULTIPLE_BLOCK, start_address);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_write_stop_cleanup, "Send: SD_CARD_CMD_WRITE_MULTIPLE_BLOCK");
/* Multiple block write */
for (i = 0; i < r->bufnum; ++i) {
#ifdef DEBUG
/* Check buffer */
if (r->bufs [i].length != e->block_size) {
RTEMS_DO_CLEANUP_RV( -RTEMS_INTERNAL_ERROR, rv, sd_card_disk_block_write_stop_cleanup, "Buffer and disk block size are not equal");
}
RTEMS_DEBUG_PRINT( "[%02u:%02u]: buffer = 0x%08x, size = %u\n", i + 1, r->bufnum, r->bufs [i].buffer, r->bufs [i].length);
#endif /* DEBUG */
rv = sd_card_write( e, SD_CARD_START_BLOCK_MULTIPLE_BLOCK_WRITE, (uint8_t *) r->bufs [i].buffer, (int) e->block_size);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_write_stop_cleanup, "Write block");
}
/* Stop multiple block write */
rv = sd_card_stop_multiple_block_write( e);
RTEMS_CLEANUP_RV( rv, sd_card_disk_block_write_cleanup, "Stop multiple block write");
}
/* Get card status */
rv = sd_card_send_command( e, SD_CARD_CMD_SEND_STATUS, 0);
RTEMS_CHECK_RV( rv, "Send: SD_CARD_CMD_SEND_STATUS");
/* Stop */
sc = sd_card_stop( e);
RTEMS_CHECK_SC_RV( sc, "Stop");
/* Done */
r->req_done( r->done_arg, RTEMS_SUCCESSFUL);
return 0;
sd_card_disk_block_write_stop_cleanup:
/* Stop multiple block write */
sd_card_stop_multiple_block_write( e);
sd_card_disk_block_write_cleanup:
/* Get card status */
rv = sd_card_send_command( e, SD_CARD_CMD_SEND_STATUS, 0);
RTEMS_CHECK_RV( rv, "Send: SD_CARD_CMD_SEND_STATUS");
/* Stop */
sd_card_stop( e);
/* Done */
r->req_done( r->done_arg, RTEMS_IO_ERROR);
return rv;
}
static int sd_card_disk_ioctl( rtems_disk_device *dd, uint32_t req, void *arg)
{
RTEMS_DEBUG_PRINT( "dev = %u, req = %u, arg = 0x08%x\n", dev, req, arg);
if (req == RTEMS_BLKIO_REQUEST) {
rtems_device_minor_number minor = rtems_disk_get_minor_number( dd);
sd_card_driver_entry *e = &sd_card_driver_table [minor];
rtems_blkdev_request *r = (rtems_blkdev_request *) arg;
int (*f)( sd_card_driver_entry *, rtems_blkdev_request *);
uint32_t retries = e->retries;
int result;
switch (r->req) {
case RTEMS_BLKDEV_REQ_READ:
f = sd_card_disk_block_read;
break;
case RTEMS_BLKDEV_REQ_WRITE:
f = sd_card_disk_block_write;
break;
default:
errno = EINVAL;
return -1;
}
do {
result = f( e, r);
} while (retries-- > 0 && result != 0);
return result;
} else if (req == RTEMS_BLKIO_CAPABILITIES) {
*(uint32_t *) arg = RTEMS_BLKDEV_CAP_MULTISECTOR_CONT;
return 0;
} else {
errno = EINVAL;
return -1;
}
}
static rtems_status_code sd_card_disk_init( rtems_device_major_number major, rtems_device_minor_number minor, void *arg)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
/* Initialize disk IO */
sc = rtems_disk_io_initialize();
RTEMS_CHECK_SC( sc, "Initialize RTEMS disk IO");
for (minor = 0; minor < sd_card_driver_table_size; ++minor) {
sd_card_driver_entry *e = &sd_card_driver_table [minor];
dev_t dev = rtems_filesystem_make_dev_t( major, minor);
uint32_t retries = e->retries;
/* Initialize SD Card */
do {
sc = sd_card_init( e);
} while (retries-- > 0 && sc != RTEMS_SUCCESSFUL);
RTEMS_CHECK_SC( sc, "Initialize SD Card");
/* Create disk device */
sc = rtems_disk_create_phys( dev, e->block_size, e->block_number, sd_card_disk_ioctl, NULL, e->device_name);
RTEMS_CHECK_SC( sc, "Create disk device");
}
return RTEMS_SUCCESSFUL;
}
/** @} */
static const rtems_driver_address_table sd_card_disk_ops = {
.initialization_entry = sd_card_disk_init,
.open_entry = rtems_blkdev_generic_open,
.close_entry = rtems_blkdev_generic_close,
.read_entry = rtems_blkdev_generic_read,
.write_entry = rtems_blkdev_generic_write,
.control_entry = rtems_blkdev_generic_ioctl
};
rtems_status_code sd_card_register( void)
{
rtems_status_code sc = RTEMS_SUCCESSFUL;
rtems_device_major_number major = 0;
sc = rtems_io_register_driver( 0, &sd_card_disk_ops, &major);
RTEMS_CHECK_SC( sc, "Register disk SD Card driver");
return RTEMS_SUCCESSFUL;
}
|
yangxi/omap4m3
|
c/src/libchip/i2c/spi-sd-card.c
|
C
|
gpl-2.0
| 38,157
|
/*
* responsive.custom.css is for custom media queries that are not set via the
* theme settings, such as cascading media queries.
*
* By default all the other responsive stylesheets used in Adaptivetheme use a
* "stacking method", however cascading media queries use a waterfall method so
* you can leverage the cascade and inheritance for all browsers that support
* media queries, regardless of screen size.
*
* @SEE http://zomigi.com/blog/essential-considerations-for-crafting-quality-media-queries/#mq-overlap-stack
*
* NOTE: this file loads by default, to disable got to your theme settings and
* look under the "CSS" settings tab.
*/
/*
* Really small screens and up
*/
/* @media only screen and (min-width: 220px) {} */
/*
* Smartphone sizes and up
*/
/* @media only screen and (min-width: 320px) {} */
/*
* Smartphone sizes and down
*/
@media only screen and (max-width: 480px) {
/*
* Float Region blocks example:
* In smaller screen sizes we can remove the float and widths so all blocks
* stack instead of displaying horizonally. The selector used here is an
* "attribute selector" which will match on any float block class. Use your
* inspector or Firebug to get the classes from the page output if you need
* more granular control over block alignment and stacking.
*
* "Float Region blocks" is an extension for floating blocks in regions, see
* your themes appearance settings, under the Extensions tab.
*/
.region[class*="float-blocks"] .block {
float: none;
width: 100%;
}
}
/*
* Tablet sizes and up
*/
/* @media only screen and (min-width: 768px) {} */
/*
* Desktops/laptops and up
*/
/* @media only screen and (min-width: 1025px) {} */
@media only screen and (max-width:399px) {
/*
* Important Information about this CSS File
*
* - Do not delete or rename this file, if you do not use it leave it blank (delete
* everything) and the file will be skipped when you enable Production Mode in
* the Global theme settings.
*
* - Read the _README file in this directory, it contains useful help and other information.
*/
/* Increase the default font size on small devices */
/*
html {
font-size: 112.5%;
}
*/
#media-check {
/* used for testing media query in js */
font-family: 'smartphone_portrait';
}
/* Department Footer */
#footer #iit-department-footer {
text-align: center;
margin-bottom: 4px;
}
#footer #iit-department-footer h5 {
font-size: 1.25em;
margin: 6px 0 0 0;
}
/* end Department Footer */
/* Home Page Header */
#header .iit-page-header h2 {
padding-bottom: 0.20588235294118em;
}
/* end Home Page Header */
/* Department Page Header */
#header .lewis-dept-header a h2 {
margin: 0 0 0 0.22857142857143em;
font-size: 2em;
}
/* end Department Page Header */
/* Department Homepages */
/* Row */
#content .panel-flexible.dept-home .dept-home-row .one-column {
width: 48.214285714286%;
margin: 0.892857142857%;
}
#content .panel-flexible.dept-home .dept-home-row .two-column {
width: 98.214285714286%;
margin: 0.892857142857%;
}
/* end Row */
/* end Department Homepages */
/* header menu */
#header .block-menu-block {
border-top: 1px solid #888;
}
/* end header menu */
/* header top 3 menu */
#header #block-menu-block-3 {
margin-top: 0.9em;
}
#header #block-menu-block-3 ul li {
margin: 4px 0;
}
/* end header top 3 menu*/
/* Sidebar Icon Links */
#block-block-10 {
margin-left: 10px;
margin-right: 10px;
width: inherit;
}
/* end Sidebar Icon Links */
/* Lewis Hompage Hero Nav */
#content .lewis-home .hero-row .hero-right {
display: none;
}
#content .lewis-home .hero-row .block {
margin: 0;
}
#content .lewis-home .hero-row .hero-left {
width: 100%
}
#content .lewis-home .hero-row .hero-left .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-left .hero-nav {
margin-bottom: 10px;
}
#content .lewis-home .hero-row .hero-left .hero-nav a {
display: block;
color: #fff;
font-family: 'oswald', sans-serif;
font-weight: 400;
font-size: 2em;
text-decoration: none;
text-transform: uppercase;
}
#content .lewis-home .hero-row .hero-left .hero-nav a span {
position: relative;
left: 8px;
}
#content .lewis-home .hero-row .hero-left .hero-nav::after {
content: "";
background-color: #295F6C;
display: block;
width: 100%;
height: 0;
padding-bottom: 6px;
margin-top: 2px;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum::after {
background-color: #a6a89c;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy::after {
background-color: #302e2f;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc::after {
background-color: #b84e46;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum a {
background-color: #89b3c1;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy a {
background-color: #7d9395;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc a {
background-color: #6291a5;
}
#content .lewis-home .hero-row .hero-left .hero-nav-app a {
background-color: #8ead52;
}
/* end Lewis Hompage Hero Nav */
/* HS_Admission Buttons Peter Made */
#HS_Admission div {
float:none;
width:inherit;
margin: 2% 0;
}
/* end HS_Admission Buttons Peter Made */
/* Profile Page */
.node-type-profile .field-name-profile-intext-sidebar {
float: none;
margin: 0 0 20px 0;
width: inherit;
}
/* end Profile Page */
/* Full Body Slideshow */
.full-body-slideshow .flexslider .slideshow-item .slide-image .slide-show-more {
display: none;
}
.full-body-slideshow .flexslider .flex-control-nav {
bottom: 3px;
padding: 0;
line-height: 11px;
}
.full-body-slideshow .flexslider .flex-control-nav li {
margin: 0 2px;
}
.full-body-slideshow .flexslider .slideshow-item .slide-caption {
height: 0;
padding-bottom: 25%;
width: 100%;
}
.full-body-slideshow .slide-title {
margin: 15px 15px 8px;
font-size: 22px;
line-height: 1.25em;
}
.full-body-slideshow .slide-body {
display: none;
}
/* end Full Body Slideshow */
}
@media only screen and (min-width:400px) and (max-width:599px) {
/*
* Important Information about this CSS File
*
* - Do not delete or rename this file, if you do not use it leave it blank (delete
* everything) and the file will be skipped when you enable Production Mode in
* the Global theme settings.
*
* - Read the _README file in this directory, it contains useful help and other information.
*/
/* Increase the body font size on small devices */
/*
html {
font-size: 112.5%;
}
*/
#media-check {
/* used for testing media query in js */
font-family: 'smartphone_landscape';
}
/* Department Footer */
#footer #iit-department-footer {
text-align: center;
margin-bottom: 4px;
}
#footer #iit-department-footer h5 {
font-size: 1.313em;
margin: 6px 0 0 0;
}
/* end Department Footer */
/* Home Page Header */
#header .iit-page-header h2 {
padding-bottom: 0.20588235294118em;
}
/* end Home Page Header */
/* Department Page Header */
#header .lewis-dept-header a h2 {
margin: 0 0 0 0.22857142857143em;
font-size: 2em;
}
/* end Department Page Header */
/* Department Homepages */
/* Row */
#content .panel-flexible.dept-home .dept-home-row .one-column {
width: 48.214285714286%;
margin: 0.892857142857%;
}
#content .panel-flexible.dept-home .dept-home-row .two-column {
width: 98.214285714286%;
margin: 0.892857142857%;
}
/* end Row */
/* end Department Homepages */
/* header menu */
#header .block-menu-block {
border-top: 1px solid #888;
}
/* end header menu */
/* header top 3 menu */
#header #block-menu-block-3 {
margin-top: 0.9em;
}
#header #block-menu-block-3 ul li {
margin: 4px 0;
}
/* end header top 3 menu*/
/* Sidebar Icon Links */
#block-block-10 {
margin-left: 10px;
margin-right: 10px;
width: inherit;
}
/* end Sidebar Icon Links */
/* Lewis Hompage Hero Nav */
#content .lewis-home .hero-row .hero-right {
display: none;
}
#content .lewis-home .hero-row .block {
margin: 0;
}
#content .lewis-home .hero-row .hero-left {
width: 100%
}
#content .lewis-home .hero-row .hero-left .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-left .hero-nav {
margin-bottom: 10px;
}
#content .lewis-home .hero-row .hero-left .hero-nav a {
display: block;
color: #fff;
font-family: 'oswald', sans-serif;
font-weight: 400;
font-size: 2em;
text-decoration: none;
text-transform: uppercase;
}
#content .lewis-home .hero-row .hero-left .hero-nav a span {
position: relative;
left: 8px;
}
#content .lewis-home .hero-row .hero-left .hero-nav::after {
content: "";
background-color: #295F6C;
display: block;
width: 100%;
height: 0;
padding-bottom: 6px;
margin-top: 2px;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum::after {
background-color: #a6a89c;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy::after {
background-color: #302e2f;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc::after {
background-color: #b84e46;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum a {
background-color: #89b3c1;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy a {
background-color: #7d9395;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc a {
background-color: #6291a5;
}
#content .lewis-home .hero-row .hero-left .hero-nav-app a {
background-color: #8ead52;
}
/* end Lewis Hompage Hero Nav */
/* HS_Admission Buttons Peter Made */
#HS_Admission div {
float:none;
width:inherit;
margin: 2% 0;
}
/* end HS_Admission Buttons Peter Made */
/* Profile Page */
.node-type-profile .field-name-profile-intext-sidebar {
float: none;
margin: 0 0 20px 0;
width: inherit;
}
/* end Profile Page */
/* Full Body Slideshow */
.full-body-slideshow .flexslider .slideshow-item .slide-image .slide-show-more {
display: none;
}
.full-body-slideshow .flexslider .flex-control-nav {
bottom: 3px;
padding: 0;
}
.full-body-slideshow .flexslider .flex-control-nav li {
margin: 0 2px;
}
.full-body-slideshow .flexslider .slideshow-item .slide-caption {
height: 0;
padding-bottom: 25%;
width: 100%;
}
.full-body-slideshow .slide-title {
margin: 20px 20px 8px;
font-size: 28px;
line-height: 1.25em;
}
.full-body-slideshow .slide-body {
display: none;
}
/* end Full Body Slideshow */
}
@media only screen and (min-width:600px) and (max-width:799px) {
/*
* Important Information about this CSS File
*
* - Do not delete or rename this file, if you do not use it leave it blank (delete
* everything) and the file will be skipped when you enable Production Mode in
* the Global theme settings.
*
* - Read the _README file in this directory, it contains useful help and other information.
*/
/* Increase the body font size on small devices */
/*
html {
font-size: 81.3%;
}
*/
#media-check {
/* used for testing media query in js */
font-family: 'tablet_portrait';
}
/* Page main content region and sidebar margins */
div.region-sidebar-second .block {
width: inherit;
}
/* end Page main content region */
/* Department Footer */
#footer #iit-department-footer {
margin-bottom: 4px;
text-align: center;
}
#footer #iit-department-footer h5 {
font-size: 1.313em;
margin: 6px 0 0 0;
}
/* end Department Footer */
/* Page Header Region */
#header-wrapper {
margin-bottom: 2em;
}
.page-humanities #header-wrapper,
.page-social-sciences #header-wrapper,
.page-psychology #header-wrapper {
margin-bottom: 6px;
}
/* end Page Header Region */
/* Home Page Header */
#header .iit-page-header h2 {
font-size: 1.875em;
padding: 0.53333333333333em 0 0.26666666666667em;
}
/* end Home Page Header */
/* Department Page Header */
#header .lewis-dept-header a h2 {
margin: 0 0 0 0.22857142857143em;
font-size: 2.1875em;
}
/* end Department Page Header */
/* header menu */
#header .block-menu-block ul {
float: left;
width: 100%;
}
#header .block-menu-block .menu-block-wrapper ul li {
float: left;
}
/* end header menu */
/* header top 3 menu */
#header #block-menu-block-3 {
position: absolute;
right:0;
top: 12px;
}
/* end header top 3 menu*/
/* Sidebar Icon Links */
#block-block-10 {
margin-left: 10px;
margin-right: 10px;
}
/* end Sidebar Icon Links */
/* Lewis Hompage Hero Nav */
#content .lewis-home .hero-row {
margin: 0 10px;
}
#content .lewis-home .hero-row .block-inner {
margin: 0;
}
#content .lewis-home .hero-row .block {
margin: 0;
}
#content .lewis-home .hero-row .hero-left {
float: left;
width: 28.125%;
margin-right: 1.785714285714%;
}
#content .lewis-home .hero-row .hero-left .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-left .hero-nav {
margin-bottom: 6.031746031746%;
}
#content .lewis-home .hero-row .hero-left .hero-nav a {
display: block;
position: relative;
height: 0;
padding-bottom: 20%;
color: #fff;
font-family: 'oswald', sans-serif;
font-weight: 400;
font-size: 1.25em;
text-decoration: none;
text-transform: uppercase;
}
#content .lewis-home .hero-row .hero-left .hero-nav a span {
position: absolute;
bottom: 0;
left: 8px;
}
#content .lewis-home .hero-row .hero-left .hero-nav::after {
content: "";
background-color: #295F6C;
display: block;
width: 100%;
height: 0;
padding-bottom: 1.904761904762%;
margin-top: 0.634920634921%;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum::after {
background-color: #a6a89c;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy::after {
background-color: #302e2f;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc::after {
background-color: #b84e46;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum a {
background-color: #89b3c1;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy a {
background-color: #7d9395;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc a {
background-color: #6291a5;
}
#content .lewis-home .hero-row .hero-left .hero-nav-app a {
background-color: #8ead52;
}
#content .lewis-home .hero-row .hero-right {
float: left;
width: 70.089285714286%;
}
#content .lewis-home .hero-row .hero-right .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-right img {
margin: 0;
display: block;
}
/* end Lewis Hompage Hero Nav */
/* faculty directory view */
.lewis-faculty-directory.view-faculty .views-row {
border-bottom: 0;
padding: 0.25em 0;
}
.lewis-faculty-directory.view-faculty .views-field-nothing {
float:left;
width:35%;
}
.lewis-faculty-directory.view-faculty .views-field-field-title {
float: left;
width: 65%;
padding-top: 0.538461538em;
}
/* end faculty directory view */
/* full faculty bio view */
.node-faculty .two-brick > .panel-row > .region-two-brick-right-above {
width: 71%;
}
.node-faculty .two-brick > .panel-row > .region-two-brick-left-above {
width: 26%;
margin-right: 3%;
}
/* end full faculty bio view */
/* faculty department directory view */
.department-faculty-directory.view-faculty .views-row {
border-bottom: 0;
padding: 0.25em 0;
}
.department-faculty-directory.view-faculty .views-field-title {
float:left;
width:35%;
}
.department-faculty-directory.view-faculty .views-field-field-title {
float: left;
width: 65%;
padding-top: 0.538461538em;
}
/* end faculty directory view */
/* Full Body Slideshow */
.full-body-slideshow .flexslider .slideshow-item .slide-image .slide-show-more {
display: none;
}
.full-body-slideshow .flexslider .flex-control-nav {
bottom: 6px;
padding: 0;
line-height: 11px;
}
.full-body-slideshow .flexslider .flex-control-nav li {
margin: 0 2px;
}
.full-body-slideshow .flexslider .slideshow-item .slide-caption {
height: 0;
padding-bottom: 25%;
width: 100%;
}
.full-body-slideshow .slide-title {
margin: 10px 15px 8px;
font-size: 31px;
line-height: 1.25em;
}
.full-body-slideshow .slide-body {
margin: 8px 15px;
font-size: 15px;
line-height: 1.35em;
}
.full-body-slideshow .slide-body p {
font-size: 1em;
line-height: 1.35em;
margin-bottom: 0.6em
}
/* end Full Body Slideshow */
}
@media only screen and (min-width:800px) and (max-width:1024px) {
/*
* Important Information about this CSS File
*
* - Do not delete or rename this file, if you do not use it leave it blank (delete
* everything) and the file will be skipped when you enable Production Mode in
* the Global theme settings.
*
* - Read the _README file in this directory, it contains useful help and other information.
*/
#media-check {
/* used for testing media query in js */
font-family: 'tablet_landscape';
}
/* Page main content region and sidebar margins */
.sidebar-second #content-column .content-inner {
margin-right: 30.26315789%;
}
div.region-sidebar-second {
margin-left: -29.12280701%;
}
/* end Page main content region */
/* Department Footer */
#footer #iit-department-footer {
margin-bottom: 4px;
}
#footer #iit-department-footer h5 {
font-size: 1.313em;
margin: 6px 0 0 0;
}
#footer #iit-department-footer .social-icons {
position: absolute;
top: 0;
right: 0;
margin-top: 6px;
}
/* end Department Footer */
/* Page Header Region */
#header-wrapper {
margin-bottom: 2em;
}
.page-humanities #header-wrapper,
.page-social-sciences #header-wrapper,
.page-psychology #header-wrapper {
margin-bottom: 6px;
}
/* end Page Header Region */
/* Home Page Header */
#header .iit-page-header h2 {
font-size: 1.875em;
padding: 0.53333333333333em 0 0.26666666666667em;
}
/* end Home Page Header */
/* Department Page Header */
#header .lewis-dept-header a h2 {
margin: 0 0 0 0.22857142857143em;
font-size: 2.1875em;
}
/* end Department Page Header */
/* header menu */
#header .block-menu-block ul {
float: left;
width: 100%;
}
#header .block-menu-block .menu-block-wrapper ul li {
float: left;
}
/* end header menu */
/* header top 3 menu */
#header #block-menu-block-3 {
position: absolute;
right:0;
top: 12px;
}
/* end header top 3 menu*/
/* Lewis Hompage Hero Nav */
#content .lewis-home .hero-row {
margin: 0 10px;
}
#content .lewis-home .hero-row .block-inner {
margin: 0;
}
#content .lewis-home .hero-row .block {
margin: 0;
}
#content .lewis-home .hero-row .hero-left {
float: left;
width: 28.125%;
margin-right: 1.785714285714%;
}
#content .lewis-home .hero-row .hero-left .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-left .hero-nav {
margin-bottom: 6.031746031746%;
}
#content .lewis-home .hero-row .hero-left .hero-nav a {
display: block;
position: relative;
height: 0;
padding-bottom: 20%;
color: #fff;
font-family: 'oswald', sans-serif;
font-weight: 400;
font-size: 1.55em;
text-decoration: none;
text-transform: uppercase;
}
#content .lewis-home .hero-row .hero-left .hero-nav a span {
position: absolute;
bottom: 0;
left: 8px;
}
#content .lewis-home .hero-row .hero-left .hero-nav::after {
content: "";
background-color: #295F6C;
display: block;
width: 100%;
height: 0;
padding-bottom: 1.904761904762%;
margin-top: 0.634920634921%;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum::after {
background-color: #a6a89c;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy::after {
background-color: #302e2f;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc::after {
background-color: #b84e46;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum a {
background-color: #89b3c1;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy a {
background-color: #7d9395;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc a {
background-color: #6291a5;
}
#content .lewis-home .hero-row .hero-left .hero-nav-app a {
background-color: #8ead52;
}
#content .lewis-home .hero-row .hero-right {
float: left;
width: 70.089285714286%;
}
#content .lewis-home .hero-row .hero-right .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-right img {
margin: 0;
display: block;
}
/* end Lewis Hompage Hero Nav */
/* faculty directory view */
.lewis-faculty-directory.view-faculty .views-row {
border-bottom: 0;
padding: 0.25em 0;
}
.lewis-faculty-directory.view-faculty .views-field-nothing {
float:left;
width:35%;
}
.lewis-faculty-directory.view-faculty .views-field-field-title {
float: left;
width: 65%;
padding-top: 0.538461538em;
}
/* end faculty directory view */
/* full faculty bio view */
.node-faculty .two-brick > .panel-row > .region-two-brick-right-above {
width: 71%;
}
.node-faculty .two-brick > .panel-row > .region-two-brick-left-above {
width: 26%;
margin-right: 3%;
}
/* end full faculty bio view */
/* faculty department directory view */
.department-faculty-directory.view-faculty .views-row {
border-bottom: 0;
padding: 0.25em 0;
}
.department-faculty-directory.view-faculty .views-field-title {
float:left;
width:35%;
}
.department-faculty-directory.view-faculty .views-field-field-title {
float: left;
width: 65%;
padding-top: 0.538461538em;
}
/* end faculty directory view */
/* Full Body Slideshow Slideshow */
.full-body-slideshow .flexslider .slideshow-item .slide-caption {
float: left;
width: 31.25%;
height: 0;
padding-bottom: 31.25%;
}
.full-body-slideshow .flexslider .slideshow-item .slide-image {
float: left;
width: 68.75%;
position: relative;
}
.full-body-slideshow .flexslider .slideshow-item .slide-image .slide-show-more {
position: absolute;
bottom: 10px;
right: 10px;
display: block;
padding: 4px 8px;
font-weight: 600;
}
.full-body-slideshow .flexslider .flex-control-nav {
bottom: 6px;
left: 6px;
width: inherit;
padding: 0;
line-height: 11px;
}
.full-body-slideshow .flexslider .flex-control-nav li {
margin: 0 2px;
}
.full-body-slideshow .slide-title {
margin: 30px 25px 8px;
font-size: 24px;
line-height: 1.25em;
}
.full-body-slideshow .slide-body {
margin: 8px 25px;
font-size: 14px;
}
.full-body-slideshow .slide-body p {
font-size: 1em;
line-height: 1.35em;
margin-bottom: 0.75em;
}
/* end Full Body Slideshow */
}
@media only screen and (min-width:1025px) {
/*
* Important Information about this CSS File
*
* - Do not delete or rename this file, if you do not use it leave it blank (delete
* everything) and the file will be skipped when you enable Production Mode in
* the Global theme settings.
*
* - Read the _README file in this directory, it contains useful help and other information.
*/
#media-check {
/* used for testing media query in js */
font-family: 'desktop';
}
/* Page main content region and sidebar margins */
.sidebar-second #content-column .content-inner {
margin-right: 30.26315789%;
}
div.region-sidebar-second {
margin-left: -29.12280701%;
}
/* end Page main content region */
/* Department Footer */
#footer #iit-department-footer {
margin-bottom: 4px;
}
#footer #iit-department-footer h5 {
font-size: 1.313em;
margin: 6px 0 0 0;
}
#footer #iit-department-footer .social-icons {
position: absolute;
top: 0;
right: 0;
margin-top: 6px;
}
/* end Department Footer */
/* Page Header Region */
#header-wrapper {
margin-bottom: 2em;
}
.page-humanities #header-wrapper,
.page-social-sciences #header-wrapper,
.page-psychology #header-wrapper {
margin-bottom: 6px;
}
/* end Page Header Region */
/* Home Page Header */
#header .iit-page-header h2 {
font-size: 2.3125em;
padding: 1.25em 0 0.26666666666667em;
}
/* end Home Page Header */
/* Department Page Header */
#header .lewis-dept-header a h2 {
margin: 0 0 0 0.22857142857143em;
font-size: 2.1875em;
}
/* end Department Page Header */
/* header menu */
#header .block-menu-block ul {
float: left;
width: 100%;
}
#header .block-menu-block .menu-block-wrapper ul li {
float: left;
}
/* end header menu */
/* header top 3 menu */
#header #block-menu-block-3 {
position: absolute;
right:0;
top: 12px;
}
/* end header top 3 menu*/
/* Lewis Hompage Hero Nav */
#content .lewis-home .hero-row {
margin: 0 10px;
}
#content .lewis-home .hero-row .block-inner {
margin: 0;
}
#content .lewis-home .hero-row .block {
margin: 0;
}
#content .lewis-home .hero-row .hero-left {
float: left;
width: 28.125%;
margin-right: 1.785714285714%;
}
#content .lewis-home .hero-row .hero-left .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-left .hero-nav {
margin-bottom: 6.031746031746%;
}
#content .lewis-home .hero-row .hero-left .hero-nav a {
display: block;
position: relative;
height: 0;
padding-bottom: 20%;
color: #fff;
font-family: 'oswald', sans-serif;
font-weight: 400;
font-size: 1.75em;
text-decoration: none;
text-transform: uppercase;
}
#content .lewis-home .hero-row .hero-left .hero-nav a span {
position: absolute;
bottom: 0;
left: 8px;
}
#content .lewis-home .hero-row .hero-left .hero-nav::after {
content: "";
background-color: #295F6C;
display: block;
width: 100%;
height: 0;
padding-bottom: 1.904761904762%;
margin-top: 0.634920634921%;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum::after {
background-color: #a6a89c;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy::after {
background-color: #302e2f;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc::after {
background-color: #b84e46;
}
#content .lewis-home .hero-row .hero-left .hero-nav-hum a {
background-color: #89b3c1;
}
#content .lewis-home .hero-row .hero-left .hero-nav-psy a {
background-color: #7d9395;
}
#content .lewis-home .hero-row .hero-left .hero-nav-soc a {
background-color: #6291a5;
}
#content .lewis-home .hero-row .hero-left .hero-nav-app a {
background-color: #8ead52;
}
#content .lewis-home .hero-row .hero-right {
float: left;
width: 70.089285714286%;
}
#content .lewis-home .hero-row .hero-right .inside {
padding: 0;
}
#content .lewis-home .hero-row .hero-right img {
margin: 0;
display: block;
}
/* end Lewis Hompage Hero Nav */
/* faculty directory view */
.lewis-faculty-directory.view-faculty .views-row {
border-bottom: 0;
padding: 0.25em 0;
}
.lewis-faculty-directory.view-faculty .views-field-nothing {
float:left;
width:35%;
}
.lewis-faculty-directory.view-faculty .views-field-field-title {
float: left;
width: 65%;
padding-top: 0.538461538em;
}
/* end faculty directory view */
/* full faculty bio view */
.node-faculty .two-brick > .panel-row > .region-two-brick-right-above {
width: 71%;
}
.node-faculty .two-brick > .panel-row > .region-two-brick-left-above {
width: 26%;
margin-right: 3%;
}
/* end full faculty bio view */
/* faculty department directory view */
.department-faculty-directory.view-faculty .views-row {
border-bottom: 0;
padding: 0.25em 0;
}
.department-faculty-directory.view-faculty .views-field-title {
float:left;
width:35%;
}
.department-faculty-directory.view-faculty .views-field-field-title {
float: left;
width: 65%;
padding-top: 0.538461538em;
}
/* end faculty directory view */
/* Full Body Slideshow */
.full-body-slideshow .flexslider .slideshow-item .slide-caption {
float: left;
width: 31.25%;
height: 0;
padding-bottom: 31.25%;
}
.full-body-slideshow .flexslider .slideshow-item .slide-image {
float: left;
width: 68.75%;
position: relative;
}
.full-body-slideshow .flexslider .slideshow-item .slide-image .slide-show-more {
position: absolute;
bottom: 10px;
right: 10px;
display: block;
padding: 4px 8px;
font-weight: 600;
}
.full-body-slideshow .flexslider .flex-control-nav {
bottom: 8px;
left: 6px;
width: inherit;
padding: 0;
line-height: 11px;
}
.full-body-slideshow .flexslider .flex-control-nav li {
margin: 0 2px;
}
.full-body-slideshow .slide-title {
margin: 40px 35px 12px;
font-size: 33px;
line-height: 1.15em;
}
.full-body-slideshow .slide-body {
margin: 8px 35px;
font-size: 16px;
line-height: 1.35em;
}
.full-body-slideshow .slide-body p {
font-size: 1em;
line-height: 1.4em;
margin-bottom: 0.75em;
}
/* end Full Body Slideshow */
}
|
csepuser/EthicsPublicHtmlProd
|
eelibrary-Backups/adaptivetheme/iit_ethics_files/iit_ethics.responsive.styles.css
|
CSS
|
gpl-2.0
| 28,699
|
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#ifndef IGL_PER_FACE_NORMALS_H
#define IGL_PER_FACE_NORMALS_H
#include "igl_inline.h"
#include <Eigen/Core>
namespace igl
{
// Compute face normals via vertex position list, face list
// Inputs:
// V #V by 3 eigen Matrix of mesh vertex 3D positions
// F #F by 3 eigen Matrix of face (triangle) indices
// Z 3 vector normal given to faces with degenerate normal.
// Output:
// N #F by 3 eigen Matrix of mesh face (triangle) 3D normals
//
// Example:
// // Give degenerate faces (1/3,1/3,1/3)^0.5
// per_face_normals(V,F,Vector3d(1,1,1).normalized(),N);
template <typename DerivedV, typename DerivedF, typename DerivedZ, typename DerivedN>
IGL_INLINE void per_face_normals(
const Eigen::PlainObjectBase<DerivedV>& V,
const Eigen::PlainObjectBase<DerivedF>& F,
const Eigen::PlainObjectBase<DerivedZ> & Z,
Eigen::PlainObjectBase<DerivedN> & N);
// Wrapper with Z = (0,0,0). Note that this means that row norms will be zero
// (i.e. not 1) for degenerate normals.
template <typename DerivedV, typename DerivedF, typename DerivedN>
IGL_INLINE void per_face_normals(
const Eigen::PlainObjectBase<DerivedV>& V,
const Eigen::PlainObjectBase<DerivedF>& F,
Eigen::PlainObjectBase<DerivedN> & N);
}
#ifndef IGL_STATIC_LIBRARY
# include "per_face_normals.cpp"
#endif
#endif
|
tlgimenes/SparseModelingOfIntrinsicCorrespondences
|
external/igl/per_face_normals.h
|
C
|
gpl-2.0
| 1,688
|
<?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Model
* @copyright Copyright (C) 2007 - 2010 Johan Janssens. All rights reserved.
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Koowa Model Exception class
*
* @author Johan Janssens <johan@nooku.org>
* @category Koowa
* @package Koowa_Model
*/
class KModelException extends KException {}
|
raeldc/nooku-server
|
libraries/koowa/model/exception.php
|
PHP
|
gpl-2.0
| 448
|
/*
* Samsung Exynos5 SoC series FIMC-IS driver
*
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd
*
* 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.
*/
#ifndef FIMC_IS_BINARY_H
#define FIMC_IS_BINARY_H
#include "fimc-is-config.h"
#define SDCARD_FW
#define VENDER_PATH
#ifdef VENDER_PATH
#define FIMC_IS_FW_PATH "/system/vendor/firmware/"
#define FIMC_IS_FW_DUMP_PATH "/data/"
#define FIMC_IS_SETFILE_SDCARD_PATH "/data/media/0/"
#define FIMC_IS_FW_SDCARD "/data/media/0/fimc_is_fw2.bin"
#define FIMC_IS_FW "fimc_is_fw2.bin"
#define FIMC_IS_ISP_LIB_SDCARD_PATH "/data/media/0/"
#define FIMC_IS_ISP_LIB "fimc_is_lib_isp.bin"
#define FIMC_IS_REAR_CAL_SDCARD_PATH "/data/media/0/"
#define FIMC_IS_FRONT_CAL_SDCARD_PATH "/data/media/0/"
#define FIMC_IS_REAR_CAL "rear_cal_data.bin"
#define FIMC_IS_FRONT_CAL "front_cal_data.bin"
#else
#define FIMC_IS_FW_PATH "/data/"
#define FIMC_IS_FW_DUMP_PATH "/data/"
#define FIMC_IS_SETFILE_SDCARD_PATH "/data/"
#define FIMC_IS_FW_SDCARD "/data/fimc_is_fw2.bin"
#define FIMC_IS_FW "fimc_is_fw2.bin"
#define FIMC_IS_ISP_LIB_SDCARD_PATH "/data/"
#define FIMC_IS_ISP_LIB "fimc_is_lib_isp.bin"
#define FIMC_IS_REAR_CAL_SDCARD_PATH "/data/"
#define FIMC_IS_FRONT_CAL_SDCARD_PATH "/data/"
#define FIMC_IS_REAR_CAL "rear_cal_data.bin"
#define FIMC_IS_FRONT_CAL "front_cal_data.bin"
#endif
#define FIMC_IS_FW_BASE_MASK ((1 << 26) - 1)
#define FIMC_IS_VERSION_SIZE 42
#define FIMC_IS_SETFILE_VER_OFFSET 0x40
#define FIMC_IS_SETFILE_VER_SIZE 52
#ifdef ENABLE_IS_CORE
#ifdef SUPPORTED_A5_MEMORY_SIZE_UP
#define FIMC_IS_CAL_START_ADDR (0x01FD0000)
#else
#define FIMC_IS_CAL_START_ADDR (0x013D0000)
#endif
#else /* #ifdef ENABLE_IS_CORE */
#define FIMC_IS_CAL_START_ADDR (FIMC_IS_REAR_CALDATA_OFFSET)
#define FIMC_IS_CAL_START_ADDR_FRONT (FIMC_IS_FRONT_CALDATA_OFFSET)
#endif
#define FIMC_IS_CAL_RETRY_CNT (2)
#define FIMC_IS_FW_RETRY_CNT (2)
#define FIMC_IS_MAX_COMPANION_FW_SIZE (120 * 1024)
#if defined(CONFIG_USE_HOST_FD_LIBRARY)
#define FD_SW_BIN_NAME "fimc_is_fd.bin"
#ifdef VENDER_PATH
#define FD_SW_SDCARD_PATH "/data/media/0/"
#else
#define FD_SW_SDCARD_PATH "/data/"
#endif
#endif
enum fimc_is_bin_type {
FIMC_IS_BIN_FW = 0,
FIMC_IS_BIN_SETFILE,
FIMC_IS_BIN_LIBRARY,
};
struct fimc_is_binary {
void *data;
size_t size;
const struct firmware *fw;
unsigned long customized;
/* request_firmware retry */
unsigned int retry_cnt;
int retry_err;
/* custom memory allocation */
void *(*alloc)(unsigned long size);
void (*free)(const void *buf);
};
void setup_binary_loader(struct fimc_is_binary *bin,
unsigned int retry_cnt, int retry_err,
void *(*alloc)(unsigned long size),
void (*free)(const void *buf));
int request_binary(struct fimc_is_binary *bin, const char *path,
const char *name, struct device *device);
void release_binary(struct fimc_is_binary *bin);
int was_loaded_by(struct fimc_is_binary *bin);
#endif
|
TeamWin/android_kernel_samsung_j2lte
|
drivers/media/platform/exynos/fimc-is2/include/fimc-is-binary.h
|
C
|
gpl-2.0
| 3,101
|
/***************************************************************************
QgsAttributeTableModel.cpp
--------------------------------------
Date : Feb 2009
Copyright : (C) 2009 Vita Cizek
Email : weetya (at) gmail.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. *
* *
***************************************************************************/
#include "qgsapplication.h"
#include "qgsattributetablemodel.h"
#include "qgsattributetablefiltermodel.h"
#include "qgsattributeaction.h"
#include "qgseditorwidgetregistry.h"
#include "qgsexpression.h"
#include "qgsconditionalstyle.h"
#include "qgsfield.h"
#include "qgslogger.h"
#include "qgsmapcanvas.h"
#include "qgsmaplayeractionregistry.h"
#include "qgsmaplayerregistry.h"
#include "qgsrendererv2.h"
#include "qgsvectorlayer.h"
#include "qgsvectordataprovider.h"
#include "qgssymbollayerv2utils.h"
#include <QVariant>
#include <limits>
QgsAttributeTableModel::QgsAttributeTableModel( QgsVectorLayerCache *layerCache, QObject *parent )
: QAbstractTableModel( parent )
, mLayerCache( layerCache )
, mFieldCount( 0 )
, mCachedField( -1 )
{
QgsDebugMsg( "entered." );
mExpressionContext << QgsExpressionContextUtils::globalScope()
<< QgsExpressionContextUtils::projectScope()
<< QgsExpressionContextUtils::layerScope( layerCache->layer() );
if ( layerCache->layer()->geometryType() == QGis::NoGeometry )
{
mFeatureRequest.setFlags( QgsFeatureRequest::NoGeometry );
}
mFeat.setFeatureId( std::numeric_limits<int>::min() );
if ( !layer()->hasGeometryType() )
mFeatureRequest.setFlags( QgsFeatureRequest::NoGeometry );
loadAttributes();
connect( mLayerCache, SIGNAL( attributeValueChanged( QgsFeatureId, int, const QVariant& ) ), this, SLOT( attributeValueChanged( QgsFeatureId, int, const QVariant& ) ) );
connect( layer(), SIGNAL( featuresDeleted( QgsFeatureIds ) ), this, SLOT( featuresDeleted( QgsFeatureIds ) ) );
connect( layer(), SIGNAL( attributeDeleted( int ) ), this, SLOT( attributeDeleted( int ) ) );
connect( layer(), SIGNAL( updatedFields() ), this, SLOT( updatedFields() ) );
connect( layer(), SIGNAL( editCommandEnded() ), this, SLOT( editCommandEnded() ) );
connect( mLayerCache, SIGNAL( featureAdded( QgsFeatureId ) ), this, SLOT( featureAdded( QgsFeatureId ) ) );
connect( mLayerCache, SIGNAL( cachedLayerDeleted() ), this, SLOT( layerDeleted() ) );
}
bool QgsAttributeTableModel::loadFeatureAtId( QgsFeatureId fid ) const
{
QgsDebugMsgLevel( QString( "loading feature %1" ).arg( fid ), 3 );
if ( fid == std::numeric_limits<int>::min() )
{
return false;
}
return mLayerCache->featureAtId( fid, mFeat );
}
void QgsAttributeTableModel::featuresDeleted( const QgsFeatureIds& fids )
{
QList<int> rows;
Q_FOREACH ( const QgsFeatureId& fid, fids )
{
QgsDebugMsgLevel( QString( "(%2) fid: %1" ).arg( fid ).arg( mFeatureRequest.filterType() ), 4 );
int row = idToRow( fid );
if ( row != -1 )
rows << row;
}
qSort( rows );
int lastRow = -1;
int beginRow = -1;
int currentRowCount = 0;
int removedRows = 0;
bool reset = false;
Q_FOREACH ( int row, rows )
{
#if 0
qDebug() << "Row: " << row << ", begin " << beginRow << ", last " << lastRow << ", current " << currentRowCount << ", removed " << removedRows;
#endif
if ( lastRow == -1 )
{
beginRow = row;
}
if ( row != lastRow + 1 && lastRow != -1 )
{
if ( rows.count() > 100 && currentRowCount < 10 )
{
reset = true;
break;
}
removeRows( beginRow - removedRows, currentRowCount );
beginRow = row;
removedRows += currentRowCount;
currentRowCount = 0;
}
currentRowCount++;
lastRow = row;
}
if ( !reset )
removeRows( beginRow - removedRows, currentRowCount );
else
resetModel();
}
bool QgsAttributeTableModel::removeRows( int row, int count, const QModelIndex &parent )
{
beginRemoveRows( parent, row, row + count - 1 );
#ifdef QGISDEBUG
if ( 3 > QgsLogger::debugLevel() )
QgsDebugMsgLevel( QString( "remove %2 rows at %1 (rows %3, ids %4)" ).arg( row ).arg( count ).arg( mRowIdMap.size() ).arg( mIdRowMap.size() ), 3 );
#endif
// clean old references
for ( int i = row; i < row + count; i++ )
{
mFieldCache.remove( mRowIdMap[i] );
mIdRowMap.remove( mRowIdMap[ i ] );
mRowIdMap.remove( i );
}
// update maps
int n = mRowIdMap.size() + count;
for ( int i = row + count; i < n; i++ )
{
QgsFeatureId id = mRowIdMap[i];
mIdRowMap[ id ] -= count;
mRowIdMap[ i-count ] = id;
mRowIdMap.remove( i );
}
#ifdef QGISDEBUG
if ( 4 > QgsLogger::debugLevel() )
{
QgsDebugMsgLevel( QString( "after removal rows %1, ids %2" ).arg( mRowIdMap.size() ).arg( mIdRowMap.size() ), 4 );
QgsDebugMsgLevel( "id->row", 4 );
for ( QHash<QgsFeatureId, int>::iterator it = mIdRowMap.begin(); it != mIdRowMap.end(); ++it )
QgsDebugMsgLevel( QString( "%1->%2" ).arg( FID_TO_STRING( it.key() ) ).arg( *it ), 4 );
QHash<QgsFeatureId, int>::iterator idit;
QgsDebugMsgLevel( "row->id", 4 );
for ( QHash<int, QgsFeatureId>::iterator it = mRowIdMap.begin(); it != mRowIdMap.end(); ++it )
QgsDebugMsgLevel( QString( "%1->%2" ).arg( it.key() ).arg( FID_TO_STRING( *it ) ), 4 );
}
#endif
Q_ASSERT( mRowIdMap.size() == mIdRowMap.size() );
endRemoveRows();
return true;
}
void QgsAttributeTableModel::featureAdded( QgsFeatureId fid )
{
QgsDebugMsgLevel( QString( "(%2) fid: %1" ).arg( fid ).arg( mFeatureRequest.filterType() ), 4 );
bool featOk = true;
if ( mFeat.id() != fid )
featOk = loadFeatureAtId( fid );
if ( featOk && mFeatureRequest.acceptFeature( mFeat ) )
{
mFieldCache[ fid ] = mFeat.attribute( mCachedField );
int n = mRowIdMap.size();
beginInsertRows( QModelIndex(), n, n );
mIdRowMap.insert( fid, n );
mRowIdMap.insert( n, fid );
endInsertRows();
reload( index( rowCount() - 1, 0 ), index( rowCount() - 1, columnCount() ) );
}
}
void QgsAttributeTableModel::updatedFields()
{
QgsDebugMsg( "entered." );
loadAttributes();
emit modelChanged();
}
void QgsAttributeTableModel::editCommandEnded()
{
reload( createIndex( mChangedCellBounds.top(), mChangedCellBounds.left() ),
createIndex( mChangedCellBounds.bottom(), mChangedCellBounds.right() ) );
mChangedCellBounds = QRect();
}
void QgsAttributeTableModel::attributeDeleted( int idx )
{
if ( idx == mCachedField )
{
prefetchColumnData( -1 );
}
}
void QgsAttributeTableModel::layerDeleted()
{
QgsDebugMsg( "entered." );
removeRows( 0, rowCount() );
mAttributeWidgetCaches.clear();
mAttributes.clear();
mWidgetFactories.clear();
mWidgetConfigs.clear();
}
void QgsAttributeTableModel::attributeValueChanged( QgsFeatureId fid, int idx, const QVariant &value )
{
QgsDebugMsgLevel( QString( "(%4) fid: %1, idx: %2, value: %3" ).arg( fid ).arg( idx ).arg( value.toString() ).arg( mFeatureRequest.filterType() ), 3 );
if ( idx == mCachedField )
mFieldCache[ fid ] = value;
// No filter request: skip all possibly heavy checks
if ( mFeatureRequest.filterType() == QgsFeatureRequest::FilterNone )
{
setData( index( idToRow( fid ), fieldCol( idx ) ), value, Qt::EditRole );
}
else
{
if ( loadFeatureAtId( fid ) )
{
if ( mFeatureRequest.acceptFeature( mFeat ) )
{
if ( !mIdRowMap.contains( fid ) )
{
// Feature changed in such a way, it will be shown now
featureAdded( fid );
}
else
{
// Update representation
setData( index( idToRow( fid ), fieldCol( idx ) ), value, Qt::EditRole );
}
}
else
{
if ( mIdRowMap.contains( fid ) )
{
// Feature changed such, that it is no longer shown
featuresDeleted( QgsFeatureIds() << fid );
}
// else: we don't care
}
}
}
}
void QgsAttributeTableModel::loadAttributes()
{
if ( !layer() )
{
return;
}
bool ins = false, rm = false;
QgsAttributeList attributes;
const QgsFields& fields = layer()->fields();
mWidgetFactories.clear();
mAttributeWidgetCaches.clear();
mWidgetConfigs.clear();
for ( int idx = 0; idx < fields.count(); ++idx )
{
const QString widgetType = layer()->editorWidgetV2( idx );
QgsEditorWidgetFactory* widgetFactory = QgsEditorWidgetRegistry::instance()->factory( widgetType );
if ( widgetFactory && widgetType != "Hidden" )
{
mWidgetFactories.append( widgetFactory );
mWidgetConfigs.append( layer()->editorWidgetV2Config( idx ) );
mAttributeWidgetCaches.append( widgetFactory->createCache( layer(), idx, mWidgetConfigs.last() ) );
attributes << idx;
}
}
if ( mFieldCount < attributes.size() )
{
ins = true;
beginInsertColumns( QModelIndex(), mFieldCount, attributes.size() - 1 );
}
else if ( attributes.size() < mFieldCount )
{
rm = true;
beginRemoveColumns( QModelIndex(), attributes.size(), mFieldCount - 1 );
}
mFieldCount = attributes.size();
mAttributes = attributes;
if ( ins )
{
endInsertColumns();
}
else if ( rm )
{
endRemoveColumns();
}
}
void QgsAttributeTableModel::loadLayer()
{
QgsDebugMsg( "entered." );
// make sure attributes are properly updated before caching the data
// (emit of progress() signal may enter event loop and thus attribute
// table view may be updated with inconsistent model which may assume
// wrong number of attributes)
loadAttributes();
beginResetModel();
if ( rowCount() != 0 )
{
removeRows( 0, rowCount() );
}
QgsFeatureIterator features = mLayerCache->getFeatures( mFeatureRequest );
int i = 0;
QTime t;
t.start();
QgsFeature feat;
while ( features.nextFeature( feat ) )
{
++i;
if ( t.elapsed() > 1000 )
{
bool cancel = false;
emit progress( i, cancel );
if ( cancel )
break;
t.restart();
}
mFeat = feat;
featureAdded( feat.id() );
}
emit finished();
connect( mLayerCache, SIGNAL( invalidated() ), this, SLOT( loadLayer() ), Qt::UniqueConnection );
endResetModel();
}
void QgsAttributeTableModel::fieldConditionalStyleChanged( const QString &fieldName )
{
if ( fieldName.isNull() )
{
mRowStylesMap.clear();
emit dataChanged( index( 0, 0 ), index( rowCount() - 1, columnCount() - 1 ) );
return;
}
int fieldIndex = mLayerCache->layer()->fieldNameIndex( fieldName );
if ( fieldIndex == -1 )
return;
//whole column has changed
int col = fieldCol( fieldIndex );
emit dataChanged( index( 0, col ), index( rowCount() - 1, col ) );
}
void QgsAttributeTableModel::swapRows( QgsFeatureId a, QgsFeatureId b )
{
if ( a == b )
return;
int rowA = idToRow( a );
int rowB = idToRow( b );
//emit layoutAboutToBeChanged();
mRowIdMap.remove( rowA );
mRowIdMap.remove( rowB );
mRowIdMap.insert( rowA, b );
mRowIdMap.insert( rowB, a );
mIdRowMap.remove( a );
mIdRowMap.remove( b );
mIdRowMap.insert( a, rowB );
mIdRowMap.insert( b, rowA );
//emit layoutChanged();
}
int QgsAttributeTableModel::idToRow( QgsFeatureId id ) const
{
if ( !mIdRowMap.contains( id ) )
{
QgsDebugMsg( QString( "idToRow: id %1 not in the map" ).arg( id ) );
return -1;
}
return mIdRowMap[id];
}
QModelIndex QgsAttributeTableModel::idToIndex( QgsFeatureId id ) const
{
return index( idToRow( id ), 0 );
}
QModelIndexList QgsAttributeTableModel::idToIndexList( QgsFeatureId id ) const
{
QModelIndexList indexes;
int row = idToRow( id );
int columns = columnCount();
indexes.reserve( columns );
for ( int column = 0; column < columns; ++column )
{
indexes.append( index( row, column ) );
}
return indexes;
}
QgsFeatureId QgsAttributeTableModel::rowToId( const int row ) const
{
if ( !mRowIdMap.contains( row ) )
{
QgsDebugMsg( QString( "rowToId: row %1 not in the map" ).arg( row ) );
// return negative infinite (to avoid collision with newly added features)
return std::numeric_limits<int>::min();
}
return mRowIdMap[row];
}
int QgsAttributeTableModel::fieldIdx( int col ) const
{
return mAttributes[ col ];
}
int QgsAttributeTableModel::fieldCol( int idx ) const
{
return mAttributes.indexOf( idx );
}
int QgsAttributeTableModel::rowCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return mRowIdMap.size();
}
int QgsAttributeTableModel::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return qMax( 1, mFieldCount ); // if there are zero columns all model indices will be considered invalid
}
QVariant QgsAttributeTableModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( !layer() )
return QVariant();
if ( role == Qt::DisplayRole )
{
if ( orientation == Qt::Vertical ) //row
{
return QVariant( section );
}
else if ( section >= 0 && section < mFieldCount )
{
QString attributeName = layer()->attributeAlias( mAttributes[section] );
if ( attributeName.isEmpty() )
{
QgsField field = layer()->fields().at( mAttributes[section] );
attributeName = field.name();
}
return QVariant( attributeName );
}
else
{
return tr( "feature id" );
}
}
else
{
return QVariant();
}
}
QVariant QgsAttributeTableModel::data( const QModelIndex &index, int role ) const
{
if ( !index.isValid() ||
( role != Qt::TextAlignmentRole
&& role != Qt::DisplayRole
&& role != Qt::EditRole
&& role != SortRole
&& role != FeatureIdRole
&& role != FieldIndexRole
&& role != Qt::BackgroundColorRole
&& role != Qt::TextColorRole
&& role != Qt::DecorationRole
&& role != Qt::FontRole
)
)
return QVariant();
QgsFeatureId rowId = rowToId( index.row() );
if ( role == FeatureIdRole )
return rowId;
if ( index.column() >= mFieldCount )
return role == Qt::DisplayRole ? rowId : QVariant();
int fieldId = mAttributes[ index.column()];
if ( role == FieldIndexRole )
return fieldId;
QgsField field = layer()->fields().at( fieldId );
QVariant::Type fldType = field.type();
bool fldNumeric = ( fldType == QVariant::Int || fldType == QVariant::Double || fldType == QVariant::LongLong );
if ( role == Qt::TextAlignmentRole )
{
if ( fldNumeric )
return QVariant( Qt::AlignRight );
else
return QVariant( Qt::AlignLeft );
}
QVariant val;
// if we don't have the row in current cache, load it from layer first
if ( mCachedField == fieldId )
{
val = mFieldCache[ rowId ];
}
else
{
if ( mFeat.id() != rowId || !mFeat.isValid() )
{
if ( !loadFeatureAtId( rowId ) )
return QVariant( "ERROR" );
if ( mFeat.id() != rowId )
return QVariant( "ERROR" );
}
val = mFeat.attribute( fieldId );
}
if ( role == Qt::DisplayRole )
{
return mWidgetFactories[ index.column()]->representValue( layer(), fieldId, mWidgetConfigs[ index.column()], mAttributeWidgetCaches[ index.column()], val );
}
if ( role == Qt::BackgroundColorRole || role == Qt::TextColorRole || role == Qt::DecorationRole || role == Qt::FontRole )
{
mExpressionContext.setFeature( mFeat );
QList<QgsConditionalStyle> styles;
if ( mRowStylesMap.contains( index.row() ) )
{
styles = mRowStylesMap[index.row()];
}
else
{
styles = QgsConditionalStyle::matchingConditionalStyles( layer()->conditionalStyles()->rowStyles(), QVariant(), mExpressionContext );
mRowStylesMap.insert( index.row(), styles );
}
QgsConditionalStyle rowstyle = QgsConditionalStyle::compressStyles( styles );
styles = layer()->conditionalStyles()->fieldStyles( field.name() );
styles = QgsConditionalStyle::matchingConditionalStyles( styles , val, mExpressionContext );
styles.insert( 0, rowstyle );
QgsConditionalStyle style = QgsConditionalStyle::compressStyles( styles );
if ( style.isValid() )
{
if ( role == Qt::BackgroundColorRole && style.validBackgroundColor() )
return style.backgroundColor();
if ( role == Qt::TextColorRole && style.validTextColor() )
return style.textColor();
if ( role == Qt::DecorationRole )
return style.icon();
if ( role == Qt::FontRole )
return style.font();
}
}
return val;
}
bool QgsAttributeTableModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
Q_UNUSED( value )
if ( !index.isValid() || index.column() >= mFieldCount || role != Qt::EditRole || !layer()->isEditable() )
return false;
if ( !layer()->isModified() )
return false;
if ( mChangedCellBounds.isNull() )
{
mChangedCellBounds = QRect( index.column(), index.row(), 1, 1 );
}
else
{
if ( index.column() < mChangedCellBounds.left() )
{
mChangedCellBounds.setLeft( index.column() );
}
if ( index.row() < mChangedCellBounds.top() )
{
mChangedCellBounds.setTop( index.row() );
}
if ( index.column() > mChangedCellBounds.right() )
{
mChangedCellBounds.setRight( index.column() );
}
if ( index.row() > mChangedCellBounds.bottom() )
{
mChangedCellBounds.setBottom( index.row() );
}
}
return true;
}
Qt::ItemFlags QgsAttributeTableModel::flags( const QModelIndex &index ) const
{
if ( !index.isValid() )
return Qt::ItemIsEnabled;
if ( index.column() >= mFieldCount )
return Qt::NoItemFlags;
Qt::ItemFlags flags = QAbstractItemModel::flags( index );
if ( layer()->isEditable() &&
layer()->fieldEditable( mAttributes[ index.column()] ) &&
(( layer()->dataProvider() && layer()->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) ||
FID_IS_NEW( rowToId( index.row() ) ) ) )
flags |= Qt::ItemIsEditable;
return flags;
}
void QgsAttributeTableModel::reload( const QModelIndex &index1, const QModelIndex &index2 )
{
mFeat.setFeatureId( std::numeric_limits<int>::min() );
emit dataChanged( index1, index2 );
}
void QgsAttributeTableModel::executeAction( int action, const QModelIndex &idx ) const
{
QgsFeature f = feature( idx );
layer()->actions()->doAction( action, f, fieldIdx( idx.column() ) );
}
void QgsAttributeTableModel::executeMapLayerAction( QgsMapLayerAction* action, const QModelIndex &idx ) const
{
QgsFeature f = feature( idx );
action->triggerForFeature( layer(), &f );
}
QgsFeature QgsAttributeTableModel::feature( const QModelIndex &idx ) const
{
QgsFeature f;
f.initAttributes( mAttributes.size() );
f.setFeatureId( rowToId( idx.row() ) );
for ( int i = 0; i < mAttributes.size(); i++ )
{
f.setAttribute( mAttributes[i], data( index( idx.row(), i ), Qt::EditRole ) );
}
return f;
}
void QgsAttributeTableModel::prefetchColumnData( int column )
{
mFieldCache.clear();
if ( column == -1 )
{
mCachedField = -1;
}
else
{
if ( column >= mAttributes.count() )
return;
int fieldId = mAttributes[ column ];
const QgsFields& fields = layer()->fields();
QStringList fldNames;
fldNames << fields[ fieldId ].name();
QgsFeatureRequest r( mFeatureRequest );
QgsFeatureIterator it = mLayerCache->getFeatures( r.setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( fldNames, fields ) );
QgsFeature f;
while ( it.nextFeature( f ) )
{
mFieldCache.insert( f.id(), f.attribute( fieldId ) );
}
mCachedField = fieldId;
}
}
void QgsAttributeTableModel::setRequest( const QgsFeatureRequest& request )
{
mFeatureRequest = request;
if ( layer() && !layer()->hasGeometryType() )
mFeatureRequest.setFlags( mFeatureRequest.flags() | QgsFeatureRequest::NoGeometry );
}
const QgsFeatureRequest &QgsAttributeTableModel::request() const
{
return mFeatureRequest;
}
|
dakcarto/QGIS
|
src/gui/attributetable/qgsattributetablemodel.cpp
|
C++
|
gpl-2.0
| 20,531
|
/* spglib.h version 1.5.1 */
/* Copyright (C) 2008 Atsushi Togo */
#ifndef __spglib_H__
#define __spglib_H__
/* SPGCONST is used instead of 'const' so to avoid gcc warning. */
/* However there should be better way than this way.... */
#ifndef SPGCONST
#define SPGCONST
#endif
/*
------------------------------------------------------------------
lattice: Lattice vectors (in Cartesian)
[ [ a_x, b_x, c_x ],
[ a_y, b_y, c_y ],
[ a_z, b_z, c_z ] ]
position: Atomic positions (in fractional coordinates)
[ [ x1_a, x1_b, x1_c ],
[ x2_a, x2_b, x2_c ],
[ x3_a, x3_b, x3_c ],
... ]
types: Atom types, i.e., species identified by number
[ type_1, type_2, type_3, ... ]
rotation: Rotation matricies of symmetry operations
each rotation is:
[ [ r_aa, r_ab, r_ac ],
[ r_ba, r_bb, r_bc ],
[ r_ca, r_cb, r_cc ] ]
translation: Translation vectors of symmetry operations
each translation is:
[ t_a, t_b, t_c ]
symprec: Tolerance of atomic positions (in fractional coordinate)
in finding symmetry operations
------------------------------------------------------------------
Definitio of the operation:
r : rotation 3x3 matrix
t : translation vector
x_new = r * x + t:
[ x_new_a ] [ r_aa, r_ab, r_ac ] [ x_a ] [ t_a ]
[ x_new_b ] = [ r_ba, r_bb, r_bc ] * [ x_b ] + [ t_b ]
[ x_new_c ] [ r_ca, r_cb, r_cc ] [ x_c ] [ t_c ]
------------------------------------------------------------------
*/
typedef struct {
int spacegroup_number;
int hall_number;
char international_symbol[11];
char hall_symbol[17];
double transformation_matrix[3][3]; /* bravais_lattice = T * original_lattice */
double origin_shift[3]; /* Origin shift in Bravais lattice */
int n_operations; /* Symmetry operations from database */
int (*rotations)[3][3];
double (*translations)[3];
int n_atoms;
int *wyckoffs; /* Wyckoff letters */
int *equivalent_atoms;
} SpglibDataset;
/* This is a copy from spg_database.h except for holohedry. */
typedef struct {
int number;
char schoenflies[7];
char hall_symbol[17];
char international[32];
char international_full[20];
char international_short[11];
} SpglibSpacegroupType;
SpglibDataset * spg_get_dataset(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
SpglibDataset * spgat_get_dataset(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
void spg_free_dataset(SpglibDataset *dataset);
/* Find symmetry operations. The operations are stored in */
/* ``rotatiion`` and ``translation``. The number of operations is */
/* return as the return value. Rotations and translations are */
/* given in fractional coordinates, and ``rotation[i]`` and */
/* ``translation[i]`` with same index give a symmetry oprations, */
/* i.e., these have to be used togather. */
int spg_get_symmetry(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
int spgat_get_symmetry(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Find symmetry operations with collinear spins on atoms. */
int spg_get_symmetry_with_collinear_spin(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const double spins[],
const int num_atom,
const double symprec);
int spgat_get_symmetry_with_collinear_spin(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const double spins[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Return exact number of symmetry operations. This function may */
/* be used in advance to allocate memoery space for symmetry */
/* operations. Only upper bound is required, */
/* ``spg_get_max_multiplicity`` can be used instead of this */
/* function and ``spg_get_max_multiplicity`` is faster than this */
/* function. */
int spg_get_multiplicity(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
int spgat_get_multiplicity(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Considering periodicity of crystal, one of the possible smallest */
/* lattice is searched. The lattice is stored in ``smallest_lattice``. */
int spg_get_smallest_lattice(double smallest_lattice[3][3],
SPGCONST double lattice[3][3],
const double symprec);
/* A primitive cell is found from an input cell. Be careful that */
/* ``lattice``, ``position``, and ``types`` are overwritten. */
/* ``num_atom`` is returned as return value. */
/* When any primitive cell is not found, 0 is returned. */
int spg_find_primitive(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec);
int spgat_find_primitive(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Space group is found in international table symbol (``symbol``) and */
/* number (return value). 0 is returned when it fails. */
int spg_get_international(char symbol[11],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
int spgat_get_international(char symbol[11],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Space group is found in schoenflies (``symbol``) and as number (return */
/* value). 0 is returned when it fails. */
int spg_get_schoenflies(char symbol[10],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
int spgat_get_schoenflies(char symbol[10],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Point group symbol is obtained from the rotation part of */
/* symmetry operations */
int spg_get_pointgroup(char symbol[6],
int trans_mat[3][3],
SPGCONST int rotations[][3][3],
const int num_rotations);
/* Space-group type information is accessed by index of hall symbol. */
/* The index is defined from 1 to 530. */
SpglibSpacegroupType spg_get_spacegroup_type(int hall_number);
/* Bravais lattice with internal atomic points are returned. */
/* The arrays are require to have 4 times larger memory space */
/* those of input cell. */
/* When bravais lattice could not be found, or could not be */
/* symmetrized, 0 is returned. */
int spg_refine_cell(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec);
int spgat_refine_cell(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec,
const double angle_tolerance);
/* Irreducible reciprocal grid points are searched from uniform */
/* mesh grid points specified by ``mesh`` and ``is_shift``. */
/* ``mesh`` stores three integers. Reciprocal primitive vectors */
/* are divided by the number stored in ``mesh`` with (0,0,0) point */
/* centering. The centering can be shifted only half of one mesh */
/* by setting 1 for each ``is_shift`` element. If 0 is set for */
/* ``is_shift``, it means there is no shift. This limitation of */
/* shifting enables the irreducible k-point search significantly */
/* faster when the mesh is very dense. */
/* The reducible uniform grid points are returned in reduced */
/* coordinates as ``grid_address``. A map between reducible and */
/* irreducible points are returned as ``map`` as in the indices of */
/* ``grid_address``. The number of the irreducible k-points are */
/* returned as the return value. The time reversal symmetry is */
/* imposed by setting ``is_time_reversal`` 1. */
int spg_get_ir_reciprocal_mesh(int grid_address[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
/* The irreducible k-points are searched from unique k-point mesh */
/* grids from real space lattice vectors and rotation matrices of */
/* symmetry operations in real space with stabilizers. The */
/* stabilizers are written in reduced coordinates. Number of the */
/* stabilizers are given by ``num_q``. Reduced k-points are stored */
/* in ``map`` as indices of ``grid_address``. The number of the */
/* reduced k-points with stabilizers are returned as the return */
/* value. */
int spg_get_stabilized_reciprocal_mesh(int grid_address[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const int num_q,
SPGCONST double qpoints[][3]);
/* Grid addresses are relocated inside Brillouin zone. */
/* Number of ir-grid-points inside Brillouin zone is returned. */
/* It is assumed that the following arrays have the shapes of */
/* bz_grid_address[prod(mesh + 1)][3] */
/* bz_map[prod(mesh * 2)] */
/* where grid_address[prod(mesh)][3]. */
/* Each element of grid_address is mapped to each element of */
/* bz_grid_address with keeping element order. bz_grid_address has */
/* larger memory space to represent BZ surface even if some points */
/* on a surface are translationally equivalent to the other points */
/* on the other surface. Those equivalent points are added successively */
/* as grid point numbers to bz_grid_address. Those added grid points */
/* are stored after the address of end point of grid_address, i.e. */
/* */
/* |-----------------array size of bz_grid_address---------------------| */
/* |--grid addresses similar to grid_address--|--newly added ones--|xxx| */
/* */
/* where xxx means the memory space that may not be used. Number of grid */
/* points stored in bz_grid_address is returned. */
/* bz_map is used to recover grid point index expanded to include BZ */
/* surface from grid address. The grid point indices are mapped to */
/* (mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map). */
int spg_relocate_BZ_grid_address(int bz_grid_address[][3],
int bz_map[],
SPGCONST int grid_address[][3],
const int mesh[3],
SPGCONST double rec_lattice[3][3],
const int is_shift[3]);
/* Irreducible triplets of k-points are searched under conservation of */
/* :math:``\mathbf{k}_1 + \mathbf{k}_2 + \mathbf{k}_3 = \mathbf{G}``. */
/* Memory spaces of grid_address[prod(mesh)][3], weights[prod(mesh)] */
/* and third_q[prod(mesh)] are required. rotations are point-group- */
/* operations in real space for which duplicate operations are allowed */
/* in the input. */
int spg_get_triplets_reciprocal_mesh_at_q(int weights[],
int grid_address[][3],
int third_q[],
const int grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3]);
/* Irreducible grid-point-triplets in BZ are stored. */
/* triplets are recovered from grid_point and triplet_weights. */
/* BZ boundary is considered in this recovery. Therefore grid addresses */
/* are given not by grid_address, but by bz_grid_address. */
/* triplets[num_ir_triplets][3] = number of non-zero triplets weights*/
/* Number of ir-triplets is returned. */
int spg_get_BZ_triplets_at_q(int triplets[][3],
const int grid_point,
SPGCONST int bz_grid_address[][3],
const int bz_map[],
const int triplet_weights[],
const int mesh[3]);
void spg_get_neighboring_grid_points(int relative_grid_points[],
const int grid_point,
SPGCONST int relative_grid_address[][3],
const int num_relative_grid_address,
const int mesh[3],
SPGCONST int bz_grid_address[][3],
const int bz_map[]);
void
spg_get_tetrahedra_relative_grid_address(int relative_grid_address[24][4][3],
SPGCONST double rec_lattice[3][3]);
double
spg_get_tetrahedra_integration_weight(const double omega,
SPGCONST double tetrahedra_omegas[24][4],
const char function);
void
spg_get_tetrahedra_integration_weight_at_omegas
(double integration_weights[],
const int num_omegas,
const double omegas[],
SPGCONST double tetrahedra_omegas[24][4],
const char function);
#endif
|
psavery/avogadro
|
libavogadro/src/extensions/crystallography/spglib/spglib.h
|
C
|
gpl-2.0
| 13,786
|
/*****************************************************************************\
* $Id: php_genders.h,v 1.4 2010-02-02 00:04:34 chu11 Exp $
*****************************************************************************
* Copyright (C) 2007-2019 Lawrence Livermore National Security, LLC.
* Copyright (C) 2001-2007 The Regents of the University of California.
* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
* Written by Jim Garlick <garlick@llnl.gov> and Albert Chu <chu11@llnl.gov>.
* UCRL-CODE-2003-004.
*
* This file is part of Genders, a cluster configuration database.
* For details, see <http://www.llnl.gov/linux/genders/>.
*
* Genders 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.
*
* Genders 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 Genders. If not, see <http://www.gnu.org/licenses/>.
\*****************************************************************************/
#ifndef PHP_GENDERS_H
#define PHP_GENDERS_H
extern zend_module_entry genders_module_entry;
#define phpext_genders_ptr &genders_module_entry
#ifdef PHP_WIN32
#define PHP_GENDERS_API __declspec(dllexport)
#else
#define PHP_GENDERS_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
PHP_MINIT_FUNCTION(genders);
PHP_MSHUTDOWN_FUNCTION(genders);
PHP_RINIT_FUNCTION(genders);
PHP_RSHUTDOWN_FUNCTION(genders);
PHP_MINFO_FUNCTION(genders);
PHP_FUNCTION(genders_getnumattrs);
PHP_FUNCTION(genders_getattr);
PHP_FUNCTION(genders_getattr_all);
PHP_FUNCTION(genders_getnodes);
#ifdef ZTS
#define GENDERS_G(v) TSRMG(genders_globals_id, zend_genders_globals *, v)
#else
#define GENDERS_G(v) (genders_globals.v)
#endif
#endif
|
chaos/genders
|
contrib/php/php_genders.h
|
C
|
gpl-2.0
| 2,110
|
/*
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.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 "BattlegroundEY.h"
#include "WorldPacket.h"
#include "BattlegroundMgr.h"
#include "Creature.h"
#include "Language.h"
#include "Player.h"
#include "Util.h"
#include "ObjectAccessor.h"
// these variables aren't used outside of this file, so declare them only here
uint32 BG_EY_HonorScoreTicks[BG_HONOR_MODE_NUM] =
{
260, // normal honor
160 // holiday
};
BattlegroundEY::BattlegroundEY()
{
m_BuffChange = true;
BgObjects.resize(BG_EY_OBJECT_MAX);
BgCreatures.resize(BG_EY_CREATURES_MAX);
m_Points_Trigger[FEL_REAVER] = TR_FEL_REAVER_BUFF;
m_Points_Trigger[BLOOD_ELF] = TR_BLOOD_ELF_BUFF;
m_Points_Trigger[DRAENEI_RUINS] = TR_DRAENEI_RUINS_BUFF;
m_Points_Trigger[MAGE_TOWER] = TR_MAGE_TOWER_BUFF;
m_HonorScoreTics[TEAM_ALLIANCE] = 0;
m_HonorScoreTics[TEAM_HORDE] = 0;
m_TeamPointsCount[TEAM_ALLIANCE] = 0;
m_TeamPointsCount[TEAM_HORDE] = 0;
m_FlagKeeper.Clear();
m_DroppedFlagGUID.Clear();
m_FlagCapturedBgObjectType = 0;
m_FlagState = BG_EY_FLAG_STATE_ON_BASE;
m_FlagsTimer = 0;
m_TowerCapCheckTimer = 0;
m_PointAddingTimer = 0;
m_HonorTics = 0;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
m_PointOwnedByTeam[i] = EY_POINT_NO_OWNER;
m_PointState[i] = EY_POINT_STATE_UNCONTROLLED;
m_PointBarStatus[i] = BG_EY_PROGRESS_BAR_STATE_MIDDLE;
}
for (uint8 i = 0; i < 2 * EY_POINTS_MAX; ++i)
m_CurrentPointPlayersCount[i] = 0;
StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_BG_EY_START_TWO_MINUTES;
StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_BG_EY_START_ONE_MINUTE;
StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_BG_EY_START_HALF_MINUTE;
StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_BG_EY_HAS_BEGUN;
}
BattlegroundEY::~BattlegroundEY() { }
void BattlegroundEY::PostUpdateImpl(uint32 diff)
{
if (GetStatus() == STATUS_IN_PROGRESS)
{
m_PointAddingTimer -= diff;
if (m_PointAddingTimer <= 0)
{
m_PointAddingTimer = BG_EY_FPOINTS_TICK_TIME;
if (m_TeamPointsCount[TEAM_ALLIANCE] > 0)
AddPoints(ALLIANCE, BG_EY_TickPoints[m_TeamPointsCount[TEAM_ALLIANCE] - 1]);
if (m_TeamPointsCount[TEAM_HORDE] > 0)
AddPoints(HORDE, BG_EY_TickPoints[m_TeamPointsCount[TEAM_HORDE] - 1]);
}
if (m_FlagState == BG_EY_FLAG_STATE_WAIT_RESPAWN || m_FlagState == BG_EY_FLAG_STATE_ON_GROUND)
{
m_FlagsTimer -= diff;
if (m_FlagsTimer < 0)
{
m_FlagsTimer = 0;
if (m_FlagState == BG_EY_FLAG_STATE_WAIT_RESPAWN)
RespawnFlag(true);
else
RespawnFlagAfterDrop();
}
}
m_TowerCapCheckTimer -= diff;
if (m_TowerCapCheckTimer <= 0)
{
//check if player joined point
/*I used this order of calls, because although we will check if one player is in gameobject's distance 2 times
but we can count of players on current point in CheckSomeoneLeftPoint
*/
this->CheckSomeoneJoinedPoint();
//check if player left point
this->CheckSomeoneLeftPoint();
this->UpdatePointStatuses();
m_TowerCapCheckTimer = BG_EY_FPOINTS_TICK_TIME;
}
}
}
void BattlegroundEY::StartingEventCloseDoors()
{
SpawnBGObject(BG_EY_OBJECT_DOOR_A, RESPAWN_IMMEDIATELY);
SpawnBGObject(BG_EY_OBJECT_DOOR_H, RESPAWN_IMMEDIATELY);
for (uint32 i = BG_EY_OBJECT_A_BANNER_FEL_REAVER_CENTER; i < BG_EY_OBJECT_MAX; ++i)
SpawnBGObject(i, RESPAWN_ONE_DAY);
}
void BattlegroundEY::StartingEventOpenDoors()
{
SpawnBGObject(BG_EY_OBJECT_DOOR_A, RESPAWN_ONE_DAY);
SpawnBGObject(BG_EY_OBJECT_DOOR_H, RESPAWN_ONE_DAY);
for (uint32 i = BG_EY_OBJECT_N_BANNER_FEL_REAVER_CENTER; i <= BG_EY_OBJECT_FLAG_NETHERSTORM; ++i)
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
for (uint32 i = 0; i < EY_POINTS_MAX; ++i)
{
//randomly spawn buff
uint8 buff = urand(0, 2);
SpawnBGObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + buff + i * 3, RESPAWN_IMMEDIATELY);
}
// Achievement: Flurry
StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, BG_EY_EVENT_START_BATTLE);
}
void BattlegroundEY::AddPoints(uint32 Team, uint32 Points)
{
TeamId team_index = GetTeamIndexByTeamId(Team);
m_TeamScores[team_index] += Points;
m_HonorScoreTics[team_index] += Points;
if (m_HonorScoreTics[team_index] >= m_HonorTics)
{
RewardHonorToTeam(GetBonusHonorFromKill(1), Team);
m_HonorScoreTics[team_index] -= m_HonorTics;
}
UpdateTeamScore(team_index);
}
void BattlegroundEY::CheckSomeoneJoinedPoint()
{
GameObject* obj = NULL;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
obj = GetBgMap()->GetGameObject(BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]);
if (obj)
{
uint8 j = 0;
while (j < m_PlayersNearPoint[EY_POINTS_MAX].size())
{
Player* player = ObjectAccessor::FindPlayer(m_PlayersNearPoint[EY_POINTS_MAX][j]);
if (!player)
{
TC_LOG_ERROR("bg.battleground", "BattlegroundEY:CheckSomeoneJoinedPoint: Player (%s) not found!", m_PlayersNearPoint[EY_POINTS_MAX][j].ToString().c_str());
++j;
continue;
}
if (player->CanCaptureTowerPoint() && player->IsWithinDistInMap(obj, BG_EY_POINT_RADIUS))
{
//player joined point!
//show progress bar
UpdateWorldStateForPlayer(PROGRESS_BAR_PERCENT_GREY, BG_EY_PROGRESS_BAR_PERCENT_GREY, player);
UpdateWorldStateForPlayer(PROGRESS_BAR_STATUS, m_PointBarStatus[i], player);
UpdateWorldStateForPlayer(PROGRESS_BAR_SHOW, BG_EY_PROGRESS_BAR_SHOW, player);
//add player to point
m_PlayersNearPoint[i].push_back(m_PlayersNearPoint[EY_POINTS_MAX][j]);
//remove player from "free space"
m_PlayersNearPoint[EY_POINTS_MAX].erase(m_PlayersNearPoint[EY_POINTS_MAX].begin() + j);
}
else
++j;
}
}
}
}
void BattlegroundEY::CheckSomeoneLeftPoint()
{
//reset current point counts
for (uint8 i = 0; i < 2*EY_POINTS_MAX; ++i)
m_CurrentPointPlayersCount[i] = 0;
GameObject* obj = NULL;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
obj = GetBgMap()->GetGameObject(BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]);
if (obj)
{
uint8 j = 0;
while (j < m_PlayersNearPoint[i].size())
{
Player* player = ObjectAccessor::FindPlayer(m_PlayersNearPoint[i][j]);
if (!player)
{
TC_LOG_ERROR("bg.battleground", "BattlegroundEY:CheckSomeoneLeftPoint Player (%s) not found!", m_PlayersNearPoint[i][j].ToString().c_str());
//move not existed player to "free space" - this will cause many error showing in log, but it is a very important bug
m_PlayersNearPoint[EY_POINTS_MAX].push_back(m_PlayersNearPoint[i][j]);
m_PlayersNearPoint[i].erase(m_PlayersNearPoint[i].begin() + j);
continue;
}
if (!player->CanCaptureTowerPoint() || !player->IsWithinDistInMap(obj, BG_EY_POINT_RADIUS))
//move player out of point (add him to players that are out of points
{
m_PlayersNearPoint[EY_POINTS_MAX].push_back(m_PlayersNearPoint[i][j]);
m_PlayersNearPoint[i].erase(m_PlayersNearPoint[i].begin() + j);
this->UpdateWorldStateForPlayer(PROGRESS_BAR_SHOW, BG_EY_PROGRESS_BAR_DONT_SHOW, player);
}
else
{
//player is neat flag, so update count:
m_CurrentPointPlayersCount[2 * i + GetTeamIndexByTeamId(player->GetTeam())]++;
++j;
}
}
}
}
}
void BattlegroundEY::UpdatePointStatuses()
{
for (uint8 point = 0; point < EY_POINTS_MAX; ++point)
{
if (m_PlayersNearPoint[point].empty())
continue;
//count new point bar status:
m_PointBarStatus[point] += (m_CurrentPointPlayersCount[2 * point] - m_CurrentPointPlayersCount[2 * point + 1] < BG_EY_POINT_MAX_CAPTURERS_COUNT) ? m_CurrentPointPlayersCount[2 * point] - m_CurrentPointPlayersCount[2 * point + 1] : BG_EY_POINT_MAX_CAPTURERS_COUNT;
if (m_PointBarStatus[point] > BG_EY_PROGRESS_BAR_ALI_CONTROLLED)
//point is fully alliance's
m_PointBarStatus[point] = BG_EY_PROGRESS_BAR_ALI_CONTROLLED;
if (m_PointBarStatus[point] < BG_EY_PROGRESS_BAR_HORDE_CONTROLLED)
//point is fully horde's
m_PointBarStatus[point] = BG_EY_PROGRESS_BAR_HORDE_CONTROLLED;
uint32 pointOwnerTeamId = 0;
//find which team should own this point
if (m_PointBarStatus[point] <= BG_EY_PROGRESS_BAR_NEUTRAL_LOW)
pointOwnerTeamId = HORDE;
else if (m_PointBarStatus[point] >= BG_EY_PROGRESS_BAR_NEUTRAL_HIGH)
pointOwnerTeamId = ALLIANCE;
else
pointOwnerTeamId = EY_POINT_NO_OWNER;
for (uint8 i = 0; i < m_PlayersNearPoint[point].size(); ++i)
{
Player* player = ObjectAccessor::FindPlayer(m_PlayersNearPoint[point][i]);
if (player)
{
this->UpdateWorldStateForPlayer(PROGRESS_BAR_STATUS, m_PointBarStatus[point], player);
//if point owner changed we must evoke event!
if (pointOwnerTeamId != m_PointOwnedByTeam[point])
{
//point was uncontrolled and player is from team which captured point
if (m_PointState[point] == EY_POINT_STATE_UNCONTROLLED && player->GetTeam() == pointOwnerTeamId)
this->EventTeamCapturedPoint(player, point);
//point was under control and player isn't from team which controlled it
if (m_PointState[point] == EY_POINT_UNDER_CONTROL && player->GetTeam() != m_PointOwnedByTeam[point])
this->EventTeamLostPoint(player, point);
}
/// @workaround The original AreaTrigger is covered by a bigger one and not triggered on client side.
if (point == FEL_REAVER && m_PointOwnedByTeam[point] == player->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == player->GetGUID())
if (player->GetDistance(2044.0f, 1729.729f, 1190.03f) < 3.0f)
EventPlayerCapturedFlag(player, BG_EY_OBJECT_FLAG_FEL_REAVER);
}
}
}
}
void BattlegroundEY::UpdateTeamScore(uint32 Team)
{
uint32 score = GetTeamScore(Team);
/// @todo there should be some sound played when one team is near victory!! - and define variables
/*if (!m_IsInformedNearVictory && score >= BG_EY_WARNING_NEAR_VICTORY_SCORE)
{
if (Team == ALLIANCE)
SendMessageToAll(LANG_BG_EY_A_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL);
else
SendMessageToAll(LANG_BG_EY_H_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL);
PlaySoundToAll(BG_EY_SOUND_NEAR_VICTORY);
m_IsInformedNearVictory = true;
}*/
if (score >= BG_EY_MAX_TEAM_SCORE)
{
score = BG_EY_MAX_TEAM_SCORE;
if (Team == TEAM_ALLIANCE)
EndBattleground(ALLIANCE);
else
EndBattleground(HORDE);
}
if (Team == TEAM_ALLIANCE)
UpdateWorldState(EY_ALLIANCE_RESOURCES, score);
else
UpdateWorldState(EY_HORDE_RESOURCES, score);
}
void BattlegroundEY::EndBattleground(uint32 winner)
{
// Win reward
if (winner == ALLIANCE)
RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE);
if (winner == HORDE)
RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE);
// Complete map reward
RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE);
RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE);
Battleground::EndBattleground(winner);
}
void BattlegroundEY::UpdatePointsCount(uint32 Team)
{
if (Team == ALLIANCE)
UpdateWorldState(EY_ALLIANCE_BASE, m_TeamPointsCount[TEAM_ALLIANCE]);
else
UpdateWorldState(EY_HORDE_BASE, m_TeamPointsCount[TEAM_HORDE]);
}
void BattlegroundEY::UpdatePointsIcons(uint32 Team, uint32 Point)
{
//we MUST firstly send 0, after that we can send 1!!!
if (m_PointState[Point] == EY_POINT_UNDER_CONTROL)
{
UpdateWorldState(m_PointsIconStruct[Point].WorldStateControlIndex, 0);
if (Team == ALLIANCE)
UpdateWorldState(m_PointsIconStruct[Point].WorldStateAllianceControlledIndex, 1);
else
UpdateWorldState(m_PointsIconStruct[Point].WorldStateHordeControlledIndex, 1);
}
else
{
if (Team == ALLIANCE)
UpdateWorldState(m_PointsIconStruct[Point].WorldStateAllianceControlledIndex, 0);
else
UpdateWorldState(m_PointsIconStruct[Point].WorldStateHordeControlledIndex, 0);
UpdateWorldState(m_PointsIconStruct[Point].WorldStateControlIndex, 1);
}
}
void BattlegroundEY::AddPlayer(Player* player)
{
Battleground::AddPlayer(player);
PlayerScores[player->GetGUID().GetCounter()] = new BattlegroundEYScore(player->GetGUID());
m_PlayersNearPoint[EY_POINTS_MAX].push_back(player->GetGUID());
}
void BattlegroundEY::RemovePlayer(Player* player, ObjectGuid guid, uint32 /*team*/)
{
// sometimes flag aura not removed :(
for (int j = EY_POINTS_MAX; j >= 0; --j)
{
for (size_t i = 0; i < m_PlayersNearPoint[j].size(); ++i)
if (m_PlayersNearPoint[j][i] == guid)
m_PlayersNearPoint[j].erase(m_PlayersNearPoint[j].begin() + i);
}
if (IsFlagPickedup())
{
if (m_FlagKeeper == guid)
{
if (player)
EventPlayerDroppedFlag(player);
else
{
SetFlagPicker(ObjectGuid::Empty);
RespawnFlag(true);
}
}
}
}
void BattlegroundEY::HandleAreaTrigger(Player* player, uint32 trigger)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
if (!player->IsAlive()) //hack code, must be removed later
return;
switch (trigger)
{
case TR_BLOOD_ELF_POINT:
if (m_PointState[BLOOD_ELF] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[BLOOD_ELF] == player->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == player->GetGUID())
EventPlayerCapturedFlag(player, BG_EY_OBJECT_FLAG_BLOOD_ELF);
break;
case TR_FEL_REAVER_POINT:
if (m_PointState[FEL_REAVER] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[FEL_REAVER] == player->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == player->GetGUID())
EventPlayerCapturedFlag(player, BG_EY_OBJECT_FLAG_FEL_REAVER);
break;
case TR_MAGE_TOWER_POINT:
if (m_PointState[MAGE_TOWER] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[MAGE_TOWER] == player->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == player->GetGUID())
EventPlayerCapturedFlag(player, BG_EY_OBJECT_FLAG_MAGE_TOWER);
break;
case TR_DRAENEI_RUINS_POINT:
if (m_PointState[DRAENEI_RUINS] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[DRAENEI_RUINS] == player->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == player->GetGUID())
EventPlayerCapturedFlag(player, BG_EY_OBJECT_FLAG_DRAENEI_RUINS);
break;
case 4512:
case 4515:
case 4517:
case 4519:
case 4530:
case 4531:
case 4568:
case 4569:
case 4570:
case 4571:
case 5866:
break;
default:
Battleground::HandleAreaTrigger(player, trigger);
break;
}
}
bool BattlegroundEY::SetupBattleground()
{
// doors
if (!AddObject(BG_EY_OBJECT_DOOR_A, BG_OBJECT_A_DOOR_EY_ENTRY, 2527.6f, 1596.91f, 1262.13f, -3.12414f, -0.173642f, -0.001515f, 0.98477f, -0.008594f, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_EY_OBJECT_DOOR_H, BG_OBJECT_H_DOOR_EY_ENTRY, 1803.21f, 1539.49f, 1261.09f, 3.14159f, 0.173648f, 0, 0.984808f, 0, RESPAWN_IMMEDIATELY)
// banners (alliance)
|| !AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_BLOOD_ELF_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2047.19f, 1349.19f, 1189.0f, -1.62316f, 0, 0, 0.725374f, -0.688354f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_BLOOD_ELF_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2074.32f, 1385.78f, 1194.72f, 0.488692f, 0, 0, 0.241922f, 0.970296f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_BLOOD_ELF_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2025.13f, 1386.12f, 1192.74f, 2.3911f, 0, 0, 0.930418f, 0.366501f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_DRAENEI_RUINS_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2276.8f, 1400.41f, 1196.33f, 2.44346f, 0, 0, 0.939693f, 0.34202f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_DRAENEI_RUINS_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2305.78f, 1404.56f, 1199.38f, 1.74533f, 0, 0, 0.766044f, 0.642788f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_DRAENEI_RUINS_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2245.4f, 1366.41f, 1195.28f, 2.21657f, 0, 0, 0.894934f, 0.446198f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY)
// banners (horde)
|| !AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_BLOOD_ELF_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2047.19f, 1349.19f, 1189.0f, -1.62316f, 0, 0, 0.725374f, -0.688354f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_BLOOD_ELF_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2074.32f, 1385.78f, 1194.72f, 0.488692f, 0, 0, 0.241922f, 0.970296f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_BLOOD_ELF_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2025.13f, 1386.12f, 1192.74f, 2.3911f, 0, 0, 0.930418f, 0.366501f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_DRAENEI_RUINS_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2276.8f, 1400.41f, 1196.33f, 2.44346f, 0, 0, 0.939693f, 0.34202f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_DRAENEI_RUINS_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2305.78f, 1404.56f, 1199.38f, 1.74533f, 0, 0, 0.766044f, 0.642788f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_DRAENEI_RUINS_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2245.4f, 1366.41f, 1195.28f, 2.21657f, 0, 0, 0.894934f, 0.446198f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY)
// banners (natural)
|| !AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_BLOOD_ELF_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2047.19f, 1349.19f, 1189.0f, -1.62316f, 0, 0, 0.725374f, -0.688354f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_BLOOD_ELF_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2074.32f, 1385.78f, 1194.72f, 0.488692f, 0, 0, 0.241922f, 0.970296f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_BLOOD_ELF_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2025.13f, 1386.12f, 1192.74f, 2.3911f, 0, 0, 0.930418f, 0.366501f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_DRAENEI_RUINS_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2276.8f, 1400.41f, 1196.33f, 2.44346f, 0, 0, 0.939693f, 0.34202f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_DRAENEI_RUINS_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2305.78f, 1404.56f, 1199.38f, 1.74533f, 0, 0, 0.766044f, 0.642788f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_DRAENEI_RUINS_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2245.4f, 1366.41f, 1195.28f, 2.21657f, 0, 0, 0.894934f, 0.446198f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY)
// flags
|| !AddObject(BG_EY_OBJECT_FLAG_NETHERSTORM, BG_OBJECT_FLAG2_EY_ENTRY, 2174.782227f, 1569.054688f, 1160.361938f, -1.448624f, 0, 0, 0.662620f, -0.748956f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_FEL_REAVER, BG_OBJECT_FLAG1_EY_ENTRY, 2044.28f, 1729.68f, 1189.96f, -0.017453f, 0, 0, 0.008727f, -0.999962f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_BLOOD_ELF, BG_OBJECT_FLAG1_EY_ENTRY, 2048.83f, 1393.65f, 1194.49f, 0.20944f, 0, 0, 0.104528f, 0.994522f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_DRAENEI_RUINS, BG_OBJECT_FLAG1_EY_ENTRY, 2286.56f, 1402.36f, 1197.11f, 3.72381f, 0, 0, 0.957926f, -0.287016f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_MAGE_TOWER, BG_OBJECT_FLAG1_EY_ENTRY, 2284.48f, 1731.23f, 1189.99f, 2.89725f, 0, 0, 0.992546f, 0.121869f, RESPAWN_ONE_DAY)
// tower cap
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_FEL_REAVER, BG_OBJECT_FR_TOWER_CAP_EY_ENTRY, 2024.600708f, 1742.819580f, 1195.157715f, 2.443461f, 0, 0, 0.939693f, 0.342020f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_BLOOD_ELF, BG_OBJECT_BE_TOWER_CAP_EY_ENTRY, 2050.493164f, 1372.235962f, 1194.563477f, 1.710423f, 0, 0, 0.754710f, 0.656059f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_DRAENEI_RUINS, BG_OBJECT_DR_TOWER_CAP_EY_ENTRY, 2301.010498f, 1386.931641f, 1197.183472f, 1.570796f, 0, 0, 0.707107f, 0.707107f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_MAGE_TOWER, BG_OBJECT_HU_TOWER_CAP_EY_ENTRY, 2282.121582f, 1760.006958f, 1189.707153f, 1.919862f, 0, 0, 0.819152f, 0.573576f, RESPAWN_ONE_DAY)
)
{
TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn some object Battleground not created!");
return false;
}
//buffs
for (int i = 0; i < EY_POINTS_MAX; ++i)
{
AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(m_Points_Trigger[i]);
if (!at)
{
TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Unknown trigger: %u", m_Points_Trigger[i]);
continue;
}
if (!AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3, Buff_Entries[0], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + 1, Buff_Entries[1], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + 2, Buff_Entries[2], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY)
)
TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Cannot spawn buff");
}
WorldSafeLocsEntry const* sg = NULL;
sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_ALLIANCE);
if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_ALLIANCE, sg->x, sg->y, sg->z, 3.124139f, TEAM_ALLIANCE))
{
TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guide! Battleground not created!");
return false;
}
sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_HORDE);
if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_HORDE, sg->x, sg->y, sg->z, 3.193953f, TEAM_HORDE))
{
TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guide! Battleground not created!");
return false;
}
return true;
}
void BattlegroundEY::Reset()
{
//call parent's class reset
Battleground::Reset();
m_TeamScores[TEAM_ALLIANCE] = 0;
m_TeamScores[TEAM_HORDE] = 0;
m_TeamPointsCount[TEAM_ALLIANCE] = 0;
m_TeamPointsCount[TEAM_HORDE] = 0;
m_HonorScoreTics[TEAM_ALLIANCE] = 0;
m_HonorScoreTics[TEAM_HORDE] = 0;
m_FlagState = BG_EY_FLAG_STATE_ON_BASE;
m_FlagCapturedBgObjectType = 0;
m_FlagKeeper.Clear();
m_DroppedFlagGUID.Clear();
m_PointAddingTimer = 0;
m_TowerCapCheckTimer = 0;
bool isBGWeekend = sBattlegroundMgr->IsBGWeekend(GetTypeID());
m_HonorTics = (isBGWeekend) ? BG_EY_EYWeekendHonorTicks : BG_EY_NotEYWeekendHonorTicks;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
m_PointOwnedByTeam[i] = EY_POINT_NO_OWNER;
m_PointState[i] = EY_POINT_STATE_UNCONTROLLED;
m_PointBarStatus[i] = BG_EY_PROGRESS_BAR_STATE_MIDDLE;
m_PlayersNearPoint[i].clear();
m_PlayersNearPoint[i].reserve(15); //tip size
}
m_PlayersNearPoint[EY_PLAYERS_OUT_OF_POINTS].clear();
m_PlayersNearPoint[EY_PLAYERS_OUT_OF_POINTS].reserve(30);
}
void BattlegroundEY::RespawnFlag(bool send_message)
{
if (m_FlagCapturedBgObjectType > 0)
SpawnBGObject(m_FlagCapturedBgObjectType, RESPAWN_ONE_DAY);
m_FlagCapturedBgObjectType = 0;
m_FlagState = BG_EY_FLAG_STATE_ON_BASE;
SpawnBGObject(BG_EY_OBJECT_FLAG_NETHERSTORM, RESPAWN_IMMEDIATELY);
if (send_message)
{
SendMessageToAll(LANG_BG_EY_RESETED_FLAG, CHAT_MSG_BG_SYSTEM_NEUTRAL);
PlaySoundToAll(BG_EY_SOUND_FLAG_RESET); // flags respawned sound...
}
UpdateWorldState(NETHERSTORM_FLAG, 1);
}
void BattlegroundEY::RespawnFlagAfterDrop()
{
RespawnFlag(true);
GameObject* obj = GetBgMap()->GetGameObject(GetDroppedFlagGUID());
if (obj)
obj->Delete();
else
TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Unknown dropped flag (%s)", GetDroppedFlagGUID().ToString().c_str());
SetDroppedFlagGUID(ObjectGuid::Empty);
}
void BattlegroundEY::HandleKillPlayer(Player* player, Player* killer)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
Battleground::HandleKillPlayer(player, killer);
EventPlayerDroppedFlag(player);
}
void BattlegroundEY::EventPlayerDroppedFlag(Player* player)
{
if (GetStatus() != STATUS_IN_PROGRESS)
{
// if not running, do not cast things at the dropper player, neither send unnecessary messages
// just take off the aura
if (IsFlagPickedup() && GetFlagPickerGUID() == player->GetGUID())
{
SetFlagPicker(ObjectGuid::Empty);
player->RemoveAurasDueToSpell(BG_EY_NETHERSTORM_FLAG_SPELL);
}
return;
}
if (!IsFlagPickedup())
return;
if (GetFlagPickerGUID() != player->GetGUID())
return;
SetFlagPicker(ObjectGuid::Empty);
player->RemoveAurasDueToSpell(BG_EY_NETHERSTORM_FLAG_SPELL);
m_FlagState = BG_EY_FLAG_STATE_ON_GROUND;
m_FlagsTimer = BG_EY_FLAG_RESPAWN_TIME;
player->CastSpell(player, SPELL_RECENTLY_DROPPED_FLAG, true);
player->CastSpell(player, BG_EY_PLAYER_DROPPED_FLAG_SPELL, true);
//this does not work correctly :((it should remove flag carrier name)
UpdateWorldState(NETHERSTORM_FLAG_STATE_HORDE, BG_EY_FLAG_STATE_WAIT_RESPAWN);
UpdateWorldState(NETHERSTORM_FLAG_STATE_ALLIANCE, BG_EY_FLAG_STATE_WAIT_RESPAWN);
if (player->GetTeam() == ALLIANCE)
SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL);
else
SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL);
}
void BattlegroundEY::EventPlayerClickedOnFlag(Player* player, GameObject* target_obj)
{
if (GetStatus() != STATUS_IN_PROGRESS || IsFlagPickedup() || !player->IsWithinDistInMap(target_obj, 10))
return;
if (player->GetTeam() == ALLIANCE)
{
UpdateWorldState(NETHERSTORM_FLAG_STATE_ALLIANCE, BG_EY_FLAG_STATE_ON_PLAYER);
PlaySoundToAll(BG_EY_SOUND_FLAG_PICKED_UP_ALLIANCE);
}
else
{
UpdateWorldState(NETHERSTORM_FLAG_STATE_HORDE, BG_EY_FLAG_STATE_ON_PLAYER);
PlaySoundToAll(BG_EY_SOUND_FLAG_PICKED_UP_HORDE);
}
if (m_FlagState == BG_EY_FLAG_STATE_ON_BASE)
UpdateWorldState(NETHERSTORM_FLAG, 0);
m_FlagState = BG_EY_FLAG_STATE_ON_PLAYER;
SpawnBGObject(BG_EY_OBJECT_FLAG_NETHERSTORM, RESPAWN_ONE_DAY);
SetFlagPicker(player->GetGUID());
//get flag aura on player
player->CastSpell(player, BG_EY_NETHERSTORM_FLAG_SPELL, true);
player->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
if (player->GetTeam() == ALLIANCE)
PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, player->GetName().c_str());
else
PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL, player->GetName().c_str());
}
void BattlegroundEY::EventTeamLostPoint(Player* player, uint32 Point)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
//Natural point
uint32 Team = m_PointOwnedByTeam[Point];
if (!Team)
return;
if (Team == ALLIANCE)
{
m_TeamPointsCount[TEAM_ALLIANCE]--;
SpawnBGObject(m_LosingPointTypes[Point].DespawnObjectTypeAlliance, RESPAWN_ONE_DAY);
SpawnBGObject(m_LosingPointTypes[Point].DespawnObjectTypeAlliance + 1, RESPAWN_ONE_DAY);
SpawnBGObject(m_LosingPointTypes[Point].DespawnObjectTypeAlliance + 2, RESPAWN_ONE_DAY);
}
else
{
m_TeamPointsCount[TEAM_HORDE]--;
SpawnBGObject(m_LosingPointTypes[Point].DespawnObjectTypeHorde, RESPAWN_ONE_DAY);
SpawnBGObject(m_LosingPointTypes[Point].DespawnObjectTypeHorde + 1, RESPAWN_ONE_DAY);
SpawnBGObject(m_LosingPointTypes[Point].DespawnObjectTypeHorde + 2, RESPAWN_ONE_DAY);
}
SpawnBGObject(m_LosingPointTypes[Point].SpawnNeutralObjectType, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_LosingPointTypes[Point].SpawnNeutralObjectType + 1, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_LosingPointTypes[Point].SpawnNeutralObjectType + 2, RESPAWN_IMMEDIATELY);
//buff isn't despawned
m_PointOwnedByTeam[Point] = EY_POINT_NO_OWNER;
m_PointState[Point] = EY_POINT_NO_OWNER;
if (Team == ALLIANCE)
SendMessageToAll(m_LosingPointTypes[Point].MessageIdAlliance, CHAT_MSG_BG_SYSTEM_ALLIANCE, player);
else
SendMessageToAll(m_LosingPointTypes[Point].MessageIdHorde, CHAT_MSG_BG_SYSTEM_HORDE, player);
UpdatePointsIcons(Team, Point);
UpdatePointsCount(Team);
//remove bonus honor aura trigger creature when node is lost
if (Point < EY_POINTS_MAX)
DelCreature(Point + 6);//NULL checks are in DelCreature! 0-5 spirit guides
}
void BattlegroundEY::EventTeamCapturedPoint(Player* player, uint32 Point)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
uint32 Team = player->GetTeam();
SpawnBGObject(m_CapturingPointTypes[Point].DespawnNeutralObjectType, RESPAWN_ONE_DAY);
SpawnBGObject(m_CapturingPointTypes[Point].DespawnNeutralObjectType + 1, RESPAWN_ONE_DAY);
SpawnBGObject(m_CapturingPointTypes[Point].DespawnNeutralObjectType + 2, RESPAWN_ONE_DAY);
if (Team == ALLIANCE)
{
m_TeamPointsCount[TEAM_ALLIANCE]++;
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeAlliance, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeAlliance + 1, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeAlliance + 2, RESPAWN_IMMEDIATELY);
}
else
{
m_TeamPointsCount[TEAM_HORDE]++;
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeHorde, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeHorde + 1, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeHorde + 2, RESPAWN_IMMEDIATELY);
}
//buff isn't respawned
m_PointOwnedByTeam[Point] = Team;
m_PointState[Point] = EY_POINT_UNDER_CONTROL;
if (Team == ALLIANCE)
SendMessageToAll(m_CapturingPointTypes[Point].MessageIdAlliance, CHAT_MSG_BG_SYSTEM_ALLIANCE, player);
else
SendMessageToAll(m_CapturingPointTypes[Point].MessageIdHorde, CHAT_MSG_BG_SYSTEM_HORDE, player);
if (BgCreatures[Point])
DelCreature(Point);
WorldSafeLocsEntry const* sg = NULL;
sg = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[Point].GraveYardId);
if (!sg || !AddSpiritGuide(Point, sg->x, sg->y, sg->z, 3.124139f, GetTeamIndexByTeamId(Team)))
TC_LOG_ERROR("bg.battleground", "BatteGroundEY: Failed to spawn spirit guide! point: %u, team: %u, graveyard_id: %u",
Point, Team, m_CapturingPointTypes[Point].GraveYardId);
// SpawnBGCreature(Point, RESPAWN_IMMEDIATELY);
UpdatePointsIcons(Team, Point);
UpdatePointsCount(Team);
if (Point >= EY_POINTS_MAX)
return;
Creature* trigger = GetBGCreature(Point + 6, false);//0-5 spirit guides
if (!trigger)
trigger = AddCreature(WORLD_TRIGGER, Point+6, BG_EY_TriggerPositions[Point], GetTeamIndexByTeamId(Team));
//add bonus honor aura trigger creature when node is accupied
//cast bonus aura (+50% honor in 25yards)
//aura should only apply to players who have accupied the node, set correct faction for trigger
if (trigger)
{
trigger->setFaction(Team == ALLIANCE ? 84 : 83);
trigger->CastSpell(trigger, SPELL_HONORABLE_DEFENDER_25Y, false);
}
}
void BattlegroundEY::EventPlayerCapturedFlag(Player* player, uint32 BgObjectType)
{
if (GetStatus() != STATUS_IN_PROGRESS || GetFlagPickerGUID() != player->GetGUID())
return;
SetFlagPicker(ObjectGuid::Empty);
m_FlagState = BG_EY_FLAG_STATE_WAIT_RESPAWN;
player->RemoveAurasDueToSpell(BG_EY_NETHERSTORM_FLAG_SPELL);
player->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
if (player->GetTeam() == ALLIANCE)
PlaySoundToAll(BG_EY_SOUND_FLAG_CAPTURED_ALLIANCE);
else
PlaySoundToAll(BG_EY_SOUND_FLAG_CAPTURED_HORDE);
SpawnBGObject(BgObjectType, RESPAWN_IMMEDIATELY);
m_FlagsTimer = BG_EY_FLAG_RESPAWN_TIME;
m_FlagCapturedBgObjectType = BgObjectType;
uint8 team_id = 0;
if (player->GetTeam() == ALLIANCE)
{
team_id = TEAM_ALLIANCE;
SendMessageToAll(LANG_BG_EY_CAPTURED_FLAG_A, CHAT_MSG_BG_SYSTEM_ALLIANCE, player);
}
else
{
team_id = TEAM_HORDE;
SendMessageToAll(LANG_BG_EY_CAPTURED_FLAG_H, CHAT_MSG_BG_SYSTEM_HORDE, player);
}
if (m_TeamPointsCount[team_id] > 0)
AddPoints(player->GetTeam(), BG_EY_FlagPoints[m_TeamPointsCount[team_id] - 1]);
UpdatePlayerScore(player, SCORE_FLAG_CAPTURES, 1);
}
bool BattlegroundEY::UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor)
{
if (!Battleground::UpdatePlayerScore(player, type, value, doAddHonor))
return false;
switch (type)
{
case SCORE_FLAG_CAPTURES:
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, EY_OBJECTIVE_CAPTURE_FLAG);
break;
default:
break;
}
return true;
}
void BattlegroundEY::FillInitialWorldStates(WorldPacket& data)
{
data << uint32(EY_HORDE_BASE) << uint32(m_TeamPointsCount[TEAM_HORDE]);
data << uint32(EY_ALLIANCE_BASE) << uint32(m_TeamPointsCount[TEAM_ALLIANCE]);
data << uint32(0xab6) << uint32(0x0);
data << uint32(0xab5) << uint32(0x0);
data << uint32(0xab4) << uint32(0x0);
data << uint32(0xab3) << uint32(0x0);
data << uint32(0xab2) << uint32(0x0);
data << uint32(0xab1) << uint32(0x0);
data << uint32(0xab0) << uint32(0x0);
data << uint32(0xaaf) << uint32(0x0);
data << uint32(DRAENEI_RUINS_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[DRAENEI_RUINS] == HORDE && m_PointState[DRAENEI_RUINS] == EY_POINT_UNDER_CONTROL);
data << uint32(DRAENEI_RUINS_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[DRAENEI_RUINS] == ALLIANCE && m_PointState[DRAENEI_RUINS] == EY_POINT_UNDER_CONTROL);
data << uint32(DRAENEI_RUINS_UNCONTROL) << uint32(m_PointState[DRAENEI_RUINS] != EY_POINT_UNDER_CONTROL);
data << uint32(MAGE_TOWER_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[MAGE_TOWER] == ALLIANCE && m_PointState[MAGE_TOWER] == EY_POINT_UNDER_CONTROL);
data << uint32(MAGE_TOWER_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[MAGE_TOWER] == HORDE && m_PointState[MAGE_TOWER] == EY_POINT_UNDER_CONTROL);
data << uint32(MAGE_TOWER_UNCONTROL) << uint32(m_PointState[MAGE_TOWER] != EY_POINT_UNDER_CONTROL);
data << uint32(FEL_REAVER_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[FEL_REAVER] == HORDE && m_PointState[FEL_REAVER] == EY_POINT_UNDER_CONTROL);
data << uint32(FEL_REAVER_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[FEL_REAVER] == ALLIANCE && m_PointState[FEL_REAVER] == EY_POINT_UNDER_CONTROL);
data << uint32(FEL_REAVER_UNCONTROL) << uint32(m_PointState[FEL_REAVER] != EY_POINT_UNDER_CONTROL);
data << uint32(BLOOD_ELF_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[BLOOD_ELF] == HORDE && m_PointState[BLOOD_ELF] == EY_POINT_UNDER_CONTROL);
data << uint32(BLOOD_ELF_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[BLOOD_ELF] == ALLIANCE && m_PointState[BLOOD_ELF] == EY_POINT_UNDER_CONTROL);
data << uint32(BLOOD_ELF_UNCONTROL) << uint32(m_PointState[BLOOD_ELF] != EY_POINT_UNDER_CONTROL);
data << uint32(NETHERSTORM_FLAG) << uint32(m_FlagState == BG_EY_FLAG_STATE_ON_BASE);
data << uint32(0xad2) << uint32(0x1);
data << uint32(0xad1) << uint32(0x1);
data << uint32(0xabe) << uint32(GetTeamScore(TEAM_HORDE));
data << uint32(0xabd) << uint32(GetTeamScore(TEAM_ALLIANCE));
data << uint32(0xa05) << uint32(0x8e);
data << uint32(0xaa0) << uint32(0x0);
data << uint32(0xa9f) << uint32(0x0);
data << uint32(0xa9e) << uint32(0x0);
data << uint32(0xc0d) << uint32(0x17b);
}
WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player)
{
uint32 g_id = 0;
switch (player->GetTeam())
{
case ALLIANCE: g_id = EY_GRAVEYARD_MAIN_ALLIANCE; break;
case HORDE: g_id = EY_GRAVEYARD_MAIN_HORDE; break;
default: return NULL;
}
float distance, nearestDistance;
WorldSafeLocsEntry const* entry = NULL;
WorldSafeLocsEntry const* nearestEntry = NULL;
entry = sWorldSafeLocsStore.LookupEntry(g_id);
nearestEntry = entry;
if (!entry)
{
TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Not found the main team graveyard. Graveyard system isn't working!");
return NULL;
}
float plr_x = player->GetPositionX();
float plr_y = player->GetPositionY();
float plr_z = player->GetPositionZ();
distance = (entry->x - plr_x)*(entry->x - plr_x) + (entry->y - plr_y)*(entry->y - plr_y) + (entry->z - plr_z)*(entry->z - plr_z);
nearestDistance = distance;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
if (m_PointOwnedByTeam[i] == player->GetTeam() && m_PointState[i] == EY_POINT_UNDER_CONTROL)
{
entry = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[i].GraveYardId);
if (!entry)
TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Not found graveyard: %u", m_CapturingPointTypes[i].GraveYardId);
else
{
distance = (entry->x - plr_x)*(entry->x - plr_x) + (entry->y - plr_y)*(entry->y - plr_y) + (entry->z - plr_z)*(entry->z - plr_z);
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestEntry = entry;
}
}
}
}
return nearestEntry;
}
bool BattlegroundEY::IsAllNodesControlledByTeam(uint32 team) const
{
uint32 count = 0;
for (int i = 0; i < EY_POINTS_MAX; ++i)
if (m_PointOwnedByTeam[i] == team && m_PointState[i] == EY_POINT_UNDER_CONTROL)
++count;
return count == EY_POINTS_MAX;
}
uint32 BattlegroundEY::GetPrematureWinner()
{
if (GetTeamScore(TEAM_ALLIANCE) > GetTeamScore(TEAM_HORDE))
return ALLIANCE;
else if (GetTeamScore(TEAM_HORDE) > GetTeamScore(TEAM_ALLIANCE))
return HORDE;
return Battleground::GetPrematureWinner();
}
|
Rudi9719/curly-octo-barnacle
|
src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp
|
C++
|
gpl-2.0
| 43,939
|
<?php
/*
* License: GPLv3
* License URI: http://www.gnu.org/licenses/gpl.txt
* Copyright 2012-2015 - Jean-Sebastien Morisset - http://surniaulula.com/
*/
if ( ! defined( 'ABSPATH' ) )
die( 'These aren\'t the droids you\'re looking for...' );
if ( ! class_exists( 'SucomNotice' ) ) {
class SucomNotice {
private $p;
private $lca = '';
private $uca = '';
private $label = '';
private $log = array(
'nag' => array(),
'err' => array(),
'inf' => array(),
);
public function __construct( &$plugin, $lca = 'sucom', $label = '' ) {
$this->p =& $plugin;
if ( ! empty( $this->p->debug->enabled ) )
$this->p->debug->mark();
$this->lca = empty( $this->p->cf['lca'] ) ?
$lca : $this->p->cf['lca'];
$this->uca = strtoupper( $this->lca );
$this->label = empty( $label ) ?
$this->uca : $label;
add_action( 'all_admin_notices', array( &$this, 'admin_notices' ) );
}
public function nag( $msg = '', $store = false, $user = true, $cssid = null ) {
$this->log( 'nag', $msg, $store, $user, $cssid );
}
public function err( $msg = '', $store = false, $user = true, $cssid = null ) {
$this->log( 'err', $msg, $store, $user, $cssid );
}
public function inf( $msg = '', $store = false, $user = true, $cssid = null ) {
$this->log( 'inf', $msg, $store, $user, $cssid );
}
public function log( $type, $msg = '', $store = false, $user = true, $cssid = null ) {
if ( empty( $msg ) )
return;
if ( $store == true ) { // save the message in the database
$user_id = get_current_user_id(); // since wp 3.0
if ( empty( $user_id ) ) // exclude wp-cron and/or empty user ids
$user = false;
$msg_opt = $this->lca.'_notices_'.$type; // the option name
if ( $user == true ) // get the message array from the user table
$msg_arr = get_user_option( $msg_opt, $user_id );
else $msg_arr = get_option( $msg_opt ); // get the message array from the options table
if ( $msg_arr === false )
$msg_arr = array(); // if the array doesn't already exist, define a new one
if ( ! in_array( $msg, $msg_arr ) ) { // dont't save duplicates
if ( ! empty( $cssid ) )
$msg_arr[$type.'_'.$cssid] = $msg;
else $msg_arr[] = $msg;
}
if ( $user == true ) // update the user option table
update_user_option( $user_id, $msg_opt, $msg_arr );
else update_option( $msg_opt, $msg_arr ); // update the option table
} elseif ( ! in_array( $msg, $this->log[$type] ) ) { // dont't save duplicates
if ( ! empty( $cssid ) )
$this->log[$type][$type.'_'.$cssid] = $msg;
else $this->log[$type][] = $msg;
}
}
public function trunc( $idx = '' ) {
$types = empty( $idx ) ?
array_keys( $this->log ) : array( $idx );
foreach ( $types as $type ) {
$msg_opt = $this->lca.'_notices_'.$type;
$user_id = get_current_user_id(); // since wp 3.0
if ( get_option( $msg_opt ) ) {
update_option( $msg_opt, array() ); // delete doesn't always work, so set empty value first
delete_option( $msg_opt );
}
if ( ! empty( $user_id ) ) { // exclude wp-cron and/or empty user ids
if ( get_user_option( $msg_opt, $user_id ) ) {
update_user_option( $user_id, $msg_opt, array() );
delete_user_option( $user_id, $msg_opt );
}
}
$this->log[$type] = array();
}
}
public function admin_notices() {
$all_nag_msgs = '';
foreach ( array_keys( $this->log ) as $type ) {
$user_id = get_current_user_id(); // since wp 3.0
$msg_opt = $this->lca.'_notices_'.$type;
$msg_arr = array_unique( array_merge(
(array) get_option( $msg_opt ),
(array) get_user_option( $msg_opt, $user_id ),
$this->log[$type]
) );
$this->trunc( $type );
if ( $type === 'err' &&
isset( $this->p->cf['plugin'] ) &&
class_exists( 'SucomUpdate' ) ) {
foreach ( array_keys( $this->p->cf['plugin'] ) as $lca ) {
if ( ! empty( $this->p->options['plugin_'.$lca.'_tid'] ) ) {
$umsg = SucomUpdate::get_umsg( $lca );
if ( $umsg !== false && $umsg !== true )
$msg_arr[] = $umsg;
}
}
}
if ( ! empty( $msg_arr ) ) {
if ( $type == 'nag' )
echo $this->get_nag_style( $this->lca );
foreach ( $msg_arr as $key => $msg ) {
if ( ! empty( $msg ) ) {
$label = '';
$class = '';
$cssid_attr = strpos( $key, $type.'_' ) === 0 ? ' id="'.$key.'"' : '';
switch ( $type ) {
case 'nag':
$all_nag_msgs .= $msg; // append to echo later in single div block
break;
case 'err':
if ( empty( $class ) )
$class = 'error';
if ( empty( $label ) && ! empty( $this->label ) )
$label = $this->label.' Notice'; // or 'Warning'
// no break
case 'inf':
// allow for variable definitions in previous case blocks
if ( empty( $class ) )
$class = 'updated fade';
if ( empty( $label ) && ! empty( $this->label ) )
$label = $this->label.' Notice'; // or 'Info'
echo '<div class="'.$class.'"'.$cssid_attr.'>';
if ( ! empty( $label ) )
echo '<div style="display:table-cell;">
<p style="margin:5px 0;white-space:nowrap;">
<b>'.$label.'</b>:</p></div>';
echo '<div style="display:table-cell;">
<p style="margin:5px;text-align:left">'.$msg.'</p></div>';
echo '</div>';
break;
}
}
}
}
}
if ( ! empty( $all_nag_msgs ) )
echo '<div class="update-nag '.$this->lca.'-update-nag">', $all_nag_msgs, '</div>', "\n";
}
private function get_nag_style( $lca ) {
return '<style type="text/css">
.'.$lca.'-update-nag {
display:block;
line-height:1.4em;
background-color:'.( empty( $this->p->cf['bgcolor'] ) ?
'none' : '#'.$this->p->cf['bgcolor'] ).';
background-image:'.( empty( $this->p->cf['plugin'][$this->lca]['img']['background'] ) ?
'none' : 'url("'.$this->p->cf['plugin'][$this->lca]['img']['background'].'")' ).';
background-position:top;
background-size:cover;
border:1px dashed #ccc;
padding:10px 40px 10px 40px;
margin-top:0;
}
.'.$lca.'-update-nag p,
.'.$lca.'-update-nag ul,
.'.$lca.'-update-nag ol {
font-size:1em;
clear:both;
max-width:720px;
margin:15px auto 15px auto;
text-align:center;
}
.'.$lca.'-update-nag ul li {
list-style-type:square;
}
.'.$lca.'-update-nag ol li {
list-style-type:decimal;
}
.'.$lca.'-update-nag li {
text-align:left;
margin:5px 0 5px 60px;
}
</style>';
}
}
}
?>
|
trung85/giasu
|
wp-content/plugins/wpsso/lib/com/notice.php
|
PHP
|
gpl-2.0
| 6,568
|
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Implementation of the Transmission Control Protocol(TCP).
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Mark Evans, <evansmp@uhura.aston.ac.uk>
* Corey Minyard <wf-rch!minyard@relay.EU.net>
* Florian La Roche, <flla@stud.uni-sb.de>
* Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
* Linus Torvalds, <torvalds@cs.helsinki.fi>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
* Matthew Dillon, <dillon@apollo.west.oic.com>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Jorge Cwik, <jorge@laser.satlink.net>
*/
/*
* Changes:
* Pedro Roque : Fast Retransmit/Recovery.
* Two receive queues.
* Retransmit queue handled by TCP.
* Better retransmit timer handling.
* New congestion avoidance.
* Header prediction.
* Variable renaming.
*
* Eric : Fast Retransmit.
* Randy Scott : MSS option defines.
* Eric Schenk : Fixes to slow start algorithm.
* Eric Schenk : Yet another double ACK bug.
* Eric Schenk : Delayed ACK bug fixes.
* Eric Schenk : Floyd style fast retrans war avoidance.
* David S. Miller : Don't allow zero congestion window.
* Eric Schenk : Fix retransmitter so that it sends
* next packet on ack of previous packet.
* Andi Kleen : Moved open_request checking here
* and process RSTs for open_requests.
* Andi Kleen : Better prune_queue, and other fixes.
* Andrey Savochkin: Fix RTT measurements in the presence of
* timestamps.
* Andrey Savochkin: Check sequence numbers correctly when
* removing SACKs due to in sequence incoming
* data segments.
* Andi Kleen: Make sure we never ack data there is not
* enough room for. Also make this condition
* a fatal error if it might still happen.
* Andi Kleen: Add tcp_measure_rcv_mss to make
* connections with MSS<min(MTU,ann. MSS)
* work without delayed acks.
* Andi Kleen: Process packets with PSH set in the
* fast path.
* J Hadi Salim: ECN support
* Andrei Gurtov,
* Pasi Sarolahti,
* Panu Kuhlberg: Experimental audit of TCP (re)transmission
* engine. Lots of bugs are found.
* Pasi Sarolahti: F-RTO for dealing with spurious RTOs
*/
#define pr_fmt(fmt) "TCP: " fmt
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/sysctl.h>
#include <linux/kernel.h>
#include <net/dst.h>
#include <net/tcp.h>
#include <net/inet_common.h>
#include <linux/ipsec.h>
#include <asm/unaligned.h>
#include <net/netdma.h>
int sysctl_tcp_timestamps __read_mostly = 1;
int sysctl_tcp_window_scaling __read_mostly = 1;
int sysctl_tcp_sack __read_mostly = 1;
int sysctl_tcp_fack __read_mostly = 1;
int sysctl_tcp_reordering __read_mostly = TCP_FASTRETRANS_THRESH;
EXPORT_SYMBOL(sysctl_tcp_reordering);
int sysctl_tcp_dsack __read_mostly = 1;
int sysctl_tcp_app_win __read_mostly = 31;
int sysctl_tcp_adv_win_scale __read_mostly = 1;
EXPORT_SYMBOL(sysctl_tcp_adv_win_scale);
/* rfc5961 challenge ack rate limiting */
int sysctl_tcp_challenge_ack_limit = 100;
int sysctl_tcp_stdurg __read_mostly;
int sysctl_tcp_rfc1337 __read_mostly;
int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
int sysctl_tcp_frto __read_mostly = 2;
int sysctl_tcp_thin_dupack __read_mostly;
int sysctl_tcp_moderate_rcvbuf __read_mostly = 1;
int sysctl_tcp_early_retrans __read_mostly = 3;
#define FLAG_DATA 0x01 /* Incoming frame contained data. */
#define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
#define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
#define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
#define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
#define FLAG_DATA_SACKED 0x20 /* New SACK. */
#define FLAG_ECE 0x40 /* ECE in this ACK */
#define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
#define FLAG_ORIG_SACK_ACKED 0x200 /* Never retransmitted data are (s)acked */
#define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
#define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */
#define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */
#define FLAG_UPDATE_TS_RECENT 0x4000 /* tcp_replace_ts_recent() */
#define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
#define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE)
#define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
#define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
#define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
/* Adapt the MSS value used to make delayed ack decision to the
* real world.
*/
static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
{
struct inet_connection_sock *icsk = inet_csk(sk);
const unsigned int lss = icsk->icsk_ack.last_seg_size;
unsigned int len;
icsk->icsk_ack.last_seg_size = 0;
/* skb->len may jitter because of SACKs, even if peer
* sends good full-sized frames.
*/
len = skb_shinfo(skb)->gso_size ? : skb->len;
if (len >= icsk->icsk_ack.rcv_mss) {
icsk->icsk_ack.rcv_mss = len;
} else {
/* Otherwise, we make more careful check taking into account,
* that SACKs block is variable.
*
* "len" is invariant segment length, including TCP header.
*/
len += skb->data - skb_transport_header(skb);
if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
/* If PSH is not set, packet should be
* full sized, provided peer TCP is not badly broken.
* This observation (if it is correct 8)) allows
* to handle super-low mtu links fairly.
*/
(len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
!(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
/* Subtract also invariant (if peer is RFC compliant),
* tcp header plus fixed timestamp option length.
* Resulting "len" is MSS free of SACK jitter.
*/
len -= tcp_sk(sk)->tcp_header_len;
icsk->icsk_ack.last_seg_size = len;
if (len == lss) {
icsk->icsk_ack.rcv_mss = len;
return;
}
}
if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
}
}
static void tcp_incr_quickack(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
if (quickacks == 0)
quickacks = 2;
if (quickacks > icsk->icsk_ack.quick)
icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
}
static void tcp_enter_quickack_mode(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
tcp_incr_quickack(sk);
icsk->icsk_ack.pingpong = 0;
icsk->icsk_ack.ato = TCP_ATO_MIN;
}
/* Send ACKs quickly, if "quick" count is not exhausted
* and the session is not interactive.
*/
static inline bool tcp_in_quickack_mode(const struct sock *sk)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
return icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong;
}
static inline void TCP_ECN_queue_cwr(struct tcp_sock *tp)
{
if (tp->ecn_flags & TCP_ECN_OK)
tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
}
static inline void TCP_ECN_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb)
{
if (tcp_hdr(skb)->cwr)
tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
}
static inline void TCP_ECN_withdraw_cwr(struct tcp_sock *tp)
{
tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
}
static inline void TCP_ECN_check_ce(struct tcp_sock *tp, const struct sk_buff *skb)
{
if (!(tp->ecn_flags & TCP_ECN_OK))
return;
switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
case INET_ECN_NOT_ECT:
/* Funny extension: if ECT is not set on a segment,
* and we already seen ECT on a previous segment,
* it is probably a retransmit.
*/
if (tp->ecn_flags & TCP_ECN_SEEN)
tcp_enter_quickack_mode((struct sock *)tp);
break;
case INET_ECN_CE:
if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) {
/* Better not delay acks, sender can have a very low cwnd */
tcp_enter_quickack_mode((struct sock *)tp);
tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
}
/* fallinto */
default:
tp->ecn_flags |= TCP_ECN_SEEN;
}
}
static inline void TCP_ECN_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
{
if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
tp->ecn_flags &= ~TCP_ECN_OK;
}
static inline void TCP_ECN_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
{
if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
tp->ecn_flags &= ~TCP_ECN_OK;
}
static bool TCP_ECN_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
{
if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
return true;
return false;
}
/* Buffer size and advertised window tuning.
*
* 1. Tuning sk->sk_sndbuf, when connection enters established state.
*/
static void tcp_fixup_sndbuf(struct sock *sk)
{
int sndmem = SKB_TRUESIZE(tcp_sk(sk)->rx_opt.mss_clamp + MAX_TCP_HEADER);
sndmem *= TCP_INIT_CWND;
if (sk->sk_sndbuf < sndmem)
sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
}
/* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
*
* All tcp_full_space() is split to two parts: "network" buffer, allocated
* forward and advertised in receiver window (tp->rcv_wnd) and
* "application buffer", required to isolate scheduling/application
* latencies from network.
* window_clamp is maximal advertised window. It can be less than
* tcp_full_space(), in this case tcp_full_space() - window_clamp
* is reserved for "application" buffer. The less window_clamp is
* the smoother our behaviour from viewpoint of network, but the lower
* throughput and the higher sensitivity of the connection to losses. 8)
*
* rcv_ssthresh is more strict window_clamp used at "slow start"
* phase to predict further behaviour of this connection.
* It is used for two goals:
* - to enforce header prediction at sender, even when application
* requires some significant "application buffer". It is check #1.
* - to prevent pruning of receive queue because of misprediction
* of receiver window. Check #2.
*
* The scheme does not work when sender sends good segments opening
* window and then starts to feed us spaghetti. But it should work
* in common situations. Otherwise, we have to rely on queue collapsing.
*/
/* Slow part of check#2. */
static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Optimize this! */
int truesize = tcp_win_from_space(skb->truesize) >> 1;
int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1;
while (tp->rcv_ssthresh <= window) {
if (truesize <= skb->len)
return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
truesize >>= 1;
window >>= 1;
}
return 0;
}
static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Check #1 */
if (tp->rcv_ssthresh < tp->window_clamp &&
(int)tp->rcv_ssthresh < tcp_space(sk) &&
!sk_under_memory_pressure(sk)) {
int incr;
/* Check #2. Increase window, if skb with such overhead
* will fit to rcvbuf in future.
*/
if (tcp_win_from_space(skb->truesize) <= skb->len)
incr = 2 * tp->advmss;
else
incr = __tcp_grow_window(sk, skb);
if (incr) {
incr = max_t(int, incr, 2 * skb->len);
tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr,
tp->window_clamp);
inet_csk(sk)->icsk_ack.quick |= 1;
}
}
}
/* 3. Tuning rcvbuf, when connection enters established state. */
static void tcp_fixup_rcvbuf(struct sock *sk)
{
u32 mss = tcp_sk(sk)->advmss;
u32 icwnd = TCP_DEFAULT_INIT_RCVWND;
int rcvmem;
/* Limit to 10 segments if mss <= 1460,
* or 14600/mss segments, with a minimum of two segments.
*/
if (mss > 1460)
icwnd = max_t(u32, (1460 * TCP_DEFAULT_INIT_RCVWND) / mss, 2);
rcvmem = SKB_TRUESIZE(mss + MAX_TCP_HEADER);
while (tcp_win_from_space(rcvmem) < mss)
rcvmem += 128;
rcvmem *= icwnd;
if (sk->sk_rcvbuf < rcvmem)
sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]);
}
/* 4. Try to fixup all. It is made immediately after connection enters
* established state.
*/
void tcp_init_buffer_space(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
int maxwin;
if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
tcp_fixup_rcvbuf(sk);
if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
tcp_fixup_sndbuf(sk);
tp->rcvq_space.space = tp->rcv_wnd;
maxwin = tcp_full_space(sk);
if (tp->window_clamp >= maxwin) {
tp->window_clamp = maxwin;
if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
tp->window_clamp = max(maxwin -
(maxwin >> sysctl_tcp_app_win),
4 * tp->advmss);
}
/* Force reservation of one segment. */
if (sysctl_tcp_app_win &&
tp->window_clamp > 2 * tp->advmss &&
tp->window_clamp + tp->advmss > maxwin)
tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
tp->snd_cwnd_stamp = tcp_time_stamp;
}
/* 5. Recalculate window clamp after socket hit its memory bounds. */
static void tcp_clamp_window(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_ack.quick = 0;
if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
!(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
!sk_under_memory_pressure(sk) &&
sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
sysctl_tcp_rmem[2]);
}
if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
}
/* Initialize RCV_MSS value.
* RCV_MSS is an our guess about MSS used by the peer.
* We haven't any direct information about the MSS.
* It's better to underestimate the RCV_MSS rather than overestimate.
* Overestimations make us ACKing less frequently than needed.
* Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
*/
void tcp_initialize_rcv_mss(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
hint = min(hint, tp->rcv_wnd / 2);
hint = min(hint, TCP_MSS_DEFAULT);
hint = max(hint, TCP_MIN_MSS);
inet_csk(sk)->icsk_ack.rcv_mss = hint;
}
EXPORT_SYMBOL(tcp_initialize_rcv_mss);
/* Receiver "autotuning" code.
*
* The algorithm for RTT estimation w/o timestamps is based on
* Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
* <http://public.lanl.gov/radiant/pubs.html#DRS>
*
* More detail on this code can be found at
* <http://staff.psc.edu/jheffner/>,
* though this reference is out of date. A new paper
* is pending.
*/
static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
{
u32 new_sample = tp->rcv_rtt_est.rtt;
long m = sample;
if (m == 0)
m = 1;
if (new_sample != 0) {
/* If we sample in larger samples in the non-timestamp
* case, we could grossly overestimate the RTT especially
* with chatty applications or bulk transfer apps which
* are stalled on filesystem I/O.
*
* Also, since we are only going for a minimum in the
* non-timestamp case, we do not smooth things out
* else with timestamps disabled convergence takes too
* long.
*/
if (!win_dep) {
m -= (new_sample >> 3);
new_sample += m;
} else {
m <<= 3;
if (m < new_sample)
new_sample = m;
}
} else {
/* No previous measure. */
new_sample = m << 3;
}
if (tp->rcv_rtt_est.rtt != new_sample)
tp->rcv_rtt_est.rtt = new_sample;
}
static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
{
if (tp->rcv_rtt_est.time == 0)
goto new_measure;
if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
return;
tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rcv_rtt_est.time, 1);
new_measure:
tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
tp->rcv_rtt_est.time = tcp_time_stamp;
}
static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
const struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tp->rx_opt.rcv_tsecr &&
(TCP_SKB_CB(skb)->end_seq -
TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss))
tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0);
}
/*
* This function should be called every time data is copied to user space.
* It calculates the appropriate TCP receive buffer space.
*/
void tcp_rcv_space_adjust(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
int time;
int space;
if (tp->rcvq_space.time == 0)
goto new_measure;
time = tcp_time_stamp - tp->rcvq_space.time;
if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0)
return;
space = 2 * (tp->copied_seq - tp->rcvq_space.seq);
space = max(tp->rcvq_space.space, space);
if (tp->rcvq_space.space != space) {
int rcvmem;
tp->rcvq_space.space = space;
if (sysctl_tcp_moderate_rcvbuf &&
!(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
int new_clamp = space;
/* Receive space grows, normalize in order to
* take into account packet headers and sk_buff
* structure overhead.
*/
space /= tp->advmss;
if (!space)
space = 1;
rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
while (tcp_win_from_space(rcvmem) < tp->advmss)
rcvmem += 128;
space *= rcvmem;
space = min(space, sysctl_tcp_rmem[2]);
if (space > sk->sk_rcvbuf) {
sk->sk_rcvbuf = space;
/* Make the window clamp follow along. */
tp->window_clamp = new_clamp;
}
}
}
new_measure:
tp->rcvq_space.seq = tp->copied_seq;
tp->rcvq_space.time = tcp_time_stamp;
}
/* There is something which you must keep in mind when you analyze the
* behavior of the tp->ato delayed ack timeout interval. When a
* connection starts up, we want to ack as quickly as possible. The
* problem is that "good" TCP's do slow start at the beginning of data
* transmission. The means that until we send the first few ACK's the
* sender will sit on his end and only queue most of his data, because
* he can only send snd_cwnd unacked packets at any given time. For
* each ACK we send, he increments snd_cwnd and transmits more of his
* queue. -DaveM
*/
static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
u32 now;
inet_csk_schedule_ack(sk);
tcp_measure_rcv_mss(sk, skb);
tcp_rcv_rtt_measure(tp);
now = tcp_time_stamp;
if (!icsk->icsk_ack.ato) {
/* The _first_ data packet received, initialize
* delayed ACK engine.
*/
tcp_incr_quickack(sk);
icsk->icsk_ack.ato = TCP_ATO_MIN;
} else {
int m = now - icsk->icsk_ack.lrcvtime;
if (m <= TCP_ATO_MIN / 2) {
/* The fastest case is the first. */
icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
} else if (m < icsk->icsk_ack.ato) {
icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
if (icsk->icsk_ack.ato > icsk->icsk_rto)
icsk->icsk_ack.ato = icsk->icsk_rto;
} else if (m > icsk->icsk_rto) {
/* Too long gap. Apparently sender failed to
* restart window, so that we send ACKs quickly.
*/
tcp_incr_quickack(sk);
sk_mem_reclaim(sk);
}
}
icsk->icsk_ack.lrcvtime = now;
TCP_ECN_check_ce(tp, skb);
if (skb->len >= 128)
tcp_grow_window(sk, skb);
}
/* Called to compute a smoothed rtt estimate. The data fed to this
* routine either comes from timestamps, or from segments that were
* known _not_ to have been retransmitted [see Karn/Partridge
* Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
* piece by Van Jacobson.
* NOTE: the next three routines used to be one big routine.
* To save cycles in the RFC 1323 implementation it was better to break
* it up into three procedures. -- erics
*/
static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt)
{
struct tcp_sock *tp = tcp_sk(sk);
long m = mrtt; /* RTT */
/* The following amusing code comes from Jacobson's
* article in SIGCOMM '88. Note that rtt and mdev
* are scaled versions of rtt and mean deviation.
* This is designed to be as fast as possible
* m stands for "measurement".
*
* On a 1990 paper the rto value is changed to:
* RTO = rtt + 4 * mdev
*
* Funny. This algorithm seems to be very broken.
* These formulae increase RTO, when it should be decreased, increase
* too slowly, when it should be increased quickly, decrease too quickly
* etc. I guess in BSD RTO takes ONE value, so that it is absolutely
* does not matter how to _calculate_ it. Seems, it was trap
* that VJ failed to avoid. 8)
*/
if (m == 0)
m = 1;
if (tp->srtt != 0) {
m -= (tp->srtt >> 3); /* m is now error in rtt est */
tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */
if (m < 0) {
m = -m; /* m is now abs(error) */
m -= (tp->mdev >> 2); /* similar update on mdev */
/* This is similar to one of Eifel findings.
* Eifel blocks mdev updates when rtt decreases.
* This solution is a bit different: we use finer gain
* for mdev in this case (alpha*beta).
* Like Eifel it also prevents growth of rto,
* but also it limits too fast rto decreases,
* happening in pure Eifel.
*/
if (m > 0)
m >>= 3;
} else {
m -= (tp->mdev >> 2); /* similar update on mdev */
}
tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */
if (tp->mdev > tp->mdev_max) {
tp->mdev_max = tp->mdev;
if (tp->mdev_max > tp->rttvar)
tp->rttvar = tp->mdev_max;
}
if (after(tp->snd_una, tp->rtt_seq)) {
if (tp->mdev_max < tp->rttvar)
tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2;
tp->rtt_seq = tp->snd_nxt;
tp->mdev_max = tcp_rto_min(sk);
}
} else {
/* no previous measure. */
tp->srtt = m << 3; /* take the measured time to be rtt */
tp->mdev = m << 1; /* make sure rto = 3*rtt */
tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
tp->rtt_seq = tp->snd_nxt;
}
}
/* Set the sk_pacing_rate to allow proper sizing of TSO packets.
* Note: TCP stack does not yet implement pacing.
* FQ packet scheduler can be used to implement cheap but effective
* TCP pacing, to smooth the burst on large writes when packets
* in flight is significantly lower than cwnd (or rwin)
*/
static void tcp_update_pacing_rate(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
u64 rate;
/* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
rate = (u64)tp->mss_cache * 2 * (HZ << 3);
rate *= max(tp->snd_cwnd, tp->packets_out);
/* Correction for small srtt : minimum srtt being 8 (1 jiffy << 3),
* be conservative and assume srtt = 1 (125 us instead of 1.25 ms)
* We probably need usec resolution in the future.
* Note: This also takes care of possible srtt=0 case,
* when tcp_rtt_estimator() was not yet called.
*/
if (tp->srtt > 8 + 2)
do_div(rate, tp->srtt);
sk->sk_pacing_rate = min_t(u64, rate, ~0U);
}
/* Calculate rto without backoff. This is the second half of Van Jacobson's
* routine referred to above.
*/
void tcp_set_rto(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
/* Old crap is replaced with new one. 8)
*
* More seriously:
* 1. If rtt variance happened to be less 50msec, it is hallucination.
* It cannot be less due to utterly erratic ACK generation made
* at least by solaris and freebsd. "Erratic ACKs" has _nothing_
* to do with delayed acks, because at cwnd>2 true delack timeout
* is invisible. Actually, Linux-2.4 also generates erratic
* ACKs in some circumstances.
*/
inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
/* 2. Fixups made earlier cannot be right.
* If we do not estimate RTO correctly without them,
* all the algo is pure shit and should be replaced
* with correct one. It is exactly, which we pretend to do.
*/
/* NOTE: clamping at TCP_RTO_MIN is not required, current algo
* guarantees that rto is higher.
*/
tcp_bound_rto(sk);
}
__u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
{
__u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
if (!cwnd)
cwnd = TCP_INIT_CWND;
return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
}
/*
* Packet counting of FACK is based on in-order assumptions, therefore TCP
* disables it when reordering is detected
*/
void tcp_disable_fack(struct tcp_sock *tp)
{
/* RFC3517 uses different metric in lost marker => reset on change */
if (tcp_is_fack(tp))
tp->lost_skb_hint = NULL;
tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED;
}
/* Take a notice that peer is sending D-SACKs */
static void tcp_dsack_seen(struct tcp_sock *tp)
{
tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
}
static void tcp_update_reordering(struct sock *sk, const int metric,
const int ts)
{
struct tcp_sock *tp = tcp_sk(sk);
if (metric > tp->reordering) {
int mib_idx;
tp->reordering = min(TCP_MAX_REORDERING, metric);
/* This exciting event is worth to be remembered. 8) */
if (ts)
mib_idx = LINUX_MIB_TCPTSREORDER;
else if (tcp_is_reno(tp))
mib_idx = LINUX_MIB_TCPRENOREORDER;
else if (tcp_is_fack(tp))
mib_idx = LINUX_MIB_TCPFACKREORDER;
else
mib_idx = LINUX_MIB_TCPSACKREORDER;
NET_INC_STATS_BH(sock_net(sk), mib_idx);
#if FASTRETRANS_DEBUG > 1
pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
tp->reordering,
tp->fackets_out,
tp->sacked_out,
tp->undo_marker ? tp->undo_retrans : 0);
#endif
tcp_disable_fack(tp);
}
if (metric > 0)
tcp_disable_early_retrans(tp);
}
/* This must be called before lost_out is incremented */
static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
{
if ((tp->retransmit_skb_hint == NULL) ||
before(TCP_SKB_CB(skb)->seq,
TCP_SKB_CB(tp->retransmit_skb_hint)->seq))
tp->retransmit_skb_hint = skb;
if (!tp->lost_out ||
after(TCP_SKB_CB(skb)->end_seq, tp->retransmit_high))
tp->retransmit_high = TCP_SKB_CB(skb)->end_seq;
}
static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb)
{
if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
tcp_verify_retransmit_hint(tp, skb);
tp->lost_out += tcp_skb_pcount(skb);
TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
}
}
static void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp,
struct sk_buff *skb)
{
tcp_verify_retransmit_hint(tp, skb);
if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
tp->lost_out += tcp_skb_pcount(skb);
TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
}
}
/* This procedure tags the retransmission queue when SACKs arrive.
*
* We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
* Packets in queue with these bits set are counted in variables
* sacked_out, retrans_out and lost_out, correspondingly.
*
* Valid combinations are:
* Tag InFlight Description
* 0 1 - orig segment is in flight.
* S 0 - nothing flies, orig reached receiver.
* L 0 - nothing flies, orig lost by net.
* R 2 - both orig and retransmit are in flight.
* L|R 1 - orig is lost, retransmit is in flight.
* S|R 1 - orig reached receiver, retrans is still in flight.
* (L|S|R is logically valid, it could occur when L|R is sacked,
* but it is equivalent to plain S and code short-curcuits it to S.
* L|S is logically invalid, it would mean -1 packet in flight 8))
*
* These 6 states form finite state machine, controlled by the following events:
* 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
* 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
* 3. Loss detection event of two flavors:
* A. Scoreboard estimator decided the packet is lost.
* A'. Reno "three dupacks" marks head of queue lost.
* A''. Its FACK modification, head until snd.fack is lost.
* B. SACK arrives sacking SND.NXT at the moment, when the
* segment was retransmitted.
* 4. D-SACK added new rule: D-SACK changes any tag to S.
*
* It is pleasant to note, that state diagram turns out to be commutative,
* so that we are allowed not to be bothered by order of our actions,
* when multiple events arrive simultaneously. (see the function below).
*
* Reordering detection.
* --------------------
* Reordering metric is maximal distance, which a packet can be displaced
* in packet stream. With SACKs we can estimate it:
*
* 1. SACK fills old hole and the corresponding segment was not
* ever retransmitted -> reordering. Alas, we cannot use it
* when segment was retransmitted.
* 2. The last flaw is solved with D-SACK. D-SACK arrives
* for retransmitted and already SACKed segment -> reordering..
* Both of these heuristics are not used in Loss state, when we cannot
* account for retransmits accurately.
*
* SACK block validation.
* ----------------------
*
* SACK block range validation checks that the received SACK block fits to
* the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
* Note that SND.UNA is not included to the range though being valid because
* it means that the receiver is rather inconsistent with itself reporting
* SACK reneging when it should advance SND.UNA. Such SACK block this is
* perfectly valid, however, in light of RFC2018 which explicitly states
* that "SACK block MUST reflect the newest segment. Even if the newest
* segment is going to be discarded ...", not that it looks very clever
* in case of head skb. Due to potentional receiver driven attacks, we
* choose to avoid immediate execution of a walk in write queue due to
* reneging and defer head skb's loss recovery to standard loss recovery
* procedure that will eventually trigger (nothing forbids us doing this).
*
* Implements also blockage to start_seq wrap-around. Problem lies in the
* fact that though start_seq (s) is before end_seq (i.e., not reversed),
* there's no guarantee that it will be before snd_nxt (n). The problem
* happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
* wrap (s_w):
*
* <- outs wnd -> <- wrapzone ->
* u e n u_w e_w s n_w
* | | | | | | |
* |<------------+------+----- TCP seqno space --------------+---------->|
* ...-- <2^31 ->| |<--------...
* ...---- >2^31 ------>| |<--------...
*
* Current code wouldn't be vulnerable but it's better still to discard such
* crazy SACK blocks. Doing this check for start_seq alone closes somewhat
* similar case (end_seq after snd_nxt wrap) as earlier reversed check in
* snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
* equal to the ideal case (infinite seqno space without wrap caused issues).
*
* With D-SACK the lower bound is extended to cover sequence space below
* SND.UNA down to undo_marker, which is the last point of interest. Yet
* again, D-SACK block must not to go across snd_una (for the same reason as
* for the normal SACK blocks, explained above). But there all simplicity
* ends, TCP might receive valid D-SACKs below that. As long as they reside
* fully below undo_marker they do not affect behavior in anyway and can
* therefore be safely ignored. In rare cases (which are more or less
* theoretical ones), the D-SACK will nicely cross that boundary due to skb
* fragmentation and packet reordering past skb's retransmission. To consider
* them correctly, the acceptable range must be extended even more though
* the exact amount is rather hard to quantify. However, tp->max_window can
* be used as an exaggerated estimate.
*/
static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
u32 start_seq, u32 end_seq)
{
/* Too far in future, or reversed (interpretation is ambiguous) */
if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
return false;
/* Nasty start_seq wrap-around check (see comments above) */
if (!before(start_seq, tp->snd_nxt))
return false;
/* In outstanding window? ...This is valid exit for D-SACKs too.
* start_seq == snd_una is non-sensical (see comments above)
*/
if (after(start_seq, tp->snd_una))
return true;
if (!is_dsack || !tp->undo_marker)
return false;
/* ...Then it's D-SACK, and must reside below snd_una completely */
if (after(end_seq, tp->snd_una))
return false;
if (!before(start_seq, tp->undo_marker))
return true;
/* Too old */
if (!after(end_seq, tp->undo_marker))
return false;
/* Undo_marker boundary crossing (overestimates a lot). Known already:
* start_seq < undo_marker and end_seq >= undo_marker.
*/
return !before(start_seq, end_seq - tp->max_window);
}
/* Check for lost retransmit. This superb idea is borrowed from "ratehalving".
* Event "B". Later note: FACK people cheated me again 8), we have to account
* for reordering! Ugly, but should help.
*
* Search retransmitted skbs from write_queue that were sent when snd_nxt was
* less than what is now known to be received by the other end (derived from
* highest SACK block). Also calculate the lowest snd_nxt among the remaining
* retransmitted skbs to avoid some costly processing per ACKs.
*/
static void tcp_mark_lost_retrans(struct sock *sk)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
int cnt = 0;
u32 new_low_seq = tp->snd_nxt;
u32 received_upto = tcp_highest_sack_seq(tp);
if (!tcp_is_fack(tp) || !tp->retrans_out ||
!after(received_upto, tp->lost_retrans_low) ||
icsk->icsk_ca_state != TCP_CA_Recovery)
return;
tcp_for_write_queue(skb, sk) {
u32 ack_seq = TCP_SKB_CB(skb)->ack_seq;
if (skb == tcp_send_head(sk))
break;
if (cnt == tp->retrans_out)
break;
if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
continue;
if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS))
continue;
/* TODO: We would like to get rid of tcp_is_fack(tp) only
* constraint here (see above) but figuring out that at
* least tp->reordering SACK blocks reside between ack_seq
* and received_upto is not easy task to do cheaply with
* the available datastructures.
*
* Whether FACK should check here for tp->reordering segs
* in-between one could argue for either way (it would be
* rather simple to implement as we could count fack_count
* during the walk and do tp->fackets_out - fack_count).
*/
if (after(received_upto, ack_seq)) {
TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
tp->retrans_out -= tcp_skb_pcount(skb);
tcp_skb_mark_lost_uncond_verify(tp, skb);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT);
} else {
if (before(ack_seq, new_low_seq))
new_low_seq = ack_seq;
cnt += tcp_skb_pcount(skb);
}
}
if (tp->retrans_out)
tp->lost_retrans_low = new_low_seq;
}
static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
struct tcp_sack_block_wire *sp, int num_sacks,
u32 prior_snd_una)
{
struct tcp_sock *tp = tcp_sk(sk);
u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
bool dup_sack = false;
if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
dup_sack = true;
tcp_dsack_seen(tp);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
} else if (num_sacks > 1) {
u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
if (!after(end_seq_0, end_seq_1) &&
!before(start_seq_0, start_seq_1)) {
dup_sack = true;
tcp_dsack_seen(tp);
NET_INC_STATS_BH(sock_net(sk),
LINUX_MIB_TCPDSACKOFORECV);
}
}
/* D-SACK for already forgotten data... Do dumb counting. */
if (dup_sack && tp->undo_marker && tp->undo_retrans > 0 &&
!after(end_seq_0, prior_snd_una) &&
after(end_seq_0, tp->undo_marker))
tp->undo_retrans--;
return dup_sack;
}
struct tcp_sacktag_state {
int reord;
int fack_count;
int flag;
};
/* Check if skb is fully within the SACK block. In presence of GSO skbs,
* the incoming SACK may not exactly match but we can find smaller MSS
* aligned portion of it that matches. Therefore we might need to fragment
* which may fail and creates some hassle (caller must handle error case
* returns).
*
* FIXME: this could be merged to shift decision code
*/
static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
u32 start_seq, u32 end_seq)
{
int err;
bool in_sack;
unsigned int pkt_len;
unsigned int mss;
in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
!before(end_seq, TCP_SKB_CB(skb)->end_seq);
if (tcp_skb_pcount(skb) > 1 && !in_sack &&
after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
mss = tcp_skb_mss(skb);
in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
if (!in_sack) {
pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
if (pkt_len < mss)
pkt_len = mss;
} else {
pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
if (pkt_len < mss)
return -EINVAL;
}
/* Round if necessary so that SACKs cover only full MSSes
* and/or the remaining small portion (if present)
*/
if (pkt_len > mss) {
unsigned int new_len = (pkt_len / mss) * mss;
if (!in_sack && new_len < pkt_len) {
new_len += mss;
if (new_len >= skb->len)
return 0;
}
pkt_len = new_len;
}
err = tcp_fragment(sk, skb, pkt_len, mss);
if (err < 0)
return err;
}
return in_sack;
}
/* Mark the given newly-SACKed range as such, adjusting counters and hints. */
static u8 tcp_sacktag_one(struct sock *sk,
struct tcp_sacktag_state *state, u8 sacked,
u32 start_seq, u32 end_seq,
bool dup_sack, int pcount)
{
struct tcp_sock *tp = tcp_sk(sk);
int fack_count = state->fack_count;
/* Account D-SACK for retransmitted packet. */
if (dup_sack && (sacked & TCPCB_RETRANS)) {
if (tp->undo_marker && tp->undo_retrans > 0 &&
after(end_seq, tp->undo_marker))
tp->undo_retrans--;
if (sacked & TCPCB_SACKED_ACKED)
state->reord = min(fack_count, state->reord);
}
/* Nothing to do; acked frame is about to be dropped (was ACKed). */
if (!after(end_seq, tp->snd_una))
return sacked;
if (!(sacked & TCPCB_SACKED_ACKED)) {
if (sacked & TCPCB_SACKED_RETRANS) {
/* If the segment is not tagged as lost,
* we do not clear RETRANS, believing
* that retransmission is still in flight.
*/
if (sacked & TCPCB_LOST) {
sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
tp->lost_out -= pcount;
tp->retrans_out -= pcount;
}
} else {
if (!(sacked & TCPCB_RETRANS)) {
/* New sack for not retransmitted frame,
* which was in hole. It is reordering.
*/
if (before(start_seq,
tcp_highest_sack_seq(tp)))
state->reord = min(fack_count,
state->reord);
if (!after(end_seq, tp->high_seq))
state->flag |= FLAG_ORIG_SACK_ACKED;
}
if (sacked & TCPCB_LOST) {
sacked &= ~TCPCB_LOST;
tp->lost_out -= pcount;
}
}
sacked |= TCPCB_SACKED_ACKED;
state->flag |= FLAG_DATA_SACKED;
tp->sacked_out += pcount;
fack_count += pcount;
/* Lost marker hint past SACKed? Tweak RFC3517 cnt */
if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) &&
before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
tp->lost_cnt_hint += pcount;
if (fack_count > tp->fackets_out)
tp->fackets_out = fack_count;
}
/* D-SACK. We can detect redundant retransmission in S|R and plain R
* frames and clear it. undo_retrans is decreased above, L|R frames
* are accounted above as well.
*/
if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
sacked &= ~TCPCB_SACKED_RETRANS;
tp->retrans_out -= pcount;
}
return sacked;
}
/* Shift newly-SACKed bytes from this skb to the immediately previous
* already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
*/
static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *skb,
struct tcp_sacktag_state *state,
unsigned int pcount, int shifted, int mss,
bool dup_sack)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *prev = tcp_write_queue_prev(sk, skb);
u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */
u32 end_seq = start_seq + shifted; /* end of newly-SACKed */
BUG_ON(!pcount);
/* Adjust counters and hints for the newly sacked sequence
* range but discard the return value since prev is already
* marked. We must tag the range first because the seq
* advancement below implicitly advances
* tcp_highest_sack_seq() when skb is highest_sack.
*/
tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
start_seq, end_seq, dup_sack, pcount);
if (skb == tp->lost_skb_hint)
tp->lost_cnt_hint += pcount;
TCP_SKB_CB(prev)->end_seq += shifted;
TCP_SKB_CB(skb)->seq += shifted;
skb_shinfo(prev)->gso_segs += pcount;
BUG_ON(skb_shinfo(skb)->gso_segs < pcount);
skb_shinfo(skb)->gso_segs -= pcount;
/* When we're adding to gso_segs == 1, gso_size will be zero,
* in theory this shouldn't be necessary but as long as DSACK
* code can come after this skb later on it's better to keep
* setting gso_size to something.
*/
if (!skb_shinfo(prev)->gso_size) {
skb_shinfo(prev)->gso_size = mss;
skb_shinfo(prev)->gso_type = sk->sk_gso_type;
}
/* CHECKME: To clear or not to clear? Mimics normal skb currently */
if (skb_shinfo(skb)->gso_segs <= 1) {
skb_shinfo(skb)->gso_size = 0;
skb_shinfo(skb)->gso_type = 0;
}
/* Difference in this won't matter, both ACKed by the same cumul. ACK */
TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
if (skb->len > 0) {
BUG_ON(!tcp_skb_pcount(skb));
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTED);
return false;
}
/* Whole SKB was eaten :-) */
if (skb == tp->retransmit_skb_hint)
tp->retransmit_skb_hint = prev;
if (skb == tp->scoreboard_skb_hint)
tp->scoreboard_skb_hint = prev;
if (skb == tp->lost_skb_hint) {
tp->lost_skb_hint = prev;
tp->lost_cnt_hint -= tcp_skb_pcount(prev);
}
TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
TCP_SKB_CB(prev)->end_seq++;
if (skb == tcp_highest_sack(sk))
tcp_advance_highest_sack(sk, skb);
tcp_unlink_write_queue(skb, sk);
sk_wmem_free_skb(sk, skb);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKMERGED);
return true;
}
/* I wish gso_size would have a bit more sane initialization than
* something-or-zero which complicates things
*/
static int tcp_skb_seglen(const struct sk_buff *skb)
{
return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
}
/* Shifting pages past head area doesn't work */
static int skb_can_shift(const struct sk_buff *skb)
{
return !skb_headlen(skb) && skb_is_nonlinear(skb);
}
/* Try collapsing SACK blocks spanning across multiple skbs to a single
* skb.
*/
static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
struct tcp_sacktag_state *state,
u32 start_seq, u32 end_seq,
bool dup_sack)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *prev;
int mss;
int pcount = 0;
int len;
int in_sack;
if (!sk_can_gso(sk))
goto fallback;
/* Normally R but no L won't result in plain S */
if (!dup_sack &&
(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
goto fallback;
if (!skb_can_shift(skb))
goto fallback;
/* This frame is about to be dropped (was ACKed). */
if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
goto fallback;
/* Can only happen with delayed DSACK + discard craziness */
if (unlikely(skb == tcp_write_queue_head(sk)))
goto fallback;
prev = tcp_write_queue_prev(sk, skb);
if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
goto fallback;
in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
!before(end_seq, TCP_SKB_CB(skb)->end_seq);
if (in_sack) {
len = skb->len;
pcount = tcp_skb_pcount(skb);
mss = tcp_skb_seglen(skb);
/* TODO: Fix DSACKs to not fragment already SACKed and we can
* drop this restriction as unnecessary
*/
if (mss != tcp_skb_seglen(prev))
goto fallback;
} else {
if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
goto noop;
/* CHECKME: This is non-MSS split case only?, this will
* cause skipped skbs due to advancing loop btw, original
* has that feature too
*/
if (tcp_skb_pcount(skb) <= 1)
goto noop;
in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
if (!in_sack) {
/* TODO: head merge to next could be attempted here
* if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
* though it might not be worth of the additional hassle
*
* ...we can probably just fallback to what was done
* previously. We could try merging non-SACKed ones
* as well but it probably isn't going to buy off
* because later SACKs might again split them, and
* it would make skb timestamp tracking considerably
* harder problem.
*/
goto fallback;
}
len = end_seq - TCP_SKB_CB(skb)->seq;
BUG_ON(len < 0);
BUG_ON(len > skb->len);
/* MSS boundaries should be honoured or else pcount will
* severely break even though it makes things bit trickier.
* Optimize common case to avoid most of the divides
*/
mss = tcp_skb_mss(skb);
/* TODO: Fix DSACKs to not fragment already SACKed and we can
* drop this restriction as unnecessary
*/
if (mss != tcp_skb_seglen(prev))
goto fallback;
if (len == mss) {
pcount = 1;
} else if (len < mss) {
goto noop;
} else {
pcount = len / mss;
len = pcount * mss;
}
}
/* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
goto fallback;
if (!skb_shift(prev, skb, len))
goto fallback;
if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack))
goto out;
/* Hole filled allows collapsing with the next as well, this is very
* useful when hole on every nth skb pattern happens
*/
if (prev == tcp_write_queue_tail(sk))
goto out;
skb = tcp_write_queue_next(sk, prev);
if (!skb_can_shift(skb) ||
(skb == tcp_send_head(sk)) ||
((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
(mss != tcp_skb_seglen(skb)))
goto out;
len = skb->len;
if (skb_shift(prev, skb, len)) {
pcount += tcp_skb_pcount(skb);
tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0);
}
out:
state->fack_count += pcount;
return prev;
noop:
return skb;
fallback:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
return NULL;
}
static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
struct tcp_sack_block *next_dup,
struct tcp_sacktag_state *state,
u32 start_seq, u32 end_seq,
bool dup_sack_in)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *tmp;
tcp_for_write_queue_from(skb, sk) {
int in_sack = 0;
bool dup_sack = dup_sack_in;
if (skb == tcp_send_head(sk))
break;
/* queue is in-order => we can short-circuit the walk early */
if (!before(TCP_SKB_CB(skb)->seq, end_seq))
break;
if ((next_dup != NULL) &&
before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
in_sack = tcp_match_skb_to_sack(sk, skb,
next_dup->start_seq,
next_dup->end_seq);
if (in_sack > 0)
dup_sack = true;
}
/* skb reference here is a bit tricky to get right, since
* shifting can eat and free both this skb and the next,
* so not even _safe variant of the loop is enough.
*/
if (in_sack <= 0) {
tmp = tcp_shift_skb_data(sk, skb, state,
start_seq, end_seq, dup_sack);
if (tmp != NULL) {
if (tmp != skb) {
skb = tmp;
continue;
}
in_sack = 0;
} else {
in_sack = tcp_match_skb_to_sack(sk, skb,
start_seq,
end_seq);
}
}
if (unlikely(in_sack < 0))
break;
if (in_sack) {
TCP_SKB_CB(skb)->sacked =
tcp_sacktag_one(sk,
state,
TCP_SKB_CB(skb)->sacked,
TCP_SKB_CB(skb)->seq,
TCP_SKB_CB(skb)->end_seq,
dup_sack,
tcp_skb_pcount(skb));
if (!before(TCP_SKB_CB(skb)->seq,
tcp_highest_sack_seq(tp)))
tcp_advance_highest_sack(sk, skb);
}
state->fack_count += tcp_skb_pcount(skb);
}
return skb;
}
/* Avoid all extra work that is being done by sacktag while walking in
* a normal way
*/
static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
struct tcp_sacktag_state *state,
u32 skip_to_seq)
{
tcp_for_write_queue_from(skb, sk) {
if (skb == tcp_send_head(sk))
break;
if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq))
break;
state->fack_count += tcp_skb_pcount(skb);
}
return skb;
}
static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
struct sock *sk,
struct tcp_sack_block *next_dup,
struct tcp_sacktag_state *state,
u32 skip_to_seq)
{
if (next_dup == NULL)
return skb;
if (before(next_dup->start_seq, skip_to_seq)) {
skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq);
skb = tcp_sacktag_walk(skb, sk, NULL, state,
next_dup->start_seq, next_dup->end_seq,
1);
}
return skb;
}
static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
{
return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
}
static int
tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
u32 prior_snd_una)
{
struct tcp_sock *tp = tcp_sk(sk);
const unsigned char *ptr = (skb_transport_header(ack_skb) +
TCP_SKB_CB(ack_skb)->sacked);
struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
struct tcp_sack_block sp[TCP_NUM_SACKS];
struct tcp_sack_block *cache;
struct tcp_sacktag_state state;
struct sk_buff *skb;
int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
int used_sacks;
bool found_dup_sack = false;
int i, j;
int first_sack_index;
state.flag = 0;
state.reord = tp->packets_out;
if (!tp->sacked_out) {
if (WARN_ON(tp->fackets_out))
tp->fackets_out = 0;
tcp_highest_sack_reset(sk);
}
found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
num_sacks, prior_snd_una);
if (found_dup_sack)
state.flag |= FLAG_DSACKING_ACK;
/* Eliminate too old ACKs, but take into
* account more or less fresh ones, they can
* contain valid SACK info.
*/
if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
return 0;
if (!tp->packets_out)
goto out;
used_sacks = 0;
first_sack_index = 0;
for (i = 0; i < num_sacks; i++) {
bool dup_sack = !i && found_dup_sack;
sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
if (!tcp_is_sackblock_valid(tp, dup_sack,
sp[used_sacks].start_seq,
sp[used_sacks].end_seq)) {
int mib_idx;
if (dup_sack) {
if (!tp->undo_marker)
mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
else
mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
} else {
/* Don't count olds caused by ACK reordering */
if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
!after(sp[used_sacks].end_seq, tp->snd_una))
continue;
mib_idx = LINUX_MIB_TCPSACKDISCARD;
}
NET_INC_STATS_BH(sock_net(sk), mib_idx);
if (i == 0)
first_sack_index = -1;
continue;
}
/* Ignore very old stuff early */
if (!after(sp[used_sacks].end_seq, prior_snd_una))
continue;
used_sacks++;
}
/* order SACK blocks to allow in order walk of the retrans queue */
for (i = used_sacks - 1; i > 0; i--) {
for (j = 0; j < i; j++) {
if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
swap(sp[j], sp[j + 1]);
/* Track where the first SACK block goes to */
if (j == first_sack_index)
first_sack_index = j + 1;
}
}
}
skb = tcp_write_queue_head(sk);
state.fack_count = 0;
i = 0;
if (!tp->sacked_out) {
/* It's already past, so skip checking against it */
cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
} else {
cache = tp->recv_sack_cache;
/* Skip empty blocks in at head of the cache */
while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
!cache->end_seq)
cache++;
}
while (i < used_sacks) {
u32 start_seq = sp[i].start_seq;
u32 end_seq = sp[i].end_seq;
bool dup_sack = (found_dup_sack && (i == first_sack_index));
struct tcp_sack_block *next_dup = NULL;
if (found_dup_sack && ((i + 1) == first_sack_index))
next_dup = &sp[i + 1];
/* Skip too early cached blocks */
while (tcp_sack_cache_ok(tp, cache) &&
!before(start_seq, cache->end_seq))
cache++;
/* Can skip some work by looking recv_sack_cache? */
if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
after(end_seq, cache->start_seq)) {
/* Head todo? */
if (before(start_seq, cache->start_seq)) {
skb = tcp_sacktag_skip(skb, sk, &state,
start_seq);
skb = tcp_sacktag_walk(skb, sk, next_dup,
&state,
start_seq,
cache->start_seq,
dup_sack);
}
/* Rest of the block already fully processed? */
if (!after(end_seq, cache->end_seq))
goto advance_sp;
skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
&state,
cache->end_seq);
/* ...tail remains todo... */
if (tcp_highest_sack_seq(tp) == cache->end_seq) {
/* ...but better entrypoint exists! */
skb = tcp_highest_sack(sk);
if (skb == NULL)
break;
state.fack_count = tp->fackets_out;
cache++;
goto walk;
}
skb = tcp_sacktag_skip(skb, sk, &state, cache->end_seq);
/* Check overlap against next cached too (past this one already) */
cache++;
continue;
}
if (!before(start_seq, tcp_highest_sack_seq(tp))) {
skb = tcp_highest_sack(sk);
if (skb == NULL)
break;
state.fack_count = tp->fackets_out;
}
skb = tcp_sacktag_skip(skb, sk, &state, start_seq);
walk:
skb = tcp_sacktag_walk(skb, sk, next_dup, &state,
start_seq, end_seq, dup_sack);
advance_sp:
i++;
}
/* Clear the head of the cache sack blocks so we can skip it next time */
for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
tp->recv_sack_cache[i].start_seq = 0;
tp->recv_sack_cache[i].end_seq = 0;
}
for (j = 0; j < used_sacks; j++)
tp->recv_sack_cache[i++] = sp[j];
tcp_mark_lost_retrans(sk);
tcp_verify_left_out(tp);
if ((state.reord < tp->fackets_out) &&
((inet_csk(sk)->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker))
tcp_update_reordering(sk, tp->fackets_out - state.reord, 0);
out:
#if FASTRETRANS_DEBUG > 0
WARN_ON((int)tp->sacked_out < 0);
WARN_ON((int)tp->lost_out < 0);
WARN_ON((int)tp->retrans_out < 0);
WARN_ON((int)tcp_packets_in_flight(tp) < 0);
#endif
return state.flag;
}
/* Limits sacked_out so that sum with lost_out isn't ever larger than
* packets_out. Returns false if sacked_out adjustement wasn't necessary.
*/
static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
{
u32 holes;
holes = max(tp->lost_out, 1U);
holes = min(holes, tp->packets_out);
if ((tp->sacked_out + holes) > tp->packets_out) {
tp->sacked_out = tp->packets_out - holes;
return true;
}
return false;
}
/* If we receive more dupacks than we expected counting segments
* in assumption of absent reordering, interpret this as reordering.
* The only another reason could be bug in receiver TCP.
*/
static void tcp_check_reno_reordering(struct sock *sk, const int addend)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tcp_limit_reno_sacked(tp))
tcp_update_reordering(sk, tp->packets_out + addend, 0);
}
/* Emulate SACKs for SACKless connection: account for a new dupack. */
static void tcp_add_reno_sack(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
tp->sacked_out++;
tcp_check_reno_reordering(sk, 0);
tcp_verify_left_out(tp);
}
/* Account for ACK, ACKing some data in Reno Recovery phase. */
static void tcp_remove_reno_sacks(struct sock *sk, int acked)
{
struct tcp_sock *tp = tcp_sk(sk);
if (acked > 0) {
/* One ACK acked hole. The rest eat duplicate ACKs. */
if (acked - 1 >= tp->sacked_out)
tp->sacked_out = 0;
else
tp->sacked_out -= acked - 1;
}
tcp_check_reno_reordering(sk, acked);
tcp_verify_left_out(tp);
}
static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
{
tp->sacked_out = 0;
}
static void tcp_clear_retrans_partial(struct tcp_sock *tp)
{
tp->retrans_out = 0;
tp->lost_out = 0;
tp->undo_marker = 0;
tp->undo_retrans = -1;
}
void tcp_clear_retrans(struct tcp_sock *tp)
{
tcp_clear_retrans_partial(tp);
tp->fackets_out = 0;
tp->sacked_out = 0;
}
/* Enter Loss state. If "how" is not zero, forget all SACK information
* and reset tags completely, otherwise preserve SACKs. If receiver
* dropped its ofo queue, we will know this due to reneging detection.
*/
void tcp_enter_loss(struct sock *sk, int how)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
bool new_recovery = false;
/* Reduce ssthresh if it has not yet been made inside this window. */
if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
!after(tp->high_seq, tp->snd_una) ||
(icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
new_recovery = true;
tp->prior_ssthresh = tcp_current_ssthresh(sk);
tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
tcp_ca_event(sk, CA_EVENT_LOSS);
}
tp->snd_cwnd = 1;
tp->snd_cwnd_cnt = 0;
tp->snd_cwnd_stamp = tcp_time_stamp;
tcp_clear_retrans_partial(tp);
if (tcp_is_reno(tp))
tcp_reset_reno_sack(tp);
tp->undo_marker = tp->snd_una;
if (how) {
tp->sacked_out = 0;
tp->fackets_out = 0;
}
tcp_clear_all_retrans_hints(tp);
tcp_for_write_queue(skb, sk) {
if (skb == tcp_send_head(sk))
break;
if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
tp->undo_marker = 0;
TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
tp->lost_out += tcp_skb_pcount(skb);
tp->retransmit_high = TCP_SKB_CB(skb)->end_seq;
}
}
tcp_verify_left_out(tp);
tp->reordering = min_t(unsigned int, tp->reordering,
sysctl_tcp_reordering);
tcp_set_ca_state(sk, TCP_CA_Loss);
tp->high_seq = tp->snd_nxt;
TCP_ECN_queue_cwr(tp);
/* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
* loss recovery is underway except recurring timeout(s) on
* the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
*/
tp->frto = sysctl_tcp_frto &&
(new_recovery || icsk->icsk_retransmits) &&
!inet_csk(sk)->icsk_mtup.probe_size;
}
/* If ACK arrived pointing to a remembered SACK, it means that our
* remembered SACKs do not reflect real state of receiver i.e.
* receiver _host_ is heavily congested (or buggy).
*
* Do processing similar to RTO timeout.
*/
static bool tcp_check_sack_reneging(struct sock *sk, int flag)
{
if (flag & FLAG_SACK_RENEGING) {
struct inet_connection_sock *icsk = inet_csk(sk);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
tcp_enter_loss(sk, 1);
icsk->icsk_retransmits++;
tcp_retransmit_skb(sk, tcp_write_queue_head(sk));
inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
icsk->icsk_rto, TCP_RTO_MAX);
return true;
}
return false;
}
static inline int tcp_fackets_out(const struct tcp_sock *tp)
{
return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out;
}
/* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
* counter when SACK is enabled (without SACK, sacked_out is used for
* that purpose).
*
* Instead, with FACK TCP uses fackets_out that includes both SACKed
* segments up to the highest received SACK block so far and holes in
* between them.
*
* With reordering, holes may still be in flight, so RFC3517 recovery
* uses pure sacked_out (total number of SACKed segments) even though
* it violates the RFC that uses duplicate ACKs, often these are equal
* but when e.g. out-of-window ACKs or packet duplication occurs,
* they differ. Since neither occurs due to loss, TCP should really
* ignore them.
*/
static inline int tcp_dupack_heuristics(const struct tcp_sock *tp)
{
return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1;
}
static bool tcp_pause_early_retransmit(struct sock *sk, int flag)
{
struct tcp_sock *tp = tcp_sk(sk);
unsigned long delay;
/* Delay early retransmit and entering fast recovery for
* max(RTT/4, 2msec) unless ack has ECE mark, no RTT samples
* available, or RTO is scheduled to fire first.
*/
if (sysctl_tcp_early_retrans < 2 || sysctl_tcp_early_retrans > 3 ||
(flag & FLAG_ECE) || !tp->srtt)
return false;
delay = max_t(unsigned long, (tp->srtt >> 5), msecs_to_jiffies(2));
if (!time_after(inet_csk(sk)->icsk_timeout, (jiffies + delay)))
return false;
inet_csk_reset_xmit_timer(sk, ICSK_TIME_EARLY_RETRANS, delay,
TCP_RTO_MAX);
return true;
}
static inline int tcp_skb_timedout(const struct sock *sk,
const struct sk_buff *skb)
{
return tcp_time_stamp - TCP_SKB_CB(skb)->when > inet_csk(sk)->icsk_rto;
}
static inline int tcp_head_timedout(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
return tp->packets_out &&
tcp_skb_timedout(sk, tcp_write_queue_head(sk));
}
/* Linux NewReno/SACK/FACK/ECN state machine.
* --------------------------------------
*
* "Open" Normal state, no dubious events, fast path.
* "Disorder" In all the respects it is "Open",
* but requires a bit more attention. It is entered when
* we see some SACKs or dupacks. It is split of "Open"
* mainly to move some processing from fast path to slow one.
* "CWR" CWND was reduced due to some Congestion Notification event.
* It can be ECN, ICMP source quench, local device congestion.
* "Recovery" CWND was reduced, we are fast-retransmitting.
* "Loss" CWND was reduced due to RTO timeout or SACK reneging.
*
* tcp_fastretrans_alert() is entered:
* - each incoming ACK, if state is not "Open"
* - when arrived ACK is unusual, namely:
* * SACK
* * Duplicate ACK.
* * ECN ECE.
*
* Counting packets in flight is pretty simple.
*
* in_flight = packets_out - left_out + retrans_out
*
* packets_out is SND.NXT-SND.UNA counted in packets.
*
* retrans_out is number of retransmitted segments.
*
* left_out is number of segments left network, but not ACKed yet.
*
* left_out = sacked_out + lost_out
*
* sacked_out: Packets, which arrived to receiver out of order
* and hence not ACKed. With SACKs this number is simply
* amount of SACKed data. Even without SACKs
* it is easy to give pretty reliable estimate of this number,
* counting duplicate ACKs.
*
* lost_out: Packets lost by network. TCP has no explicit
* "loss notification" feedback from network (for now).
* It means that this number can be only _guessed_.
* Actually, it is the heuristics to predict lossage that
* distinguishes different algorithms.
*
* F.e. after RTO, when all the queue is considered as lost,
* lost_out = packets_out and in_flight = retrans_out.
*
* Essentially, we have now two algorithms counting
* lost packets.
*
* FACK: It is the simplest heuristics. As soon as we decided
* that something is lost, we decide that _all_ not SACKed
* packets until the most forward SACK are lost. I.e.
* lost_out = fackets_out - sacked_out and left_out = fackets_out.
* It is absolutely correct estimate, if network does not reorder
* packets. And it loses any connection to reality when reordering
* takes place. We use FACK by default until reordering
* is suspected on the path to this destination.
*
* NewReno: when Recovery is entered, we assume that one segment
* is lost (classic Reno). While we are in Recovery and
* a partial ACK arrives, we assume that one more packet
* is lost (NewReno). This heuristics are the same in NewReno
* and SACK.
*
* Imagine, that's all! Forget about all this shamanism about CWND inflation
* deflation etc. CWND is real congestion window, never inflated, changes
* only according to classic VJ rules.
*
* Really tricky (and requiring careful tuning) part of algorithm
* is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
* The first determines the moment _when_ we should reduce CWND and,
* hence, slow down forward transmission. In fact, it determines the moment
* when we decide that hole is caused by loss, rather than by a reorder.
*
* tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
* holes, caused by lost packets.
*
* And the most logically complicated part of algorithm is undo
* heuristics. We detect false retransmits due to both too early
* fast retransmit (reordering) and underestimated RTO, analyzing
* timestamps and D-SACKs. When we detect that some segments were
* retransmitted by mistake and CWND reduction was wrong, we undo
* window reduction and abort recovery phase. This logic is hidden
* inside several functions named tcp_try_undo_<something>.
*/
/* This function decides, when we should leave Disordered state
* and enter Recovery phase, reducing congestion window.
*
* Main question: may we further continue forward transmission
* with the same cwnd?
*/
static bool tcp_time_to_recover(struct sock *sk, int flag)
{
struct tcp_sock *tp = tcp_sk(sk);
__u32 packets_out;
/* Trick#1: The loss is proven. */
if (tp->lost_out)
return true;
/* Not-A-Trick#2 : Classic rule... */
if (tcp_dupack_heuristics(tp) > tp->reordering)
return true;
/* Trick#3 : when we use RFC2988 timer restart, fast
* retransmit can be triggered by timeout of queue head.
*/
if (tcp_is_fack(tp) && tcp_head_timedout(sk))
return true;
/* Trick#4: It is still not OK... But will it be useful to delay
* recovery more?
*/
packets_out = tp->packets_out;
if (packets_out <= tp->reordering &&
tp->sacked_out >= max_t(__u32, packets_out/2, sysctl_tcp_reordering) &&
!tcp_may_send_now(sk)) {
/* We have nothing to send. This connection is limited
* either by receiver window or by application.
*/
return true;
}
/* If a thin stream is detected, retransmit after first
* received dupack. Employ only if SACK is supported in order
* to avoid possible corner-case series of spurious retransmissions
* Use only if there are no unsent data.
*/
if ((tp->thin_dupack || sysctl_tcp_thin_dupack) &&
tcp_stream_is_thin(tp) && tcp_dupack_heuristics(tp) > 1 &&
tcp_is_sack(tp) && !tcp_send_head(sk))
return true;
/* Trick#6: TCP early retransmit, per RFC5827. To avoid spurious
* retransmissions due to small network reorderings, we implement
* Mitigation A.3 in the RFC and delay the retransmission for a short
* interval if appropriate.
*/
if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out &&
(tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) &&
!tcp_may_send_now(sk))
return !tcp_pause_early_retransmit(sk, flag);
return false;
}
/* New heuristics: it is possible only after we switched to restart timer
* each time when something is ACKed. Hence, we can detect timed out packets
* during fast retransmit without falling to slow start.
*
* Usefulness of this as is very questionable, since we should know which of
* the segments is the next to timeout which is relatively expensive to find
* in general case unless we add some data structure just for that. The
* current approach certainly won't find the right one too often and when it
* finally does find _something_ it usually marks large part of the window
* right away (because a retransmission with a larger timestamp blocks the
* loop from advancing). -ij
*/
static void tcp_timeout_skbs(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
if (!tcp_is_fack(tp) || !tcp_head_timedout(sk))
return;
skb = tp->scoreboard_skb_hint;
if (tp->scoreboard_skb_hint == NULL)
skb = tcp_write_queue_head(sk);
tcp_for_write_queue_from(skb, sk) {
if (skb == tcp_send_head(sk))
break;
if (!tcp_skb_timedout(sk, skb))
break;
tcp_skb_mark_lost(tp, skb);
}
tp->scoreboard_skb_hint = skb;
tcp_verify_left_out(tp);
}
/* Detect loss in event "A" above by marking head of queue up as lost.
* For FACK or non-SACK(Reno) senders, the first "packets" number of segments
* are considered lost. For RFC3517 SACK, a segment is considered lost if it
* has at least tp->reordering SACKed seqments above it; "packets" refers to
* the maximum SACKed segments to pass before reaching this limit.
*/
static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
int cnt, oldcnt;
int err;
unsigned int mss;
/* Use SACK to deduce losses of new sequences sent during recovery */
const u32 loss_high = tcp_is_sack(tp) ? tp->snd_nxt : tp->high_seq;
WARN_ON(packets > tp->packets_out);
if (tp->lost_skb_hint) {
skb = tp->lost_skb_hint;
cnt = tp->lost_cnt_hint;
/* Head already handled? */
if (mark_head && skb != tcp_write_queue_head(sk))
return;
} else {
skb = tcp_write_queue_head(sk);
cnt = 0;
}
tcp_for_write_queue_from(skb, sk) {
if (skb == tcp_send_head(sk))
break;
/* TODO: do this better */
/* this is not the most efficient way to do this... */
tp->lost_skb_hint = skb;
tp->lost_cnt_hint = cnt;
if (after(TCP_SKB_CB(skb)->end_seq, loss_high))
break;
oldcnt = cnt;
if (tcp_is_fack(tp) || tcp_is_reno(tp) ||
(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
cnt += tcp_skb_pcount(skb);
if (cnt > packets) {
if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) ||
(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
(oldcnt >= packets))
break;
mss = skb_shinfo(skb)->gso_size;
err = tcp_fragment(sk, skb, (packets - oldcnt) * mss, mss);
if (err < 0)
break;
cnt = packets;
}
tcp_skb_mark_lost(tp, skb);
if (mark_head)
break;
}
tcp_verify_left_out(tp);
}
/* Account newly detected lost packet(s) */
static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tcp_is_reno(tp)) {
tcp_mark_head_lost(sk, 1, 1);
} else if (tcp_is_fack(tp)) {
int lost = tp->fackets_out - tp->reordering;
if (lost <= 0)
lost = 1;
tcp_mark_head_lost(sk, lost, 0);
} else {
int sacked_upto = tp->sacked_out - tp->reordering;
if (sacked_upto >= 0)
tcp_mark_head_lost(sk, sacked_upto, 0);
else if (fast_rexmit)
tcp_mark_head_lost(sk, 1, 1);
}
tcp_timeout_skbs(sk);
}
/* CWND moderation, preventing bursts due to too big ACKs
* in dubious situations.
*/
static inline void tcp_moderate_cwnd(struct tcp_sock *tp)
{
tp->snd_cwnd = min(tp->snd_cwnd,
tcp_packets_in_flight(tp) + tcp_max_burst(tp));
tp->snd_cwnd_stamp = tcp_time_stamp;
}
/* Nothing was retransmitted or returned timestamp is less
* than timestamp of the first retransmission.
*/
static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
{
return !tp->retrans_stamp ||
(tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
before(tp->rx_opt.rcv_tsecr, tp->retrans_stamp));
}
/* Undo procedures. */
#if FASTRETRANS_DEBUG > 1
static void DBGUNDO(struct sock *sk, const char *msg)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
if (sk->sk_family == AF_INET) {
pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
msg,
&inet->inet_daddr, ntohs(inet->inet_dport),
tp->snd_cwnd, tcp_left_out(tp),
tp->snd_ssthresh, tp->prior_ssthresh,
tp->packets_out);
}
#if IS_ENABLED(CONFIG_IPV6)
else if (sk->sk_family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
msg,
&np->daddr, ntohs(inet->inet_dport),
tp->snd_cwnd, tcp_left_out(tp),
tp->snd_ssthresh, tp->prior_ssthresh,
tp->packets_out);
}
#endif
}
#else
#define DBGUNDO(x...) do { } while (0)
#endif
static void tcp_undo_cwr(struct sock *sk, const bool undo_ssthresh)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tp->prior_ssthresh) {
const struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_ca_ops->undo_cwnd)
tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
else
tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1);
if (undo_ssthresh && tp->prior_ssthresh > tp->snd_ssthresh) {
tp->snd_ssthresh = tp->prior_ssthresh;
TCP_ECN_withdraw_cwr(tp);
}
} else {
tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
}
tp->snd_cwnd_stamp = tcp_time_stamp;
}
static inline bool tcp_may_undo(const struct tcp_sock *tp)
{
return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
}
/* People celebrate: "We love our President!" */
static bool tcp_try_undo_recovery(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tcp_may_undo(tp)) {
int mib_idx;
/* Happy end! We did not retransmit anything
* or our original transmission succeeded.
*/
DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
tcp_undo_cwr(sk, true);
if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
mib_idx = LINUX_MIB_TCPLOSSUNDO;
else
mib_idx = LINUX_MIB_TCPFULLUNDO;
NET_INC_STATS_BH(sock_net(sk), mib_idx);
tp->undo_marker = 0;
}
if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
/* Hold old state until something *above* high_seq
* is ACKed. For Reno it is MUST to prevent false
* fast retransmits (RFC2582). SACK TCP is safe. */
tcp_moderate_cwnd(tp);
return true;
}
tcp_set_ca_state(sk, TCP_CA_Open);
return false;
}
/* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
static void tcp_try_undo_dsack(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tp->undo_marker && !tp->undo_retrans) {
DBGUNDO(sk, "D-SACK");
tcp_undo_cwr(sk, true);
tp->undo_marker = 0;
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
}
}
/* We can clear retrans_stamp when there are no retransmissions in the
* window. It would seem that it is trivially available for us in
* tp->retrans_out, however, that kind of assumptions doesn't consider
* what will happen if errors occur when sending retransmission for the
* second time. ...It could the that such segment has only
* TCPCB_EVER_RETRANS set at the present time. It seems that checking
* the head skb is enough except for some reneging corner cases that
* are not worth the effort.
*
* Main reason for all this complexity is the fact that connection dying
* time now depends on the validity of the retrans_stamp, in particular,
* that successive retransmissions of a segment must not advance
* retrans_stamp under any conditions.
*/
static bool tcp_any_retrans_done(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
if (tp->retrans_out)
return true;
skb = tcp_write_queue_head(sk);
if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
return true;
return false;
}
/* Undo during fast recovery after partial ACK. */
static int tcp_try_undo_partial(struct sock *sk, int acked)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Partial ACK arrived. Force Hoe's retransmit. */
int failed = tcp_is_reno(tp) || (tcp_fackets_out(tp) > tp->reordering);
if (tcp_may_undo(tp)) {
/* Plain luck! Hole if filled with delayed
* packet, rather than with a retransmit.
*/
if (!tcp_any_retrans_done(sk))
tp->retrans_stamp = 0;
tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1);
DBGUNDO(sk, "Hoe");
tcp_undo_cwr(sk, false);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
/* So... Do not make Hoe's retransmit yet.
* If the first packet was delayed, the rest
* ones are most probably delayed as well.
*/
failed = 0;
}
return failed;
}
/* Undo during loss recovery after partial ACK or using F-RTO. */
static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
{
struct tcp_sock *tp = tcp_sk(sk);
if (frto_undo || tcp_may_undo(tp)) {
struct sk_buff *skb;
tcp_for_write_queue(skb, sk) {
if (skb == tcp_send_head(sk))
break;
TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
}
tcp_clear_all_retrans_hints(tp);
DBGUNDO(sk, "partial loss");
tp->lost_out = 0;
tcp_undo_cwr(sk, true);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
if (frto_undo)
NET_INC_STATS_BH(sock_net(sk),
LINUX_MIB_TCPSPURIOUSRTOS);
inet_csk(sk)->icsk_retransmits = 0;
tp->undo_marker = 0;
if (frto_undo || tcp_is_sack(tp))
tcp_set_ca_state(sk, TCP_CA_Open);
return true;
}
return false;
}
/* The cwnd reduction in CWR and Recovery use the PRR algorithm
* https://datatracker.ietf.org/doc/draft-ietf-tcpm-proportional-rate-reduction/
* It computes the number of packets to send (sndcnt) based on packets newly
* delivered:
* 1) If the packets in flight is larger than ssthresh, PRR spreads the
* cwnd reductions across a full RTT.
* 2) If packets in flight is lower than ssthresh (such as due to excess
* losses and/or application stalls), do not perform any further cwnd
* reductions, but instead slow start up to ssthresh.
*/
static void tcp_init_cwnd_reduction(struct sock *sk, const bool set_ssthresh)
{
struct tcp_sock *tp = tcp_sk(sk);
tp->high_seq = tp->snd_nxt;
tp->tlp_high_seq = 0;
tp->snd_cwnd_cnt = 0;
tp->prior_cwnd = tp->snd_cwnd;
tp->prr_delivered = 0;
tp->prr_out = 0;
if (set_ssthresh)
tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
TCP_ECN_queue_cwr(tp);
}
static void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked,
int fast_rexmit)
{
struct tcp_sock *tp = tcp_sk(sk);
int sndcnt = 0;
int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
tp->prr_delivered += newly_acked_sacked;
if (tcp_packets_in_flight(tp) > tp->snd_ssthresh) {
u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
tp->prior_cwnd - 1;
sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
} else {
sndcnt = min_t(int, delta,
max_t(int, tp->prr_delivered - tp->prr_out,
newly_acked_sacked) + 1);
}
sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));
tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
}
static inline void tcp_end_cwnd_reduction(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR ||
(tp->undo_marker && tp->snd_ssthresh < TCP_INFINITE_SSTHRESH)) {
tp->snd_cwnd = tp->snd_ssthresh;
tp->snd_cwnd_stamp = tcp_time_stamp;
}
tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
}
/* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
void tcp_enter_cwr(struct sock *sk, const int set_ssthresh)
{
struct tcp_sock *tp = tcp_sk(sk);
tp->prior_ssthresh = 0;
if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
tp->undo_marker = 0;
tcp_init_cwnd_reduction(sk, set_ssthresh);
tcp_set_ca_state(sk, TCP_CA_CWR);
}
}
static void tcp_try_keep_open(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
int state = TCP_CA_Open;
if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
state = TCP_CA_Disorder;
if (inet_csk(sk)->icsk_ca_state != state) {
tcp_set_ca_state(sk, state);
tp->high_seq = tp->snd_nxt;
}
}
static void tcp_try_to_open(struct sock *sk, int flag, int newly_acked_sacked)
{
struct tcp_sock *tp = tcp_sk(sk);
tcp_verify_left_out(tp);
if (!tcp_any_retrans_done(sk))
tp->retrans_stamp = 0;
if (flag & FLAG_ECE)
tcp_enter_cwr(sk, 1);
if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
tcp_try_keep_open(sk);
if (inet_csk(sk)->icsk_ca_state != TCP_CA_Open)
tcp_moderate_cwnd(tp);
} else {
tcp_cwnd_reduction(sk, newly_acked_sacked, 0);
}
}
static void tcp_mtup_probe_failed(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
icsk->icsk_mtup.probe_size = 0;
}
static void tcp_mtup_probe_success(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
/* FIXME: breaks with very large cwnd */
tp->prior_ssthresh = tcp_current_ssthresh(sk);
tp->snd_cwnd = tp->snd_cwnd *
tcp_mss_to_mtu(sk, tp->mss_cache) /
icsk->icsk_mtup.probe_size;
tp->snd_cwnd_cnt = 0;
tp->snd_cwnd_stamp = tcp_time_stamp;
tp->snd_ssthresh = tcp_current_ssthresh(sk);
icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
icsk->icsk_mtup.probe_size = 0;
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
}
/* Do a simple retransmit without using the backoff mechanisms in
* tcp_timer. This is used for path mtu discovery.
* The socket is already locked here.
*/
void tcp_simple_retransmit(struct sock *sk)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
unsigned int mss = tcp_current_mss(sk);
u32 prior_lost = tp->lost_out;
tcp_for_write_queue(skb, sk) {
if (skb == tcp_send_head(sk))
break;
if (tcp_skb_seglen(skb) > mss &&
!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
tp->retrans_out -= tcp_skb_pcount(skb);
}
tcp_skb_mark_lost_uncond_verify(tp, skb);
}
}
tcp_clear_retrans_hints_partial(tp);
if (prior_lost == tp->lost_out)
return;
if (tcp_is_reno(tp))
tcp_limit_reno_sacked(tp);
tcp_verify_left_out(tp);
/* Don't muck with the congestion window here.
* Reason is that we do not increase amount of _data_
* in network, but units changed and effective
* cwnd/ssthresh really reduced now.
*/
if (icsk->icsk_ca_state != TCP_CA_Loss) {
tp->high_seq = tp->snd_nxt;
tp->snd_ssthresh = tcp_current_ssthresh(sk);
tp->prior_ssthresh = 0;
tp->undo_marker = 0;
tcp_set_ca_state(sk, TCP_CA_Loss);
}
tcp_xmit_retransmit_queue(sk);
}
EXPORT_SYMBOL(tcp_simple_retransmit);
static void tcp_enter_recovery(struct sock *sk, bool ece_ack)
{
struct tcp_sock *tp = tcp_sk(sk);
int mib_idx;
if (tcp_is_reno(tp))
mib_idx = LINUX_MIB_TCPRENORECOVERY;
else
mib_idx = LINUX_MIB_TCPSACKRECOVERY;
NET_INC_STATS_BH(sock_net(sk), mib_idx);
tp->prior_ssthresh = 0;
tp->undo_marker = tp->snd_una;
tp->undo_retrans = tp->retrans_out ? : -1;
if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
if (!ece_ack)
tp->prior_ssthresh = tcp_current_ssthresh(sk);
tcp_init_cwnd_reduction(sk, true);
}
tcp_set_ca_state(sk, TCP_CA_Recovery);
}
/* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
* recovered or spurious. Otherwise retransmits more on partial ACKs.
*/
static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
bool recovered = !before(tp->snd_una, tp->high_seq);
if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
/* Step 3.b. A timeout is spurious if not all data are
* lost, i.e., never-retransmitted data are (s)acked.
*/
if (tcp_try_undo_loss(sk, flag & FLAG_ORIG_SACK_ACKED))
return;
if (after(tp->snd_nxt, tp->high_seq) &&
(flag & FLAG_DATA_SACKED || is_dupack)) {
tp->frto = 0; /* Loss was real: 2nd part of step 3.a */
} else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
tp->high_seq = tp->snd_nxt;
__tcp_push_pending_frames(sk, tcp_current_mss(sk),
TCP_NAGLE_OFF);
if (after(tp->snd_nxt, tp->high_seq))
return; /* Step 2.b */
tp->frto = 0;
}
}
if (recovered) {
/* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
icsk->icsk_retransmits = 0;
tcp_try_undo_recovery(sk);
return;
}
if (flag & FLAG_DATA_ACKED)
icsk->icsk_retransmits = 0;
if (tcp_is_reno(tp)) {
/* A Reno DUPACK means new data in F-RTO step 2.b above are
* delivered. Lower inflight to clock out (re)tranmissions.
*/
if (after(tp->snd_nxt, tp->high_seq) && is_dupack)
tcp_add_reno_sack(sk);
else if (flag & FLAG_SND_UNA_ADVANCED)
tcp_reset_reno_sack(tp);
}
if (tcp_try_undo_loss(sk, false))
return;
tcp_xmit_retransmit_queue(sk);
}
/* Process an event, which can update packets-in-flight not trivially.
* Main goal of this function is to calculate new estimate for left_out,
* taking into account both packets sitting in receiver's buffer and
* packets lost by network.
*
* Besides that it does CWND reduction, when packet loss is detected
* and changes state of machine.
*
* It does _not_ decide what to send, it is made in function
* tcp_xmit_retransmit_queue().
*/
static void tcp_fastretrans_alert(struct sock *sk, int pkts_acked,
int prior_sacked, int prior_packets,
bool is_dupack, int flag)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
int do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) &&
(tcp_fackets_out(tp) > tp->reordering));
int newly_acked_sacked = 0;
int fast_rexmit = 0;
if (WARN_ON(!tp->packets_out && tp->sacked_out))
tp->sacked_out = 0;
if (WARN_ON(!tp->sacked_out && tp->fackets_out))
tp->fackets_out = 0;
/* Now state machine starts.
* A. ECE, hence prohibit cwnd undoing, the reduction is required. */
if (flag & FLAG_ECE)
tp->prior_ssthresh = 0;
/* B. In all the states check for reneging SACKs. */
if (tcp_check_sack_reneging(sk, flag))
return;
/* C. Check consistency of the current state. */
tcp_verify_left_out(tp);
/* D. Check state exit conditions. State can be terminated
* when high_seq is ACKed. */
if (icsk->icsk_ca_state == TCP_CA_Open) {
WARN_ON(tp->retrans_out != 0);
tp->retrans_stamp = 0;
} else if (!before(tp->snd_una, tp->high_seq)) {
switch (icsk->icsk_ca_state) {
case TCP_CA_CWR:
/* CWR is to be held something *above* high_seq
* is ACKed for CWR bit to reach receiver. */
if (tp->snd_una != tp->high_seq) {
tcp_end_cwnd_reduction(sk);
tcp_set_ca_state(sk, TCP_CA_Open);
}
break;
case TCP_CA_Recovery:
if (tcp_is_reno(tp))
tcp_reset_reno_sack(tp);
if (tcp_try_undo_recovery(sk))
return;
tcp_end_cwnd_reduction(sk);
break;
}
}
/* E. Process state. */
switch (icsk->icsk_ca_state) {
case TCP_CA_Recovery:
if (!(flag & FLAG_SND_UNA_ADVANCED)) {
if (tcp_is_reno(tp) && is_dupack)
tcp_add_reno_sack(sk);
} else
do_lost = tcp_try_undo_partial(sk, pkts_acked);
newly_acked_sacked = prior_packets - tp->packets_out +
tp->sacked_out - prior_sacked;
break;
case TCP_CA_Loss:
tcp_process_loss(sk, flag, is_dupack);
if (icsk->icsk_ca_state != TCP_CA_Open)
return;
/* Fall through to processing in Open state. */
default:
if (tcp_is_reno(tp)) {
if (flag & FLAG_SND_UNA_ADVANCED)
tcp_reset_reno_sack(tp);
if (is_dupack)
tcp_add_reno_sack(sk);
}
newly_acked_sacked = prior_packets - tp->packets_out +
tp->sacked_out - prior_sacked;
if (icsk->icsk_ca_state <= TCP_CA_Disorder)
tcp_try_undo_dsack(sk);
if (!tcp_time_to_recover(sk, flag)) {
tcp_try_to_open(sk, flag, newly_acked_sacked);
return;
}
/* MTU probe failure: don't reduce cwnd */
if (icsk->icsk_ca_state < TCP_CA_CWR &&
icsk->icsk_mtup.probe_size &&
tp->snd_una == tp->mtu_probe.probe_seq_start) {
tcp_mtup_probe_failed(sk);
/* Restores the reduction we did in tcp_mtup_probe() */
tp->snd_cwnd++;
tcp_simple_retransmit(sk);
return;
}
/* Otherwise enter Recovery state */
tcp_enter_recovery(sk, (flag & FLAG_ECE));
fast_rexmit = 1;
}
if (do_lost || (tcp_is_fack(tp) && tcp_head_timedout(sk)))
tcp_update_scoreboard(sk, fast_rexmit);
tcp_cwnd_reduction(sk, newly_acked_sacked, fast_rexmit);
tcp_xmit_retransmit_queue(sk);
}
void tcp_valid_rtt_meas(struct sock *sk, u32 seq_rtt)
{
tcp_rtt_estimator(sk, seq_rtt);
tcp_set_rto(sk);
inet_csk(sk)->icsk_backoff = 0;
}
EXPORT_SYMBOL(tcp_valid_rtt_meas);
/* Read draft-ietf-tcplw-high-performance before mucking
* with this code. (Supersedes RFC1323)
*/
static void tcp_ack_saw_tstamp(struct sock *sk, int flag)
{
/* RTTM Rule: A TSecr value received in a segment is used to
* update the averaged RTT measurement only if the segment
* acknowledges some new data, i.e., only if it advances the
* left edge of the send window.
*
* See draft-ietf-tcplw-high-performance-00, section 3.3.
* 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
*
* Changed: reset backoff as soon as we see the first valid sample.
* If we do not, we get strongly overestimated rto. With timestamps
* samples are accepted even from very old segments: f.e., when rtt=1
* increases to 8, we retransmit 5 times and after 8 seconds delayed
* answer arrives rto becomes 120 seconds! If at least one of segments
* in window is lost... Voila. --ANK (010210)
*/
struct tcp_sock *tp = tcp_sk(sk);
tcp_valid_rtt_meas(sk, tcp_time_stamp - tp->rx_opt.rcv_tsecr);
}
static void tcp_ack_no_tstamp(struct sock *sk, u32 seq_rtt, int flag)
{
/* We don't have a timestamp. Can only use
* packets that are not retransmitted to determine
* rtt estimates. Also, we must not reset the
* backoff for rto until we get a non-retransmitted
* packet. This allows us to deal with a situation
* where the network delay has increased suddenly.
* I.e. Karn's algorithm. (SIGCOMM '87, p5.)
*/
if (flag & FLAG_RETRANS_DATA_ACKED)
return;
tcp_valid_rtt_meas(sk, seq_rtt);
}
static inline void tcp_ack_update_rtt(struct sock *sk, const int flag,
const s32 seq_rtt)
{
const struct tcp_sock *tp = tcp_sk(sk);
/* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
tcp_ack_saw_tstamp(sk, flag);
else if (seq_rtt >= 0)
tcp_ack_no_tstamp(sk, seq_rtt, flag);
}
static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 in_flight)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_ca_ops->cong_avoid(sk, ack, in_flight);
tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp;
}
/* Restart timer after forward progress on connection.
* RFC2988 recommends to restart timer to now+rto.
*/
void tcp_rearm_rto(struct sock *sk)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
/* If the retrans timer is currently being used by Fast Open
* for SYN-ACK retrans purpose, stay put.
*/
if (tp->fastopen_rsk)
return;
if (!tp->packets_out) {
inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
} else {
u32 rto = inet_csk(sk)->icsk_rto;
/* Offset the time elapsed after installing regular RTO */
if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||
icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
struct sk_buff *skb = tcp_write_queue_head(sk);
const u32 rto_time_stamp = TCP_SKB_CB(skb)->when + rto;
s32 delta = (s32)(rto_time_stamp - tcp_time_stamp);
/* delta may not be positive if the socket is locked
* when the retrans timer fires and is rescheduled.
*/
if (delta > 0)
rto = delta;
}
inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto,
TCP_RTO_MAX);
}
}
/* This function is called when the delayed ER timer fires. TCP enters
* fast recovery and performs fast-retransmit.
*/
void tcp_resume_early_retransmit(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
tcp_rearm_rto(sk);
/* Stop if ER is disabled after the delayed ER timer is scheduled */
if (!tp->do_early_retrans)
return;
tcp_enter_recovery(sk, false);
tcp_update_scoreboard(sk, 1);
tcp_xmit_retransmit_queue(sk);
}
/* If we get here, the whole TSO packet has not been acked. */
static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
u32 packets_acked;
BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
packets_acked = tcp_skb_pcount(skb);
if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
return 0;
packets_acked -= tcp_skb_pcount(skb);
if (packets_acked) {
BUG_ON(tcp_skb_pcount(skb) == 0);
BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
}
return packets_acked;
}
/* Remove acknowledged frames from the retransmission queue. If our packet
* is before the ack sequence we can discard it as it's confirmed to have
* arrived at the other end.
*/
static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets,
u32 prior_snd_una)
{
struct tcp_sock *tp = tcp_sk(sk);
const struct inet_connection_sock *icsk = inet_csk(sk);
struct sk_buff *skb;
u32 now = tcp_time_stamp;
int fully_acked = true;
int flag = 0;
u32 pkts_acked = 0;
u32 reord = tp->packets_out;
u32 prior_sacked = tp->sacked_out;
s32 seq_rtt = -1;
s32 ca_seq_rtt = -1;
ktime_t last_ackt = net_invalid_timestamp();
while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) {
struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
u32 acked_pcount;
u8 sacked = scb->sacked;
/* Determine how many packets and what bytes were acked, tso and else */
if (after(scb->end_seq, tp->snd_una)) {
if (tcp_skb_pcount(skb) == 1 ||
!after(tp->snd_una, scb->seq))
break;
acked_pcount = tcp_tso_acked(sk, skb);
if (!acked_pcount)
break;
fully_acked = false;
} else {
acked_pcount = tcp_skb_pcount(skb);
}
if (sacked & TCPCB_RETRANS) {
if (sacked & TCPCB_SACKED_RETRANS)
tp->retrans_out -= acked_pcount;
flag |= FLAG_RETRANS_DATA_ACKED;
ca_seq_rtt = -1;
seq_rtt = -1;
} else {
ca_seq_rtt = now - scb->when;
last_ackt = skb->tstamp;
if (seq_rtt < 0) {
seq_rtt = ca_seq_rtt;
}
if (!(sacked & TCPCB_SACKED_ACKED)) {
reord = min(pkts_acked, reord);
if (!after(scb->end_seq, tp->high_seq))
flag |= FLAG_ORIG_SACK_ACKED;
}
}
if (sacked & TCPCB_SACKED_ACKED)
tp->sacked_out -= acked_pcount;
if (sacked & TCPCB_LOST)
tp->lost_out -= acked_pcount;
tp->packets_out -= acked_pcount;
pkts_acked += acked_pcount;
/* Initial outgoing SYN's get put onto the write_queue
* just like anything else we transmit. It is not
* true data, and if we misinform our callers that
* this ACK acks real data, we will erroneously exit
* connection startup slow start one packet too
* quickly. This is severely frowned upon behavior.
*/
if (!(scb->tcp_flags & TCPHDR_SYN)) {
flag |= FLAG_DATA_ACKED;
} else {
flag |= FLAG_SYN_ACKED;
tp->retrans_stamp = 0;
}
if (!fully_acked)
break;
tcp_unlink_write_queue(skb, sk);
sk_wmem_free_skb(sk, skb);
tp->scoreboard_skb_hint = NULL;
if (skb == tp->retransmit_skb_hint)
tp->retransmit_skb_hint = NULL;
if (skb == tp->lost_skb_hint)
tp->lost_skb_hint = NULL;
}
if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
tp->snd_up = tp->snd_una;
if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
flag |= FLAG_SACK_RENEGING;
if (flag & FLAG_ACKED) {
const struct tcp_congestion_ops *ca_ops
= inet_csk(sk)->icsk_ca_ops;
if (unlikely(icsk->icsk_mtup.probe_size &&
!after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
tcp_mtup_probe_success(sk);
}
tcp_ack_update_rtt(sk, flag, seq_rtt);
tcp_rearm_rto(sk);
if (tcp_is_reno(tp)) {
tcp_remove_reno_sacks(sk, pkts_acked);
} else {
int delta;
/* Non-retransmitted hole got filled? That's reordering */
if (reord < prior_fackets)
tcp_update_reordering(sk, tp->fackets_out - reord, 0);
delta = tcp_is_fack(tp) ? pkts_acked :
prior_sacked - tp->sacked_out;
tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta);
}
tp->fackets_out -= min(pkts_acked, tp->fackets_out);
if (ca_ops->pkts_acked) {
s32 rtt_us = -1;
/* Is the ACK triggering packet unambiguous? */
if (!(flag & FLAG_RETRANS_DATA_ACKED)) {
/* High resolution needed and available? */
if (ca_ops->flags & TCP_CONG_RTT_STAMP &&
!ktime_equal(last_ackt,
net_invalid_timestamp()))
rtt_us = ktime_us_delta(ktime_get_real(),
last_ackt);
else if (ca_seq_rtt >= 0)
rtt_us = jiffies_to_usecs(ca_seq_rtt);
}
ca_ops->pkts_acked(sk, pkts_acked, rtt_us);
}
}
#if FASTRETRANS_DEBUG > 0
WARN_ON((int)tp->sacked_out < 0);
WARN_ON((int)tp->lost_out < 0);
WARN_ON((int)tp->retrans_out < 0);
if (!tp->packets_out && tcp_is_sack(tp)) {
icsk = inet_csk(sk);
if (tp->lost_out) {
pr_debug("Leak l=%u %d\n",
tp->lost_out, icsk->icsk_ca_state);
tp->lost_out = 0;
}
if (tp->sacked_out) {
pr_debug("Leak s=%u %d\n",
tp->sacked_out, icsk->icsk_ca_state);
tp->sacked_out = 0;
}
if (tp->retrans_out) {
pr_debug("Leak r=%u %d\n",
tp->retrans_out, icsk->icsk_ca_state);
tp->retrans_out = 0;
}
}
#endif
return flag;
}
static void tcp_ack_probe(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
/* Was it a usable window open? */
if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) {
icsk->icsk_backoff = 0;
inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
/* Socket must be waked up by subsequent tcp_data_snd_check().
* This function is not for random using!
*/
} else {
inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX),
TCP_RTO_MAX);
}
}
static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
{
return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
}
static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
{
const struct tcp_sock *tp = tcp_sk(sk);
return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
!tcp_in_cwnd_reduction(sk);
}
/* Check that window update is acceptable.
* The function assumes that snd_una<=ack<=snd_next.
*/
static inline bool tcp_may_update_window(const struct tcp_sock *tp,
const u32 ack, const u32 ack_seq,
const u32 nwin)
{
return after(ack, tp->snd_una) ||
after(ack_seq, tp->snd_wl1) ||
(ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd);
}
/* Update our send window.
*
* Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
* and in FreeBSD. NetBSD's one is even worse.) is wrong.
*/
static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
u32 ack_seq)
{
struct tcp_sock *tp = tcp_sk(sk);
int flag = 0;
u32 nwin = ntohs(tcp_hdr(skb)->window);
if (likely(!tcp_hdr(skb)->syn))
nwin <<= tp->rx_opt.snd_wscale;
if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
flag |= FLAG_WIN_UPDATE;
tcp_update_wl(tp, ack_seq);
if (tp->snd_wnd != nwin) {
tp->snd_wnd = nwin;
/* Note, it is the only place, where
* fast path is recovered for sending TCP.
*/
tp->pred_flags = 0;
tcp_fast_path_check(sk);
if (nwin > tp->max_window) {
tp->max_window = nwin;
tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
}
}
}
tp->snd_una = ack;
return flag;
}
/* RFC 5961 7 [ACK Throttling] */
static void tcp_send_challenge_ack(struct sock *sk)
{
/* unprotected vars, we dont care of overwrites */
static u32 challenge_timestamp;
static unsigned int challenge_count;
u32 now = jiffies / HZ;
if (now != challenge_timestamp) {
challenge_timestamp = now;
challenge_count = 0;
}
if (++challenge_count <= sysctl_tcp_challenge_ack_limit) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
tcp_send_ack(sk);
}
}
static void tcp_store_ts_recent(struct tcp_sock *tp)
{
tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
tp->rx_opt.ts_recent_stamp = get_seconds();
}
static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
{
if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
/* PAWS bug workaround wrt. ACK frames, the PAWS discard
* extra check below makes sure this can only happen
* for pure ACK frames. -DaveM
*
* Not only, also it occurs for expired timestamps.
*/
if (tcp_paws_check(&tp->rx_opt, 0))
tcp_store_ts_recent(tp);
}
}
/* This routine deals with acks during a TLP episode.
* Ref: loss detection algorithm in draft-dukkipati-tcpm-tcp-loss-probe.
*/
static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
{
struct tcp_sock *tp = tcp_sk(sk);
bool is_tlp_dupack = (ack == tp->tlp_high_seq) &&
!(flag & (FLAG_SND_UNA_ADVANCED |
FLAG_NOT_DUP | FLAG_DATA_SACKED));
/* Mark the end of TLP episode on receiving TLP dupack or when
* ack is after tlp_high_seq.
*/
if (is_tlp_dupack) {
tp->tlp_high_seq = 0;
return;
}
if (after(ack, tp->tlp_high_seq)) {
tp->tlp_high_seq = 0;
/* Don't reduce cwnd if DSACK arrives for TLP retrans. */
if (!(flag & FLAG_DSACKING_ACK)) {
tcp_init_cwnd_reduction(sk, true);
tcp_set_ca_state(sk, TCP_CA_CWR);
tcp_end_cwnd_reduction(sk);
tcp_try_keep_open(sk);
NET_INC_STATS_BH(sock_net(sk),
LINUX_MIB_TCPLOSSPROBERECOVERY);
}
}
}
/* This routine deals with incoming acks, but not outgoing ones. */
static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
u32 prior_snd_una = tp->snd_una;
u32 ack_seq = TCP_SKB_CB(skb)->seq;
u32 ack = TCP_SKB_CB(skb)->ack_seq;
bool is_dupack = false;
u32 prior_in_flight, prior_cwnd = tp->snd_cwnd, prior_rtt = tp->srtt;
u32 prior_fackets;
int prior_packets = tp->packets_out;
int prior_sacked = tp->sacked_out;
int pkts_acked = 0;
int previous_packets_out = 0;
/* If the ack is older than previous acks
* then we can probably ignore it.
*/
if (before(ack, prior_snd_una)) {
/* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
if (before(ack, prior_snd_una - tp->max_window)) {
tcp_send_challenge_ack(sk);
return -1;
}
goto old_ack;
}
/* If the ack includes data we haven't sent yet, discard
* this segment (RFC793 Section 3.9).
*/
if (after(ack, tp->snd_nxt))
goto invalid_ack;
if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||
icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)
tcp_rearm_rto(sk);
if (after(ack, prior_snd_una))
flag |= FLAG_SND_UNA_ADVANCED;
prior_fackets = tp->fackets_out;
prior_in_flight = tcp_packets_in_flight(tp);
/* ts_recent update must be made after we are sure that the packet
* is in window.
*/
if (flag & FLAG_UPDATE_TS_RECENT)
tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
/* Window is constant, pure forward advance.
* No more checks are required.
* Note, we use the fact that SND.UNA>=SND.WL2.
*/
tcp_update_wl(tp, ack_seq);
tp->snd_una = ack;
flag |= FLAG_WIN_UPDATE;
tcp_ca_event(sk, CA_EVENT_FAST_ACK);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPACKS);
} else {
if (ack_seq != TCP_SKB_CB(skb)->end_seq)
flag |= FLAG_DATA;
else
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPUREACKS);
flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
if (TCP_SKB_CB(skb)->sacked)
flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
if (TCP_ECN_rcv_ecn_echo(tp, tcp_hdr(skb)))
flag |= FLAG_ECE;
tcp_ca_event(sk, CA_EVENT_SLOW_ACK);
}
/* We passed data and got it acked, remove any soft error
* log. Something worked...
*/
sk->sk_err_soft = 0;
icsk->icsk_probes_out = 0;
tp->rcv_tstamp = tcp_time_stamp;
if (!prior_packets)
goto no_queue;
/* See if we can take anything off of the retransmit queue. */
previous_packets_out = tp->packets_out;
flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una);
pkts_acked = previous_packets_out - tp->packets_out;
if (tcp_ack_is_dubious(sk, flag)) {
/* Advance CWND, if state allows this. */
if ((flag & FLAG_DATA_ACKED) && tcp_may_raise_cwnd(sk, flag))
tcp_cong_avoid(sk, ack, prior_in_flight);
is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
tcp_fastretrans_alert(sk, pkts_acked, prior_sacked,
prior_packets, is_dupack, flag);
} else {
if (flag & FLAG_DATA_ACKED)
tcp_cong_avoid(sk, ack, prior_in_flight);
}
if (tp->tlp_high_seq)
tcp_process_tlp_ack(sk, ack, flag);
if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP)) {
struct dst_entry *dst = __sk_dst_get(sk);
if (dst)
dst_confirm(dst);
}
if (icsk->icsk_pending == ICSK_TIME_RETRANS)
tcp_schedule_loss_probe(sk);
if (tp->srtt != prior_rtt || tp->snd_cwnd != prior_cwnd)
tcp_update_pacing_rate(sk);
return 1;
no_queue:
/* If data was DSACKed, see if we can undo a cwnd reduction. */
if (flag & FLAG_DSACKING_ACK)
tcp_fastretrans_alert(sk, pkts_acked, prior_sacked,
prior_packets, is_dupack, flag);
/* If this ack opens up a zero window, clear backoff. It was
* being used to time the probes, and is probably far higher than
* it needs to be for normal retransmission.
*/
if (tcp_send_head(sk))
tcp_ack_probe(sk);
if (tp->tlp_high_seq)
tcp_process_tlp_ack(sk, ack, flag);
return 1;
invalid_ack:
SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
return -1;
old_ack:
/* If data was SACKed, tag it and see if we should send more data.
* If data was DSACKed, see if we can undo a cwnd reduction.
*/
if (TCP_SKB_CB(skb)->sacked) {
flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
tcp_fastretrans_alert(sk, pkts_acked, prior_sacked,
prior_packets, is_dupack, flag);
}
SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
return 0;
}
/* Look for tcp options. Normally only called on SYN and SYNACK packets.
* But, this can also be called on packets in the established flow when
* the fast version below fails.
*/
void tcp_parse_options(const struct sk_buff *skb,
struct tcp_options_received *opt_rx, int estab,
struct tcp_fastopen_cookie *foc)
{
const unsigned char *ptr;
const struct tcphdr *th = tcp_hdr(skb);
int length = (th->doff * 4) - sizeof(struct tcphdr);
ptr = (const unsigned char *)(th + 1);
opt_rx->saw_tstamp = 0;
while (length > 0) {
int opcode = *ptr++;
int opsize;
switch (opcode) {
case TCPOPT_EOL:
return;
case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
length--;
continue;
default:
opsize = *ptr++;
if (opsize < 2) /* "silly options" */
return;
if (opsize > length)
return; /* don't parse partial options */
switch (opcode) {
case TCPOPT_MSS:
if (opsize == TCPOLEN_MSS && th->syn && !estab) {
u16 in_mss = get_unaligned_be16(ptr);
if (in_mss) {
if (opt_rx->user_mss &&
opt_rx->user_mss < in_mss)
in_mss = opt_rx->user_mss;
opt_rx->mss_clamp = in_mss;
}
}
break;
case TCPOPT_WINDOW:
if (opsize == TCPOLEN_WINDOW && th->syn &&
!estab && sysctl_tcp_window_scaling) {
__u8 snd_wscale = *(__u8 *)ptr;
opt_rx->wscale_ok = 1;
if (snd_wscale > 14) {
net_info_ratelimited("%s: Illegal window scaling value %d >14 received\n",
__func__,
snd_wscale);
snd_wscale = 14;
}
opt_rx->snd_wscale = snd_wscale;
}
break;
case TCPOPT_TIMESTAMP:
if ((opsize == TCPOLEN_TIMESTAMP) &&
((estab && opt_rx->tstamp_ok) ||
(!estab && sysctl_tcp_timestamps))) {
opt_rx->saw_tstamp = 1;
opt_rx->rcv_tsval = get_unaligned_be32(ptr);
opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
}
break;
case TCPOPT_SACK_PERM:
if (opsize == TCPOLEN_SACK_PERM && th->syn &&
!estab && sysctl_tcp_sack) {
opt_rx->sack_ok = TCP_SACK_SEEN;
tcp_sack_reset(opt_rx);
}
break;
case TCPOPT_SACK:
if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
!((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
opt_rx->sack_ok) {
TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
}
break;
#ifdef CONFIG_TCP_MD5SIG
case TCPOPT_MD5SIG:
/*
* The MD5 Hash has already been
* checked (see tcp_v{4,6}_do_rcv()).
*/
break;
#endif
case TCPOPT_EXP:
/* Fast Open option shares code 254 using a
* 16 bits magic number. It's valid only in
* SYN or SYN-ACK with an even size.
*/
if (opsize < TCPOLEN_EXP_FASTOPEN_BASE ||
get_unaligned_be16(ptr) != TCPOPT_FASTOPEN_MAGIC ||
foc == NULL || !th->syn || (opsize & 1))
break;
foc->len = opsize - TCPOLEN_EXP_FASTOPEN_BASE;
if (foc->len >= TCP_FASTOPEN_COOKIE_MIN &&
foc->len <= TCP_FASTOPEN_COOKIE_MAX)
memcpy(foc->val, ptr + 2, foc->len);
else if (foc->len != 0)
foc->len = -1;
break;
}
ptr += opsize-2;
length -= opsize;
}
}
}
EXPORT_SYMBOL(tcp_parse_options);
static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
{
const __be32 *ptr = (const __be32 *)(th + 1);
if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
| (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
tp->rx_opt.saw_tstamp = 1;
++ptr;
tp->rx_opt.rcv_tsval = ntohl(*ptr);
++ptr;
if (*ptr)
tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
else
tp->rx_opt.rcv_tsecr = 0;
return true;
}
return false;
}
/* Fast parse options. This hopes to only see timestamps.
* If it is wrong it falls back on tcp_parse_options().
*/
static bool tcp_fast_parse_options(const struct sk_buff *skb,
const struct tcphdr *th, struct tcp_sock *tp)
{
/* In the spirit of fast parsing, compare doff directly to constant
* values. Because equality is used, short doff can be ignored here.
*/
if (th->doff == (sizeof(*th) / 4)) {
tp->rx_opt.saw_tstamp = 0;
return false;
} else if (tp->rx_opt.tstamp_ok &&
th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
if (tcp_parse_aligned_timestamp(tp, th))
return true;
}
tcp_parse_options(skb, &tp->rx_opt, 1, NULL);
if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
tp->rx_opt.rcv_tsecr -= tp->tsoffset;
return true;
}
#ifdef CONFIG_TCP_MD5SIG
/*
* Parse MD5 Signature option
*/
const u8 *tcp_parse_md5sig_option(const struct tcphdr *th)
{
int length = (th->doff << 2) - sizeof(*th);
const u8 *ptr = (const u8 *)(th + 1);
/* If the TCP option is too short, we can short cut */
if (length < TCPOLEN_MD5SIG)
return NULL;
while (length > 0) {
int opcode = *ptr++;
int opsize;
switch(opcode) {
case TCPOPT_EOL:
return NULL;
case TCPOPT_NOP:
length--;
continue;
default:
opsize = *ptr++;
if (opsize < 2 || opsize > length)
return NULL;
if (opcode == TCPOPT_MD5SIG)
return opsize == TCPOLEN_MD5SIG ? ptr : NULL;
}
ptr += opsize - 2;
length -= opsize;
}
return NULL;
}
EXPORT_SYMBOL(tcp_parse_md5sig_option);
#endif
/* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
*
* It is not fatal. If this ACK does _not_ change critical state (seqs, window)
* it can pass through stack. So, the following predicate verifies that
* this segment is not used for anything but congestion avoidance or
* fast retransmit. Moreover, we even are able to eliminate most of such
* second order effects, if we apply some small "replay" window (~RTO)
* to timestamp space.
*
* All these measures still do not guarantee that we reject wrapped ACKs
* on networks with high bandwidth, when sequence space is recycled fastly,
* but it guarantees that such events will be very rare and do not affect
* connection seriously. This doesn't look nice, but alas, PAWS is really
* buggy extension.
*
* [ Later note. Even worse! It is buggy for segments _with_ data. RFC
* states that events when retransmit arrives after original data are rare.
* It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
* the biggest problem on large power networks even with minor reordering.
* OK, let's give it small replay window. If peer clock is even 1hz, it is safe
* up to bandwidth of 18Gigabit/sec. 8) ]
*/
static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
{
const struct tcp_sock *tp = tcp_sk(sk);
const struct tcphdr *th = tcp_hdr(skb);
u32 seq = TCP_SKB_CB(skb)->seq;
u32 ack = TCP_SKB_CB(skb)->ack_seq;
return (/* 1. Pure ACK with correct sequence number. */
(th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
/* 2. ... and duplicate ACK. */
ack == tp->snd_una &&
/* 3. ... and does not update window. */
!tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
/* 4. ... and sits in replay window. */
(s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
}
static inline bool tcp_paws_discard(const struct sock *sk,
const struct sk_buff *skb)
{
const struct tcp_sock *tp = tcp_sk(sk);
return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) &&
!tcp_disordered_ack(sk, skb);
}
/* Check segment sequence number for validity.
*
* Segment controls are considered valid, if the segment
* fits to the window after truncation to the window. Acceptability
* of data (and SYN, FIN, of course) is checked separately.
* See tcp_data_queue(), for example.
*
* Also, controls (RST is main one) are accepted using RCV.WUP instead
* of RCV.NXT. Peer still did not advance his SND.UNA when we
* delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
* (borrowed from freebsd)
*/
static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq)
{
return !before(end_seq, tp->rcv_wup) &&
!after(seq, tp->rcv_nxt + tcp_receive_window(tp));
}
/* When we get a reset we do this. */
void tcp_reset(struct sock *sk)
{
/* We want the right error as BSD sees it (and indeed as we do). */
switch (sk->sk_state) {
case TCP_SYN_SENT:
sk->sk_err = ECONNREFUSED;
break;
case TCP_CLOSE_WAIT:
sk->sk_err = EPIPE;
break;
case TCP_CLOSE:
return;
default:
sk->sk_err = ECONNRESET;
}
/* This barrier is coupled with smp_rmb() in tcp_poll() */
smp_wmb();
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
tcp_done(sk);
}
/*
* Process the FIN bit. This now behaves as it is supposed to work
* and the FIN takes effect when it is validly part of sequence
* space. Not before when we get holes.
*
* If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
* (and thence onto LAST-ACK and finally, CLOSE, we never enter
* TIME-WAIT)
*
* If we are in FINWAIT-1, a received FIN indicates simultaneous
* close and we go into CLOSING (and later onto TIME-WAIT)
*
* If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
*/
static void tcp_fin(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
inet_csk_schedule_ack(sk);
sk->sk_shutdown |= RCV_SHUTDOWN;
sock_set_flag(sk, SOCK_DONE);
switch (sk->sk_state) {
case TCP_SYN_RECV:
case TCP_ESTABLISHED:
/* Move to CLOSE_WAIT */
tcp_set_state(sk, TCP_CLOSE_WAIT);
inet_csk(sk)->icsk_ack.pingpong = 1;
break;
case TCP_CLOSE_WAIT:
case TCP_CLOSING:
/* Received a retransmission of the FIN, do
* nothing.
*/
break;
case TCP_LAST_ACK:
/* RFC793: Remain in the LAST-ACK state. */
break;
case TCP_FIN_WAIT1:
/* This case occurs when a simultaneous close
* happens, we must ack the received FIN and
* enter the CLOSING state.
*/
tcp_send_ack(sk);
tcp_set_state(sk, TCP_CLOSING);
break;
case TCP_FIN_WAIT2:
/* Received a FIN -- send ACK and enter TIME_WAIT. */
tcp_send_ack(sk);
tcp_time_wait(sk, TCP_TIME_WAIT, 0);
break;
default:
/* Only TCP_LISTEN and TCP_CLOSE are left, in these
* cases we should never reach this piece of code.
*/
pr_err("%s: Impossible, sk->sk_state=%d\n",
__func__, sk->sk_state);
break;
}
/* It _is_ possible, that we have something out-of-order _after_ FIN.
* Probably, we should reset in this case. For now drop them.
*/
__skb_queue_purge(&tp->out_of_order_queue);
if (tcp_is_sack(tp))
tcp_sack_reset(&tp->rx_opt);
sk_mem_reclaim(sk);
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
/* Do not send POLL_HUP for half duplex close. */
if (sk->sk_shutdown == SHUTDOWN_MASK ||
sk->sk_state == TCP_CLOSE)
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
else
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
}
}
static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
u32 end_seq)
{
if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
if (before(seq, sp->start_seq))
sp->start_seq = seq;
if (after(end_seq, sp->end_seq))
sp->end_seq = end_seq;
return true;
}
return false;
}
static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
int mib_idx;
if (before(seq, tp->rcv_nxt))
mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
else
mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
NET_INC_STATS_BH(sock_net(sk), mib_idx);
tp->rx_opt.dsack = 1;
tp->duplicate_sack[0].start_seq = seq;
tp->duplicate_sack[0].end_seq = end_seq;
}
}
static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
{
struct tcp_sock *tp = tcp_sk(sk);
if (!tp->rx_opt.dsack)
tcp_dsack_set(sk, seq, end_seq);
else
tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
}
static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
tcp_enter_quickack_mode(sk);
if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
u32 end_seq = TCP_SKB_CB(skb)->end_seq;
if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
end_seq = tp->rcv_nxt;
tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
}
}
tcp_send_ack(sk);
}
/* These routines update the SACK block as out-of-order packets arrive or
* in-order packets close up the sequence space.
*/
static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
{
int this_sack;
struct tcp_sack_block *sp = &tp->selective_acks[0];
struct tcp_sack_block *swalk = sp + 1;
/* See if the recent change to the first SACK eats into
* or hits the sequence space of other SACK blocks, if so coalesce.
*/
for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
int i;
/* Zap SWALK, by moving every further SACK up by one slot.
* Decrease num_sacks.
*/
tp->rx_opt.num_sacks--;
for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
sp[i] = sp[i + 1];
continue;
}
this_sack++, swalk++;
}
}
static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
{
struct tcp_sock *tp = tcp_sk(sk);
struct tcp_sack_block *sp = &tp->selective_acks[0];
int cur_sacks = tp->rx_opt.num_sacks;
int this_sack;
if (!cur_sacks)
goto new_sack;
for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
if (tcp_sack_extend(sp, seq, end_seq)) {
/* Rotate this_sack to the first one. */
for (; this_sack > 0; this_sack--, sp--)
swap(*sp, *(sp - 1));
if (cur_sacks > 1)
tcp_sack_maybe_coalesce(tp);
return;
}
}
/* Could not find an adjacent existing SACK, build a new one,
* put it at the front, and shift everyone else down. We
* always know there is at least one SACK present already here.
*
* If the sack array is full, forget about the last one.
*/
if (this_sack >= TCP_NUM_SACKS) {
this_sack--;
tp->rx_opt.num_sacks--;
sp--;
}
for (; this_sack > 0; this_sack--, sp--)
*sp = *(sp - 1);
new_sack:
/* Build the new head SACK, and we're done. */
sp->start_seq = seq;
sp->end_seq = end_seq;
tp->rx_opt.num_sacks++;
}
/* RCV.NXT advances, some SACKs should be eaten. */
static void tcp_sack_remove(struct tcp_sock *tp)
{
struct tcp_sack_block *sp = &tp->selective_acks[0];
int num_sacks = tp->rx_opt.num_sacks;
int this_sack;
/* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
if (skb_queue_empty(&tp->out_of_order_queue)) {
tp->rx_opt.num_sacks = 0;
return;
}
for (this_sack = 0; this_sack < num_sacks;) {
/* Check if the start of the sack is covered by RCV.NXT. */
if (!before(tp->rcv_nxt, sp->start_seq)) {
int i;
/* RCV.NXT must cover all the block! */
WARN_ON(before(tp->rcv_nxt, sp->end_seq));
/* Zap this SACK, by moving forward any other SACKS. */
for (i=this_sack+1; i < num_sacks; i++)
tp->selective_acks[i-1] = tp->selective_acks[i];
num_sacks--;
continue;
}
this_sack++;
sp++;
}
tp->rx_opt.num_sacks = num_sacks;
}
/* This one checks to see if we can put data from the
* out_of_order queue into the receive_queue.
*/
static void tcp_ofo_queue(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
__u32 dsack_high = tp->rcv_nxt;
struct sk_buff *skb;
while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
break;
if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
__u32 dsack = dsack_high;
if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
dsack_high = TCP_SKB_CB(skb)->end_seq;
tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
}
if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
SOCK_DEBUG(sk, "ofo packet was already received\n");
__skb_unlink(skb, &tp->out_of_order_queue);
__kfree_skb(skb);
continue;
}
SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
TCP_SKB_CB(skb)->end_seq);
__skb_unlink(skb, &tp->out_of_order_queue);
__skb_queue_tail(&sk->sk_receive_queue, skb);
tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
if (tcp_hdr(skb)->fin)
tcp_fin(sk);
}
}
static bool tcp_prune_ofo_queue(struct sock *sk);
static int tcp_prune_queue(struct sock *sk);
static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb,
unsigned int size)
{
if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
!sk_rmem_schedule(sk, skb, size)) {
if (tcp_prune_queue(sk) < 0)
return -1;
if (!sk_rmem_schedule(sk, skb, size)) {
if (!tcp_prune_ofo_queue(sk))
return -1;
if (!sk_rmem_schedule(sk, skb, size))
return -1;
}
}
return 0;
}
/**
* tcp_try_coalesce - try to merge skb to prior one
* @sk: socket
* @to: prior buffer
* @from: buffer to add in queue
* @fragstolen: pointer to boolean
*
* Before queueing skb @from after @to, try to merge them
* to reduce overall memory use and queue lengths, if cost is small.
* Packets in ofo or receive queues can stay a long time.
* Better try to coalesce them right now to avoid future collapses.
* Returns true if caller should free @from instead of queueing it
*/
static bool tcp_try_coalesce(struct sock *sk,
struct sk_buff *to,
struct sk_buff *from,
bool *fragstolen)
{
int delta;
*fragstolen = false;
if (tcp_hdr(from)->fin)
return false;
/* Its possible this segment overlaps with prior segment in queue */
if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
return false;
if (!skb_try_coalesce(to, from, fragstolen, &delta))
return false;
atomic_add(delta, &sk->sk_rmem_alloc);
sk_mem_charge(sk, delta);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
return true;
}
static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb1;
u32 seq, end_seq;
TCP_ECN_check_ce(tp, skb);
if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFODROP);
__kfree_skb(skb);
return;
}
/* Disable header prediction. */
tp->pred_flags = 0;
inet_csk_schedule_ack(sk);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
skb1 = skb_peek_tail(&tp->out_of_order_queue);
if (!skb1) {
/* Initial out of order segment, build 1 SACK. */
if (tcp_is_sack(tp)) {
tp->rx_opt.num_sacks = 1;
tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
tp->selective_acks[0].end_seq =
TCP_SKB_CB(skb)->end_seq;
}
__skb_queue_head(&tp->out_of_order_queue, skb);
goto end;
}
seq = TCP_SKB_CB(skb)->seq;
end_seq = TCP_SKB_CB(skb)->end_seq;
if (seq == TCP_SKB_CB(skb1)->end_seq) {
bool fragstolen;
if (!tcp_try_coalesce(sk, skb1, skb, &fragstolen)) {
__skb_queue_after(&tp->out_of_order_queue, skb1, skb);
} else {
kfree_skb_partial(skb, fragstolen);
skb = NULL;
}
if (!tp->rx_opt.num_sacks ||
tp->selective_acks[0].end_seq != seq)
goto add_sack;
/* Common case: data arrive in order after hole. */
tp->selective_acks[0].end_seq = end_seq;
goto end;
}
/* Find place to insert this segment. */
while (1) {
if (!after(TCP_SKB_CB(skb1)->seq, seq))
break;
if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) {
skb1 = NULL;
break;
}
skb1 = skb_queue_prev(&tp->out_of_order_queue, skb1);
}
/* Do skb overlap to previous one? */
if (skb1 && before(seq, TCP_SKB_CB(skb1)->end_seq)) {
if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
/* All the bits are present. Drop. */
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
__kfree_skb(skb);
skb = NULL;
tcp_dsack_set(sk, seq, end_seq);
goto add_sack;
}
if (after(seq, TCP_SKB_CB(skb1)->seq)) {
/* Partial overlap. */
tcp_dsack_set(sk, seq,
TCP_SKB_CB(skb1)->end_seq);
} else {
if (skb_queue_is_first(&tp->out_of_order_queue,
skb1))
skb1 = NULL;
else
skb1 = skb_queue_prev(
&tp->out_of_order_queue,
skb1);
}
}
if (!skb1)
__skb_queue_head(&tp->out_of_order_queue, skb);
else
__skb_queue_after(&tp->out_of_order_queue, skb1, skb);
/* And clean segments covered by new one as whole. */
while (!skb_queue_is_last(&tp->out_of_order_queue, skb)) {
skb1 = skb_queue_next(&tp->out_of_order_queue, skb);
if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
break;
if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
end_seq);
break;
}
__skb_unlink(skb1, &tp->out_of_order_queue);
tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
TCP_SKB_CB(skb1)->end_seq);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
__kfree_skb(skb1);
}
add_sack:
if (tcp_is_sack(tp))
tcp_sack_new_ofo_skb(sk, seq, end_seq);
end:
if (skb)
skb_set_owner_r(skb, sk);
}
static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen,
bool *fragstolen)
{
int eaten;
struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
__skb_pull(skb, hdrlen);
eaten = (tail &&
tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0;
tcp_sk(sk)->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
if (!eaten) {
__skb_queue_tail(&sk->sk_receive_queue, skb);
skb_set_owner_r(skb, sk);
}
return eaten;
}
int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
{
struct sk_buff *skb = NULL;
struct tcphdr *th;
bool fragstolen;
if (size == 0)
return 0;
skb = alloc_skb(size + sizeof(*th), sk->sk_allocation);
if (!skb)
goto err;
if (tcp_try_rmem_schedule(sk, skb, size + sizeof(*th)))
goto err_free;
th = (struct tcphdr *)skb_put(skb, sizeof(*th));
skb_reset_transport_header(skb);
memset(th, 0, sizeof(*th));
if (memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size))
goto err_free;
TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
if (tcp_queue_rcv(sk, skb, sizeof(*th), &fragstolen)) {
WARN_ON_ONCE(fragstolen); /* should not happen */
__kfree_skb(skb);
}
return size;
err_free:
kfree_skb(skb);
err:
return -ENOMEM;
}
static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
{
const struct tcphdr *th = tcp_hdr(skb);
struct tcp_sock *tp = tcp_sk(sk);
int eaten = -1;
bool fragstolen = false;
if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
goto drop;
skb_dst_drop(skb);
__skb_pull(skb, th->doff * 4);
TCP_ECN_accept_cwr(tp, skb);
tp->rx_opt.dsack = 0;
/* Queue data for delivery to the user.
* Packets in sequence go to the receive queue.
* Out of sequence packets to the out_of_order_queue.
*/
if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
if (tcp_receive_window(tp) == 0)
goto out_of_window;
/* Ok. In sequence. In window. */
if (tp->ucopy.task == current &&
tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
sock_owned_by_user(sk) && !tp->urg_data) {
int chunk = min_t(unsigned int, skb->len,
tp->ucopy.len);
__set_current_state(TASK_RUNNING);
local_bh_enable();
if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
tp->ucopy.len -= chunk;
tp->copied_seq += chunk;
eaten = (chunk == skb->len);
tcp_rcv_space_adjust(sk);
}
local_bh_disable();
}
if (eaten <= 0) {
queue_and_out:
if (eaten < 0 &&
tcp_try_rmem_schedule(sk, skb, skb->truesize))
goto drop;
eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen);
}
tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
if (skb->len)
tcp_event_data_recv(sk, skb);
if (th->fin)
tcp_fin(sk);
if (!skb_queue_empty(&tp->out_of_order_queue)) {
tcp_ofo_queue(sk);
/* RFC2581. 4.2. SHOULD send immediate ACK, when
* gap in queue is filled.
*/
if (skb_queue_empty(&tp->out_of_order_queue))
inet_csk(sk)->icsk_ack.pingpong = 0;
}
if (tp->rx_opt.num_sacks)
tcp_sack_remove(tp);
tcp_fast_path_check(sk);
if (eaten > 0)
kfree_skb_partial(skb, fragstolen);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, 0);
return;
}
if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
/* A retransmit, 2nd most common case. Force an immediate ack. */
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
out_of_window:
tcp_enter_quickack_mode(sk);
inet_csk_schedule_ack(sk);
drop:
__kfree_skb(skb);
return;
}
/* Out of window. F.e. zero window probe. */
if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
goto out_of_window;
tcp_enter_quickack_mode(sk);
if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
/* Partial packet, seq < rcv_next < end_seq */
SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
TCP_SKB_CB(skb)->end_seq);
tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
/* If window is closed, drop tail of packet. But after
* remembering D-SACK for its head made in previous line.
*/
if (!tcp_receive_window(tp))
goto out_of_window;
goto queue_and_out;
}
tcp_data_queue_ofo(sk, skb);
}
static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
struct sk_buff_head *list)
{
struct sk_buff *next = NULL;
if (!skb_queue_is_last(list, skb))
next = skb_queue_next(list, skb);
__skb_unlink(skb, list);
__kfree_skb(skb);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
return next;
}
/* Collapse contiguous sequence of skbs head..tail with
* sequence numbers start..end.
*
* If tail is NULL, this means until the end of the list.
*
* Segments with FIN/SYN are not collapsed (only because this
* simplifies code)
*/
static void
tcp_collapse(struct sock *sk, struct sk_buff_head *list,
struct sk_buff *head, struct sk_buff *tail,
u32 start, u32 end)
{
struct sk_buff *skb, *n;
bool end_of_skbs;
/* First, check that queue is collapsible and find
* the point where collapsing can be useful. */
skb = head;
restart:
end_of_skbs = true;
skb_queue_walk_from_safe(list, skb, n) {
if (skb == tail)
break;
/* No new bits? It is possible on ofo queue. */
if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
skb = tcp_collapse_one(sk, skb, list);
if (!skb)
break;
goto restart;
}
/* The first skb to collapse is:
* - not SYN/FIN and
* - bloated or contains data before "start" or
* overlaps to the next one.
*/
if (!tcp_hdr(skb)->syn && !tcp_hdr(skb)->fin &&
(tcp_win_from_space(skb->truesize) > skb->len ||
before(TCP_SKB_CB(skb)->seq, start))) {
end_of_skbs = false;
break;
}
if (!skb_queue_is_last(list, skb)) {
struct sk_buff *next = skb_queue_next(list, skb);
if (next != tail &&
TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) {
end_of_skbs = false;
break;
}
}
/* Decided to skip this, advance start seq. */
start = TCP_SKB_CB(skb)->end_seq;
}
if (end_of_skbs || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin)
return;
while (before(start, end)) {
struct sk_buff *nskb;
unsigned int header = skb_headroom(skb);
int copy = SKB_MAX_ORDER(header, 0);
/* Too big header? This can happen with IPv6. */
if (copy < 0)
return;
if (end - start < copy)
copy = end - start;
nskb = alloc_skb(copy + header, GFP_ATOMIC);
if (!nskb)
return;
skb_set_mac_header(nskb, skb_mac_header(skb) - skb->head);
skb_set_network_header(nskb, (skb_network_header(skb) -
skb->head));
skb_set_transport_header(nskb, (skb_transport_header(skb) -
skb->head));
skb_reserve(nskb, header);
memcpy(nskb->head, skb->head, header);
memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
__skb_queue_before(list, skb, nskb);
skb_set_owner_r(nskb, sk);
/* Copy data, releasing collapsed skbs. */
while (copy > 0) {
int offset = start - TCP_SKB_CB(skb)->seq;
int size = TCP_SKB_CB(skb)->end_seq - start;
BUG_ON(offset < 0);
if (size > 0) {
size = min(copy, size);
if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
BUG();
TCP_SKB_CB(nskb)->end_seq += size;
copy -= size;
start += size;
}
if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
skb = tcp_collapse_one(sk, skb, list);
if (!skb ||
skb == tail ||
tcp_hdr(skb)->syn ||
tcp_hdr(skb)->fin)
return;
}
}
}
}
/* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
* and tcp_collapse() them until all the queue is collapsed.
*/
static void tcp_collapse_ofo_queue(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
struct sk_buff *head;
u32 start, end;
if (skb == NULL)
return;
start = TCP_SKB_CB(skb)->seq;
end = TCP_SKB_CB(skb)->end_seq;
head = skb;
for (;;) {
struct sk_buff *next = NULL;
if (!skb_queue_is_last(&tp->out_of_order_queue, skb))
next = skb_queue_next(&tp->out_of_order_queue, skb);
skb = next;
/* Segment is terminated when we see gap or when
* we are at the end of all the queue. */
if (!skb ||
after(TCP_SKB_CB(skb)->seq, end) ||
before(TCP_SKB_CB(skb)->end_seq, start)) {
tcp_collapse(sk, &tp->out_of_order_queue,
head, skb, start, end);
head = skb;
if (!skb)
break;
/* Start new segment */
start = TCP_SKB_CB(skb)->seq;
end = TCP_SKB_CB(skb)->end_seq;
} else {
if (before(TCP_SKB_CB(skb)->seq, start))
start = TCP_SKB_CB(skb)->seq;
if (after(TCP_SKB_CB(skb)->end_seq, end))
end = TCP_SKB_CB(skb)->end_seq;
}
}
}
/*
* Purge the out-of-order queue.
* Return true if queue was pruned.
*/
static bool tcp_prune_ofo_queue(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
bool res = false;
if (!skb_queue_empty(&tp->out_of_order_queue)) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_OFOPRUNED);
__skb_queue_purge(&tp->out_of_order_queue);
/* Reset SACK state. A conforming SACK implementation will
* do the same at a timeout based retransmit. When a connection
* is in a sad state like this, we care only about integrity
* of the connection not performance.
*/
if (tp->rx_opt.sack_ok)
tcp_sack_reset(&tp->rx_opt);
sk_mem_reclaim(sk);
res = true;
}
return res;
}
/* Reduce allocated memory if we can, trying to get
* the socket within its memory limits again.
*
* Return less than zero if we should start dropping frames
* until the socket owning process reads some of the data
* to stabilize the situation.
*/
static int tcp_prune_queue(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PRUNECALLED);
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
tcp_clamp_window(sk);
else if (sk_under_memory_pressure(sk))
tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
tcp_collapse_ofo_queue(sk);
if (!skb_queue_empty(&sk->sk_receive_queue))
tcp_collapse(sk, &sk->sk_receive_queue,
skb_peek(&sk->sk_receive_queue),
NULL,
tp->copied_seq, tp->rcv_nxt);
sk_mem_reclaim(sk);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
return 0;
/* Collapsing did not help, destructive actions follow.
* This must not ever occur. */
tcp_prune_ofo_queue(sk);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
return 0;
/* If we are really being abused, tell the caller to silently
* drop receive data on the floor. It will get retransmitted
* and hopefully then we'll have sufficient space.
*/
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_RCVPRUNED);
/* Massive buffer overcommit. */
tp->pred_flags = 0;
return -1;
}
/* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
* As additional protections, we do not touch cwnd in retransmission phases,
* and if application hit its sndbuf limit recently.
*/
void tcp_cwnd_application_limited(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open &&
sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
/* Limited by application or receiver window. */
u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk));
u32 win_used = max(tp->snd_cwnd_used, init_win);
if (win_used < tp->snd_cwnd) {
tp->snd_ssthresh = tcp_current_ssthresh(sk);
tp->snd_cwnd = (tp->snd_cwnd + win_used) >> 1;
}
tp->snd_cwnd_used = 0;
}
tp->snd_cwnd_stamp = tcp_time_stamp;
}
static bool tcp_should_expand_sndbuf(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
/* If the user specified a specific send buffer setting, do
* not modify it.
*/
if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
return false;
/* If we are under global TCP memory pressure, do not expand. */
if (sk_under_memory_pressure(sk))
return false;
/* If we are under soft global TCP memory pressure, do not expand. */
if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
return false;
/* If we filled the congestion window, do not expand. */
if (tp->packets_out >= tp->snd_cwnd)
return false;
return true;
}
/* When incoming ACK allowed to free some skb from write_queue,
* we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket
* on the exit from tcp input handler.
*
* PROBLEM: sndbuf expansion does not work well with largesend.
*/
static void tcp_new_space(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
if (tcp_should_expand_sndbuf(sk)) {
int sndmem = SKB_TRUESIZE(max_t(u32,
tp->rx_opt.mss_clamp,
tp->mss_cache) +
MAX_TCP_HEADER);
int demanded = max_t(unsigned int, tp->snd_cwnd,
tp->reordering + 1);
sndmem *= 2 * demanded;
if (sndmem > sk->sk_sndbuf)
sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
tp->snd_cwnd_stamp = tcp_time_stamp;
}
sk->sk_write_space(sk);
}
static void tcp_check_space(struct sock *sk)
{
if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) {
sock_reset_flag(sk, SOCK_QUEUE_SHRUNK);
if (sk->sk_socket &&
test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
tcp_new_space(sk);
}
}
static inline void tcp_data_snd_check(struct sock *sk)
{
tcp_push_pending_frames(sk);
tcp_check_space(sk);
}
/*
* Check if sending an ack is needed.
*/
static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
{
struct tcp_sock *tp = tcp_sk(sk);
/* More than one full frame received... */
if (((tp->rcv_nxt - tp->rcv_wup) > (inet_csk(sk)->icsk_ack.rcv_mss) *
sysctl_tcp_delack_seg &&
/* ... and right edge of window advances far enough.
* (tcp_recvmsg() will send ACK otherwise). Or...
*/
__tcp_select_window(sk) >= tp->rcv_wnd) ||
/* We ACK each frame or... */
tcp_in_quickack_mode(sk) ||
/* We have out of order data. */
(ofo_possible && skb_peek(&tp->out_of_order_queue))) {
/* Then ack it now */
tcp_send_ack(sk);
} else {
/* Else, send delayed ack. */
tcp_send_delayed_ack(sk);
}
}
static inline void tcp_ack_snd_check(struct sock *sk)
{
if (!inet_csk_ack_scheduled(sk)) {
/* We sent a data segment already. */
return;
}
__tcp_ack_snd_check(sk, 1);
}
/*
* This routine is only called when we have urgent data
* signaled. Its the 'slow' part of tcp_urg. It could be
* moved inline now as tcp_urg is only called from one
* place. We handle URGent data wrong. We have to - as
* BSD still doesn't use the correction from RFC961.
* For 1003.1g we should support a new option TCP_STDURG to permit
* either form (or just set the sysctl tcp_stdurg).
*/
static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
{
struct tcp_sock *tp = tcp_sk(sk);
u32 ptr = ntohs(th->urg_ptr);
if (ptr && !sysctl_tcp_stdurg)
ptr--;
ptr += ntohl(th->seq);
/* Ignore urgent data that we've already seen and read. */
if (after(tp->copied_seq, ptr))
return;
/* Do not replay urg ptr.
*
* NOTE: interesting situation not covered by specs.
* Misbehaving sender may send urg ptr, pointing to segment,
* which we already have in ofo queue. We are not able to fetch
* such data and will stay in TCP_URG_NOTYET until will be eaten
* by recvmsg(). Seems, we are not obliged to handle such wicked
* situations. But it is worth to think about possibility of some
* DoSes using some hypothetical application level deadlock.
*/
if (before(ptr, tp->rcv_nxt))
return;
/* Do we already have a newer (or duplicate) urgent pointer? */
if (tp->urg_data && !after(ptr, tp->urg_seq))
return;
/* Tell the world about our new urgent pointer. */
sk_send_sigurg(sk);
/* We may be adding urgent data when the last byte read was
* urgent. To do this requires some care. We cannot just ignore
* tp->copied_seq since we would read the last urgent byte again
* as data, nor can we alter copied_seq until this data arrives
* or we break the semantics of SIOCATMARK (and thus sockatmark())
*
* NOTE. Double Dutch. Rendering to plain English: author of comment
* above did something sort of send("A", MSG_OOB); send("B", MSG_OOB);
* and expect that both A and B disappear from stream. This is _wrong_.
* Though this happens in BSD with high probability, this is occasional.
* Any application relying on this is buggy. Note also, that fix "works"
* only in this artificial test. Insert some normal data between A and B and we will
* decline of BSD again. Verdict: it is better to remove to trap
* buggy users.
*/
if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
!sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
tp->copied_seq++;
if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
__skb_unlink(skb, &sk->sk_receive_queue);
__kfree_skb(skb);
}
}
tp->urg_data = TCP_URG_NOTYET;
tp->urg_seq = ptr;
/* Disable header prediction. */
tp->pred_flags = 0;
}
/* This is the 'fast' part of urgent handling. */
static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Check if we get a new urgent pointer - normally not. */
if (th->urg)
tcp_check_urg(sk, th);
/* Do we wait for any urgent data? - normally not... */
if (tp->urg_data == TCP_URG_NOTYET) {
u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
th->syn;
/* Is the urgent pointer pointing into this packet? */
if (ptr < skb->len) {
u8 tmp;
if (skb_copy_bits(skb, ptr, &tmp, 1))
BUG();
tp->urg_data = TCP_URG_VALID | tmp;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, 0);
}
}
}
static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
{
struct tcp_sock *tp = tcp_sk(sk);
int chunk = skb->len - hlen;
int err;
local_bh_enable();
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
else
err = skb_copy_and_csum_datagram_iovec(skb, hlen,
tp->ucopy.iov);
if (!err) {
tp->ucopy.len -= chunk;
tp->copied_seq += chunk;
tcp_rcv_space_adjust(sk);
}
local_bh_disable();
return err;
}
static __sum16 __tcp_checksum_complete_user(struct sock *sk,
struct sk_buff *skb)
{
__sum16 result;
if (sock_owned_by_user(sk)) {
local_bh_enable();
result = __tcp_checksum_complete(skb);
local_bh_disable();
} else {
result = __tcp_checksum_complete(skb);
}
return result;
}
static inline bool tcp_checksum_complete_user(struct sock *sk,
struct sk_buff *skb)
{
return !skb_csum_unnecessary(skb) &&
__tcp_checksum_complete_user(sk, skb);
}
#ifdef CONFIG_NET_DMA
static bool tcp_dma_try_early_copy(struct sock *sk, struct sk_buff *skb,
int hlen)
{
struct tcp_sock *tp = tcp_sk(sk);
int chunk = skb->len - hlen;
int dma_cookie;
bool copied_early = false;
if (tp->ucopy.wakeup)
return false;
if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
tp->ucopy.dma_chan = net_dma_find_channel();
if (tp->ucopy.dma_chan && skb_csum_unnecessary(skb)) {
dma_cookie = dma_skb_copy_datagram_iovec(tp->ucopy.dma_chan,
skb, hlen,
tp->ucopy.iov, chunk,
tp->ucopy.pinned_list);
if (dma_cookie < 0)
goto out;
tp->ucopy.dma_cookie = dma_cookie;
copied_early = true;
tp->ucopy.len -= chunk;
tp->copied_seq += chunk;
tcp_rcv_space_adjust(sk);
if ((tp->ucopy.len == 0) ||
(tcp_flag_word(tcp_hdr(skb)) & TCP_FLAG_PSH) ||
(atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1))) {
tp->ucopy.wakeup = 1;
sk->sk_data_ready(sk, 0);
}
} else if (chunk > 0) {
tp->ucopy.wakeup = 1;
sk->sk_data_ready(sk, 0);
}
out:
return copied_early;
}
#endif /* CONFIG_NET_DMA */
/* Does PAWS and seqno based validation of an incoming segment, flags will
* play significant role here.
*/
static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
const struct tcphdr *th, int syn_inerr)
{
struct tcp_sock *tp = tcp_sk(sk);
/* RFC1323: H1. Apply PAWS check first. */
if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp &&
tcp_paws_discard(sk, skb)) {
if (!th->rst) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
tcp_send_dupack(sk, skb);
goto discard;
}
/* Reset is accepted even if it did not pass PAWS. */
}
/* Step 1: check sequence number */
if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
/* RFC793, page 37: "In all states except SYN-SENT, all reset
* (RST) segments are validated by checking their SEQ-fields."
* And page 69: "If an incoming segment is not acceptable,
* an acknowledgment should be sent in reply (unless the RST
* bit is set, if so drop the segment and return)".
*/
if (!th->rst) {
if (th->syn)
goto syn_challenge;
tcp_send_dupack(sk, skb);
}
goto discard;
}
/* Step 2: check RST bit */
if (th->rst) {
/* RFC 5961 3.2 :
* If sequence number exactly matches RCV.NXT, then
* RESET the connection
* else
* Send a challenge ACK
*/
if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt)
tcp_reset(sk);
else
tcp_send_challenge_ack(sk);
goto discard;
}
/* step 3: check security and precedence [ignored] */
/* step 4: Check for a SYN
* RFC 5691 4.2 : Send a challenge ack
*/
if (th->syn) {
syn_challenge:
if (syn_inerr)
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
tcp_send_challenge_ack(sk);
goto discard;
}
return true;
discard:
__kfree_skb(skb);
return false;
}
/*
* TCP receive function for the ESTABLISHED state.
*
* It is split into a fast path and a slow path. The fast path is
* disabled when:
* - A zero window was announced from us - zero window probing
* is only handled properly in the slow path.
* - Out of order segments arrived.
* - Urgent data is expected.
* - There is no buffer space left
* - Unexpected TCP flags/window values/header lengths are received
* (detected by checking the TCP header against pred_flags)
* - Data is sent in both directions. Fast path only supports pure senders
* or pure receivers (this means either the sequence number or the ack
* value must stay constant)
* - Unexpected TCP option.
*
* When these conditions are not satisfied it drops into a standard
* receive procedure patterned after RFC793 to handle all cases.
* The first three cases are guaranteed by proper pred_flags setting,
* the rest is checked inline. Fast processing is turned on in
* tcp_data_queue when everything is OK.
*/
int tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
const struct tcphdr *th, unsigned int len)
{
struct tcp_sock *tp = tcp_sk(sk);
if (unlikely(sk->sk_rx_dst == NULL))
inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
/*
* Header prediction.
* The code loosely follows the one in the famous
* "30 instruction TCP receive" Van Jacobson mail.
*
* Van's trick is to deposit buffers into socket queue
* on a device interrupt, to call tcp_recv function
* on the receive process context and checksum and copy
* the buffer to user space. smart...
*
* Our current scheme is not silly either but we take the
* extra cost of the net_bh soft interrupt processing...
* We do checksum and copy also but from device to kernel.
*/
tp->rx_opt.saw_tstamp = 0;
/* pred_flags is 0xS?10 << 16 + snd_wnd
* if header_prediction is to be made
* 'S' will always be tp->tcp_header_len >> 2
* '?' will be 0 for the fast path, otherwise pred_flags is 0 to
* turn it off (when there are holes in the receive
* space for instance)
* PSH flag is ignored.
*/
if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
int tcp_header_len = tp->tcp_header_len;
/* Timestamp header prediction: tcp_header_len
* is automatically equal to th->doff*4 due to pred_flags
* match.
*/
/* Check timestamp */
if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
/* No? Slow path! */
if (!tcp_parse_aligned_timestamp(tp, th))
goto slow_path;
/* If PAWS failed, check it more carefully in slow path */
if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0)
goto slow_path;
/* DO NOT update ts_recent here, if checksum fails
* and timestamp was corrupted part, it will result
* in a hung connection since we will drop all
* future packets due to the PAWS test.
*/
}
if (len <= tcp_header_len) {
/* Bulk data transfer: sender */
if (len == tcp_header_len) {
/* Predicted packet is in window by definition.
* seq == rcv_nxt and rcv_wup <= rcv_nxt.
* Hence, check seq<=rcv_wup reduces to:
*/
if (tcp_header_len ==
(sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
tp->rcv_nxt == tp->rcv_wup)
tcp_store_ts_recent(tp);
/* We know that such packets are checksummed
* on entry.
*/
tcp_ack(sk, skb, 0);
__kfree_skb(skb);
tcp_data_snd_check(sk);
return 0;
} else { /* Header too small */
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
goto discard;
}
} else {
int eaten = 0;
int copied_early = 0;
bool fragstolen = false;
if (tp->copied_seq == tp->rcv_nxt &&
len - tcp_header_len <= tp->ucopy.len) {
#ifdef CONFIG_NET_DMA
if (tp->ucopy.task == current &&
sock_owned_by_user(sk) &&
tcp_dma_try_early_copy(sk, skb, tcp_header_len)) {
copied_early = 1;
eaten = 1;
}
#endif
if (tp->ucopy.task == current &&
sock_owned_by_user(sk) && !copied_early) {
__set_current_state(TASK_RUNNING);
if (!tcp_copy_to_iovec(sk, skb, tcp_header_len))
eaten = 1;
}
if (eaten) {
/* Predicted packet is in window by definition.
* seq == rcv_nxt and rcv_wup <= rcv_nxt.
* Hence, check seq<=rcv_wup reduces to:
*/
if (tcp_header_len ==
(sizeof(struct tcphdr) +
TCPOLEN_TSTAMP_ALIGNED) &&
tp->rcv_nxt == tp->rcv_wup)
tcp_store_ts_recent(tp);
tcp_rcv_rtt_measure_ts(sk, skb);
__skb_pull(skb, tcp_header_len);
tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITSTOUSER);
}
if (copied_early)
tcp_cleanup_rbuf(sk, skb->len);
}
if (!eaten) {
if (tcp_checksum_complete_user(sk, skb))
goto csum_error;
if ((int)skb->truesize > sk->sk_forward_alloc)
goto step5;
/* Predicted packet is in window by definition.
* seq == rcv_nxt and rcv_wup <= rcv_nxt.
* Hence, check seq<=rcv_wup reduces to:
*/
if (tcp_header_len ==
(sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
tp->rcv_nxt == tp->rcv_wup)
tcp_store_ts_recent(tp);
tcp_rcv_rtt_measure_ts(sk, skb);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITS);
/* Bulk data transfer: receiver */
eaten = tcp_queue_rcv(sk, skb, tcp_header_len,
&fragstolen);
}
tcp_event_data_recv(sk, skb);
if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
/* Well, only one small jumplet in fast path... */
tcp_ack(sk, skb, FLAG_DATA);
tcp_data_snd_check(sk);
if (!inet_csk_ack_scheduled(sk))
goto no_ack;
}
if (!copied_early || tp->rcv_nxt != tp->rcv_wup)
__tcp_ack_snd_check(sk, 0);
no_ack:
#ifdef CONFIG_NET_DMA
if (copied_early)
__skb_queue_tail(&sk->sk_async_wait_queue, skb);
else
#endif
if (eaten)
kfree_skb_partial(skb, fragstolen);
sk->sk_data_ready(sk, 0);
return 0;
}
}
slow_path:
if (len < (th->doff << 2) || tcp_checksum_complete_user(sk, skb))
goto csum_error;
if (!th->ack && !th->rst)
goto discard;
/*
* Standard slow path.
*/
if (!tcp_validate_incoming(sk, skb, th, 1))
return 0;
step5:
if (tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) < 0)
goto discard;
tcp_rcv_rtt_measure_ts(sk, skb);
/* Process urgent data. */
tcp_urg(sk, skb, th);
/* step 7: process the segment text */
tcp_data_queue(sk, skb);
tcp_data_snd_check(sk);
tcp_ack_snd_check(sk);
return 0;
csum_error:
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_CSUMERRORS);
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
discard:
__kfree_skb(skb);
return 0;
}
EXPORT_SYMBOL(tcp_rcv_established);
void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
tcp_set_state(sk, TCP_ESTABLISHED);
if (skb != NULL) {
icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
security_inet_conn_established(sk, skb);
}
/* Make sure socket is routed, for correct metrics. */
icsk->icsk_af_ops->rebuild_header(sk);
tcp_init_metrics(sk);
tcp_init_congestion_control(sk);
/* Prevent spurious tcp_cwnd_restart() on first data
* packet.
*/
tp->lsndtime = tcp_time_stamp;
tcp_init_buffer_space(sk);
if (sock_flag(sk, SOCK_KEEPOPEN))
inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp));
if (!tp->rx_opt.snd_wscale)
__tcp_fast_path_on(tp, tp->snd_wnd);
else
tp->pred_flags = 0;
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
}
}
static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
struct tcp_fastopen_cookie *cookie)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *data = tp->syn_data ? tcp_write_queue_head(sk) : NULL;
u16 mss = tp->rx_opt.mss_clamp;
bool syn_drop;
if (mss == tp->rx_opt.user_mss) {
struct tcp_options_received opt;
/* Get original SYNACK MSS value if user MSS sets mss_clamp */
tcp_clear_options(&opt);
opt.user_mss = opt.mss_clamp = 0;
tcp_parse_options(synack, &opt, 0, NULL);
mss = opt.mss_clamp;
}
if (!tp->syn_fastopen) /* Ignore an unsolicited cookie */
cookie->len = -1;
/* The SYN-ACK neither has cookie nor acknowledges the data. Presumably
* the remote receives only the retransmitted (regular) SYNs: either
* the original SYN-data or the corresponding SYN-ACK is lost.
*/
syn_drop = (cookie->len <= 0 && data && tp->total_retrans);
tcp_fastopen_cache_set(sk, mss, cookie, syn_drop);
if (data) { /* Retransmit unacked data in SYN */
tcp_for_write_queue_from(data, sk) {
if (data == tcp_send_head(sk) ||
__tcp_retransmit_skb(sk, data))
break;
}
tcp_rearm_rto(sk);
return true;
}
tp->syn_data_acked = tp->syn_data;
return false;
}
static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
const struct tcphdr *th, unsigned int len)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct tcp_fastopen_cookie foc = { .len = -1 };
int saved_clamp = tp->rx_opt.mss_clamp;
tcp_parse_options(skb, &tp->rx_opt, 0, &foc);
if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
tp->rx_opt.rcv_tsecr -= tp->tsoffset;
if (th->ack) {
/* rfc793:
* "If the state is SYN-SENT then
* first check the ACK bit
* If the ACK bit is set
* If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
* a reset (unless the RST bit is set, if so drop
* the segment and return)"
*/
if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt))
goto reset_and_undo;
if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
!between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
tcp_time_stamp)) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSACTIVEREJECTED);
goto reset_and_undo;
}
/* Now ACK is acceptable.
*
* "If the RST bit is set
* If the ACK was acceptable then signal the user "error:
* connection reset", drop the segment, enter CLOSED state,
* delete TCB, and return."
*/
if (th->rst) {
tcp_reset(sk);
goto discard;
}
/* rfc793:
* "fifth, if neither of the SYN or RST bits is set then
* drop the segment and return."
*
* See note below!
* --ANK(990513)
*/
if (!th->syn)
goto discard_and_undo;
/* rfc793:
* "If the SYN bit is on ...
* are acceptable then ...
* (our SYN has been ACKed), change the connection
* state to ESTABLISHED..."
*/
TCP_ECN_rcv_synack(tp, th);
tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
tcp_ack(sk, skb, FLAG_SLOWPATH);
/* Ok.. it's good. Set up sequence numbers and
* move to established.
*/
tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
/* RFC1323: The window in SYN & SYN/ACK segments is
* never scaled.
*/
tp->snd_wnd = ntohs(th->window);
if (!tp->rx_opt.wscale_ok) {
tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
tp->window_clamp = min(tp->window_clamp, 65535U);
}
if (tp->rx_opt.saw_tstamp) {
tp->rx_opt.tstamp_ok = 1;
tp->tcp_header_len =
sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
tcp_store_ts_recent(tp);
} else {
tp->tcp_header_len = sizeof(struct tcphdr);
}
if (tcp_is_sack(tp) && sysctl_tcp_fack)
tcp_enable_fack(tp);
tcp_mtup_init(sk);
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
tcp_initialize_rcv_mss(sk);
/* Remember, tcp_poll() does not lock socket!
* Change state from SYN-SENT only after copied_seq
* is initialized. */
tp->copied_seq = tp->rcv_nxt;
smp_mb();
tcp_finish_connect(sk, skb);
if ((tp->syn_fastopen || tp->syn_data) &&
tcp_rcv_fastopen_synack(sk, skb, &foc))
return -1;
if (sk->sk_write_pending ||
icsk->icsk_accept_queue.rskq_defer_accept ||
icsk->icsk_ack.pingpong) {
/* Save one ACK. Data will be ready after
* several ticks, if write_pending is set.
*
* It may be deleted, but with this feature tcpdumps
* look so _wonderfully_ clever, that I was not able
* to stand against the temptation 8) --ANK
*/
inet_csk_schedule_ack(sk);
icsk->icsk_ack.lrcvtime = tcp_time_stamp;
tcp_enter_quickack_mode(sk);
inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
TCP_DELACK_MAX, TCP_RTO_MAX);
discard:
__kfree_skb(skb);
return 0;
} else {
tcp_send_ack(sk);
}
return -1;
}
/* No ACK in the segment */
if (th->rst) {
/* rfc793:
* "If the RST bit is set
*
* Otherwise (no ACK) drop the segment and return."
*/
goto discard_and_undo;
}
/* PAWS check. */
if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
tcp_paws_reject(&tp->rx_opt, 0))
goto discard_and_undo;
if (th->syn) {
/* We see SYN without ACK. It is attempt of
* simultaneous connect with crossed SYNs.
* Particularly, it can be connect to self.
*/
tcp_set_state(sk, TCP_SYN_RECV);
if (tp->rx_opt.saw_tstamp) {
tp->rx_opt.tstamp_ok = 1;
tcp_store_ts_recent(tp);
tp->tcp_header_len =
sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
} else {
tp->tcp_header_len = sizeof(struct tcphdr);
}
tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
/* RFC1323: The window in SYN & SYN/ACK segments is
* never scaled.
*/
tp->snd_wnd = ntohs(th->window);
tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
tp->max_window = tp->snd_wnd;
TCP_ECN_rcv_syn(tp, th);
tcp_mtup_init(sk);
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
tcp_initialize_rcv_mss(sk);
tcp_send_synack(sk);
#if 0
/* Note, we could accept data and URG from this segment.
* There are no obstacles to make this (except that we must
* either change tcp_recvmsg() to prevent it from returning data
* before 3WHS completes per RFC793, or employ TCP Fast Open).
*
* However, if we ignore data in ACKless segments sometimes,
* we have no reasons to accept it sometimes.
* Also, seems the code doing it in step6 of tcp_rcv_state_process
* is not flawless. So, discard packet for sanity.
* Uncomment this return to process the data.
*/
return -1;
#else
goto discard;
#endif
}
/* "fifth, if neither of the SYN or RST bits is set then
* drop the segment and return."
*/
discard_and_undo:
tcp_clear_options(&tp->rx_opt);
tp->rx_opt.mss_clamp = saved_clamp;
goto discard;
reset_and_undo:
tcp_clear_options(&tp->rx_opt);
tp->rx_opt.mss_clamp = saved_clamp;
return 1;
}
/*
* This function implements the receiving procedure of RFC 793 for
* all states except ESTABLISHED and TIME_WAIT.
* It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
* address independent.
*/
int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
const struct tcphdr *th, unsigned int len)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct request_sock *req;
int queued = 0;
tp->rx_opt.saw_tstamp = 0;
switch (sk->sk_state) {
case TCP_CLOSE:
goto discard;
case TCP_LISTEN:
if (th->ack)
return 1;
if (th->rst)
goto discard;
if (th->syn) {
if (th->fin)
goto discard;
if (icsk->icsk_af_ops->conn_request(sk, skb) < 0)
return 1;
/* Now we have several options: In theory there is
* nothing else in the frame. KA9Q has an option to
* send data with the syn, BSD accepts data with the
* syn up to the [to be] advertised window and
* Solaris 2.1 gives you a protocol error. For now
* we just ignore it, that fits the spec precisely
* and avoids incompatibilities. It would be nice in
* future to drop through and process the data.
*
* Now that TTCP is starting to be used we ought to
* queue this data.
* But, this leaves one open to an easy denial of
* service attack, and SYN cookies can't defend
* against this problem. So, we drop the data
* in the interest of security over speed unless
* it's still in use.
*/
kfree_skb(skb);
return 0;
}
goto discard;
case TCP_SYN_SENT:
queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
if (queued >= 0)
return queued;
/* Do step6 onward by hand. */
tcp_urg(sk, skb, th);
__kfree_skb(skb);
tcp_data_snd_check(sk);
return 0;
}
req = tp->fastopen_rsk;
if (req != NULL) {
WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
sk->sk_state != TCP_FIN_WAIT1);
if (tcp_check_req(sk, skb, req, NULL, true) == NULL)
goto discard;
}
if (!th->ack && !th->rst)
goto discard;
if (!tcp_validate_incoming(sk, skb, th, 0))
return 0;
/* step 5: check the ACK field */
if (true) {
int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH |
FLAG_UPDATE_TS_RECENT) > 0;
switch (sk->sk_state) {
case TCP_SYN_RECV:
if (acceptable) {
/* Once we leave TCP_SYN_RECV, we no longer
* need req so release it.
*/
if (req) {
tcp_synack_rtt_meas(sk, req);
tp->total_retrans = req->num_retrans;
reqsk_fastopen_remove(sk, req, false);
} else {
/* Make sure socket is routed, for
* correct metrics.
*/
icsk->icsk_af_ops->rebuild_header(sk);
tcp_init_congestion_control(sk);
tcp_mtup_init(sk);
tcp_init_buffer_space(sk);
tp->copied_seq = tp->rcv_nxt;
}
smp_mb();
tcp_set_state(sk, TCP_ESTABLISHED);
sk->sk_state_change(sk);
/* Note, that this wakeup is only for marginal
* crossed SYN case. Passively open sockets
* are not waked up, because sk->sk_sleep ==
* NULL and sk->sk_socket == NULL.
*/
if (sk->sk_socket)
sk_wake_async(sk,
SOCK_WAKE_IO, POLL_OUT);
tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
tp->snd_wnd = ntohs(th->window) <<
tp->rx_opt.snd_wscale;
tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
if (tp->rx_opt.tstamp_ok)
tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
if (req) {
/* Re-arm the timer because data may
* have been sent out. This is similar
* to the regular data transmission case
* when new data has just been ack'ed.
*
* (TFO) - we could try to be more
* aggressive and retranmitting any data
* sooner based on when they were sent
* out.
*/
tcp_rearm_rto(sk);
} else
tcp_init_metrics(sk);
tcp_update_pacing_rate(sk);
/* Prevent spurious tcp_cwnd_restart() on
* first data packet.
*/
tp->lsndtime = tcp_time_stamp;
tcp_initialize_rcv_mss(sk);
tcp_fast_path_on(tp);
} else {
return 1;
}
break;
case TCP_FIN_WAIT1:
/* If we enter the TCP_FIN_WAIT1 state and we are a
* Fast Open socket and this is the first acceptable
* ACK we have received, this would have acknowledged
* our SYNACK so stop the SYNACK timer.
*/
if (req != NULL) {
/* Return RST if ack_seq is invalid.
* Note that RFC793 only says to generate a
* DUPACK for it but for TCP Fast Open it seems
* better to treat this case like TCP_SYN_RECV
* above.
*/
if (!acceptable)
return 1;
/* We no longer need the request sock. */
reqsk_fastopen_remove(sk, req, false);
tcp_rearm_rto(sk);
}
if (tp->snd_una == tp->write_seq) {
struct dst_entry *dst;
tcp_set_state(sk, TCP_FIN_WAIT2);
sk->sk_shutdown |= SEND_SHUTDOWN;
dst = __sk_dst_get(sk);
if (dst)
dst_confirm(dst);
if (!sock_flag(sk, SOCK_DEAD))
/* Wake up lingering close() */
sk->sk_state_change(sk);
else {
int tmo;
if (tp->linger2 < 0 ||
(TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
tcp_done(sk);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
return 1;
}
tmo = tcp_fin_time(sk);
if (tmo > TCP_TIMEWAIT_LEN) {
inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
} else if (th->fin || sock_owned_by_user(sk)) {
/* Bad case. We could lose such FIN otherwise.
* It is not a big problem, but it looks confusing
* and not so rare event. We still can lose it now,
* if it spins in bh_lock_sock(), but it is really
* marginal case.
*/
inet_csk_reset_keepalive_timer(sk, tmo);
} else {
tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
goto discard;
}
}
}
break;
case TCP_CLOSING:
if (tp->snd_una == tp->write_seq) {
tcp_time_wait(sk, TCP_TIME_WAIT, 0);
goto discard;
}
break;
case TCP_LAST_ACK:
if (tp->snd_una == tp->write_seq) {
tcp_update_metrics(sk);
tcp_done(sk);
goto discard;
}
break;
}
}
/* step 6: check the URG bit */
tcp_urg(sk, skb, th);
/* step 7: process the segment text */
switch (sk->sk_state) {
case TCP_CLOSE_WAIT:
case TCP_CLOSING:
case TCP_LAST_ACK:
if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
break;
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
/* RFC 793 says to queue data in these states,
* RFC 1122 says we MUST send a reset.
* BSD 4.4 also does reset.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN) {
if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
tcp_reset(sk);
return 1;
}
}
/* Fall through */
case TCP_ESTABLISHED:
tcp_data_queue(sk, skb);
queued = 1;
break;
}
/* tcp_data could move socket to TIME-WAIT */
if (sk->sk_state != TCP_CLOSE) {
tcp_data_snd_check(sk);
tcp_ack_snd_check(sk);
}
if (!queued) {
discard:
__kfree_skb(skb);
}
return 0;
}
EXPORT_SYMBOL(tcp_rcv_state_process);
|
chhapil/Kernel-Lenovo-A6000-KK
|
net/ipv4/tcp_input.c
|
C
|
gpl-2.0
| 170,207
|
<?php
/**
* Unit tests for ParamBag.
*
* PHP version 5
*
* Copyright (C) Villanova University 2010.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Search
* @author David Maus <maus@hab.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org
*/
namespace VuFindTest;
use PHPUnit_Framework_TestCase as TestCase;
use VuFindSearch\ParamBag;
/**
* Unit tests for ParamBag.
*
* @category VuFind
* @package Search
* @author David Maus <maus@hab.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org
*/
class ParamBagTest extends TestCase
{
/**
* Test "contains"
*
* @return void
*/
public function testContains()
{
$bag = new ParamBag();
$bag->set('foo', 'bar');
$this->assertTrue($bag->contains('foo', 'bar'));
$this->assertFalse($bag->contains('bar', 'foo'));
$this->assertFalse($bag->contains('foo', 'baz'));
}
/**
* Test "hasParam"
*
* @return void
*/
public function testHasParam()
{
$bag = new ParamBag();
$bag->set('foo', 'bar');
$this->assertTrue($bag->hasParam('foo'));
$this->assertFalse($bag->hasParam('bar'));
}
/**
* Test "remove"
*
* @return void
*/
public function testRemove()
{
$bag = new ParamBag();
$bag->set('foo', 'bar');
$bag->set('bar', 'baz');
$bag->remove('foo');
$this->assertEquals(['bar' => ['baz']], $bag->getArrayCopy());
}
/**
* Test "merge with all"
*
* @return void
*/
public function testMergeWithAll()
{
$bag1 = new ParamBag(['a' => 1]);
$bag2 = new ParamBag(['b' => 2]);
$bag3 = new ParamBag(['c' => 3]);
$bag3->mergeWithAll([$bag1, $bag2]);
$this->assertEquals(['a' => [1], 'b' => [2], 'c' => [3]], $bag3->getArrayCopy());
}
}
|
bbeckman/NDL-VuFind2
|
module/VuFindSearch/tests/unit-tests/src/VuFindTest/ParamBagTest.php
|
PHP
|
gpl-2.0
| 2,652
|
<!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.6.0_33) on Fri Jun 22 11:01:54 IST 2012 -->
<TITLE>
de.fuberlin.wiwiss.d2rq.nodes Class Hierarchy (D2RQ)
</TITLE>
<META NAME="date" CONTENT="2012-06-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="de.fuberlin.wiwiss.d2rq.nodes Class Hierarchy (D2RQ)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= 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=2 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"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </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-files/index-1.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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/mapgen/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/optimizer/expr/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?de/fuberlin/wiwiss/d2rq/nodes/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.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>
Hierarchy For Package de.fuberlin.wiwiss.d2rq.nodes
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/DetermineNodeType.html" title="class in de.fuberlin.wiwiss.d2rq.nodes"><B>DetermineNodeType</B></A> (implements de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeSetFilter.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes">NodeSetFilter</A>)
<LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/FixedNodeMaker.html" title="class in de.fuberlin.wiwiss.d2rq.nodes"><B>FixedNodeMaker</B></A> (implements de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeMaker.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes">NodeMaker</A>)
<LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeSetConstraintBuilder.html" title="class in de.fuberlin.wiwiss.d2rq.nodes"><B>NodeSetConstraintBuilder</B></A> (implements de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeSetFilter.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes">NodeSetFilter</A>)
<LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/TypedNodeMaker.html" title="class in de.fuberlin.wiwiss.d2rq.nodes"><B>TypedNodeMaker</B></A> (implements de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeMaker.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes">NodeMaker</A>)
</UL>
</UL>
<H2>
Interface Hierarchy
</H2>
<UL>
<LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeMaker.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes"><B>NodeMaker</B></A><LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/NodeSetFilter.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes"><B>NodeSetFilter</B></A><LI TYPE="circle">de.fuberlin.wiwiss.d2rq.nodes.<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/nodes/TypedNodeMaker.NodeType.html" title="interface in de.fuberlin.wiwiss.d2rq.nodes"><B>TypedNodeMaker.NodeType</B></A></UL>
<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=2 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"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </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-files/index-1.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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/mapgen/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/optimizer/expr/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?de/fuberlin/wiwiss/d2rq/nodes/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.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>
</BODY>
</HTML>
|
Augustus061193/OpenCollegeGraph
|
d2rq/doc/javadoc/de/fuberlin/wiwiss/d2rq/nodes/package-tree.html
|
HTML
|
gpl-2.0
| 8,389
|
/* Copyright (C) 2004 - 2009 Versant Inc. http://www.db4o.com */
using Db4objects.Db4o.Internal;
using Db4objects.Db4o.Internal.Delete;
using Db4objects.Db4o.Marshall;
using Db4objects.Db4o.Typehandlers;
namespace Db4objects.Db4o.Internal.Handlers
{
/// <summary>Tyehandler for naked plain objects (java.lang.Object).</summary>
/// <remarks>Tyehandler for naked plain objects (java.lang.Object).</remarks>
public class PlainObjectHandler : IReferenceTypeHandler
{
public virtual void Defragment(IDefragmentContext context)
{
}
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception>
public virtual void Delete(IDeleteContext context)
{
}
public virtual void Activate(IReferenceActivationContext context)
{
}
public virtual void Write(IWriteContext context, object obj)
{
}
}
}
|
meebey/smuxi-head-mirror
|
lib/db4o-net/Db4objects.Db4o/Db4objects.Db4o/Internal/Handlers/PlainObjectHandler.cs
|
C#
|
gpl-2.0
| 859
|
/*
* Freeplane - mind map editor
* Copyright (C) 2009 Dimitry
*
* This file author is Dimitry
*
* 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/>.
*/
package org.freeplane.view.swing.map;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import org.freeplane.core.ui.AFreeplaneAction;
import org.freeplane.core.ui.SelectableAction;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.styles.MapStyle;
import org.freeplane.features.styles.MapViewLayout;
/**
* @author Dimitry Polivaev
* 29.08.2009
*/
@SelectableAction(checkOnPopup = true)
public class ViewLayoutTypeAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private final MapViewLayout layoutType;
public ViewLayoutTypeAction(final MapViewLayout layoutType) {
super("ViewLayoutTypeAction." + layoutType.toString());
this.layoutType = layoutType;
}
public void actionPerformed(final ActionEvent e) {
final MapView map = (MapView) Controller.getCurrentController().getMapViewManager().getMapViewComponent();
if (isSelected()) {
map.setLayoutType(MapViewLayout.MAP);
setSelected(false);
}
else {
map.setLayoutType(layoutType);
setSelected(true);
}
final MapStyle mapStyle = (MapStyle) map.getModeController().getExtension(MapStyle.class);
mapStyle.setMapViewLayout(map.getModel(), map.getLayoutType());
map.getMapSelection().keepNodePosition(map.getSelected().getModel(), 0.5f, 0.5f);
final NodeView root = map.getRoot();
invalidate(root);
root.revalidate();
}
private void invalidate(final Component c) {
c.invalidate();
if(! (c instanceof Container))
return;
Container c2 = (Container) c;
for(int i = 0; i < c2.getComponentCount(); i++)
invalidate(c2.getComponent(i));
}
@Override
public void setSelected() {
final MapView map = (MapView) Controller.getCurrentController().getMapViewManager().getMapViewComponent();
setSelected(map != null && map.getLayoutType() == layoutType);
}
}
|
fnatter/freeplane-debian-dev
|
freeplane/src/main/java/org/freeplane/view/swing/map/ViewLayoutTypeAction.java
|
Java
|
gpl-2.0
| 2,662
|
/*
* Created on 20 mars 2005
*
* Firemox is a turn based strategy simulator
* Copyright (C) 2003-2007 Fabrice Daugan
*
* 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
*/
package net.sf.firemox.test;
import java.io.IOException;
import java.io.InputStream;
import net.sf.firemox.annotation.XmlTestElement;
import net.sf.firemox.clickable.ability.Ability;
import net.sf.firemox.clickable.target.Target;
/**
* @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a>
* @since 0.83
*/
@XmlTestElement(id = IdTest.IS_SPELL)
public class IsSpell extends TestObject {
/**
* Create an instance of IsSpell by reading a file. Offset's file must
* pointing on the first byte of this test <br>
* <ul>
* Structure of InputStream : Data[size]
* </ul>
*
* @param inputFile
* is the file containing this test
* @throws IOException
* if error occurred during the reading process from the specified
* input stream
*/
IsSpell(InputStream inputFile) throws IOException {
super(inputFile);
}
@Override
public boolean test(Ability ability, Target tested) {
return on.getTargetable(ability, tested).isSpell();
}
}
|
JoeyLeeuwinga/Firemox
|
src/main/java/net/sf/firemox/test/IsSpell.java
|
Java
|
gpl-2.0
| 1,930
|
/// <summary> Copyright (C) 2004 Free Software Foundation, Inc.
/// *
/// Author: Alexander Gnauck AG-Software, mailto:gnauck@ag-software.de
/// *
/// This file is part of GNU Libidn.
/// *
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public License
/// as published by the Free Software Foundation; either version 2.1 of
/// the License, or (at your option) any later version.
/// *
/// This library is distributed in the hope that it will be useful, but
/// WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
/// Lesser General Public License for more details.
/// *
/// You should have received a copy of the GNU Lesser General Public
/// License along with this library; if not, write to the Free Software
/// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
/// USA
/// </summary>
using System;
namespace agsXMPP.Idn
{
public class StringprepException : Exception
{
public static string CONTAINS_UNASSIGNED = "Contains unassigned code points.";
public static string CONTAINS_PROHIBITED = "Contains prohibited code points.";
public static string BIDI_BOTHRAL = "Contains both R and AL code points.";
public static string BIDI_LTRAL = "Leading and trailing code points not both R or AL.";
public StringprepException(string message) : base(message)
{
}
}
}
|
octgn/Agsxmpp
|
trunk/agsxmpp/Idn/StringprepException.cs
|
C#
|
gpl-2.0
| 1,493
|
/*
Theme Name: Silver Blue
Theme URI: http://www.alappin.com/wordpress-themes
Author: Alappin
Author URI: http://www.alappin.com/
Description: The Silver Blue theme for WordPress is a fully responsive and elegant theme that looks great with a touch of silver and blue styling. Customizable menu, header image, and background.
Version: 1.0.2
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, gray, red, silver, blue, white, one-column, two-columns, right-sidebar, flexible-width, custom-background, custom-header, custom-menu, editor-style, featured-images, flexible-header, full-width-template, microformats, post-formats, rtl-language-support, sticky-post, theme-options, translation-ready
Text Domain: silverblue
Feel free to use the theme for whatever purpose you see fit.
Attributing the author is greatly appreciated.
*/
/*** === Notes === ***/
/* -------------------------------------------------------------- */
/*
key: id(class)
Site Structure:
page(site)
{
masthead(site-header)
{
site-navigation(main-navigation)
}
main(wrapper)
{
}
(footer)
{
colophon(footer)
{
(site-info) (site-social)
}
}
}
*/
/* === reset === */
/* -------------------------------------------------------------- */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
vertical-align: baseline;
}
body {
line-height: 1;
}
ol,
ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
caption,
th,
td {
font-weight: normal;
text-align: left;
}
h1,
h2,
h3,
h4,
h5,
h6 {
clear: both;
}
html {
overflow-y: scroll;
font-size: 100%;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
a:focus {
outline: thin dotted;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
nav,
section {
display: block;
}
audio,
canvas,
video {
display: inline-block;
}
audio:not([controls]) {
display: none;
}
del {
color: #333;
}
ins {
background: #fff9c0;
text-decoration: none;
}
hr {
background-color: #ccc;
border: 0;
height: 1px;
margin: 24px;
margin-bottom: 1.714285714rem;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
small {
font-size: smaller;
}
img {
border: 0;
-ms-interpolation-mode: bicubic;
}
/* Clearing floats */
.clear:after,
.wrapper:after,
.format-status .entry-header:after {
clear: both;
}
.clear:before,
.clear:after,
.wrapper:before,
.wrapper:after,
.format-status .entry-header:before,
.format-status .entry-header:after {
display: table;
content: "";
}
/* === Styling Defaults === */
/* -------------------------------------------------------------- */
/* Small headers */
.archive-title,
.page-title,
.widget-title,
.entry-content th,
.comment-content th {
font-size: 11px;
font-size: 0.785714286rem;
line-height: 2.181818182;
font-weight: bold;
text-transform: uppercase;
color: #636363;
}
/* Shared Post Format styling */
article.format-quote footer.entry-meta,
article.format-link footer.entry-meta,
article.format-status footer.entry-meta {
font-size: 11px;
font-size: 0.785714286rem;
line-height: 2.181818182;
}
/* Form fields, general styles first */
button,
input,
textarea {
border: 1px solid #ccc;
border-radius: 3px;
font-family: inherit;
padding: 6px;
padding: 0.428571429rem;
}
button,
input {
line-height: normal;
}
textarea {
font-size: 100%;
overflow: auto;
vertical-align: top;
}
/* Reset non-text input types */
input[type="checkbox"],
input[type="radio"],
input[type="file"],
input[type="hidden"],
input[type="image"],
input[type="color"] {
border: 0;
border-radius: 0;
padding: 0;
}
/* Buttons */
.menu-toggle,
input[type="submit"],
input[type="button"],
input[type="reset"],
article.post-password-required input[type=submit],
li.bypostauthor cite span {
padding: 6px 10px;
padding: 0.428571429rem 0.714285714rem;
font-size: 11px;
font-size: 0.785714286rem;
line-height: 1.428571429;
font-weight: normal;
color: #7c7c7c;
background-color: #e6e6e6;
background-repeat: repeat-x;
background-image: -moz-linear-gradient(top, #f4f4f4, #e6e6e6);
background-image: -ms-linear-gradient(top, #f4f4f4, #e6e6e6);
background-image: -webkit-linear-gradient(top, #f4f4f4, #e6e6e6);
background-image: -o-linear-gradient(top, #f4f4f4, #e6e6e6);
background-image: linear-gradient(top, #f4f4f4, #e6e6e6);
border: 1px solid #d2d2d2;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(64, 64, 64, 0.1);
}
.menu-toggle,
button,
input[type="submit"],
input[type="button"],
input[type="reset"] {
cursor: pointer;
}
button[disabled],
input[disabled] {
cursor: default;
}
.menu-toggle:hover,
button:hover,
input[type="submit"]:hover,
input[type="button"]:hover,
input[type="reset"]:hover,
article.post-password-required input[type=submit]:hover {
color: #5e5e5e;
background-color: #ebebeb;
background-repeat: repeat-x;
background-image: -moz-linear-gradient(top, #f9f9f9, #ebebeb);
background-image: -ms-linear-gradient(top, #f9f9f9, #ebebeb);
background-image: -webkit-linear-gradient(top, #f9f9f9, #ebebeb);
background-image: -o-linear-gradient(top, #f9f9f9, #ebebeb);
background-image: linear-gradient(top, #f9f9f9, #ebebeb);
}
.menu-toggle:active,
.menu-toggle.toggled-on,
button:active,
input[type="submit"]:active,
input[type="button"]:active,
input[type="reset"]:active {
color: #757575;
background-color: #e1e1e1;
background-repeat: repeat-x;
background-image: -moz-linear-gradient(top, #ebebeb, #e1e1e1);
background-image: -ms-linear-gradient(top, #ebebeb, #e1e1e1);
background-image: -webkit-linear-gradient(top, #ebebeb, #e1e1e1);
background-image: -o-linear-gradient(top, #ebebeb, #e1e1e1);
background-image: linear-gradient(top, #ebebeb, #e1e1e1);
box-shadow: inset 0 0 8px 2px #c6c6c6, 0 1px 0 0 #f4f4f4;
border: none;
}
li.bypostauthor cite span {
color: #fff;
background-color: #21759b;
background-image: none;
border: 1px solid #1f6f93;
border-radius: 2px;
box-shadow: none;
padding: 0;
}
/* Responsive images */
.entry-content img,
.comment-content img,
.widget img {
max-width: 100%; /* Fluid images for posts, comments, and widgets */
}
img[class*="align"],
img[class*="wp-image-"],
img[class*="attachment-"] {
height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */
}
img.size-full,
img.size-large,
img.header-image,
img.wp-post-image {
max-width: 100%;
height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */
}
/* Make sure videos and embeds fit their containers */
embed,
iframe,
object,
video {
max-width: 100%;
}
.entry-content .twitter-tweet-rendered {
max-width: 100% !important; /* Override the Twitter embed fixed width */
}
/* Images */
.alignleft {
float: left;
}
.alignright {
float: right;
}
.aligncenter {
display: block;
margin-left: auto;
margin-right: auto;
}
.entry-content img,
.comment-content img,
.widget img,
/*img.header-image,*/
.author-avatar img,
img.wp-post-image {
/* Add fancy borders to all WordPress-added images but not things like badges and icons and the like */
border-radius: 3px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}
.wp-caption {
max-width: 100%; /* Keep wide captions from overflowing their container. */
padding: 4px;
}
.wp-caption .wp-caption-text,
.gallery-caption,
.entry-caption {
font-style: italic;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 2;
color: #757575;
}
img.wp-smiley,
.rsswidget img {
border: 0;
border-radius: 0;
box-shadow: none;
margin-bottom: 0;
margin-top: 0;
padding: 0;
}
.entry-content dl.gallery-item {
margin: 0;
}
.gallery-item a,
.gallery-caption {
width: 90%;
}
.gallery-item a {
display: block;
}
.gallery-caption a {
display: inline;
}
.gallery-columns-1 .gallery-item a {
max-width: 100%;
width: auto;
}
.gallery .gallery-icon img {
height: auto;
max-width: 90%;
padding: 5%;
}
.gallery-columns-1 .gallery-icon img {
padding: 3%;
}
/*** === navigation === ***/
/* -------------------------------------------------------------- */
.site-content nav {
clear: both;
line-height: 2;
overflow: hidden;
}
#nav-above {
padding: 24px 0;
padding: 1.714285714rem 0;
}
#nav-above {
display: none;
}
.paged #nav-above {
display: block;
}
.nav-previous,
.previous-image {
float: left;
width: 50%;
}
.nav-next,
.next-image {
float: right;
text-align: right;
width: 50%;
}
.nav-single + .comments-area,
#comment-nav-above {
margin: 48px 0;
margin: 3.428571429rem 0;
}
/* Author profiles */
.author .archive-header {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.author-info {
border-top: 1px solid #ededed;
margin: 24px 0;
margin: 1.714285714rem 0;
padding-top: 24px;
padding-top: 1.714285714rem;
overflow: hidden;
}
.author-description p {
color: #757575;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
}
.author.archive .author-info {
border-top: 0;
margin: 0 0 48px;
margin: 0 0 3.428571429rem;
}
.author.archive .author-avatar {
margin-top: 0;
}
/*** === basic structure === ***/
/* -------------------------------------------------------------- */
/* Body, links, basics */
html {
font-size: 87.5%;
}
body {
font-size: 14px;
font-size: 1rem;
font-family: Helvetica, Arial, sans-serif;
text-rendering: optimizeLegibility;
color: #444;
}
body.custom-font-enabled {
font-family: "Open Sans", Helvetica, Arial, sans-serif;
}
a {
outline: none;
color: #21759b;
}
a:hover {
/*color: #0f3647;*/
color: rgb(26,103,235);
}
/* Assistive text */
.assistive-text,
.site .screen-reader-text {
position: absolute !important;
clip: rect(1px, 1px, 1px, 1px);
}
.main-navigation .assistive-text:hover,
.main-navigation .assistive-text:active,
.main-navigation .assistive-text:focus {
background: #fff;
border: 2px solid #333;
border-radius: 3px;
clip: auto !important;
color: #000;
display: block;
font-size: 12px;
padding: 12px;
position: absolute;
top: 5px;
left: 5px;
z-index: 100000; /* Above WP toolbar */
}
/*** === site structure === ***/
/* -------------------------------------------------------------- */
/* Page structure */
.site {
padding: 0px;
background-color: #fff;
}
.wrapper {
width:100%;
display: block;
margin: 0;
padding: 0 0 24px 0;
padding: 0 0 1.714285714rem 0;
}
.site-wrap{
margin: 0 auto;
}
.site-content {
margin: 24px 0 0;
margin: 1.714285714rem 0 0;
}
.widget-area {
margin: 24px 0 0;
margin: 1.714285714rem 0 0;
}
/* Header */
.site-header {
padding: 24px 0 0 0;
padding: 1.714285714rem 0 0 0;
}
.site-header h1,
.site-header h2 {
text-align: center;
}
.site-header h1 a,
.site-header h2 a {
color: #515151;
display: inline-block;
text-decoration: none;
}
.site-header h1 a:hover,
.site-header h2 a:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
.site-header h1 {
font-size: 24px;
font-size: 1.714285714rem;
line-height: 1.285714286;
margin-bottom: 14px;
margin-bottom: 1rem;
}
.site-header h2 {
font-weight: normal;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
color: #757575;
}
.header-image {
margin-top: 24px;
margin-top: 1.714285714rem;
}
/* Navigation Menu */
.main-navigation {
margin-top: 24px;
margin-top: 1.714285714rem;
text-align: center;
}
.main-navigation li {
margin-top: 24px;
margin-top: 1.714285714rem;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 1.42857143;
}
.main-navigation a {
color: #5e5e5e;
}
.main-navigation a:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
.main-navigation ul.nav-menu,
.main-navigation div.nav-menu > ul {
display: none;
}
.main-navigation ul.nav-menu.toggled-on,
.menu-toggle {
display: inline-block;
}
/* Banner */
section[role="banner"] {
margin-bottom: 48px;
margin-bottom: 3.428571429rem;
}
/* Sidebar */
.widget-area .widget {
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
margin-bottom: 48px;
margin-bottom: 3.428571429rem;
word-wrap: break-word;
}
.widget-area .widget h3 {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.widget-area .widget p,
.widget-area .widget li,
.widget-area .widget .textwidget {
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
}
.widget-area .widget p {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.widget-area .textwidget ul {
list-style: disc outside;
margin: 0 0 24px;
margin: 0 0 1.714285714rem;
}
.widget-area .textwidget li {
margin-left: 36px;
margin-left: 2.571428571rem;
}
.widget-area .widget a {
color: #757575;
}
.widget-area .widget a:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
.widget-area #s {
width: 53.66666666666%; /* define a width to avoid dropping a wider submit button */
}
/* Footer */
.footer {
width: 100%;
display: block;
border-top: 1px solid #ededed;
}
footer[role="contentinfo"] {
clear: both;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 2;
max-width: 960px;
max-width: 68.571428571rem;
margin:0;
margin-left: auto;
margin-right: auto;
padding: 24px 0;
padding: 1.714285714rem 0;
}
footer[role="contentinfo"] a {
color: #686868;
}
footer[role="contentinfo"] a:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
/*** === Main content and comment content === ***/
/* -------------------------------------------------------------- */
.entry-meta {
clear: both;
}
.entry-header {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.entry-header img.wp-post-image {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.entry-header .entry-title {
font-size: 30px;
font-size: 2.142857143rem;
line-height: 1.2;
font-weight: bold;
}
.entry-header .entry-title a {
color: rgb(45, 45, 45);
text-decoration: none;
text-shadow: 1px 1px 0px rgb(223, 223, 223), 2px 2px 0px rgb(185, 185, 185);
}
.entry-title a:hover {
color: rgb(26,103,235);
text-decoration: none;
text-shadow: 1px 1px 0px rgb(223, 223, 223), 2px 2px 0px rgb(185, 185, 185);
}
.entry-header .entry-format {
margin-top: 24px;
margin-top: 1.714285714rem;
font-weight: normal;
}
.entry-header .comments-link {
margin-top: 24px;
margin-top: 1.714285714rem;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
color: #757575;
}
.comments-link a,
.entry-meta a {
color: #757575;
}
.comments-link a:hover,
.entry-meta a:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
article.sticky .featured-post {
border-top: 4px double #ededed;
border-bottom: 4px double #ededed;
color: #757575;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 3.692307692;
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
text-align: center;
}
.entry-content,
.entry-summary,
.mu_register {
line-height: 1.714285714;
}
.entry-content h1,
.comment-content h1,
.entry-content h2,
.comment-content h2,
.entry-content h3,
.comment-content h3,
.entry-content h4,
.comment-content h4,
.entry-content h5,
.comment-content h5,
.entry-content h6,
.comment-content h6 {
margin: 24px 0;
margin: 1.714285714rem 0;
line-height: 1.714285714;
}
.entry-content h1,
.comment-content h1 {
font-size: 21px;
font-size: 1.5rem;
line-height: 1.5;
}
.entry-content h2,
.comment-content h2,
.mu_register h2 {
font-size: 18px;
font-size: 1.285714286rem;
line-height: 1.6;
}
.entry-content h3,
.comment-content h3 {
font-size: 16px;
font-size: 1.142857143rem;
line-height: 1.846153846;
}
.entry-content h4,
.comment-content h4 {
font-size: 14px;
font-size: 1rem;
line-height: 1.846153846;
}
.entry-content h5,
.comment-content h5 {
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
}
.entry-content h6,
.comment-content h6 {
font-size: 12px;
font-size: 0.857142857rem;
line-height: 1.846153846;
}
.entry-content p,
.entry-summary p,
.comment-content p,
.mu_register p {
margin: 0 0 24px;
margin: 0 0 1.714285714rem;
line-height: 1.714285714;
}
.entry-content ol,
.comment-content ol,
.entry-content ul,
.comment-content ul,
.mu_register ul {
margin: 0 0 24px;
margin: 0 0 1.714285714rem;
line-height: 1.714285714;
}
.entry-content ul ul,
.comment-content ul ul,
.entry-content ol ol,
.comment-content ol ol,
.entry-content ul ol,
.comment-content ul ol,
.entry-content ol ul,
.comment-content ol ul {
margin-bottom: 0;
}
.entry-content ul,
.comment-content ul,
.mu_register ul {
list-style: disc outside;
}
.entry-content ol,
.comment-content ol {
list-style: decimal outside;
}
.entry-content li,
.comment-content li,
.mu_register li {
margin: 0 0 0 36px;
margin: 0 0 0 2.571428571rem;
}
.entry-content blockquote,
.comment-content blockquote {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
padding: 24px;
padding: 1.714285714rem;
font-style: italic;
}
.entry-content blockquote p:last-child,
.comment-content blockquote p:last-child {
margin-bottom: 0;
}
.entry-content code,
.comment-content code {
font-family: Consolas, Monaco, Lucida Console, monospace;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 2;
}
.entry-content pre,
.comment-content pre {
border: 1px solid #ededed;
color: #666;
font-family: Consolas, Monaco, Lucida Console, monospace;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 1.714285714;
margin: 24px 0;
margin: 1.714285714rem 0;
overflow: auto;
padding: 24px;
padding: 1.714285714rem;
}
.entry-content pre code,
.comment-content pre code {
display: block;
}
.entry-content abbr,
.comment-content abbr,
.entry-content dfn,
.comment-content dfn,
.entry-content acronym,
.comment-content acronym {
border-bottom: 1px dotted #666;
cursor: help;
}
.entry-content address,
.comment-content address {
display: block;
line-height: 1.714285714;
margin: 0 0 24px;
margin: 0 0 1.714285714rem;
}
img.alignleft {
margin: 12px 24px 12px 0;
margin: 0.857142857rem 1.714285714rem 0.857142857rem 0;
}
img.alignright {
margin: 12px 0 12px 24px;
margin: 0.857142857rem 0 0.857142857rem 1.714285714rem;
}
img.aligncenter {
margin-top: 12px;
margin-top: 0.857142857rem;
margin-bottom: 12px;
margin-bottom: 0.857142857rem;
}
.entry-content embed,
.entry-content iframe,
.entry-content object,
.entry-content video {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.entry-content dl,
.comment-content dl {
margin: 0 24px;
margin: 0 1.714285714rem;
}
.entry-content dt,
.comment-content dt {
font-weight: bold;
line-height: 1.714285714;
}
.entry-content dd,
.comment-content dd {
line-height: 1.714285714;
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.entry-content table,
.comment-content table {
border-bottom: 1px solid #ededed;
color: #757575;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 2;
margin: 0 0 24px;
margin: 0 0 1.714285714rem;
width: 100%;
}
.entry-content table caption,
.comment-content table caption {
font-size: 16px;
font-size: 1.142857143rem;
margin: 24px 0;
margin: 1.714285714rem 0;
}
.entry-content td,
.comment-content td {
border-top: 1px solid #ededed;
padding: 6px 10px 6px 0;
}
.site-content article {
border-bottom: 4px double #ededed;
margin-bottom: 72px;
margin-bottom: 5.142857143rem;
padding-bottom: 24px;
padding-bottom: 1.714285714rem;
word-wrap: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}
.page-links {
clear: both;
line-height: 1.714285714;
}
footer.entry-meta {
margin-top: 24px;
margin-top: 1.714285714rem;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
color: #757575;
}
.single-author .entry-meta .by-author {
display: none;
}
.mu_register h2 {
color: #757575;
font-weight: normal;
}
/*** === Archives === ***/
/* -------------------------------------------------------------- */
.archive-header,
.page-header {
margin-bottom: 48px;
margin-bottom: 3.428571429rem;
padding-bottom: 22px;
padding-bottom: 1.571428571rem;
border-bottom: 1px solid #ededed;
}
.archive-meta {
color: #757575;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 2;
margin-top: 22px;
margin-top: 1.571428571rem;
}
/*** === Single image attachment view === ***/
/* -------------------------------------------------------------- */
.article.attachment {
overflow: hidden;
}
.image-attachment div.attachment {
text-align: center;
}
.image-attachment div.attachment p {
text-align: center;
}
.image-attachment div.attachment img {
display: block;
height: auto;
margin: 0 auto;
max-width: 100%;
}
.image-attachment .entry-caption {
margin-top: 8px;
margin-top: 0.571428571rem;
}
/*** === Aside post format === ***/
/* -------------------------------------------------------------- */
article.format-aside h1 {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
article.format-aside h1 a {
text-decoration: none;
color: #4d525a;
}
article.format-aside h1 a:hover {
color: #2e3542;
}
article.format-aside .aside {
padding: 24px 24px 0;
padding: 1.714285714rem;
background: #d2e0f9;
border-left: 22px solid #a8bfe8;
}
article.format-aside p {
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
color: #4a5466;
}
article.format-aside blockquote:last-child,
article.format-aside p:last-child {
margin-bottom: 0;
}
/*** === Post formats === ***/
/* -------------------------------------------------------------- */
/* Image posts */
article.format-image footer h1 {
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
font-weight: normal;
}
article.format-image footer h2 {
font-size: 11px;
font-size: 0.785714286rem;
line-height: 2.181818182;
}
article.format-image footer a h2 {
font-weight: normal;
}
/* Link posts */
article.format-link header {
padding: 0 10px;
padding: 0 0.714285714rem;
float: right;
font-size: 11px;
font-size: 0.785714286rem;
line-height: 2.181818182;
font-weight: bold;
font-style: italic;
text-transform: uppercase;
color: #848484;
background-color: #ebebeb;
border-radius: 3px;
}
article.format-link .entry-content {
max-width: 80%;
float: left;
}
article.format-link .entry-content a {
font-size: 22px;
font-size: 1.571428571rem;
line-height: 1.090909091;
text-decoration: none;
}
/* Quote posts */
article.format-quote .entry-content p {
margin: 0;
padding-bottom: 24px;
padding-bottom: 1.714285714rem;
}
article.format-quote .entry-content blockquote {
display: block;
padding: 24px 24px 0;
padding: 1.714285714rem 1.714285714rem 0;
font-size: 15px;
font-size: 1.071428571rem;
line-height: 1.6;
font-style: normal;
color: #6a6a6a;
background: #efefef;
}
/* Status posts */
.format-status .entry-header {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.format-status .entry-header header {
display: inline-block;
}
.format-status .entry-header h1 {
font-size: 15px;
font-size: 1.071428571rem;
font-weight: normal;
line-height: 1.6;
margin: 0;
}
.format-status .entry-header h2 {
font-size: 12px;
font-size: 0.857142857rem;
font-weight: normal;
line-height: 2;
margin: 0;
}
.format-status .entry-header header a {
color: #757575;
}
.format-status .entry-header header a:hover {
color: #21759b;
}
.format-status .entry-header img {
float: left;
margin-right: 21px;
margin-right: 1.5rem;
}
/*** === Comments === ***/
/* -------------------------------------------------------------- */
.comments-title {
margin-bottom: 48px;
margin-bottom: 3.428571429rem;
font-size: 16px;
font-size: 1.142857143rem;
line-height: 1.5;
font-weight: normal;
}
.comments-area article {
margin: 24px 0;
margin: 1.714285714rem 0;
}
.comments-area article header {
margin: 0 0 48px;
margin: 0 0 3.428571429rem;
overflow: hidden;
position: relative;
}
.comments-area article header img {
float: left;
padding: 0;
line-height: 0;
}
.comments-area article header cite,
.comments-area article header time {
display: block;
margin-left: 85px;
margin-left: 6.071428571rem;
}
.comments-area article header cite {
font-style: normal;
font-size: 15px;
font-size: 1.071428571rem;
line-height: 1.42857143;
}
.comments-area article header time {
line-height: 1.714285714;
text-decoration: none;
font-size: 12px;
font-size: 0.857142857rem;
color: #5e5e5e;
}
.comments-area article header a {
text-decoration: none;
color: #5e5e5e;
}
.comments-area article header a:hover {
color: #21759b;
}
.comments-area article header cite a {
color: #444;
}
.comments-area article header cite a:hover {
text-decoration: underline;
}
.comments-area article header h4 {
position: absolute;
top: 0;
right: 0;
padding: 6px 12px;
padding: 0.428571429rem 0.857142857rem;
font-size: 12px;
font-size: 0.857142857rem;
font-weight: normal;
color: #fff;
background-color: #0088d0;
background-repeat: repeat-x;
background-image: -moz-linear-gradient(top, #009cee, #0088d0);
background-image: -ms-linear-gradient(top, #009cee, #0088d0);
background-image: -webkit-linear-gradient(top, #009cee, #0088d0);
background-image: -o-linear-gradient(top, #009cee, #0088d0);
background-image: linear-gradient(top, #009cee, #0088d0);
border-radius: 3px;
border: 1px solid #007cbd;
}
.comments-area li.bypostauthor cite span {
position: absolute;
margin-left: 5px;
margin-left: 0.357142857rem;
padding: 2px 5px;
padding: 0.142857143rem 0.357142857rem;
font-size: 10px;
font-size: 0.714285714rem;
}
a.comment-reply-link,
a.comment-edit-link {
color: #686868;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
}
a.comment-reply-link:hover,
a.comment-edit-link:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
.commentlist .pingback {
line-height: 1.714285714;
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
/* Comment form */
#respond {
margin-top: 48px;
margin-top: 3.428571429rem;
}
#respond h3#reply-title {
font-size: 16px;
font-size: 1.142857143rem;
line-height: 1.5;
}
#respond h3#reply-title #cancel-comment-reply-link {
margin-left: 10px;
margin-left: 0.714285714rem;
font-weight: normal;
font-size: 12px;
font-size: 0.857142857rem;
}
#respond form {
margin: 24px 0;
margin: 1.714285714rem 0;
}
#respond form p {
margin: 11px 0;
margin: 0.785714286rem 0;
}
#respond form p.logged-in-as {
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
#respond form label {
display: block;
line-height: 1.714285714;
}
#respond form input[type="text"],
#respond form textarea {
-moz-box-sizing: border-box;
box-sizing: border-box;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 1.714285714;
padding: 10px;
padding: 0.714285714rem;
width: 100%;
}
#respond form p.form-allowed-tags {
margin: 0;
font-size: 12px;
font-size: 0.857142857rem;
line-height: 2;
color: #5e5e5e;
}
.required {
color: red;
}
/*** === Front page template === ***/
/* -------------------------------------------------------------- */
.entry-page-image {
margin-bottom: 14px;
margin-bottom: 1rem;
}
.template-front-page .site-content article {
border: 0;
margin-bottom: 0;
}
.template-front-page .widget-area {
clear: both;
float: none;
width: auto;
padding-top: 24px;
padding-top: 1.714285714rem;
border-top: 1px solid #ededed;
}
.template-front-page .widget-area .widget li {
margin: 8px 0 0;
margin: 0.571428571rem 0 0;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.714285714;
list-style-type: square;
list-style-position: inside;
}
.template-front-page .widget-area .widget li a {
color: #757575;
}
.template-front-page .widget-area .widget li a:hover {
/*color: #21759b;*/
color: rgb(26,103,235);
}
.template-front-page .widget-area .widget_text img {
float: left;
margin: 8px 24px 8px 0;
margin: 0.571428571rem 1.714285714rem 0.571428571rem 0;
}
/*** === Widgets === ***/
/* -------------------------------------------------------------- */
.widget-area .widget ul ul {
margin-left: 12px;
margin-left: 0.857142857rem;
}
.widget_rss li {
margin: 12px 0;
margin: 0.857142857rem 0;
}
.widget_recent_entries .post-date,
.widget_rss .rss-date {
color: #aaa;
font-size: 11px;
font-size: 0.785714286rem;
margin-left: 12px;
margin-left: 0.857142857rem;
}
#wp-calendar {
margin: 0;
width: 100%;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
color: #686868;
}
#wp-calendar th,
#wp-calendar td,
#wp-calendar caption {
text-align: left;
}
#wp-calendar #next {
padding-right: 24px;
padding-right: 1.714285714rem;
text-align: right;
}
.widget_search label {
display: block;
font-size: 13px;
font-size: 0.928571429rem;
line-height: 1.846153846;
}
.widget_twitter li {
list-style-type: none;
}
.widget_twitter .timesince {
display: block;
text-align: right;
}
/*** === Plugins === ***/
/* ----------------------------------------------- */
img#wpstats {
display: block;
margin: 0 auto 24px;
margin: 0 auto 1.714285714rem;
}
/*** === Media Screen === ***/
/* -------------------------------------------------------------- */
/* Minimum width of 600 pixels. */
@media screen and (min-width: 600px) {
.author-avatar {
float: left;
margin-top: 8px;
margin-top: 0.571428571rem;
}
.author-description {
float: right;
width: 80%;
}
::selection
{
color: white;
background-color: #4487f9;
}
::-moz-selection
{
color: white;
background-color: #4487f9;
}
.site {
margin: 0 auto;
max-width: 100%;
overflow: hidden;
}
.site-header {
z-index: 1;
position: relative;
/*Overwrite site-header styles*/
}
.wrapper{
/*Overwrite wrapper styles*/
}
.site-wrap{
margin: 0 auto;
max-width: 960px;
max-width: 68.571428571rem;
overflow: hidden;
}
.site-content {
float: left;
width: 65.104166667%;
}
.site-content article {
/*border-bottom: 4px double #ededed;*/
border-bottom:none;
background: url("img/silver-line-clear.png") no-repeat scroll center bottom transparent;
margin-bottom: 36px;
margin-bottom: 2.571428571rem;
padding-bottom: 42px;
padding-bottom: 3rem;
}
.comments-area article {
border-bottom: 4px double #ededed;
background: none;
}
.footer {
width: 100%;
display: block;
/*Overwrite footer styles*/
}
.footer .site-foot {
max-width: 960px;
max-width: 68.57142857rem;
min-height: 24px;
min-height: 1.714285714rem;
}
.footer .site-info{
max-width: 480px;
max-width: 34.28571429rem;
float: left;
display: block;
position: relative:
}
.footer .site-social{
max-width: 480px;
max-width: 34.28571429rem;
float: right;
display: block;
position: relative;
border: 1px solid #ededed;
border-radius: 5px 5px 5px 5px;
box-shadow: 0px 1px 2px rgba(0,0,0,0.4) inset;
}
.footer .site-social ul { float: right; list-style: none; padding: 0; margin: 0;}
.footer .site-social ul li {float: left; padding: 0px 10px 0px 10px;}
.footer .site-social ul li a {text-decoration:none;}
body.template-front-page .site-content,
body.single-attachment .site-content,
body.full-width .site-content {
width: 100%;
}
.widget-area {
float: right;
width: 26.041666667%;
padding: 7px;
padding: 0.5rem;
}
.widget-area .widget {
padding: 14px;
padding: 1rem;
background: linear-gradient(rgb(255, 255, 255), rgb(238, 238, 238)) repeat scroll 0% 0% transparent;
background: -webkit-linear-gradient(top, rgb(255, 255, 255), rgb(238, 238, 238)) repeat scroll 0% 0% transparent;
border-radius: 5px 5px 5px 5px;
box-shadow:
0 0 2px rgba(0, 0, 0, 0.2),
0 1px 1px rgba(0, 0, 0, .2),
0 3px 0 #fff,
0 4px 0 rgba(0, 0, 0, .2),
0 6px 0 #fff,
0 7px 0 rgba(0, 0, 0, .2);
position: relative;
z-index: 0;
}
.widget-area .widget:before {
content: '';
position: absolute;
z-index: -1;
border: 1px dashed #ccc;
top: 5px;
top: 0.3571428571rem;
bottom: 5px;
bottom: 0.3571428571rem;
left: 5px;
left: 0.3571428571rem;
right: 5px;
right: 0.3571428571rem;
-moz-box-shadow: 0 0 0 1px #fff;
-webkit-box-shadow: 0 0 0 1px #fff;
box-shadow: 0 0 0 1px #fff;
}
.site-header h1,
.site-header h2 {
text-align: left;
}
.site-header h1 {
font-size: 26px;
font-size: 1.857142857rem;
line-height: 1.846153846;
margin-bottom: 0;
}
.main-navigation div.nav-menu{
z-index: 10;
width: 100%;
background: linear-gradient(rgb(255, 255, 255), rgb(238, 238, 238)) repeat scroll 0% 0% transparent;
background: -webkit-linear-gradient(top, rgb(255, 255, 255), rgb(238, 238, 238)) repeat scroll 0% 0% transparent;
box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.4);
}
.main-navigation ul.nav-menu,
.main-navigation div.nav-menu > ul {
margin: 0 auto;
width: 960px;
width: 68.571428571rem;
display: inline-block !important;
text-align: left;
}
.main-navigation ul {
margin: 0;
text-indent: 0;
}
.main-navigation li a,
.main-navigation li {
display: inline-block;
text-decoration: none;
}
.main-navigation li a {
border-bottom: 0;
color: #6a6a6a;
line-height: 3.692307692;
text-transform: uppercase;
white-space: nowrap;
}
.main-navigation li a:hover {
color: #000;
}
.main-navigation li {
margin: 0px;
position: relative;
}
.main-navigation ul li a {
display: block;
background: transparent;
padding: 0px 28px;
padding: 0rem 2rem;
}
.main-navigation ul li:hover {
background: linear-gradient(rgb(249, 249, 249), rgb(229, 229, 229)) repeat scroll 0% 0% transparent;
background: -webkit-linear-gradient(top, rgb(249, 249, 249), rgb(229, 229, 229)) repeat scroll 0% 0% transparent;
}
.main-navigation li ul li{
padding: 0px;
}
.main-navigation li ul {
display: none;
margin: 0;
padding: 0;
position: absolute;
top: 100%;
z-index: 100;
}
.main-navigation li ul ul {
top: 0;
left: 100%;
}
.main-navigation ul li:hover > ul {
border-left: 0;
display: block;
}
.main-navigation li ul li a {
background: rgb(250,250,250);
border-bottom: 1px solid #ededed;
display: block;
font-size: 11px;
font-size: 0.785714286rem;
line-height: 2.181818182;
padding: 8px 10px;
padding: 0.571428571rem 0.714285714rem;
width: 180px;
width: 12.85714286rem;
white-space: normal;
}
.main-navigation li ul li a:hover {
background: rgb(246,246,246);
color: #444;
}
.main-navigation .current-menu-item, .main-navigation .current-menu-item:hover,
.main-navigation .current-menu-ancestor, .main-navigation .current-menu-ancestor:hover,
.main-navigation .current_page_item, .main-navigation .current_page_item:hover,
.main-navigation .current_page_ancestor, .main-navigation .current_page_ancestor:hover {
background: linear-gradient(rgb(70, 138, 248), rgb(26, 103, 235)) repeat scroll 0% 0% transparent;
background: -webkit-linear-gradient(top, rgb(70, 138, 248), rgb(26, 103, 235)) repeat scroll 0% 0% transparent;
}
.main-navigation .current-menu-item > a, .main-navigation .current-menu-item > a:hover,
.main-navigation .current-menu-ancestor > a, .main-navigation .current-menu-ancestor > a:hover,
.main-navigation .current_page_item > a, .main-navigation .current_page_item > a:hover,
.main-navigation .current_page_ancestor > a, .main-navigation .current_page_ancestor > a:hover {
color: #ffffff;
font-weight: bold;
}
.menu-toggle {
display: none;
}
.entry-header .entry-title {
font-size: 30px
font-size: 2.142857143rem;
}
#respond form input[type="text"] {
width: 46.333333333%;
}
#respond form textarea.blog-textarea {
width: 79.666666667%;
}
.template-front-page .site-content,
.template-front-page article {
overflow: hidden;
}
.template-front-page.has-post-thumbnail article {
float: left;
width: 47.916666667%;
}
.entry-page-image {
float: right;
margin-bottom: 0;
width: 47.916666667%;
}
.template-front-page .widget-area .widget,
.template-front-page.two-sidebars .widget-area .front-widgets {
float: left;
width: 51.875%;
margin-bottom: 24px;
margin-bottom: 1.714285714rem;
}
.template-front-page .widget-area .widget:nth-child(odd) {
clear: right;
}
.template-front-page .widget-area .widget:nth-child(even),
.template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets {
float: right;
width: 39.0625%;
margin: 0 0 24px;
margin: 0 0 1.714285714rem;
}
.template-front-page.two-sidebars .widget,
.template-front-page.two-sidebars .widget:nth-child(even) {
float: none;
width: auto;
}
.commentlist .children {
margin-left: 48px;
margin-left: 3.428571429rem;
}
}
/* Minimum width of 960 pixels. */
@media screen and (min-width: 960px) {
body {
background-color: #e6e6e6;
}
body .site {
padding: 0px;
margin-top: 0px;
margin-bottom: 0px;
box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3);
}
body.custom-background-empty {
background-color: #fff;
}
body.custom-background-empty .site,
body.custom-background-white .site {
padding: 0;
margin-top: 0;
margin-bottom: 0;
box-shadow: none;
}
}
/*** === Print === ***/
/* ----------------------------------------------- */
@media print {
body {
background: none !important;
color: #000;
font-size: 10pt;
}
footer a[rel=bookmark]:link:after,
footer a[rel=bookmark]:visited:after {
content: " [" attr(href) "] "; /* Show URLs */
}
a {
text-decoration: none;
}
.entry-content img,
.comment-content img,
.author-avatar img,
img.wp-post-image {
border-radius: 0;
box-shadow: none;
}
.site {
clear: both !important;
display: block !important;
float: none !important;
max-width: 100%;
position: relative !important;
}
.site-header {
margin-bottom: 72px;
margin-bottom: 5.142857143rem;
text-align: left;
}
.site-header h1 {
font-size: 21pt;
line-height: 1;
text-align: left;
}
.site-header h2 {
color: #000;
font-size: 10pt;
text-align: left;
}
.site-header h1 a,
.site-header h2 a {
color: #000;
}
.author-avatar,
#colophon,
#respond,
.commentlist .comment-edit-link,
.commentlist .reply,
.entry-header .comments-link,
.entry-meta .edit-link a,
.page-link,
.site-content nav,
.widget-area,
img.header-image,
.main-navigation {
display: none;
}
.wrapper {
border-top: none;
box-shadow: none;
}
.site-content {
margin: 0;
width: auto;
}
.singular .entry-header .entry-meta {
position: static;
}
.singular .site-content,
.singular .entry-header,
.singular .entry-content,
.singular footer.entry-meta,
.singular .comments-title {
margin: 0;
width: 100%;
}
.entry-header .entry-title,
.entry-title,
.singular .entry-title {
font-size: 21pt;
}
footer.entry-meta,
footer.entry-meta a {
color: #444;
font-size: 10pt;
}
.author-description {
float: none;
width: auto;
}
/* Comments */
.commentlist > li.comment {
background: none;
position: relative;
width: auto;
}
.commentlist .avatar {
height: 39px;
left: 2.2em;
top: 2.2em;
width: 39px;
}
.comments-area article header cite,
.comments-area article header time {
margin-left: 50px;
margin-left: 3.57142857rem;
}
}
|
bggo/wp-auction-os
|
wp-content/themes/silver-blue/style.css
|
CSS
|
gpl-2.0
| 41,498
|
/*
*@@sourcefile disk.h:
* header file for disk.c (XFldDisk implementation).
*
* This file is ALL new with V0.9.0.
*
*@@include #define INCL_DOSDEVIOCTL
*@@include #include <os2.h>
*@@include #include "shared\notebook.h"
*@@include #include "filesys\disk.h"
*/
/*
* Copyright (C) 1997-2006 Ulrich Mller.
*
* This file is part of the XWorkplace source package.
* XWorkplace 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, in version 2 as it comes in the
* "COPYING" file of the XWorkplace main distribution.
* 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.
*/
#ifndef DISK_HEADER_INCLUDED
#define DISK_HEADER_INCLUDED
/* ******************************************************************
*
* Disk implementation
*
********************************************************************/
#ifdef SOM_WPFolder_h
WPFolder* dskCheckDriveReady(WPDisk *somSelf);
#endif
#ifdef INCL_DOSDEVIOCTL
BOOL APIENTRY dskQueryInfo(PXDISKINFO paDiskInfos,
ULONG ulLogicalDrive);
typedef BOOL APIENTRY DSKQUERYINFO(PXDISKINFO paDiskInfos,
ULONG ulLogicalDrive);
typedef DSKQUERYINFO *PDSKQUERYINFO;
#endif
/* ******************************************************************
*
* Setup strings
*
********************************************************************/
#ifdef SOM_WPFolder_h
BOOL dskSetup(WPDisk *somSelf,
PCSZ pszSetupString); // V1.0.6 (2006-08-22) [pr]: added
#endif
/* ******************************************************************
*
* XFldDisk notebook callbacks (notebook.c)
*
********************************************************************/
#ifdef NOTEBOOK_HEADER_INCLUDED
VOID XWPENTRY dskDetailsInitPage(PNOTEBOOKPAGE pnbp,
ULONG flFlags);
MRESULT XWPENTRY dskDetailsItemChanged(PNOTEBOOKPAGE pnbp,
ULONG ulItemID,
USHORT usNotifyCode,
ULONG ulExtra);
VOID XWPENTRY dskDetailsTimer(PNOTEBOOKPAGE pnbp, ULONG ul);
#endif
#endif
|
rousseaux/netlabs.xworkplace
|
include/filesys/disk.h
|
C
|
gpl-2.0
| 2,757
|
/*
* linux/drivers/cpufreq/freq_table.c
*
* Copyright (C) 2002 - 2003 Dominik Brodowski
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#define dprintk(msg...) cpufreq_debug_printk(CPUFREQ_DEBUG_CORE, "freq-table", msg)
/*********************************************************************
* FREQUENCY TABLE HELPERS *
*********************************************************************/
int cpufreq_frequency_table_cpuinfo(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table)
{
unsigned int min_freq = ~0;
unsigned int max_freq = 0;
unsigned int i = 0;
for (i=0; (table[i].frequency != CPUFREQ_TABLE_END); i++) {
unsigned int freq = table[i].frequency;
if (freq == CPUFREQ_ENTRY_INVALID) {
dprintk("table entry %u is invalid, skipping\n", i);
continue;
}
dprintk("table entry %u: %u kHz, %u index\n", i, freq, table[i].index);
if (freq < min_freq)
min_freq = freq;
if (freq > max_freq)
max_freq = freq;
}
policy->min = policy->cpuinfo.min_freq = min_freq;
policy->max = policy->cpuinfo.max_freq = max_freq;
if (policy->min == ~0)
return -EINVAL;
else
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_cpuinfo);
int cpufreq_frequency_table_verify(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table)
{
unsigned int next_larger = ~0;
unsigned int i = 0;
unsigned int count = 0;
dprintk("request for verification of policy (%u - %u kHz) for cpu %u\n", policy->min, policy->max, policy->cpu);
if (!cpu_online(policy->cpu))
return -EINVAL;
cpufreq_verify_within_limits(policy,
policy->cpuinfo.min_freq, policy->cpuinfo.max_freq);
for (i=0; (table[i].frequency != CPUFREQ_TABLE_END); i++) {
unsigned int freq = table[i].frequency;
if (freq == CPUFREQ_ENTRY_INVALID)
continue;
if ((freq >= policy->min) && (freq <= policy->max))
count++;
else if ((next_larger > freq) && (freq > policy->max))
next_larger = freq;
}
if (!count)
policy->max = next_larger;
cpufreq_verify_within_limits(policy,
policy->cpuinfo.min_freq, policy->cpuinfo.max_freq);
dprintk("verification lead to (%u - %u kHz) for cpu %u\n", policy->min, policy->max, policy->cpu);
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_verify);
int cpufreq_frequency_table_target(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table,
unsigned int target_freq,
unsigned int relation,
unsigned int *index)
{
struct cpufreq_frequency_table optimal = { .index = ~0, };
struct cpufreq_frequency_table suboptimal = { .index = ~0, };
unsigned int i;
dprintk("request for target %u kHz (relation: %u) for cpu %u\n", target_freq, relation, policy->cpu);
switch (relation) {
case CPUFREQ_RELATION_H:
optimal.frequency = 0;
suboptimal.frequency = ~0;
break;
case CPUFREQ_RELATION_L:
optimal.frequency = ~0;
suboptimal.frequency = 0;
break;
}
if (!cpu_online(policy->cpu))
return -EINVAL;
for (i=0; (table[i].frequency != CPUFREQ_TABLE_END); i++) {
unsigned int freq = table[i].frequency;
if (freq == CPUFREQ_ENTRY_INVALID)
continue;
if ((freq < policy->min) || (freq > policy->max))
continue;
switch(relation) {
case CPUFREQ_RELATION_H:
if (freq <= target_freq) {
if (freq >= optimal.frequency) {
optimal.frequency = freq;
optimal.index = i;
}
} else {
if (freq <= suboptimal.frequency) {
suboptimal.frequency = freq;
suboptimal.index = i;
}
}
break;
case CPUFREQ_RELATION_L:
if (freq >= target_freq) {
if (freq <= optimal.frequency) {
optimal.frequency = freq;
optimal.index = i;
}
} else {
if (freq >= suboptimal.frequency) {
suboptimal.frequency = freq;
suboptimal.index = i;
}
}
break;
}
}
if (optimal.index > i) {
if (suboptimal.index > i)
return -EINVAL;
*index = suboptimal.index;
} else
*index = optimal.index;
dprintk("target is %u (%u kHz, %u)\n", *index, table[*index].frequency,
table[*index].index);
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_target);
static struct cpufreq_frequency_table *show_table[NR_CPUS];
/**
* show_scaling_governor - show the current policy for the specified CPU
*/
static ssize_t show_available_freqs (struct cpufreq_policy *policy, char *buf)
{
unsigned int i = 0;
unsigned int cpu = policy->cpu;
ssize_t count = 0;
struct cpufreq_frequency_table *table;
if (!show_table[cpu])
return -ENODEV;
table = show_table[cpu];
for (i=0; (table[i].frequency != CPUFREQ_TABLE_END); i++) {
if (table[i].frequency == CPUFREQ_ENTRY_INVALID)
continue;
count += sprintf(&buf[count], "%d ", table[i].frequency);
}
count += sprintf(&buf[count], "\n");
return count;
}
struct freq_attr cpufreq_freq_attr_scaling_available_freqs = {
.attr = { .name = "scaling_available_frequencies", .mode = 0444, .owner=THIS_MODULE },
.show = show_available_freqs,
};
EXPORT_SYMBOL_GPL(cpufreq_freq_attr_scaling_available_freqs);
/*
* if you use these, you must assure that the frequency table is valid
* all the time between get_attr and put_attr!
*/
void cpufreq_frequency_table_get_attr(struct cpufreq_frequency_table *table,
unsigned int cpu)
{
dprintk("setting show_table for cpu %u to %p\n", cpu, table);
show_table[cpu] = table;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_get_attr);
void cpufreq_frequency_table_put_attr(unsigned int cpu)
{
dprintk("clearing show_table for cpu %u\n", cpu);
show_table[cpu] = NULL;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_put_attr);
struct cpufreq_frequency_table *cpufreq_frequency_get_table(unsigned int cpu)
{
return show_table[cpu];
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_get_table);
MODULE_AUTHOR ("Dominik Brodowski <linux@brodo.de>");
MODULE_DESCRIPTION ("CPUfreq frequency table helpers");
MODULE_LICENSE ("GPL");
|
zrafa/linuxkernel
|
linux-2.6.17.new/drivers/cpufreq/freq_table.c
|
C
|
gpl-2.0
| 5,953
|
/* BFD library -- caching of file descriptors.
Copyright 1990, 1991, 1992, 1993, 1994, 1996, 2000, 2001, 2002,
2003, 2004, 2005, 2007, 2008, 2009 Free Software Foundation, Inc.
Hacked by Steve Chamberlain of Cygnus Support (steve@cygnus.com).
This file is part of BFD, the Binary File Descriptor library.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
/*
SECTION
File caching
The file caching mechanism is embedded within BFD and allows
the application to open as many BFDs as it wants without
regard to the underlying operating system's file descriptor
limit (often as low as 20 open files). The module in
<<cache.c>> maintains a least recently used list of
<<BFD_CACHE_MAX_OPEN>> files, and exports the name
<<bfd_cache_lookup>>, which runs around and makes sure that
the required BFD is open. If not, then it chooses a file to
close, closes it and opens the one wanted, returning its file
handle.
SUBSECTION
Caching functions
*/
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "libiberty.h"
#include "bfd_stdint.h"
#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif
/* In some cases we can optimize cache operation when reopening files.
For instance, a flush is entirely unnecessary if the file is already
closed, so a flush would use CACHE_NO_OPEN. Similarly, a seek using
SEEK_SET or SEEK_END need not first seek to the current position.
For stat we ignore seek errors, just in case the file has changed
while we weren't looking. If it has, then it's possible that the
file is shorter and we don't want a seek error to prevent us doing
the stat. */
enum cache_flag {
CACHE_NORMAL = 0,
CACHE_NO_OPEN = 1,
CACHE_NO_SEEK = 2,
CACHE_NO_SEEK_ERROR = 4
};
/* The maximum number of files which the cache will keep open at
one time. */
#define BFD_CACHE_MAX_OPEN 10
/* The number of BFD files we have open. */
static int open_files;
/* Zero, or a pointer to the topmost BFD on the chain. This is
used by the <<bfd_cache_lookup>> macro in @file{libbfd.h} to
determine when it can avoid a function call. */
static bfd *bfd_last_cache = NULL;
/* Insert a BFD into the cache. */
static void
insert (bfd *abfd)
{
if (bfd_last_cache == NULL)
{
abfd->lru_next = abfd;
abfd->lru_prev = abfd;
}
else
{
abfd->lru_next = bfd_last_cache;
abfd->lru_prev = bfd_last_cache->lru_prev;
abfd->lru_prev->lru_next = abfd;
abfd->lru_next->lru_prev = abfd;
}
bfd_last_cache = abfd;
}
/* Remove a BFD from the cache. */
static void
snip (bfd *abfd)
{
abfd->lru_prev->lru_next = abfd->lru_next;
abfd->lru_next->lru_prev = abfd->lru_prev;
if (abfd == bfd_last_cache)
{
bfd_last_cache = abfd->lru_next;
if (abfd == bfd_last_cache)
bfd_last_cache = NULL;
}
}
/* Close a BFD and remove it from the cache. */
static bfd_boolean
bfd_cache_delete (bfd *abfd)
{
bfd_boolean ret;
if (fclose ((FILE *) abfd->iostream) == 0)
ret = TRUE;
else
{
ret = FALSE;
bfd_set_error (bfd_error_system_call);
}
snip (abfd);
abfd->iostream = NULL;
--open_files;
return ret;
}
/* We need to open a new file, and the cache is full. Find the least
recently used cacheable BFD and close it. */
static bfd_boolean
close_one (void)
{
register bfd *to_kill;
if (bfd_last_cache == NULL)
to_kill = NULL;
else
{
for (to_kill = bfd_last_cache->lru_prev;
! to_kill->cacheable;
to_kill = to_kill->lru_prev)
{
if (to_kill == bfd_last_cache)
{
to_kill = NULL;
break;
}
}
}
if (to_kill == NULL)
{
/* There are no open cacheable BFD's. */
return TRUE;
}
to_kill->where = real_ftell ((FILE *) to_kill->iostream);
return bfd_cache_delete (to_kill);
}
/* Check to see if the required BFD is the same as the last one
looked up. If so, then it can use the stream in the BFD with
impunity, since it can't have changed since the last lookup;
otherwise, it has to perform the complicated lookup function. */
#define bfd_cache_lookup(x, flag) \
((x) == bfd_last_cache \
? (FILE *) (bfd_last_cache->iostream) \
: bfd_cache_lookup_worker (x, flag))
/* Called when the macro <<bfd_cache_lookup>> fails to find a
quick answer. Find a file descriptor for @var{abfd}. If
necessary, it open it. If there are already more than
<<BFD_CACHE_MAX_OPEN>> files open, it tries to close one first, to
avoid running out of file descriptors. It will return NULL
if it is unable to (re)open the @var{abfd}. */
static FILE *
bfd_cache_lookup_worker (bfd *abfd, enum cache_flag flag)
{
bfd *orig_bfd = abfd;
if ((abfd->flags & BFD_IN_MEMORY) != 0)
abort ();
while (abfd->my_archive)
abfd = abfd->my_archive;
if (abfd->iostream != NULL)
{
/* Move the file to the start of the cache. */
if (abfd != bfd_last_cache)
{
snip (abfd);
insert (abfd);
}
return (FILE *) abfd->iostream;
}
if (flag & CACHE_NO_OPEN)
return NULL;
if (bfd_open_file (abfd) == NULL)
;
else if (!(flag & CACHE_NO_SEEK)
&& real_fseek ((FILE *) abfd->iostream, abfd->where, SEEK_SET) != 0
&& !(flag & CACHE_NO_SEEK_ERROR))
bfd_set_error (bfd_error_system_call);
else
return (FILE *) abfd->iostream;
(*_bfd_error_handler) (_("reopening %B: %s\n"),
orig_bfd, bfd_errmsg (bfd_get_error ()));
return NULL;
}
static file_ptr
cache_btell (struct bfd *abfd)
{
FILE *f = bfd_cache_lookup (abfd, CACHE_NO_OPEN);
if (f == NULL)
return abfd->where;
return real_ftell (f);
}
static int
cache_bseek (struct bfd *abfd, file_ptr offset, int whence)
{
FILE *f = bfd_cache_lookup (abfd, whence != SEEK_CUR ? CACHE_NO_SEEK : CACHE_NORMAL);
if (f == NULL)
return -1;
return real_fseek (f, offset, whence);
}
/* Note that archive entries don't have streams; they share their parent's.
This allows someone to play with the iostream behind BFD's back.
Also, note that the origin pointer points to the beginning of a file's
contents (0 for non-archive elements). For archive entries this is the
first octet in the file, NOT the beginning of the archive header. */
static file_ptr
cache_bread_1 (struct bfd *abfd, void *buf, file_ptr nbytes)
{
FILE *f;
file_ptr nread;
/* FIXME - this looks like an optimization, but it's really to cover
up for a feature of some OSs (not solaris - sigh) that
ld/pe-dll.c takes advantage of (apparently) when it creates BFDs
internally and tries to link against them. BFD seems to be smart
enough to realize there are no symbol records in the "file" that
doesn't exist but attempts to read them anyway. On Solaris,
attempting to read zero bytes from a NULL file results in a core
dump, but on other platforms it just returns zero bytes read.
This makes it to something reasonable. - DJ */
if (nbytes == 0)
return 0;
f = bfd_cache_lookup (abfd, CACHE_NORMAL);
if (f == NULL)
return 0;
#if defined (__VAX) && defined (VMS)
/* Apparently fread on Vax VMS does not keep the record length
information. */
nread = read (fileno (f), buf, nbytes);
/* Set bfd_error if we did not read as much data as we expected. If
the read failed due to an error set the bfd_error_system_call,
else set bfd_error_file_truncated. */
if (nread == (file_ptr)-1)
{
bfd_set_error (bfd_error_system_call);
return -1;
}
#else
nread = fread (buf, 1, nbytes, f);
/* Set bfd_error if we did not read as much data as we expected. If
the read failed due to an error set the bfd_error_system_call,
else set bfd_error_file_truncated. */
if (nread < nbytes && ferror (f))
{
bfd_set_error (bfd_error_system_call);
return -1;
}
#endif
if (nread < nbytes)
/* This may or may not be an error, but in case the calling code
bails out because of it, set the right error code. */
bfd_set_error (bfd_error_file_truncated);
return nread;
}
static file_ptr
cache_bread (struct bfd *abfd, void *buf, file_ptr nbytes)
{
file_ptr nread = 0;
/* Some filesystems are unable to handle reads that are too large
(for instance, NetApp shares with oplocks turned off). To avoid
hitting this limitation, we read the buffer in chunks of 8MB max. */
while (nread < nbytes)
{
const file_ptr max_chunk_size = 0x800000;
file_ptr chunk_size = nbytes - nread;
file_ptr chunk_nread;
if (chunk_size > max_chunk_size)
chunk_size = max_chunk_size;
chunk_nread = cache_bread_1 (abfd, (char *) buf + nread, chunk_size);
/* Update the nread count.
We just have to be careful of the case when cache_bread_1 returns
a negative count: If this is our first read, then set nread to
that negative count in order to return that negative value to the
caller. Otherwise, don't add it to our total count, or we would
end up returning a smaller number of bytes read than we actually
did. */
if (nread == 0 || chunk_nread > 0)
nread += chunk_nread;
if (chunk_nread < chunk_size)
break;
}
return nread;
}
static file_ptr
cache_bwrite (struct bfd *abfd, const void *where, file_ptr nbytes)
{
file_ptr nwrite;
FILE *f = bfd_cache_lookup (abfd, CACHE_NORMAL);
if (f == NULL)
return 0;
nwrite = fwrite (where, 1, nbytes, f);
if (nwrite < nbytes && ferror (f))
{
bfd_set_error (bfd_error_system_call);
return -1;
}
return nwrite;
}
static int
cache_bclose (struct bfd *abfd)
{
return bfd_cache_close (abfd);
}
static int
cache_bflush (struct bfd *abfd)
{
int sts;
FILE *f = bfd_cache_lookup (abfd, CACHE_NO_OPEN);
if (f == NULL)
return 0;
sts = fflush (f);
if (sts < 0)
bfd_set_error (bfd_error_system_call);
return sts;
}
static int
cache_bstat (struct bfd *abfd, struct stat *sb)
{
int sts;
FILE *f = bfd_cache_lookup (abfd, CACHE_NO_SEEK_ERROR);
if (f == NULL)
return -1;
sts = fstat (fileno (f), sb);
if (sts < 0)
bfd_set_error (bfd_error_system_call);
return sts;
}
static void *
cache_bmmap (struct bfd *abfd ATTRIBUTE_UNUSED,
void *addr ATTRIBUTE_UNUSED,
bfd_size_type len ATTRIBUTE_UNUSED,
int prot ATTRIBUTE_UNUSED,
int flags ATTRIBUTE_UNUSED,
file_ptr offset ATTRIBUTE_UNUSED,
void **map_addr ATTRIBUTE_UNUSED,
bfd_size_type *map_len ATTRIBUTE_UNUSED)
{
void *ret = (void *) -1;
if ((abfd->flags & BFD_IN_MEMORY) != 0)
abort ();
#ifdef HAVE_MMAP
else
{
static uintptr_t pagesize_m1;
FILE *f;
file_ptr pg_offset;
bfd_size_type pg_len;
f = bfd_cache_lookup (abfd, CACHE_NO_SEEK_ERROR);
if (f == NULL)
return ret;
if (pagesize_m1 == 0)
pagesize_m1 = getpagesize () - 1;
/* Handle archive members. */
if (abfd->my_archive != NULL)
offset += abfd->origin;
/* Align. */
pg_offset = offset & ~pagesize_m1;
pg_len = (len + (offset - pg_offset) + pagesize_m1) & ~pagesize_m1;
ret = mmap (addr, pg_len, prot, flags, fileno (f), pg_offset);
if (ret == (void *) -1)
bfd_set_error (bfd_error_system_call);
else
{
*map_addr = ret;
*map_len = pg_len;
ret = (char *) ret + (offset & pagesize_m1);
}
}
#endif
return ret;
}
static const struct bfd_iovec cache_iovec =
{
&cache_bread, &cache_bwrite, &cache_btell, &cache_bseek,
&cache_bclose, &cache_bflush, &cache_bstat, &cache_bmmap
};
/*
INTERNAL_FUNCTION
bfd_cache_init
SYNOPSIS
bfd_boolean bfd_cache_init (bfd *abfd);
DESCRIPTION
Add a newly opened BFD to the cache.
*/
bfd_boolean
bfd_cache_init (bfd *abfd)
{
BFD_ASSERT (abfd->iostream != NULL);
if (open_files >= BFD_CACHE_MAX_OPEN)
{
if (! close_one ())
return FALSE;
}
abfd->iovec = &cache_iovec;
insert (abfd);
++open_files;
return TRUE;
}
/*
INTERNAL_FUNCTION
bfd_cache_close
SYNOPSIS
bfd_boolean bfd_cache_close (bfd *abfd);
DESCRIPTION
Remove the BFD @var{abfd} from the cache. If the attached file is open,
then close it too.
RETURNS
<<FALSE>> is returned if closing the file fails, <<TRUE>> is
returned if all is well.
*/
bfd_boolean
bfd_cache_close (bfd *abfd)
{
if (abfd->iovec != &cache_iovec)
return TRUE;
if (abfd->iostream == NULL)
/* Previously closed. */
return TRUE;
return bfd_cache_delete (abfd);
}
/*
FUNCTION
bfd_cache_close_all
SYNOPSIS
bfd_boolean bfd_cache_close_all (void);
DESCRIPTION
Remove all BFDs from the cache. If the attached file is open,
then close it too.
RETURNS
<<FALSE>> is returned if closing one of the file fails, <<TRUE>> is
returned if all is well.
*/
bfd_boolean
bfd_cache_close_all ()
{
bfd_boolean ret = TRUE;
while (bfd_last_cache != NULL)
ret &= bfd_cache_close (bfd_last_cache);
return ret;
}
/*
INTERNAL_FUNCTION
bfd_open_file
SYNOPSIS
FILE* bfd_open_file (bfd *abfd);
DESCRIPTION
Call the OS to open a file for @var{abfd}. Return the <<FILE *>>
(possibly <<NULL>>) that results from this operation. Set up the
BFD so that future accesses know the file is open. If the <<FILE *>>
returned is <<NULL>>, then it won't have been put in the
cache, so it won't have to be removed from it.
*/
FILE *
bfd_open_file (bfd *abfd)
{
abfd->cacheable = TRUE; /* Allow it to be closed later. */
if (open_files >= BFD_CACHE_MAX_OPEN)
{
if (! close_one ())
return NULL;
}
switch (abfd->direction)
{
case read_direction:
case no_direction:
abfd->iostream = real_fopen (abfd->filename, FOPEN_RB);
break;
case both_direction:
case write_direction:
if (abfd->opened_once)
{
abfd->iostream = real_fopen (abfd->filename, FOPEN_RUB);
if (abfd->iostream == NULL)
abfd->iostream = real_fopen (abfd->filename, FOPEN_WUB);
}
else
{
/* Create the file.
Some operating systems won't let us overwrite a running
binary. For them, we want to unlink the file first.
However, gcc 2.95 will create temporary files using
O_EXCL and tight permissions to prevent other users from
substituting other .o files during the compilation. gcc
will then tell the assembler to use the newly created
file as an output file. If we unlink the file here, we
open a brief window when another user could still
substitute a file.
So we unlink the output file if and only if it has
non-zero size. */
#ifndef __MSDOS__
/* Don't do this for MSDOS: it doesn't care about overwriting
a running binary, but if this file is already open by
another BFD, we will be in deep trouble if we delete an
open file. In fact, objdump does just that if invoked with
the --info option. */
struct stat s;
if (stat (abfd->filename, &s) == 0 && s.st_size != 0)
unlink_if_ordinary (abfd->filename);
#endif
abfd->iostream = real_fopen (abfd->filename, FOPEN_WUB);
abfd->opened_once = TRUE;
}
break;
}
if (abfd->iostream == NULL)
bfd_set_error (bfd_error_system_call);
else
{
if (! bfd_cache_init (abfd))
return NULL;
}
return (FILE *) abfd->iostream;
}
|
mm120/binutils-vc4
|
bfd/cache.c
|
C
|
gpl-2.0
| 16,006
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.