repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
Paregov/hexadiv | edno/software/nuttx/sched/group/group_join.c | 2 | 8105 | /*****************************************************************************
* sched/group/group_join.c
*
* Copyright (C) 2013 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* 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 NuttX 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.
*
*****************************************************************************/
/*****************************************************************************
* Included Files
*****************************************************************************/
#include <nuttx/config.h>
#include <sched.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>
#include <nuttx/kmalloc.h>
#include "sched/sched.h"
#include "group/group.h"
#include "environ/environ.h"
#if defined(HAVE_TASK_GROUP) && !defined(CONFIG_DISABLE_PTHREAD)
/*****************************************************************************
* Pre-processor Definitions
*****************************************************************************/
/* Is this worth making a configuration option? */
#define GROUP_REALLOC_MEMBERS 4
/*****************************************************************************
* Private Types
*****************************************************************************/
/*****************************************************************************
* Private Data
*****************************************************************************/
/*****************************************************************************
* Private Functions
*****************************************************************************/
/*****************************************************************************
* Name: group_addmember
*
* Description:
* Add a new member to a group.
*
* Parameters:
* group - The task group to add the new member
* pid - The new member
*
* Return Value:
* 0 (OK) on success; a negated errno value on failure.
*
* Assumptions:
* Called during thread creation and during reparenting in a safe context.
* No special precautions are required here.
*
*****************************************************************************/
#ifdef HAVE_GROUP_MEMBERS
static inline int group_addmember(FAR struct task_group_s *group, pid_t pid)
{
irqstate_t flags;
DEBUGASSERT(group && group->tg_nmembers < UINT8_MAX);
/* Will we need to extend the size of the array of groups? */
if (group->tg_nmembers >= group->tg_mxmembers)
{
FAR pid_t *newmembers;
unsigned int newmax;
/* Yes... reallocate the array of members */
newmax = group->tg_mxmembers + GROUP_REALLOC_MEMBERS;
if (newmax > UINT8_MAX)
{
newmax = UINT8_MAX;
}
newmembers = (FAR pid_t *)
kmm_realloc(group->tg_members, sizeof(pid_t) * newmax);
if (!newmembers)
{
sdbg("ERROR: Failed to reallocate tg_members\n");
return -ENOMEM;
}
/* Save the new number of members in the reallocated members array.
* We need to make the following atomic because the member list
* may be traversed from an interrupt handler (read-only).
*/
flags = irqsave();
group->tg_members = newmembers;
group->tg_mxmembers = newmax;
irqrestore(flags);
}
/* Assign this new pid to the group; group->tg_nmembers will be incremented
* by the caller.
*/
group->tg_members[group->tg_nmembers] = pid;
return OK;
}
#endif /* HAVE_GROUP_MEMBERS */
/*****************************************************************************
* Public Functions
*****************************************************************************/
/*****************************************************************************
* Name: group_bind
*
* Description:
* A thread joins the group when it is created. This is a two step process,
* first, the group must bound to the new threads TCB. group_bind() does
* this (at the return from group_join, things are a little unstable: The
* group has been bound, but tg_nmembers has not yet been incremented).
* Then, after the new thread is initialized and has a PID assigned to it,
* group_join() is called, incrementing the tg_nmembers count on the group.
*
* Parameters:
* tcb - The TCB of the new "child" task that need to join the group.
*
* Return Value:
* 0 (OK) on success; a negated errno value on failure.
*
* Assumptions:
* - The parent task from which the group will be inherited is the task at
* the thead of the ready to run list.
* - Called during thread creation in a safe context. No special precautions
* are required here.
*
*****************************************************************************/
int group_bind(FAR struct pthread_tcb_s *tcb)
{
FAR struct tcb_s *ptcb = (FAR struct tcb_s *)g_readytorun.head;
DEBUGASSERT(ptcb && tcb && ptcb->group && !tcb->cmn.group);
/* Copy the group reference from the parent to the child */
tcb->cmn.group = ptcb->group;
return OK;
}
/*****************************************************************************
* Name: group_join
*
* Description:
* A thread joins the group when it is created. This is a two step process,
* first, the group must bound to the new threads TCB. group_bind() does
* this (at the return from group_join, things are a little unstable: The
* group has been bound, but tg_nmembers has not yet been incremented).
* Then, after the new thread is initialized and has a PID assigned to it,
* group_join() is called, incrementing the tg_nmembers count on the group.
*
* Parameters:
* tcb - The TCB of the new "child" task that need to join the group.
*
* Return Value:
* 0 (OK) on success; a negated errno value on failure.
*
* Assumptions:
* - The parent task from which the group will be inherited is the task at
* the thead of the ready to run list.
* - Called during thread creation in a safe context. No special precautions
* are required here.
*
*****************************************************************************/
int group_join(FAR struct pthread_tcb_s *tcb)
{
FAR struct task_group_s *group;
#ifdef HAVE_GROUP_MEMBERS
int ret;
#endif
DEBUGASSERT(tcb && tcb->cmn.group &&
tcb->cmn.group->tg_nmembers < UINT8_MAX);
/* Get the group from the TCB */
group = tcb->cmn.group;
#ifdef HAVE_GROUP_MEMBERS
/* Add the member to the group */
ret = group_addmember(group, tcb->cmn.pid);
if (ret < 0)
{
return ret;
}
#endif
group->tg_nmembers++;
return OK;
}
#endif /* HAVE_TASK_GROUP && !CONFIG_DISABLE_PTHREAD */
| mit |
ctgiant/litedoge---DO-NOT-USE | src/qt/bitcoinunits.cpp | 2 | 4290 | #include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("LDOGE");
case mBTC: return QString("mLDOGE");
case uBTC: return QString::fromUtf8("μLDOGE");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("Litedoges");
case mBTC: return QString("Milli-Litedoges (1 / 1,000)");
case uBTC: return QString("Micro-Litedoges (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| mit |
ArnMan/yescoin | src/rpcblockchain.cpp | 2 | 17253 | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "bitcoinrpc.h"
#include "alert.h"
#include "mixerann.h"
#include "base58.h"
using namespace json_spirit;
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = pindexBest;
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
Array txs;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
txs.push_back(tx.GetHash().GetHex());
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
return result;
}
Value sendalert(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 1))
throw runtime_error(
"sendalert <alertdata>\n"
"Verifies the alert signature and sends to all connected peers.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
CAlert alert;
vector<unsigned char> msgData(ParseHexV(params[0], "argument"));
CDataStream vRecv(msgData, SER_NETWORK, PROTOCOL_VERSION);
vRecv >> alert;
CDataStream vRecv2(msgData, SER_NETWORK, PROTOCOL_VERSION);
if (alert.CheckSignature())
ProcessMessage(NULL, "alert", vRecv2);
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid signature on alert, not sending");
return true;
}
Value signalert(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 2))
throw runtime_error(
"signalert <alertdata> <privatekey>\n"
"Signs the alert data with the private key.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
CAlert alert;
vector<unsigned char> msgData(ParseHexV(params[0], "argument"));
vector<unsigned char> keyData(ParseHexV(params[1], "argument"));
alert.vchMsg = msgData;
CPrivKey key;
key.reserve(keyData.size());
copy(keyData.begin(),keyData.end(),back_inserter(key));
CKey key2;
key2.SetPrivKey(key, false);
if (!key2.Sign(alert.GetHash(), alert.vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed, invalid key?");
if (alert.CheckSignature())
{
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << alert;
return HexStr(ssTx.begin(), ssTx.end());
}
return false;
}
Value createalert(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() < 11 || params.size() > 12))
throw runtime_error(
"createalert <relayuntil> <expiration> <id> <cancelupto> <ids to cancel eg [1,2]> <minprotocolver> <maxprotocolvar> <versions alert applies to eg [\"/Euphoria:1.0.6.0/\",\"/Euphoria:1.0.6.5/\"]> <priority> <comment> <statusbar> [reserved]\n"
"Creates alert data for the given parameters.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
CUnsignedAlert alert;
alert.SetNull();
alert.nRelayUntil = params[0].get_int64();
alert.nExpiration = params[1].get_int64();
alert.nID = params[2].get_int();
alert.nCancel = params[3].get_int();
Array setCancels = params[4].get_array();
BOOST_FOREACH(const Value& cid, setCancels)
{
alert.setCancel.insert(cid.get_int());
}
alert.nMinVer = params[5].get_int();
alert.nMaxVer = params[6].get_int();
Array setSubVer = params[7].get_array();
BOOST_FOREACH(const Value& cid, setSubVer)
{
alert.setSubVer.insert(cid.get_str());
}
alert.nPriority = params[8].get_int();
alert.strComment = params[9].get_str();
alert.strStatusBar = params[10].get_str();
if (params.size() > 11)
alert.strReserved = params[11].get_str();
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << alert;
return HexStr(ssTx.begin(), ssTx.end());
}
Value sendann(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 1))
throw runtime_error(
"sendann <anndata>\n"
"Verifies the announcement signature and sends to all connected peers.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
CAnnouncement ann;
vector<unsigned char> msgData(ParseHexV(params[0], "argument"));
CDataStream vRecv(msgData, SER_NETWORK, PROTOCOL_VERSION);
vRecv >> ann;
CDataStream vRecv2(msgData, SER_NETWORK, PROTOCOL_VERSION);
if (ann.CheckSignature())
ProcessMessage(NULL, "announcement", vRecv2);
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid signature on announcement, not sending");
return true;
}
Value signann(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 2))
throw runtime_error(
"signann <alertdata> <privatekey>\n"
"Signs the announcement data with the private key.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
CAnnouncement ann;
vector<unsigned char> msgData(ParseHexV(params[0], "argument"));
vector<unsigned char> keyData(ParseHexV(params[1], "argument"));
ann.vchMsg = msgData;
CPrivKey key;
key.reserve(keyData.size());
copy(keyData.begin(),keyData.end(),back_inserter(key));
CKey key2;
key2.SetPrivKey(key, false);
if (!key2.Sign(ann.GetHash(), ann.vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed, invalid key?");
if (ann.CheckSignature())
{
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << ann;
return HexStr(ssTx.begin(), ssTx.end());
}
return false;
}
Value createann(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 9))
throw runtime_error(
"createann <expiration> <id> <ids to revoke eg [1,2]> <minprotocolver> <maxprotocolvar> <versions alert applies to eg [\"/Euphoria:1.0.6.0/\",\"/Euphoria:1.0.6.5/\"]> <hex:recvPubKey> <hex:sendPubKey> <hex:rsaPubKey>\n"
"Creates alert data for the given parameters.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
CUnsignedAnnouncement ann;
ann.SetNull();
ann.nExpiration = params[0].get_int64();
ann.nID = params[1].get_int();
Array setRevokes = params[2].get_array();
BOOST_FOREACH(const Value& cid, setRevokes)
{
ann.setRevoke.insert(cid.get_int());
}
ann.nMinVer = params[3].get_int();
ann.nMaxVer = params[4].get_int();
Array setSubVer = params[5].get_array();
BOOST_FOREACH(const Value& cid, setSubVer)
{
ann.setSubVer.insert(cid.get_str());
}
vector<unsigned char> recv(ParseHexV(params[6], "argument"));
vector<unsigned char> send(ParseHexV(params[7], "argument"));
vector<unsigned char> rsa(ParseHexV(params[8], "argument"));
ann.pReceiveAddressPubKey = recv;
ann.pSendAddressPubKey = send;
ann.pRsaPubKey = rsa;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << ann;
return HexStr(ssTx.begin(), ssTx.end());
}
Value listann(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 0))
throw runtime_error(
"listann\n"
"Lists active mixer announcements on this node.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
std::stringstream ss;
ss << "Current: " << nCurrentMixer << "\r\n\r\n";
{
LOCK(cs_mapAnns);
for (map<uint256, CAnnouncement>::iterator mi = mapAnns.begin(); mi != mapAnns.end(); mi++)
{
const CAnnouncement& ann = (*mi).second;
ss << "========\r\n";
ss << (*mi).first.GetHex();
ss << "\r\n========\r\n";
ss << ann.ToString();
ss << "\r\n\r\n";
}
}
return ss.str();
}
Value getchainvalue(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || (params.size() != 0 && params.size() != 1))
throw runtime_error(
"getchainvalue [height]\n"
"Returns the total amount of coins mined on the current chain up the to given height.");
int nHeight = nBestHeight;
if (params.size() == 1)
nHeight = params[0].get_int();
return ValueFromAmount(GetChainValue(nHeight));
}
Value getblockcount(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getbestblockhash(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best (tip) block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getdifficulty(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
return GetDifficulty();
}
Value settxfee(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nTransactionFee = nAmount;
return true;
}
Value getrawmempool(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("getblockhash(): block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [verbose=true]\n"
"If verbose is false, returns a string that is serialized, hex-encoded data for block <hash>.\n"
"If verbose is true, returns an Object with information about block <hash>."
);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex);
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
Value gettxoutsetinfo(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gettxoutsetinfo\n"
"Returns statistics about the unspent transaction output set.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
Object ret;
CCoinsStats stats;
if (pcoinsTip->GetStats(stats)) {
ret.push_back(Pair("height", (boost::int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize));
ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
Value gettxout(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout <txid> <n> [includemempool=true]\n"
"Returns details about an unspent transaction output.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
Object ret;
std::string strHash = params[0].get_str();
uint256 hash(strHash);
int n = params[1].get_int();
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
CCoins coins;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(*pcoinsTip, mempool);
if (!view.GetCoins(hash, coins))
return Value::null;
mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
} else {
if (!pcoinsTip->GetCoins(hash, coins))
return Value::null;
}
if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
return Value::null;
ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex()));
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
ret.push_back(Pair("confirmations", 0));
else
ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1));
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
Object o;
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("version", coins.nVersion));
ret.push_back(Pair("coinbase", coins.fCoinBase));
return ret;
}
Value verifychain(const Array& params, const CRPCContext& ctx, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain [check level] [num blocks]\n"
"Verifies blockchain database.");
if (!ctx.isAdmin) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (unauthorized)");
int nCheckLevel = GetArg("-checklevel", 3);
int nCheckDepth = GetArg("-checkblocks", 288);
if (params.size() > 0)
nCheckLevel = params[0].get_int();
if (params.size() > 1)
nCheckDepth = params[1].get_int();
return VerifyDB(nCheckLevel, nCheckDepth);
}
| mit |
horzelski/Voxel-Raycasting-using-True-Impostors | src/GL_Main.cpp | 2 | 12016 | ////////////////////////////////////////////////////////////////////////////////
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#pragma warning(disable:4996)
#endif
////////////////////////////////////////////////////////////////////////////////
// includes, GL
#include "GLee.h"
#include <GL/glut.h>
#include "GL_Main.h"
////////////////////////////////////////////////////////////////////////////////
//extern "C" void pboRegister( int pbo );
//extern "C" void pboUnregister( int pbo );
////////////////////////////////////////////////////////////////////////////////
GL_Main gl_main;
////////////////////////////////////////////////////////////////////////////////
GL_Main *GL_Main::This=NULL;
////////////////////////////////////////////////////////////////////////////////
void GL_Main::keyDown1Static(int key, int x, int y) { GL_Main::This->KeyPressed(key, x, y,true); }
void GL_Main::keyDown2Static(unsigned char key, int x, int y) { GL_Main::This->KeyPressed(key, x, y,true); }
void GL_Main::keyUp1Static(int key, int x, int y) { GL_Main::This->KeyPressed(key, x, y,false); }
void GL_Main::keyUp2Static(unsigned char key, int x, int y) { GL_Main::This->KeyPressed(key, x, y,false); }
////////////////////////////////////////////////////////////////////////////////
void GL_Main::MouseMotionStatic (int x,int y)
{
mouse.mouseX = float(x)/float(screen.window_width);
mouse.mouseY = float(y)/float(screen.window_height);
}
////////////////////////////////////////////////////////////////////////////////
void GL_Main::MouseButtonStatic(int button_index, int state, int x, int y)
{
mouse.button[button_index] = ( state == GLUT_DOWN ) ? true : false;
}
////////////////////////////////////////////////////////////////////////////////
void GL_Main::KeyPressed(int key, int x, int y,bool pressed)
{
if(key==27)
{
exit(0);
}
Sleep(10);
keyboard.key[ key&255 ] = pressed;
switch (key) {
case GLUT_KEY_UP:
default: ;
}
}
////////////////////////////////////////////////////////////////////////////////
void GL_Main::ToggleFullscreen()
{
static int win_width=screen.window_width;
static int win_height=screen.window_height;
if(fullscreen)
{
glutReshapeWindow(win_width,win_height);
screen.window_width = win_width;
screen.window_height = win_height;
}
else
{
win_width=screen.window_width;
win_height=screen.window_height;
glutFullScreen() ;
}
fullscreen = (fullscreen) ? false : true;
}
////////////////////////////////////////////////////////////////////////////////
void update_viewpoint();
void idle_func()
{
//ProcessKeys();
update_viewpoint();
glutPostRedisplay();
}
////////////////////////////////////////////////////////////////////////////////
void GL_Main::Init(int window_width, int window_height, bool fullscreen,void (*display_func)(void))
{
screen.window_width = window_width;
screen.window_height = window_height;
// Create GL context
char* headline="CUDA SVO Voxel Demo (c) by Sven Forstmann in 2009";int nop=1;
glutInit( &nop, &headline );
glutInitDisplayMode( GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize( window_width, window_height);
glutCreateWindow( headline );
this->fullscreen = fullscreen;
if(fullscreen)
{
glutFullScreen() ;
}
// initialize necessary OpenGL extensions
bool okay = GLEE_VERSION_2_0 || GLEE_ARB_pixel_buffer_object || GLEE_EXT_framebuffer_object;
if ( ! okay )
{
printf( "ERROR: Support for necessary OpenGL extensions missing.\n");
while(1) Sleep(100);;
}
// default initialization
glClearColor( 0.5, 0.5, 0.5, 1.0);
glDisable( GL_DEPTH_TEST);
// viewport
glViewport( 0, 0, window_width, window_height);
// projection
glMatrixMode( GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat)window_width / (GLfloat) window_height, 0.1, 1000.0);
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_LIGHT0);
float red[] = { 1.0, 0.1, 0.1, 1.0 };
float white[] = { 1.0, 1.0, 1.0, 1.0 };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0);
// register callbacks
glutDisplayFunc( display_func);
glutReshapeFunc( &reshape_static);
glutIdleFunc( &idle_static );
glutIdleFunc(idle_func);
glutSpecialFunc(&keyDown1Static);
glutSpecialUpFunc(&keyUp1Static);
glutKeyboardFunc(&keyDown2Static);
glutKeyboardUpFunc(&keyUp2Static);
glutMotionFunc(&MouseMotionStatic);
glutPassiveMotionFunc(&MouseMotionStatic);
glutMouseFunc (&MouseButtonStatic);
get_error();
}
////////////////////////////////////////////////////////////////////////////////
void GL_Main::deleteTexture( GLuint* tex) {
glDeleteTextures( 1, tex);
get_error();
*tex = 0;
}
////////////////////////////////////////////////////////////////////////////////
int GL_Main::createTexture( unsigned int size_x, unsigned int size_y,int bpp, unsigned char* data)
{
GLuint tex_name;
// create a tex as attachment
glGenTextures( 1, &tex_name);
glBindTexture( GL_TEXTURE_2D, tex_name);
// set basic parameters
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);//GL_CLAMP_TO_EDGE);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);//GL_CLAMP_TO_EDGE);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//GL_NEAREST);//GL_LINEAR);//NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);//GL_NEAREST);//GL_LINEAR);//GL_NEAREST);
// buffer data
if(bpp==16)
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, size_x, size_y, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data);
else
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, size_x, size_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
get_error();
return tex_name;
}
////////////////////////////////////////////////////////////////////////////////
int GL_Main::createFloatTexture( unsigned int size_x, unsigned int size_y,char* data,int elements,bool isFloat) {
GLuint tex_id;
// create a tex as attachment
glGenTextures( 1, &tex_id);
glBindTexture( GL_TEXTURE_2D, tex_id);
// set basic parameters
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT);// GL_CLAMP_TO_EDGE);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);//GL_CLAMP_TO_EDGE);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);//GL_LINEAR);//NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);//GL_LINEAR);//GL_NEAREST);
// buffer data
//glTexImage2D( GL_TEXTURE_2D, 0,
//GL_LUMINANCE32F_ARB, size_x, size_y, 0, GL_LUMINANCE, GL_FLOAT, data);
if(isFloat)
{
if(elements==1)
gluBuild2DMipmaps(
GL_TEXTURE_2D,
GL_LUMINANCE16F_ARB, size_x, size_y,
GL_LUMINANCE, GL_FLOAT, data);
if(elements==3)
gluBuild2DMipmaps(
GL_TEXTURE_2D,
GL_RGB16F_ARB, size_x, size_y,
GL_RGB, GL_FLOAT, data);
if(elements==4)
gluBuild2DMipmaps(
GL_TEXTURE_2D,
// GL_RGBA, size_x, size_y,
GL_RGBA16F_ARB, size_x, size_y,
GL_RGBA, GL_FLOAT, data);
}
else
{
if(elements==1)
gluBuild2DMipmaps(
GL_TEXTURE_2D,
GL_LUMINANCE, size_x, size_y,
GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
if(elements==3)
gluBuild2DMipmaps(
GL_TEXTURE_2D,
GL_RGB, size_x, size_y,
GL_RGB, GL_UNSIGNED_BYTE, data);
if(elements==4)
gluBuild2DMipmaps(
GL_TEXTURE_2D,
// GL_RGBA, size_x, size_y,
GL_RGBA, size_x, size_y,
GL_RGBA, GL_UNSIGNED_BYTE, data);
}
glBindTexture( GL_TEXTURE_2D, 0);
get_error();
return tex_id;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//! Display callback
////////////////////////////////////////////////////////////////////////////////
void GL_Main::reshape_static(int w, int h)
{
screen.window_width = w;
screen.window_height = h;
}
////////////////////////////////////////////////////////////////////////////////
//! Display callback
////////////////////////////////////////////////////////////////////////////////
void GL_Main::idle_static()
{
wglSwapIntervalEXT(0);
glutPostRedisplay();
}
////////////////////////////////////////////////////////////////////////////////
//! Create PBO
////////////////////////////////////////////////////////////////////////////////
void GL_Main::createPBO( GLuint* pbo,int image_width , int image_height,int bpp) {
// set up vertex data parameter
void *data = malloc(image_width * image_height * (bpp/8));
// create buffer object
glGenBuffers( 1, pbo);
glBindBuffer( GL_ARRAY_BUFFER, *pbo);
// buffer data
glBufferData( GL_ARRAY_BUFFER, image_width * image_height * (bpp/8), data, GL_DYNAMIC_COPY);
free(data);
glBindBuffer( GL_ARRAY_BUFFER, 0);
// attach this Buffer Object to CUDA
//pboRegister(*pbo);
get_error();
}
////////////////////////////////////////////////////////////////////////////////
//! Delete PBO
////////////////////////////////////////////////////////////////////////////////
void GL_Main::deletePBO( GLuint* pbo) {
glBindBuffer( GL_ARRAY_BUFFER, *pbo);
glDeleteBuffers( 1, pbo);
get_error();
*pbo = 0;
}
////////////////////////////////////////////////////////////////////////////////
int GL_Main::LoadTex(const char *name,int flags)
{
Bmp bmp;
if(!bmp.load(name))
return -1;
return LoadTexBmp(bmp,flags);
}
////////////////////////////////////////////////////////////////////////////////
int GL_Main::LoadTexBmp(Bmp &bmp,int flags)
{
get_error();
int gl_handle;
glGenTextures(1,(GLuint*)(&gl_handle));
glBindTexture (GL_TEXTURE_2D, gl_handle);
glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
//if(flags==0) bmp.addalpha(255,0,255);
if((flags & TEX_NORMALIZE)!=0) bmp.normalize();
if((flags & TEX_NORMALMAP)!=0) bmp.normalMap();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);//GL_CLAMP_TO_EDGE);//GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT);// GL_CLAMP_TO_EDGE);// GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );// _MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );// _MIPMAP_LINEAR);
glTexEnvf (GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_MODULATE);
get_error();
int format1 = (bmp.bpp==32) ? GL_RGBA : GL_RGB;
int format2 = (bmp.bpp==32) ? GL_BGRA_EXT : GL_BGR_EXT;
glTexImage2D (
GL_TEXTURE_2D,
0,
format1,
bmp.width,
bmp.height,
0,
format2 ,
GL_UNSIGNED_BYTE,
bmp.data);
/*
glTexImage2D (
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
const GLvoid *pixels);
*/
//if(bmp.bpp==32) gluBuild2DMipmaps(GL_TEXTURE_2D,GL_RGBA, bmp.width, bmp.height,/*GL_RGBA*/GL_BGRA_EXT, GL_UNSIGNED_BYTE, bmp.data );
//else gluBuild2DMipmaps(GL_TEXTURE_2D,GL_RGB, bmp.width, bmp.height,/*GL_RGB*/ GL_BGR_EXT , GL_UNSIGNED_BYTE, bmp.data );
get_error();
return gl_handle;
}
////////////////////////////////////////////////////////////////////////////////
void GL_Main::UpdateTexBmp(int handle, Bmp &bmp,int flags)
{
glBindTexture ( GL_TEXTURE_2D , handle );
int format1 = (bmp.bpp==32) ? GL_RGBA : GL_RGB;
int format2 = (bmp.bpp==32) ? GL_BGRA_EXT : GL_BGR_EXT;
glTexSubImage2D (
GL_TEXTURE_2D,//GLenum target,
0,//GLint level,
0,//GLint xoffset,
0,//GLint yoffset,
bmp.width,//GLsizei width,
bmp.height,//GLsizei height,
format2,//GLenum format,
GL_UNSIGNED_BYTE,//GLenum type,
bmp.data);//const GLvoid *pixels
get_error();
}
//////////////////////////////////////////////////////////////////////////////// | mit |
maurer/tiamat | samples/Juliet/testcases/CWE758_Undefined_Behavior/CWE758_Undefined_Behavior__long_alloca_use_18.c | 2 | 2102 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE758_Undefined_Behavior__long_alloca_use_18.c
Label Definition File: CWE758_Undefined_Behavior.alloc.label.xml
Template File: point-flaw-18.tmpl.c
*/
/*
* @description
* CWE: 758 Undefined Behavior
* Sinks: alloca_use
* GoodSink: Initialize then use data
* BadSink : Use data from alloca without initialization
* Flow Variant: 18 Control flow: goto statements
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE758_Undefined_Behavior__long_alloca_use_18_bad()
{
goto sink;
sink:
{
long * pointer = (long *)ALLOCA(sizeof(long));
long data = *pointer; /* FLAW: the value pointed to by pointer is undefined */
printLongLine(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good1() reverses the blocks on the goto statement */
static void good1()
{
goto sink;
sink:
{
long data;
long * pointer = (long *)ALLOCA(sizeof(long));
data = 5L;
*pointer = data; /* FIX: Assign a value to the thing pointed to by pointer */
{
long data = *pointer;
printLongLine(data);
}
}
}
void CWE758_Undefined_Behavior__long_alloca_use_18_good()
{
good1();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE758_Undefined_Behavior__long_alloca_use_18_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE758_Undefined_Behavior__long_alloca_use_18_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| mit |
Seeed-Studio/DSOQuad_SourceCode | APP_V2.32/USBLib/src/usb_mem.c | 2 | 3346 | /******************** (C) COPYRIGHT 2008 STMicroelectronics ********************
* File Name : usb_mem.c
* Author : MCD Application Team
* Version : V2.2.1
* Date : 09/22/2008
* Description : Utility functions for memory transfers to/from PMA
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : UserToPMABufferCopy
* Description : Copy a buffer from user memory area to packet memory area (PMA)
* Input : - pbUsrBuf: pointer to user memory area.
* - wPMABufAddr: address into PMA.
* - wNBytes: no. of bytes to be copied.
* Output : None.
* Return : None .
*******************************************************************************/
void UserToPMABufferCopy(u8 *pbUsrBuf, u16 wPMABufAddr, u16 wNBytes)
{
u32 n = (wNBytes + 1) >> 1; /* n = (wNBytes + 1) / 2 */
u32 i, temp1, temp2;
u16 *pdwVal;
pdwVal = (u16 *)(wPMABufAddr * 2 + PMAAddr);
for (i = n; i != 0; i--)
{
temp1 = (u16) * pbUsrBuf;
pbUsrBuf++;
temp2 = temp1 | (u16) * pbUsrBuf << 8;
*pdwVal++ = temp2;
pdwVal++;
pbUsrBuf++;
}
}
/*******************************************************************************
* Function Name : PMAToUserBufferCopy
* Description : Copy a buffer from user memory area to packet memory area (PMA)
* Input : - pbUsrBuf = pointer to user memory area.
* - wPMABufAddr = address into PMA.
* - wNBytes = no. of bytes to be copied.
* Output : None.
* Return : None.
*******************************************************************************/
void PMAToUserBufferCopy(u8 *pbUsrBuf, u16 wPMABufAddr, u16 wNBytes)
{
u32 n = (wNBytes + 1) >> 1;/* /2*/
u32 i;
u32 *pdwVal;
pdwVal = (u32 *)(wPMABufAddr * 2 + PMAAddr);
for (i = n; i != 0; i--)
{
*(u16*)pbUsrBuf++ = *pdwVal++;
pbUsrBuf++;
}
}
/******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/
| mit |
AlexandruValeanu/Competitive-Programming | Data-Structures/Hash-Table (std::unordered_map).cpp | 2 | 4656 | #include <vector>
#include <memory>
#include <limits>
#include <functional>
#include <random>
#include <cassert>
template<typename T, typename V>
class HashTable
{
private:
const unsigned int numberOfPrimes = 15;
const std::vector<unsigned int> primes{359,149,71,2789,41,2003,79,83,977,97,1049,283,157,1013,661};
unsigned int generatePrime()
{
static std::default_random_engine e{};
static std::uniform_int_distribution<unsigned int> d{0, numberOfPrimes - 1};
return primes[d(e)];
}
unsigned int prime;
unsigned int MAX_SIZE = 1 << 5;
unsigned int MASK = MAX_SIZE - 1;
const int EMPTY = std::numeric_limits<T>::max();
const int ERASED = std::numeric_limits<T>::max() - 1;
std::hash<T> hasher;
std::unique_ptr<std::pair<T,V>[]> table;
unsigned int _size;
void init(std::unique_ptr<std::pair<T,V>[]>& _table)
{
for (unsigned int i = 0; i < MAX_SIZE; ++i)
{
_table[i].first = EMPTY;
_table[i].second = V();
}
}
unsigned int check(const std::unique_ptr<std::pair<T,V>[]>& _table, const unsigned int p, const T& key) const
{
return _table[p].first != EMPTY && _table[p].first != key;
}
unsigned int supposedPosition(const std::unique_ptr<std::pair<T,V>[]>& _table, const T& key) const
{
unsigned int p = (prime * hasher(key)) & MASK;
while (check(_table, p, key))
p = (p + 1) & MASK;
return p;
}
void insert(std::unique_ptr<std::pair<T,V>[]>& _table, const T& key, const V& value)
{
unsigned int p = supposedPosition(_table, key);
if (_table[p].first != key)
{
_table[p].first = key;
this->_size++;
}
_table[p].second = value;
}
void erase(std::unique_ptr<std::pair<T,V>[]>& _table, const T& key)
{
unsigned int p = supposedPosition(_table, key);
if (_table[p].first == key)
{
_table[p].first = ERASED;
_table[p].second = V();
}
}
void rehash()
{
unsigned int __size = this->_size;
this->_size = 0;
MAX_SIZE *= 2;
MASK = MAX_SIZE - 1;
std::unique_ptr<std::pair<T,V>[]> _table(new std::pair<T,V>[MAX_SIZE]);
init(_table);
for (unsigned int i = 0; 2 * i < MAX_SIZE; ++i)
if (this->table[i].first != ERASED && this->table[i].first != EMPTY)
this->insert(_table, this->table[i].first, this->table[i].second);
this->_size = __size;
this->table = std::move(_table);
}
public:
HashTable() : prime(generatePrime()), hasher(), table(), _size(0)
{
this->table = std::make_unique<std::pair<T,V>[]>(MAX_SIZE);
this->init(this->table);
}
HashTable(const HashTable &rhs) : prime(rhs.prime), hasher(rhs.hasher), table(), _size(0)
{
this->table = std::make_unique<std::pair<T,V>[]>(MAX_SIZE);
this->init(this->table);
for (unsigned int i = 0; i < rhs.MAX_SIZE; ++i)
if (rhs.table[i].first != ERASED && rhs.table[i].first != EMPTY)
this->insert(this->table, rhs.table[i].first, rhs.table[i].second);
}
void insert(const T& key, const V& value)
{
this->insert(this->table, key, value);
if (2 * this->_size >= MAX_SIZE)
rehash();
}
V& operator [] (const T& key)
{
unsigned int p = supposedPosition(this->table, key);
if (this->table[p].first != key)
{
this->table[p].first = key;
this->table[p].second = V();
_size++;
if (2 * this->_size >= MAX_SIZE)
rehash();
p = supposedPosition(this->table, key);
assert(this->table[p].first == key);
}
return this->table[p].second;
}
void erase(const T& key)
{
this->erase(this->table, key);
}
bool find(const T& key) const
{
unsigned int p = supposedPosition(this->table, key);
return this->table[p].first == key;
}
V count(const T& key) const
{
unsigned int p = supposedPosition(this->table, key);
if (this->table[p].first == key)
return this->table[p].second;
else
return V();
}
size_t size() const
{
return static_cast<size_t>(this->_size);
}
bool empty() const
{
return this->_size == 0;
}
size_t max_size() const
{
return static_cast<size_t>(this->MAX_SIZE);
}
};
int main()
{
return 0;
}
| mit |
jessdtate/SCIRun | src/Externals/spire/es-render/Registration2.cpp | 3 | 2775 | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifdef __APPLE__
#define GL_SILENCE_DEPRECATION
#endif
#include "Registration.hpp"
// Components
#include "comp/CommonUniforms.hpp"
#include "comp/GLState.hpp"
#include "comp/IBO.hpp"
#include "comp/MatUniform.hpp"
#include "comp/RenderSequence.hpp"
#include "comp/Shader.hpp"
#include "comp/ShaderPromiseVF.hpp"
#include "comp/RenderSimpleGeom.hpp"
#include "comp/SkinnedGeom.hpp"
#include "comp/StaticArcBallCam.hpp"
#include "comp/StaticGLState.hpp"
#include "comp/StaticShaderMan.hpp"
#include "comp/StaticVBOMan.hpp"
#include "comp/StaticGeomMan.hpp"
#include "comp/StaticTextureMan.hpp"
#include "comp/StaticFontMan.hpp"
#include "comp/StaticIBOMan.hpp"
#include "comp/StaticFBOMan.hpp"
#include "comp/GeomPromise.hpp"
#include "comp/Geom.hpp"
#include "comp/Font.hpp"
#include "comp/FontPromise.hpp"
#include "comp/Texture.hpp"
#include "comp/TexturePromise.hpp"
#include "comp/UniformLocation.hpp"
#include "comp/VBO.hpp"
#include "comp/VecUniform.hpp"
#include "comp/RenderFont.hpp"
#include "comp/UtilViewPosAlign.hpp"
namespace ren {
void register2(spire::Acorn& core)
{
core.registerComponent<StaticArcBallCam>();
core.registerComponent<StaticGLState>();
core.registerComponent<StaticShaderMan>();
core.registerComponent<StaticGeomMan>();
core.registerComponent<StaticTextureMan>();
core.registerComponent<StaticVBOMan>();
core.registerComponent<StaticIBOMan>();
core.registerComponent<StaticFBOMan>();
core.registerComponent<StaticFontMan>();
}
} // namespace ren
| mit |
palmd/BALLS | src/walletdb.cpp | 3 | 14603 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2012 The Snowballs developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletdb.h"
#include "wallet.h"
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost;
static uint64 nAccountingEntryNumber = 0;
extern CCriticalSection cs_db;
extern map<string, int> mapFileUseCount;
extern void CloseDb(const string& strFile);
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
{
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
}
int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
int64 nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
loop
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
entries.push_back(acentry);
}
pcursor->close();
}
int CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey.clear();
int nFileVersion = 0;
vector<uint256> vWalletUpgrade;
bool fIsEncrypted = false;
//// todo: shouldn't we catch exceptions and try to recover and continue?
{
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
printf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
loop
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
printf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
string strType;
ssKey >> strType;
if (strType == "name")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[strAddress];
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx& wtx = pwallet->mapWallet[hash];
ssValue >> wtx;
wtx.BindWallet(pwallet);
if (wtx.GetHash() != hash)
printf("Error in wallet.dat, hash mismatch\n");
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
wtx.fTimeReceivedIsTxTime = 0;
}
vWalletUpgrade.push_back(hash);
}
//// debug print
//printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
//printf(" %12"PRI64d" %s %s %s\n",
// wtx.vout[0].nValue,
// DateTimeStrFormat(wtx.GetBlockTime()).c_str(),
// wtx.hashBlock.ToString().substr(0,20).c_str(),
// wtx.mapValue["message"].c_str());
}
else if (strType == "acentry")
{
string strAccount;
ssKey >> strAccount;
uint64 nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
}
else if (strType == "key" || strType == "wkey")
{
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
CKey key;
if (strType == "key")
{
CPrivKey pkey;
ssValue >> pkey;
key.SetPubKey(vchPubKey);
key.SetPrivKey(pkey);
if (key.GetPubKey() != vchPubKey)
{
printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
return DB_CORRUPT;
}
if (!key.IsValid())
{
printf("Error reading wallet database: invalid CPrivKey\n");
return DB_CORRUPT;
}
}
else
{
CWalletKey wkey;
ssValue >> wkey;
key.SetPubKey(vchPubKey);
key.SetPrivKey(wkey.vchPrivKey);
if (key.GetPubKey() != vchPubKey)
{
printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
return DB_CORRUPT;
}
if (!key.IsValid())
{
printf("Error reading wallet database: invalid CWalletKey\n");
return DB_CORRUPT;
}
}
if (!pwallet->LoadKey(key))
{
printf("Error reading wallet database: LoadKey failed\n");
return DB_CORRUPT;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
return DB_CORRUPT;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
printf("Error reading wallet database: LoadCryptedKey failed\n");
return DB_CORRUPT;
}
fIsEncrypted = true;
}
else if (strType == "defaultkey")
{
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64 nIndex;
ssKey >> nIndex;
pwallet->setKeyPool.insert(nIndex);
}
else if (strType == "version")
{
ssValue >> nFileVersion;
if (nFileVersion == 10300)
nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script))
{
printf("Error reading wallet database: LoadCScript failed\n");
return DB_CORRUPT;
}
}
}
pcursor->close();
}
BOOST_FOREACH(uint256 hash, vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
printf("nFileVersion = %d\n", nFileVersion);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
return DB_NEED_REWRITE;
if (nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
return DB_LOAD_OK;
}
void ThreadFlushWalletDB(void* parg)
{
const string& strFile = ((const string*)parg)[0];
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", true))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64 nLastWalletUpdate = GetTime();
while (!fShutdown)
{
Sleep(500);
if (nLastSeen != nWalletDBUpdated)
{
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
{
TRY_LOCK(cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end())
{
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0 && !fShutdown)
{
map<string, int>::iterator mi = mapFileUseCount.find(strFile);
if (mi != mapFileUseCount.end())
{
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64 nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
CloseDb(strFile);
dbenv.txn_checkpoint(0, 0, 0);
dbenv.lsn_reset(strFile.c_str(), 0);
mapFileUseCount.erase(mi++);
printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (!fShutdown)
{
{
LOCK(cs_db);
if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
CloseDb(wallet.strWalletFile);
dbenv.txn_checkpoint(0, 0, 0);
dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
printf("copied wallet.dat to %s\n", pathDest.string().c_str());
return true;
} catch(const filesystem::filesystem_error &e) {
printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
return false;
}
}
}
Sleep(100);
}
return false;
}
| mit |
jjimenezg93/ai-state_machines | moai/3rdparty/fmod-4.44.08/examples/playlist/main.cpp | 3 | 6935 | /*===============================================================================================
PlayList Example
Copyright (c), Firelight Technologies Pty, Ltd 2004-2011.
This example shows how to load a playlist and play the sounds in a playlist.
===============================================================================================*/
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include "../../api/inc/fmod.hpp"
#include "../../api/inc/fmod_errors.h"
void ERRCHECK(FMOD_RESULT result)
{
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
exit(-1);
}
}
int main(int argc, char *argv[])
{
FMOD::System *system = 0;
FMOD::Sound *playlist = 0;
FMOD::Sound *sound = 0;
FMOD::Channel *channel = 0;
FMOD_TAG tag;
FMOD_RESULT result;
FMOD_SOUND_TYPE soundtype;
bool isplaylist = false;
char *title = NULL;
int count = 0;
int key;
unsigned int version;
char file[128];
/*
Create a System object and initialize.
*/
result = FMOD::System_Create(&system);
ERRCHECK(result);
result = system->getVersion(&version);
ERRCHECK(result);
if (version < FMOD_VERSION)
{
printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION);
return 0;
}
result = system->init(32, FMOD_INIT_NORMAL, 0);
ERRCHECK(result);
result = system->createSound("../media/playlist.m3u", FMOD_DEFAULT, 0, &playlist);
ERRCHECK(result);
result = playlist->getFormat(&soundtype, 0, 0, 0);
ERRCHECK(result);
isplaylist = (soundtype == FMOD_SOUND_TYPE_PLAYLIST);
printf("===================================================================\n");
printf("PlayList Example. Copyright (c) Firelight Technologies 2004-2011.\n");
printf("===================================================================\n");
printf("\n");
printf("Press 'n' to play next sound in playlist\n");
printf("Press 'space' to pause/unpause current sound\n");
printf("Press 'Esc' to quit\n");
printf("\n");
if (isplaylist)
{
printf("PLAYLIST loaded.\n");
/*
Get the first song in the playlist, create the sound and then play it.
*/
result = playlist->getTag("FILE", count, &tag);
ERRCHECK(result);
sprintf(file, "../media/%s", (char *)tag.data);
result = system->createSound(file, FMOD_DEFAULT, 0, &sound);
ERRCHECK(result);
result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
ERRCHECK(result);
playlist->getTag("TITLE", count, &tag);
title = (char *)tag.data;
count++;
}
else
{
printf("SOUND loaded.\n");
/*
This is just a normal sound, so just play it.
*/
sound = playlist;
result = sound->setMode(FMOD_LOOP_NORMAL);
ERRCHECK(result);
result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
ERRCHECK(result);
}
printf("\n");
/*
Main loop.
*/
do
{
bool isplaying = false;
if (channel && isplaylist)
{
/*
When sound has finished playing, play the next sound in the playlist
*/
channel->isPlaying(&isplaying);
if (!isplaying)
{
if (sound)
{
sound->release();
sound = NULL;
}
result = playlist->getTag("FILE", count, &tag);
if (result != FMOD_OK)
{
count = 0;
}
else
{
printf("playing next song in playlist...\n");
sprintf(file, "../media/%s", (char *)tag.data);
result = system->createSound(file, FMOD_DEFAULT, 0, &sound);
ERRCHECK(result);
result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel);
ERRCHECK(result);
playlist->getTag("TITLE", count, &tag);
title = (char *)tag.data;
count++;
}
}
}
if (_kbhit())
{
key = _getch();
switch (key)
{
case 'n' :
{
/*
Play the next song in the playlist
*/
if (channel && isplaylist)
{
channel->stop();
}
break;
}
case ' ' :
{
if (channel)
{
bool paused;
channel->getPaused(&paused);
channel->setPaused(!paused);
}
}
}
}
system->update();
{
unsigned int ms = 0;
unsigned int lenms = 0;
bool paused = 0;
if (channel)
{
if (sound)
{
result = sound->getLength(&lenms, FMOD_TIMEUNIT_MS);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
{
ERRCHECK(result);
}
}
result = channel->getPaused(&paused);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
{
ERRCHECK(result);
}
result = channel->getPosition(&ms, FMOD_TIMEUNIT_MS);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
{
ERRCHECK(result);
}
}
printf("Time %02d:%02d:%02d/%02d:%02d:%02d : %s : %s\r", ms / 1000 / 60, ms / 1000 % 60, ms / 10 % 100, lenms / 1000 / 60, lenms / 1000 % 60, lenms / 10 % 100, paused ? "Paused " : "Playing ", title);
}
Sleep(10);
} while (key != 27);
printf("\n");
/*
Shut down
*/
if (sound)
{
result = sound->release();
ERRCHECK(result);
}
if (isplaylist)
{
result = playlist->release();
ERRCHECK(result);
}
result = system->close();
ERRCHECK(result);
result = system->release();
ERRCHECK(result);
return 0;
}
| mit |
roucoin/roucoin | src/qt/splashscreen.cpp | 3 | 1788 | #include "splashscreen.h"
#include "clientversion.h"
#include "util.h"
#include <QPainter>
#include <QApplication>
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
QSplashScreen(pixmap, f)
{
// set reference point, paddings
int paddingLeftCol2 = 230;
int paddingTopCol2 = 376;
int line1 = 0;
int line2 = 13;
int line3 = 26;
float fontFactor = 1.0;
// define text to place
QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion()));
// QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
// QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Execoin developers"));
QString font = "Arial";
// load the bitmap for writing some text over it
QPixmap newPixmap;
if(GetBoolArg("-testnet")) {
newPixmap = QPixmap(":/images/splash_testnet");
}
else {
newPixmap = QPixmap(":/images/splash");
}
QPainter pixPaint(&newPixmap);
pixPaint.setPen(QColor(100,100,100));
pixPaint.setFont(QFont(font, 9*fontFactor));
pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText);
// draw copyright stuff
// pixPaint.setFont(QFont(font, 9*fontFactor));
// pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1);
// pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2);
pixPaint.end();
this->setPixmap(newPixmap);
}
| mit |
laudaa/bitcoin | src/txdb.cpp | 4 | 14487 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <txdb.h>
#include <chainparams.h>
#include <hash.h>
#include <random.h>
#include <pow.h>
#include <uint256.h>
#include <util.h>
#include <ui_interface.h>
#include <init.h>
#include <stdint.h>
#include <boost/thread.hpp>
static const char DB_COIN = 'C';
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_HEAD_BLOCKS = 'H';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
namespace {
struct CoinEntry {
COutPoint* outpoint;
char key;
explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}
template<typename Stream>
void Serialize(Stream &s) const {
s << key;
s << outpoint->hash;
s << VARINT(outpoint->n);
}
template<typename Stream>
void Unserialize(Stream& s) {
s >> key;
s >> outpoint->hash;
s >> VARINT(outpoint->n);
}
};
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true)
{
}
bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const {
return db.Read(CoinEntry(&outpoint), coin);
}
bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const {
return db.Exists(CoinEntry(&outpoint));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256();
return hashBestChain;
}
std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const {
std::vector<uint256> vhashHeadBlocks;
if (!db.Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) {
return std::vector<uint256>();
}
return vhashHeadBlocks;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CDBBatch batch(db);
size_t count = 0;
size_t changed = 0;
size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize);
int crash_simulate = gArgs.GetArg("-dbcrashratio", 0);
assert(!hashBlock.IsNull());
uint256 old_tip = GetBestBlock();
if (old_tip.IsNull()) {
// We may be in the middle of replaying.
std::vector<uint256> old_heads = GetHeadBlocks();
if (old_heads.size() == 2) {
assert(old_heads[0] == hashBlock);
old_tip = old_heads[1];
}
}
// In the first batch, mark the database as being in the middle of a
// transition from old_tip to hashBlock.
// A vector is used for future extensibility, as we may want to support
// interrupting after partial writes from multiple independent reorgs.
batch.Erase(DB_BEST_BLOCK);
batch.Write(DB_HEAD_BLOCKS, std::vector<uint256>{hashBlock, old_tip});
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
CoinEntry entry(&it->first);
if (it->second.coin.IsSpent())
batch.Erase(entry);
else
batch.Write(entry, it->second.coin);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
if (batch.SizeEstimate() > batch_size) {
LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
db.WriteBatch(batch);
batch.Clear();
if (crash_simulate) {
static FastRandomContext rng;
if (rng.randrange(crash_simulate) == 0) {
LogPrintf("Simulating a crash. Goodbye.\n");
_Exit(0);
}
}
}
}
// In the last batch, mark the database as consistent with hashBlock again.
batch.Erase(DB_HEAD_BLOCKS);
batch.Write(DB_BEST_BLOCK, hashBlock);
LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
bool ret = db.WriteBatch(batch);
LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return ret;
}
size_t CCoinsViewDB::EstimateSize() const
{
return db.EstimateSize(DB_COIN, (char)(DB_COIN+1));
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
CCoinsViewCursor *CCoinsViewDB::Cursor() const
{
CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper&>(db).NewIterator(), GetBestBlock());
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
i->pcursor->Seek(DB_COIN);
// Cache key of first record
if (i->pcursor->Valid()) {
CoinEntry entry(&i->keyTmp.second);
i->pcursor->GetKey(entry);
i->keyTmp.first = entry.key;
} else {
i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false
}
return i;
}
bool CCoinsViewDBCursor::GetKey(COutPoint &key) const
{
// Return cached key
if (keyTmp.first == DB_COIN) {
key = keyTmp.second;
return true;
}
return false;
}
bool CCoinsViewDBCursor::GetValue(Coin &coin) const
{
return pcursor->GetValue(coin);
}
unsigned int CCoinsViewDBCursor::GetValueSize() const
{
return pcursor->GetValueSize();
}
bool CCoinsViewDBCursor::Valid() const
{
return keyTmp.first == DB_COIN;
}
void CCoinsViewDBCursor::Next()
{
pcursor->Next();
CoinEntry entry(&keyTmp.second);
if (!pcursor->Valid() || !pcursor->GetKey(entry)) {
keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false
} else {
keyTmp.first = entry.key;
}
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch(*this);
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(std::make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CDBBatch batch(*this);
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(std::make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex)
{
std::unique_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
CDiskBlockIndex diskindex;
if (pcursor->GetValue(diskindex)) {
// Construct block index object
CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = insertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams))
return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString());
pcursor->Next();
} else {
return error("%s: failed to read value", __func__);
}
} else {
break;
}
}
return true;
}
namespace {
//! Legacy class to deserialize pre-pertxout database entries without reindex.
class CCoins
{
public:
//! whether transaction is a coinbase
bool fCoinBase;
//! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
std::vector<CTxOut> vout;
//! at which height this transaction was included in the active block chain
int nHeight;
//! empty constructor
CCoins() : fCoinBase(false), vout(0), nHeight(0) { }
template<typename Stream>
void Unserialize(Stream &s) {
unsigned int nCode = 0;
// version
int nVersionDummy;
::Unserialize(s, VARINT(nVersionDummy));
// header code
::Unserialize(s, VARINT(nCode));
fCoinBase = nCode & 1;
std::vector<bool> vAvail(2, false);
vAvail[0] = (nCode & 2) != 0;
vAvail[1] = (nCode & 4) != 0;
unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
// spentness bitmask
while (nMaskCode > 0) {
unsigned char chAvail = 0;
::Unserialize(s, chAvail);
for (unsigned int p = 0; p < 8; p++) {
bool f = (chAvail & (1 << p)) != 0;
vAvail.push_back(f);
}
if (chAvail != 0)
nMaskCode--;
}
// txouts themself
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
::Unserialize(s, REF(CTxOutCompressor(vout[i])));
}
// coinbase height
::Unserialize(s, VARINT(nHeight));
}
};
}
/** Upgrade the database from older formats.
*
* Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout.
*/
bool CCoinsViewDB::Upgrade() {
std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
pcursor->Seek(std::make_pair(DB_COINS, uint256()));
if (!pcursor->Valid()) {
return true;
}
int64_t count = 0;
LogPrintf("Upgrading utxo-set database...\n");
LogPrintf("[0%%]...");
uiInterface.ShowProgress(_("Upgrading UTXO database"), 0, true);
size_t batch_size = 1 << 24;
CDBBatch batch(db);
int reportDone = 0;
std::pair<unsigned char, uint256> key;
std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()};
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
if (ShutdownRequested()) {
break;
}
if (pcursor->GetKey(key) && key.first == DB_COINS) {
if (count++ % 256 == 0) {
uint32_t high = 0x100 * *key.second.begin() + *(key.second.begin() + 1);
int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5);
uiInterface.ShowProgress(_("Upgrading UTXO database"), percentageDone, true);
if (reportDone < percentageDone/10) {
// report max. every 10% step
LogPrintf("[%d%%]...", percentageDone);
reportDone = percentageDone/10;
}
}
CCoins old_coins;
if (!pcursor->GetValue(old_coins)) {
return error("%s: cannot parse CCoins record", __func__);
}
COutPoint outpoint(key.second, 0);
for (size_t i = 0; i < old_coins.vout.size(); ++i) {
if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) {
Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase);
outpoint.n = i;
CoinEntry entry(&outpoint);
batch.Write(entry, newcoin);
}
}
batch.Erase(key);
if (batch.SizeEstimate() > batch_size) {
db.WriteBatch(batch);
batch.Clear();
db.CompactRange(prev_key, key);
prev_key = key;
}
pcursor->Next();
} else {
break;
}
}
db.WriteBatch(batch);
db.CompactRange({DB_COINS, uint256()}, key);
uiInterface.ShowProgress("", 100, false);
LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE");
return !ShutdownRequested();
}
| mit |
petruchito/sylvanian-fireplace | STM8S_StdPeriph_Driver/src/stm8s_tim4.c | 4 | 11810 | /**
******************************************************************************
* @file stm8s_tim4.c
* @author MCD Application Team
* @version V2.2.0
* @date 30-September-2014
* @brief This file contains all the functions for the TIM4 peripheral.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm8s_tim4.h"
/** @addtogroup STM8S_StdPeriph_Driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/**
* @addtogroup TIM4_Public_Functions
* @{
*/
/**
* @brief Deinitializes the TIM4 peripheral registers to their default reset values.
* @param None
* @retval None
*/
void TIM4_DeInit(void)
{
TIM4->CR1 = TIM4_CR1_RESET_VALUE;
TIM4->IER = TIM4_IER_RESET_VALUE;
TIM4->CNTR = TIM4_CNTR_RESET_VALUE;
TIM4->PSCR = TIM4_PSCR_RESET_VALUE;
TIM4->ARR = TIM4_ARR_RESET_VALUE;
TIM4->SR1 = TIM4_SR1_RESET_VALUE;
}
/**
* @brief Initializes the TIM4 Time Base Unit according to the specified parameters.
* @param TIM4_Prescaler specifies the Prescaler from TIM4_Prescaler_TypeDef.
* @param TIM4_Period specifies the Period value.
* @retval None
*/
void TIM4_TimeBaseInit(TIM4_Prescaler_TypeDef TIM4_Prescaler, uint8_t TIM4_Period)
{
/* Check TIM4 prescaler value */
assert_param(IS_TIM4_PRESCALER_OK(TIM4_Prescaler));
/* Set the Prescaler value */
TIM4->PSCR = (uint8_t)(TIM4_Prescaler);
/* Set the Autoreload value */
TIM4->ARR = (uint8_t)(TIM4_Period);
}
/**
* @brief Enables or disables the TIM4 peripheral.
* @param NewState new state of the TIM4 peripheral. This parameter can
* be ENABLE or DISABLE.
* @retval None
*/
void TIM4_Cmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONALSTATE_OK(NewState));
/* set or Reset the CEN Bit */
if (NewState != DISABLE)
{
TIM4->CR1 |= TIM4_CR1_CEN;
}
else
{
TIM4->CR1 &= (uint8_t)(~TIM4_CR1_CEN);
}
}
/**
* @brief Enables or disables the specified TIM4 interrupts.
* @param NewState new state of the TIM4 peripheral.
* This parameter can be: ENABLE or DISABLE.
* @param TIM4_IT specifies the TIM4 interrupts sources to be enabled or disabled.
* This parameter can be any combination of the following values:
* - TIM4_IT_UPDATE: TIM4 update Interrupt source
* @param NewState new state of the TIM4 peripheral.
* @retval None
*/
void TIM4_ITConfig(TIM4_IT_TypeDef TIM4_IT, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_TIM4_IT_OK(TIM4_IT));
assert_param(IS_FUNCTIONALSTATE_OK(NewState));
if (NewState != DISABLE)
{
/* Enable the Interrupt sources */
TIM4->IER |= (uint8_t)TIM4_IT;
}
else
{
/* Disable the Interrupt sources */
TIM4->IER &= (uint8_t)(~TIM4_IT);
}
}
/**
* @brief Enables or Disables the TIM4 Update event.
* @param NewState new state of the TIM4 peripheral Preload register. This parameter can
* be ENABLE or DISABLE.
* @retval None
*/
void TIM4_UpdateDisableConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONALSTATE_OK(NewState));
/* Set or Reset the UDIS Bit */
if (NewState != DISABLE)
{
TIM4->CR1 |= TIM4_CR1_UDIS;
}
else
{
TIM4->CR1 &= (uint8_t)(~TIM4_CR1_UDIS);
}
}
/**
* @brief Selects the TIM4 Update Request Interrupt source.
* @param TIM4_UpdateSource specifies the Update source.
* This parameter can be one of the following values
* - TIM4_UPDATESOURCE_REGULAR
* - TIM4_UPDATESOURCE_GLOBAL
* @retval None
*/
void TIM4_UpdateRequestConfig(TIM4_UpdateSource_TypeDef TIM4_UpdateSource)
{
/* Check the parameters */
assert_param(IS_TIM4_UPDATE_SOURCE_OK(TIM4_UpdateSource));
/* Set or Reset the URS Bit */
if (TIM4_UpdateSource != TIM4_UPDATESOURCE_GLOBAL)
{
TIM4->CR1 |= TIM4_CR1_URS;
}
else
{
TIM4->CR1 &= (uint8_t)(~TIM4_CR1_URS);
}
}
/**
* @brief Selects the TIM4s One Pulse Mode.
* @param TIM4_OPMode specifies the OPM Mode to be used.
* This parameter can be one of the following values
* - TIM4_OPMODE_SINGLE
* - TIM4_OPMODE_REPETITIVE
* @retval None
*/
void TIM4_SelectOnePulseMode(TIM4_OPMode_TypeDef TIM4_OPMode)
{
/* Check the parameters */
assert_param(IS_TIM4_OPM_MODE_OK(TIM4_OPMode));
/* Set or Reset the OPM Bit */
if (TIM4_OPMode != TIM4_OPMODE_REPETITIVE)
{
TIM4->CR1 |= TIM4_CR1_OPM;
}
else
{
TIM4->CR1 &= (uint8_t)(~TIM4_CR1_OPM);
}
}
/**
* @brief Configures the TIM4 Prescaler.
* @param Prescaler specifies the Prescaler Register value
* This parameter can be one of the following values
* - TIM4_PRESCALER_1
* - TIM4_PRESCALER_2
* - TIM4_PRESCALER_4
* - TIM4_PRESCALER_8
* - TIM4_PRESCALER_16
* - TIM4_PRESCALER_32
* - TIM4_PRESCALER_64
* - TIM4_PRESCALER_128
* @param TIM4_PSCReloadMode specifies the TIM4 Prescaler Reload mode.
* This parameter can be one of the following values
* - TIM4_PSCRELOADMODE_IMMEDIATE: The Prescaler is loaded
* immediately.
* - TIM4_PSCRELOADMODE_UPDATE: The Prescaler is loaded at
* the update event.
* @retval None
*/
void TIM4_PrescalerConfig(TIM4_Prescaler_TypeDef Prescaler, TIM4_PSCReloadMode_TypeDef TIM4_PSCReloadMode)
{
/* Check the parameters */
assert_param(IS_TIM4_PRESCALER_RELOAD_OK(TIM4_PSCReloadMode));
assert_param(IS_TIM4_PRESCALER_OK(Prescaler));
/* Set the Prescaler value */
TIM4->PSCR = (uint8_t)Prescaler;
/* Set or reset the UG Bit */
TIM4->EGR = (uint8_t)TIM4_PSCReloadMode;
}
/**
* @brief Enables or disables TIM4 peripheral Preload register on ARR.
* @param NewState new state of the TIM4 peripheral Preload register.
* This parameter can be ENABLE or DISABLE.
* @retval None
*/
void TIM4_ARRPreloadConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONALSTATE_OK(NewState));
/* Set or Reset the ARPE Bit */
if (NewState != DISABLE)
{
TIM4->CR1 |= TIM4_CR1_ARPE;
}
else
{
TIM4->CR1 &= (uint8_t)(~TIM4_CR1_ARPE);
}
}
/**
* @brief Configures the TIM4 event to be generated by software.
* @param TIM4_EventSource specifies the event source.
* This parameter can be one of the following values:
* - TIM4_EVENTSOURCE_UPDATE: TIM4 update Event source
* @retval None
*/
void TIM4_GenerateEvent(TIM4_EventSource_TypeDef TIM4_EventSource)
{
/* Check the parameters */
assert_param(IS_TIM4_EVENT_SOURCE_OK(TIM4_EventSource));
/* Set the event sources */
TIM4->EGR = (uint8_t)(TIM4_EventSource);
}
/**
* @brief Sets the TIM4 Counter Register value.
* @param Counter specifies the Counter register new value.
* This parameter is between 0x00 and 0xFF.
* @retval None
*/
void TIM4_SetCounter(uint8_t Counter)
{
/* Set the Counter Register value */
TIM4->CNTR = (uint8_t)(Counter);
}
/**
* @brief Sets the TIM4 Autoreload Register value.
* @param Autoreload specifies the Autoreload register new value.
* This parameter is between 0x00 and 0xFF.
* @retval None
*/
void TIM4_SetAutoreload(uint8_t Autoreload)
{
/* Set the Autoreload Register value */
TIM4->ARR = (uint8_t)(Autoreload);
}
/**
* @brief Gets the TIM4 Counter value.
* @param None
* @retval Counter Register value.
*/
uint8_t TIM4_GetCounter(void)
{
/* Get the Counter Register value */
return (uint8_t)(TIM4->CNTR);
}
/**
* @brief Gets the TIM4 Prescaler value.
* @param None
* @retval Prescaler Register configuration value.
*/
TIM4_Prescaler_TypeDef TIM4_GetPrescaler(void)
{
/* Get the Prescaler Register value */
return (TIM4_Prescaler_TypeDef)(TIM4->PSCR);
}
/**
* @brief Checks whether the specified TIM4 flag is set or not.
* @param TIM4_FLAG specifies the flag to check.
* This parameter can be one of the following values:
* - TIM4_FLAG_UPDATE: TIM4 update Flag
* @retval FlagStatus The new state of TIM4_FLAG (SET or RESET).
*/
FlagStatus TIM4_GetFlagStatus(TIM4_FLAG_TypeDef TIM4_FLAG)
{
FlagStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_TIM4_GET_FLAG_OK(TIM4_FLAG));
if ((TIM4->SR1 & (uint8_t)TIM4_FLAG) != 0)
{
bitstatus = SET;
}
else
{
bitstatus = RESET;
}
return ((FlagStatus)bitstatus);
}
/**
* @brief Clears the TIM4s pending flags.
* @param TIM4_FLAG specifies the flag to clear.
* This parameter can be one of the following values:
* - TIM4_FLAG_UPDATE: TIM4 update Flag
* @retval None.
*/
void TIM4_ClearFlag(TIM4_FLAG_TypeDef TIM4_FLAG)
{
/* Check the parameters */
assert_param(IS_TIM4_GET_FLAG_OK(TIM4_FLAG));
/* Clear the flags (rc_w0) clear this bit by writing 0. Writing 1 has no effect*/
TIM4->SR1 = (uint8_t)(~TIM4_FLAG);
}
/**
* @brief Checks whether the TIM4 interrupt has occurred or not.
* @param TIM4_IT specifies the TIM4 interrupt source to check.
* This parameter can be one of the following values:
* - TIM4_IT_UPDATE: TIM4 update Interrupt source
* @retval ITStatus The new state of the TIM4_IT (SET or RESET).
*/
ITStatus TIM4_GetITStatus(TIM4_IT_TypeDef TIM4_IT)
{
ITStatus bitstatus = RESET;
uint8_t itstatus = 0x0, itenable = 0x0;
/* Check the parameters */
assert_param(IS_TIM4_IT_OK(TIM4_IT));
itstatus = (uint8_t)(TIM4->SR1 & (uint8_t)TIM4_IT);
itenable = (uint8_t)(TIM4->IER & (uint8_t)TIM4_IT);
if ((itstatus != (uint8_t)RESET ) && (itenable != (uint8_t)RESET ))
{
bitstatus = (ITStatus)SET;
}
else
{
bitstatus = (ITStatus)RESET;
}
return ((ITStatus)bitstatus);
}
/**
* @brief Clears the TIM4's interrupt pending bits.
* @param TIM4_IT specifies the pending bit to clear.
* This parameter can be one of the following values:
* - TIM4_IT_UPDATE: TIM4 update Interrupt source
* @retval None.
*/
void TIM4_ClearITPendingBit(TIM4_IT_TypeDef TIM4_IT)
{
/* Check the parameters */
assert_param(IS_TIM4_IT_OK(TIM4_IT));
/* Clear the IT pending Bit */
TIM4->SR1 = (uint8_t)(~TIM4_IT);
}
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| mit |
Josiastech/vuforia-gamekit-integration | Gamekit/Ogre-1.8/RenderSystems/GLES2/src/EGL/X11/OgreX11EGLContext.cpp | 5 | 2026 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2RenderSystem.h"
#include "OgreEGLSupport.h"
#include "OgreX11EGLContext.h"
#include "OgreRoot.h"
namespace Ogre {
X11EGLContext::X11EGLContext(EGLDisplay eglDisplay,
const EGLSupport* glsupport,
::EGLConfig glconfig,
::EGLSurface drawable)
: EGLContext(eglDisplay, glsupport, glconfig, drawable)
{
}
X11EGLContext::~X11EGLContext()
{
}
GLES2Context* X11EGLContext::clone() const
{
return new X11EGLContext(mEglDisplay, mGLSupport, mConfig, mDrawable);
}
}
| mit |
sanqianyuejia/CSDK | curl/lib/url.c | 5 | 183708 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#ifndef HAVE_SOCKET
#error "We can't compile without socket() support!"
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef USE_LIBIDN
#include <idna.h>
#include <tld.h>
#include <stringprep.h>
#ifdef HAVE_IDN_FREE_H
#include <idn-free.h>
#else
/* prototype from idn-free.h, not provided by libidn 0.4.5's make install! */
void idn_free (void *ptr);
#endif
#ifndef HAVE_IDN_FREE
/* if idn_free() was not found in this version of libidn use free() instead */
#define idn_free(x) (free)(x)
#endif
#elif defined(USE_WIN32_IDN)
/* prototype for curl_win32_idn_to_ascii() */
int curl_win32_idn_to_ascii(const char *in, char **out);
#endif /* USE_LIBIDN */
#include "urldata.h"
#include "netrc.h"
#include "formdata.h"
#include "vtls/vtls.h"
#include "hostip.h"
#include "transfer.h"
#include "sendf.h"
#include "progress.h"
#include "cookie.h"
#include "strequal.h"
#include "strerror.h"
#include "escape.h"
#include "strtok.h"
#include "share.h"
#include "content_encoding.h"
#include "http_digest.h"
#include "http_negotiate.h"
#include "select.h"
#include "multiif.h"
#include "easyif.h"
#include "speedcheck.h"
#include "rawstr.h"
#include "warnless.h"
#include "non-ascii.h"
#include "inet_pton.h"
/* And now for the protocols */
#include "ftp.h"
#include "dict.h"
#include "telnet.h"
#include "tftp.h"
#include "http.h"
#include "file.h"
#include "curl_ldap.h"
#include "ssh.h"
#include "imap.h"
#include "url.h"
#include "connect.h"
#include "inet_ntop.h"
#include "curl_ntlm.h"
#include "curl_ntlm_wb.h"
#include "socks.h"
#include "curl_rtmp.h"
#include "gopher.h"
#include "http_proxy.h"
#include "bundles.h"
#include "conncache.h"
#include "multihandle.h"
#include "pipeline.h"
#include "dotdot.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local static prototypes */
static struct connectdata *
find_oldest_idle_connection(struct SessionHandle *data);
static struct connectdata *
find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
struct connectbundle *bundle);
static void conn_free(struct connectdata *conn);
static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
static CURLcode do_init(struct connectdata *conn);
static CURLcode parse_url_login(struct SessionHandle *data,
struct connectdata *conn,
char **userptr, char **passwdptr,
char **optionsptr);
static CURLcode parse_login_details(const char *login, const size_t len,
char **userptr, char **passwdptr,
char **optionsptr);
/*
* Protocol table.
*/
static const struct Curl_handler * const protocols[] = {
#ifndef CURL_DISABLE_HTTP
&Curl_handler_http,
#endif
#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
&Curl_handler_https,
#endif
#ifndef CURL_DISABLE_FTP
&Curl_handler_ftp,
#endif
#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
&Curl_handler_ftps,
#endif
#ifndef CURL_DISABLE_TELNET
&Curl_handler_telnet,
#endif
#ifndef CURL_DISABLE_DICT
&Curl_handler_dict,
#endif
#ifndef CURL_DISABLE_LDAP
&Curl_handler_ldap,
#if !defined(CURL_DISABLE_LDAPS) && \
((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
(!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
&Curl_handler_ldaps,
#endif
#endif
#ifndef CURL_DISABLE_FILE
&Curl_handler_file,
#endif
#ifndef CURL_DISABLE_TFTP
&Curl_handler_tftp,
#endif
#ifdef USE_LIBSSH2
&Curl_handler_scp,
&Curl_handler_sftp,
#endif
#ifndef CURL_DISABLE_IMAP
&Curl_handler_imap,
#ifdef USE_SSL
&Curl_handler_imaps,
#endif
#endif
#ifndef CURL_DISABLE_POP3
&Curl_handler_pop3,
#ifdef USE_SSL
&Curl_handler_pop3s,
#endif
#endif
#ifndef CURL_DISABLE_SMTP
&Curl_handler_smtp,
#ifdef USE_SSL
&Curl_handler_smtps,
#endif
#endif
#ifndef CURL_DISABLE_RTSP
&Curl_handler_rtsp,
#endif
#ifndef CURL_DISABLE_GOPHER
&Curl_handler_gopher,
#endif
#ifdef USE_LIBRTMP
&Curl_handler_rtmp,
&Curl_handler_rtmpt,
&Curl_handler_rtmpe,
&Curl_handler_rtmpte,
&Curl_handler_rtmps,
&Curl_handler_rtmpts,
#endif
(struct Curl_handler *) NULL
};
/*
* Dummy handler for undefined protocol schemes.
*/
static const struct Curl_handler Curl_handler_dummy = {
"<no protocol>", /* scheme */
ZERO_NULL, /* setup_connection */
ZERO_NULL, /* do_it */
ZERO_NULL, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
0, /* defport */
0, /* protocol */
PROTOPT_NONE /* flags */
};
void Curl_freeset(struct SessionHandle *data)
{
/* Free all dynamic strings stored in the data->set substructure. */
enum dupstring i;
for(i=(enum dupstring)0; i < STRING_LAST; i++)
Curl_safefree(data->set.str[i]);
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
}
static CURLcode setstropt(char **charp, char *s)
{
/* Release the previous storage at `charp' and replace by a dynamic storage
copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
Curl_safefree(*charp);
if(s) {
s = strdup(s);
if(!s)
return CURLE_OUT_OF_MEMORY;
*charp = s;
}
return CURLE_OK;
}
static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp)
{
CURLcode result = CURLE_OK;
char *user = NULL;
char *passwd = NULL;
/* Parse the login details if specified. It not then we treat NULL as a hint
to clear the existing data */
if(option) {
result = parse_login_details(option, strlen(option),
(userp ? &user : NULL),
(passwdp ? &passwd : NULL),
NULL);
}
if(!result) {
/* Store the username part of option if required */
if(userp) {
if(!user && option && option[0] == ':') {
/* Allocate an empty string instead of returning NULL as user name */
user = strdup("");
if(!user)
result = CURLE_OUT_OF_MEMORY;
}
Curl_safefree(*userp);
*userp = user;
}
/* Store the password part of option if required */
if(passwdp) {
Curl_safefree(*passwdp);
*passwdp = passwd;
}
}
return result;
}
CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src)
{
CURLcode r = CURLE_OK;
enum dupstring i;
/* Copy src->set into dst->set first, then deal with the strings
afterwards */
dst->set = src->set;
/* clear all string pointers first */
memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
/* duplicate all strings */
for(i=(enum dupstring)0; i< STRING_LAST; i++) {
r = setstropt(&dst->set.str[i], src->set.str[i]);
if(r != CURLE_OK)
break;
}
/* If a failure occurred, freeing has to be performed externally. */
return r;
}
/*
* This is the internal function curl_easy_cleanup() calls. This should
* cleanup and free all resources associated with this sessionhandle.
*
* NOTE: if we ever add something that attempts to write to a socket or
* similar here, we must ignore SIGPIPE first. It is currently only done
* when curl_easy_perform() is invoked.
*/
CURLcode Curl_close(struct SessionHandle *data)
{
struct Curl_multi *m;
if(!data)
return CURLE_OK;
Curl_expire(data, 0); /* shut off timers */
m = data->multi;
if(m)
/* This handle is still part of a multi handle, take care of this first
and detach this handle from there. */
curl_multi_remove_handle(data->multi, data);
if(data->multi_easy)
/* when curl_easy_perform() is used, it creates its own multi handle to
use and this is the one */
curl_multi_cleanup(data->multi_easy);
/* Destroy the timeout list that is held in the easy handle. It is
/normally/ done by curl_multi_remove_handle() but this is "just in
case" */
if(data->state.timeoutlist) {
Curl_llist_destroy(data->state.timeoutlist, NULL);
data->state.timeoutlist = NULL;
}
data->magic = 0; /* force a clear AFTER the possibly enforced removal from
the multi handle, since that function uses the magic
field! */
if(data->state.rangestringalloc)
free(data->state.range);
/* Free the pathbuffer */
Curl_safefree(data->state.pathbuffer);
data->state.path = NULL;
/* freed here just in case DONE wasn't called */
Curl_free_request_state(data);
/* Close down all open SSL info and sessions */
Curl_ssl_close_all(data);
Curl_safefree(data->state.first_host);
Curl_safefree(data->state.scratch);
Curl_ssl_free_certinfo(data);
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
data->change.url = NULL;
Curl_safefree(data->state.headerbuff);
Curl_flush_cookies(data, 1);
Curl_digest_cleanup(data);
Curl_safefree(data->info.contenttype);
Curl_safefree(data->info.wouldredirect);
/* this destroys the channel and we cannot use it anymore after this */
Curl_resolver_cleanup(data->state.resolver);
Curl_convert_close(data);
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
Curl_freeset(data);
free(data);
return CURLE_OK;
}
/*
* Initialize the UserDefined fields within a SessionHandle.
* This may be safely called on a new or existing SessionHandle.
*/
CURLcode Curl_init_userdefined(struct UserDefined *set)
{
CURLcode res = CURLE_OK;
set->out = stdout; /* default output to stdout */
set->in = stdin; /* default input from stdin */
set->err = stderr; /* default stderr to stderr */
/* use fwrite as default function to store output */
set->fwrite_func = (curl_write_callback)fwrite;
/* use fread as default function to read input */
set->fread_func = (curl_read_callback)fread;
set->is_fread_set = 0;
set->is_fwrite_set = 0;
set->seek_func = ZERO_NULL;
set->seek_client = ZERO_NULL;
/* conversion callbacks for non-ASCII hosts */
set->convfromnetwork = ZERO_NULL;
set->convtonetwork = ZERO_NULL;
set->convfromutf8 = ZERO_NULL;
set->filesize = -1; /* we don't know the size */
set->postfieldsize = -1; /* unknown size */
set->maxredirs = -1; /* allow any amount by default */
set->httpreq = HTTPREQ_GET; /* Default HTTP request */
set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
set->ftp_filemethod = FTPFILE_MULTICWD;
set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
/* Set the default size of the SSL session ID cache */
set->ssl.max_ssl_sessions = 5;
set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
/* make libcurl quiet by default: */
set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
/*
* libcurl 7.10 introduced SSL verification *by default*! This needs to be
* switched off unless wanted.
*/
set->ssl.verifypeer = TRUE;
set->ssl.verifyhost = TRUE;
#ifdef USE_TLS_SRP
set->ssl.authtype = CURL_TLSAUTH_NONE;
#endif
set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
type */
set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
set->new_file_perms = 0644; /* Default permissions */
set->new_directory_perms = 0755; /* Default permissions */
/* for the *protocols fields we don't use the CURLPROTO_ALL convenience
define since we internally only use the lower 16 bits for the passed
in bitmask to not conflict with the private bits */
set->allowed_protocols = CURLPROTO_ALL;
set->redir_protocols =
CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
/*
* disallow unprotected protection negotiation NEC reference implementation
* seem not to follow rfc1961 section 4.3/4.4
*/
set->socks5_gssapi_nec = FALSE;
/* set default gssapi service name */
res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
(char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
if(res != CURLE_OK)
return res;
#endif
/* This is our preferred CA cert bundle/path since install time */
#if defined(CURL_CA_BUNDLE)
res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
#elif defined(CURL_CA_PATH)
res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
#endif
set->wildcardmatch = FALSE;
set->chunk_bgn = ZERO_NULL;
set->chunk_end = ZERO_NULL;
/* tcp keepalives are disabled by default, but provide reasonable values for
* the interval and idle times.
*/
set->tcp_keepalive = FALSE;
set->tcp_keepintvl = 60;
set->tcp_keepidle = 60;
set->ssl_enable_npn = TRUE;
set->ssl_enable_alpn = TRUE;
set->expect_100_timeout = 1000L; /* Wait for a second by default. */
return res;
}
/**
* Curl_open()
*
* @param curl is a pointer to a sessionhandle pointer that gets set by this
* function.
* @return CURLcode
*/
CURLcode Curl_open(struct SessionHandle **curl)
{
CURLcode res = CURLE_OK;
struct SessionHandle *data;
CURLcode status;
/* Very simple start-up: alloc the struct, init it with zeroes and return */
data = calloc(1, sizeof(struct SessionHandle));
if(!data) {
/* this is a very serious error */
DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
return CURLE_OUT_OF_MEMORY;
}
data->magic = CURLEASY_MAGIC_NUMBER;
status = Curl_resolver_init(&data->state.resolver);
if(status) {
DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
free(data);
return status;
}
/* We do some initial setup here, all those fields that can't be just 0 */
data->state.headerbuff = malloc(HEADERSIZE);
if(!data->state.headerbuff) {
DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
res = CURLE_OUT_OF_MEMORY;
}
else {
res = Curl_init_userdefined(&data->set);
data->state.headersize=HEADERSIZE;
Curl_convert_init(data);
/* most recent connection is not yet defined */
data->state.lastconnect = NULL;
data->progress.flags |= PGRS_HIDE;
data->state.current_speed = -1; /* init to negative == impossible */
data->wildcard.state = CURLWC_INIT;
data->wildcard.filelist = NULL;
data->set.fnmatch = ZERO_NULL;
data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
}
if(res) {
Curl_resolver_cleanup(data->state.resolver);
if(data->state.headerbuff)
free(data->state.headerbuff);
Curl_freeset(data);
free(data);
data = NULL;
}
else
*curl = data;
return res;
}
CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
va_list param)
{
char *argptr;
CURLcode result = CURLE_OK;
long arg;
#ifndef CURL_DISABLE_HTTP
curl_off_t bigsize;
#endif
switch(option) {
case CURLOPT_DNS_CACHE_TIMEOUT:
data->set.dns_cache_timeout = va_arg(param, long);
break;
case CURLOPT_DNS_USE_GLOBAL_CACHE:
/* remember we want this enabled */
arg = va_arg(param, long);
data->set.global_dns_cache = (0 != arg)?TRUE:FALSE;
break;
case CURLOPT_SSL_CIPHER_LIST:
/* set a list of cipher we want to use in the SSL connection */
result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
va_arg(param, char *));
break;
case CURLOPT_RANDOM_FILE:
/*
* This is the path name to a file that contains random data to seed
* the random SSL stuff with. The file is only used for reading.
*/
result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
va_arg(param, char *));
break;
case CURLOPT_EGDSOCKET:
/*
* The Entropy Gathering Daemon socket pathname
*/
result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
va_arg(param, char *));
break;
case CURLOPT_MAXCONNECTS:
/*
* Set the absolute number of maximum simultaneous alive connection that
* libcurl is allowed to have.
*/
data->set.maxconnects = va_arg(param, long);
break;
case CURLOPT_FORBID_REUSE:
/*
* When this transfer is done, it must not be left to be reused by a
* subsequent transfer but shall be closed immediately.
*/
data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FRESH_CONNECT:
/*
* This transfer shall not use a previously cached connection but
* should be made with a fresh new connect!
*/
data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_VERBOSE:
/*
* Verbose means infof() calls that give a lot of information about
* the connection and transfer procedures as well as internal choices.
*/
data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_HEADER:
/*
* Set to include the header in the general data output stream.
*/
data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_NOPROGRESS:
/*
* Shut off the internal supported progress meter
*/
data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE;
if(data->set.hide_progress)
data->progress.flags |= PGRS_HIDE;
else
data->progress.flags &= ~PGRS_HIDE;
break;
case CURLOPT_NOBODY:
/*
* Do not include the body part in the output data stream.
*/
data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FAILONERROR:
/*
* Don't output the >=300 error code HTML-page, but instead only
* return error.
*/
data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_UPLOAD:
case CURLOPT_PUT:
/*
* We want to sent data to the remote host. If this is HTTP, that equals
* using the PUT request.
*/
data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE;
if(data->set.upload) {
/* If this is HTTP, PUT is what's needed to "upload" */
data->set.httpreq = HTTPREQ_PUT;
data->set.opt_no_body = FALSE; /* this is implied */
}
else
/* In HTTP, the opposite of upload is GET (unless NOBODY is true as
then this can be changed to HEAD later on) */
data->set.httpreq = HTTPREQ_GET;
break;
case CURLOPT_FILETIME:
/*
* Try to get the file time of the remote document. The time will
* later (possibly) become available using curl_easy_getinfo().
*/
data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_CREATE_MISSING_DIRS:
/*
* An FTP option that modifies an upload to create missing directories on
* the server.
*/
switch(va_arg(param, long)) {
case 0:
data->set.ftp_create_missing_dirs = 0;
break;
case 1:
data->set.ftp_create_missing_dirs = 1;
break;
case 2:
data->set.ftp_create_missing_dirs = 2;
break;
default:
/* reserve other values for future use */
result = CURLE_UNKNOWN_OPTION;
break;
}
break;
case CURLOPT_SERVER_RESPONSE_TIMEOUT:
/*
* Option that specifies how quickly an server response must be obtained
* before it is considered failure. For pingpong protocols.
*/
data->set.server_response_timeout = va_arg( param , long ) * 1000;
break;
case CURLOPT_TFTP_BLKSIZE:
/*
* TFTP option that specifies the block size to use for data transmission
*/
data->set.tftp_blksize = va_arg(param, long);
break;
case CURLOPT_DIRLISTONLY:
/*
* An option that changes the command to one that asks for a list
* only, no file info details.
*/
data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_APPEND:
/*
* We want to upload and append to an existing file.
*/
data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_FILEMETHOD:
/*
* How do access files over FTP.
*/
data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
break;
case CURLOPT_NETRC:
/*
* Parse the $HOME/.netrc file
*/
data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
break;
case CURLOPT_NETRC_FILE:
/*
* Use this file instead of the $HOME/.netrc file
*/
result = setstropt(&data->set.str[STRING_NETRC_FILE],
va_arg(param, char *));
break;
case CURLOPT_TRANSFERTEXT:
/*
* This option was previously named 'FTPASCII'. Renamed to work with
* more protocols than merely FTP.
*
* Transfer using ASCII (instead of BINARY).
*/
data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_TIMECONDITION:
/*
* Set HTTP time condition. This must be one of the defines in the
* curl/curl.h header file.
*/
data->set.timecondition = (curl_TimeCond)va_arg(param, long);
break;
case CURLOPT_TIMEVALUE:
/*
* This is the value to compare with the remote document with the
* method set with CURLOPT_TIMECONDITION
*/
data->set.timevalue = (time_t)va_arg(param, long);
break;
case CURLOPT_SSLVERSION:
/*
* Set explicit SSL version to try to connect with, as some SSL
* implementations are lame.
*/
data->set.ssl.version = va_arg(param, long);
break;
#ifndef CURL_DISABLE_HTTP
case CURLOPT_AUTOREFERER:
/*
* Switch on automatic referer that gets set if curl follows locations.
*/
data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_ACCEPT_ENCODING:
/*
* String to use at the value of Accept-Encoding header.
*
* If the encoding is set to "" we use an Accept-Encoding header that
* encompasses all the encodings we support.
* If the encoding is set to NULL we don't send an Accept-Encoding header
* and ignore an received Content-Encoding header.
*
*/
argptr = va_arg(param, char *);
result = setstropt(&data->set.str[STRING_ENCODING],
(argptr && !*argptr)?
(char *) ALL_CONTENT_ENCODINGS: argptr);
break;
case CURLOPT_TRANSFER_ENCODING:
data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FOLLOWLOCATION:
/*
* Follow Location: header hints on a HTTP-server.
*/
data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_UNRESTRICTED_AUTH:
/*
* Send authentication (user+password) when following locations, even when
* hostname changed.
*/
data->set.http_disable_hostname_check_before_authentication =
(0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_MAXREDIRS:
/*
* The maximum amount of hops you allow curl to follow Location:
* headers. This should mostly be used to detect never-ending loops.
*/
data->set.maxredirs = va_arg(param, long);
break;
case CURLOPT_POSTREDIR:
{
/*
* Set the behaviour of POST when redirecting
* CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
* CURL_REDIR_POST_301 - POST is kept as POST after 301
* CURL_REDIR_POST_302 - POST is kept as POST after 302
* CURL_REDIR_POST_303 - POST is kept as POST after 303
* CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
* other - POST is kept as POST after 301 and 302
*/
int postRedir = curlx_sltosi(va_arg(param, long));
data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
}
break;
case CURLOPT_POST:
/* Does this option serve a purpose anymore? Yes it does, when
CURLOPT_POSTFIELDS isn't used and the POST data is read off the
callback! */
if(va_arg(param, long)) {
data->set.httpreq = HTTPREQ_POST;
data->set.opt_no_body = FALSE; /* this is implied */
}
else
data->set.httpreq = HTTPREQ_GET;
break;
case CURLOPT_COPYPOSTFIELDS:
/*
* A string with POST data. Makes curl HTTP POST. Even if it is NULL.
* If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
* CURLOPT_COPYPOSTFIELDS and not altered later.
*/
argptr = va_arg(param, char *);
if(!argptr || data->set.postfieldsize == -1)
result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
else {
/*
* Check that requested length does not overflow the size_t type.
*/
if((data->set.postfieldsize < 0) ||
((sizeof(curl_off_t) != sizeof(size_t)) &&
(data->set.postfieldsize > (curl_off_t)((size_t)-1))))
result = CURLE_OUT_OF_MEMORY;
else {
char * p;
(void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
/* Allocate even when size == 0. This satisfies the need of possible
later address compare to detect the COPYPOSTFIELDS mode, and
to mark that postfields is used rather than read function or
form data.
*/
p = malloc((size_t)(data->set.postfieldsize?
data->set.postfieldsize:1));
if(!p)
result = CURLE_OUT_OF_MEMORY;
else {
if(data->set.postfieldsize)
memcpy(p, argptr, (size_t)data->set.postfieldsize);
data->set.str[STRING_COPYPOSTFIELDS] = p;
}
}
}
data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
data->set.httpreq = HTTPREQ_POST;
break;
case CURLOPT_POSTFIELDS:
/*
* Like above, but use static data instead of copying it.
*/
data->set.postfields = va_arg(param, void *);
/* Release old copied data. */
(void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
data->set.httpreq = HTTPREQ_POST;
break;
case CURLOPT_POSTFIELDSIZE:
/*
* The size of the POSTFIELD data to prevent libcurl to do strlen() to
* figure it out. Enables binary posts.
*/
bigsize = va_arg(param, long);
if(data->set.postfieldsize < bigsize &&
data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
/* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
(void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
data->set.postfields = NULL;
}
data->set.postfieldsize = bigsize;
break;
case CURLOPT_POSTFIELDSIZE_LARGE:
/*
* The size of the POSTFIELD data to prevent libcurl to do strlen() to
* figure it out. Enables binary posts.
*/
bigsize = va_arg(param, curl_off_t);
if(data->set.postfieldsize < bigsize &&
data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
/* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
(void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
data->set.postfields = NULL;
}
data->set.postfieldsize = bigsize;
break;
case CURLOPT_HTTPPOST:
/*
* Set to make us do HTTP POST
*/
data->set.httppost = va_arg(param, struct curl_httppost *);
data->set.httpreq = HTTPREQ_POST_FORM;
data->set.opt_no_body = FALSE; /* this is implied */
break;
case CURLOPT_REFERER:
/*
* String to set in the HTTP Referer: field.
*/
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
result = setstropt(&data->set.str[STRING_SET_REFERER],
va_arg(param, char *));
data->change.referer = data->set.str[STRING_SET_REFERER];
break;
case CURLOPT_USERAGENT:
/*
* String to use in the HTTP User-Agent field
*/
result = setstropt(&data->set.str[STRING_USERAGENT],
va_arg(param, char *));
break;
case CURLOPT_HTTPHEADER:
/*
* Set a list with HTTP headers to use (or replace internals with)
*/
data->set.headers = va_arg(param, struct curl_slist *);
break;
case CURLOPT_PROXYHEADER:
/*
* Set a list with proxy headers to use (or replace internals with)
*
* Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a
* long time we remain doing it this way until CURLOPT_PROXYHEADER is
* used. As soon as this option has been used, if set to anything but
* NULL, custom headers for proxies are only picked from this list.
*
* Set this option to NULL to restore the previous behavior.
*/
data->set.proxyheaders = va_arg(param, struct curl_slist *);
break;
case CURLOPT_HEADEROPT:
/*
* Set header option.
*/
arg = va_arg(param, long);
data->set.sep_headers = (arg & CURLHEADER_SEPARATE)? TRUE: FALSE;
break;
case CURLOPT_HTTP200ALIASES:
/*
* Set a list of aliases for HTTP 200 in response header
*/
data->set.http200aliases = va_arg(param, struct curl_slist *);
break;
#if !defined(CURL_DISABLE_COOKIES)
case CURLOPT_COOKIE:
/*
* Cookie string to send to the remote server in the request.
*/
result = setstropt(&data->set.str[STRING_COOKIE],
va_arg(param, char *));
break;
case CURLOPT_COOKIEFILE:
/*
* Set cookie file to read and parse. Can be used multiple times.
*/
argptr = (char *)va_arg(param, void *);
if(argptr) {
struct curl_slist *cl;
/* append the cookie file name to the list of file names, and deal with
them later */
cl = curl_slist_append(data->change.cookielist, argptr);
if(!cl) {
curl_slist_free_all(data->change.cookielist);
data->change.cookielist = NULL;
return CURLE_OUT_OF_MEMORY;
}
data->change.cookielist = cl; /* store the list for later use */
}
break;
case CURLOPT_COOKIEJAR:
/*
* Set cookie file name to dump all cookies to when we're done.
*/
result = setstropt(&data->set.str[STRING_COOKIEJAR],
va_arg(param, char *));
/*
* Activate the cookie parser. This may or may not already
* have been made.
*/
data->cookies = Curl_cookie_init(data, NULL, data->cookies,
data->set.cookiesession);
break;
case CURLOPT_COOKIESESSION:
/*
* Set this option to TRUE to start a new "cookie session". It will
* prevent the forthcoming read-cookies-from-file actions to accept
* cookies that are marked as being session cookies, as they belong to a
* previous session.
*
* In the original Netscape cookie spec, "session cookies" are cookies
* with no expire date set. RFC2109 describes the same action if no
* 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
* a 'Discard' action that can enforce the discard even for cookies that
* have a Max-Age.
*
* We run mostly with the original cookie spec, as hardly anyone implements
* anything else.
*/
data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_COOKIELIST:
argptr = va_arg(param, char *);
if(argptr == NULL)
break;
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
if(Curl_raw_equal(argptr, "ALL")) {
/* clear all cookies */
Curl_cookie_clearall(data->cookies);
}
else if(Curl_raw_equal(argptr, "SESS")) {
/* clear session cookies */
Curl_cookie_clearsess(data->cookies);
}
else if(Curl_raw_equal(argptr, "FLUSH")) {
/* flush cookies to file */
Curl_flush_cookies(data, 0);
}
else {
if(!data->cookies)
/* if cookie engine was not running, activate it */
data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
argptr = strdup(argptr);
if(!argptr) {
result = CURLE_OUT_OF_MEMORY;
}
else {
if(checkprefix("Set-Cookie:", argptr))
/* HTTP Header format line */
Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
else
/* Netscape format line */
Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
free(argptr);
}
}
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
break;
#endif /* CURL_DISABLE_COOKIES */
case CURLOPT_HTTPGET:
/*
* Set to force us do HTTP GET
*/
if(va_arg(param, long)) {
data->set.httpreq = HTTPREQ_GET;
data->set.upload = FALSE; /* switch off upload */
data->set.opt_no_body = FALSE; /* this is implied */
}
break;
case CURLOPT_HTTP_VERSION:
/*
* This sets a requested HTTP version to be used. The value is one of
* the listed enums in curl/curl.h.
*/
arg = va_arg(param, long);
#ifndef USE_NGHTTP2
if(arg == CURL_HTTP_VERSION_2_0)
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
data->set.httpversion = arg;
break;
case CURLOPT_HTTPAUTH:
/*
* Set HTTP Authentication type BITMASK.
*/
{
int bitcheck;
bool authbits;
unsigned long auth = va_arg(param, unsigned long);
if(auth == CURLAUTH_NONE) {
data->set.httpauth = auth;
break;
}
/* the DIGEST_IE bit is only used to set a special marker, for all the
rest we need to handle it as normal DIGEST */
data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
if(auth & CURLAUTH_DIGEST_IE) {
auth |= CURLAUTH_DIGEST; /* set standard digest bit */
auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
}
/* switch off bits we can't support */
#ifndef USE_NTLM
auth &= ~CURLAUTH_NTLM; /* no NTLM support */
auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
#elif !defined(NTLM_WB_ENABLED)
auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
#endif
#ifndef USE_HTTP_NEGOTIATE
auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
WINDOWS_SSPI */
#endif
/* check if any auth bit lower than CURLAUTH_ONLY is still set */
bitcheck = 0;
authbits = FALSE;
while(bitcheck < 31) {
if(auth & (1UL << bitcheck++)) {
authbits = TRUE;
break;
}
}
if(!authbits)
return CURLE_NOT_BUILT_IN; /* no supported types left! */
data->set.httpauth = auth;
}
break;
case CURLOPT_EXPECT_100_TIMEOUT_MS:
/*
* Time to wait for a response to a HTTP request containing an
* Expect: 100-continue header before sending the data anyway.
*/
data->set.expect_100_timeout = va_arg(param, long);
break;
#endif /* CURL_DISABLE_HTTP */
case CURLOPT_CUSTOMREQUEST:
/*
* Set a custom string to use as request
*/
result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
va_arg(param, char *));
/* we don't set
data->set.httpreq = HTTPREQ_CUSTOM;
here, we continue as if we were using the already set type
and this just changes the actual request keyword */
break;
#ifndef CURL_DISABLE_PROXY
case CURLOPT_HTTPPROXYTUNNEL:
/*
* Tunnel operations through the proxy instead of normal proxy use
*/
data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_PROXYPORT:
/*
* Explicitly set HTTP proxy port number.
*/
data->set.proxyport = va_arg(param, long);
break;
case CURLOPT_PROXYAUTH:
/*
* Set HTTP Authentication type BITMASK.
*/
{
int bitcheck;
bool authbits;
unsigned long auth = va_arg(param, unsigned long);
if(auth == CURLAUTH_NONE) {
data->set.proxyauth = auth;
break;
}
/* the DIGEST_IE bit is only used to set a special marker, for all the
rest we need to handle it as normal DIGEST */
data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
if(auth & CURLAUTH_DIGEST_IE) {
auth |= CURLAUTH_DIGEST; /* set standard digest bit */
auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
}
/* switch off bits we can't support */
#ifndef USE_NTLM
auth &= ~CURLAUTH_NTLM; /* no NTLM support */
auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
#elif !defined(NTLM_WB_ENABLED)
auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
#endif
#ifndef USE_HTTP_NEGOTIATE
auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
WINDOWS_SSPI */
#endif
/* check if any auth bit lower than CURLAUTH_ONLY is still set */
bitcheck = 0;
authbits = FALSE;
while(bitcheck < 31) {
if(auth & (1UL << bitcheck++)) {
authbits = TRUE;
break;
}
}
if(!authbits)
return CURLE_NOT_BUILT_IN; /* no supported types left! */
data->set.proxyauth = auth;
}
break;
case CURLOPT_PROXY:
/*
* Set proxy server:port to use as HTTP proxy.
*
* If the proxy is set to "" we explicitly say that we don't want to use a
* proxy (even though there might be environment variables saying so).
*
* Setting it to NULL, means no proxy but allows the environment variables
* to decide for us.
*/
result = setstropt(&data->set.str[STRING_PROXY],
va_arg(param, char *));
break;
case CURLOPT_PROXYTYPE:
/*
* Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
*/
data->set.proxytype = (curl_proxytype)va_arg(param, long);
break;
case CURLOPT_PROXY_TRANSFER_MODE:
/*
* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
*/
switch (va_arg(param, long)) {
case 0:
data->set.proxy_transfer_mode = FALSE;
break;
case 1:
data->set.proxy_transfer_mode = TRUE;
break;
default:
/* reserve other values for future use */
result = CURLE_UNKNOWN_OPTION;
break;
}
break;
#endif /* CURL_DISABLE_PROXY */
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
case CURLOPT_SOCKS5_GSSAPI_SERVICE:
/*
* Set gssapi service name
*/
result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
va_arg(param, char *));
break;
case CURLOPT_SOCKS5_GSSAPI_NEC:
/*
* set flag for nec socks5 support
*/
data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE;
break;
#endif
case CURLOPT_WRITEHEADER:
/*
* Custom pointer to pass the header write callback function
*/
data->set.writeheader = (void *)va_arg(param, void *);
break;
case CURLOPT_ERRORBUFFER:
/*
* Error buffer provided by the caller to get the human readable
* error string in.
*/
data->set.errorbuffer = va_arg(param, char *);
break;
case CURLOPT_FILE:
/*
* FILE pointer to write to. Or possibly
* used as argument to the write callback.
*/
data->set.out = va_arg(param, void *);
break;
case CURLOPT_FTPPORT:
/*
* Use FTP PORT, this also specifies which IP address to use
*/
result = setstropt(&data->set.str[STRING_FTPPORT],
va_arg(param, char *));
data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ?
TRUE:FALSE;
break;
case CURLOPT_FTP_USE_EPRT:
data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_USE_EPSV:
data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_USE_PRET:
data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_SSL_CCC:
data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
break;
case CURLOPT_FTP_SKIP_PASV_IP:
/*
* Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
* bypass of the IP address in PASV responses.
*/
data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_INFILE:
/*
* FILE pointer to read the file to be uploaded from. Or possibly
* used as argument to the read callback.
*/
data->set.in = va_arg(param, void *);
break;
case CURLOPT_INFILESIZE:
/*
* If known, this should inform curl about the file size of the
* to-be-uploaded file.
*/
data->set.filesize = va_arg(param, long);
break;
case CURLOPT_INFILESIZE_LARGE:
/*
* If known, this should inform curl about the file size of the
* to-be-uploaded file.
*/
data->set.filesize = va_arg(param, curl_off_t);
break;
case CURLOPT_LOW_SPEED_LIMIT:
/*
* The low speed limit that if transfers are below this for
* CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
*/
data->set.low_speed_limit=va_arg(param, long);
break;
case CURLOPT_MAX_SEND_SPEED_LARGE:
/*
* When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
* bytes per second the transfer is throttled..
*/
data->set.max_send_speed=va_arg(param, curl_off_t);
break;
case CURLOPT_MAX_RECV_SPEED_LARGE:
/*
* When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
* second the transfer is throttled..
*/
data->set.max_recv_speed=va_arg(param, curl_off_t);
break;
case CURLOPT_LOW_SPEED_TIME:
/*
* The low speed time that if transfers are below the set
* CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
*/
data->set.low_speed_time=va_arg(param, long);
break;
case CURLOPT_URL:
/*
* The URL to fetch.
*/
if(data->change.url_alloc) {
/* the already set URL is allocated, free it first! */
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
result = setstropt(&data->set.str[STRING_SET_URL],
va_arg(param, char *));
data->change.url = data->set.str[STRING_SET_URL];
break;
case CURLOPT_PORT:
/*
* The port number to use when getting the URL
*/
data->set.use_port = va_arg(param, long);
break;
case CURLOPT_TIMEOUT:
/*
* The maximum time you allow curl to use for a single transfer
* operation.
*/
data->set.timeout = va_arg(param, long) * 1000L;
break;
case CURLOPT_TIMEOUT_MS:
data->set.timeout = va_arg(param, long);
break;
case CURLOPT_CONNECTTIMEOUT:
/*
* The maximum time you allow curl to use to connect.
*/
data->set.connecttimeout = va_arg(param, long) * 1000L;
break;
case CURLOPT_CONNECTTIMEOUT_MS:
data->set.connecttimeout = va_arg(param, long);
break;
case CURLOPT_ACCEPTTIMEOUT_MS:
/*
* The maximum time you allow curl to wait for server connect
*/
data->set.accepttimeout = va_arg(param, long);
break;
case CURLOPT_USERPWD:
/*
* user:password to use in the operation
*/
result = setstropt_userpwd(va_arg(param, char *),
&data->set.str[STRING_USERNAME],
&data->set.str[STRING_PASSWORD]);
break;
case CURLOPT_USERNAME:
/*
* authentication user name to use in the operation
*/
result = setstropt(&data->set.str[STRING_USERNAME],
va_arg(param, char *));
break;
case CURLOPT_PASSWORD:
/*
* authentication password to use in the operation
*/
result = setstropt(&data->set.str[STRING_PASSWORD],
va_arg(param, char *));
break;
case CURLOPT_LOGIN_OPTIONS:
/*
* authentication options to use in the operation
*/
result = setstropt(&data->set.str[STRING_OPTIONS],
va_arg(param, char *));
break;
case CURLOPT_XOAUTH2_BEARER:
/*
* XOAUTH2 bearer token to use in the operation
*/
result = setstropt(&data->set.str[STRING_BEARER],
va_arg(param, char *));
break;
case CURLOPT_POSTQUOTE:
/*
* List of RAW FTP commands to use after a transfer
*/
data->set.postquote = va_arg(param, struct curl_slist *);
break;
case CURLOPT_PREQUOTE:
/*
* List of RAW FTP commands to use prior to RETR (Wesley Laxton)
*/
data->set.prequote = va_arg(param, struct curl_slist *);
break;
case CURLOPT_QUOTE:
/*
* List of RAW FTP commands to use before a transfer
*/
data->set.quote = va_arg(param, struct curl_slist *);
break;
case CURLOPT_RESOLVE:
/*
* List of NAME:[address] names to populate the DNS cache with
* Prefix the NAME with dash (-) to _remove_ the name from the cache.
*
* Names added with this API will remain in the cache until explicitly
* removed or the handle is cleaned up.
*
* This API can remove any name from the DNS cache, but only entries
* that aren't actually in use right now will be pruned immediately.
*/
data->set.resolve = va_arg(param, struct curl_slist *);
data->change.resolve = data->set.resolve;
break;
case CURLOPT_PROGRESSFUNCTION:
/*
* Progress callback function
*/
data->set.fprogress = va_arg(param, curl_progress_callback);
if(data->set.fprogress)
data->progress.callback = TRUE; /* no longer internal */
else
data->progress.callback = FALSE; /* NULL enforces internal */
break;
case CURLOPT_XFERINFOFUNCTION:
/*
* Transfer info callback function
*/
data->set.fxferinfo = va_arg(param, curl_xferinfo_callback);
if(data->set.fxferinfo)
data->progress.callback = TRUE; /* no longer internal */
else
data->progress.callback = FALSE; /* NULL enforces internal */
break;
case CURLOPT_PROGRESSDATA:
/*
* Custom client data to pass to the progress callback
*/
data->set.progress_client = va_arg(param, void *);
break;
#ifndef CURL_DISABLE_PROXY
case CURLOPT_PROXYUSERPWD:
/*
* user:password needed to use the proxy
*/
result = setstropt_userpwd(va_arg(param, char *),
&data->set.str[STRING_PROXYUSERNAME],
&data->set.str[STRING_PROXYPASSWORD]);
break;
case CURLOPT_PROXYUSERNAME:
/*
* authentication user name to use in the operation
*/
result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
va_arg(param, char *));
break;
case CURLOPT_PROXYPASSWORD:
/*
* authentication password to use in the operation
*/
result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
va_arg(param, char *));
break;
case CURLOPT_NOPROXY:
/*
* proxy exception list
*/
result = setstropt(&data->set.str[STRING_NOPROXY],
va_arg(param, char *));
break;
#endif
case CURLOPT_RANGE:
/*
* What range of the file you want to transfer
*/
result = setstropt(&data->set.str[STRING_SET_RANGE],
va_arg(param, char *));
break;
case CURLOPT_RESUME_FROM:
/*
* Resume transfer at the give file position
*/
data->set.set_resume_from = va_arg(param, long);
break;
case CURLOPT_RESUME_FROM_LARGE:
/*
* Resume transfer at the give file position
*/
data->set.set_resume_from = va_arg(param, curl_off_t);
break;
case CURLOPT_DEBUGFUNCTION:
/*
* stderr write callback.
*/
data->set.fdebug = va_arg(param, curl_debug_callback);
/*
* if the callback provided is NULL, it'll use the default callback
*/
break;
case CURLOPT_DEBUGDATA:
/*
* Set to a void * that should receive all error writes. This
* defaults to CURLOPT_STDERR for normal operations.
*/
data->set.debugdata = va_arg(param, void *);
break;
case CURLOPT_STDERR:
/*
* Set to a FILE * that should receive all error writes. This
* defaults to stderr for normal operations.
*/
data->set.err = va_arg(param, FILE *);
if(!data->set.err)
data->set.err = stderr;
break;
case CURLOPT_HEADERFUNCTION:
/*
* Set header write callback
*/
data->set.fwrite_header = va_arg(param, curl_write_callback);
break;
case CURLOPT_WRITEFUNCTION:
/*
* Set data write callback
*/
data->set.fwrite_func = va_arg(param, curl_write_callback);
if(!data->set.fwrite_func) {
data->set.is_fwrite_set = 0;
/* When set to NULL, reset to our internal default function */
data->set.fwrite_func = (curl_write_callback)fwrite;
}
else
data->set.is_fwrite_set = 1;
break;
case CURLOPT_READFUNCTION:
/*
* Read data callback
*/
data->set.fread_func = va_arg(param, curl_read_callback);
if(!data->set.fread_func) {
data->set.is_fread_set = 0;
/* When set to NULL, reset to our internal default function */
data->set.fread_func = (curl_read_callback)fread;
}
else
data->set.is_fread_set = 1;
break;
case CURLOPT_SEEKFUNCTION:
/*
* Seek callback. Might be NULL.
*/
data->set.seek_func = va_arg(param, curl_seek_callback);
break;
case CURLOPT_SEEKDATA:
/*
* Seek control callback. Might be NULL.
*/
data->set.seek_client = va_arg(param, void *);
break;
case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
/*
* "Convert from network encoding" callback
*/
data->set.convfromnetwork = va_arg(param, curl_conv_callback);
break;
case CURLOPT_CONV_TO_NETWORK_FUNCTION:
/*
* "Convert to network encoding" callback
*/
data->set.convtonetwork = va_arg(param, curl_conv_callback);
break;
case CURLOPT_CONV_FROM_UTF8_FUNCTION:
/*
* "Convert from UTF-8 encoding" callback
*/
data->set.convfromutf8 = va_arg(param, curl_conv_callback);
break;
case CURLOPT_IOCTLFUNCTION:
/*
* I/O control callback. Might be NULL.
*/
data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
break;
case CURLOPT_IOCTLDATA:
/*
* I/O control data pointer. Might be NULL.
*/
data->set.ioctl_client = va_arg(param, void *);
break;
case CURLOPT_SSLCERT:
/*
* String that holds file name of the SSL certificate to use
*/
result = setstropt(&data->set.str[STRING_CERT],
va_arg(param, char *));
break;
case CURLOPT_SSLCERTTYPE:
/*
* String that holds file type of the SSL certificate to use
*/
result = setstropt(&data->set.str[STRING_CERT_TYPE],
va_arg(param, char *));
break;
case CURLOPT_SSLKEY:
/*
* String that holds file name of the SSL key to use
*/
result = setstropt(&data->set.str[STRING_KEY],
va_arg(param, char *));
break;
case CURLOPT_SSLKEYTYPE:
/*
* String that holds file type of the SSL key to use
*/
result = setstropt(&data->set.str[STRING_KEY_TYPE],
va_arg(param, char *));
break;
case CURLOPT_KEYPASSWD:
/*
* String that holds the SSL or SSH private key password.
*/
result = setstropt(&data->set.str[STRING_KEY_PASSWD],
va_arg(param, char *));
break;
case CURLOPT_SSLENGINE:
/*
* String that holds the SSL crypto engine.
*/
argptr = va_arg(param, char *);
if(argptr && argptr[0])
result = Curl_ssl_set_engine(data, argptr);
break;
case CURLOPT_SSLENGINE_DEFAULT:
/*
* flag to set engine as default.
*/
result = Curl_ssl_set_engine_default(data);
break;
case CURLOPT_CRLF:
/*
* Kludgy option to enable CRLF conversions. Subject for removal.
*/
data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_INTERFACE:
/*
* Set what interface or address/hostname to bind the socket to when
* performing an operation and thus what from-IP your connection will use.
*/
result = setstropt(&data->set.str[STRING_DEVICE],
va_arg(param, char *));
break;
case CURLOPT_LOCALPORT:
/*
* Set what local port to bind the socket to when performing an operation.
*/
data->set.localport = curlx_sltous(va_arg(param, long));
break;
case CURLOPT_LOCALPORTRANGE:
/*
* Set number of local ports to try, starting with CURLOPT_LOCALPORT.
*/
data->set.localportrange = curlx_sltosi(va_arg(param, long));
break;
case CURLOPT_KRBLEVEL:
/*
* A string that defines the kerberos security level.
*/
result = setstropt(&data->set.str[STRING_KRB_LEVEL],
va_arg(param, char *));
data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE;
break;
case CURLOPT_GSSAPI_DELEGATION:
/*
* GSSAPI credential delegation
*/
data->set.gssapi_delegation = va_arg(param, long);
break;
case CURLOPT_SSL_VERIFYPEER:
/*
* Enable peer SSL verifying.
*/
data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_SSL_VERIFYHOST:
/*
* Enable verification of the host name in the peer certificate
*/
arg = va_arg(param, long);
/* Obviously people are not reading documentation and too many thought
this argument took a boolean when it wasn't and misused it. We thus ban
1 as a sensible input and we warn about its use. Then we only have the
2 action internally stored as TRUE. */
if(1 == arg) {
failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE;
break;
#ifdef USE_SSLEAY
/* since these two options are only possible to use on an OpenSSL-
powered libcurl we #ifdef them on this condition so that libcurls
built against other SSL libs will return a proper error when trying
to set this option! */
case CURLOPT_SSL_CTX_FUNCTION:
/*
* Set a SSL_CTX callback
*/
data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
break;
case CURLOPT_SSL_CTX_DATA:
/*
* Set a SSL_CTX callback parameter pointer
*/
data->set.ssl.fsslctxp = va_arg(param, void *);
break;
#endif
#if defined(USE_SSLEAY) || defined(USE_QSOSSL) || defined(USE_GSKIT) || \
defined(USE_NSS)
case CURLOPT_CERTINFO:
data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE;
break;
#endif
case CURLOPT_CAINFO:
/*
* Set CA info for SSL connection. Specify file name of the CA certificate
*/
result = setstropt(&data->set.str[STRING_SSL_CAFILE],
va_arg(param, char *));
break;
case CURLOPT_CAPATH:
/*
* Set CA path info for SSL connection. Specify directory name of the CA
* certificates which have been prepared using openssl c_rehash utility.
*/
/* This does not work on windows. */
result = setstropt(&data->set.str[STRING_SSL_CAPATH],
va_arg(param, char *));
break;
case CURLOPT_CRLFILE:
/*
* Set CRL file info for SSL connection. Specify file name of the CRL
* to check certificates revocation
*/
result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
va_arg(param, char *));
break;
case CURLOPT_ISSUERCERT:
/*
* Set Issuer certificate file
* to check certificates issuer
*/
result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
va_arg(param, char *));
break;
case CURLOPT_TELNETOPTIONS:
/*
* Set a linked list of telnet options
*/
data->set.telnet_options = va_arg(param, struct curl_slist *);
break;
case CURLOPT_BUFFERSIZE:
/*
* The application kindly asks for a differently sized receive buffer.
* If it seems reasonable, we'll use it.
*/
data->set.buffer_size = va_arg(param, long);
if((data->set.buffer_size> (BUFSIZE -1 )) ||
(data->set.buffer_size < 1))
data->set.buffer_size = 0; /* huge internal default */
break;
case CURLOPT_NOSIGNAL:
/*
* The application asks not to set any signal() or alarm() handlers,
* even when using a timeout.
*/
data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_SHARE:
{
struct Curl_share *set;
set = va_arg(param, struct Curl_share *);
/* disconnect from old share, if any */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
if(data->dns.hostcachetype == HCACHE_SHARED) {
data->dns.hostcache = NULL;
data->dns.hostcachetype = HCACHE_NONE;
}
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
if(data->share->cookies == data->cookies)
data->cookies = NULL;
#endif
if(data->share->sslsession == data->state.session)
data->state.session = NULL;
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
data->share = NULL;
}
/* use new share if it set */
data->share = set;
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty++;
if(data->share->hostcache) {
/* use shared host cache */
data->dns.hostcache = data->share->hostcache;
data->dns.hostcachetype = HCACHE_SHARED;
}
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
if(data->share->cookies) {
/* use shared cookie list, first free own one if any */
if(data->cookies)
Curl_cookie_cleanup(data->cookies);
/* enable cookies since we now use a share that uses cookies! */
data->cookies = data->share->cookies;
}
#endif /* CURL_DISABLE_HTTP */
if(data->share->sslsession) {
data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions;
data->state.session = data->share->sslsession;
}
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
/* check for host cache not needed,
* it will be done by curl_easy_perform */
}
break;
case CURLOPT_PRIVATE:
/*
* Set private data pointer.
*/
data->set.private_data = va_arg(param, void *);
break;
case CURLOPT_MAXFILESIZE:
/*
* Set the maximum size of a file to download.
*/
data->set.max_filesize = va_arg(param, long);
break;
#ifdef USE_SSL
case CURLOPT_USE_SSL:
/*
* Make transfers attempt to use SSL/TLS.
*/
data->set.use_ssl = (curl_usessl)va_arg(param, long);
break;
case CURLOPT_SSL_OPTIONS:
arg = va_arg(param, long);
data->set.ssl_enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE;
break;
#endif
case CURLOPT_FTPSSLAUTH:
/*
* Set a specific auth for FTP-SSL transfers.
*/
data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
break;
case CURLOPT_IPRESOLVE:
data->set.ipver = va_arg(param, long);
break;
case CURLOPT_MAXFILESIZE_LARGE:
/*
* Set the maximum size of a file to download.
*/
data->set.max_filesize = va_arg(param, curl_off_t);
break;
case CURLOPT_TCP_NODELAY:
/*
* Enable or disable TCP_NODELAY, which will disable/enable the Nagle
* algorithm
*/
data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_ACCOUNT:
result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
va_arg(param, char *));
break;
case CURLOPT_IGNORE_CONTENT_LENGTH:
data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_CONNECT_ONLY:
/*
* No data transfer, set up connection and let application use the socket
*/
data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_FTP_ALTERNATIVE_TO_USER:
result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
va_arg(param, char *));
break;
case CURLOPT_SOCKOPTFUNCTION:
/*
* socket callback function: called after socket() but before connect()
*/
data->set.fsockopt = va_arg(param, curl_sockopt_callback);
break;
case CURLOPT_SOCKOPTDATA:
/*
* socket callback data pointer. Might be NULL.
*/
data->set.sockopt_client = va_arg(param, void *);
break;
case CURLOPT_OPENSOCKETFUNCTION:
/*
* open/create socket callback function: called instead of socket(),
* before connect()
*/
data->set.fopensocket = va_arg(param, curl_opensocket_callback);
break;
case CURLOPT_OPENSOCKETDATA:
/*
* socket callback data pointer. Might be NULL.
*/
data->set.opensocket_client = va_arg(param, void *);
break;
case CURLOPT_CLOSESOCKETFUNCTION:
/*
* close socket callback function: called instead of close()
* when shutting down a connection
*/
data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
break;
case CURLOPT_CLOSESOCKETDATA:
/*
* socket callback data pointer. Might be NULL.
*/
data->set.closesocket_client = va_arg(param, void *);
break;
case CURLOPT_SSL_SESSIONID_CACHE:
data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE;
break;
#ifdef USE_LIBSSH2
/* we only include SSH options if explicitly built to support SSH */
case CURLOPT_SSH_AUTH_TYPES:
data->set.ssh_auth_types = va_arg(param, long);
break;
case CURLOPT_SSH_PUBLIC_KEYFILE:
/*
* Use this file instead of the $HOME/.ssh/id_dsa.pub file
*/
result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
va_arg(param, char *));
break;
case CURLOPT_SSH_PRIVATE_KEYFILE:
/*
* Use this file instead of the $HOME/.ssh/id_dsa file
*/
result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
va_arg(param, char *));
break;
case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
/*
* Option to allow for the MD5 of the host public key to be checked
* for validation purposes.
*/
result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
va_arg(param, char *));
break;
#ifdef HAVE_LIBSSH2_KNOWNHOST_API
case CURLOPT_SSH_KNOWNHOSTS:
/*
* Store the file name to read known hosts from.
*/
result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
va_arg(param, char *));
break;
case CURLOPT_SSH_KEYFUNCTION:
/* setting to NULL is fine since the ssh.c functions themselves will
then rever to use the internal default */
data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
break;
case CURLOPT_SSH_KEYDATA:
/*
* Custom client data to pass to the SSH keyfunc callback
*/
data->set.ssh_keyfunc_userp = va_arg(param, void *);
break;
#endif /* HAVE_LIBSSH2_KNOWNHOST_API */
#endif /* USE_LIBSSH2 */
case CURLOPT_HTTP_TRANSFER_DECODING:
/*
* disable libcurl transfer encoding is used
*/
data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_HTTP_CONTENT_DECODING:
/*
* raw data passed to the application when content encoding is used
*/
data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_NEW_FILE_PERMS:
/*
* Uses these permissions instead of 0644
*/
data->set.new_file_perms = va_arg(param, long);
break;
case CURLOPT_NEW_DIRECTORY_PERMS:
/*
* Uses these permissions instead of 0755
*/
data->set.new_directory_perms = va_arg(param, long);
break;
case CURLOPT_ADDRESS_SCOPE:
/*
* We always get longs when passed plain numericals, but for this value we
* know that an unsigned int will always hold the value so we blindly
* typecast to this type
*/
data->set.scope = curlx_sltoui(va_arg(param, long));
break;
case CURLOPT_PROTOCOLS:
/* set the bitmask for the protocols that are allowed to be used for the
transfer, which thus helps the app which takes URLs from users or other
external inputs and want to restrict what protocol(s) to deal
with. Defaults to CURLPROTO_ALL. */
data->set.allowed_protocols = va_arg(param, long);
break;
case CURLOPT_REDIR_PROTOCOLS:
/* set the bitmask for the protocols that libcurl is allowed to follow to,
as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
to be set in both bitmasks to be allowed to get redirected to. Defaults
to all protocols except FILE and SCP. */
data->set.redir_protocols = va_arg(param, long);
break;
case CURLOPT_MAIL_FROM:
/* Set the SMTP mail originator */
result = setstropt(&data->set.str[STRING_MAIL_FROM],
va_arg(param, char *));
break;
case CURLOPT_MAIL_AUTH:
/* Set the SMTP auth originator */
result = setstropt(&data->set.str[STRING_MAIL_AUTH],
va_arg(param, char *));
break;
case CURLOPT_MAIL_RCPT:
/* Set the list of mail recipients */
data->set.mail_rcpt = va_arg(param, struct curl_slist *);
break;
case CURLOPT_SASL_IR:
/* Enable/disable SASL initial response */
data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
break;
case CURLOPT_RTSP_REQUEST:
{
/*
* Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
* Would this be better if the RTSPREQ_* were just moved into here?
*/
long curl_rtspreq = va_arg(param, long);
Curl_RtspReq rtspreq = RTSPREQ_NONE;
switch(curl_rtspreq) {
case CURL_RTSPREQ_OPTIONS:
rtspreq = RTSPREQ_OPTIONS;
break;
case CURL_RTSPREQ_DESCRIBE:
rtspreq = RTSPREQ_DESCRIBE;
break;
case CURL_RTSPREQ_ANNOUNCE:
rtspreq = RTSPREQ_ANNOUNCE;
break;
case CURL_RTSPREQ_SETUP:
rtspreq = RTSPREQ_SETUP;
break;
case CURL_RTSPREQ_PLAY:
rtspreq = RTSPREQ_PLAY;
break;
case CURL_RTSPREQ_PAUSE:
rtspreq = RTSPREQ_PAUSE;
break;
case CURL_RTSPREQ_TEARDOWN:
rtspreq = RTSPREQ_TEARDOWN;
break;
case CURL_RTSPREQ_GET_PARAMETER:
rtspreq = RTSPREQ_GET_PARAMETER;
break;
case CURL_RTSPREQ_SET_PARAMETER:
rtspreq = RTSPREQ_SET_PARAMETER;
break;
case CURL_RTSPREQ_RECORD:
rtspreq = RTSPREQ_RECORD;
break;
case CURL_RTSPREQ_RECEIVE:
rtspreq = RTSPREQ_RECEIVE;
break;
default:
rtspreq = RTSPREQ_NONE;
}
data->set.rtspreq = rtspreq;
break;
}
case CURLOPT_RTSP_SESSION_ID:
/*
* Set the RTSP Session ID manually. Useful if the application is
* resuming a previously established RTSP session
*/
result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
va_arg(param, char *));
break;
case CURLOPT_RTSP_STREAM_URI:
/*
* Set the Stream URI for the RTSP request. Unless the request is
* for generic server options, the application will need to set this.
*/
result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
va_arg(param, char *));
break;
case CURLOPT_RTSP_TRANSPORT:
/*
* The content of the Transport: header for the RTSP request
*/
result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
va_arg(param, char *));
break;
case CURLOPT_RTSP_CLIENT_CSEQ:
/*
* Set the CSEQ number to issue for the next RTSP request. Useful if the
* application is resuming a previously broken connection. The CSEQ
* will increment from this new number henceforth.
*/
data->state.rtsp_next_client_CSeq = va_arg(param, long);
break;
case CURLOPT_RTSP_SERVER_CSEQ:
/* Same as the above, but for server-initiated requests */
data->state.rtsp_next_client_CSeq = va_arg(param, long);
break;
case CURLOPT_INTERLEAVEDATA:
data->set.rtp_out = va_arg(param, void *);
break;
case CURLOPT_INTERLEAVEFUNCTION:
/* Set the user defined RTP write function */
data->set.fwrite_rtp = va_arg(param, curl_write_callback);
break;
case CURLOPT_WILDCARDMATCH:
data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_CHUNK_BGN_FUNCTION:
data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
break;
case CURLOPT_CHUNK_END_FUNCTION:
data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
break;
case CURLOPT_FNMATCH_FUNCTION:
data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
break;
case CURLOPT_CHUNK_DATA:
data->wildcard.customptr = va_arg(param, void *);
break;
case CURLOPT_FNMATCH_DATA:
data->set.fnmatch_data = va_arg(param, void *);
break;
#ifdef USE_TLS_SRP
case CURLOPT_TLSAUTH_USERNAME:
result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
va_arg(param, char *));
if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
break;
case CURLOPT_TLSAUTH_PASSWORD:
result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
va_arg(param, char *));
if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
break;
case CURLOPT_TLSAUTH_TYPE:
if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
data->set.ssl.authtype = CURL_TLSAUTH_SRP;
else
data->set.ssl.authtype = CURL_TLSAUTH_NONE;
break;
#endif
case CURLOPT_DNS_SERVERS:
result = Curl_set_dns_servers(data, va_arg(param, char *));
break;
case CURLOPT_DNS_INTERFACE:
result = Curl_set_dns_interface(data, va_arg(param, char *));
break;
case CURLOPT_DNS_LOCAL_IP4:
result = Curl_set_dns_local_ip4(data, va_arg(param, char *));
break;
case CURLOPT_DNS_LOCAL_IP6:
result = Curl_set_dns_local_ip6(data, va_arg(param, char *));
break;
case CURLOPT_TCP_KEEPALIVE:
data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_TCP_KEEPIDLE:
data->set.tcp_keepidle = va_arg(param, long);
break;
case CURLOPT_TCP_KEEPINTVL:
data->set.tcp_keepintvl = va_arg(param, long);
break;
case CURLOPT_SSL_ENABLE_NPN:
data->set.ssl_enable_npn = (0 != va_arg(param, long))?TRUE:FALSE;
break;
case CURLOPT_SSL_ENABLE_ALPN:
data->set.ssl_enable_alpn = (0 != va_arg(param, long))?TRUE:FALSE;
break;
default:
/* unknown tag and its companion, just ignore: */
result = CURLE_UNKNOWN_OPTION;
break;
}
return result;
}
static void conn_free(struct connectdata *conn)
{
if(!conn)
return;
/* possible left-overs from the async name resolvers */
Curl_resolver_cancel(conn);
/* close the SSL stuff before we close any sockets since they will/may
write to the sockets */
Curl_ssl_close(conn, FIRSTSOCKET);
Curl_ssl_close(conn, SECONDARYSOCKET);
/* close possibly still open sockets */
if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
if(CURL_SOCKET_BAD != conn->tempsock[0])
Curl_closesocket(conn, conn->tempsock[0]);
if(CURL_SOCKET_BAD != conn->tempsock[1])
Curl_closesocket(conn, conn->tempsock[1]);
#if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
Curl_ntlm_wb_cleanup(conn);
#endif
Curl_safefree(conn->user);
Curl_safefree(conn->passwd);
Curl_safefree(conn->xoauth2_bearer);
Curl_safefree(conn->options);
Curl_safefree(conn->proxyuser);
Curl_safefree(conn->proxypasswd);
Curl_safefree(conn->allocptr.proxyuserpwd);
Curl_safefree(conn->allocptr.uagent);
Curl_safefree(conn->allocptr.userpwd);
Curl_safefree(conn->allocptr.accept_encoding);
Curl_safefree(conn->allocptr.te);
Curl_safefree(conn->allocptr.rangeline);
Curl_safefree(conn->allocptr.ref);
Curl_safefree(conn->allocptr.host);
Curl_safefree(conn->allocptr.cookiehost);
Curl_safefree(conn->allocptr.rtsp_transport);
Curl_safefree(conn->trailer);
Curl_safefree(conn->host.rawalloc); /* host name buffer */
Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
Curl_safefree(conn->master_buffer);
Curl_llist_destroy(conn->send_pipe, NULL);
Curl_llist_destroy(conn->recv_pipe, NULL);
conn->send_pipe = NULL;
conn->recv_pipe = NULL;
Curl_safefree(conn->localdev);
Curl_free_ssl_config(&conn->ssl_config);
free(conn); /* free all the connection oriented data */
}
CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
{
struct SessionHandle *data;
if(!conn)
return CURLE_OK; /* this is closed and fine already */
data = conn->data;
if(!data) {
DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
return CURLE_OK;
}
if(conn->dns_entry != NULL) {
Curl_resolv_unlock(data, conn->dns_entry);
conn->dns_entry = NULL;
}
Curl_hostcache_prune(data); /* kill old DNS cache entries */
{
int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
/* Authentication data is a mix of connection-related and sessionhandle-
related stuff. NTLM is connection-related so when we close the shop
we shall forget. */
if(has_host_ntlm) {
data->state.authhost.done = FALSE;
data->state.authhost.picked =
data->state.authhost.want;
}
if(has_proxy_ntlm) {
data->state.authproxy.done = FALSE;
data->state.authproxy.picked =
data->state.authproxy.want;
}
if(has_host_ntlm || has_proxy_ntlm)
data->state.authproblem = FALSE;
}
/* Cleanup NTLM connection-related data */
Curl_http_ntlm_cleanup(conn);
/* Cleanup possible redirect junk */
if(data->req.newurl) {
free(data->req.newurl);
data->req.newurl = NULL;
}
if(conn->handler->disconnect)
/* This is set if protocol-specific cleanups should be made */
conn->handler->disconnect(conn, dead_connection);
/* unlink ourselves! */
infof(data, "Closing connection %ld\n", conn->connection_id);
Curl_conncache_remove_conn(data->state.conn_cache, conn);
#if defined(USE_LIBIDN)
if(conn->host.encalloc)
idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
with idn_free() since this was allocated
by libidn */
if(conn->proxy.encalloc)
idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
freed with idn_free() since this was
allocated by libidn */
#elif defined(USE_WIN32_IDN)
free(conn->host.encalloc); /* encoded host name buffer, must be freed with
idn_free() since this was allocated by
curl_win32_idn_to_ascii */
if(conn->proxy.encalloc)
free(conn->proxy.encalloc); /* encoded proxy name buffer, must be freed
with idn_free() since this was allocated by
curl_win32_idn_to_ascii */
#endif
Curl_ssl_close(conn, FIRSTSOCKET);
/* Indicate to all handles on the pipe that we're dead */
if(Curl_multi_pipeline_enabled(data->multi)) {
signalPipeClose(conn->send_pipe, TRUE);
signalPipeClose(conn->recv_pipe, TRUE);
}
conn_free(conn);
Curl_speedinit(data);
return CURLE_OK;
}
/*
* This function should return TRUE if the socket is to be assumed to
* be dead. Most commonly this happens when the server has closed the
* connection due to inactivity.
*/
static bool SocketIsDead(curl_socket_t sock)
{
int sval;
bool ret_val = TRUE;
sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
if(sval == 0)
/* timeout */
ret_val = FALSE;
return ret_val;
}
static bool IsPipeliningPossible(const struct SessionHandle *handle,
const struct connectdata *conn)
{
if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
Curl_multi_pipeline_enabled(handle->multi) &&
(handle->set.httpreq == HTTPREQ_GET ||
handle->set.httpreq == HTTPREQ_HEAD) &&
handle->set.httpversion != CURL_HTTP_VERSION_1_0)
return TRUE;
return FALSE;
}
bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
{
return Curl_multi_pipeline_enabled(handle->multi);
}
CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
struct curl_llist *pipeline)
{
if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
struct curl_llist *pipeline)
{
struct curl_llist_element *curr;
curr = pipeline->head;
while(curr) {
if(curr->ptr == handle) {
Curl_llist_remove(pipeline, curr, NULL);
return 1; /* we removed a handle */
}
curr = curr->next;
}
return 0;
}
#if 0 /* this code is saved here as it is useful for debugging purposes */
static void Curl_printPipeline(struct curl_llist *pipeline)
{
struct curl_llist_element *curr;
curr = pipeline->head;
while(curr) {
struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
infof(data, "Handle in pipeline: %s\n", data->state.path);
curr = curr->next;
}
}
#endif
static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
{
struct curl_llist_element *curr = pipeline->head;
if(curr) {
return (struct SessionHandle *) curr->ptr;
}
return NULL;
}
/* remove the specified connection from all (possible) pipelines and related
queues */
void Curl_getoff_all_pipelines(struct SessionHandle *data,
struct connectdata *conn)
{
bool recv_head = (conn->readchannel_inuse &&
(gethandleathead(conn->recv_pipe) == data)) ? TRUE : FALSE;
bool send_head = (conn->writechannel_inuse &&
(gethandleathead(conn->send_pipe) == data)) ? TRUE : FALSE;
if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
conn->readchannel_inuse = FALSE;
if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
conn->writechannel_inuse = FALSE;
}
static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
{
struct curl_llist_element *curr;
if(!pipeline)
return;
curr = pipeline->head;
while(curr) {
struct curl_llist_element *next = curr->next;
struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
#ifdef DEBUGBUILD /* debug-only code */
if(data->magic != CURLEASY_MAGIC_NUMBER) {
/* MAJOR BADNESS */
infof(data, "signalPipeClose() found BAAD easy handle\n");
}
#endif
if(pipe_broke)
data->state.pipe_broke = TRUE;
Curl_multi_handlePipeBreak(data);
Curl_llist_remove(pipeline, curr, NULL);
curr = next;
}
}
/*
* This function finds the connection in the connection
* cache that has been unused for the longest time.
*
* Returns the pointer to the oldest idle connection, or NULL if none was
* found.
*/
static struct connectdata *
find_oldest_idle_connection(struct SessionHandle *data)
{
struct conncache *bc = data->state.conn_cache;
struct curl_hash_iterator iter;
struct curl_llist_element *curr;
struct curl_hash_element *he;
long highscore=-1;
long score;
struct timeval now;
struct connectdata *conn_candidate = NULL;
struct connectbundle *bundle;
now = Curl_tvnow();
Curl_hash_start_iterate(bc->hash, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
struct connectdata *conn;
bundle = he->ptr;
curr = bundle->conn_list->head;
while(curr) {
conn = curr->ptr;
if(!conn->inuse) {
/* Set higher score for the age passed since the connection was used */
score = Curl_tvdiff(now, conn->now);
if(score > highscore) {
highscore = score;
conn_candidate = conn;
}
}
curr = curr->next;
}
he = Curl_hash_next_element(&iter);
}
return conn_candidate;
}
/*
* This function finds the connection in the connection
* bundle that has been unused for the longest time.
*
* Returns the pointer to the oldest idle connection, or NULL if none was
* found.
*/
static struct connectdata *
find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
struct connectbundle *bundle)
{
struct curl_llist_element *curr;
long highscore=-1;
long score;
struct timeval now;
struct connectdata *conn_candidate = NULL;
struct connectdata *conn;
(void)data;
now = Curl_tvnow();
curr = bundle->conn_list->head;
while(curr) {
conn = curr->ptr;
if(!conn->inuse) {
/* Set higher score for the age passed since the connection was used */
score = Curl_tvdiff(now, conn->now);
if(score > highscore) {
highscore = score;
conn_candidate = conn;
}
}
curr = curr->next;
}
return conn_candidate;
}
/*
* Given one filled in connection struct (named needle), this function should
* detect if there already is one that has all the significant details
* exactly the same and thus should be used instead.
*
* If there is a match, this function returns TRUE - and has marked the
* connection as 'in-use'. It must later be called with ConnectionDone() to
* return back to 'idle' (unused) state.
*
* The force_reuse flag is set if the connection must be used, even if
* the pipelining strategy wants to open a new connection instead of reusing.
*/
static bool
ConnectionExists(struct SessionHandle *data,
struct connectdata *needle,
struct connectdata **usethis,
bool *force_reuse)
{
struct connectdata *check;
struct connectdata *chosen = 0;
bool canPipeline = IsPipeliningPossible(data, needle);
bool wantNTLMhttp = ((data->state.authhost.want & CURLAUTH_NTLM) ||
(data->state.authhost.want & CURLAUTH_NTLM_WB)) &&
(needle->handler->protocol & PROTO_FAMILY_HTTP) ? TRUE : FALSE;
struct connectbundle *bundle;
*force_reuse = FALSE;
/* We can't pipe if the site is blacklisted */
if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
canPipeline = FALSE;
}
/* Look up the bundle with all the connections to this
particular host */
bundle = Curl_conncache_find_bundle(data->state.conn_cache,
needle->host.name);
if(bundle) {
size_t max_pipe_len = Curl_multi_max_pipeline_length(data->multi);
size_t best_pipe_len = max_pipe_len;
struct curl_llist_element *curr;
infof(data, "Found bundle for host %s: %p\n",
needle->host.name, (void *)bundle);
/* We can't pipe if we don't know anything about the server */
if(canPipeline && !bundle->server_supports_pipelining) {
infof(data, "Server doesn't support pipelining\n");
canPipeline = FALSE;
}
curr = bundle->conn_list->head;
while(curr) {
bool match = FALSE;
bool credentialsMatch = FALSE;
size_t pipeLen;
/*
* Note that if we use a HTTP proxy, we check connections to that
* proxy and not to the actual remote server.
*/
check = curr->ptr;
curr = curr->next;
pipeLen = check->send_pipe->size + check->recv_pipe->size;
if(!pipeLen && !check->inuse) {
/* The check for a dead socket makes sense only if there are no
handles in pipeline and the connection isn't already marked in
use */
bool dead;
if(check->handler->protocol & CURLPROTO_RTSP)
/* RTSP is a special case due to RTP interleaving */
dead = Curl_rtsp_connisdead(check);
else
dead = SocketIsDead(check->sock[FIRSTSOCKET]);
if(dead) {
check->data = data;
infof(data, "Connection %ld seems to be dead!\n",
check->connection_id);
/* disconnect resources */
Curl_disconnect(check, /* dead_connection */ TRUE);
continue;
}
}
if(canPipeline) {
/* Make sure the pipe has only GET requests */
struct SessionHandle* sh = gethandleathead(check->send_pipe);
struct SessionHandle* rh = gethandleathead(check->recv_pipe);
if(sh) {
if(!IsPipeliningPossible(sh, check))
continue;
}
else if(rh) {
if(!IsPipeliningPossible(rh, check))
continue;
}
}
else {
if(pipeLen > 0) {
/* can only happen within multi handles, and means that another easy
handle is using this connection */
continue;
}
if(Curl_resolver_asynch()) {
/* ip_addr_str[0] is NUL only if the resolving of the name hasn't
completed yet and until then we don't re-use this connection */
if(!check->ip_addr_str[0]) {
infof(data,
"Connection #%ld is still name resolving, can't reuse\n",
check->connection_id);
continue;
}
}
if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
check->bits.close) {
/* Don't pick a connection that hasn't connected yet or that is going
to get closed. */
infof(data, "Connection #%ld isn't open enough, can't reuse\n",
check->connection_id);
#ifdef DEBUGBUILD
if(check->recv_pipe->size > 0) {
infof(data,
"BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
check->connection_id);
}
#endif
continue;
}
}
if((needle->handler->flags&PROTOPT_SSL) !=
(check->handler->flags&PROTOPT_SSL))
/* don't do mixed SSL and non-SSL connections */
if(!(needle->handler->protocol & check->handler->protocol))
/* except protocols that have been upgraded via TLS */
continue;
if(needle->handler->flags&PROTOPT_SSL) {
if((data->set.ssl.verifypeer != check->verifypeer) ||
(data->set.ssl.verifyhost != check->verifyhost))
continue;
}
if(needle->bits.proxy != check->bits.proxy)
/* don't do mixed proxy and non-proxy connections */
continue;
if(!canPipeline && check->inuse)
/* this request can't be pipelined but the checked connection is
already in use so we skip it */
continue;
if(needle->localdev || needle->localport) {
/* If we are bound to a specific local end (IP+port), we must not
re-use a random other one, although if we didn't ask for a
particular one we can reuse one that was bound.
This comparison is a bit rough and too strict. Since the input
parameters can be specified in numerous ways and still end up the
same it would take a lot of processing to make it really accurate.
Instead, this matching will assume that re-uses of bound connections
will most likely also re-use the exact same binding parameters and
missing out a few edge cases shouldn't hurt anyone very much.
*/
if((check->localport != needle->localport) ||
(check->localportrange != needle->localportrange) ||
!check->localdev ||
!needle->localdev ||
strcmp(check->localdev, needle->localdev))
continue;
}
if((!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) ||
wantNTLMhttp) {
/* This protocol requires credentials per connection or is HTTP+NTLM,
so verify that we're using the same name and password as well */
if(!strequal(needle->user, check->user) ||
!strequal(needle->passwd, check->passwd)) {
/* one of them was different */
continue;
}
credentialsMatch = TRUE;
}
if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
(needle->bits.httpproxy && check->bits.httpproxy &&
needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
(needle->port == check->port))) {
/* The requested connection does not use a HTTP proxy or it uses SSL or
it is a non-SSL protocol tunneled over the same http proxy name and
port number or it is a non-SSL protocol which is allowed to be
upgraded via TLS */
if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
needle->handler->protocol & check->handler->protocol) &&
Curl_raw_equal(needle->host.name, check->host.name) &&
needle->remote_port == check->remote_port) {
if(needle->handler->flags & PROTOPT_SSL) {
/* This is a SSL connection so verify that we're using the same
SSL options as well */
if(!Curl_ssl_config_matches(&needle->ssl_config,
&check->ssl_config)) {
DEBUGF(infof(data,
"Connection #%ld has different SSL parameters, "
"can't reuse\n",
check->connection_id));
continue;
}
else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
DEBUGF(infof(data,
"Connection #%ld has not started SSL connect, "
"can't reuse\n",
check->connection_id));
continue;
}
}
match = TRUE;
}
}
else { /* The requested needle connection is using a proxy,
is the checked one using the same host, port and type? */
if(check->bits.proxy &&
(needle->proxytype == check->proxytype) &&
(needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
needle->port == check->port) {
/* This is the same proxy connection, use it! */
match = TRUE;
}
}
if(match) {
/* If we are looking for an HTTP+NTLM connection, check if this is
already authenticating with the right credentials. If not, keep
looking so that we can reuse NTLM connections if
possible. (Especially we must not reuse the same connection if
partway through a handshake!) */
if(wantNTLMhttp) {
if(credentialsMatch && check->ntlm.state != NTLMSTATE_NONE) {
chosen = check;
/* We must use this connection, no other */
*force_reuse = TRUE;
break;
}
else if(credentialsMatch)
/* this is a backup choice */
chosen = check;
continue;
}
if(canPipeline) {
/* We can pipeline if we want to. Let's continue looking for
the optimal connection to use, i.e the shortest pipe that is not
blacklisted. */
if(pipeLen == 0) {
/* We have the optimal connection. Let's stop looking. */
chosen = check;
break;
}
/* We can't use the connection if the pipe is full */
if(pipeLen >= max_pipe_len)
continue;
/* We can't use the connection if the pipe is penalized */
if(Curl_pipeline_penalized(data, check))
continue;
if(pipeLen < best_pipe_len) {
/* This connection has a shorter pipe so far. We'll pick this
and continue searching */
chosen = check;
best_pipe_len = pipeLen;
continue;
}
}
else {
/* We have found a connection. Let's stop searching. */
chosen = check;
break;
}
}
}
}
if(chosen) {
*usethis = chosen;
return TRUE; /* yes, we found one to use! */
}
return FALSE; /* no matching connecting exists */
}
/* Mark the connection as 'idle', or close it if the cache is full.
Returns TRUE if the connection is kept, or FALSE if it was closed. */
static bool
ConnectionDone(struct SessionHandle *data, struct connectdata *conn)
{
/* data->multi->maxconnects can be negative, deal with it. */
size_t maxconnects =
(data->multi->maxconnects < 0) ? data->multi->num_easy * 4:
data->multi->maxconnects;
struct connectdata *conn_candidate = NULL;
/* Mark the current connection as 'unused' */
conn->inuse = FALSE;
if(maxconnects > 0 &&
data->state.conn_cache->num_connections > maxconnects) {
infof(data, "Connection cache is full, closing the oldest one.\n");
conn_candidate = find_oldest_idle_connection(data);
if(conn_candidate) {
/* Set the connection's owner correctly */
conn_candidate->data = data;
/* the winner gets the honour of being disconnected */
(void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
}
}
return (conn_candidate == conn) ? FALSE : TRUE;
}
/*
* The given input connection struct pointer is to be stored in the connection
* cache. If the cache is already full, least interesting existing connection
* (if any) gets closed.
*
* The given connection should be unique. That must've been checked prior to
* this call.
*/
static CURLcode ConnectionStore(struct SessionHandle *data,
struct connectdata *conn)
{
static int connection_id_counter = 0;
CURLcode result;
/* Assign a number to the connection for easier tracking in the log
output */
conn->connection_id = connection_id_counter++;
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result != CURLE_OK)
conn->connection_id = -1;
return result;
}
/* after a TCP connection to the proxy has been verified, this function does
the next magic step.
Note: this function's sub-functions call failf()
*/
CURLcode Curl_connected_proxy(struct connectdata *conn,
int sockindex)
{
if(!conn->bits.proxy || sockindex)
/* this magic only works for the primary socket as the secondary is used
for FTP only and it has FTP specific magic in ftp.c */
return CURLE_OK;
switch(conn->proxytype) {
#ifndef CURL_DISABLE_PROXY
case CURLPROXY_SOCKS5:
case CURLPROXY_SOCKS5_HOSTNAME:
return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
conn->host.name, conn->remote_port,
FIRSTSOCKET, conn);
case CURLPROXY_SOCKS4:
return Curl_SOCKS4(conn->proxyuser, conn->host.name,
conn->remote_port, FIRSTSOCKET, conn, FALSE);
case CURLPROXY_SOCKS4A:
return Curl_SOCKS4(conn->proxyuser, conn->host.name,
conn->remote_port, FIRSTSOCKET, conn, TRUE);
#endif /* CURL_DISABLE_PROXY */
case CURLPROXY_HTTP:
case CURLPROXY_HTTP_1_0:
/* do nothing here. handled later. */
break;
default:
break;
} /* switch proxytype */
return CURLE_OK;
}
/*
* verboseconnect() displays verbose information after a connect
*/
#ifndef CURL_DISABLE_VERBOSE_STRINGS
void Curl_verboseconnect(struct connectdata *conn)
{
if(conn->data->set.verbose)
infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
conn->ip_addr_str, conn->port, conn->connection_id);
}
#endif
int Curl_protocol_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn->handler->proto_getsock)
return conn->handler->proto_getsock(conn, socks, numsocks);
return GETSOCK_BLANK;
}
int Curl_doing_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn && conn->handler->doing_getsock)
return conn->handler->doing_getsock(conn, socks, numsocks);
return GETSOCK_BLANK;
}
/*
* We are doing protocol-specific connecting and this is being called over and
* over from the multi interface until the connection phase is done on
* protocol layer.
*/
CURLcode Curl_protocol_connecting(struct connectdata *conn,
bool *done)
{
CURLcode result=CURLE_OK;
if(conn && conn->handler->connecting) {
*done = FALSE;
result = conn->handler->connecting(conn, done);
}
else
*done = TRUE;
return result;
}
/*
* We are DOING this is being called over and over from the multi interface
* until the DOING phase is done on protocol layer.
*/
CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
{
CURLcode result=CURLE_OK;
if(conn && conn->handler->doing) {
*done = FALSE;
result = conn->handler->doing(conn, done);
}
else
*done = TRUE;
return result;
}
/*
* We have discovered that the TCP connection has been successful, we can now
* proceed with some action.
*
*/
CURLcode Curl_protocol_connect(struct connectdata *conn,
bool *protocol_done)
{
CURLcode result=CURLE_OK;
*protocol_done = FALSE;
if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
/* We already are connected, get back. This may happen when the connect
worked fine in the first call, like when we connect to a local server
or proxy. Note that we don't know if the protocol is actually done.
Unless this protocol doesn't have any protocol-connect callback, as
then we know we're done. */
if(!conn->handler->connecting)
*protocol_done = TRUE;
return CURLE_OK;
}
if(!conn->bits.protoconnstart) {
result = Curl_proxy_connect(conn);
if(result)
return result;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
(conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
/* when using an HTTP tunnel proxy, await complete tunnel establishment
before proceeding further. Return CURLE_OK so we'll be called again */
return CURLE_OK;
if(conn->handler->connect_it) {
/* is there a protocol-specific connect() procedure? */
/* Call the protocol-specific connect function */
result = conn->handler->connect_it(conn, protocol_done);
}
else
*protocol_done = TRUE;
/* it has started, possibly even completed but that knowledge isn't stored
in this bit! */
if(!result)
conn->bits.protoconnstart = TRUE;
}
return result; /* pass back status */
}
/*
* Helpers for IDNA convertions.
*/
static bool is_ASCII_name(const char *hostname)
{
const unsigned char *ch = (const unsigned char*)hostname;
while(*ch) {
if(*ch++ & 0x80)
return FALSE;
}
return TRUE;
}
#ifdef USE_LIBIDN
/*
* Check if characters in hostname is allowed in Top Level Domain.
*/
static bool tld_check_name(struct SessionHandle *data,
const char *ace_hostname)
{
size_t err_pos;
char *uc_name = NULL;
int rc;
#ifndef CURL_DISABLE_VERBOSE_STRINGS
const char *tld_errmsg = "<no msg>";
#else
(void)data;
#endif
/* Convert (and downcase) ACE-name back into locale's character set */
rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
if(rc != IDNA_SUCCESS)
return FALSE;
rc = tld_check_lz(uc_name, &err_pos, NULL);
#ifndef CURL_DISABLE_VERBOSE_STRINGS
#ifdef HAVE_TLD_STRERROR
if(rc != TLD_SUCCESS)
tld_errmsg = tld_strerror((Tld_rc)rc);
#endif
if(rc == TLD_INVALID)
infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
tld_errmsg, err_pos, uc_name[err_pos],
uc_name[err_pos] & 255);
else if(rc != TLD_SUCCESS)
infof(data, "WARNING: TLD check for %s failed; %s\n",
uc_name, tld_errmsg);
#endif /* CURL_DISABLE_VERBOSE_STRINGS */
if(uc_name)
idn_free(uc_name);
if(rc != TLD_SUCCESS)
return FALSE;
return TRUE;
}
#endif
/*
* Perform any necessary IDN conversion of hostname
*/
static void fix_hostname(struct SessionHandle *data,
struct connectdata *conn, struct hostname *host)
{
size_t len;
#ifndef USE_LIBIDN
(void)data;
(void)conn;
#elif defined(CURL_DISABLE_VERBOSE_STRINGS)
(void)conn;
#endif
/* set the name we use to display the host name */
host->dispname = host->name;
len = strlen(host->name);
if(host->name[len-1] == '.')
/* strip off a single trailing dot if present, primarily for SNI but
there's no use for it */
host->name[len-1]=0;
if(!is_ASCII_name(host->name)) {
#ifdef USE_LIBIDN
/*************************************************************
* Check name for non-ASCII and convert hostname to ACE form.
*************************************************************/
if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
char *ace_hostname = NULL;
int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
infof (data, "Input domain encoded as `%s'\n",
stringprep_locale_charset ());
if(rc != IDNA_SUCCESS)
infof(data, "Failed to convert %s to ACE; %s\n",
host->name, Curl_idn_strerror(conn,rc));
else {
/* tld_check_name() displays a warning if the host name contains
"illegal" characters for this TLD */
(void)tld_check_name(data, ace_hostname);
host->encalloc = ace_hostname;
/* change the name pointer to point to the encoded hostname */
host->name = host->encalloc;
}
}
#elif defined(USE_WIN32_IDN)
/*************************************************************
* Check name for non-ASCII and convert hostname to ACE form.
*************************************************************/
char *ace_hostname = NULL;
int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname);
if(rc == 0)
infof(data, "Failed to convert %s to ACE;\n",
host->name);
else {
host->encalloc = ace_hostname;
/* change the name pointer to point to the encoded hostname */
host->name = host->encalloc;
}
#else
infof(data, "IDN support not present, can't parse Unicode domains\n");
#endif
}
}
static void llist_dtor(void *user, void *element)
{
(void)user;
(void)element;
/* Do nothing */
}
/*
* Allocate and initialize a new connectdata object.
*/
static struct connectdata *allocate_conn(struct SessionHandle *data)
{
struct connectdata *conn = calloc(1, sizeof(struct connectdata));
if(!conn)
return NULL;
conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
already from start to avoid NULL
situations and checks */
/* and we setup a few fields in case we end up actually using this struct */
conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
conn->connection_id = -1; /* no ID */
conn->port = -1; /* unknown at this point */
conn->remote_port = -1; /* unknown */
/* Default protocol-independent behavior doesn't support persistent
connections, so we set this to force-close. Protocols that support
this need to set this to FALSE in their "curl_do" functions. */
conn->bits.close = TRUE;
/* Store creation time to help future close decision making */
conn->created = Curl_tvnow();
conn->data = data; /* Setup the association between this connection
and the SessionHandle */
conn->proxytype = data->set.proxytype; /* type */
#ifdef CURL_DISABLE_PROXY
conn->bits.proxy = FALSE;
conn->bits.httpproxy = FALSE;
conn->bits.proxy_user_passwd = FALSE;
conn->bits.tunnel_proxy = FALSE;
#else /* CURL_DISABLE_PROXY */
/* note that these two proxy bits are now just on what looks to be
requested, they may be altered down the road */
conn->bits.proxy = (data->set.str[STRING_PROXY] &&
*data->set.str[STRING_PROXY])?TRUE:FALSE;
conn->bits.httpproxy = (conn->bits.proxy &&
(conn->proxytype == CURLPROXY_HTTP ||
conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE;
conn->bits.proxy_user_passwd =
(NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE;
conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
#endif /* CURL_DISABLE_PROXY */
conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE;
conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
conn->verifypeer = data->set.ssl.verifypeer;
conn->verifyhost = data->set.ssl.verifyhost;
conn->ip_version = data->set.ipver;
#if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
conn->ntlm_auth_hlpr_pid = 0;
conn->challenge_header = NULL;
conn->response_header = NULL;
#endif
if(Curl_multi_pipeline_enabled(data->multi) &&
!conn->master_buffer) {
/* Allocate master_buffer to be used for pipelining */
conn->master_buffer = calloc(BUFSIZE, sizeof (char));
if(!conn->master_buffer)
goto error;
}
/* Initialize the pipeline lists */
conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
if(!conn->send_pipe || !conn->recv_pipe)
goto error;
#ifdef HAVE_GSSAPI
conn->data_prot = PROT_CLEAR;
#endif
/* Store the local bind parameters that will be used for this connection */
if(data->set.str[STRING_DEVICE]) {
conn->localdev = strdup(data->set.str[STRING_DEVICE]);
if(!conn->localdev)
goto error;
}
conn->localportrange = data->set.localportrange;
conn->localport = data->set.localport;
/* the close socket stuff needs to be copied to the connection struct as
it may live on without (this specific) SessionHandle */
conn->fclosesocket = data->set.fclosesocket;
conn->closesocket_client = data->set.closesocket_client;
return conn;
error:
Curl_llist_destroy(conn->send_pipe, NULL);
Curl_llist_destroy(conn->recv_pipe, NULL);
conn->send_pipe = NULL;
conn->recv_pipe = NULL;
Curl_safefree(conn->master_buffer);
Curl_safefree(conn->localdev);
Curl_safefree(conn);
return NULL;
}
static CURLcode findprotocol(struct SessionHandle *data,
struct connectdata *conn,
const char *protostr)
{
const struct Curl_handler * const *pp;
const struct Curl_handler *p;
/* Scan protocol handler table and match against 'protostr' to set a few
variables based on the URL. Now that the handler may be changed later
when the protocol specific setup function is called. */
for(pp = protocols; (p = *pp) != NULL; pp++) {
if(Curl_raw_equal(p->scheme, protostr)) {
/* Protocol found in table. Check if allowed */
if(!(data->set.allowed_protocols & p->protocol))
/* nope, get out */
break;
/* it is allowed for "normal" request, now do an extra check if this is
the result of a redirect */
if(data->state.this_is_a_follow &&
!(data->set.redir_protocols & p->protocol))
/* nope, get out */
break;
/* Perform setup complement if some. */
conn->handler = conn->given = p;
/* 'port' and 'remote_port' are set in setup_connection_internals() */
return CURLE_OK;
}
}
/* The protocol was not found in the table, but we don't have to assign it
to anything since it is already assigned to a dummy-struct in the
create_conn() function when the connectdata struct is allocated. */
failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
protostr);
return CURLE_UNSUPPORTED_PROTOCOL;
}
/*
* Parse URL and fill in the relevant members of the connection struct.
*/
static CURLcode parseurlandfillconn(struct SessionHandle *data,
struct connectdata *conn,
bool *prot_missing,
char **userp, char **passwdp,
char **optionsp)
{
char *at;
char *fragment;
char *path = data->state.path;
char *query;
int rc;
char protobuf[16] = "";
const char *protop = "";
CURLcode result;
bool rebuild_url = FALSE;
*prot_missing = FALSE;
/*************************************************************
* Parse the URL.
*
* We need to parse the url even when using the proxy, because we will need
* the hostname and port in case we are trying to SSL connect through the
* proxy -- and we don't know if we will need to use SSL until we parse the
* url ...
************************************************************/
if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
protobuf, path)) &&
Curl_raw_equal(protobuf, "file")) {
if(path[0] == '/' && path[1] == '/') {
/* Allow omitted hostname (e.g. file:/<path>). This is not strictly
* speaking a valid file: URL by RFC 1738, but treating file:/<path> as
* file://localhost/<path> is similar to how other schemes treat missing
* hostnames. See RFC 1808. */
/* This cannot be done with strcpy() in a portable manner, since the
memory areas overlap! */
memmove(path, path + 2, strlen(path + 2)+1);
}
/*
* we deal with file://<host>/<path> differently since it supports no
* hostname other than "localhost" and "127.0.0.1", which is unique among
* the URL protocols specified in RFC 1738
*/
if(path[0] != '/') {
/* the URL included a host name, we ignore host names in file:// URLs
as the standards don't define what to do with them */
char *ptr=strchr(path, '/');
if(ptr) {
/* there was a slash present
RFC1738 (section 3.1, page 5) says:
The rest of the locator consists of data specific to the scheme,
and is known as the "url-path". It supplies the details of how the
specified resource can be accessed. Note that the "/" between the
host (or port) and the url-path is NOT part of the url-path.
As most agents use file://localhost/foo to get '/foo' although the
slash preceding foo is a separator and not a slash for the path,
a URL as file://localhost//foo must be valid as well, to refer to
the same file with an absolute path.
*/
if(ptr[1] && ('/' == ptr[1]))
/* if there was two slashes, we skip the first one as that is then
used truly as a separator */
ptr++;
/* This cannot be made with strcpy, as the memory chunks overlap! */
memmove(path, ptr, strlen(ptr)+1);
}
}
protop = "file"; /* protocol string */
}
else {
/* clear path */
path[0]=0;
if(2 > sscanf(data->change.url,
"%15[^\n:]://%[^\n/?]%[^\n]",
protobuf,
conn->host.name, path)) {
/*
* The URL was badly formatted, let's try the browser-style _without_
* protocol specified like 'http://'.
*/
rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
if(1 > rc) {
/*
* We couldn't even get this format.
* djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
* assigned, but the return value is EOF!
*/
#if defined(__DJGPP__) && (DJGPP_MINOR == 4)
if(!(rc == -1 && *conn->host.name))
#endif
{
failf(data, "<url> malformed");
return CURLE_URL_MALFORMAT;
}
}
/*
* Since there was no protocol part specified, we guess what protocol it
* is based on the first letters of the server name.
*/
/* Note: if you add a new protocol, please update the list in
* lib/version.c too! */
if(checkprefix("FTP.", conn->host.name))
protop = "ftp";
else if(checkprefix("DICT.", conn->host.name))
protop = "DICT";
else if(checkprefix("LDAP.", conn->host.name))
protop = "LDAP";
else if(checkprefix("IMAP.", conn->host.name))
protop = "IMAP";
else if(checkprefix("SMTP.", conn->host.name))
protop = "smtp";
else if(checkprefix("POP3.", conn->host.name))
protop = "pop3";
else {
protop = "http";
}
*prot_missing = TRUE; /* not given in URL */
}
else
protop = protobuf;
}
/* We search for '?' in the host name (but only on the right side of a
* @-letter to allow ?-letters in username and password) to handle things
* like http://example.com?param= (notice the missing '/').
*/
at = strchr(conn->host.name, '@');
if(at)
query = strchr(at+1, '?');
else
query = strchr(conn->host.name, '?');
if(query) {
/* We must insert a slash before the '?'-letter in the URL. If the URL had
a slash after the '?', that is where the path currently begins and the
'?string' is still part of the host name.
We must move the trailing part from the host name and put it first in
the path. And have it all prefixed with a slash.
*/
size_t hostlen = strlen(query);
size_t pathlen = strlen(path);
/* move the existing path plus the zero byte forward, to make room for
the host-name part */
memmove(path+hostlen+1, path, pathlen+1);
/* now copy the trailing host part in front of the existing path */
memcpy(path+1, query, hostlen);
path[0]='/'; /* prepend the missing slash */
rebuild_url = TRUE;
*query=0; /* now cut off the hostname at the ? */
}
else if(!path[0]) {
/* if there's no path set, use a single slash */
strcpy(path, "/");
rebuild_url = TRUE;
}
/* If the URL is malformatted (missing a '/' after hostname before path) we
* insert a slash here. The only letter except '/' we accept to start a path
* is '?'.
*/
if(path[0] == '?') {
/* We need this function to deal with overlapping memory areas. We know
that the memory area 'path' points to is 'urllen' bytes big and that
is bigger than the path. Use +1 to move the zero byte too. */
memmove(&path[1], path, strlen(path)+1);
path[0] = '/';
rebuild_url = TRUE;
}
else {
/* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
char *newp = Curl_dedotdotify(path);
if(!newp)
return CURLE_OUT_OF_MEMORY;
if(strcmp(newp, path)) {
rebuild_url = TRUE;
free(data->state.pathbuffer);
data->state.pathbuffer = newp;
data->state.path = newp;
path = newp;
}
else
free(newp);
}
/*
* "rebuild_url" means that one or more URL components have been modified so
* we need to generate an updated full version. We need the corrected URL
* when communicating over HTTP proxy and we don't know at this point if
* we're using a proxy or not.
*/
if(rebuild_url) {
char *reurl;
size_t plen = strlen(path); /* new path, should be 1 byte longer than
the original */
size_t urllen = strlen(data->change.url); /* original URL length */
size_t prefixlen = strlen(conn->host.name);
if(!*prot_missing)
prefixlen += strlen(protop) + strlen("://");
reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */
if(!reurl)
return CURLE_OUT_OF_MEMORY;
/* copy the prefix */
memcpy(reurl, data->change.url, prefixlen);
/* append the trailing piece + zerobyte */
memcpy(&reurl[prefixlen], path, plen + 1);
/* possible free the old one */
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
infof(data, "Rebuilt URL to: %s\n", reurl);
data->change.url = reurl;
data->change.url_alloc = TRUE; /* free this later */
}
/*
* Parse the login details from the URL and strip them out of
* the host name
*/
result = parse_url_login(data, conn, userp, passwdp, optionsp);
if(result != CURLE_OK)
return result;
if(conn->host.name[0] == '[') {
/* This looks like an IPv6 address literal. See if there is an address
scope if there is no location header */
char *percent = strchr(conn->host.name, '%');
if(percent) {
unsigned int identifier_offset = 3;
char *endp;
unsigned long scope;
if(strncmp("%25", percent, 3) != 0) {
infof(data,
"Please URL encode %% as %%25, see RFC 6874.\n");
identifier_offset = 1;
}
scope = strtoul(percent + identifier_offset, &endp, 10);
if(*endp == ']') {
/* The address scope was well formed. Knock it out of the
hostname. */
memmove(percent, endp, strlen(endp)+1);
conn->scope = (unsigned int)scope;
}
else {
/* Zone identifier is not numeric */
#if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ)
char ifname[IFNAMSIZ + 2];
char *square_bracket;
unsigned int scopeidx = 0;
strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
/* Ensure nullbyte termination */
ifname[IFNAMSIZ + 1] = '\0';
square_bracket = strchr(ifname, ']');
if(square_bracket) {
/* Remove ']' */
*square_bracket = '\0';
scopeidx = if_nametoindex(ifname);
if(scopeidx == 0) {
infof(data, "Invalid network interface: %s; %s\n", ifname,
strerror(errno));
}
}
if(scopeidx > 0) {
/* Remove zone identifier from hostname */
memmove(percent,
percent + identifier_offset + strlen(ifname),
identifier_offset + strlen(ifname));
conn->scope = scopeidx;
}
else
#endif /* HAVE_NET_IF_H && IFNAMSIZ */
infof(data, "Invalid IPv6 address format\n");
}
}
}
if(data->set.scope)
/* Override any scope that was set above. */
conn->scope = data->set.scope;
/* Remove the fragment part of the path. Per RFC 2396, this is always the
last part of the URI. We are looking for the first '#' so that we deal
gracefully with non conformant URI such as http://example.com#foo#bar. */
fragment = strchr(path, '#');
if(fragment) {
*fragment = 0;
/* we know the path part ended with a fragment, so we know the full URL
string does too and we need to cut it off from there so it isn't used
over proxy */
fragment = strchr(data->change.url, '#');
if(fragment)
*fragment = 0;
}
/*
* So if the URL was A://B/C#D,
* protop is A
* conn->host.name is B
* data->state.path is /C
*/
return findprotocol(data, conn, protop);
}
/*
* If we're doing a resumed transfer, we need to setup our stuff
* properly.
*/
static CURLcode setup_range(struct SessionHandle *data)
{
struct UrlState *s = &data->state;
s->resume_from = data->set.set_resume_from;
if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
if(s->rangestringalloc)
free(s->range);
if(s->resume_from)
s->range = aprintf("%" CURL_FORMAT_CURL_OFF_TU "-", s->resume_from);
else
s->range = strdup(data->set.str[STRING_SET_RANGE]);
s->rangestringalloc = (s->range)?TRUE:FALSE;
if(!s->range)
return CURLE_OUT_OF_MEMORY;
/* tell ourselves to fetch this range */
s->use_range = TRUE; /* enable range download */
}
else
s->use_range = FALSE; /* disable range download */
return CURLE_OK;
}
/*
* setup_connection_internals() -
*
* Setup connection internals specific to the requested protocol in the
* SessionHandle. This is inited and setup before the connection is made but
* is about the particular protocol that is to be used.
*
* This MUST get called after proxy magic has been figured out.
*/
static CURLcode setup_connection_internals(struct connectdata *conn)
{
const struct Curl_handler * p;
CURLcode result;
struct SessionHandle *data = conn->data;
/* in some case in the multi state-machine, we go back to the CONNECT state
and then a second (or third or...) call to this function will be made
without doing a DISCONNECT or DONE in between (since the connection is
yet in place) and therefore this function needs to first make sure
there's no lingering previous data allocated. */
Curl_free_request_state(data);
memset(&data->req, 0, sizeof(struct SingleRequest));
data->req.maxdownload = -1;
conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
/* Perform setup complement if some. */
p = conn->handler;
if(p->setup_connection) {
result = (*p->setup_connection)(conn);
if(result != CURLE_OK)
return result;
p = conn->handler; /* May have changed. */
}
if(conn->port < 0)
/* we check for -1 here since if proxy was detected already, this
was very likely already set to the proxy port */
conn->port = p->defport;
/* only if remote_port was not already parsed off the URL we use the
default port number */
if(conn->remote_port < 0)
conn->remote_port = (unsigned short)conn->given->defport;
return CURLE_OK;
}
/*
* Curl_free_request_state() should free temp data that was allocated in the
* SessionHandle for this single request.
*/
void Curl_free_request_state(struct SessionHandle *data)
{
Curl_safefree(data->req.protop);
}
#ifndef CURL_DISABLE_PROXY
/****************************************************************
* Checks if the host is in the noproxy list. returns true if it matches
* and therefore the proxy should NOT be used.
****************************************************************/
static bool check_noproxy(const char* name, const char* no_proxy)
{
/* no_proxy=domain1.dom,host.domain2.dom
* (a comma-separated list of hosts which should
* not be proxied, or an asterisk to override
* all proxy variables)
*/
size_t tok_start;
size_t tok_end;
const char* separator = ", ";
size_t no_proxy_len;
size_t namelen;
char *endptr;
if(no_proxy && no_proxy[0]) {
if(Curl_raw_equal("*", no_proxy)) {
return TRUE;
}
/* NO_PROXY was specified and it wasn't just an asterisk */
no_proxy_len = strlen(no_proxy);
endptr = strchr(name, ':');
if(endptr)
namelen = endptr - name;
else
namelen = strlen(name);
for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
while(tok_start < no_proxy_len &&
strchr(separator, no_proxy[tok_start]) != NULL) {
/* Look for the beginning of the token. */
++tok_start;
}
if(tok_start == no_proxy_len)
break; /* It was all trailing separator chars, no more tokens. */
for(tok_end = tok_start; tok_end < no_proxy_len &&
strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
/* Look for the end of the token. */
;
/* To match previous behaviour, where it was necessary to specify
* ".local.com" to prevent matching "notlocal.com", we will leave
* the '.' off.
*/
if(no_proxy[tok_start] == '.')
++tok_start;
if((tok_end - tok_start) <= namelen) {
/* Match the last part of the name to the domain we are checking. */
const char *checkn = name + namelen - (tok_end - tok_start);
if(Curl_raw_nequal(no_proxy + tok_start, checkn,
tok_end - tok_start)) {
if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
/* We either have an exact match, or the previous character is a .
* so it is within the same domain, so no proxy for this host.
*/
return TRUE;
}
}
} /* if((tok_end - tok_start) <= namelen) */
} /* for(tok_start = 0; tok_start < no_proxy_len;
tok_start = tok_end + 1) */
} /* NO_PROXY was specified and it wasn't just an asterisk */
return FALSE;
}
/****************************************************************
* Detect what (if any) proxy to use. Remember that this selects a host
* name and is not limited to HTTP proxies only.
* The returned pointer must be freed by the caller (unless NULL)
****************************************************************/
static char *detect_proxy(struct connectdata *conn)
{
char *proxy = NULL;
#ifndef CURL_DISABLE_HTTP
/* If proxy was not specified, we check for default proxy environment
* variables, to enable i.e Lynx compliance:
*
* http_proxy=http://some.server.dom:port/
* https_proxy=http://some.server.dom:port/
* ftp_proxy=http://some.server.dom:port/
* no_proxy=domain1.dom,host.domain2.dom
* (a comma-separated list of hosts which should
* not be proxied, or an asterisk to override
* all proxy variables)
* all_proxy=http://some.server.dom:port/
* (seems to exist for the CERN www lib. Probably
* the first to check for.)
*
* For compatibility, the all-uppercase versions of these variables are
* checked if the lowercase versions don't exist.
*/
char *no_proxy=NULL;
char proxy_env[128];
no_proxy=curl_getenv("no_proxy");
if(!no_proxy)
no_proxy=curl_getenv("NO_PROXY");
if(!check_noproxy(conn->host.name, no_proxy)) {
/* It was not listed as without proxy */
const char *protop = conn->handler->scheme;
char *envp = proxy_env;
char *prox;
/* Now, build <protocol>_proxy and check for such a one to use */
while(*protop)
*envp++ = (char)tolower((int)*protop++);
/* append _proxy */
strcpy(envp, "_proxy");
/* read the protocol proxy: */
prox=curl_getenv(proxy_env);
/*
* We don't try the uppercase version of HTTP_PROXY because of
* security reasons:
*
* When curl is used in a webserver application
* environment (cgi or php), this environment variable can
* be controlled by the web server user by setting the
* http header 'Proxy:' to some value.
*
* This can cause 'internal' http/ftp requests to be
* arbitrarily redirected by any external attacker.
*/
if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
/* There was no lowercase variable, try the uppercase version: */
Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
prox=curl_getenv(proxy_env);
}
if(prox && *prox) { /* don't count "" strings */
proxy = prox; /* use this */
}
else {
proxy = curl_getenv("all_proxy"); /* default proxy to use */
if(!proxy)
proxy=curl_getenv("ALL_PROXY");
}
} /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
non-proxy */
if(no_proxy)
free(no_proxy);
#else /* !CURL_DISABLE_HTTP */
(void)conn;
#endif /* CURL_DISABLE_HTTP */
return proxy;
}
/*
* If this is supposed to use a proxy, we need to figure out the proxy
* host name, so that we can re-use an existing connection
* that may exist registered to the same proxy host.
* proxy will be freed before this function returns.
*/
static CURLcode parse_proxy(struct SessionHandle *data,
struct connectdata *conn, char *proxy)
{
char *prox_portno;
char *endofprot;
/* We use 'proxyptr' to point to the proxy name from now on... */
char *proxyptr;
char *portptr;
char *atsign;
/* We do the proxy host string parsing here. We want the host name and the
* port name. Accept a protocol:// prefix
*/
/* Parse the protocol part if present */
endofprot = strstr(proxy, "://");
if(endofprot) {
proxyptr = endofprot+3;
if(checkprefix("socks5h", proxy))
conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
else if(checkprefix("socks5", proxy))
conn->proxytype = CURLPROXY_SOCKS5;
else if(checkprefix("socks4a", proxy))
conn->proxytype = CURLPROXY_SOCKS4A;
else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
conn->proxytype = CURLPROXY_SOCKS4;
/* Any other xxx:// : change to http proxy */
}
else
proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
/* Is there a username and password given in this proxy url? */
atsign = strchr(proxyptr, '@');
if(atsign) {
CURLcode res = CURLE_OK;
char *proxyuser = NULL;
char *proxypasswd = NULL;
res = parse_login_details(proxyptr, atsign - proxyptr,
&proxyuser, &proxypasswd, NULL);
if(!res) {
/* found user and password, rip them out. note that we are
unescaping them, as there is otherwise no way to have a
username or password with reserved characters like ':' in
them. */
Curl_safefree(conn->proxyuser);
if(proxyuser && strlen(proxyuser) < MAX_CURL_USER_LENGTH)
conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
else
conn->proxyuser = strdup("");
if(!conn->proxyuser)
res = CURLE_OUT_OF_MEMORY;
else {
Curl_safefree(conn->proxypasswd);
if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
else
conn->proxypasswd = strdup("");
if(!conn->proxypasswd)
res = CURLE_OUT_OF_MEMORY;
}
if(!res) {
conn->bits.proxy_user_passwd = TRUE; /* enable it */
atsign++; /* the right side of the @-letter */
if(atsign)
proxyptr = atsign; /* now use this instead */
else
res = CURLE_OUT_OF_MEMORY;
}
}
Curl_safefree(proxyuser);
Curl_safefree(proxypasswd);
if(res)
return res;
}
/* start scanning for port number at this point */
portptr = proxyptr;
/* detect and extract RFC6874-style IPv6-addresses */
if(*proxyptr == '[') {
char *ptr = ++proxyptr; /* advance beyond the initial bracket */
while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
ptr++;
if(*ptr == '%') {
/* There might be a zone identifier */
if(strncmp("%25", ptr, 3))
infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
ptr++;
/* Allow unresered characters as defined in RFC 3986 */
while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
(*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
ptr++;
}
if(*ptr == ']')
/* yeps, it ended nicely with a bracket as well */
*ptr++ = 0;
else
infof(data, "Invalid IPv6 address format\n");
portptr = ptr;
/* Note that if this didn't end with a bracket, we still advanced the
* proxyptr first, but I can't see anything wrong with that as no host
* name nor a numeric can legally start with a bracket.
*/
}
/* Get port number off proxy.server.com:1080 */
prox_portno = strchr(portptr, ':');
if(prox_portno) {
*prox_portno = 0x0; /* cut off number from host name */
prox_portno ++;
/* now set the local port number */
conn->port = strtol(prox_portno, NULL, 10);
}
else {
if(proxyptr[0]=='/')
/* If the first character in the proxy string is a slash, fail
immediately. The following code will otherwise clear the string which
will lead to code running as if no proxy was set! */
return CURLE_COULDNT_RESOLVE_PROXY;
/* without a port number after the host name, some people seem to use
a slash so we strip everything from the first slash */
atsign = strchr(proxyptr, '/');
if(atsign)
*atsign = 0x0; /* cut off path part from host name */
if(data->set.proxyport)
/* None given in the proxy string, then get the default one if it is
given */
conn->port = data->set.proxyport;
}
/* now, clone the cleaned proxy host name */
conn->proxy.rawalloc = strdup(proxyptr);
conn->proxy.name = conn->proxy.rawalloc;
if(!conn->proxy.rawalloc)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
/*
* Extract the user and password from the authentication string
*/
static CURLcode parse_proxy_auth(struct SessionHandle *data,
struct connectdata *conn)
{
char proxyuser[MAX_CURL_USER_LENGTH]="";
char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
MAX_CURL_USER_LENGTH);
proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
}
if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
MAX_CURL_PASSWORD_LENGTH);
proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
}
conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
if(!conn->proxyuser)
return CURLE_OUT_OF_MEMORY;
conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
if(!conn->proxypasswd)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
#endif /* CURL_DISABLE_PROXY */
/*
* parse_url_login()
*
* Parse the login details (user name, password and options) from the URL and
* strip them out of the host name
*
* Inputs: data->set.use_netrc (CURLOPT_NETRC)
* conn->host.name
*
* Outputs: (almost :- all currently undefined)
* conn->bits.user_passwd - non-zero if non-default passwords exist
* user - non-zero length if defined
* passwd - non-zero length if defined
* options - non-zero length if defined
* conn->host.name - remove user name and password
*/
static CURLcode parse_url_login(struct SessionHandle *data,
struct connectdata *conn,
char **user, char **passwd, char **options)
{
CURLcode result = CURLE_OK;
char *userp = NULL;
char *passwdp = NULL;
char *optionsp = NULL;
/* At this point, we're hoping all the other special cases have
* been taken care of, so conn->host.name is at most
* [user[:password][;options]]@]hostname
*
* We need somewhere to put the embedded details, so do that first.
*/
char *ptr = strchr(conn->host.name, '@');
char *login = conn->host.name;
DEBUGASSERT(!**user);
DEBUGASSERT(!**passwd);
DEBUGASSERT(!**options);
if(!ptr)
goto out;
/* We will now try to extract the
* possible login information in a string like:
* ftp://user:password@ftp.my.site:8021/README */
conn->host.name = ++ptr;
/* So the hostname is sane. Only bother interpreting the
* results if we could care. It could still be wasted
* work because it might be overtaken by the programmatically
* set user/passwd, but doing that first adds more cases here :-(
*/
if(data->set.use_netrc == CURL_NETRC_REQUIRED)
goto out;
/* We could use the login information in the URL so extract it */
result = parse_login_details(login, ptr - login - 1,
&userp, &passwdp, &optionsp);
if(result != CURLE_OK)
goto out;
if(userp) {
char *newname;
/* We have a user in the URL */
conn->bits.userpwd_in_url = TRUE;
conn->bits.user_passwd = TRUE; /* enable user+password */
/* Decode the user */
newname = curl_easy_unescape(data, userp, 0, NULL);
if(!newname) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
free(*user);
*user = newname;
}
if(passwdp) {
/* We have a password in the URL so decode it */
char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
if(!newpasswd) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
free(*passwd);
*passwd = newpasswd;
}
if(optionsp) {
/* We have an options list in the URL so decode it */
char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
if(!newoptions) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
free(*options);
*options = newoptions;
}
out:
Curl_safefree(userp);
Curl_safefree(passwdp);
Curl_safefree(optionsp);
return result;
}
/*
* parse_login_details()
*
* This is used to parse a login string for user name, password and options in
* the following formats:
*
* user
* user:password
* user:password;options
* user;options
* user;options:password
* :password
* :password;options
* ;options
* ;options:password
*
* Parameters:
*
* login [in] - The login string.
* len [in] - The length of the login string.
* userp [in/out] - The address where a pointer to newly allocated memory
* holding the user will be stored upon completion.
* passdwp [in/out] - The address where a pointer to newly allocated memory
* holding the password will be stored upon completion.
* optionsp [in/out] - The address where a pointer to newly allocated memory
* holding the options will be stored upon completion.
*
* Returns CURLE_OK on success.
*/
static CURLcode parse_login_details(const char *login, const size_t len,
char **userp, char **passwdp,
char **optionsp)
{
CURLcode result = CURLE_OK;
char *ubuf = NULL;
char *pbuf = NULL;
char *obuf = NULL;
const char *psep = NULL;
const char *osep = NULL;
size_t ulen;
size_t plen;
size_t olen;
/* Attempt to find the password separator */
if(passwdp) {
psep = strchr(login, ':');
/* Within the constraint of the login string */
if(psep >= login + len)
psep = NULL;
}
/* Attempt to find the options separator */
if(optionsp) {
osep = strchr(login, ';');
/* Within the constraint of the login string */
if(osep >= login + len)
osep = NULL;
}
/* Calculate the portion lengths */
ulen = (psep ?
(size_t)(osep && psep > osep ? osep - login : psep - login) :
(osep ? (size_t)(osep - login) : len));
plen = (psep ?
(osep && osep > psep ? (size_t)(osep - psep) :
(size_t)(login + len - psep)) - 1 : 0);
olen = (osep ?
(psep && psep > osep ? (size_t)(psep - osep) :
(size_t)(login + len - osep)) - 1 : 0);
/* Allocate the user portion buffer */
if(userp && ulen) {
ubuf = malloc(ulen + 1);
if(!ubuf)
result = CURLE_OUT_OF_MEMORY;
}
/* Allocate the password portion buffer */
if(!result && passwdp && plen) {
pbuf = malloc(plen + 1);
if(!pbuf) {
Curl_safefree(ubuf);
result = CURLE_OUT_OF_MEMORY;
}
}
/* Allocate the options portion buffer */
if(!result && optionsp && olen) {
obuf = malloc(olen + 1);
if(!obuf) {
Curl_safefree(pbuf);
Curl_safefree(ubuf);
result = CURLE_OUT_OF_MEMORY;
}
}
if(!result) {
/* Store the user portion if necessary */
if(ubuf) {
memcpy(ubuf, login, ulen);
ubuf[ulen] = '\0';
Curl_safefree(*userp);
*userp = ubuf;
}
/* Store the password portion if necessary */
if(pbuf) {
memcpy(pbuf, psep + 1, plen);
pbuf[plen] = '\0';
Curl_safefree(*passwdp);
*passwdp = pbuf;
}
/* Store the options portion if necessary */
if(obuf) {
memcpy(obuf, osep + 1, olen);
obuf[olen] = '\0';
Curl_safefree(*optionsp);
*optionsp = obuf;
}
}
return result;
}
/*************************************************************
* Figure out the remote port number and fix it in the URL
*
* No matter if we use a proxy or not, we have to figure out the remote
* port number of various reasons.
*
* To be able to detect port number flawlessly, we must not confuse them
* IPv6-specified addresses in the [0::1] style. (RFC2732)
*
* The conn->host.name is currently [user:passwd@]host[:port] where host
* could be a hostname, IPv4 address or IPv6 address.
*
* The port number embedded in the URL is replaced, if necessary.
*************************************************************/
static CURLcode parse_remote_port(struct SessionHandle *data,
struct connectdata *conn)
{
char *portptr;
char endbracket;
/* Note that at this point, the IPv6 address cannot contain any scope
suffix as that has already been removed in the parseurlandfillconn()
function */
if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
&endbracket)) &&
(']' == endbracket)) {
/* this is a RFC2732-style specified IP-address */
conn->bits.ipv6_ip = TRUE;
conn->host.name++; /* skip over the starting bracket */
portptr = strchr(conn->host.name, ']');
if(portptr) {
*portptr++ = '\0'; /* zero terminate, killing the bracket */
if(':' != *portptr)
portptr = NULL; /* no port number available */
}
}
else {
#ifdef ENABLE_IPV6
struct in6_addr in6;
if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
/* This is a numerical IPv6 address, meaning this is a wrongly formatted
URL */
failf(data, "IPv6 numerical address used in URL without brackets");
return CURLE_URL_MALFORMAT;
}
#endif
portptr = strrchr(conn->host.name, ':');
}
if(data->set.use_port && data->state.allow_port) {
/* if set, we use this and ignore the port possibly given in the URL */
conn->remote_port = (unsigned short)data->set.use_port;
if(portptr)
*portptr = '\0'; /* cut off the name there anyway - if there was a port
number - since the port number is to be ignored! */
if(conn->bits.httpproxy) {
/* we need to create new URL with the new port number */
char *url;
char type[12]="";
if(conn->bits.type_set)
snprintf(type, sizeof(type), ";type=%c",
data->set.prefer_ascii?'A':
(data->set.ftp_list_only?'D':'I'));
/*
* This synthesized URL isn't always right--suffixes like ;type=A are
* stripped off. It would be better to work directly from the original
* URL and simply replace the port part of it.
*/
url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
conn->bits.ipv6_ip?"[":"", conn->host.name,
conn->bits.ipv6_ip?"]":"", conn->remote_port,
data->state.slash_removed?"/":"", data->state.path,
type);
if(!url)
return CURLE_OUT_OF_MEMORY;
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
data->change.url = url;
data->change.url_alloc = TRUE;
}
}
else if(portptr) {
/* no CURLOPT_PORT given, extract the one from the URL */
char *rest;
long port;
port=strtol(portptr+1, &rest, 10); /* Port number must be decimal */
if((port < 0) || (port > 0xffff)) {
/* Single unix standard says port numbers are 16 bits long */
failf(data, "Port number out of range");
return CURLE_URL_MALFORMAT;
}
else if(rest != &portptr[1]) {
*portptr = '\0'; /* cut off the name there */
conn->remote_port = curlx_ultous(port);
}
else
/* Browser behavior adaptation. If there's a colon with no digits after,
just cut off the name there which makes us ignore the colon and just
use the default port. Firefox and Chrome both do that. */
*portptr = '\0';
}
return CURLE_OK;
}
/*
* Override the login details from the URL with that in the CURLOPT_USERPWD
* option or a .netrc file, if applicable.
*/
static CURLcode override_login(struct SessionHandle *data,
struct connectdata *conn,
char **userp, char **passwdp, char **optionsp)
{
if(data->set.str[STRING_USERNAME]) {
free(*userp);
*userp = strdup(data->set.str[STRING_USERNAME]);
if(!*userp)
return CURLE_OUT_OF_MEMORY;
}
if(data->set.str[STRING_PASSWORD]) {
free(*passwdp);
*passwdp = strdup(data->set.str[STRING_PASSWORD]);
if(!*passwdp)
return CURLE_OUT_OF_MEMORY;
}
if(data->set.str[STRING_OPTIONS]) {
free(*optionsp);
*optionsp = strdup(data->set.str[STRING_OPTIONS]);
if(!*optionsp)
return CURLE_OUT_OF_MEMORY;
}
conn->bits.netrc = FALSE;
if(data->set.use_netrc != CURL_NETRC_IGNORED) {
int ret = Curl_parsenetrc(conn->host.name,
userp, passwdp,
data->set.str[STRING_NETRC_FILE]);
if(ret > 0) {
infof(data, "Couldn't find host %s in the "
DOT_CHAR "netrc file; using defaults\n",
conn->host.name);
}
else if(ret < 0 ) {
return CURLE_OUT_OF_MEMORY;
}
else {
/* set bits.netrc TRUE to remember that we got the name from a .netrc
file, so that it is safe to use even if we followed a Location: to a
different host or similar. */
conn->bits.netrc = TRUE;
conn->bits.user_passwd = TRUE; /* enable user+password */
}
}
return CURLE_OK;
}
/*
* Set the login details so they're available in the connection
*/
static CURLcode set_login(struct connectdata *conn,
const char *user, const char *passwd,
const char *options)
{
CURLcode result = CURLE_OK;
/* If our protocol needs a password and we have none, use the defaults */
if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
/* Store the default user */
conn->user = strdup(CURL_DEFAULT_USER);
/* Store the default password */
if(conn->user)
conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
else
conn->passwd = NULL;
/* This is the default password, so DON'T set conn->bits.user_passwd */
}
else {
/* Store the user, zero-length if not set */
conn->user = strdup(user);
/* Store the password (only if user is present), zero-length if not set */
if(conn->user)
conn->passwd = strdup(passwd);
else
conn->passwd = NULL;
}
if(!conn->user || !conn->passwd)
result = CURLE_OUT_OF_MEMORY;
/* Store the options, null if not set */
if(!result && options[0]) {
conn->options = strdup(options);
if(!conn->options)
result = CURLE_OUT_OF_MEMORY;
}
return result;
}
/*************************************************************
* Resolve the address of the server or proxy
*************************************************************/
static CURLcode resolve_server(struct SessionHandle *data,
struct connectdata *conn,
bool *async)
{
CURLcode result=CURLE_OK;
long timeout_ms = Curl_timeleft(data, NULL, TRUE);
/*************************************************************
* Resolve the name of the server or proxy
*************************************************************/
if(conn->bits.reuse)
/* We're reusing the connection - no need to resolve anything, and
fix_hostname() was called already in create_conn() for the re-use
case. */
*async = FALSE;
else {
/* this is a fresh connect */
int rc;
struct Curl_dns_entry *hostaddr;
/* set a pointer to the hostname we display */
fix_hostname(data, conn, &conn->host);
if(!conn->proxy.name || !*conn->proxy.name) {
/* If not connecting via a proxy, extract the port from the URL, if it is
* there, thus overriding any defaults that might have been set above. */
conn->port = conn->remote_port; /* it is the same port */
/* Resolve target host right on */
rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
&hostaddr, timeout_ms);
if(rc == CURLRESOLV_PENDING)
*async = TRUE;
else if(rc == CURLRESOLV_TIMEDOUT)
result = CURLE_OPERATION_TIMEDOUT;
else if(!hostaddr) {
failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
result = CURLE_COULDNT_RESOLVE_HOST;
/* don't return yet, we need to clean up the timeout first */
}
}
else {
/* This is a proxy that hasn't been resolved yet. */
/* IDN-fix the proxy name */
fix_hostname(data, conn, &conn->proxy);
/* resolve proxy */
rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
&hostaddr, timeout_ms);
if(rc == CURLRESOLV_PENDING)
*async = TRUE;
else if(rc == CURLRESOLV_TIMEDOUT)
result = CURLE_OPERATION_TIMEDOUT;
else if(!hostaddr) {
failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
result = CURLE_COULDNT_RESOLVE_PROXY;
/* don't return yet, we need to clean up the timeout first */
}
}
DEBUGASSERT(conn->dns_entry == NULL);
conn->dns_entry = hostaddr;
}
return result;
}
/*
* Cleanup the connection just allocated before we can move along and use the
* previously existing one. All relevant data is copied over and old_conn is
* ready for freeing once this function returns.
*/
static void reuse_conn(struct connectdata *old_conn,
struct connectdata *conn)
{
if(old_conn->proxy.rawalloc)
free(old_conn->proxy.rawalloc);
/* free the SSL config struct from this connection struct as this was
allocated in vain and is targeted for destruction */
Curl_free_ssl_config(&old_conn->ssl_config);
conn->data = old_conn->data;
/* get the user+password information from the old_conn struct since it may
* be new for this request even when we re-use an existing connection */
conn->bits.user_passwd = old_conn->bits.user_passwd;
if(conn->bits.user_passwd) {
/* use the new user name and password though */
Curl_safefree(conn->user);
Curl_safefree(conn->passwd);
conn->user = old_conn->user;
conn->passwd = old_conn->passwd;
old_conn->user = NULL;
old_conn->passwd = NULL;
}
conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
if(conn->bits.proxy_user_passwd) {
/* use the new proxy user name and proxy password though */
Curl_safefree(conn->proxyuser);
Curl_safefree(conn->proxypasswd);
conn->proxyuser = old_conn->proxyuser;
conn->proxypasswd = old_conn->proxypasswd;
old_conn->proxyuser = NULL;
old_conn->proxypasswd = NULL;
}
/* host can change, when doing keepalive with a proxy or if the case is
different this time etc */
Curl_safefree(conn->host.rawalloc);
conn->host=old_conn->host;
/* persist connection info in session handle */
Curl_persistconninfo(conn);
/* re-use init */
conn->bits.reuse = TRUE; /* yes, we're re-using here */
Curl_safefree(old_conn->user);
Curl_safefree(old_conn->passwd);
Curl_safefree(old_conn->proxyuser);
Curl_safefree(old_conn->proxypasswd);
Curl_safefree(old_conn->localdev);
Curl_llist_destroy(old_conn->send_pipe, NULL);
Curl_llist_destroy(old_conn->recv_pipe, NULL);
old_conn->send_pipe = NULL;
old_conn->recv_pipe = NULL;
Curl_safefree(old_conn->master_buffer);
}
/**
* create_conn() sets up a new connectdata struct, or re-uses an already
* existing one, and resolves host name.
*
* if this function returns CURLE_OK and *async is set to TRUE, the resolve
* response will be coming asynchronously. If *async is FALSE, the name is
* already resolved.
*
* @param data The sessionhandle pointer
* @param in_connect is set to the next connection data pointer
* @param async is set TRUE when an async DNS resolution is pending
* @see Curl_setup_conn()
*
* *NOTE* this function assigns the conn->data pointer!
*/
static CURLcode create_conn(struct SessionHandle *data,
struct connectdata **in_connect,
bool *async)
{
CURLcode result = CURLE_OK;
struct connectdata *conn;
struct connectdata *conn_temp = NULL;
size_t urllen;
char *user = NULL;
char *passwd = NULL;
char *options = NULL;
bool reuse;
char *proxy = NULL;
bool prot_missing = FALSE;
bool no_connections_available = FALSE;
bool force_reuse;
size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
*async = FALSE;
/*************************************************************
* Check input data
*************************************************************/
if(!data->change.url) {
result = CURLE_URL_MALFORMAT;
goto out;
}
/* First, split up the current URL in parts so that we can use the
parts for checking against the already present connections. In order
to not have to modify everything at once, we allocate a temporary
connection data struct and fill in for comparison purposes. */
conn = allocate_conn(data);
if(!conn) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
/* We must set the return variable as soon as possible, so that our
parent can cleanup any possible allocs we may have done before
any failure */
*in_connect = conn;
/* This initing continues below, see the comment "Continue connectdata
* initialization here" */
/***********************************************************
* We need to allocate memory to store the path in. We get the size of the
* full URL to be sure, and we need to make it at least 256 bytes since
* other parts of the code will rely on this fact
***********************************************************/
#define LEAST_PATH_ALLOC 256
urllen=strlen(data->change.url);
if(urllen < LEAST_PATH_ALLOC)
urllen=LEAST_PATH_ALLOC;
/*
* We malloc() the buffers below urllen+2 to make room for 2 possibilities:
* 1 - an extra terminating zero
* 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
*/
Curl_safefree(data->state.pathbuffer);
data->state.path = NULL;
data->state.pathbuffer = malloc(urllen+2);
if(NULL == data->state.pathbuffer) {
result = CURLE_OUT_OF_MEMORY; /* really bad error */
goto out;
}
data->state.path = data->state.pathbuffer;
conn->host.rawalloc = malloc(urllen+2);
if(NULL == conn->host.rawalloc) {
Curl_safefree(data->state.pathbuffer);
data->state.path = NULL;
result = CURLE_OUT_OF_MEMORY;
goto out;
}
conn->host.name = conn->host.rawalloc;
conn->host.name[0] = 0;
user = strdup("");
passwd = strdup("");
options = strdup("");
if(!user || !passwd || !options) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
&options);
if(result != CURLE_OK)
goto out;
/*************************************************************
* No protocol part in URL was used, add it!
*************************************************************/
if(prot_missing) {
/* We're guessing prefixes here and if we're told to use a proxy or if
we're gonna follow a Location: later or... then we need the protocol
part added so that we have a valid URL. */
char *reurl;
reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
if(!reurl) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
data->change.url = reurl;
data->change.url_alloc = TRUE; /* free this later */
}
/*************************************************************
* If the protocol can't handle url query strings, then cut
* off the unhandable part
*************************************************************/
if((conn->given->flags&PROTOPT_NOURLQUERY)) {
char *path_q_sep = strchr(conn->data->state.path, '?');
if(path_q_sep) {
/* according to rfc3986, allow the query (?foo=bar)
also on protocols that can't handle it.
cut the string-part after '?'
*/
/* terminate the string */
path_q_sep[0] = 0;
}
}
if(data->set.str[STRING_BEARER]) {
conn->xoauth2_bearer = strdup(data->set.str[STRING_BEARER]);
if(!conn->xoauth2_bearer) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
#ifndef CURL_DISABLE_PROXY
/*************************************************************
* Extract the user and password from the authentication string
*************************************************************/
if(conn->bits.proxy_user_passwd) {
result = parse_proxy_auth(data, conn);
if(result != CURLE_OK)
goto out;
}
/*************************************************************
* Detect what (if any) proxy to use
*************************************************************/
if(data->set.str[STRING_PROXY]) {
proxy = strdup(data->set.str[STRING_PROXY]);
/* if global proxy is set, this is it */
if(NULL == proxy) {
failf(data, "memory shortage");
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
if(data->set.str[STRING_NOPROXY] &&
check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
if(proxy) {
free(proxy); /* proxy is in exception list */
proxy = NULL;
}
}
else if(!proxy)
proxy = detect_proxy(conn);
if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
free(proxy); /* Don't bother with an empty proxy string or if the
protocol doesn't work with network */
proxy = NULL;
}
/***********************************************************************
* If this is supposed to use a proxy, we need to figure out the proxy host
* name, proxy type and port number, so that we can re-use an existing
* connection that may exist registered to the same proxy host.
***********************************************************************/
if(proxy) {
result = parse_proxy(data, conn, proxy);
Curl_safefree(proxy); /* parse_proxy copies the proxy string */
if(result)
goto out;
if((conn->proxytype == CURLPROXY_HTTP) ||
(conn->proxytype == CURLPROXY_HTTP_1_0)) {
#ifdef CURL_DISABLE_HTTP
/* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
result = CURLE_UNSUPPORTED_PROTOCOL;
goto out;
#else
/* force this connection's protocol to become HTTP if not already
compatible - if it isn't tunneling through */
if(!(conn->handler->protocol & PROTO_FAMILY_HTTP) &&
!conn->bits.tunnel_proxy)
conn->handler = &Curl_handler_http;
conn->bits.httpproxy = TRUE;
#endif
}
else
conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
conn->bits.proxy = TRUE;
}
else {
/* we aren't using the proxy after all... */
conn->bits.proxy = FALSE;
conn->bits.httpproxy = FALSE;
conn->bits.proxy_user_passwd = FALSE;
conn->bits.tunnel_proxy = FALSE;
}
#endif /* CURL_DISABLE_PROXY */
/*************************************************************
* If the protocol is using SSL and HTTP proxy is used, we set
* the tunnel_proxy bit.
*************************************************************/
if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
/*************************************************************
* Figure out the remote port number and fix it in the URL
*************************************************************/
result = parse_remote_port(data, conn);
if(result != CURLE_OK)
goto out;
/* Check for overridden login details and set them accordingly so they
they are known when protocol->setup_connection is called! */
result = override_login(data, conn, &user, &passwd, &options);
if(result != CURLE_OK)
goto out;
result = set_login(conn, user, passwd, options);
if(result != CURLE_OK)
goto out;
/*************************************************************
* Setup internals depending on protocol. Needs to be done after
* we figured out what/if proxy to use.
*************************************************************/
result = setup_connection_internals(conn);
if(result != CURLE_OK)
goto out;
conn->recv[FIRSTSOCKET] = Curl_recv_plain;
conn->send[FIRSTSOCKET] = Curl_send_plain;
conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
conn->send[SECONDARYSOCKET] = Curl_send_plain;
/***********************************************************************
* file: is a special case in that it doesn't need a network connection
***********************************************************************/
#ifndef CURL_DISABLE_FILE
if(conn->handler->flags & PROTOPT_NONETWORK) {
bool done;
/* this is supposed to be the connect function so we better at least check
that the file is present here! */
DEBUGASSERT(conn->handler->connect_it);
result = conn->handler->connect_it(conn, &done);
/* Setup a "faked" transfer that'll do nothing */
if(CURLE_OK == result) {
conn->data = data;
conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
ConnectionStore(data, conn);
/*
* Setup whatever necessary for a resumed transfer
*/
result = setup_range(data);
if(result) {
DEBUGASSERT(conn->handler->done);
/* we ignore the return code for the protocol-specific DONE */
(void)conn->handler->done(conn, result, FALSE);
goto out;
}
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
-1, NULL); /* no upload */
}
/* since we skip do_init() */
do_init(conn);
goto out;
}
#endif
/* Get a cloned copy of the SSL config situation stored in the
connection struct. But to get this going nicely, we must first make
sure that the strings in the master copy are pointing to the correct
strings in the session handle strings array!
Keep in mind that the pointers in the master copy are pointing to strings
that will be freed as part of the SessionHandle struct, but all cloned
copies will be separately allocated.
*/
data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
#ifdef USE_TLS_SRP
data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
#endif
if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config)) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
/*************************************************************
* Check the current list of connections to see if we can
* re-use an already existing one or if we have to create a
* new one.
*************************************************************/
/* reuse_fresh is TRUE if we are told to use a new connection by force, but
we only acknowledge this option if this is not a re-used connection
already (which happens due to follow-location or during a HTTP
authentication phase). */
if(data->set.reuse_fresh && !data->state.this_is_a_follow)
reuse = FALSE;
else
reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse);
/* If we found a reusable connection, we may still want to
open a new connection if we are pipelining. */
if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
if(pipelen > 0) {
infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
conn_temp->connection_id, pipelen);
if(conn_temp->bundle->num_connections < max_host_connections &&
data->state.conn_cache->num_connections < max_total_connections) {
/* We want a new connection anyway */
reuse = FALSE;
infof(data, "We can reuse, but we want a new connection anyway\n");
}
}
}
if(reuse) {
/*
* We already have a connection for this, we got the former connection
* in the conn_temp variable and thus we need to cleanup the one we
* just allocated before we can move along and use the previously
* existing one.
*/
conn_temp->inuse = TRUE; /* mark this as being in use so that no other
handle in a multi stack may nick it */
reuse_conn(conn, conn_temp);
free(conn); /* we don't need this anymore */
conn = conn_temp;
*in_connect = conn;
/* set a pointer to the hostname we display */
fix_hostname(data, conn, &conn->host);
infof(data, "Re-using existing connection! (#%ld) with host %s\n",
conn->connection_id,
conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
}
else {
/* We have decided that we want a new connection. However, we may not
be able to do that if we have reached the limit of how many
connections we are allowed to open. */
struct connectbundle *bundle;
bundle = Curl_conncache_find_bundle(data->state.conn_cache,
conn->host.name);
if(max_host_connections > 0 && bundle &&
(bundle->num_connections >= max_host_connections)) {
struct connectdata *conn_candidate;
/* The bundle is full. Let's see if we can kill a connection. */
conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
if(conn_candidate) {
/* Set the connection's owner correctly, then kill it */
conn_candidate->data = data;
(void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
}
else
no_connections_available = TRUE;
}
if(max_total_connections > 0 &&
(data->state.conn_cache->num_connections >= max_total_connections)) {
struct connectdata *conn_candidate;
/* The cache is full. Let's see if we can kill a connection. */
conn_candidate = find_oldest_idle_connection(data);
if(conn_candidate) {
/* Set the connection's owner correctly, then kill it */
conn_candidate->data = data;
(void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
}
else
no_connections_available = TRUE;
}
if(no_connections_available) {
infof(data, "No connections available.\n");
conn_free(conn);
*in_connect = NULL;
result = CURLE_NO_CONNECTION_AVAILABLE;
goto out;
}
else {
/*
* This is a brand new connection, so let's store it in the connection
* cache of ours!
*/
ConnectionStore(data, conn);
}
}
/* Mark the connection as used */
conn->inuse = TRUE;
/* Setup and init stuff before DO starts, in preparing for the transfer. */
do_init(conn);
/*
* Setup whatever necessary for a resumed transfer
*/
result = setup_range(data);
if(result)
goto out;
/* Continue connectdata initialization here. */
/*
* Inherit the proper values from the urldata struct AFTER we have arranged
* the persistent connection stuff
*/
conn->fread_func = data->set.fread_func;
conn->fread_in = data->set.in;
conn->seek_func = data->set.seek_func;
conn->seek_client = data->set.seek_client;
/*************************************************************
* Resolve the address of the server or proxy
*************************************************************/
result = resolve_server(data, conn, async);
out:
Curl_safefree(options);
Curl_safefree(passwd);
Curl_safefree(user);
Curl_safefree(proxy);
return result;
}
/* Curl_setup_conn() is called after the name resolve initiated in
* create_conn() is all done.
*
* Curl_setup_conn() also handles reused connections
*
* conn->data MUST already have been setup fine (in create_conn)
*/
CURLcode Curl_setup_conn(struct connectdata *conn,
bool *protocol_done)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
Curl_pgrsTime(data, TIMER_NAMELOOKUP);
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* nothing to setup when not using a network */
*protocol_done = TRUE;
return result;
}
*protocol_done = FALSE; /* default to not done */
/* set proxy_connect_closed to false unconditionally already here since it
is used strictly to provide extra information to a parent function in the
case of proxy CONNECT failures and we must make sure we don't have it
lingering set from a previous invoke */
conn->bits.proxy_connect_closed = FALSE;
/*
* Set user-agent. Used for HTTP, but since we can attempt to tunnel
* basically anything through a http proxy we can't limit this based on
* protocol.
*/
if(data->set.str[STRING_USERAGENT]) {
Curl_safefree(conn->allocptr.uagent);
conn->allocptr.uagent =
aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
if(!conn->allocptr.uagent)
return CURLE_OUT_OF_MEMORY;
}
data->req.headerbytecount = 0;
#ifdef CURL_DO_LINEEND_CONV
data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
#endif /* CURL_DO_LINEEND_CONV */
/* set start time here for timeout purposes in the connect procedure, it
is later set again for the progress meter purpose */
conn->now = Curl_tvnow();
if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
result = Curl_connecthost(conn, conn->dns_entry);
if(result)
return result;
}
else {
Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
*protocol_done = TRUE;
Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
Curl_verboseconnect(conn);
}
conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
set this here perhaps a second time */
#ifdef __EMX__
/*
* This check is quite a hack. We're calling _fsetmode to fix the problem
* with fwrite converting newline characters (you get mangled text files,
* and corrupted binary files when you download to stdout and redirect it to
* a file).
*/
if((data->set.out)->_handle == NULL) {
_fsetmode(stdout, "b");
}
#endif
return result;
}
CURLcode Curl_connect(struct SessionHandle *data,
struct connectdata **in_connect,
bool *asyncp,
bool *protocol_done)
{
CURLcode code;
*asyncp = FALSE; /* assume synchronous resolves by default */
/* call the stuff that needs to be called */
code = create_conn(data, in_connect, asyncp);
if(CURLE_OK == code) {
/* no error */
if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
/* pipelining */
*protocol_done = TRUE;
else if(!*asyncp) {
/* DNS resolution is done: that's either because this is a reused
connection, in which case DNS was unnecessary, or because DNS
really did finish already (synch resolver/fast async resolve) */
code = Curl_setup_conn(*in_connect, protocol_done);
}
}
if(code == CURLE_NO_CONNECTION_AVAILABLE) {
*in_connect = NULL;
return code;
}
if(code && *in_connect) {
/* We're not allowed to return failure with memory left allocated
in the connectdata struct, free those here */
Curl_disconnect(*in_connect, FALSE); /* close the connection */
*in_connect = NULL; /* return a NULL */
}
return code;
}
CURLcode Curl_done(struct connectdata **connp,
CURLcode status, /* an error if this is called after an
error was detected */
bool premature)
{
CURLcode result;
struct connectdata *conn;
struct SessionHandle *data;
DEBUGASSERT(*connp);
conn = *connp;
data = conn->data;
if(conn->bits.done)
/* Stop if Curl_done() has already been called */
return CURLE_OK;
Curl_getoff_all_pipelines(data, conn);
if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
!data->set.reuse_forbid &&
!conn->bits.close))
/* Stop if pipeline is not empty and we do not have to close
connection. */
return CURLE_OK;
conn->bits.done = TRUE; /* called just now! */
/* Cleanup possible redirect junk */
if(data->req.newurl) {
free(data->req.newurl);
data->req.newurl = NULL;
}
if(data->req.location) {
free(data->req.location);
data->req.location = NULL;
}
Curl_resolver_cancel(conn);
if(conn->dns_entry) {
Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
conn->dns_entry = NULL;
}
switch(status) {
case CURLE_ABORTED_BY_CALLBACK:
case CURLE_READ_ERROR:
case CURLE_WRITE_ERROR:
/* When we're aborted due to a callback return code it basically have to
be counted as premature as there is trouble ahead if we don't. We have
many callbacks and protocols work differently, we could potentially do
this more fine-grained in the future. */
premature = TRUE;
default:
break;
}
/* this calls the protocol-specific function pointer previously set */
if(conn->handler->done)
result = conn->handler->done(conn, status, premature);
else
result = CURLE_OK;
if(Curl_pgrsDone(conn) && !result)
result = CURLE_ABORTED_BY_CALLBACK;
/* if the transfer was completed in a paused state there can be buffered
data left to write and then kill */
if(data->state.tempwrite) {
free(data->state.tempwrite);
data->state.tempwrite = NULL;
}
/* if data->set.reuse_forbid is TRUE, it means the libcurl client has
forced us to close this no matter what we think.
if conn->bits.close is TRUE, it means that the connection should be
closed in spite of all our efforts to be nice, due to protocol
restrictions in our or the server's end
if premature is TRUE, it means this connection was said to be DONE before
the entire request operation is complete and thus we can't know in what
state it is for re-using, so we're forced to close it. In a perfect world
we can add code that keep track of if we really must close it here or not,
but currently we have no such detail knowledge.
*/
if(data->set.reuse_forbid || conn->bits.close || premature) {
CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
/* If we had an error already, make sure we return that one. But
if we got a new error, return that. */
if(!result && res2)
result = res2;
}
else {
/* the connection is no longer in use */
if(ConnectionDone(data, conn)) {
/* remember the most recently used connection */
data->state.lastconnect = conn;
infof(data, "Connection #%ld to host %s left intact\n",
conn->connection_id,
conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
}
else
data->state.lastconnect = NULL;
}
*connp = NULL; /* to make the caller of this function better detect that
this was either closed or handed over to the connection
cache here, and therefore cannot be used from this point on
*/
Curl_free_request_state(data);
return result;
}
/*
* do_init() inits the readwrite session. This is inited each time (in the DO
* function before the protocol-specific DO functions are invoked) for a
* transfer, sometimes multiple times on the same SessionHandle. Make sure
* nothing in here depends on stuff that are setup dynamically for the
* transfer.
*/
static CURLcode do_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct SingleRequest *k = &data->req;
conn->bits.done = FALSE; /* Curl_done() is not called yet */
conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
data->state.expect100header = FALSE;
if(data->set.opt_no_body)
/* in HTTP lingo, no body means using the HEAD request... */
data->set.httpreq = HTTPREQ_HEAD;
else if(HTTPREQ_HEAD == data->set.httpreq)
/* ... but if unset there really is no perfect method that is the
"opposite" of HEAD but in reality most people probably think GET
then. The important thing is that we can't let it remain HEAD if the
opt_no_body is set FALSE since then we'll behave wrong when getting
HTTP. */
data->set.httpreq = HTTPREQ_GET;
k->start = Curl_tvnow(); /* start time */
k->now = k->start; /* current time is now */
k->header = TRUE; /* assume header */
k->bytecount = 0;
k->buf = data->state.buffer;
k->uploadbuf = data->state.uploadbuffer;
k->hbufp = data->state.headerbuff;
k->ignorebody=FALSE;
Curl_speedinit(data);
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
return CURLE_OK;
}
/*
* do_complete is called when the DO actions are complete.
*
* We init chunking and trailer bits to their default values here immediately
* before receiving any header data for the current request in the pipeline.
*/
static void do_complete(struct connectdata *conn)
{
conn->data->req.chunk=FALSE;
conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
conn->sockfd:conn->writesockfd)+1;
Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
}
CURLcode Curl_do(struct connectdata **connp, bool *done)
{
CURLcode result=CURLE_OK;
struct connectdata *conn = *connp;
struct SessionHandle *data = conn->data;
if(conn->handler->do_it) {
/* generic protocol-specific function pointer set in curl_connect() */
result = conn->handler->do_it(conn, done);
/* This was formerly done in transfer.c, but we better do it here */
if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
/*
* If the connection is using an easy handle, call reconnect
* to re-establish the connection. Otherwise, let the multi logic
* figure out how to re-establish the connection.
*/
if(!data->multi) {
result = Curl_reconnect_request(connp);
if(result == CURLE_OK) {
/* ... finally back to actually retry the DO phase */
conn = *connp; /* re-assign conn since Curl_reconnect_request
creates a new connection */
result = conn->handler->do_it(conn, done);
}
}
else
return result;
}
if((result == CURLE_OK) && *done)
/* do_complete must be called after the protocol-specific DO function */
do_complete(conn);
}
return result;
}
/*
* Curl_do_more() is called during the DO_MORE multi state. It is basically a
* second stage DO state which (wrongly) was introduced to support FTP's
* second connection.
*
* TODO: A future libcurl should be able to work away this state.
*
* 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
* DOING state there's more work to do!
*/
CURLcode Curl_do_more(struct connectdata *conn, int *complete)
{
CURLcode result=CURLE_OK;
*complete = 0;
if(conn->handler->do_more)
result = conn->handler->do_more(conn, complete);
if(!result && (*complete == 1))
/* do_complete must be called after the protocol-specific DO function */
do_complete(conn);
return result;
}
| mit |
CallForSanity/glviz | extern/sdl/src/core/winrt/SDL_winrtapp_direct3d.cpp | 6 | 29587 | /*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
/* Standard C++11 includes */
#include <functional>
#include <string>
#include <sstream>
using namespace std;
/* Windows includes */
#include "ppltasks.h"
using namespace concurrency;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Devices::Input;
using namespace Windows::Graphics::Display;
using namespace Windows::Foundation;
using namespace Windows::System;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
using namespace Windows::Phone::UI::Input;
#endif
/* SDL includes */
extern "C" {
#include "../../SDL_internal.h"
#include "SDL_assert.h"
#include "SDL_events.h"
#include "SDL_hints.h"
#include "SDL_log.h"
#include "SDL_main.h"
#include "SDL_stdinc.h"
#include "SDL_render.h"
#include "../../video/SDL_sysvideo.h"
//#include "../../SDL_hints_c.h"
#include "../../events/SDL_events_c.h"
#include "../../events/SDL_keyboard_c.h"
#include "../../events/SDL_mouse_c.h"
#include "../../events/SDL_windowevents_c.h"
#include "../../render/SDL_sysrender.h"
#include "../windows/SDL_windows.h"
}
#include "../../video/winrt/SDL_winrtevents_c.h"
#include "../../video/winrt/SDL_winrtvideo_cpp.h"
#include "SDL_winrtapp_common.h"
#include "SDL_winrtapp_direct3d.h"
#if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
/* Calling IDXGIDevice3::Trim on the active Direct3D 11.x device is necessary
* when Windows 8.1 apps are about to get suspended.
*/
extern "C" void D3D11_Trim(SDL_Renderer *);
#endif
// Compile-time debugging options:
// To enable, uncomment; to disable, comment them out.
//#define LOG_POINTER_EVENTS 1
//#define LOG_WINDOW_EVENTS 1
//#define LOG_ORIENTATION_EVENTS 1
// HACK, DLudwig: record a reference to the global, WinRT 'app'/view.
// SDL/WinRT will use this throughout its code.
//
// TODO, WinRT: consider replacing SDL_WinRTGlobalApp with something
// non-global, such as something created inside
// SDL_InitSubSystem(SDL_INIT_VIDEO), or something inside
// SDL_CreateWindow().
SDL_WinRTApp ^ SDL_WinRTGlobalApp = nullptr;
ref class SDLApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
{
public:
virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
};
IFrameworkView^ SDLApplicationSource::CreateView()
{
// TODO, WinRT: see if this function (CreateView) can ever get called
// more than once. For now, just prevent it from ever assigning
// SDL_WinRTGlobalApp more than once.
SDL_assert(!SDL_WinRTGlobalApp);
SDL_WinRTApp ^ app = ref new SDL_WinRTApp();
if (!SDL_WinRTGlobalApp)
{
SDL_WinRTGlobalApp = app;
}
return app;
}
int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **))
{
WINRT_SDLAppEntryPoint = mainFunction;
auto direct3DApplicationSource = ref new SDLApplicationSource();
CoreApplication::Run(direct3DApplicationSource);
return 0;
}
static void WINRT_SetDisplayOrientationsPreference(void *userdata, const char *name, const char *oldValue, const char *newValue)
{
SDL_assert(SDL_strcmp(name, SDL_HINT_ORIENTATIONS) == 0);
/* HACK: prevent SDL from altering an app's .appxmanifest-set orientation
* from being changed on startup, by detecting when SDL_HINT_ORIENTATIONS
* is getting registered.
*
* TODO, WinRT: consider reading in an app's .appxmanifest file, and apply its orientation when 'newValue == NULL'.
*/
if ((oldValue == NULL) && (newValue == NULL)) {
return;
}
// Start with no orientation flags, then add each in as they're parsed
// from newValue.
unsigned int orientationFlags = 0;
if (newValue) {
std::istringstream tokenizer(newValue);
while (!tokenizer.eof()) {
std::string orientationName;
std::getline(tokenizer, orientationName, ' ');
if (orientationName == "LandscapeLeft") {
orientationFlags |= (unsigned int) DisplayOrientations::LandscapeFlipped;
} else if (orientationName == "LandscapeRight") {
orientationFlags |= (unsigned int) DisplayOrientations::Landscape;
} else if (orientationName == "Portrait") {
orientationFlags |= (unsigned int) DisplayOrientations::Portrait;
} else if (orientationName == "PortraitUpsideDown") {
orientationFlags |= (unsigned int) DisplayOrientations::PortraitFlipped;
}
}
}
// If no valid orientation flags were specified, use a reasonable set of defaults:
if (!orientationFlags) {
// TODO, WinRT: consider seeing if an app's default orientation flags can be found out via some API call(s).
orientationFlags = (unsigned int) ( \
DisplayOrientations::Landscape |
DisplayOrientations::LandscapeFlipped |
DisplayOrientations::Portrait |
DisplayOrientations::PortraitFlipped);
}
// Set the orientation/rotation preferences. Please note that this does
// not constitute a 100%-certain lock of a given set of possible
// orientations. According to Microsoft's documentation on WinRT [1]
// when a device is not capable of being rotated, Windows may ignore
// the orientation preferences, and stick to what the device is capable of
// displaying.
//
// [1] Documentation on the 'InitialRotationPreference' setting for a
// Windows app's manifest file describes how some orientation/rotation
// preferences may be ignored. See
// http://msdn.microsoft.com/en-us/library/windows/apps/hh700343.aspx
// for details. Microsoft's "Display orientation sample" also gives an
// outline of how Windows treats device rotation
// (http://code.msdn.microsoft.com/Display-Orientation-Sample-19a58e93).
WINRT_DISPLAY_PROPERTY(AutoRotationPreferences) = (DisplayOrientations) orientationFlags;
}
static void
WINRT_ProcessWindowSizeChange()
{
SDL_VideoDevice *_this = SDL_GetVideoDevice();
// Make the new window size be the one true fullscreen mode.
// This change was initially done, in part, to allow the Direct3D 11.1
// renderer to receive window-resize events as a device rotates.
// Before, rotating a device from landscape, to portrait, and then
// back to landscape would cause the Direct3D 11.1 swap buffer to
// not get resized appropriately. SDL would, on the rotation from
// landscape to portrait, re-resize the SDL window to it's initial
// size (landscape). On the subsequent rotation, SDL would drop the
// window-resize event as it appeared the SDL window didn't change
// size, and the Direct3D 11.1 renderer wouldn't resize its swap
// chain.
SDL_DisplayMode newDisplayMode;
if (WINRT_CalcDisplayModeUsingNativeWindow(&newDisplayMode) != 0) {
return;
}
// Make note of the old display mode, and it's old driverdata.
SDL_DisplayMode oldDisplayMode;
SDL_zero(oldDisplayMode);
if (_this) {
oldDisplayMode = _this->displays[0].desktop_mode;
}
// Setup the new display mode in the appropriate spots.
if (_this) {
// Make a full copy of the display mode for display_modes[0],
// one with with a separately malloced 'driverdata' field.
// SDL_VideoQuit(), if called, will attempt to free the driverdata
// fields in 'desktop_mode' and each entry in the 'display_modes'
// array.
if (_this->displays[0].display_modes[0].driverdata) {
// Free the previous mode's memory
SDL_free(_this->displays[0].display_modes[0].driverdata);
_this->displays[0].display_modes[0].driverdata = NULL;
}
if (WINRT_DuplicateDisplayMode(&(_this->displays[0].display_modes[0]), &newDisplayMode) != 0) {
// Uh oh, something went wrong. A malloc call probably failed.
SDL_free(newDisplayMode.driverdata);
return;
}
// Install 'newDisplayMode' into 'current_mode' and 'desktop_mode'.
_this->displays[0].current_mode = newDisplayMode;
_this->displays[0].desktop_mode = newDisplayMode;
}
if (WINRT_GlobalSDLWindow) {
// If the window size changed, send a resize event to SDL and its host app:
int window_w = 0;
int window_h = 0;
SDL_GetWindowSize(WINRT_GlobalSDLWindow, &window_w, &window_h);
if ((window_w != newDisplayMode.w) || (window_h != newDisplayMode.h)) {
SDL_SendWindowEvent(
WINRT_GlobalSDLWindow,
SDL_WINDOWEVENT_RESIZED,
newDisplayMode.w,
newDisplayMode.h);
} else {
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
// HACK: Make sure that orientation changes
// lead to the Direct3D renderer's viewport getting updated:
//
// For some reason, this doesn't seem to need to be done on Windows 8.x,
// even when going from Landscape to LandscapeFlipped. It only seems to
// be needed on Windows Phone, at least when I tested on my devices.
// I'm not currently sure why this is, but it seems to work fine. -- David L.
//
// TODO, WinRT: do more extensive research into why orientation changes on Win 8.x don't need D3D changes, or if they might, in some cases
const DisplayOrientations oldOrientation = ((SDL_DisplayModeData *)oldDisplayMode.driverdata)->currentOrientation;
const DisplayOrientations newOrientation = ((SDL_DisplayModeData *)newDisplayMode.driverdata)->currentOrientation;
if (oldOrientation != newOrientation)
{
SDL_SendWindowEvent(
WINRT_GlobalSDLWindow,
SDL_WINDOWEVENT_SIZE_CHANGED,
newDisplayMode.w,
newDisplayMode.h);
}
#endif
}
}
// Finally, free the 'driverdata' field of the old 'desktop_mode'.
if (oldDisplayMode.driverdata) {
SDL_free(oldDisplayMode.driverdata);
oldDisplayMode.driverdata = NULL;
}
}
SDL_WinRTApp::SDL_WinRTApp() :
m_windowClosed(false),
m_windowVisible(true)
{
}
void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView)
{
applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &SDL_WinRTApp::OnActivated);
CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &SDL_WinRTApp::OnSuspending);
CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnResuming);
CoreApplication::Exiting +=
ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnExiting);
}
#if NTDDI_VERSION > NTDDI_WIN8
void SDL_WinRTApp::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
#else
void SDL_WinRTApp::OnOrientationChanged(Object^ sender)
#endif
{
#if LOG_ORIENTATION_EVENTS==1
CoreWindow^ window = CoreWindow::GetForCurrentThread();
if (window) {
SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Size={%f,%f}\n",
__FUNCTION__,
WINRT_DISPLAY_PROPERTY(CurrentOrientation),
WINRT_DISPLAY_PROPERTY(NativeOrientation),
WINRT_DISPLAY_PROPERTY(AutoRotationPreferences),
window->Bounds.Width,
window->Bounds.Height);
} else {
SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d\n",
__FUNCTION__,
WINRT_DISPLAY_PROPERTY(CurrentOrientation),
WINRT_DISPLAY_PROPERTY(NativeOrientation),
WINRT_DISPLAY_PROPERTY(AutoRotationPreferences));
}
#endif
WINRT_ProcessWindowSizeChange();
}
void SDL_WinRTApp::SetWindow(CoreWindow^ window)
{
#if LOG_WINDOW_EVENTS==1
SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window Size={%f,%f}\n",
__FUNCTION__,
WINRT_DISPLAY_PROPERTY(CurrentOrientation),
WINRT_DISPLAY_PROPERTY(NativeOrientation),
WINRT_DISPLAY_PROPERTY(AutoRotationPreferences),
window->Bounds.Width,
window->Bounds.Height);
#endif
window->SizeChanged +=
ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &SDL_WinRTApp::OnWindowSizeChanged);
window->VisibilityChanged +=
ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &SDL_WinRTApp::OnVisibilityChanged);
window->Closed +=
ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &SDL_WinRTApp::OnWindowClosed);
#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
#endif
window->PointerPressed +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerPressed);
window->PointerMoved +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerMoved);
window->PointerReleased +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerReleased);
window->PointerWheelChanged +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerWheelChanged);
#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
// Retrieves relative-only mouse movements:
Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &SDL_WinRTApp::OnMouseMoved);
#endif
window->KeyDown +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyDown);
window->KeyUp +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyUp);
window->CharacterReceived +=
ref new TypedEventHandler<CoreWindow^, CharacterReceivedEventArgs^>(this, &SDL_WinRTApp::OnCharacterReceived);
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
HardwareButtons::BackPressed +=
ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
#endif
#if NTDDI_VERSION > NTDDI_WIN8
DisplayInformation::GetForCurrentView()->OrientationChanged +=
ref new TypedEventHandler<Windows::Graphics::Display::DisplayInformation^, Object^>(this, &SDL_WinRTApp::OnOrientationChanged);
#else
DisplayProperties::OrientationChanged +=
ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged);
#endif
// Register the hint, SDL_HINT_ORIENTATIONS, with SDL.
// TODO, WinRT: see if an app's default orientation can be found out via WinRT API(s), then set the initial value of SDL_HINT_ORIENTATIONS accordingly.
SDL_AddHintCallback(SDL_HINT_ORIENTATIONS, WINRT_SetDisplayOrientationsPreference, NULL);
#if WINAPI_FAMILY == WINAPI_FAMILY_APP // for Windows 8/8.1/RT apps... (and not Phone apps)
// Make sure we know when a user has opened the app's settings pane.
// This is needed in order to display a privacy policy, which needs
// to be done for network-enabled apps, as per Windows Store requirements.
using namespace Windows::UI::ApplicationSettings;
SettingsPane::GetForCurrentView()->CommandsRequested +=
ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>
(this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
#endif
}
void SDL_WinRTApp::Load(Platform::String^ entryPoint)
{
}
void SDL_WinRTApp::Run()
{
SDL_SetMainReady();
if (WINRT_SDLAppEntryPoint)
{
// TODO, WinRT: pass the C-style main() a reasonably realistic
// representation of command line arguments.
int argc = 0;
char **argv = NULL;
WINRT_SDLAppEntryPoint(argc, argv);
}
}
static bool IsSDLWindowEventPending(SDL_WindowEventID windowEventID)
{
SDL_Event events[128];
const int count = SDL_PeepEvents(events, sizeof(events)/sizeof(SDL_Event), SDL_PEEKEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT);
for (int i = 0; i < count; ++i) {
if (events[i].window.event == windowEventID) {
return true;
}
}
return false;
}
bool SDL_WinRTApp::ShouldWaitForAppResumeEvents()
{
/* Don't wait if the app is visible: */
if (m_windowVisible) {
return false;
}
/* Don't wait until the window-hide events finish processing.
* Do note that if an app-suspend event is sent (as indicated
* by SDL_APP_WILLENTERBACKGROUND and SDL_APP_DIDENTERBACKGROUND
* events), then this code may be a moot point, as WinRT's
* own event pump (aka ProcessEvents()) will pause regardless
* of what we do here. This happens on Windows Phone 8, to note.
* Windows 8.x apps, on the other hand, may get a chance to run
* these.
*/
if (IsSDLWindowEventPending(SDL_WINDOWEVENT_HIDDEN)) {
return false;
} else if (IsSDLWindowEventPending(SDL_WINDOWEVENT_FOCUS_LOST)) {
return false;
} else if (IsSDLWindowEventPending(SDL_WINDOWEVENT_MINIMIZED)) {
return false;
}
return true;
}
void SDL_WinRTApp::PumpEvents()
{
if (!m_windowClosed) {
if (!ShouldWaitForAppResumeEvents()) {
/* This is the normal way in which events should be pumped.
* 'ProcessAllIfPresent' will make ProcessEvents() process anywhere
* from zero to N events, and will then return.
*/
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
} else {
/* This style of event-pumping, with 'ProcessOneAndAllPending',
* will cause anywhere from one to N events to be processed. If
* at least one event is processed, the call will return. If
* no events are pending, then the call will wait until one is
* available, and will not return (to the caller) until this
* happens! This should only occur when the app is hidden.
*/
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
}
}
}
void SDL_WinRTApp::Uninitialize()
{
}
#if WINAPI_FAMILY == WINAPI_FAMILY_APP
void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
Windows::UI::ApplicationSettings::SettingsPane ^p,
Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args)
{
using namespace Platform;
using namespace Windows::UI::ApplicationSettings;
using namespace Windows::UI::Popups;
String ^privacyPolicyURL = nullptr; // a URL to an app's Privacy Policy
String ^privacyPolicyLabel = nullptr; // label/link text
const char *tmpHintValue = NULL; // SDL_GetHint-retrieved value, used immediately
wchar_t *tmpStr = NULL; // used for UTF8 to UCS2 conversion
// Setup a 'Privacy Policy' link, if one is available (via SDL_GetHint):
tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_URL);
if (tmpHintValue && tmpHintValue[0] != '\0') {
// Convert the privacy policy's URL to UCS2:
tmpStr = WIN_UTF8ToString(tmpHintValue);
privacyPolicyURL = ref new String(tmpStr);
SDL_free(tmpStr);
// Optionally retrieve custom label-text for the link. If this isn't
// available, a default value will be used instead.
tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_LABEL);
if (tmpHintValue && tmpHintValue[0] != '\0') {
tmpStr = WIN_UTF8ToString(tmpHintValue);
privacyPolicyLabel = ref new String(tmpStr);
SDL_free(tmpStr);
} else {
privacyPolicyLabel = ref new String(L"Privacy Policy");
}
// Register the link, along with a handler to be called if and when it is
// clicked:
auto cmd = ref new SettingsCommand(L"privacyPolicy", privacyPolicyLabel,
ref new UICommandInvokedHandler([=](IUICommand ^) {
Windows::System::Launcher::LaunchUriAsync(ref new Uri(privacyPolicyURL));
}));
args->Request->ApplicationCommands->Append(cmd);
}
}
#endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
{
#if LOG_WINDOW_EVENTS==1
SDL_Log("%s, size={%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n",
__FUNCTION__,
args->Size.Width, args->Size.Height,
WINRT_DISPLAY_PROPERTY(CurrentOrientation),
WINRT_DISPLAY_PROPERTY(NativeOrientation),
WINRT_DISPLAY_PROPERTY(AutoRotationPreferences),
(WINRT_GlobalSDLWindow ? "yes" : "no"));
#endif
WINRT_ProcessWindowSizeChange();
}
void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
#if LOG_WINDOW_EVENTS==1
SDL_Log("%s, visible?=%s, WINRT_GlobalSDLWindow?=%s\n",
__FUNCTION__,
(args->Visible ? "yes" : "no"),
(WINRT_GlobalSDLWindow ? "yes" : "no"));
#endif
m_windowVisible = args->Visible;
if (WINRT_GlobalSDLWindow) {
SDL_bool wasSDLWindowSurfaceValid = WINRT_GlobalSDLWindow->surface_valid;
if (args->Visible) {
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SHOWN, 0, 0);
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_RESTORED, 0, 0);
} else {
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_HIDDEN, 0, 0);
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
}
// HACK: Prevent SDL's window-hide handling code, which currently
// triggers a fake window resize (possibly erronously), from
// marking the SDL window's surface as invalid.
//
// A better solution to this probably involves figuring out if the
// fake window resize can be prevented.
WINRT_GlobalSDLWindow->surface_valid = wasSDLWindowSurfaceValid;
}
}
void SDL_WinRTApp::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
#if LOG_WINDOW_EVENTS==1
SDL_Log("%s\n", __FUNCTION__);
#endif
m_windowClosed = true;
}
void SDL_WinRTApp::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
CoreWindow::GetForCurrentThread()->Activate();
}
void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
// Save app state asynchronously after requesting a deferral. Holding a deferral
// indicates that the application is busy performing suspending operations. Be
// aware that a deferral may not be held indefinitely. After about five seconds,
// the app will be forced to exit.
// ... but first, let the app know it's about to go to the background.
// The separation of events may be important, given that the deferral
// runs in a separate thread. This'll make SDL_APP_WILLENTERBACKGROUND
// the only event among the two that runs in the main thread. Given
// that a few WinRT operations can only be done from the main thread
// (things that access the WinRT CoreWindow are one example of this),
// this could be important.
SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
create_task([this, deferral]()
{
// Send an app did-enter-background event immediately to observers.
// CoreDispatcher::ProcessEvents, which is the backbone on which
// SDL_WinRTApp::PumpEvents is built, will not return to its caller
// once it sends out a suspend event. Any events posted to SDL's
// event queue won't get received until the WinRT app is resumed.
// SDL_AddEventWatch() may be used to receive app-suspend events on
// WinRT.
SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
// Let the Direct3D 11 renderer prepare for the app to be backgrounded.
// This is necessary for Windows 8.1, possibly elsewhere in the future.
// More details at: http://msdn.microsoft.com/en-us/library/windows/apps/Hh994929.aspx
#if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
if (WINRT_GlobalSDLWindow) {
SDL_Renderer * renderer = SDL_GetRenderer(WINRT_GlobalSDLWindow);
if (renderer && (SDL_strcmp(renderer->info.name, "direct3d11") == 0)) {
D3D11_Trim(renderer);
}
}
#endif
deferral->Complete();
});
}
void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
// Restore any data or state that was unloaded on suspend. By default, data
// and state are persisted when resuming from suspend. Note that these events
// do not occur if the app was previously terminated.
SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
}
void SDL_WinRTApp::OnExiting(Platform::Object^ sender, Platform::Object^ args)
{
SDL_SendAppEvent(SDL_APP_TERMINATING);
}
static void
WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
{
Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint;
SDL_Log("%s: Position={%f,%f}, Transformed Pos={%f, %f}, MouseWheelDelta=%d, FrameId=%d, PointerId=%d, SDL button=%d\n",
header,
pt->Position.X, pt->Position.Y,
transformedPoint.X, transformedPoint.Y,
pt->Properties->MouseWheelDelta,
pt->FrameId,
pt->PointerId,
WINRT_GetSDLButtonForPointerPoint(pt));
}
void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
#if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
#endif
WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
}
void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
#if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
#endif
WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
}
void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
{
#if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
#endif
WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
}
void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args)
{
#if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
#endif
WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
}
void SDL_WinRTApp::OnMouseMoved(MouseDevice^ mouseDevice, MouseEventArgs^ args)
{
WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args);
}
void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
{
WINRT_ProcessKeyDownEvent(args);
}
void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
{
WINRT_ProcessKeyUpEvent(args);
}
void SDL_WinRTApp::OnCharacterReceived(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CharacterReceivedEventArgs^ args)
{
WINRT_ProcessCharacterReceivedEvent(args);
}
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
{
SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_AC_BACK);
SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_AC_BACK);
const char *hint = SDL_GetHint(SDL_HINT_WINRT_HANDLE_BACK_BUTTON);
if (hint) {
if (*hint == '1') {
args->Handled = true;
}
}
}
#endif
| mit |
Marpessa/tabletennis | app/Resources/utilities/optipng-0.7.5/src/pngxtern/pngxio.c | 6 | 6686 | /*
* pngxio.c - libpng extension: I/O state query.
*
* Copyright (C) 2003-2011 Cosmin Truta.
* This software is distributed under the same licensing and warranty terms
* as libpng.
*
* NOTE:
* The functionality provided in this module has "graduated", and is now
* part of libpng. The original code, retrofitted as a back-port, has
* limitations: it is thread-unsafe, and it only allows one png_ptr object
* for reading and one for writing.
*
* CAUTION:
* libpng-1.4.5 is the earliest version whose I/O state implementation
* can be used reliably.
*/
#include "pngxutil.h"
#define PNGX_INTERNAL
#include "pngxpriv.h"
#if PNG_LIBPNG_VER < 10405
static png_structp _pngxio_read_ptr;
static png_structp _pngxio_write_ptr;
static png_rw_ptr _pngxio_read_fn;
static png_rw_ptr _pngxio_write_fn;
static int _pngxio_read_io_state;
static int _pngxio_write_io_state;
static png_byte _pngxio_read_crt_chunk_hdr[9];
static png_byte _pngxio_write_crt_chunk_hdr[9];
static unsigned int _pngxio_read_crt_chunk_hdr_len;
static unsigned int _pngxio_write_crt_chunk_hdr_len;
static png_uint_32 _pngxio_read_crt_len;
static png_uint_32 _pngxio_write_crt_len;
static const char *_pngxio_errmsg_invalid_argument =
"[PNGXIO internal] invalid argument";
/* Update io_state and call the user-supplied read/write functions. */
void /* PRIVATE */
pngxio_read_write(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_rw_ptr io_data_fn;
int *io_state_ptr;
int io_state_op;
png_byte *crt_chunk_hdr;
unsigned int *crt_chunk_hdr_len_ptr;
png_uint_32 *crt_len_ptr;
if (png_ptr == _pngxio_read_ptr)
{
io_data_fn = _pngxio_read_fn;
io_state_ptr = &_pngxio_read_io_state;
io_state_op = PNGX_IO_READING;
crt_chunk_hdr = _pngxio_read_crt_chunk_hdr;
crt_chunk_hdr_len_ptr = &_pngxio_read_crt_chunk_hdr_len;
crt_len_ptr = &_pngxio_read_crt_len;
}
else if (png_ptr == _pngxio_write_ptr)
{
io_data_fn = _pngxio_write_fn;
io_state_ptr = &_pngxio_write_io_state;
io_state_op = PNGX_IO_WRITING;
crt_chunk_hdr = _pngxio_write_crt_chunk_hdr;
crt_chunk_hdr_len_ptr = &_pngxio_write_crt_chunk_hdr_len;
crt_len_ptr = &_pngxio_write_crt_len;
}
else
{
png_error(png_ptr, _pngxio_errmsg_invalid_argument);
/* NOTREACHED */
return;
}
switch (*io_state_ptr & PNGX_IO_MASK_LOC)
{
case PNGX_IO_SIGNATURE:
/* libpng must serialize the signature in a single I/O session. */
PNGX_ASSERT(length <= 8);
io_data_fn(png_ptr, data, length);
*io_state_ptr = io_state_op | PNGX_IO_CHUNK_HDR;
*crt_chunk_hdr_len_ptr = 0;
return;
case PNGX_IO_CHUNK_HDR:
/* libpng must serialize the chunk header in a single I/O session.
* (This was done in libpng-1.2.30, but regressed in libpng-1.4.0,
* so we cannot rely on it here.)
*/
PNGX_ASSERT(length == 4 || length == 8);
PNGX_ASSERT(length + *crt_chunk_hdr_len_ptr <= 8);
if (io_state_op == PNGX_IO_READING)
{
if (*crt_chunk_hdr_len_ptr == 0)
io_data_fn(png_ptr, crt_chunk_hdr, 8);
memcpy(data, crt_chunk_hdr + *crt_chunk_hdr_len_ptr, length);
*crt_chunk_hdr_len_ptr += length;
if (*crt_chunk_hdr_len_ptr < 8)
return;
*crt_len_ptr = png_get_uint_32(crt_chunk_hdr);
/* memcpy(png_ptr->chunk_name, crt_chunk_hdr + 4, 4); */
}
else /* io_state_op == PNGX_IO_WRITING */
{
memcpy(crt_chunk_hdr + *crt_chunk_hdr_len_ptr, data, length);
*crt_chunk_hdr_len_ptr += length;
if (*crt_chunk_hdr_len_ptr < 8)
return;
*crt_len_ptr = png_get_uint_32(crt_chunk_hdr);
/* memcpy(png_ptr->chunk_name, crt_chunk_hdr + 4, 4); */
io_data_fn(png_ptr, crt_chunk_hdr, 8);
}
*crt_chunk_hdr_len_ptr = 0;
*io_state_ptr = io_state_op | PNGX_IO_CHUNK_DATA;
return;
case PNGX_IO_CHUNK_DATA:
/* libpng may serialize the chunk data in multiple I/O sessions. */
if (length == 0)
return;
if (*crt_len_ptr > 0)
{
PNGX_ASSERT(length <= *crt_len_ptr);
io_data_fn(png_ptr, data, length);
*crt_len_ptr -= length;
return;
}
*io_state_ptr = io_state_op | PNGX_IO_CHUNK_CRC;
/* FALLTHROUGH */
case PNGX_IO_CHUNK_CRC:
/* libpng must serialize the chunk CRC in a single I/O session. */
PNGX_ASSERT(length == 4);
io_data_fn(png_ptr, data, 4);
*io_state_ptr = io_state_op | PNGX_IO_CHUNK_HDR;
return;
}
}
/* Get png_ptr->io_state. */
png_uint_32 PNGAPI
pngx_get_io_state(png_structp png_ptr)
{
png_uint_32 io_state;
if (png_ptr == _pngxio_read_ptr)
io_state = _pngxio_read_io_state;
else if (png_ptr == _pngxio_write_ptr)
io_state = _pngxio_write_io_state;
else
{
png_error(png_ptr, _pngxio_errmsg_invalid_argument);
/* NOTREACHED */
io_state = PNGX_IO_NONE;
}
return io_state;
}
/* Get png_ptr->chunk_name. */
png_bytep PNGAPI
pngx_get_io_chunk_name(png_structp png_ptr)
{
png_bytep chunk_name;
if (png_ptr == _pngxio_read_ptr)
chunk_name = _pngxio_read_crt_chunk_hdr + 4;
else if (png_ptr == _pngxio_write_ptr)
chunk_name = _pngxio_write_crt_chunk_hdr + 4;
else
{
png_error(png_ptr, _pngxio_errmsg_invalid_argument);
/* NOTREACHED */
chunk_name = NULL;
}
return chunk_name;
}
/* Wrap png_set_read_fn. */
void PNGAPI
pngx_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr read_data_fn)
{
_pngxio_read_ptr = png_ptr;
_pngxio_write_ptr = NULL;
_pngxio_read_fn = read_data_fn;
png_set_read_fn(png_ptr, io_ptr, pngxio_read_write);
_pngxio_read_io_state = PNGX_IO_READING | PNGX_IO_SIGNATURE;
}
/* Wrap png_set_write_fn. */
void PNGAPI
pngx_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
{
_pngxio_write_ptr = png_ptr;
_pngxio_read_ptr = NULL;
_pngxio_write_fn = write_data_fn;
png_set_write_fn(png_ptr, io_ptr, pngxio_read_write, output_flush_fn);
_pngxio_write_io_state = PNGX_IO_WRITING | PNGX_IO_SIGNATURE;
}
/* Wrap png_write_sig. */
void PNGAPI
pngx_write_sig(png_structp png_ptr)
{
#if PNG_LIBPNG_VER >= 10400
png_write_sig(png_ptr);
#else
/* png_write_sig is not exported from the earlier libpng versions. */
static png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
pngxio_read_write(png_ptr, png_signature, 8);
/* TODO: Take png_ptr->sig_bytes into account. */
#endif
}
#endif /* PNG_LIBPNG_VER < 10405 */
| mit |
MrPepperoni/Reaping2-1 | src/network/heal_taken_message.cpp | 6 | 1905 | #include "platform/i_platform.h"
#include "network/heal_taken_message.h"
#include "core/i_health_component.h"
#include <portable_iarchive.hpp>
#include <portable_oarchive.hpp>
namespace network {
HealTakenMessageSenderSystem::HealTakenMessageSenderSystem()
: MessageSenderSystem()
{
}
void HealTakenMessageSenderSystem::Init()
{
MessageSenderSystem::Init();
mOnHealTaken = EventServer<core::HealTakenEvent>::Get().Subscribe( boost::bind( &HealTakenMessageSenderSystem::OnHealTaken, this, _1 ) );
}
void HealTakenMessageSenderSystem::Update( double DeltaTime )
{
MessageSenderSystem::Update( DeltaTime );
}
void HealTakenMessageSenderSystem::OnHealTaken( core::HealTakenEvent const& Evt )
{
std::auto_ptr<HealTakenMessage> healTakenMsg( new HealTakenMessage );
healTakenMsg->mX = std::floor( Evt.mX * PRECISION );
healTakenMsg->mY = std::floor( Evt.mY * PRECISION );
healTakenMsg->mHeal = Evt.mHeal;
healTakenMsg->mActorGUID = Evt.mActorGUID;
mMessageHolder.AddOutgoingMessage( healTakenMsg );
}
HealTakenMessageHandlerSubSystem::HealTakenMessageHandlerSubSystem()
: MessageHandlerSubSystem()
{
}
void HealTakenMessageHandlerSubSystem::Init()
{
}
void HealTakenMessageHandlerSubSystem::Execute( Message const& message )
{
HealTakenMessage const& msg = static_cast<HealTakenMessage const&>( message );
Opt<Actor> actor = mScene.GetActor( msg.mActorGUID );
if ( !actor.IsValid() )
{
L1( "cannot find actor with GUID: (%s) %d \n", __FUNCTION__, msg.mActorGUID );
return;
}
Opt<IHealthComponent> healthC = actor->Get<IHealthComponent>();
if ( !healthC.IsValid() )
{
L1( "heal taken on an actor withot heal component \n" );
return;
}
healthC->TakeHeal( msg.mHeal );
}
} // namespace network
REAPING2_CLASS_EXPORT_IMPLEMENT( network__HealTakenMessage, network::HealTakenMessage );
| mit |
xiaojuntong/opencvr | 3rdparty/onvifc/win32/GeneratedFiles/Release/moc_qhttp.cpp | 6 | 14699 | /****************************************************************************
** Meta object code from reading C++ file 'qhttp.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../include/qhttp.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#include <QtCore/QList>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qhttp.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.4.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_QHttp_t {
QByteArrayData data[36];
char stringdata[526];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QHttp_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QHttp_t qt_meta_stringdata_QHttp = {
{
QT_MOC_LITERAL(0, 0, 5), // "QHttp"
QT_MOC_LITERAL(1, 6, 12), // "stateChanged"
QT_MOC_LITERAL(2, 19, 0), // ""
QT_MOC_LITERAL(3, 20, 22), // "responseHeaderReceived"
QT_MOC_LITERAL(4, 43, 19), // "QHttpResponseHeader"
QT_MOC_LITERAL(5, 63, 4), // "resp"
QT_MOC_LITERAL(6, 68, 9), // "readyRead"
QT_MOC_LITERAL(7, 78, 16), // "dataSendProgress"
QT_MOC_LITERAL(8, 95, 16), // "dataReadProgress"
QT_MOC_LITERAL(9, 112, 14), // "requestStarted"
QT_MOC_LITERAL(10, 127, 15), // "requestFinished"
QT_MOC_LITERAL(11, 143, 4), // "done"
QT_MOC_LITERAL(12, 148, 27), // "proxyAuthenticationRequired"
QT_MOC_LITERAL(13, 176, 13), // "QNetworkProxy"
QT_MOC_LITERAL(14, 190, 5), // "proxy"
QT_MOC_LITERAL(15, 196, 15), // "QAuthenticator*"
QT_MOC_LITERAL(16, 212, 22), // "authenticationRequired"
QT_MOC_LITERAL(17, 235, 8), // "hostname"
QT_MOC_LITERAL(18, 244, 4), // "port"
QT_MOC_LITERAL(19, 249, 9), // "sslErrors"
QT_MOC_LITERAL(20, 259, 16), // "QList<QSslError>"
QT_MOC_LITERAL(21, 276, 6), // "errors"
QT_MOC_LITERAL(22, 283, 5), // "abort"
QT_MOC_LITERAL(23, 289, 15), // "ignoreSslErrors"
QT_MOC_LITERAL(24, 305, 19), // "_q_startNextRequest"
QT_MOC_LITERAL(25, 325, 16), // "_q_slotReadyRead"
QT_MOC_LITERAL(26, 342, 16), // "_q_slotConnected"
QT_MOC_LITERAL(27, 359, 12), // "_q_slotError"
QT_MOC_LITERAL(28, 372, 28), // "QAbstractSocket::SocketError"
QT_MOC_LITERAL(29, 401, 13), // "_q_slotClosed"
QT_MOC_LITERAL(30, 415, 19), // "_q_slotBytesWritten"
QT_MOC_LITERAL(31, 435, 8), // "numBytes"
QT_MOC_LITERAL(32, 444, 28), // "_q_slotEncryptedBytesWritten"
QT_MOC_LITERAL(33, 473, 17), // "_q_slotDoFinished"
QT_MOC_LITERAL(34, 491, 18), // "_q_slotSendRequest"
QT_MOC_LITERAL(35, 510, 15) // "_q_continuePost"
},
"QHttp\0stateChanged\0\0responseHeaderReceived\0"
"QHttpResponseHeader\0resp\0readyRead\0"
"dataSendProgress\0dataReadProgress\0"
"requestStarted\0requestFinished\0done\0"
"proxyAuthenticationRequired\0QNetworkProxy\0"
"proxy\0QAuthenticator*\0authenticationRequired\0"
"hostname\0port\0sslErrors\0QList<QSslError>\0"
"errors\0abort\0ignoreSslErrors\0"
"_q_startNextRequest\0_q_slotReadyRead\0"
"_q_slotConnected\0_q_slotError\0"
"QAbstractSocket::SocketError\0_q_slotClosed\0"
"_q_slotBytesWritten\0numBytes\0"
"_q_slotEncryptedBytesWritten\0"
"_q_slotDoFinished\0_q_slotSendRequest\0"
"_q_continuePost"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QHttp[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
23, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
11, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 129, 2, 0x06 /* Public */,
3, 1, 132, 2, 0x06 /* Public */,
6, 1, 135, 2, 0x06 /* Public */,
7, 2, 138, 2, 0x06 /* Public */,
8, 2, 143, 2, 0x06 /* Public */,
9, 1, 148, 2, 0x06 /* Public */,
10, 2, 151, 2, 0x06 /* Public */,
11, 1, 156, 2, 0x06 /* Public */,
12, 2, 159, 2, 0x06 /* Public */,
16, 3, 164, 2, 0x06 /* Public */,
19, 1, 171, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
22, 0, 174, 2, 0x0a /* Public */,
23, 0, 175, 2, 0x0a /* Public */,
24, 0, 176, 2, 0x08 /* Private */,
25, 0, 177, 2, 0x08 /* Private */,
26, 0, 178, 2, 0x08 /* Private */,
27, 1, 179, 2, 0x08 /* Private */,
29, 0, 182, 2, 0x08 /* Private */,
30, 1, 183, 2, 0x08 /* Private */,
32, 1, 186, 2, 0x08 /* Private */,
33, 0, 189, 2, 0x08 /* Private */,
34, 0, 190, 2, 0x08 /* Private */,
35, 0, 191, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::Int, 2,
QMetaType::Void, 0x80000000 | 4, 5,
QMetaType::Void, 0x80000000 | 4, 5,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 2, 2,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 2, 2,
QMetaType::Void, QMetaType::Int, 2,
QMetaType::Void, QMetaType::Int, QMetaType::Bool, 2, 2,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void, 0x80000000 | 13, 0x80000000 | 15, 14, 2,
QMetaType::Void, QMetaType::QString, QMetaType::UShort, 0x80000000 | 15, 17, 18, 2,
QMetaType::Void, 0x80000000 | 20, 21,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 28, 2,
QMetaType::Void,
QMetaType::Void, QMetaType::LongLong, 31,
QMetaType::Void, QMetaType::LongLong, 31,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void QHttp::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
QHttp *_t = static_cast<QHttp *>(_o);
switch (_id) {
case 0: _t->stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->responseHeaderReceived((*reinterpret_cast< const QHttpResponseHeader(*)>(_a[1]))); break;
case 2: _t->readyRead((*reinterpret_cast< const QHttpResponseHeader(*)>(_a[1]))); break;
case 3: _t->dataSendProgress((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 4: _t->dataReadProgress((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 5: _t->requestStarted((*reinterpret_cast< int(*)>(_a[1]))); break;
case 6: _t->requestFinished((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
case 7: _t->done((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 8: _t->proxyAuthenticationRequired((*reinterpret_cast< const QNetworkProxy(*)>(_a[1])),(*reinterpret_cast< QAuthenticator*(*)>(_a[2]))); break;
case 9: _t->authenticationRequired((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< quint16(*)>(_a[2])),(*reinterpret_cast< QAuthenticator*(*)>(_a[3]))); break;
case 10: _t->sslErrors((*reinterpret_cast< const QList<QSslError>(*)>(_a[1]))); break;
case 11: _t->abort(); break;
case 12: _t->ignoreSslErrors(); break;
case 13: _t->d->_q_startNextRequest(); break;
case 14: _t->d->_q_slotReadyRead(); break;
case 15: _t->d->_q_slotConnected(); break;
case 16: _t->d->_q_slotError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
case 17: _t->d->_q_slotClosed(); break;
case 18: _t->d->_q_slotBytesWritten((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 19: _t->d->_q_slotEncryptedBytesWritten((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 20: _t->d->_q_slotDoFinished(); break;
case 21: _t->d->_q_slotSendRequest(); break;
case 22: _t->d->_q_continuePost(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (QHttp::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::stateChanged)) {
*result = 0;
}
}
{
typedef void (QHttp::*_t)(const QHttpResponseHeader & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::responseHeaderReceived)) {
*result = 1;
}
}
{
typedef void (QHttp::*_t)(const QHttpResponseHeader & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::readyRead)) {
*result = 2;
}
}
{
typedef void (QHttp::*_t)(int , int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::dataSendProgress)) {
*result = 3;
}
}
{
typedef void (QHttp::*_t)(int , int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::dataReadProgress)) {
*result = 4;
}
}
{
typedef void (QHttp::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::requestStarted)) {
*result = 5;
}
}
{
typedef void (QHttp::*_t)(int , bool );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::requestFinished)) {
*result = 6;
}
}
{
typedef void (QHttp::*_t)(bool );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::done)) {
*result = 7;
}
}
{
typedef void (QHttp::*_t)(const QNetworkProxy & , QAuthenticator * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::proxyAuthenticationRequired)) {
*result = 8;
}
}
{
typedef void (QHttp::*_t)(const QString & , quint16 , QAuthenticator * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::authenticationRequired)) {
*result = 9;
}
}
{
typedef void (QHttp::*_t)(const QList<QSslError> & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QHttp::sslErrors)) {
*result = 10;
}
}
}
}
const QMetaObject QHttp::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_QHttp.data,
qt_meta_data_QHttp, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *QHttp::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QHttp::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_QHttp.stringdata))
return static_cast<void*>(const_cast< QHttp*>(this));
return QObject::qt_metacast(_clname);
}
int QHttp::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 23)
qt_static_metacall(this, _c, _id, _a);
_id -= 23;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 23)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 23;
}
return _id;
}
// SIGNAL 0
void QHttp::stateChanged(int _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void QHttp::responseHeaderReceived(const QHttpResponseHeader & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void QHttp::readyRead(const QHttpResponseHeader & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
// SIGNAL 3
void QHttp::dataSendProgress(int _t1, int _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
// SIGNAL 4
void QHttp::dataReadProgress(int _t1, int _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 4, _a);
}
// SIGNAL 5
void QHttp::requestStarted(int _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 5, _a);
}
// SIGNAL 6
void QHttp::requestFinished(int _t1, bool _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 6, _a);
}
// SIGNAL 7
void QHttp::done(bool _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 7, _a);
}
// SIGNAL 8
void QHttp::proxyAuthenticationRequired(const QNetworkProxy & _t1, QAuthenticator * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 8, _a);
}
// SIGNAL 9
void QHttp::authenticationRequired(const QString & _t1, quint16 _t2, QAuthenticator * _t3)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 9, _a);
}
// SIGNAL 10
void QHttp::sslErrors(const QList<QSslError> & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 10, _a);
}
QT_END_MOC_NAMESPACE
| mit |
YunzhuLi/InfoGAIL | torcs-1.3.4/src/modules/simu/simuv2/axle.cpp | 6 | 2490 | /***************************************************************************
file : axle.cpp
created : Sun Mar 19 00:05:09 CET 2000
copyright : (C) 2000 by Eric Espie
email : torcs@free.fr
version : $Id: axle.cpp,v 1.8.2.1 2008/12/31 03:53:56 berniw Exp $
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "sim.h"
static const char *AxleSect[2] = {SECT_FRNTAXLE, SECT_REARAXLE};
void SimAxleConfig(tCar *car, int index)
{
void *hdle = car->params;
tdble rollCenter;
tAxle *axle = &(car->axle[index]);
axle->xpos = GfParmGetNum(hdle, AxleSect[index], PRM_XPOS, (char*)NULL, 0.0f);
axle->I = GfParmGetNum(hdle, AxleSect[index], PRM_INERTIA, (char*)NULL, 0.15f);
rollCenter = GfParmGetNum(hdle, AxleSect[index], PRM_ROLLCENTER, (char*)NULL, 0.15f);
car->wheel[index*2].rollCenter = car->wheel[index*2+1].rollCenter = rollCenter;
if (index == 0) {
SimSuspConfig(hdle, SECT_FRNTARB, &(axle->arbSusp), 0, 0);
axle->arbSusp.spring.K = -axle->arbSusp.spring.K;
} else {
SimSuspConfig(hdle, SECT_REARARB, &(axle->arbSusp), 0, 0);
axle->arbSusp.spring.K = -axle->arbSusp.spring.K;
}
car->wheel[index*2].feedBack.I += axle->I / 2.0;
car->wheel[index*2+1].feedBack.I += axle->I / 2.0;
}
void SimAxleUpdate(tCar *car, int index)
{
tAxle *axle = &(car->axle[index]);
tdble str, stl, sgn;
str = car->wheel[index*2].susp.x;
stl = car->wheel[index*2+1].susp.x;
sgn = SIGN(stl - str);
axle->arbSusp.x = fabs(stl - str);
tSpring *spring = &(axle->arbSusp.spring);
// To save CPU power we compute the force here directly. Just the spring
// is considered.
tdble f;
f = spring->K * axle->arbSusp.x;
// right
car->wheel[index*2].axleFz = + sgn * f;
// left
car->wheel[index*2+1].axleFz = - sgn * f;
}
| mit |
ycsoft/FatCat-Server | LIBS/boost_1_58_0/libs/geometry/doc/src/examples/algorithms/centroid.cpp | 6 | 1435 | // Boost.Geometry (aka GGL, Generic Geometry Library)
// QuickBook Example
// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//[centroid
//` Shows calculation of a centroid of a polygon
#include <iostream>
#include <list>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
/*<-*/ #include "create_svg_two.hpp" /*->*/
int main()
{
typedef boost::geometry::model::d2::point_xy<double> point_type;
typedef boost::geometry::model::polygon<point_type> polygon_type;
polygon_type poly;
boost::geometry::read_wkt(
"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)"
"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))", poly);
point_type p;
boost::geometry::centroid(poly, p);
std::cout << "centroid: " << boost::geometry::dsv(p) << std::endl;
/*<-*/ create_svg("centroid.svg", poly, p); /*->*/
return 0;
}
//]
//[centroid_output
/*`
Output:
[pre
centroid: (4.04663, 1.6349)
[$img/algorithms/centroid.png]
]
Note that the centroid might be located in a hole or outside a polygon, easily.
*/
//]
| mit |
hemantsangwan/Arduino-Json | test/JsonParser_Variant_Tests.cpp | 6 | 2032 | // Copyright Benoit Blanchon 2014-2016
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <ArduinoJson.h>
class JsonParser_Variant_Test : public testing::Test {
protected:
void whenInputIs(const char* jsonString) {
strcpy(_jsonString, jsonString);
_result = _jsonBuffer.parse(_jsonString);
}
template <typename T>
void resultMustEqual(T expected) {
EXPECT_EQ(expected, _result.as<T>());
}
void resultMustEqual(const char* expected) {
EXPECT_STREQ(expected, _result.as<char*>());
}
template <typename T>
void resultTypeMustBe() {
EXPECT_TRUE(_result.is<T>());
}
void resultMustBeInvalid() { EXPECT_FALSE(_result.success()); }
void resultMustBeValid() { EXPECT_TRUE(_result.success()); }
private:
DynamicJsonBuffer _jsonBuffer;
JsonVariant _result;
char _jsonString[256];
};
TEST_F(JsonParser_Variant_Test, EmptyObject) {
whenInputIs("{}");
resultMustBeValid();
resultTypeMustBe<JsonObject>();
}
TEST_F(JsonParser_Variant_Test, EmptyArray) {
whenInputIs("[]");
resultMustBeValid();
resultTypeMustBe<JsonArray>();
}
TEST_F(JsonParser_Variant_Test, Integer) {
whenInputIs("42");
resultMustBeValid();
resultTypeMustBe<int>();
resultMustEqual(42);
}
TEST_F(JsonParser_Variant_Test, Double) {
whenInputIs("3.14");
resultMustBeValid();
resultTypeMustBe<double>();
resultMustEqual(3.14);
}
TEST_F(JsonParser_Variant_Test, String) {
whenInputIs("\"hello world\"");
resultMustBeValid();
resultTypeMustBe<char*>();
resultMustEqual("hello world");
}
TEST_F(JsonParser_Variant_Test, True) {
whenInputIs("true");
resultMustBeValid();
resultTypeMustBe<bool>();
resultMustEqual(true);
}
TEST_F(JsonParser_Variant_Test, False) {
whenInputIs("false");
resultMustBeValid();
resultTypeMustBe<bool>();
resultMustEqual(false);
}
TEST_F(JsonParser_Variant_Test, Invalid) {
whenInputIs("{");
resultMustBeInvalid();
}
| mit |
shackra/godot | drivers/opus/silk/fixed/warped_autocorrelation_FIX.c | 6 | 4625 | /***********************************************************************
Copyright (c) 2006-2011, Skype Limited. 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 Internet Society, IETF or IETF Trust, nor the
names of specific 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.
***********************************************************************/
#ifdef OPUS_ENABLED
#include "opus/opus_config.h"
#endif
#include "opus/silk/fixed/main_FIX.h"
#define QC 10
#define QS 14
/* Autocorrelations for a warped frequency axis */
void silk_warped_autocorrelation_FIX(
opus_int32 *corr, /* O Result [order + 1] */
opus_int *scale, /* O Scaling of the correlation vector */
const opus_int16 *input, /* I Input data to correlate */
const opus_int warping_Q16, /* I Warping coefficient */
const opus_int length, /* I Length of input */
const opus_int order /* I Correlation order (even) */
)
{
opus_int n, i, lsh;
opus_int32 tmp1_QS, tmp2_QS;
opus_int32 state_QS[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
opus_int64 corr_QC[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
/* Order must be even */
silk_assert( ( order & 1 ) == 0 );
silk_assert( 2 * QS - QC >= 0 );
/* Loop over samples */
for( n = 0; n < length; n++ ) {
tmp1_QS = silk_LSHIFT32( (opus_int32)input[ n ], QS );
/* Loop over allpass sections */
for( i = 0; i < order; i += 2 ) {
/* Output of allpass section */
tmp2_QS = silk_SMLAWB( state_QS[ i ], state_QS[ i + 1 ] - tmp1_QS, warping_Q16 );
state_QS[ i ] = tmp1_QS;
corr_QC[ i ] += silk_RSHIFT64( silk_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );
/* Output of allpass section */
tmp1_QS = silk_SMLAWB( state_QS[ i + 1 ], state_QS[ i + 2 ] - tmp2_QS, warping_Q16 );
state_QS[ i + 1 ] = tmp2_QS;
corr_QC[ i + 1 ] += silk_RSHIFT64( silk_SMULL( tmp2_QS, state_QS[ 0 ] ), 2 * QS - QC );
}
state_QS[ order ] = tmp1_QS;
corr_QC[ order ] += silk_RSHIFT64( silk_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );
}
lsh = silk_CLZ64( corr_QC[ 0 ] ) - 35;
lsh = silk_LIMIT( lsh, -12 - QC, 30 - QC );
*scale = -( QC + lsh );
silk_assert( *scale >= -30 && *scale <= 12 );
if( lsh >= 0 ) {
for( i = 0; i < order + 1; i++ ) {
corr[ i ] = (opus_int32)silk_CHECK_FIT32( silk_LSHIFT64( corr_QC[ i ], lsh ) );
}
} else {
for( i = 0; i < order + 1; i++ ) {
corr[ i ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( corr_QC[ i ], -lsh ) );
}
}
silk_assert( corr_QC[ 0 ] >= 0 ); /* If breaking, decrease QC*/
}
| mit |
peercoin/peercoin | src/torcontrol.cpp | 9 | 31271 | // Copyright (c) 2015-2019 The Bitcoin Core developers
// Copyright (c) 2017 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <torcontrol.h>
#include <util/strencodings.h>
#include <netbase.h>
#include <net.h>
#include <util/system.h>
#include <crypto/hmac_sha256.h>
#include <vector>
#include <deque>
#include <set>
#include <stdlib.h>
#include <boost/signals2/signal.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/thread.h>
/** Default control port */
const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
/** Tor cookie size (from control-spec.txt) */
static const int TOR_COOKIE_SIZE = 32;
/** Size of client/server nonce for SAFECOOKIE */
static const int TOR_NONCE_SIZE = 32;
/** For computing serverHash in SAFECOOKIE */
static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
/** For computing clientHash in SAFECOOKIE */
static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
/** Exponential backoff configuration - initial timeout in seconds */
static const float RECONNECT_TIMEOUT_START = 1.0;
/** Exponential backoff configuration - growth factor */
static const float RECONNECT_TIMEOUT_EXP = 1.5;
/** Maximum length for lines received on TorControlConnection.
* tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
* this is belt-and-suspenders sanity limit to prevent memory exhaustion.
*/
static const int MAX_LINE_LENGTH = 100000;
/****** Low-level TorControlConnection ********/
/** Reply from Tor, can be single or multi-line */
class TorControlReply
{
public:
TorControlReply() { Clear(); }
int code;
std::vector<std::string> lines;
void Clear()
{
code = 0;
lines.clear();
}
};
/** Low-level handling for Tor control connection.
* Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
*/
class TorControlConnection
{
public:
typedef std::function<void(TorControlConnection&)> ConnectionCB;
typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
/** Create a new TorControlConnection.
*/
explicit TorControlConnection(struct event_base *base);
~TorControlConnection();
/**
* Connect to a Tor control port.
* target is address of the form host:port.
* connected is the handler that is called when connection is successfully established.
* disconnected is a handler that is called when the connection is broken.
* Return true on success.
*/
bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
/**
* Disconnect from Tor control port.
*/
void Disconnect();
/** Send a command, register a handler for the reply.
* A trailing CRLF is automatically added.
* Return true on success.
*/
bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
/** Response handlers for async replies */
boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
private:
/** Callback when ready for use */
std::function<void(TorControlConnection&)> connected;
/** Callback when connection lost */
std::function<void(TorControlConnection&)> disconnected;
/** Libevent event base */
struct event_base *base;
/** Connection to control socket */
struct bufferevent *b_conn;
/** Message being received */
TorControlReply message;
/** Response handlers */
std::deque<ReplyHandlerCB> reply_handlers;
/** Libevent handlers: internal */
static void readcb(struct bufferevent *bev, void *ctx);
static void eventcb(struct bufferevent *bev, short what, void *ctx);
};
TorControlConnection::TorControlConnection(struct event_base *_base):
base(_base), b_conn(nullptr)
{
}
TorControlConnection::~TorControlConnection()
{
if (b_conn)
bufferevent_free(b_conn);
}
void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
{
TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
struct evbuffer *input = bufferevent_get_input(bev);
size_t n_read_out = 0;
char *line;
assert(input);
// If there is not a whole line to read, evbuffer_readln returns nullptr
while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
{
std::string s(line, n_read_out);
free(line);
if (s.size() < 4) // Short line
continue;
// <status>(-|+| )<data><CRLF>
self->message.code = atoi(s.substr(0,3));
self->message.lines.push_back(s.substr(4));
char ch = s[3]; // '-','+' or ' '
if (ch == ' ') {
// Final line, dispatch reply and clean up
if (self->message.code >= 600) {
// Dispatch async notifications to async handler
// Synchronous and asynchronous messages are never interleaved
self->async_handler(*self, self->message);
} else {
if (!self->reply_handlers.empty()) {
// Invoke reply handler with message
self->reply_handlers.front()(*self, self->message);
self->reply_handlers.pop_front();
} else {
LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
}
}
self->message.Clear();
}
}
// Check for size of buffer - protect against memory exhaustion with very long lines
// Do this after evbuffer_readln to make sure all full lines have been
// removed from the buffer. Everything left is an incomplete line.
if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
self->Disconnect();
}
}
void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
{
TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
if (what & BEV_EVENT_CONNECTED) {
LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
self->connected(*self);
} else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
} else {
LogPrint(BCLog::TOR, "tor: End of stream\n");
}
self->Disconnect();
self->disconnected(*self);
}
}
bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
{
if (b_conn)
Disconnect();
// Parse target address:port
struct sockaddr_storage connect_to_addr;
int connect_to_addrlen = sizeof(connect_to_addr);
if (evutil_parse_sockaddr_port(target.c_str(),
(struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
LogPrintf("tor: Error parsing socket address %s\n", target);
return false;
}
// Create a new socket, set up callbacks and enable notification bits
b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (!b_conn)
return false;
bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
bufferevent_enable(b_conn, EV_READ|EV_WRITE);
this->connected = _connected;
this->disconnected = _disconnected;
// Finally, connect to target
if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
LogPrintf("tor: Error connecting to address %s\n", target);
return false;
}
return true;
}
void TorControlConnection::Disconnect()
{
if (b_conn)
bufferevent_free(b_conn);
b_conn = nullptr;
}
bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
{
if (!b_conn)
return false;
struct evbuffer *buf = bufferevent_get_output(b_conn);
if (!buf)
return false;
evbuffer_add(buf, cmd.data(), cmd.size());
evbuffer_add(buf, "\r\n", 2);
reply_handlers.push_back(reply_handler);
return true;
}
/****** General parsing utilities ********/
/* Split reply line in the form 'AUTH METHODS=...' into a type
* 'AUTH' and arguments 'METHODS=...'.
* Grammar is implicitly defined in https://spec.torproject.org/control-spec by
* the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
*/
std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
{
size_t ptr=0;
std::string type;
while (ptr < s.size() && s[ptr] != ' ') {
type.push_back(s[ptr]);
++ptr;
}
if (ptr < s.size())
++ptr; // skip ' '
return make_pair(type, s.substr(ptr));
}
/** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
* Returns a map of keys to values, or an empty map if there was an error.
* Grammar is implicitly defined in https://spec.torproject.org/control-spec by
* the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
* and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
*/
std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
{
std::map<std::string,std::string> mapping;
size_t ptr=0;
while (ptr < s.size()) {
std::string key, value;
while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
key.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
if (s[ptr] == ' ') // The remaining string is an OptArguments
break;
++ptr; // skip '='
if (ptr < s.size() && s[ptr] == '"') { // Quoted string
++ptr; // skip opening '"'
bool escape_next = false;
while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
// Repeated backslashes must be interpreted as pairs
escape_next = (s[ptr] == '\\' && !escape_next);
value.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
++ptr; // skip closing '"'
/**
* Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
*
* For future-proofing, controller implementors MAY use the following
* rules to be compatible with buggy Tor implementations and with
* future ones that implement the spec as intended:
*
* Read \n \t \r and \0 ... \377 as C escapes.
* Treat a backslash followed by any other character as that character.
*/
std::string escaped_value;
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '\\') {
// This will always be valid, because if the QuotedString
// ended in an odd number of backslashes, then the parser
// would already have returned above, due to a missing
// terminating double-quote.
++i;
if (value[i] == 'n') {
escaped_value.push_back('\n');
} else if (value[i] == 't') {
escaped_value.push_back('\t');
} else if (value[i] == 'r') {
escaped_value.push_back('\r');
} else if ('0' <= value[i] && value[i] <= '7') {
size_t j;
// Octal escape sequences have a limit of three octal digits,
// but terminate at the first character that is not a valid
// octal digit if encountered sooner.
for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
// Tor restricts first digit to 0-3 for three-digit octals.
// A leading digit of 4-7 would therefore be interpreted as
// a two-digit octal.
if (j == 3 && value[i] > '3') {
j--;
}
escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
// Account for automatic incrementing at loop end
i += j - 1;
} else {
escaped_value.push_back(value[i]);
}
} else {
escaped_value.push_back(value[i]);
}
}
value = escaped_value;
} else { // Unquoted value. Note that values can contain '=' at will, just no spaces
while (ptr < s.size() && s[ptr] != ' ') {
value.push_back(s[ptr]);
++ptr;
}
}
if (ptr < s.size() && s[ptr] == ' ')
++ptr; // skip ' ' after key=value
mapping[key] = value;
}
return mapping;
}
/** Read full contents of a file and return them in a std::string.
* Returns a pair <status, string>.
* If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
*
* @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
* (with len > maxsize) will be returned.
*/
static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
{
FILE *f = fsbridge::fopen(filename, "rb");
if (f == nullptr)
return std::make_pair(false,"");
std::string retval;
char buffer[128];
size_t n;
while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
// Check for reading errors so we don't return any data if we couldn't
// read the entire file (or up to maxsize)
if (ferror(f)) {
fclose(f);
return std::make_pair(false,"");
}
retval.append(buffer, buffer+n);
if (retval.size() > maxsize)
break;
}
fclose(f);
return std::make_pair(true,retval);
}
/** Write contents of std::string to a file.
* @return true on success.
*/
static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
{
FILE *f = fsbridge::fopen(filename, "wb");
if (f == nullptr)
return false;
if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
fclose(f);
return false;
}
fclose(f);
return true;
}
/****** Bitcoin specific TorController implementation ********/
/** Controller that connects to Tor control socket, authenticate, then create
* and maintain an ephemeral hidden service.
*/
class TorController
{
public:
TorController(struct event_base* base, const std::string& target);
~TorController();
/** Get name of file to store private key in */
fs::path GetPrivateKeyFile();
/** Reconnect, after getting disconnected */
void Reconnect();
private:
struct event_base* base;
std::string target;
TorControlConnection conn;
std::string private_key;
std::string service_id;
bool reconnect;
struct event *reconnect_ev;
float reconnect_timeout;
CService service;
/** Cookie for SAFECOOKIE auth */
std::vector<uint8_t> cookie;
/** ClientNonce for SAFECOOKIE auth */
std::vector<uint8_t> clientNonce;
/** Callback for ADD_ONION result */
void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHENTICATE result */
void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHCHALLENGE result */
void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for PROTOCOLINFO result */
void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback after successful connection */
void connected_cb(TorControlConnection& conn);
/** Callback after connection lost or failed connection attempt */
void disconnected_cb(TorControlConnection& conn);
/** Callback for reconnect timer */
static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
};
TorController::TorController(struct event_base* _base, const std::string& _target):
base(_base),
target(_target), conn(base), reconnect(true), reconnect_ev(0),
reconnect_timeout(RECONNECT_TIMEOUT_START)
{
reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
if (!reconnect_ev)
LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
// Start connection attempts immediately
if (!conn.Connect(_target, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
}
// Read service private key if cached
std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
if (pkf.first) {
LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
private_key = pkf.second;
}
}
TorController::~TorController()
{
if (reconnect_ev) {
event_free(reconnect_ev);
reconnect_ev = nullptr;
}
if (service.IsValid()) {
RemoveLocal(service);
}
}
void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
for (const std::string &s : reply.lines) {
std::map<std::string,std::string> m = ParseTorReplyMapping(s);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("ServiceID")) != m.end())
service_id = i->second;
if ((i = m.find("PrivateKey")) != m.end())
private_key = i->second;
}
if (service_id.empty()) {
LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
for (const std::string &s : reply.lines) {
LogPrintf(" %s\n", SanitizeString(s));
}
return;
}
service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
} else {
LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
}
AddLocal(service, LOCAL_MANUAL);
// ... onion requested - keep connection open
} else if (reply.code == 510) { // 510 Unrecognized command
LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
} else {
LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
}
}
void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint(BCLog::TOR, "tor: Authentication successful\n");
// Now that we know Tor is running setup the proxy for onion addresses
// if -onion isn't set to something else.
if (gArgs.GetArg("-onion", "") == "") {
CService resolved(LookupNumeric("127.0.0.1", 9050));
proxyType addrOnion = proxyType(resolved, true);
SetProxy(NET_ONION, addrOnion);
SetReachable(NET_ONION, true);
}
// Finally - now create the service
if (private_key.empty()) // No private key, generate one
private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
// Request hidden service, redirect port.
// Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
_conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, Params().GetDefaultPort(), GetListenPort()),
std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
} else {
LogPrintf("tor: Authentication failed\n");
}
}
/** Compute Tor SAFECOOKIE response.
*
* ServerHash is computed as:
* HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
* CookieString | ClientNonce | ServerNonce)
* (with the HMAC key as its first argument)
*
* After a controller sends a successful AUTHCHALLENGE command, the
* next command sent on the connection must be an AUTHENTICATE command,
* and the only authentication string which that AUTHENTICATE command
* will accept is:
*
* HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
* CookieString | ClientNonce | ServerNonce)
*
*/
static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
{
CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
computeHash.Write(cookie.data(), cookie.size());
computeHash.Write(clientNonce.data(), clientNonce.size());
computeHash.Write(serverNonce.data(), serverNonce.size());
computeHash.Finalize(computedHash.data());
return computedHash;
}
void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
if (l.first == "AUTHCHALLENGE") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
if (m.empty()) {
LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
return;
}
std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
if (serverNonce.size() != 32) {
LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
return;
}
std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
if (computedServerHash != serverHash) {
LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
return;
}
std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
_conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
} else {
LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
}
} else {
LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
}
}
void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
std::set<std::string> methods;
std::string cookiefile;
/*
* 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
* 250-AUTH METHODS=NULL
* 250-AUTH METHODS=HASHEDPASSWORD
*/
for (const std::string &s : reply.lines) {
std::pair<std::string,std::string> l = SplitTorReplyLine(s);
if (l.first == "AUTH") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("METHODS")) != m.end())
boost::split(methods, i->second, boost::is_any_of(","));
if ((i = m.find("COOKIEFILE")) != m.end())
cookiefile = i->second;
} else if (l.first == "VERSION") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("Tor")) != m.end()) {
LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
}
}
}
for (const std::string &s : methods) {
LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
}
// Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
/* Authentication:
* cookie: hex-encoded ~/.tor/control_auth_cookie
* password: "password"
*/
std::string torpassword = gArgs.GetArg("-torpassword", "");
if (!torpassword.empty()) {
if (methods.count("HASHEDPASSWORD")) {
LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
boost::replace_all(torpassword, "\"", "\\\"");
_conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
} else {
LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
}
} else if (methods.count("NULL")) {
LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
_conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
} else if (methods.count("SAFECOOKIE")) {
// Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
// _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
_conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
} else {
if (status_cookie.first) {
LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
} else {
LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
}
}
} else if (methods.count("HASHEDPASSWORD")) {
LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
} else {
LogPrintf("tor: No supported authentication method\n");
}
} else {
LogPrintf("tor: Requesting protocol info failed\n");
}
}
void TorController::connected_cb(TorControlConnection& _conn)
{
reconnect_timeout = RECONNECT_TIMEOUT_START;
// First send a PROTOCOLINFO command to figure out what authentication is expected
if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
LogPrintf("tor: Error sending initial protocolinfo command\n");
}
void TorController::disconnected_cb(TorControlConnection& _conn)
{
// Stop advertising service when disconnected
if (service.IsValid())
RemoveLocal(service);
service = CService();
if (!reconnect)
return;
LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
// Single-shot timer for reconnect. Use exponential backoff.
struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
if (reconnect_ev)
event_add(reconnect_ev, &time);
reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
}
void TorController::Reconnect()
{
/* Try to reconnect and reestablish if we get booted - for example, Tor
* may be restarting.
*/
if (!conn.Connect(target, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
}
}
fs::path TorController::GetPrivateKeyFile()
{
return GetDataDir() / "onion_private_key";
}
void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
{
TorController *self = static_cast<TorController*>(arg);
self->Reconnect();
}
/****** Thread ********/
static struct event_base *gBase;
static std::thread torControlThread;
static void TorControlThread()
{
TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
event_base_dispatch(gBase);
}
void StartTorControl()
{
assert(!gBase);
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
gBase = event_base_new();
if (!gBase) {
LogPrintf("tor: Unable to create event_base\n");
return;
}
torControlThread = std::thread(std::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
}
void InterruptTorControl()
{
if (gBase) {
LogPrintf("tor: Thread interrupt\n");
event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
event_base_loopbreak(gBase);
}, nullptr, nullptr);
}
}
void StopTorControl()
{
if (gBase) {
torControlThread.join();
event_base_free(gBase);
gBase = nullptr;
}
}
| mit |
daleooo/barrelfish | lib/oldc/msun/src/e_acoshf.c | 9 | 1367 | /* e_acoshf.c -- float version of e_acosh.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/lib/msun/src/e_acoshf.c,v 1.8 2008/02/22 02:30:34 das Exp $");
#include "math.h"
#include "math_private.h"
static const float
one = 1.0,
ln2 = 6.9314718246e-01; /* 0x3f317218 */
float
__ieee754_acoshf(float x)
{
float t;
int32_t hx;
GET_FLOAT_WORD(hx,x);
if(hx<0x3f800000) { /* x < 1 */
return (x-x)/(x-x);
} else if(hx >=0x4d800000) { /* x > 2**28 */
if(hx >=0x7f800000) { /* x is inf of NaN */
return x+x;
} else
return __ieee754_logf(x)+ln2; /* acosh(huge)=log(2x) */
} else if (hx==0x3f800000) {
return 0.0; /* acosh(1) = 0 */
} else if (hx > 0x40000000) { /* 2**28 > x > 2 */
t=x*x;
return __ieee754_logf((float)2.0*x-one/(x+__ieee754_sqrtf(t-one)));
} else { /* 1<x<2 */
t = x-one;
return log1pf(t+__ieee754_sqrtf((float)2.0*t+t*t));
}
}
| mit |
GovanifY/Polycode | Examples/C++/Contents/2DPhysics_Joints/HelloPolycodeApp.cpp | 10 | 1776 | #include "HelloPolycodeApp.h"
HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) {
core = new POLYCODE_CORE(view, 640,480,false,true,0,0,90, 0, true);
PhysicsScene2D *scene = new PhysicsScene2D(0.1, 50);
ScenePrimitive *ceiling = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 2.0, 0.1);
ceiling->setColor(0.0, 0.0, 0.0, 1.0);
ceiling->setPosition(0, 0.5);
scene->addPhysicsChild(ceiling, PhysicsScene2DEntity::ENTITY_RECT, true);
// Revolute Joint
ScenePrimitive *shape = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 0.03, 0.2);
shape->setAnchorPoint(0.0, 1.0, 0.0);
shape->setPosition(-0.3, 0.48);
scene->addPhysicsChild(shape, PhysicsScene2DEntity::ENTITY_RECT, false);
scene->createRevoluteJoint(shape, ceiling, 0.0, 0.01);
scene->applyImpulse(shape, 10, 0);
// Distance Joint
shape = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 0.1, 0.02);
shape->setPosition(0.0, 0.2);
scene->addPhysicsChild(shape, PhysicsScene2DEntity::ENTITY_RECT, false);
scene->createDistanceJoint(shape, ceiling, false);
scene->applyImpulse(shape, 2, 0);
SceneLine *line = new SceneLine(shape, ceiling);
line->setColor(1.0, 0.0, 0.0, 1.0);
scene->addChild(line);
// Prismatic Joint
shape = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 0.05, 0.1);
shape->setPosition(0.3, 0.3);
scene->addPhysicsChild(shape, PhysicsScene2DEntity::ENTITY_RECT, false);
scene->createPrismaticJoint(ceiling, shape, Vector2(0,1), 0,0, false, -0.3, 0, true);
SceneEntity *lineAnchor = new SceneEntity();
lineAnchor->setPosition(0.3,0.5);
line = new SceneLine(shape, lineAnchor);
line->setColor(0.0, 1.0, 0.0, 1.0);
scene->addChild(line);
}
HelloPolycodeApp::~HelloPolycodeApp() {
}
bool HelloPolycodeApp::Update() {
return core->updateAndRender();
}
| mit |
miguelmota/find-me-burritos | node_modules/mean-connect-mongo/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c | 3341 | 7466 | #include "kerberos_sspi.h"
#include <stdlib.h>
#include <stdio.h>
static HINSTANCE _sspi_security_dll = NULL;
static HINSTANCE _sspi_secur32_dll = NULL;
/**
* Encrypt A Message
*/
SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) {
// Create function pointer instance
encryptMessage_fn pfn_encryptMessage = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function to library method
pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage");
// Check if the we managed to map function pointer
if(!pfn_encryptMessage) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo);
}
/**
* Acquire Credentials
*/
SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle(
LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse,
void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument,
PCredHandle phCredential, PTimeStamp ptsExpiry
) {
SECURITY_STATUS status;
// Create function pointer instance
acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
#ifdef _UNICODE
pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW");
#else
pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA");
#endif
// Check if the we managed to map function pointer
if(!pfn_acquireCredentialsHandle) {
printf("GetProcAddress failed.\n");
return -2;
}
// Status
status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse,
pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry
);
// Call the function
return status;
}
/**
* Delete Security Context
*/
SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) {
// Create function pointer instance
deleteSecurityContext_fn pfn_deleteSecurityContext = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext");
// Check if the we managed to map function pointer
if(!pfn_deleteSecurityContext) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_deleteSecurityContext)(phContext);
}
/**
* Decrypt Message
*/
SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) {
// Create function pointer instance
decryptMessage_fn pfn_decryptMessage = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage");
// Check if the we managed to map function pointer
if(!pfn_decryptMessage) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP);
}
/**
* Initialize Security Context
*/
SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext(
PCredHandle phCredential, PCtxtHandle phContext,
LPSTR pszTargetName, unsigned long fContextReq,
unsigned long Reserved1, unsigned long TargetDataRep,
PSecBufferDesc pInput, unsigned long Reserved2,
PCtxtHandle phNewContext, PSecBufferDesc pOutput,
unsigned long * pfContextAttr, PTimeStamp ptsExpiry
) {
SECURITY_STATUS status;
// Create function pointer instance
initializeSecurityContext_fn pfn_initializeSecurityContext = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
#ifdef _UNICODE
pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW");
#else
pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA");
#endif
// Check if the we managed to map function pointer
if(!pfn_initializeSecurityContext) {
printf("GetProcAddress failed.\n");
return -2;
}
// Execute intialize context
status = (*pfn_initializeSecurityContext)(
phCredential, phContext, pszTargetName, fContextReq,
Reserved1, TargetDataRep, pInput, Reserved2,
phNewContext, pOutput, pfContextAttr, ptsExpiry
);
// Call the function
return status;
}
/**
* Query Context Attributes
*/
SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes(
PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer
) {
// Create function pointer instance
queryContextAttributes_fn pfn_queryContextAttributes = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
#ifdef _UNICODE
pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW");
#else
pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA");
#endif
// Check if the we managed to map function pointer
if(!pfn_queryContextAttributes) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_queryContextAttributes)(
phContext, ulAttribute, pBuffer
);
}
/**
* InitSecurityInterface
*/
PSecurityFunctionTable _ssip_InitSecurityInterface() {
INIT_SECURITY_INTERFACE InitSecurityInterface;
PSecurityFunctionTable pSecurityInterface = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return NULL;
#ifdef _UNICODE
// Get the address of the InitSecurityInterface function.
InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress (
_sspi_secur32_dll,
TEXT("InitSecurityInterfaceW"));
#else
// Get the address of the InitSecurityInterface function.
InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress (
_sspi_secur32_dll,
TEXT("InitSecurityInterfaceA"));
#endif
if(!InitSecurityInterface) {
printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ());
return NULL;
}
// Use InitSecurityInterface to get the function table.
pSecurityInterface = (*InitSecurityInterface)();
if(!pSecurityInterface) {
printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ());
return NULL;
}
return pSecurityInterface;
}
/**
* Load security.dll dynamically
*/
int load_library() {
DWORD err;
// Load the library
_sspi_security_dll = LoadLibrary("security.dll");
// Check if the library loaded
if(_sspi_security_dll == NULL) {
err = GetLastError();
return err;
}
// Load the library
_sspi_secur32_dll = LoadLibrary("secur32.dll");
// Check if the library loaded
if(_sspi_secur32_dll == NULL) {
err = GetLastError();
return err;
}
return 0;
} | mit |
andrewrk/zig | lib/libc/wasi/libc-top-half/musl/src/stdlib/qsort.c | 14 | 4991 | /* Copyright (C) 2011 by Valentin Ochs
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/* Minor changes by Rich Felker for integration in musl, 2011-04-27. */
/* Smoothsort, an adaptive variant of Heapsort. Memory usage: O(1).
Run time: Worst case O(n log n), close to O(n) in the mostly-sorted case. */
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "atomic.h"
#define ntz(x) a_ctz_l((x))
typedef int (*cmpfun)(const void *, const void *);
static inline int pntz(size_t p[2]) {
int r = ntz(p[0] - 1);
if(r != 0 || (r = 8*sizeof(size_t) + ntz(p[1])) != 8*sizeof(size_t)) {
return r;
}
return 0;
}
static void cycle(size_t width, unsigned char* ar[], int n)
{
unsigned char tmp[256];
size_t l;
int i;
if(n < 2) {
return;
}
ar[n] = tmp;
while(width) {
l = sizeof(tmp) < width ? sizeof(tmp) : width;
memcpy(ar[n], ar[0], l);
for(i = 0; i < n; i++) {
memcpy(ar[i], ar[i + 1], l);
ar[i] += l;
}
width -= l;
}
}
/* shl() and shr() need n > 0 */
static inline void shl(size_t p[2], int n)
{
if(n >= 8 * sizeof(size_t)) {
n -= 8 * sizeof(size_t);
p[1] = p[0];
p[0] = 0;
}
p[1] <<= n;
p[1] |= p[0] >> (sizeof(size_t) * 8 - n);
p[0] <<= n;
}
static inline void shr(size_t p[2], int n)
{
if(n >= 8 * sizeof(size_t)) {
n -= 8 * sizeof(size_t);
p[0] = p[1];
p[1] = 0;
}
p[0] >>= n;
p[0] |= p[1] << (sizeof(size_t) * 8 - n);
p[1] >>= n;
}
static void sift(unsigned char *head, size_t width, cmpfun cmp, int pshift, size_t lp[])
{
unsigned char *rt, *lf;
unsigned char *ar[14 * sizeof(size_t) + 1];
int i = 1;
ar[0] = head;
while(pshift > 1) {
rt = head - width;
lf = head - width - lp[pshift - 2];
if((*cmp)(ar[0], lf) >= 0 && (*cmp)(ar[0], rt) >= 0) {
break;
}
if((*cmp)(lf, rt) >= 0) {
ar[i++] = lf;
head = lf;
pshift -= 1;
} else {
ar[i++] = rt;
head = rt;
pshift -= 2;
}
}
cycle(width, ar, i);
}
static void trinkle(unsigned char *head, size_t width, cmpfun cmp, size_t pp[2], int pshift, int trusty, size_t lp[])
{
unsigned char *stepson,
*rt, *lf;
size_t p[2];
unsigned char *ar[14 * sizeof(size_t) + 1];
int i = 1;
int trail;
p[0] = pp[0];
p[1] = pp[1];
ar[0] = head;
while(p[0] != 1 || p[1] != 0) {
stepson = head - lp[pshift];
if((*cmp)(stepson, ar[0]) <= 0) {
break;
}
if(!trusty && pshift > 1) {
rt = head - width;
lf = head - width - lp[pshift - 2];
if((*cmp)(rt, stepson) >= 0 || (*cmp)(lf, stepson) >= 0) {
break;
}
}
ar[i++] = stepson;
head = stepson;
trail = pntz(p);
shr(p, trail);
pshift += trail;
trusty = 0;
}
if(!trusty) {
cycle(width, ar, i);
sift(head, width, cmp, pshift, lp);
}
}
void qsort(void *base, size_t nel, size_t width, cmpfun cmp)
{
size_t lp[12*sizeof(size_t)];
size_t i, size = width * nel;
unsigned char *head, *high;
size_t p[2] = {1, 0};
int pshift = 1;
int trail;
if (!size) return;
head = base;
high = head + size - width;
/* Precompute Leonardo numbers, scaled by element width */
for(lp[0]=lp[1]=width, i=2; (lp[i]=lp[i-2]+lp[i-1]+width) < size; i++);
while(head < high) {
if((p[0] & 3) == 3) {
sift(head, width, cmp, pshift, lp);
shr(p, 2);
pshift += 2;
} else {
if(lp[pshift - 1] >= high - head) {
trinkle(head, width, cmp, p, pshift, 0, lp);
} else {
sift(head, width, cmp, pshift, lp);
}
if(pshift == 1) {
shl(p, 1);
pshift = 0;
} else {
shl(p, pshift - 1);
pshift = 1;
}
}
p[0] |= 1;
head += width;
}
trinkle(head, width, cmp, p, pshift, 0, lp);
while(pshift != 1 || p[0] != 1 || p[1] != 0) {
if(pshift <= 1) {
trail = pntz(p);
shr(p, trail);
pshift += trail;
} else {
shl(p, 2);
pshift -= 2;
p[0] ^= 7;
shr(p, 1);
trinkle(head - lp[pshift] - width, width, cmp, p, pshift + 1, 1, lp);
shl(p, 1);
p[0] |= 1;
trinkle(head - width, width, cmp, p, pshift, 1, lp);
}
head -= width;
}
}
| mit |
goldcoin/gldcoin | BuildDeps/deps/boost/libs/math/tools/ellint_k_data.cpp | 16 | 1644 | // (C) Copyright John Maddock 2007.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/math/bindings/rr.hpp>
#include <boost/math/tools/test_data.hpp>
#include <boost/test/included/test_exec_monitor.hpp>
#include <boost/math/special_functions/ellint_1.hpp>
#include <fstream>
#include <boost/math/tools/test_data.hpp>
#include <boost/tr1/random.hpp>
using namespace boost::math::tools;
using namespace boost::math;
using namespace std;
template<class T>
T ellint_k_data(T k)
{
return ellint_1(k);
}
int test_main(int argc, char*argv [])
{
using namespace boost::math::tools;
boost::math::ntl::RR::SetOutputPrecision(50);
boost::math::ntl::RR::SetPrecision(1000);
parameter_info<boost::math::ntl::RR> arg1;
test_data<boost::math::ntl::RR> data;
bool cont;
std::string line;
if(argc < 1)
return 1;
do{
if(0 == get_user_parameter_info(arg1, "phi"))
return 1;
data.insert(&ellint_k_data<boost::math::ntl::RR>, arg1);
std::cout << "Any more data [y/n]?";
std::getline(std::cin, line);
boost::algorithm::trim(line);
cont = (line == "y");
}while(cont);
std::cout << "Enter name of test data file [default=ellint_k_data.ipp]";
std::getline(std::cin, line);
boost::algorithm::trim(line);
if(line == "")
line = "ellint_k_data.ipp";
std::ofstream ofs(line.c_str());
line.erase(line.find('.'));
ofs << std::scientific;
write_code(ofs, data, line.c_str());
return 0;
}
| mit |
takashi310/fluorender | fluorender/ffmpeg/OSX/include/libavformat/mpc.c | 18 | 7037 | /*
* Musepack demuxer
* Copyright (c) 2006 Konstantin Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/channel_layout.h"
#include "libavcodec/get_bits.h"
#include "avformat.h"
#include "internal.h"
#include "apetag.h"
#include "id3v1.h"
#include "libavutil/dict.h"
#define MPC_FRAMESIZE 1152
#define DELAY_FRAMES 32
static const int mpc_rate[4] = { 44100, 48000, 37800, 32000 };
typedef struct {
int64_t pos;
int size, skip;
}MPCFrame;
typedef struct {
int ver;
uint32_t curframe, lastframe;
uint32_t fcount;
MPCFrame *frames;
int curbits;
int frames_noted;
} MPCContext;
static int mpc_probe(AVProbeData *p)
{
const uint8_t *d = p->buf;
if (d[0] == 'M' && d[1] == 'P' && d[2] == '+' && (d[3] == 0x17 || d[3] == 0x7))
return AVPROBE_SCORE_MAX;
return 0;
}
static int mpc_read_header(AVFormatContext *s)
{
MPCContext *c = s->priv_data;
AVStream *st;
if(avio_rl24(s->pb) != MKTAG('M', 'P', '+', 0)){
av_log(s, AV_LOG_ERROR, "Not a Musepack file\n");
return AVERROR_INVALIDDATA;
}
c->ver = avio_r8(s->pb);
if(c->ver != 0x07 && c->ver != 0x17){
av_log(s, AV_LOG_ERROR, "Can demux Musepack SV7, got version %02X\n", c->ver);
return AVERROR_INVALIDDATA;
}
c->fcount = avio_rl32(s->pb);
if((int64_t)c->fcount * sizeof(MPCFrame) >= UINT_MAX){
av_log(s, AV_LOG_ERROR, "Too many frames, seeking is not possible\n");
return AVERROR_INVALIDDATA;
}
if(c->fcount){
c->frames = av_malloc(c->fcount * sizeof(MPCFrame));
if(!c->frames){
av_log(s, AV_LOG_ERROR, "Cannot allocate seektable\n");
return AVERROR(ENOMEM);
}
}else{
av_log(s, AV_LOG_WARNING, "Container reports no frames\n");
}
c->curframe = 0;
c->lastframe = -1;
c->curbits = 8;
c->frames_noted = 0;
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = AV_CODEC_ID_MUSEPACK7;
st->codec->channels = 2;
st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
st->codec->bits_per_coded_sample = 16;
if (ff_get_extradata(st->codec, s->pb, 16) < 0)
return AVERROR(ENOMEM);
st->codec->sample_rate = mpc_rate[st->codec->extradata[2] & 3];
avpriv_set_pts_info(st, 32, MPC_FRAMESIZE, st->codec->sample_rate);
/* scan for seekpoints */
st->start_time = 0;
st->duration = c->fcount;
/* try to read APE tags */
if (s->pb->seekable) {
int64_t pos = avio_tell(s->pb);
ff_ape_parse_tag(s);
if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
ff_id3v1_read(s);
avio_seek(s->pb, pos, SEEK_SET);
}
return 0;
}
static int mpc_read_packet(AVFormatContext *s, AVPacket *pkt)
{
MPCContext *c = s->priv_data;
int ret, size, size2, curbits, cur = c->curframe;
unsigned tmp;
int64_t pos;
if (c->curframe >= c->fcount && c->fcount)
return AVERROR_EOF;
if(c->curframe != c->lastframe + 1){
avio_seek(s->pb, c->frames[c->curframe].pos, SEEK_SET);
c->curbits = c->frames[c->curframe].skip;
}
c->lastframe = c->curframe;
c->curframe++;
curbits = c->curbits;
pos = avio_tell(s->pb);
tmp = avio_rl32(s->pb);
if(curbits <= 12){
size2 = (tmp >> (12 - curbits)) & 0xFFFFF;
}else{
size2 = (tmp << (curbits - 12) | avio_rl32(s->pb) >> (44 - curbits)) & 0xFFFFF;
}
curbits += 20;
avio_seek(s->pb, pos, SEEK_SET);
size = ((size2 + curbits + 31) & ~31) >> 3;
if(cur == c->frames_noted && c->fcount){
c->frames[cur].pos = pos;
c->frames[cur].size = size;
c->frames[cur].skip = curbits - 20;
av_add_index_entry(s->streams[0], cur, cur, size, 0, AVINDEX_KEYFRAME);
c->frames_noted++;
}
c->curbits = (curbits + size2) & 0x1F;
if ((ret = av_new_packet(pkt, size + 4)) < 0)
return ret;
pkt->data[0] = curbits;
pkt->data[1] = (c->curframe > c->fcount) && c->fcount;
pkt->data[2] = 0;
pkt->data[3] = 0;
pkt->stream_index = 0;
pkt->pts = cur;
ret = avio_read(s->pb, pkt->data + 4, size);
if(c->curbits)
avio_seek(s->pb, -4, SEEK_CUR);
if(ret < size){
av_free_packet(pkt);
return ret < 0 ? ret : AVERROR(EIO);
}
pkt->size = ret + 4;
return 0;
}
static int mpc_read_close(AVFormatContext *s)
{
MPCContext *c = s->priv_data;
av_freep(&c->frames);
return 0;
}
/**
* Seek to the given position
* If position is unknown but is within the limits of file
* then packets are skipped unless desired position is reached
*
* Also this function makes use of the fact that timestamp == frameno
*/
static int mpc_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
{
AVStream *st = s->streams[stream_index];
MPCContext *c = s->priv_data;
AVPacket pkt1, *pkt = &pkt1;
int ret;
int index = av_index_search_timestamp(st, FFMAX(timestamp - DELAY_FRAMES, 0), flags);
uint32_t lastframe;
/* if found, seek there */
if (index >= 0 && st->index_entries[st->nb_index_entries-1].timestamp >= timestamp - DELAY_FRAMES){
c->curframe = st->index_entries[index].pos;
return 0;
}
/* if timestamp is out of bounds, return error */
if(timestamp < 0 || timestamp >= c->fcount)
return -1;
timestamp -= DELAY_FRAMES;
/* seek to the furthest known position and read packets until
we reach desired position */
lastframe = c->curframe;
if(c->frames_noted) c->curframe = c->frames_noted - 1;
while(c->curframe < timestamp){
ret = av_read_frame(s, pkt);
if (ret < 0){
c->curframe = lastframe;
return ret;
}
av_free_packet(pkt);
}
return 0;
}
AVInputFormat ff_mpc_demuxer = {
.name = "mpc",
.long_name = NULL_IF_CONFIG_SMALL("Musepack"),
.priv_data_size = sizeof(MPCContext),
.read_probe = mpc_probe,
.read_header = mpc_read_header,
.read_packet = mpc_read_packet,
.read_close = mpc_read_close,
.read_seek = mpc_read_seek,
.extensions = "mpc",
};
| mit |
publicloudapp/csrutil | linux-4.3/drivers/gpu/drm/shmobile/shmob_drm_kms.c | 1298 | 3992 | /*
* shmob_drm_kms.c -- SH Mobile DRM Mode Setting
*
* Copyright (C) 2012 Renesas Electronics Corporation
*
* Laurent Pinchart (laurent.pinchart@ideasonboard.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <drm/drmP.h>
#include <drm/drm_crtc.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_fb_cma_helper.h>
#include <drm/drm_gem_cma_helper.h>
#include <video/sh_mobile_meram.h>
#include "shmob_drm_crtc.h"
#include "shmob_drm_drv.h"
#include "shmob_drm_kms.h"
#include "shmob_drm_regs.h"
/* -----------------------------------------------------------------------------
* Format helpers
*/
static const struct shmob_drm_format_info shmob_drm_format_infos[] = {
{
.fourcc = DRM_FORMAT_RGB565,
.bpp = 16,
.yuv = false,
.lddfr = LDDFR_PKF_RGB16,
.meram = SH_MOBILE_MERAM_PF_RGB,
}, {
.fourcc = DRM_FORMAT_RGB888,
.bpp = 24,
.yuv = false,
.lddfr = LDDFR_PKF_RGB24,
.meram = SH_MOBILE_MERAM_PF_RGB,
}, {
.fourcc = DRM_FORMAT_ARGB8888,
.bpp = 32,
.yuv = false,
.lddfr = LDDFR_PKF_ARGB32,
.meram = SH_MOBILE_MERAM_PF_RGB,
}, {
.fourcc = DRM_FORMAT_NV12,
.bpp = 12,
.yuv = true,
.lddfr = LDDFR_CC | LDDFR_YF_420,
.meram = SH_MOBILE_MERAM_PF_NV,
}, {
.fourcc = DRM_FORMAT_NV21,
.bpp = 12,
.yuv = true,
.lddfr = LDDFR_CC | LDDFR_YF_420,
.meram = SH_MOBILE_MERAM_PF_NV,
}, {
.fourcc = DRM_FORMAT_NV16,
.bpp = 16,
.yuv = true,
.lddfr = LDDFR_CC | LDDFR_YF_422,
.meram = SH_MOBILE_MERAM_PF_NV,
}, {
.fourcc = DRM_FORMAT_NV61,
.bpp = 16,
.yuv = true,
.lddfr = LDDFR_CC | LDDFR_YF_422,
.meram = SH_MOBILE_MERAM_PF_NV,
}, {
.fourcc = DRM_FORMAT_NV24,
.bpp = 24,
.yuv = true,
.lddfr = LDDFR_CC | LDDFR_YF_444,
.meram = SH_MOBILE_MERAM_PF_NV24,
}, {
.fourcc = DRM_FORMAT_NV42,
.bpp = 24,
.yuv = true,
.lddfr = LDDFR_CC | LDDFR_YF_444,
.meram = SH_MOBILE_MERAM_PF_NV24,
},
};
const struct shmob_drm_format_info *shmob_drm_format_info(u32 fourcc)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(shmob_drm_format_infos); ++i) {
if (shmob_drm_format_infos[i].fourcc == fourcc)
return &shmob_drm_format_infos[i];
}
return NULL;
}
/* -----------------------------------------------------------------------------
* Frame buffer
*/
static struct drm_framebuffer *
shmob_drm_fb_create(struct drm_device *dev, struct drm_file *file_priv,
struct drm_mode_fb_cmd2 *mode_cmd)
{
const struct shmob_drm_format_info *format;
format = shmob_drm_format_info(mode_cmd->pixel_format);
if (format == NULL) {
dev_dbg(dev->dev, "unsupported pixel format %08x\n",
mode_cmd->pixel_format);
return ERR_PTR(-EINVAL);
}
if (mode_cmd->pitches[0] & 7 || mode_cmd->pitches[0] >= 65536) {
dev_dbg(dev->dev, "invalid pitch value %u\n",
mode_cmd->pitches[0]);
return ERR_PTR(-EINVAL);
}
if (format->yuv) {
unsigned int chroma_cpp = format->bpp == 24 ? 2 : 1;
if (mode_cmd->pitches[1] != mode_cmd->pitches[0] * chroma_cpp) {
dev_dbg(dev->dev,
"luma and chroma pitches do not match\n");
return ERR_PTR(-EINVAL);
}
}
return drm_fb_cma_create(dev, file_priv, mode_cmd);
}
static const struct drm_mode_config_funcs shmob_drm_mode_config_funcs = {
.fb_create = shmob_drm_fb_create,
};
int shmob_drm_modeset_init(struct shmob_drm_device *sdev)
{
drm_mode_config_init(sdev->ddev);
shmob_drm_crtc_create(sdev);
shmob_drm_encoder_create(sdev);
shmob_drm_connector_create(sdev, &sdev->encoder.encoder);
drm_kms_helper_poll_init(sdev->ddev);
sdev->ddev->mode_config.min_width = 0;
sdev->ddev->mode_config.min_height = 0;
sdev->ddev->mode_config.max_width = 4095;
sdev->ddev->mode_config.max_height = 4095;
sdev->ddev->mode_config.funcs = &shmob_drm_mode_config_funcs;
drm_helper_disable_unused_functions(sdev->ddev);
return 0;
}
| mit |
allwinner-ics/platform_external_collada | src/1.4/dom/domCg_setparam.cpp | 19 | 2959 | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the MIT Open Source License, for details please see license.txt or the website
* http://www.opensource.org/licenses/mit-license.php
*
*/
#include <dae.h>
#include <dae/daeDom.h>
#include <dom/domCg_setparam.h>
#include <dae/daeMetaCMPolicy.h>
#include <dae/daeMetaSequence.h>
#include <dae/daeMetaChoice.h>
#include <dae/daeMetaGroup.h>
#include <dae/daeMetaAny.h>
#include <dae/daeMetaElementAttribute.h>
daeElementRef
domCg_setparam::create(DAE& dae)
{
domCg_setparamRef ref = new domCg_setparam(dae);
return ref;
}
daeMetaElement *
domCg_setparam::registerElement(DAE& dae)
{
daeMetaElement* meta = dae.getMeta(ID());
if ( meta != NULL ) return meta;
meta = new daeMetaElement(dae);
dae.setMeta(ID(), *meta);
meta->setName( "cg_setparam" );
meta->registerClass(domCg_setparam::create);
daeMetaCMPolicy *cm = NULL;
daeMetaElementAttribute *mea = NULL;
cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 );
mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 );
mea->setName( "cg_param_type" );
mea->setOffset( daeOffsetOf(domCg_setparam,elemCg_param_type) );
mea->setElementType( domCg_param_type::registerElement(dae) );
cm->appendChild( new daeMetaGroup( mea, meta, cm, 0, 1, 1 ) );
mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 );
mea->setName( "usertype" );
mea->setOffset( daeOffsetOf(domCg_setparam,elemUsertype) );
mea->setElementType( domCg_setuser_type::registerElement(dae) );
cm->appendChild( mea );
mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 );
mea->setName( "array" );
mea->setOffset( daeOffsetOf(domCg_setparam,elemArray) );
mea->setElementType( domCg_setarray_type::registerElement(dae) );
cm->appendChild( mea );
mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 );
mea->setName( "connect_param" );
mea->setOffset( daeOffsetOf(domCg_setparam,elemConnect_param) );
mea->setElementType( domCg_connect_param::registerElement(dae) );
cm->appendChild( mea );
cm->setMaxOrdinal( 0 );
meta->setCMRoot( cm );
// Ordered list of sub-elements
meta->addContents(daeOffsetOf(domCg_setparam,_contents));
meta->addContentsOrder(daeOffsetOf(domCg_setparam,_contentsOrder));
meta->addCMDataArray(daeOffsetOf(domCg_setparam,_CMData), 1);
// Add attribute: ref
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "ref" );
ma->setType( dae.getAtomicTypes().get("Cg_identifier"));
ma->setOffset( daeOffsetOf( domCg_setparam , attrRef ));
ma->setContainer( meta );
ma->setIsRequired( true );
meta->appendAttribute(ma);
}
// Add attribute: program
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "program" );
ma->setType( dae.getAtomicTypes().get("xsNCName"));
ma->setOffset( daeOffsetOf( domCg_setparam , attrProgram ));
ma->setContainer( meta );
meta->appendAttribute(ma);
}
meta->setElementSize(sizeof(domCg_setparam));
meta->validate();
return meta;
}
| mit |
romyny/cbir_binary_code | caffe/src/caffe/util/benchmark.cpp | 19 | 3778 | #include <boost/date_time/posix_time/posix_time.hpp>
#include "caffe/common.hpp"
#include "caffe/util/benchmark.hpp"
namespace caffe {
Timer::Timer()
: initted_(false),
running_(false),
has_run_at_least_once_(false) {
Init();
}
Timer::~Timer() {
if (Caffe::mode() == Caffe::GPU) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaEventDestroy(start_gpu_));
CUDA_CHECK(cudaEventDestroy(stop_gpu_));
#else
NO_GPU;
#endif
}
}
void Timer::Start() {
if (!running()) {
if (Caffe::mode() == Caffe::GPU) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaEventRecord(start_gpu_, 0));
#else
NO_GPU;
#endif
} else {
start_cpu_ = boost::posix_time::microsec_clock::local_time();
}
running_ = true;
has_run_at_least_once_ = true;
}
}
void Timer::Stop() {
if (running()) {
if (Caffe::mode() == Caffe::GPU) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaEventRecord(stop_gpu_, 0));
#else
NO_GPU;
#endif
} else {
stop_cpu_ = boost::posix_time::microsec_clock::local_time();
}
running_ = false;
}
}
float Timer::MicroSeconds() {
if (!has_run_at_least_once()) {
LOG(WARNING) << "Timer has never been run before reading time.";
return 0;
}
if (running()) {
Stop();
}
if (Caffe::mode() == Caffe::GPU) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaEventSynchronize(stop_gpu_));
CUDA_CHECK(cudaEventElapsedTime(&elapsed_milliseconds_, start_gpu_,
stop_gpu_));
// Cuda only measure milliseconds
elapsed_microseconds_ = elapsed_milliseconds_ * 1000;
#else
NO_GPU;
#endif
} else {
elapsed_microseconds_ = (stop_cpu_ - start_cpu_).total_microseconds();
}
return elapsed_microseconds_;
}
float Timer::MilliSeconds() {
if (!has_run_at_least_once()) {
LOG(WARNING) << "Timer has never been run before reading time.";
return 0;
}
if (running()) {
Stop();
}
if (Caffe::mode() == Caffe::GPU) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaEventSynchronize(stop_gpu_));
CUDA_CHECK(cudaEventElapsedTime(&elapsed_milliseconds_, start_gpu_,
stop_gpu_));
#else
NO_GPU;
#endif
} else {
elapsed_milliseconds_ = (stop_cpu_ - start_cpu_).total_milliseconds();
}
return elapsed_milliseconds_;
}
float Timer::Seconds() {
return MilliSeconds() / 1000.;
}
void Timer::Init() {
if (!initted()) {
if (Caffe::mode() == Caffe::GPU) {
#ifndef CPU_ONLY
CUDA_CHECK(cudaEventCreate(&start_gpu_));
CUDA_CHECK(cudaEventCreate(&stop_gpu_));
#else
NO_GPU;
#endif
}
initted_ = true;
}
}
CPUTimer::CPUTimer() {
this->initted_ = true;
this->running_ = false;
this->has_run_at_least_once_ = false;
}
void CPUTimer::Start() {
if (!running()) {
this->start_cpu_ = boost::posix_time::microsec_clock::local_time();
this->running_ = true;
this->has_run_at_least_once_ = true;
}
}
void CPUTimer::Stop() {
if (running()) {
this->stop_cpu_ = boost::posix_time::microsec_clock::local_time();
this->running_ = false;
}
}
float CPUTimer::MilliSeconds() {
if (!has_run_at_least_once()) {
LOG(WARNING) << "Timer has never been run before reading time.";
return 0;
}
if (running()) {
Stop();
}
this->elapsed_milliseconds_ = (this->stop_cpu_ -
this->start_cpu_).total_milliseconds();
return this->elapsed_milliseconds_;
}
float CPUTimer::MicroSeconds() {
if (!has_run_at_least_once()) {
LOG(WARNING) << "Timer has never been run before reading time.";
return 0;
}
if (running()) {
Stop();
}
this->elapsed_microseconds_ = (this->stop_cpu_ -
this->start_cpu_).total_microseconds();
return this->elapsed_microseconds_;
}
} // namespace caffe
| mit |
rachitb777/samples | AllJoyn/Samples/ZWaveAdapter/AdapterLib/ZWaveAdapterDevice.cpp | 21 | 7489 | // Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include "pch.h"
#include "ZWaveAdapterDevice.h"
#include "ZWaveAdapterProperty.h"
#include "ZWaveAdapterSignal.h"
#include "ZWaveAdapterMethod.h"
#include "Manager.h"
#include "BridgeUtils.h"
#include "AdapterUtils.h"
#include <string>
#include <sstream>
using namespace BridgeRT;
using namespace Platform;
using namespace Windows::Foundation;
using namespace std;
using namespace OpenZWave;
using namespace BridgeRT;
namespace AdapterLib
{
ZWaveAdapterDevice::ZWaveAdapterDevice(ZWaveAdapter^ adapter, uint32 homeId, uint8 nodeId)
: m_homeId(homeId)
, m_nodeId(nodeId)
, m_controlPanel(nullptr)
, m_lightingServiceHandler(nullptr)
, m_parent(adapter)
{
}
void ZWaveAdapterDevice::AddPropertyValue(const ValueID& value)
{
//check to see if its a method(button)
ValueID::ValueType type = value.GetType();
if (type == ValueID::ValueType::ValueType_Button)
{
//add it as a method
//if the method is already in the list, ignore
if (find_if(m_methods.begin(), m_methods.end(), [&value](IAdapterMethod^ method)
{
return dynamic_cast<ZWaveAdapterMethod^>(method)->m_valueId == value;
}) == m_methods.end())
{
m_methods.push_back(ref new ZWaveAdapterMethod(value));
}
}
else
{
//add it as property
//get the property
auto adapterProperty = GetProperty(value);
if (adapterProperty == m_properties.end())
{
m_properties.push_back(ref new ZWaveAdapterProperty(value));
}
}
}
void ZWaveAdapterDevice::UpdatePropertyValue(const ValueID& value)
{
//get the property
auto adapterProperty = GetProperty(value);
if (adapterProperty != m_properties.end())
{
(dynamic_cast<ZWaveAdapterProperty^>(*adapterProperty))->UpdateValue();
}
}
void ZWaveAdapterDevice::RemovePropertyValue(const ValueID & value)
{
//get the property
auto adapterProperty = GetProperty(value);
if (adapterProperty != m_properties.end())
{
m_properties.erase(adapterProperty);
}
}
ZWaveAdapterProperty^ ZWaveAdapterDevice::GetPropertyByName(Platform::String^ name)
{
// Try to find the specified adapter property
auto iter = find_if(begin(Properties), end(Properties), [&name](IAdapterProperty^ adapterProperty)
{
ZWaveAdapterProperty^ currProperty = dynamic_cast<ZWaveAdapterProperty^>(adapterProperty);
return currProperty->Name == name;
});
// return null if not found, or the property reference if it was found
IAdapterProperty^ outProperty = nullptr;
if (iter != end(Properties))
{
outProperty = *(iter);
}
return dynamic_cast<ZWaveAdapterProperty^>(outProperty);
}
std::vector<BridgeRT::IAdapterProperty^>::iterator ZWaveAdapterDevice::GetProperty(const ValueID & value)
{
//find if the property already exist
auto iter = find_if(m_properties.begin(), m_properties.end(), [&value](IAdapterProperty^ adapterProperty)
{
return (dynamic_cast<ZWaveAdapterProperty^>(adapterProperty))->m_valueId == value;
});
return iter;
}
void ZWaveAdapterDevice::BuildSignals()
{
//first clear the list
m_signals.clear();
ZWaveAdapterSignal^ signal = ref new ZWaveAdapterSignal(Constants::CHANGE_OF_VALUE_SIGNAL);
//add params
ValueID value(uint32(0), uint64(0)); //placeholder value
ZWaveAdapterProperty^ tmpProperty = ref new ZWaveAdapterProperty(value);
ZWaveAdapterValue^ tmpValue = ref new ZWaveAdapterValue(L"CovPlaceHolder", nullptr);
signal->AddParam(ref new ZWaveAdapterValue(Constants::COV__PROPERTY_HANDLE, tmpProperty));
signal->AddParam(ref new ZWaveAdapterValue(Constants::COV__ATTRIBUTE_HANDLE, tmpValue));
m_signals.push_back(signal);
}
IAdapterSignal^ ZWaveAdapterDevice::GetSignal(String^ name)
{
for (auto signal : m_signals)
{
if (signal->Name == ref new String(name->Data()))
{
return signal;
}
}
return nullptr;
}
void ZWaveAdapterDevice::AddLampStateChangedSignal()
{
try
{
ZWaveAdapterSignal^ lampStateChangedSignal = ref new ZWaveAdapterSignal(Constants::LAMP_STATE_CHANGED_SIGNAL_NAME);
Platform::Object^ data = PropertyValue::CreateString(m_serialNumber);
ZWaveAdapterValue^ lampIdSignalParameter = ref new ZWaveAdapterValue(Constants::SIGNAL_PARAMETER__LAMP_ID__NAME, data);
lampStateChangedSignal->AddParam(lampIdSignalParameter);
m_signals.push_back(lampStateChangedSignal);
}
catch (OutOfMemoryException^ ex)
{
return;
}
}
void ZWaveAdapterDevice::Initialize()
{
wstringstream ss;
//prepend the home id and node id to the name
wstring nodeName = ConvertTo<wstring>(Manager::Get()->GetNodeName(m_homeId, m_nodeId));
if (nodeName.empty())
{
ss << L"HomeID_" << m_homeId << L"_Node_" << (uint32)m_nodeId;
nodeName = ss.str();
}
m_name = ref new String(nodeName.c_str());
//vendor
m_vendor = ref new String(ConvertTo<wstring>(Manager::Get()->GetNodeManufacturerName(m_homeId, m_nodeId)).c_str());
//model
m_model = ref new String(ConvertTo<wstring>(Manager::Get()->GetNodeProductName(m_homeId, m_nodeId)).c_str());
//version
ss.str(L"");
ss << (uint32)Manager::Get()->GetNodeVersion(m_homeId, m_nodeId);
m_version = ref new String(ss.str().c_str());
//description
m_description = ref new String(ConvertTo<wstring>(Manager::Get()->GetNodeType(m_homeId, m_nodeId)).c_str());
//FW version
m_firmwareVersion = ref new String();
//serial number
ss.str(L"");
ss << m_homeId << L"_" << (uint32)m_nodeId;
m_serialNumber = ref new String(ss.str().c_str());
BuildSignals();
//initialize properties
for (auto prop : m_properties)
{
dynamic_cast<ZWaveAdapterProperty^>(prop)->Initialize(m_parent);
}
//initialize methods
for (auto method : m_methods)
{
dynamic_cast<ZWaveAdapterMethod^>(method)->Initialize();
}
}
}
| mit |
Ghost233/MatchMaster | MatchMaster/cocos2d/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp | 22 | 7808 | /*
* Copyright (c) 2012 cocos2d-x.org
* http://www.cocos2d-x.org
*
* Copyright 2012 Stewart Hamilton-Arrandale.
* http://creativewax.co.uk
*
* Modified by Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Converted to c++ / cocos2d-x by Angus C
*/
#include "CCControlSaturationBrightnessPicker.h"
NS_CC_EXT_BEGIN
ControlSaturationBrightnessPicker::ControlSaturationBrightnessPicker()
: _saturation(0.0f)
, _brightness(0.0f)
, _background(NULL)
, _overlay(NULL)
, _shadow(NULL)
, _slider(NULL)
, boxPos(0)
, boxSize(0)
{
}
ControlSaturationBrightnessPicker::~ControlSaturationBrightnessPicker()
{
removeAllChildrenWithCleanup(true);
_background = NULL;
_overlay = NULL;
_shadow = NULL;
_slider = NULL;
}
bool ControlSaturationBrightnessPicker::initWithTargetAndPos(Node* target, Point pos)
{
if (Control::init())
{
// Add background and slider sprites
_background=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerBackground.png", target, pos, Point(0.0f, 0.0f));
_overlay=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerOverlay.png", target, pos, Point(0.0f, 0.0f));
_shadow=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerShadow.png", target, pos, Point(0.0f, 0.0f));
_slider=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, Point(0.5f, 0.5f));
_startPos=pos; // starting position of the colour picker
boxPos = 35; // starting position of the virtual box area for picking a colour
boxSize = _background->getContentSize().width / 2;; // the size (width and height) of the virtual box for picking a colour from
return true;
}
else
{
return false;
}
}
ControlSaturationBrightnessPicker* ControlSaturationBrightnessPicker::create(Node* target, Point pos)
{
ControlSaturationBrightnessPicker *pRet = new ControlSaturationBrightnessPicker();
pRet->initWithTargetAndPos(target, pos);
pRet->autorelease();
return pRet;
}
void ControlSaturationBrightnessPicker::setEnabled(bool enabled)
{
Control::setEnabled(enabled);
if (_slider != NULL)
{
_slider->setOpacity(enabled ? 255 : 128);
}
}
void ControlSaturationBrightnessPicker::updateWithHSV(HSV hsv)
{
HSV hsvTemp;
hsvTemp.s = 1;
hsvTemp.h = hsv.h;
hsvTemp.v = 1;
RGBA rgb = ControlUtils::RGBfromHSV(hsvTemp);
_background->setColor(Color3B((GLubyte)(rgb.r * 255.0f), (GLubyte)(rgb.g * 255.0f), (GLubyte)(rgb.b * 255.0f)));
}
void ControlSaturationBrightnessPicker::updateDraggerWithHSV(HSV hsv)
{
// Set the position of the slider to the correct saturation and brightness
Point pos = Point(_startPos.x + boxPos + (boxSize*(1 - hsv.s)),
_startPos.y + boxPos + (boxSize*hsv.v));
// update
updateSliderPosition(pos);
}
void ControlSaturationBrightnessPicker::updateSliderPosition(Point sliderPosition)
{
// Clamp the position of the icon within the circle
// Get the center point of the bkgd image
float centerX = _startPos.x + _background->getBoundingBox().size.width*0.5f;
float centerY = _startPos.y + _background->getBoundingBox().size.height*0.5f;
// Work out the distance difference between the location and center
float dx = sliderPosition.x - centerX;
float dy = sliderPosition.y - centerY;
float dist = sqrtf(dx * dx + dy * dy);
// Update angle by using the direction of the location
float angle = atan2f(dy, dx);
// Set the limit to the slider movement within the colour picker
float limit = _background->getBoundingBox().size.width*0.5f;
// Check distance doesn't exceed the bounds of the circle
if (dist > limit)
{
sliderPosition.x = centerX + limit * cosf(angle);
sliderPosition.y = centerY + limit * sinf(angle);
}
// Set the position of the dragger
_slider->setPosition(sliderPosition);
// Clamp the position within the virtual box for colour selection
if (sliderPosition.x < _startPos.x + boxPos) sliderPosition.x = _startPos.x + boxPos;
else if (sliderPosition.x > _startPos.x + boxPos + boxSize - 1) sliderPosition.x = _startPos.x + boxPos + boxSize - 1;
if (sliderPosition.y < _startPos.y + boxPos) sliderPosition.y = _startPos.y + boxPos;
else if (sliderPosition.y > _startPos.y + boxPos + boxSize) sliderPosition.y = _startPos.y + boxPos + boxSize;
// Use the position / slider width to determin the percentage the dragger is at
_saturation = 1.0f - fabs((_startPos.x + (float)boxPos - sliderPosition.x)/(float)boxSize);
_brightness = fabs((_startPos.y + (float)boxPos - sliderPosition.y)/(float)boxSize);
}
bool ControlSaturationBrightnessPicker::checkSliderPosition(Point location)
{
// Clamp the position of the icon within the circle
// get the center point of the bkgd image
float centerX = _startPos.x + _background->getBoundingBox().size.width*0.5f;
float centerY = _startPos.y + _background->getBoundingBox().size.height*0.5f;
// work out the distance difference between the location and center
float dx = location.x - centerX;
float dy = location.y - centerY;
float dist = sqrtf(dx*dx+dy*dy);
// check that the touch location is within the bounding rectangle before sending updates
if (dist <= _background->getBoundingBox().size.width*0.5f)
{
updateSliderPosition(location);
sendActionsForControlEvents(Control::EventType::VALUE_CHANGED);
return true;
}
return false;
}
bool ControlSaturationBrightnessPicker::onTouchBegan(Touch* touch, Event* event)
{
if (!isEnabled() || !isVisible())
{
return false;
}
// Get the touch location
Point touchLocation=getTouchLocation(touch);
// Check the touch position on the slider
return checkSliderPosition(touchLocation);
}
void ControlSaturationBrightnessPicker::onTouchMoved(Touch* touch, Event* event)
{
// Get the touch location
Point touchLocation=getTouchLocation(touch);
//small modification: this allows changing of the colour, even if the touch leaves the bounding area
// updateSliderPosition(touchLocation);
// sendActionsForControlEvents(Control::EventType::VALUE_CHANGED);
// Check the touch position on the slider
checkSliderPosition(touchLocation);
}
NS_CC_EXT_END
| mit |
philippeback/urbit | outside/libuv_0.11/test/test-tcp-try-write.c | 24 | 3742 | /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "uv.h"
#include "task.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BYTES 1024 * 1024
#ifdef _WIN32
TEST_IMPL(tcp_try_write) {
MAKE_VALGRIND_HAPPY();
return 0;
}
#else /* !_WIN32 */
static uv_tcp_t server;
static uv_tcp_t client;
static uv_tcp_t incoming;
static int connect_cb_called;
static int close_cb_called;
static int connection_cb_called;
static int bytes_read;
static int bytes_written;
static void close_cb(uv_handle_t* handle) {
close_cb_called++;
}
static void connect_cb(uv_connect_t* req, int status) {
int r;
uv_buf_t buf;
ASSERT(status == 0);
connect_cb_called++;
do {
buf = uv_buf_init("PING", 4);
r = uv_try_write((uv_stream_t*) &client, &buf, 1);
ASSERT(r > 0 || r == UV_EAGAIN);
if (r > 0) {
bytes_written += r;
break;
}
} while (1);
uv_close((uv_handle_t*) &client, close_cb);
}
static void alloc_cb(uv_handle_t* handle, size_t size, uv_buf_t* buf) {
static char base[1024];
buf->base = base;
buf->len = sizeof(base);
}
static void read_cb(uv_stream_t* tcp, ssize_t nread, const uv_buf_t* buf) {
if (nread < 0) {
uv_close((uv_handle_t*) tcp, close_cb);
uv_close((uv_handle_t*) &server, close_cb);
return;
}
bytes_read += nread;
}
static void connection_cb(uv_stream_t* tcp, int status) {
ASSERT(status == 0);
ASSERT(0 == uv_tcp_init(tcp->loop, &incoming));
ASSERT(0 == uv_accept(tcp, (uv_stream_t*) &incoming));
connection_cb_called++;
ASSERT(0 == uv_read_start((uv_stream_t*) &incoming, alloc_cb, read_cb));
}
static void start_server(void) {
struct sockaddr_in addr;
ASSERT(0 == uv_ip4_addr("0.0.0.0", TEST_PORT, &addr));
ASSERT(0 == uv_tcp_init(uv_default_loop(), &server));
ASSERT(0 == uv_tcp_bind(&server, (struct sockaddr*) &addr, 0));
ASSERT(0 == uv_listen((uv_stream_t*) &server, 128, connection_cb));
}
TEST_IMPL(tcp_try_write) {
uv_connect_t connect_req;
struct sockaddr_in addr;
start_server();
ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr));
ASSERT(0 == uv_tcp_init(uv_default_loop(), &client));
ASSERT(0 == uv_tcp_connect(&connect_req,
&client,
(struct sockaddr*) &addr,
connect_cb));
ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT));
ASSERT(connect_cb_called == 1);
ASSERT(close_cb_called == 3);
ASSERT(connection_cb_called == 1);
ASSERT(bytes_read == bytes_written);
ASSERT(bytes_written > 0);
MAKE_VALGRIND_HAPPY();
return 0;
}
#endif /* !_WIN32 */
| mit |
GuzmanPI/AngularEs | node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c | 3352 | 3691 | /**
* Copyright (c) 2006-2008 Apple Inc. 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.
**/
#include "base64.h"
#include <stdlib.h>
#include <string.h>
// base64 tables
static char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static signed char index_64[128] =
{
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
};
#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)])
// base64_encode : base64 encode
//
// value : data to encode
// vlen : length of data
// (result) : new char[] - c-str of result
char *base64_encode(const unsigned char *value, int vlen)
{
char *result = (char *)malloc((vlen * 4) / 3 + 5);
char *out = result;
unsigned char oval;
while (vlen >= 3)
{
*out++ = basis_64[value[0] >> 2];
*out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)];
*out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)];
*out++ = basis_64[value[2] & 0x3F];
value += 3;
vlen -= 3;
}
if (vlen > 0)
{
*out++ = basis_64[value[0] >> 2];
oval = (value[0] << 4) & 0x30;
if (vlen > 1) oval |= value[1] >> 4;
*out++ = basis_64[oval];
*out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C];
*out++ = '=';
}
*out = '\0';
return result;
}
// base64_decode : base64 decode
//
// value : c-str to decode
// rlen : length of decoded result
// (result) : new unsigned char[] - decoded result
unsigned char *base64_decode(const char *value, int *rlen)
{
int c1, c2, c3, c4;
int vlen = (int)strlen(value);
unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1);
unsigned char *out = result;
*rlen = 0;
while (1)
{
if (value[0]==0)
return result;
c1 = value[0];
if (CHAR64(c1) == -1)
goto base64_decode_error;;
c2 = value[1];
if (CHAR64(c2) == -1)
goto base64_decode_error;;
c3 = value[2];
if ((c3 != '=') && (CHAR64(c3) == -1))
goto base64_decode_error;;
c4 = value[3];
if ((c4 != '=') && (CHAR64(c4) == -1))
goto base64_decode_error;;
value += 4;
*out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4);
*rlen += 1;
if (c3 != '=')
{
*out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2);
*rlen += 1;
if (c4 != '=')
{
*out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4);
*rlen += 1;
}
}
}
base64_decode_error:
*result = 0;
*rlen = 0;
return result;
}
| mit |
JohanAlvarado/heroku-buildpack-ruby-with-qrencode | qrencode-3.2.0/tests/view_qrcode.c | 25 | 12611 | #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <SDL.h>
#include <getopt.h>
#include <errno.h>
#include "../config.h"
#include "../qrspec.h"
#include "../qrinput.h"
#include "../split.h"
#include "../qrencode_inner.h"
static SDL_Surface *screen = NULL;
static int casesensitive = 1;
static int eightbit = 0;
static int version = 1;
static int size = 4;
static int margin = 4;
static int structured = 0;
static int micro = 0;
static QRecLevel level = QR_ECLEVEL_L;
static QRencodeMode hint = QR_MODE_8;
static char **textv;
static int textc;
static const struct option options[] = {
{"help" , no_argument , NULL, 'h'},
{"level" , required_argument, NULL, 'l'},
{"size" , required_argument, NULL, 's'},
{"symversion" , required_argument, NULL, 'v'},
{"margin" , required_argument, NULL, 'm'},
{"structured" , no_argument , NULL, 'S'},
{"kanji" , no_argument , NULL, 'k'},
{"casesensitive", no_argument , NULL, 'c'},
{"ignorecase" , no_argument , NULL, 'i'},
{"8bit" , no_argument , NULL, '8'},
{"micro" , no_argument , NULL, 'M'},
{"version" , no_argument , NULL, 'V'},
{NULL, 0, NULL, 0}
};
static char *optstring = "hl:s:v:m:Skci8MV";
static char levelChar[4] = {'L', 'M', 'Q', 'H'};
static void usage(int help, int longopt)
{
fprintf(stderr,
"view_qrcode version %s\n"
"Copyright (C) 2008, 2009, 2010 Kentaro Fukuchi\n", VERSION);
if(help) {
if(longopt) {
fprintf(stderr,
"Usage: view_qrcode [OPTION]... [STRING]\n"
"Encode input data in a QR Code and display.\n\n"
" -h, --help display the help message. -h displays only the help of short\n"
" options.\n\n"
" -s NUMBER, --size=NUMBER\n"
" specify module size in dots (pixels). (default=3)\n\n"
" -l {LMQH}, --level={LMQH}\n"
" specify error correction level from L (lowest) to H (highest).\n"
" (default=L)\n\n"
" -v NUMBER, --symversion=NUMBER\n"
" specify the version of the symbol. (default=auto)\n\n"
" -m NUMBER, --margin=NUMBER\n"
" specify the width of the margins. (default=4)\n\n"
" -S, --structured\n"
" make structured symbols. Version must be specified.\n\n"
" -k, --kanji assume that the input text contains kanji (shift-jis).\n\n"
" -c, --casesensitive\n"
" encode lower-case alphabet characters in 8-bit mode. (default)\n\n"
" -i, --ignorecase\n"
" ignore case distinctions and use only upper-case characters.\n\n"
" -8, --8bit encode entire data in 8-bit mode. -k, -c and -i will be ignored.\n\n"
" -M, --micro encode in a Micro QR Code. (experimental)\n\n"
" -V, --version\n"
" display the version number and copyrights of the qrencode.\n\n"
" [STRING] input data. If it is not specified, data will be taken from\n"
" standard input.\n"
);
} else {
fprintf(stderr,
"Usage: view_qrcode [OPTION]... [STRING]\n"
"Encode input data in a QR Code and display.\n\n"
" -h display this message.\n"
" --help display the usage of long options.\n"
" -s NUMBER specify module size in dots (pixels). (default=3)\n"
" -l {LMQH} specify error correction level from L (lowest) to H (highest).\n"
" (default=L)\n"
" -v NUMBER specify the version of the symbol. (default=auto)\n"
" -m NUMBER specify the width of the margins. (default=4)\n"
" -S make structured symbols. Version must be specified.\n"
" -k assume that the input text contains kanji (shift-jis).\n"
" -c encode lower-case alphabet characters in 8-bit mode. (default)\n"
" -i ignore case distinctions and use only upper-case characters.\n"
" -8 encode entire data in 8-bit mode. -k, -c and -i will be ignored.\n"
" -M encode in a Micro QR Code.\n"
" -V display the version number and copyrights of the qrencode.\n"
" [STRING] input data. If it is not specified, data will be taken from\n"
" standard input.\n"
);
}
}
}
#define MAX_DATA_SIZE (7090 * 16) /* from the specification */
static unsigned char *readStdin(int *length)
{
unsigned char *buffer;
int ret;
buffer = (unsigned char *)malloc(MAX_DATA_SIZE + 1);
if(buffer == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
ret = fread(buffer, 1, MAX_DATA_SIZE, stdin);
if(ret == 0) {
fprintf(stderr, "No input data.\n");
exit(EXIT_FAILURE);
}
if(feof(stdin) == 0) {
fprintf(stderr, "Input data is too large.\n");
exit(EXIT_FAILURE);
}
buffer[ret] = '\0';
*length = ret;
return buffer;
}
static void draw_QRcode(QRcode *qrcode, int ox, int oy)
{
int x, y, width;
unsigned char *p;
SDL_Rect rect;
ox += margin * size;
oy += margin * size;
width = qrcode->width;
p = qrcode->data;
for(y=0; y<width; y++) {
for(x=0; x<width; x++) {
rect.x = ox + x * size;
rect.y = oy + y * size;
rect.w = size;
rect.h = size;
SDL_FillRect(screen, &rect, (*p&1)?0:0xffffff);
p++;
}
}
}
void draw_singleQRcode(QRinput *stream, int mask)
{
QRcode *qrcode;
int width;
QRinput_setVersionAndErrorCorrectionLevel(stream, version, level);
if(micro) {
qrcode = QRcode_encodeMaskMQR(stream, mask);
} else {
qrcode = QRcode_encodeMask(stream, mask);
}
if(qrcode == NULL) {
width = (11 + margin * 2) * size;
fprintf(stderr, "Input data does not fit to this setting.\n");
} else {
version = qrcode->version;
width = (qrcode->width + margin * 2) * size;
}
screen = SDL_SetVideoMode(width, width, 32, 0);
SDL_FillRect(screen, NULL, 0xffffff);
if(qrcode) {
draw_QRcode(qrcode, 0, 0);
}
SDL_Flip(screen);
QRcode_free(qrcode);
}
void draw_structuredQRcode(QRinput_Struct *s)
{
int i, w, h, n, x, y;
int swidth;
QRcode_List *qrcodes, *p;
qrcodes = QRcode_encodeInputStructured(s);
if(qrcodes == NULL) return;
swidth = (qrcodes->code->width + margin * 2) * size;
n = QRcode_List_size(qrcodes);
w = (n < 4)?n:4;
h = (n - 1) / 4 + 1;
screen = SDL_SetVideoMode(swidth * w, swidth * h, 32, 0);
SDL_FillRect(screen, NULL, 0xffffff);
p = qrcodes;
for(i=0; i<n; i++) {
x = (i % 4) * swidth;
y = (i / 4) * swidth;
draw_QRcode(p->code, x, y);
p = p->next;
}
SDL_Flip(screen);
QRcode_List_free(qrcodes);
}
void draw_structuredQRcodeFromText(int argc, char **argv)
{
QRinput_Struct *s;
QRinput *input;
int i, ret;
s = QRinput_Struct_new();
if(s == NULL) {
fprintf(stderr, "Failed to allocate memory.\n");
exit(EXIT_FAILURE);
}
for(i=0; i<argc; i++) {
input = QRinput_new2(version, level);
if(input == NULL) {
fprintf(stderr, "Failed to allocate memory.\n");
exit(EXIT_FAILURE);
}
if(eightbit) {
ret = QRinput_append(input, QR_MODE_8, strlen(argv[i]), (unsigned char *)argv[i]);
} else {
ret = Split_splitStringToQRinput(argv[i], input, hint, casesensitive);
}
if(ret < 0) {
perror("Encoding the input string");
exit(EXIT_FAILURE);
}
ret = QRinput_Struct_appendInput(s, input);
if(ret < 0) {
perror("Encoding the input string");
exit(EXIT_FAILURE);
}
}
ret = QRinput_Struct_insertStructuredAppendHeaders(s);
if(ret < 0) {
fprintf(stderr, "Too many inputs.\n");
}
draw_structuredQRcode(s);
QRinput_Struct_free(s);
}
void draw_structuredQRcodeFromQRinput(QRinput *stream)
{
QRinput_Struct *s;
QRinput_setVersion(stream, version);
QRinput_setErrorCorrectionLevel(stream, level);
s = QRinput_splitQRinputToStruct(stream);
if(s != NULL) {
draw_structuredQRcode(s);
QRinput_Struct_free(s);
} else {
fprintf(stderr, "Input data is too large for this setting.\n");
}
}
void view(int mode, QRinput *input)
{
int flag = 1;
int mask = -1;
SDL_Event event;
int loop;
while(flag) {
if(mode) {
draw_structuredQRcodeFromText(textc, textv);
} else {
if(structured) {
draw_structuredQRcodeFromQRinput(input);
} else {
draw_singleQRcode(input, mask);
}
}
if(mode || structured) {
printf("Version %d, Level %c.\n", version, levelChar[level]);
} else {
printf("Version %d, Level %c, Mask %d.\n", version, levelChar[level], mask);
}
loop = 1;
while(loop) {
usleep(10000);
while(SDL_PollEvent(&event)) {
if(event.type == SDL_KEYDOWN) {
switch(event.key.keysym.sym) {
case SDLK_RIGHT:
version++;
if(version > QRSPEC_VERSION_MAX)
version = QRSPEC_VERSION_MAX;
loop = 0;
break;
case SDLK_LEFT:
version--;
if(version < 1)
version = 1;
loop = 0;
break;
case SDLK_UP:
size++;
loop = 0;
break;
case SDLK_DOWN:
size--;
if(size < 1) size = 1;
loop = 0;
break;
case SDLK_0:
case SDLK_1:
case SDLK_2:
case SDLK_3:
case SDLK_4:
case SDLK_5:
case SDLK_6:
case SDLK_7:
if(!mode && !structured) {
mask = (event.key.keysym.sym - SDLK_0);
loop = 0;
}
break;
case SDLK_8:
if(!mode && !structured) {
mask = -1;
loop = 0;
}
break;
case SDLK_l:
level = QR_ECLEVEL_L;
loop = 0;
break;
case SDLK_m:
level = QR_ECLEVEL_M;
loop = 0;
break;
case SDLK_h:
level = QR_ECLEVEL_H;
loop = 0;
break;
case SDLK_q:
level = QR_ECLEVEL_Q;
loop = 0;
break;
case SDLK_ESCAPE:
loop = 0;
flag = 0;
break;
default:
break;
}
}
if(event.type == SDL_QUIT) {
loop = 0;
flag = 0;
}
}
}
}
}
void view_simple(const unsigned char *str, int length)
{
QRinput *input;
int ret;
if(micro) {
input = QRinput_newMQR(version, level);
} else {
input = QRinput_new2(version, level);
}
if(input == NULL) {
fprintf(stderr, "Memory allocation error.\n");
exit(EXIT_FAILURE);
}
if(eightbit) {
ret = QRinput_append(input, QR_MODE_8, length, str);
} else {
ret = Split_splitStringToQRinput((char *)str, input, hint, casesensitive);
}
if(ret < 0) {
perror("Encoding the input string");
exit(EXIT_FAILURE);
}
view(0, input);
QRinput_free(input);
}
void view_multiText(char **argv, int argc)
{
textc = argc;
textv = argv;
view(1, NULL);
}
int main(int argc, char **argv)
{
int opt, lindex = -1;
unsigned char *intext = NULL;
int length = 0;
while((opt = getopt_long(argc, argv, optstring, options, &lindex)) != -1) {
switch(opt) {
case 'h':
if(lindex == 0) {
usage(1, 1);
} else {
usage(1, 0);
}
exit(EXIT_SUCCESS);
break;
case 's':
size = atoi(optarg);
if(size <= 0) {
fprintf(stderr, "Invalid size: %d\n", size);
exit(EXIT_FAILURE);
}
break;
case 'v':
version = atoi(optarg);
if(version < 0) {
fprintf(stderr, "Invalid version: %d\n", version);
exit(EXIT_FAILURE);
}
break;
case 'l':
switch(*optarg) {
case 'l':
case 'L':
level = QR_ECLEVEL_L;
break;
case 'm':
case 'M':
level = QR_ECLEVEL_M;
break;
case 'q':
case 'Q':
level = QR_ECLEVEL_Q;
break;
case 'h':
case 'H':
level = QR_ECLEVEL_H;
break;
default:
fprintf(stderr, "Invalid level: %s\n", optarg);
exit(EXIT_FAILURE);
break;
}
break;
case 'm':
margin = atoi(optarg);
if(margin < 0) {
fprintf(stderr, "Invalid margin: %d\n", margin);
exit(EXIT_FAILURE);
}
break;
case 'S':
structured = 1;
case 'k':
hint = QR_MODE_KANJI;
break;
case 'c':
casesensitive = 1;
break;
case 'i':
casesensitive = 0;
break;
case '8':
eightbit = 1;
break;
case 'M':
micro = 1;
break;
case 'V':
usage(0, 0);
exit(EXIT_SUCCESS);
break;
default:
fprintf(stderr, "Try `view_qrcode --help' for more information.\n");
exit(EXIT_FAILURE);
break;
}
}
if(argc == 1) {
usage(1, 0);
exit(EXIT_SUCCESS);
}
if(optind < argc) {
intext = (unsigned char *)argv[optind];
length = strlen((char *)intext);
}
if(intext == NULL) {
intext = readStdin(&length);
}
if(SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Failed initializing SDL: %s\n", SDL_GetError());
return -1;
}
if(structured && version < 1) {
fprintf(stderr, "Version number must be greater than 0 to encode structured symbols.\n");
exit(EXIT_FAILURE);
}
if(structured && (argc - optind > 1)) {
view_multiText(argv + optind, argc - optind);
} else {
view_simple(intext, length);
}
SDL_Quit();
return 0;
}
| mit |
elliscnck/EmulationStation | es-core/src/resources/TextureResource.cpp | 25 | 4489 | #include "resources/TextureResource.h"
#include "Log.h"
#include "platform.h"
#include GLHEADER
#include "ImageIO.h"
#include "Renderer.h"
#include "Util.h"
#include "resources/SVGResource.h"
std::map< TextureResource::TextureKeyType, std::weak_ptr<TextureResource> > TextureResource::sTextureMap;
std::list< std::weak_ptr<TextureResource> > TextureResource::sTextureList;
TextureResource::TextureResource(const std::string& path, bool tile) :
mTextureID(0), mPath(path), mTextureSize(Eigen::Vector2i::Zero()), mTile(tile)
{
}
TextureResource::~TextureResource()
{
deinit();
}
void TextureResource::unload(std::shared_ptr<ResourceManager>& rm)
{
deinit();
}
void TextureResource::reload(std::shared_ptr<ResourceManager>& rm)
{
if(!mPath.empty())
{
const ResourceData& data = rm->getFileData(mPath);
initFromMemory((const char*)data.ptr.get(), data.length);
}
}
void TextureResource::initFromPixels(const unsigned char* dataRGBA, size_t width, size_t height)
{
deinit();
assert(width > 0 && height > 0);
//now for the openGL texture stuff
glGenTextures(1, &mTextureID);
glBindTexture(GL_TEXTURE_2D, mTextureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, dataRGBA);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
const GLint wrapMode = mTile ? GL_REPEAT : GL_CLAMP_TO_EDGE;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
mTextureSize << width, height;
}
void TextureResource::initFromMemory(const char* data, size_t length)
{
size_t width, height;
std::vector<unsigned char> imageRGBA = ImageIO::loadFromMemoryRGBA32((const unsigned char*)(data), length, width, height);
if(imageRGBA.size() == 0)
{
LOG(LogError) << "Could not initialize texture from memory, invalid data! (file path: " << mPath << ", data ptr: " << (size_t)data << ", reported size: " << length << ")";
return;
}
initFromPixels(imageRGBA.data(), width, height);
}
void TextureResource::deinit()
{
if(mTextureID != 0)
{
glDeleteTextures(1, &mTextureID);
mTextureID = 0;
}
}
const Eigen::Vector2i& TextureResource::getSize() const
{
return mTextureSize;
}
bool TextureResource::isTiled() const
{
return mTile;
}
void TextureResource::bind() const
{
if(mTextureID != 0)
glBindTexture(GL_TEXTURE_2D, mTextureID);
else
LOG(LogError) << "Tried to bind uninitialized texture!";
}
std::shared_ptr<TextureResource> TextureResource::get(const std::string& path, bool tile)
{
std::shared_ptr<ResourceManager>& rm = ResourceManager::getInstance();
const std::string canonicalPath = getCanonicalPath(path);
if(canonicalPath.empty())
{
std::shared_ptr<TextureResource> tex(new TextureResource("", tile));
rm->addReloadable(tex); //make sure we get properly deinitialized even though we do nothing on reinitialization
return tex;
}
TextureKeyType key(canonicalPath, tile);
auto foundTexture = sTextureMap.find(key);
if(foundTexture != sTextureMap.end())
{
if(!foundTexture->second.expired())
return foundTexture->second.lock();
}
// need to create it
std::shared_ptr<TextureResource> tex;
// is it an SVG?
if(key.first.substr(key.first.size() - 4, std::string::npos) == ".svg")
{
// probably
// don't add it to our map because 2 svgs might be rasterized at different sizes
tex = std::shared_ptr<SVGResource>(new SVGResource(key.first, tile));
sTextureList.push_back(tex); // add it to our list though
rm->addReloadable(tex);
tex->reload(rm);
return tex;
}else{
// normal texture
tex = std::shared_ptr<TextureResource>(new TextureResource(key.first, tile));
sTextureMap[key] = std::weak_ptr<TextureResource>(tex);
sTextureList.push_back(tex);
rm->addReloadable(tex);
tex->reload(ResourceManager::getInstance());
return tex;
}
}
bool TextureResource::isInitialized() const
{
return mTextureID != 0;
}
size_t TextureResource::getMemUsage() const
{
if(!mTextureID || mTextureSize.x() == 0 || mTextureSize.y() == 0)
return 0;
return mTextureSize.x() * mTextureSize.y() * 4;
}
size_t TextureResource::getTotalMemUsage()
{
size_t total = 0;
auto it = sTextureList.begin();
while(it != sTextureList.end())
{
if((*it).expired())
{
// remove expired textures from the list
it = sTextureList.erase(it);
continue;
}
total += (*it).lock()->getMemUsage();
it++;
}
return total;
}
| mit |
CaptainPenguins/slimdx | source/math/Ray.cpp | 27 | 6806 | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <d3dx9.h>
#include "BoundingBox.h"
#include "BoundingSphere.h"
#include "Plane.h"
#include "Ray.h"
using namespace System;
using namespace System::Globalization;
namespace SlimDX
{
Ray::Ray( Vector3 position, Vector3 direction )
{
Position = position;
Direction = direction;
}
bool Ray::Intersects( Ray ray, Plane plane, [Out] float% distance )
{
ray.Direction.Normalize();
float dotDirection = (plane.Normal.X * ray.Direction.X) + (plane.Normal.Y * ray.Direction.Y) + (plane.Normal.Z * ray.Direction.Z);
if( Math::Abs( dotDirection ) < 0.000001f )
{
distance = 0;
return false;
}
float dotPosition = (plane.Normal.X * ray.Position.X) + (plane.Normal.Y * ray.Position.Y) + (plane.Normal.Z * ray.Position.Z);
float num = ( -plane.D - dotPosition ) / dotDirection;
if( num < 0.0f )
{
if( num < -0.000001f )
{
distance = 0;
return false;
}
num = 0.0f;
}
distance = num;
return true;
}
bool Ray::Intersects( Ray ray, Vector3 vertex1, Vector3 vertex2, Vector3 vertex3, [Out] float% distance )
{
float u, v;
return Intersects( ray, vertex1, vertex2, vertex3, distance, u, v );
}
bool Ray::Intersects( Ray ray, Vector3 vertex1, Vector3 vertex2, Vector3 vertex3, [Out] float% distance, [Out] float% barycentricU, [Out] float% barycentricV )
{
pin_ptr<float> pinnedDist = &distance;
pin_ptr<float> pinnedU = &barycentricU;
pin_ptr<float> pinnedV = &barycentricV;
if( D3DXIntersectTri( reinterpret_cast<D3DXVECTOR3*>( &vertex1 ),
reinterpret_cast<D3DXVECTOR3*>( &vertex2 ), reinterpret_cast<D3DXVECTOR3*>( &vertex3 ),
reinterpret_cast<D3DXVECTOR3*>( &ray.Position ), reinterpret_cast<D3DXVECTOR3*>( &ray.Direction ),
reinterpret_cast<FLOAT*>( pinnedU ), reinterpret_cast<FLOAT*>( pinnedV ), reinterpret_cast<FLOAT*>( pinnedDist ) ) )
return true;
else
return false;
}
bool Ray::Intersects( Ray ray, BoundingBox box, [Out] float% distance )
{
float d = 0.0f;
float maxValue = float::MaxValue;
ray.Direction.Normalize();
if( Math::Abs( ray.Direction.X ) < 0.0000001 )
{
if( ray.Position.X < box.Minimum.X || ray.Position.X > box.Maximum.X )
{
distance = 0.0f;
return false;
}
}
else
{
float inv = 1.0f / ray.Direction.X;
float min = (box.Minimum.X - ray.Position.X) * inv;
float max = (box.Maximum.X - ray.Position.X) * inv;
if( min > max )
{
float temp = min;
min = max;
max = temp;
}
d = Math::Max( min, d );
maxValue = Math::Min( max, maxValue );
if( d > maxValue )
{
distance = 0.0f;
return false;
}
}
if( Math::Abs( ray.Direction.Y ) < 0.0000001 )
{
if( ray.Position.Y < box.Minimum.Y || ray.Position.Y > box.Maximum.Y )
{
distance = 0.0f;
return false;
}
}
else
{
float inv = 1.0f / ray.Direction.Y;
float min = (box.Minimum.Y - ray.Position.Y) * inv;
float max = (box.Maximum.Y - ray.Position.Y) * inv;
if( min > max )
{
float temp = min;
min = max;
max = temp;
}
d = Math::Max( min, d );
maxValue = Math::Min( max, maxValue );
if( d > maxValue )
{
distance = 0.0f;
return false;
}
}
if( Math::Abs( ray.Direction.Z ) < 0.0000001 )
{
if( ray.Position.Z < box.Minimum.Z || ray.Position.Z > box.Maximum.Z )
{
distance = 0.0f;
return false;
}
}
else
{
float inv = 1.0f / ray.Direction.Z;
float min = (box.Minimum.Z - ray.Position.Z) * inv;
float max = (box.Maximum.Z - ray.Position.Z) * inv;
if( min > max )
{
float temp = min;
min = max;
max = temp;
}
d = Math::Max( min, d );
maxValue = Math::Min( max, maxValue );
if( d > maxValue )
{
distance = 0.0f;
return false;
}
}
distance = d;
return true;
}
bool Ray::Intersects( Ray ray, BoundingSphere sphere, [Out] float% distance )
{
float x = sphere.Center.X - ray.Position.X;
float y = sphere.Center.Y - ray.Position.Y;
float z = sphere.Center.Z - ray.Position.Z;
float pyth = (x * x) + (y * y) + (z * z);
float rr = sphere.Radius * sphere.Radius;
if( pyth <= rr )
{
distance = 0.0f;
return true;
}
ray.Direction.Normalize();
float dot = (x * ray.Direction.X) + (y * ray.Direction.Y) + (z * ray.Direction.Z);
if( dot < 0.0f )
{
distance = 0.0f;
return false;
}
float temp = pyth - (dot * dot);
if( temp > rr )
{
distance = 0.0f;
return false;
}
distance = dot - static_cast<float>( Math::Sqrt( static_cast<double>( rr - temp ) ) );
return true;
}
bool Ray::operator == ( Ray left, Ray right )
{
return Ray::Equals( left, right );
}
bool Ray::operator != ( Ray left, Ray right )
{
return !Ray::Equals( left, right );
}
String^ Ray::ToString()
{
return String::Format( CultureInfo::CurrentCulture, "Position:{0} Direction:{1}", Position.ToString(), Direction.ToString() );
}
int Ray::GetHashCode()
{
return Position.GetHashCode() + Direction.GetHashCode();
}
bool Ray::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<Ray>( value ) );
}
bool Ray::Equals( Ray value )
{
return ( Position == value.Position && Direction == value.Direction );
}
bool Ray::Equals( Ray% value1, Ray% value2 )
{
return ( value1.Position == value2.Position && value1.Direction == value2.Direction );
}
} | mit |
sperling/coreclr | src/vm/eepolicy.cpp | 28 | 55694 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
// ---------------------------------------------------------------------------
// EEPolicy.cpp
// ---------------------------------------------------------------------------
#include "common.h"
#include "eepolicy.h"
#include "corhost.h"
#include "dbginterface.h"
#include "eemessagebox.h"
#include "eventreporter.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#ifndef FEATURE_PAL
#include "dwreport.h"
#endif // !FEATURE_PAL
#include "eventtrace.h"
#undef ExitProcess
BYTE g_EEPolicyInstance[sizeof(EEPolicy)];
void InitEEPolicy()
{
WRAPPER_NO_CONTRACT;
new (g_EEPolicyInstance) EEPolicy();
}
EEPolicy::EEPolicy ()
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
int n;
for (n = 0; n < MaxClrOperation; n++) {
m_Timeout[n] = INFINITE;
m_ActionOnTimeout[n] = eNoAction;
m_DefaultAction[n] = eNoAction;
}
m_Timeout[OPR_ProcessExit] = 40000;
m_ActionOnTimeout[OPR_ProcessExit] = eRudeExitProcess;
m_ActionOnTimeout[OPR_ThreadAbort] = eAbortThread;
m_ActionOnTimeout[OPR_ThreadRudeAbortInNonCriticalRegion] = eRudeAbortThread;
m_ActionOnTimeout[OPR_ThreadRudeAbortInCriticalRegion] = eRudeAbortThread;
m_DefaultAction[OPR_ThreadAbort] = eAbortThread;
m_DefaultAction[OPR_ThreadRudeAbortInNonCriticalRegion] = eRudeAbortThread;
m_DefaultAction[OPR_ThreadRudeAbortInCriticalRegion] = eRudeAbortThread;
m_DefaultAction[OPR_AppDomainUnload] = eUnloadAppDomain;
m_DefaultAction[OPR_AppDomainRudeUnload] = eRudeUnloadAppDomain;
m_DefaultAction[OPR_ProcessExit] = eExitProcess;
m_DefaultAction[OPR_FinalizerRun] = eNoAction;
for (n = 0; n < MaxClrFailure; n++) {
m_ActionOnFailure[n] = eNoAction;
}
m_ActionOnFailure[FAIL_CriticalResource] = eThrowException;
m_ActionOnFailure[FAIL_NonCriticalResource] = eThrowException;
m_ActionOnFailure[FAIL_OrphanedLock] = eNoAction;
m_ActionOnFailure[FAIL_FatalRuntime] = eRudeExitProcess;
#ifdef FEATURE_CORECLR
// For CoreCLR, initialize the default action for AV processing to all
// all kind of code to catch AV exception. If the host wants, they can
// specify a different action for this.
m_ActionOnFailure[FAIL_AccessViolation] = eNoAction;
#endif // FEATURE_CORECLR
m_ActionOnFailure[FAIL_StackOverflow] = eRudeExitProcess;
m_ActionOnFailure[FAIL_CodeContract] = eThrowException;
m_unhandledExceptionPolicy = eRuntimeDeterminedPolicy;
}
BOOL EEPolicy::IsValidActionForOperation(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
switch (operation) {
case OPR_ThreadAbort:
return action >= eAbortThread &&
action < MaxPolicyAction;
case OPR_ThreadRudeAbortInNonCriticalRegion:
case OPR_ThreadRudeAbortInCriticalRegion:
return action >= eRudeAbortThread && action != eUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainUnload:
return action >= eUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainRudeUnload:
return action >= eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_ProcessExit:
return action >= eExitProcess &&
action < MaxPolicyAction;
case OPR_FinalizerRun:
return action == eNoAction ||
(action >= eAbortThread &&
action < MaxPolicyAction);
default:
_ASSERT (!"Do not know valid action for this operation");
break;
}
return FALSE;
}
BOOL EEPolicy::IsValidActionForTimeout(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
switch (operation) {
case OPR_ThreadAbort:
return action > eAbortThread &&
action < MaxPolicyAction;
case OPR_ThreadRudeAbortInNonCriticalRegion:
case OPR_ThreadRudeAbortInCriticalRegion:
return action > eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainUnload:
return action > eUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainRudeUnload:
return action > eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_ProcessExit:
return action > eExitProcess &&
action < MaxPolicyAction;
case OPR_FinalizerRun:
return action == eNoAction ||
(action >= eAbortThread &&
action < MaxPolicyAction);
default:
_ASSERT (!"Do not know valid action for this operation");
break;
}
return FALSE;
}
BOOL EEPolicy::IsValidActionForFailure(EClrFailure failure, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
switch (failure) {
case FAIL_NonCriticalResource:
return action >= eThrowException &&
action < MaxPolicyAction;
case FAIL_CriticalResource:
return action >= eThrowException &&
action < MaxPolicyAction;
case FAIL_FatalRuntime:
return action >= eRudeExitProcess &&
action < MaxPolicyAction;
case FAIL_OrphanedLock:
return action >= eUnloadAppDomain &&
action < MaxPolicyAction;
case FAIL_AccessViolation:
#ifdef FEATURE_CORECLR
// Allowed actions on failure are:
//
// eNoAction or eRudeExitProcess.
return ((action == eNoAction) || (action == eRudeExitProcess));
#else // !FEATURE_CORECLR
// FAIL_AccessViolation is defined for the desktop so that
// if any more definitions are added after it, their value
// should remain constant irrespective of whether its the
// desktop CLR or CoreCLR.
//
// That said, currently, Desktop CLR does not support
// FAIL_AccessViolation. Thus, any calls which use
// this failure are not allowed.
return FALSE;
#endif // FEATURE_CORECLR
case FAIL_StackOverflow:
return action >= eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case FAIL_CodeContract:
return action >= eThrowException &&
action <= eExitProcess;
default:
_ASSERTE (!"Do not know valid action for this failure");
break;
}
return FALSE;
}
HRESULT EEPolicy::SetTimeout(EClrOperation operation, DWORD timeout)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation)
{
m_Timeout[operation] = timeout;
if (operation == OPR_FinalizerRun &&
g_fEEStarted)
{
FastInterlockOr((DWORD*)&g_FinalizerWaiterStatus, FWS_WaitInterrupt);
FinalizerThread::SignalFinalizationDone(FALSE);
}
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
HRESULT EEPolicy::SetActionOnTimeout(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation &&
IsValidActionForTimeout(operation, action))
{
m_ActionOnTimeout[operation] = action;
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
EPolicyAction EEPolicy::GetFinalAction(EPolicyAction action, Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(static_cast<UINT>(action) < MaxPolicyAction);
if (action < eAbortThread || action > eFastExitProcess)
{
return action;
}
while(TRUE)
{
// Look at default action. If the default action is more severe,
// use the default action instead.
EPolicyAction defaultAction = action;
switch (action)
{
case eAbortThread:
defaultAction = m_DefaultAction[OPR_ThreadAbort];
break;
case eRudeAbortThread:
if (pThread && !pThread->HasLockInCurrentDomain())
{
defaultAction = m_DefaultAction[OPR_ThreadRudeAbortInNonCriticalRegion];
}
else
{
defaultAction = m_DefaultAction[OPR_ThreadRudeAbortInCriticalRegion];
}
break;
case eUnloadAppDomain:
defaultAction = m_DefaultAction[OPR_AppDomainUnload];
break;
case eRudeUnloadAppDomain:
defaultAction = m_DefaultAction[OPR_AppDomainRudeUnload];
break;
case eExitProcess:
case eFastExitProcess:
defaultAction = m_DefaultAction[OPR_ProcessExit];
if (defaultAction < action)
{
defaultAction = action;
}
break;
default:
break;
}
_ASSERTE(static_cast<UINT>(defaultAction) < MaxPolicyAction);
if (defaultAction == action)
{
return action;
}
_ASSERTE(defaultAction > action);
action = defaultAction;
}
}
// Allow setting timeout and action in one call.
// If we decide to have atomical operation on Policy, we can use lock here
// while SetTimeout and SetActionOnTimeout can not.
HRESULT EEPolicy::SetTimeoutAndAction(EClrOperation operation, DWORD timeout, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation &&
IsValidActionForTimeout(operation, action))
{
m_ActionOnTimeout[operation] = action;
m_Timeout[operation] = timeout;
if (operation == OPR_FinalizerRun &&
g_fEEStarted)
{
FastInterlockOr((DWORD*)&g_FinalizerWaiterStatus, FWS_WaitInterrupt);
FinalizerThread::SignalFinalizationDone(FALSE);
}
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
HRESULT EEPolicy::SetDefaultAction(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation &&
IsValidActionForOperation(operation, action))
{
m_DefaultAction[operation] = action;
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
HRESULT EEPolicy::SetActionOnFailure(EClrFailure failure, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(failure) < MaxClrFailure &&
IsValidActionForFailure(failure, action))
{
m_ActionOnFailure[failure] = action;
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
EPolicyAction EEPolicy::GetActionOnFailureNoHostNotification(EClrFailure failure)
{
CONTRACTL
{
SO_TOLERANT;
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}CONTRACTL_END;
_ASSERTE (failure < MaxClrFailure);
if (failure == FAIL_StackOverflow)
{
return m_ActionOnFailure[failure];
}
return GetFinalAction(m_ActionOnFailure[failure], GetThread());
}
EPolicyAction EEPolicy::GetActionOnFailure(EClrFailure failure)
{
CONTRACTL
{
SO_TOLERANT;
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}CONTRACTL_END;
_ASSERTE(static_cast<UINT>(failure) < MaxClrFailure);
if (failure == FAIL_StackOverflow)
{
return m_ActionOnFailure[failure];
}
EPolicyAction finalAction = GetActionOnFailureNoHostNotification(failure);
#ifdef FEATURE_INCLUDE_ALL_INTERFACES
IHostPolicyManager *pHostPolicyManager = CorHost2::GetHostPolicyManager();
if (pHostPolicyManager)
{
#ifdef _DEBUG
Thread* pThread = GetThread();
if (pThread)
{
pThread->AddFiberInfo(Thread::ThreadTrackInfo_Escalation);
}
#endif
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
pHostPolicyManager->OnFailure(failure, finalAction);
END_SO_TOLERANT_CODE_CALLING_HOST;
}
#endif // FEATURE_INCLUDE_ALL_INTERFACES
return finalAction;
}
void EEPolicy::NotifyHostOnTimeout(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
#ifdef FEATURE_INCLUDE_ALL_INTERFACES
IHostPolicyManager *pHostPolicyManager = CorHost2::GetHostPolicyManager();
if (pHostPolicyManager)
{
#ifdef _DEBUG
Thread* pThread = GetThread();
if (pThread)
{
pThread->AddFiberInfo(Thread::ThreadTrackInfo_Escalation);
}
#endif
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
pHostPolicyManager->OnTimeout(operation, action);
END_SO_TOLERANT_CODE_CALLING_HOST;
}
#endif // FEATURE_INCLUDE_ALL_INTERFACES
}
void EEPolicy::NotifyHostOnDefaultAction(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
#ifdef FEATURE_INCLUDE_ALL_INTERFACES
IHostPolicyManager *pHostPolicyManager = CorHost2::GetHostPolicyManager();
if (pHostPolicyManager)
{
#ifdef _DEBUG
Thread* pThread = GetThread();
if (pThread)
{
pThread->AddFiberInfo(Thread::ThreadTrackInfo_Escalation);
}
#endif
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
pHostPolicyManager->OnDefaultAction(operation, action);
END_SO_TOLERANT_CODE_CALLING_HOST;
}
#endif // FEATURE_INCLUDE_ALL_INTERFACES
}
void SafeExitProcess(UINT exitCode, BOOL fAbort = FALSE, ShutdownCompleteAction sca = SCA_ExitProcessWhenShutdownComplete)
{
// The process is shutting down. No need to check SO contract.
SO_NOT_MAINLINE_FUNCTION;
STRESS_LOG2(LF_SYNC, LL_INFO10, "SafeExitProcess: exitCode = %d, fAbort = %d\n", exitCode, fAbort);
CONTRACTL
{
DISABLED(GC_TRIGGERS);
NOTHROW;
}
CONTRACTL_END;
// The runtime must be in the appropriate thread mode when we exit, so that we
// aren't surprised by the thread mode when our DLL_PROCESS_DETACH occurs, or when
// other DLLs call Release() on us in their detach [dangerous!], etc.
GCX_PREEMP_NO_DTOR();
FastInterlockExchange((LONG*)&g_fForbidEnterEE, TRUE);
ProcessEventForHost(Event_ClrDisabled, NULL);
// Note that for free and retail builds StressLog must also be enabled
if (g_pConfig && g_pConfig->StressLog())
{
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_BreakOnBadExit))
{
// Workaround for aspnet
PathString wszFilename;
bool bShouldAssert = true;
if (WszGetModuleFileName(NULL, wszFilename))
{
wszFilename.LowerCase();
if (wcsstr(wszFilename, W("aspnet_compiler")))
{
bShouldAssert = false;
}
}
unsigned goodExit = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_SuccessExit);
if (bShouldAssert && exitCode != goodExit)
{
_ASSERTE(!"Bad Exit value");
FAULT_NOT_FATAL(); // if we OOM we can simply give up
SetErrorMode(0); // Insure that we actually cause the messsage box to pop.
EEMessageBoxCatastrophic(IDS_EE_ERRORMESSAGETEMPLATE, IDS_EE_ERRORTITLE, exitCode, W("BreakOnBadExit: returning bad exit code"));
}
}
}
// If we call ExitProcess, other threads will be torn down
// so we don't get to debug their state. Stop this!
#ifdef _DEBUG
if (_DbgBreakCount)
_ASSERTE(!"In SafeExitProcess: An assert was hit on some other thread");
#endif
// Turn off exception processing, because if some other random DLL has a
// fault in DLL_PROCESS_DETACH, we could get called for exception handling.
// Since we've turned off part of the runtime, we can't, for instance,
// properly execute the GC that handling an exception might trigger.
g_fNoExceptions = true;
LOG((LF_EH, LL_INFO10, "SafeExitProcess: turning off exceptions\n"));
if (sca == SCA_ExitProcessWhenShutdownComplete)
{
// disabled because if we fault in this code path we will trigger our
// Watson code via EntryPointFilter which is THROWS (see Dev11 317016)
CONTRACT_VIOLATION(ThrowsViolation);
#ifdef FEATURE_PAL
if (fAbort)
{
TerminateProcess(GetCurrentProcess(), exitCode);
}
#endif
EEPolicy::ExitProcessViaShim(exitCode);
}
}
// This is a helper to exit the process after coordinating with the shim. It is used by
// SafeExitProcess above, as well as from CorHost2::ExitProcess when we know that we must
// exit the process without doing further work to shutdown this runtime. This first attempts
// to call back to the Shim to shutdown any other runtimes within the process.
//
// IMPORTANT NOTE: exercise extreme caution when adding new calls to this method. It is highly
// likely that you want to call SafeExitProcess, or EEPolicy::HandleExitProcess instead of this.
// This function only exists to factor some common code out of the methods mentioned above.
//static
void EEPolicy::ExitProcessViaShim(UINT exitCode)
{
LIMITED_METHOD_CONTRACT;
// We must call back to the Shim in order to exit the process, as this may be just one
// runtime in a process with many. We need to give the other runtimes a chance to exit
// cleanly. If we can't make the call, or if the call fails for some reason, then we
// simply exit the process here, which is rude to the others, but the best we can do.
#if !defined(FEATURE_CORECLR)
{
ReleaseHolder<ICLRRuntimeHostInternal> pRuntimeHostInternal;
HRESULT hr = g_pCLRRuntime->GetInterface(CLSID_CLRRuntimeHostInternal,
IID_ICLRRuntimeHostInternal,
&pRuntimeHostInternal);
if (SUCCEEDED(hr))
{
pRuntimeHostInternal->ShutdownAllRuntimesThenExit(exitCode);
LOG((LF_EH, LL_INFO10, "ExitProcessViaShim: shim returned... exiting now.\n"));
}
}
#endif // !FEATURE_CORECLR
ExitProcess(exitCode);
}
//---------------------------------------------------------------------------------------
// DisableRuntime disables this runtime, suspending all managed execution and preventing
// threads from entering the runtime. This will cause the caller to block forever as well
// unless sca is SCA_ReturnWhenShutdownComplete.
//---------------------------------------------------------------------------------------
void DisableRuntime(ShutdownCompleteAction sca)
{
CONTRACTL
{
DISABLED(GC_TRIGGERS);
NOTHROW;
}
CONTRACTL_END;
FastInterlockExchange((LONG*)&g_fForbidEnterEE, TRUE);
if (!g_fSuspendOnShutdown)
{
if (!IsGCThread())
{
if (ThreadStore::HoldingThreadStore(GetThread()))
{
ThreadSuspend::UnlockThreadStore();
}
ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_SHUTDOWN);
}
if (!g_fSuspendOnShutdown)
{
ThreadStore::TrapReturningThreads(TRUE);
g_fSuspendOnShutdown = TRUE;
ClrFlsSetThreadType(ThreadType_Shutdown);
}
// Don't restart runtime. CLR is disabled.
}
GCX_PREEMP_NO_DTOR();
ProcessEventForHost(Event_ClrDisabled, NULL);
ClrFlsClearThreadType(ThreadType_Shutdown);
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->DisableDebugger();
}
if (sca == SCA_ExitProcessWhenShutdownComplete)
{
__SwitchToThread(INFINITE, CALLER_LIMITS_SPINNING);
_ASSERTE (!"Should not reach here");
SafeExitProcess(0);
}
}
//---------------------------------------------------------------------------------------
// HandleExitProcessHelper is used to shutdown the runtime as specified by the given
// action, then to exit the process. Note, however, that the process will not exit if
// sca is SCA_ReturnWhenShutdownComplete. In that case, this method will simply return after
// performing the shutdown actions.
//---------------------------------------------------------------------------------------
// If g_fFastExitProcess is 0, normal shutdown
// If g_fFastExitProcess is 1, fast shutdown. Only doing log.
// If g_fFastExitProcess is 2, do not run EEShutDown.
DWORD g_fFastExitProcess = 0;
extern void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading);
static void HandleExitProcessHelper(EPolicyAction action, UINT exitCode, ShutdownCompleteAction sca)
{
WRAPPER_NO_CONTRACT;
switch (action) {
case eFastExitProcess:
g_fFastExitProcess = 1;
case eExitProcess:
if (g_fEEStarted)
{
EEShutDown(FALSE);
}
if (exitCode == 0)
{
exitCode = GetLatchedExitCode();
}
SafeExitProcess(exitCode, FALSE, sca);
break;
case eRudeExitProcess:
g_fFastExitProcess = 2;
SafeExitProcess(exitCode, TRUE, sca);
break;
case eDisableRuntime:
DisableRuntime(sca);
break;
default:
_ASSERTE (!"Invalid policy");
break;
}
}
EPolicyAction EEPolicy::DetermineResourceConstraintAction(Thread *pThread)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
EPolicyAction action;
if (pThread->HasLockInCurrentDomain()) {
action = GetEEPolicy()->GetActionOnFailure(FAIL_CriticalResource);
}
else
action = GetEEPolicy()->GetActionOnFailure(FAIL_NonCriticalResource);
AppDomain *pDomain = GetAppDomain();
// If it is default domain, we can not unload the appdomain
if (pDomain == SystemDomain::System()->DefaultDomain() &&
(action == eUnloadAppDomain || action == eRudeUnloadAppDomain))
{
action = eThrowException;
}
// If the current thread is AD unload helper thread, it should not block itself.
else if (pThread->HasThreadStateNC(Thread::TSNC_ADUnloadHelper) &&
action < eExitProcess)
{
action = eThrowException;
}
return action;
}
void EEPolicy::PerformADUnloadAction(EPolicyAction action, BOOL haveStack, BOOL forStackOverflow)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::PerformADUnloadAction\n");
Thread *pThread = GetThread();
AppDomain *pDomain = GetAppDomain();
if (!IsFinalizerThread())
{
int count = 0;
Frame *pFrame = pThread->GetFirstTransitionInto(GetAppDomain(), &count);
{
pThread->SetUnloadBoundaryFrame(pFrame);
}
}
pDomain->EnableADUnloadWorker(action==eUnloadAppDomain? ADU_Safe : ADU_Rude);
// Can't perform a join when we are handling a true SO. We need to enable the unload woker but let the thread continue running
// through EH processing so that we can recover the stack and reset the guard page.
if (haveStack)
{
pThread->SetAbortRequest(action==eUnloadAppDomain? EEPolicy::TA_V1Compatible : EEPolicy::TA_Rude);
if (forStackOverflow)
{
OBJECTREF exceptObj = CLRException::GetPreallocatedRudeThreadAbortException();
pThread->SetAbortInitiated();
RaiseTheExceptionInternalOnly(exceptObj, FALSE, TRUE);
}
OBJECTREF exceptObj = CLRException::GetPreallocatedThreadAbortException();
pThread->SetAbortInitiated();
RaiseTheExceptionInternalOnly(exceptObj, FALSE, FALSE);
}
}
void EEPolicy::PerformResourceConstraintAction(Thread *pThread, EPolicyAction action, UINT exitCode, BOOL haveStack)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(GetAppDomain() != NULL);
switch (action) {
case eThrowException:
// Caller is going to rethrow.
return;
break;
case eAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Safe, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eRudeAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Rude, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eUnloadAppDomain:
case eRudeUnloadAppDomain:
{
GCX_ASSERT_COOP();
PerformADUnloadAction(action,haveStack);
}
break;
case eExitProcess:
case eFastExitProcess:
case eRudeExitProcess:
case eDisableRuntime:
HandleExitProcessFromEscalation(action, exitCode);
break;
default:
_ASSERTE (!"Invalid policy");
break;
}
}
void EEPolicy::HandleOutOfMemory()
{
WRAPPER_NO_CONTRACT;
_ASSERTE (g_pOutOfMemoryExceptionClass);
Thread *pThread = GetThread();
_ASSERTE (pThread);
EPolicyAction action = DetermineResourceConstraintAction(pThread);
// Check if we are executing in the context of a Constrained Execution Region.
if (action != eThrowException && Thread::IsExecutingWithinCer())
{
// Hitting OOM in a CER region should throw the OOM without regard to the escalation policy
// since the CER author has declared they are hardened against such failures. That's
// the whole point of CERs, to denote regions where code knows exactly how to deal with
// failures in an attempt to minimize the need for rollback or recycling.
return;
}
PerformResourceConstraintAction(pThread, action, HOST_E_EXITPROCESS_OUTOFMEMORY, TRUE);
}
#ifdef FEATURE_STACK_PROBE
//---------------------------------------------------------------------------------------
//
// IsSOTolerant - Is the current thread in SO Tolerant region?
//
// Arguments:
// pLimitFrame: the limit of search for frames
//
// Return Value:
// TRUE if in SO tolerant region.
// FALSE if in SO intolerant region.
//
// Note:
// We walk our frame chain to decide. If HelperMethodFrame is seen first, we are in tolerant
// region. If EnterSOIntolerantCodeFrame is seen first, we are in intolerant region.
//
BOOL Thread::IsSOTolerant(void * pLimitFrame)
{
LIMITED_METHOD_CONTRACT;
Frame *pFrame = GetFrame();
void* pSOIntolerantMarker = ClrFlsGetValue(TlsIdx_SOIntolerantTransitionHandler);
if (pSOIntolerantMarker == FRAME_TOP)
{
// We have not set a marker for intolerant transition yet.
return TRUE;
}
while (pFrame != FRAME_TOP && pFrame < pLimitFrame)
{
Frame::ETransitionType type = pFrame->GetTransitionType();
if (pFrame > pSOIntolerantMarker)
{
return FALSE;
}
else if (type == Frame::TT_M2U || type == Frame::TT_InternalCall ||
// We can not call HelperMethodFrame::GetFunction on SO since the call
// may need to call into host. This is why we check for TT_InternalCall first.
pFrame->GetFunction() != NULL)
{
return TRUE;
}
pFrame = pFrame->Next();
}
if (pFrame == FRAME_TOP)
// We walked to the end of chain, but the thread has one IntolerantMarker on stack decided from
// the check above while loop.
return FALSE;
else
return TRUE;
}
#endif
//---------------------------------------------------------------------------------------
//
// EEPolicy::HandleStackOverflow - Handle stack overflow according to policy
//
// Arguments:
// detector:
// pLimitFrame: the limit of search for frames in order to decide if in SO tolerant
//
// Return Value:
// None.
//
// How is stack overflow handled?
// If stack overflows in non-hosted case, we terminate the process.
// For hosted case with escalation policy
// 1. If stack overflows in managed code, or in VM before switching to SO intolerant region, and the GC mode is Cooperative
// the domain is rudely unloaded, or the process is terminated if the current domain is default domain.
// a. This action is done through BEGIN_SO_TOLERANT_CODE if there is one.
// b. If there is not this macro on the stack, we mark the domain being unload requested, and when the thread
// dies or is recycled, we finish the AD unload.
// 2. If stack overflows in SO tolerant region, but the GC mode is Preemptive, the process is killed in vector handler, or our
// managed exception handler (COMPlusFrameHandler or ProcessCLRException).
// 3. If stack overflows in SO intolerant region, the process is killed as soon as the exception is seen by our vector handler, or
// our managed exception handler.
//
// If SO Probing code is disabled (by FEATURE_STACK_PROBE not defined) then the process
// is terminated if there is StackOverflow as all clr code will be considered SO Intolerant.
void EEPolicy::HandleStackOverflow(StackOverflowDetector detector, void * pLimitFrame)
{
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleStackOverflow\n");
Thread *pThread = GetThread();
if (pThread == NULL)
{
//_ASSERTE (detector != SOD_ManagedFrameHandler);
// ProcessSOEventForHost(NULL, FALSE);
// For security reason, it is not safe to continue execution if stack overflow happens
// unless a host tells us to do something different.
// EEPolicy::HandleFatalStackOverflow(NULL);
return;
}
#ifdef FEATURE_STACK_PROBE
// We only process SO once at
// 1. VectoredExceptionHandler if SO in mscorwks
// 2. managed exception handler
// 3. SO_Tolerant transition handler
if (pThread->HasThreadStateNC(Thread::TSNC_SOWorkNeeded) &&
detector != SOD_UnmanagedFrameHandler)
{
return;
}
#endif
#ifdef FEATURE_STACK_PROBE
BOOL fInSoTolerant = pThread->IsSOTolerant(pLimitFrame);
#else
BOOL fInSoTolerant = false;
#endif
EXCEPTION_POINTERS exceptionInfo;
GetCurrentExceptionPointers(&exceptionInfo);
_ASSERTE(exceptionInfo.ExceptionRecord);
#ifdef FEATURE_STACK_PROBE
DWORD exceptionCode = exceptionInfo.ExceptionRecord->ExceptionCode;
AppDomain *pCurrentDomain = ::GetAppDomain();
BOOL fInDefaultDomain = (pCurrentDomain == SystemDomain::System()->DefaultDomain());
BOOL fInCLR = IsIPInModule(g_pMSCorEE, (PCODE)GetIP(exceptionInfo.ContextRecord));
if (exceptionCode == EXCEPTION_SOFTSO)
{
// Our probe detects a thread does not have enough stack. But we have not trashed the process
// state yet.
fInSoTolerant = TRUE;
}
else
{
_ASSERTE (exceptionCode == STATUS_STACK_OVERFLOW);
switch (detector)
{
case SOD_ManagedFrameHandler:
if (!pThread->PreemptiveGCDisabled() && !fInCLR && fInSoTolerant
&&
// Before we call managed code, we probe inside ReverseEnterRuntime for BACKOUT_CODE_STACK_LIMIT pages
// If we hit hard so here, we are still in our stub
(!CLRTaskHosted() || (UINT_PTR)pThread->m_pFrame - pThread->GetLastAllowableStackAddress() >=
ADJUST_PROBE(BACKOUT_CODE_STACK_LIMIT) * OS_PAGE_SIZE)
)
{
// Managed exception handler detects SO, but the thread is in preemptive GC mode,
// and the IP is outside CLR. This means we are inside a PINVOKE call.
fInSoTolerant = FALSE;
}
break;
case SOD_UnmanagedFrameHandler:
break;
case SOD_SOIntolerantTransitor:
fInSoTolerant = FALSE;
break;
case SOD_SOTolerantTransitor:
if (!fInCLR)
{
// If SO happens outside of CLR, and it is not detected by managed frame handler,
// it is fatal
fInSoTolerant = FALSE;
}
break;
default:
_ASSERTE(!"should not get here");
}
if (fInDefaultDomain)
{
// StackOverflow in default domain is fatal
fInSoTolerant = FALSE;
}
}
#endif // FEATURE_STACK_PROBE
ProcessSOEventForHost(&exceptionInfo, fInSoTolerant);
#ifdef FEATURE_STACK_PROBE
if (!CLRHosted() || GetEEPolicy()->GetActionOnFailure(FAIL_StackOverflow) != eRudeUnloadAppDomain)
{
// For security reason, it is not safe to continue execution if stack overflow happens
// unless a host tells us to do something different.
EEPolicy::HandleFatalStackOverflow(&exceptionInfo);
}
#endif
if (!fInSoTolerant)
{
EEPolicy::HandleFatalStackOverflow(&exceptionInfo);
}
#ifdef FEATURE_STACK_PROBE
else
{
// EnableADUnloadWorker is SO_Intolerant.
// But here we know that if we have only one page, we will only update states of the Domain.
CONTRACT_VIOLATION(SOToleranceViolation);
// Mark the current domain requested for rude unload
if (!fInDefaultDomain)
{
pCurrentDomain->EnableADUnloadWorker(ADU_Rude, FALSE);
}
pThread->PrepareThreadForSOWork();
pThread->MarkThreadForAbort(
(Thread::ThreadAbortRequester)(Thread::TAR_Thread|Thread::TAR_StackOverflow),
EEPolicy::TA_Rude);
pThread->SetSOWorkNeeded();
}
#endif
}
// We provide WatsonLastChance with a SO exception record. The ExceptionAddress is set to 0
// here. This ExceptionPointers struct is handed off to the debugger as is. A copy of this struct
// is made before invoking Watson and the ExceptionAddress is set by inspecting the stack. Note
// that the ExceptionContext member is unused and so it's ok to set it to NULL.
static EXCEPTION_RECORD g_SOExceptionRecord = {
STATUS_STACK_OVERFLOW, // ExceptionCode
0, // ExceptionFlags
NULL, // ExceptionRecord
0, // ExceptionAddress
0, // NumberOfParameters
{} }; // ExceptionInformation
EXCEPTION_POINTERS g_SOExceptionPointers = {&g_SOExceptionRecord, NULL};
#ifdef FEATURE_STACK_PROBE
// This function may be called on a thread before debugger is notified of the thread, like in
// ManagedThreadBase_DispatchMiddle. Currently we can not notify managed debugger, because
// RS requires that notification is sent first.
void EEPolicy::HandleSoftStackOverflow(BOOL fSkipDebugger)
{
WRAPPER_NO_CONTRACT;
// If we trigger a SO while handling the soft stack overflow,
// we'll rip the process
BEGIN_SO_INTOLERANT_CODE_NOPROBE;
AppDomain *pCurrentDomain = ::GetAppDomain();
if (GetEEPolicy()->GetActionOnFailure(FAIL_StackOverflow) != eRudeUnloadAppDomain ||
pCurrentDomain == SystemDomain::System()->DefaultDomain())
{
// We may not be able to build a context on stack
ProcessSOEventForHost(NULL, FALSE);
EEPolicy::HandleFatalStackOverflow(&g_SOExceptionPointers, fSkipDebugger);
}
//else if (pCurrentDomain == SystemDomain::System()->DefaultDomain())
//{
// We hit soft SO in Default domain, but default domain can not be unloaded.
// Soft SO can happen in default domain, eg. GetResourceString, or EnsureGrantSetSerialized.
// So the caller is going to throw a managed exception.
// RaiseException(EXCEPTION_SOFTSO, 0, 0, NULL);
//}
else
{
Thread* pThread = GetThread();
if (pThread && pThread->PreemptiveGCDisabled())
{
// Mark the current domain requested for rude unload
GCX_ASSERT_COOP();
EEPolicy::PerformADUnloadAction(eRudeUnloadAppDomain, TRUE, TRUE);
}
// We are leaving VM boundary, either entering managed code, or entering
// non-VM unmanaged code.
// We should not throw internal C++ exception. Instead we throw an exception
// with EXCEPTION_SOFTSO code.
RaiseException(EXCEPTION_SOFTSO, 0, 0, NULL);
}
END_SO_INTOLERANT_CODE_NOPROBE;
}
void EEPolicy::HandleStackOverflowAfterCatch()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
#ifdef STACK_GUARDS_DEBUG
BaseStackGuard::RestoreCurrentGuard(FALSE);
#endif
Thread *pThread = GetThread();
pThread->RestoreGuardPage();
pThread->FinishSOWork();
}
#endif
//---------------------------------------------------------------------------------------
// HandleExitProcess is used to shutdown the runtime, based on policy previously set,
// then to exit the process. Note, however, that the process will not exit if
// sca is SCA_ReturnWhenShutdownComplete. In that case, this method will simply return after
// performing the shutdown actions.
//---------------------------------------------------------------------------------------
void EEPolicy::HandleExitProcess(ShutdownCompleteAction sca)
{
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleExitProcess\n");
EPolicyAction action = GetEEPolicy()->GetDefaultAction(OPR_ProcessExit, NULL);
GetEEPolicy()->NotifyHostOnDefaultAction(OPR_ProcessExit,action);
HandleExitProcessHelper(action, 0, sca);
}
//
// Log an error to the event log if possible, then throw up a dialog box.
//
void EEPolicy::LogFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage, PEXCEPTION_POINTERS pExceptionInfo)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_ANY;
_ASSERTE(pExceptionInfo != NULL);
if(ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, FailFast))
{
// Fire an ETW FailFast event
FireEtwFailFast(pszMessage,
(const PVOID)address,
((pExceptionInfo && pExceptionInfo->ExceptionRecord) ? pExceptionInfo->ExceptionRecord->ExceptionCode : 0),
exitCode,
GetClrInstanceId());
}
#ifndef FEATURE_PAL
// Write an event log entry. We do allocate some resources here (spread between the stack and maybe the heap for longer
// messages), so it's possible for the event write to fail. If needs be we can use a more elaborate scheme here in the future
// (maybe trying multiple approaches and backing off on failure, falling back on a limited size static buffer as a last
// resort). In all likelihood the Win32 event reporting mechanism requires resources though, so it's not clear how much
// effort we should put into this without knowing the benefit we'd receive.
EX_TRY
{
if (ShouldLogInEventLog())
{
// If the exit code is COR_E_FAILFAST then the fatal error was raised by managed code and the address argument points to a
// unicode message buffer rather than a faulting EIP.
EventReporter::EventReporterType failureType = EventReporter::ERT_UnmanagedFailFast;
if (exitCode == (UINT)COR_E_FAILFAST)
failureType = EventReporter::ERT_ManagedFailFast;
else if (exitCode == (UINT)COR_E_CODECONTRACTFAILED)
failureType = EventReporter::ERT_CodeContractFailed;
EventReporter reporter(failureType);
if ((exitCode == (UINT)COR_E_FAILFAST) || (exitCode == (UINT)COR_E_CODECONTRACTFAILED) || (exitCode == (UINT)CLR_E_GC_OOM))
{
if (pszMessage)
{
reporter.AddDescription((WCHAR*)pszMessage);
}
if (exitCode != (UINT)CLR_E_GC_OOM)
LogCallstackForEventReporter(reporter);
}
else
{
// Fetch the localized Fatal Execution Engine Error text or fall back on a hardcoded variant if things get dire.
InlineSString<80> ssMessage;
InlineSString<80> ssErrorFormat;
if(!ssErrorFormat.LoadResource(CCompRC::Optional, IDS_ER_UNMANAGEDFAILFASTMSG ))
ssErrorFormat.Set(W("at IP %1 (%2) with exit code %3."));
SmallStackSString addressString;
addressString.Printf(W("%p"), pExceptionInfo? (UINT_PTR)pExceptionInfo->ExceptionRecord->ExceptionAddress : address);
// We should always have the reference to the runtime's instance
_ASSERTE(g_pMSCorEE != NULL);
// Setup the string to contain the runtime's base address. Thus, when customers report FEEE with just
// the event log entry containing this string, we can use the absolute and base addresses to determine
// where the fault happened inside the runtime.
SmallStackSString runtimeBaseAddressString;
runtimeBaseAddressString.Printf(W("%p"), g_pMSCorEE);
SmallStackSString exitCodeString;
exitCodeString.Printf(W("%x"), exitCode);
// Format the string
ssMessage.FormatMessage(FORMAT_MESSAGE_FROM_STRING, (LPCWSTR)ssErrorFormat, 0, 0, addressString, runtimeBaseAddressString,
exitCodeString);
reporter.AddDescription(ssMessage);
}
reporter.Report();
}
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions)
#endif // !FEATURE_PAL
#ifdef _DEBUG
// If we're native-only (Win32) debugging this process, we'd love to break now.
// However, we should not do this because a managed debugger attached to a
// SxS runtime also appears to be a native debugger. Unfortunately, the managed
// debugger won't handle any native event from another runtime, which means this
// breakpoint would go unhandled and terminate the process. Instead, we will let
// the process continue so at least the fatal error is logged rather than abrupt
// termination.
//
// This behavior can still be overridden if the right config value is set.
if (IsDebuggerPresent())
{
bool fBreak = (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgOOBinFEEE) != 0);
if (fBreak)
{
DebugBreak();
}
}
#endif // _DEBUG
// We're here logging a fatal error. If the policy is to then do anything other than
// disable the runtime (ie, if the policy is to terminate the runtime), we should give
// Watson an opportunity to capture an error report.
// Presumably, hosts that are sophisticated enough to disable the runtime are also cognizant
// of how they want to handle fatal errors in the runtime, including whether they want
// to capture Watson information (for which they are responsible).
if (GetEEPolicy()->GetActionOnFailureNoHostNotification(FAIL_FatalRuntime) != eDisableRuntime)
{
#ifdef DEBUGGING_SUPPORTED
//Give a managed debugger a chance if this fatal error is on a managed thread.
Thread *pThread = GetThread();
if (pThread)
{
GCX_COOP();
OBJECTHANDLE ohException = NULL;
if (exitCode == (UINT)COR_E_STACKOVERFLOW)
{
// If we're going down because of stack overflow, go ahead and use the preallocated SO exception.
ohException = CLRException::GetPreallocatedStackOverflowExceptionHandle();
}
else
{
// Though we would like to remove the usage of ExecutionEngineException in any manner,
// we cannot. Its okay to use it in the case below since the process is terminating
// and this will serve as an exception object for debugger.
ohException = CLRException::GetPreallocatedExecutionEngineExceptionHandle();
}
// Preallocated exception handles can be null if FailFast is invoked before LoadBaseSystemClasses
// (in SystemDomain::Init) finished. See Dev10 Bug 677432 for the detail.
if (ohException != NULL)
{
// for fail-fast, if there's a LTO available then use that as the inner exception object
// for the FEEE we'll be reporting. this can help the Watson back-end to generate better
// buckets for apps that call Environment.FailFast() and supply an exception object.
OBJECTREF lto = pThread->LastThrownObject();
if (exitCode == static_cast<UINT>(COR_E_FAILFAST) && lto != NULL)
{
EXCEPTIONREF curEx = (EXCEPTIONREF)ObjectFromHandle(ohException);
curEx->SetInnerException(lto);
}
pThread->SetLastThrownObject(ObjectFromHandle(ohException), TRUE);
}
// If a managed debugger is already attached, and if that debugger is thinking it might be inclined to
// try to intercept this excepiton, then tell it that's not possible.
if (pThread->IsExceptionInProgress())
{
pThread->GetExceptionState()->GetFlags()->SetDebuggerInterceptNotPossible();
}
}
if (EXCEPTION_CONTINUE_EXECUTION == WatsonLastChance(pThread, pExceptionInfo, TypeOfReportedError::FatalError))
{
LOG((LF_EH, LL_INFO100, "EEPolicy::LogFatalError: debugger ==> EXCEPTION_CONTINUE_EXECUTION\n"));
_ASSERTE(!"Debugger should not have returned ContinueExecution");
}
#endif // DEBUGGING_SUPPORTED
}
}
void DisplayStackOverflowException()
{
LIMITED_METHOD_CONTRACT;
PrintToStdErrA("\n");
PrintToStdErrA("Process is terminated due to StackOverflowException.\n");
}
void DECLSPEC_NORETURN EEPolicy::HandleFatalStackOverflow(EXCEPTION_POINTERS *pExceptionInfo, BOOL fSkipDebugger)
{
// This is fatal error. We do not care about SO mode any more.
// All of the code from here on out is robust to any failures in any API's that are called.
CONTRACT_VIOLATION(GCViolation | ModeViolation | SOToleranceViolation | FaultNotFatal | TakesLockViolation);
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleFatalStackOverflow\n");
DisplayStackOverflowException();
if(ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, FailFast))
{
// Fire an ETW FailFast event
FireEtwFailFast(W("StackOverflowException"),
(const PVOID)((pExceptionInfo && pExceptionInfo->ContextRecord) ? GetIP(pExceptionInfo->ContextRecord) : 0),
((pExceptionInfo && pExceptionInfo->ExceptionRecord) ? pExceptionInfo->ExceptionRecord->ExceptionCode : 0),
COR_E_STACKOVERFLOW,
GetClrInstanceId());
}
if (!fSkipDebugger)
{
Thread *pThread = GetThread();
BOOL fTreatAsNativeUnhandledException = FALSE;
if (pThread)
{
GCX_COOP();
// If we had a SO before preallocated exception objects are initialized, we will AV here. This can happen
// during the initialization of SystemDomain during EEStartup. Thus, setup the SO throwable only if its not
// NULL.
//
// When WatsonLastChance (WLC) is invoked below, it treats this case as UnhandledException. If there is no
// managed exception object available, we should treat this case as NativeUnhandledException. This aligns
// well with the fact that there cannot be a managed debugger attached at this point that will require
// LastChanceManagedException notification to be delivered. Also, this is the same as how
// we treat an unhandled exception as NativeUnhandled when throwable is not available.
OBJECTHANDLE ohSO = CLRException::GetPreallocatedStackOverflowExceptionHandle();
if (ohSO != NULL)
{
pThread->SafeSetThrowables(ObjectFromHandle(ohSO)
DEBUG_ARG(ThreadExceptionState::STEC_CurrentTrackerEqualNullOkHackForFatalStackOverflow),
TRUE);
}
else
{
// We dont have a throwable - treat this as native unhandled exception
fTreatAsNativeUnhandledException = TRUE;
}
}
FrameWithCookie<FaultingExceptionFrame> fef;
#if defined(WIN64EXCEPTIONS)
*((&fef)->GetGSCookiePtr()) = GetProcessGSCookie();
#endif // WIN64EXCEPTIONS
if (pExceptionInfo && pExceptionInfo->ContextRecord)
{
GCX_COOP();
fef.InitAndLink(pExceptionInfo->ContextRecord);
}
#ifndef FEATURE_PAL
if (RunningOnWin7() && IsWatsonEnabled() && (g_pDebugInterface != NULL))
{
_ASSERTE(pExceptionInfo != NULL);
ResetWatsonBucketsParams param;
param.m_pThread = pThread;
param.pExceptionRecord = pExceptionInfo->ExceptionRecord;
g_pDebugInterface->RequestFavor(ResetWatsonBucketsFavorWorker, reinterpret_cast<void *>(¶m));
}
#endif // !FEATURE_PAL
WatsonLastChance(pThread, pExceptionInfo,
(fTreatAsNativeUnhandledException == FALSE)? TypeOfReportedError::UnhandledException: TypeOfReportedError::NativeThreadUnhandledException);
}
TerminateProcess(GetCurrentProcess(), COR_E_STACKOVERFLOW);
UNREACHABLE();
}
void DECLSPEC_NORETURN EEPolicy::HandleFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage /* = NULL */, PEXCEPTION_POINTERS pExceptionInfo /* = NULL */)
{
WRAPPER_NO_CONTRACT;
// All of the code from here on out is robust to any failures in any API's that are called.
FAULT_NOT_FATAL();
EXCEPTION_RECORD exceptionRecord;
EXCEPTION_POINTERS exceptionPointers;
CONTEXT context;
if (pExceptionInfo == NULL)
{
ZeroMemory(&exceptionPointers, sizeof(exceptionPointers));
ZeroMemory(&exceptionRecord, sizeof(exceptionRecord));
ZeroMemory(&context, sizeof(context));
context.ContextFlags = CONTEXT_CONTROL;
ClrCaptureContext(&context);
exceptionRecord.ExceptionCode = exitCode;
exceptionRecord.ExceptionAddress = reinterpret_cast< PVOID >(address);
exceptionPointers.ExceptionRecord = &exceptionRecord;
exceptionPointers.ContextRecord = &context;
pExceptionInfo = &exceptionPointers;
}
// All of the code from here on out is allowed to trigger a GC, even if we're in a no-trigger region. We're
// ripping the process down due to a fatal error... our invariants are already gone.
{
// This is fatal error. We do not care about SO mode any more.
// All of the code from here on out is robust to any failures in any API's that are called.
CONTRACT_VIOLATION(GCViolation | ModeViolation | SOToleranceViolation | FaultNotFatal | TakesLockViolation);
// ThreadStore lock needs to be released before continuing with the FatalError handling should
// because debugger is going to take CrstDebuggerMutex, whose lock level is higher than that of
// CrstThreadStore. It should be safe to release the lock since execution will not be resumed
// after fatal errors.
if (ThreadStore::HoldingThreadStore(GetThread()))
{
ThreadSuspend::UnlockThreadStore();
}
g_fFastExitProcess = 2;
STRESS_LOG0(LF_CORDB,LL_INFO100, "D::HFE: About to call LogFatalError\n");
switch (GetEEPolicy()->GetActionOnFailure(FAIL_FatalRuntime))
{
case eRudeExitProcess:
LogFatalError(exitCode, address, pszMessage, pExceptionInfo);
SafeExitProcess(exitCode, TRUE);
break;
case eDisableRuntime:
LogFatalError(exitCode, address, pszMessage, pExceptionInfo);
DisableRuntime(SCA_ExitProcessWhenShutdownComplete);
break;
default:
_ASSERTE(!"Invalid action for FAIL_FatalRuntime");
break;
}
}
UNREACHABLE();
}
void EEPolicy::HandleExitProcessFromEscalation(EPolicyAction action, UINT exitCode)
{
WRAPPER_NO_CONTRACT;
CONTRACT_VIOLATION(GCViolation);
_ASSERTE (action >= eExitProcess);
// If policy for ExitProcess is not default action, i.e. ExitProcess, we will use it.
// Otherwise overwrite it with passing arg action;
EPolicyAction todo = GetEEPolicy()->GetDefaultAction(OPR_ProcessExit, NULL);
if (todo == eExitProcess)
{
todo = action;
}
GetEEPolicy()->NotifyHostOnDefaultAction(OPR_ProcessExit,todo);
HandleExitProcessHelper(todo, exitCode, SCA_ExitProcessWhenShutdownComplete);
}
void EEPolicy::HandleCodeContractFailure(LPCWSTR pMessage, LPCWSTR pCondition, LPCWSTR pInnerExceptionAsString)
{
WRAPPER_NO_CONTRACT;
EEPolicy* pPolicy = GetEEPolicy();
// GetActionOnFailure will notify the host for us.
EPolicyAction action = pPolicy->GetActionOnFailure(FAIL_CodeContract);
Thread* pThread = GetThread();
AppDomain* pCurrentDomain = ::GetAppDomain();
switch(action) {
case eThrowException:
// Let managed code throw a ContractException (it's easier to pass the right parameters to the constructor).
break;
case eAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Safe, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eRudeAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Rude, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eUnloadAppDomain:
// Register an appdomain unload, which starts on a separate thread.
IfFailThrow(AppDomain::UnloadById(pCurrentDomain->GetId(), FALSE));
// Don't continue execution on this thread.
pThread->UserAbort(Thread::TAR_Thread, TA_Safe, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eRudeUnloadAppDomain:
pCurrentDomain->SetRudeUnload();
// Register an appdomain unload, which starts on a separate thread.
IfFailThrow(AppDomain::UnloadById(pCurrentDomain->GetId(), FALSE));
// Don't continue execution on this thread.
pThread->UserAbort(Thread::TAR_Thread, TA_Rude, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eExitProcess: // Merged w/ default case
default:
_ASSERTE(action == eExitProcess);
// Since we have no exception object, make sure
// UE tracker is clean so that RetrieveManagedBucketParameters
// does not take any bucket details.
#ifndef FEATURE_PAL
pThread->GetExceptionState()->GetUEWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // !FEATURE_PAL
pPolicy->HandleFatalError(COR_E_CODECONTRACTFAILED, NULL, pMessage);
break;
}
}
| mit |
NSWRyan/AR.Drone_2.0 | AR.Drone_2.0_Eclipse_Project/jni/ffmpeg-0.8/libavformat/gxf.c | 30 | 17408 | /*
* GXF demuxer.
* Copyright (c) 2006 Reimar Doeffinger
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/common.h"
#include "avformat.h"
#include "internal.h"
#include "gxf.h"
struct gxf_stream_info {
int64_t first_field;
int64_t last_field;
AVRational frames_per_second;
int32_t fields_per_frame;
};
/**
* \brief parses a packet header, extracting type and length
* \param pb AVIOContext to read header from
* \param type detected packet type is stored here
* \param length detected packet length, excluding header is stored here
* \return 0 if header not found or contains invalid data, 1 otherwise
*/
static int parse_packet_header(AVIOContext *pb, GXFPktType *type, int *length) {
if (avio_rb32(pb))
return 0;
if (avio_r8(pb) != 1)
return 0;
*type = avio_r8(pb);
*length = avio_rb32(pb);
if ((*length >> 24) || *length < 16)
return 0;
*length -= 16;
if (avio_rb32(pb))
return 0;
if (avio_r8(pb) != 0xe1)
return 0;
if (avio_r8(pb) != 0xe2)
return 0;
return 1;
}
/**
* \brief check if file starts with a PKT_MAP header
*/
static int gxf_probe(AVProbeData *p) {
static const uint8_t startcode[] = {0, 0, 0, 0, 1, 0xbc}; // start with map packet
static const uint8_t endcode[] = {0, 0, 0, 0, 0xe1, 0xe2};
if (!memcmp(p->buf, startcode, sizeof(startcode)) &&
!memcmp(&p->buf[16 - sizeof(endcode)], endcode, sizeof(endcode)))
return AVPROBE_SCORE_MAX;
return 0;
}
/**
* \brief gets the stream index for the track with the specified id, creates new
* stream if not found
* \param id id of stream to find / add
* \param format stream format identifier
*/
static int get_sindex(AVFormatContext *s, int id, int format) {
int i;
AVStream *st = NULL;
i = ff_find_stream_index(s, id);
if (i >= 0)
return i;
st = av_new_stream(s, id);
if (!st)
return AVERROR(ENOMEM);
switch (format) {
case 3:
case 4:
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = CODEC_ID_MJPEG;
break;
case 13:
case 15:
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = CODEC_ID_DVVIDEO;
break;
case 14:
case 16:
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = CODEC_ID_DVVIDEO;
break;
case 11:
case 12:
case 20:
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
st->need_parsing = AVSTREAM_PARSE_HEADERS; //get keyframe flag etc.
break;
case 22:
case 23:
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = CODEC_ID_MPEG1VIDEO;
st->need_parsing = AVSTREAM_PARSE_HEADERS; //get keyframe flag etc.
break;
case 9:
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = CODEC_ID_PCM_S24LE;
st->codec->channels = 1;
st->codec->sample_rate = 48000;
st->codec->bit_rate = 3 * 1 * 48000 * 8;
st->codec->block_align = 3 * 1;
st->codec->bits_per_coded_sample = 24;
break;
case 10:
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = CODEC_ID_PCM_S16LE;
st->codec->channels = 1;
st->codec->sample_rate = 48000;
st->codec->bit_rate = 2 * 1 * 48000 * 8;
st->codec->block_align = 2 * 1;
st->codec->bits_per_coded_sample = 16;
break;
case 17:
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = CODEC_ID_AC3;
st->codec->channels = 2;
st->codec->sample_rate = 48000;
break;
// timecode tracks:
case 7:
case 8:
case 24:
st->codec->codec_type = AVMEDIA_TYPE_DATA;
st->codec->codec_id = CODEC_ID_NONE;
break;
default:
st->codec->codec_type = AVMEDIA_TYPE_UNKNOWN;
st->codec->codec_id = CODEC_ID_NONE;
break;
}
return s->nb_streams - 1;
}
/**
* \brief filters out interesting tags from material information.
* \param len length of tag section, will be adjusted to contain remaining bytes
* \param si struct to store collected information into
*/
static void gxf_material_tags(AVIOContext *pb, int *len, struct gxf_stream_info *si) {
si->first_field = AV_NOPTS_VALUE;
si->last_field = AV_NOPTS_VALUE;
while (*len >= 2) {
GXFMatTag tag = avio_r8(pb);
int tlen = avio_r8(pb);
*len -= 2;
if (tlen > *len)
return;
*len -= tlen;
if (tlen == 4) {
uint32_t value = avio_rb32(pb);
if (tag == MAT_FIRST_FIELD)
si->first_field = value;
else if (tag == MAT_LAST_FIELD)
si->last_field = value;
} else
avio_skip(pb, tlen);
}
}
/**
* \brief convert fps tag value to AVRational fps
* \param fps fps value from tag
* \return fps as AVRational, or 0 / 0 if unknown
*/
static AVRational fps_tag2avr(int32_t fps) {
extern const AVRational ff_frame_rate_tab[];
if (fps < 1 || fps > 9) fps = 9;
return ff_frame_rate_tab[9 - fps]; // values have opposite order
}
/**
* \brief convert UMF attributes flags to AVRational fps
* \param flags UMF flags to convert
* \return fps as AVRational, or 0 / 0 if unknown
*/
static AVRational fps_umf2avr(uint32_t flags) {
static const AVRational map[] = {{50, 1}, {60000, 1001}, {24, 1},
{25, 1}, {30000, 1001}};
int idx = av_log2((flags & 0x7c0) >> 6);
return map[idx];
}
/**
* \brief filters out interesting tags from track information.
* \param len length of tag section, will be adjusted to contain remaining bytes
* \param si struct to store collected information into
*/
static void gxf_track_tags(AVIOContext *pb, int *len, struct gxf_stream_info *si) {
si->frames_per_second = (AVRational){0, 0};
si->fields_per_frame = 0;
while (*len >= 2) {
GXFTrackTag tag = avio_r8(pb);
int tlen = avio_r8(pb);
*len -= 2;
if (tlen > *len)
return;
*len -= tlen;
if (tlen == 4) {
uint32_t value = avio_rb32(pb);
if (tag == TRACK_FPS)
si->frames_per_second = fps_tag2avr(value);
else if (tag == TRACK_FPF && (value == 1 || value == 2))
si->fields_per_frame = value;
} else
avio_skip(pb, tlen);
}
}
/**
* \brief read index from FLT packet into stream 0 av_index
*/
static void gxf_read_index(AVFormatContext *s, int pkt_len) {
AVIOContext *pb = s->pb;
AVStream *st = s->streams[0];
uint32_t fields_per_map = avio_rl32(pb);
uint32_t map_cnt = avio_rl32(pb);
int i;
pkt_len -= 8;
if (s->flags & AVFMT_FLAG_IGNIDX) {
avio_skip(pb, pkt_len);
return;
}
if (map_cnt > 1000) {
av_log(s, AV_LOG_ERROR, "too many index entries %u (%x)\n", map_cnt, map_cnt);
map_cnt = 1000;
}
if (pkt_len < 4 * map_cnt) {
av_log(s, AV_LOG_ERROR, "invalid index length\n");
avio_skip(pb, pkt_len);
return;
}
pkt_len -= 4 * map_cnt;
av_add_index_entry(st, 0, 0, 0, 0, 0);
for (i = 0; i < map_cnt; i++)
av_add_index_entry(st, (uint64_t)avio_rl32(pb) * 1024,
i * (uint64_t)fields_per_map + 1, 0, 0, 0);
avio_skip(pb, pkt_len);
}
static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
AVIOContext *pb = s->pb;
GXFPktType pkt_type;
int map_len;
int len;
AVRational main_timebase = {0, 0};
struct gxf_stream_info si;
int i;
if (!parse_packet_header(pb, &pkt_type, &map_len) || pkt_type != PKT_MAP) {
av_log(s, AV_LOG_ERROR, "map packet not found\n");
return 0;
}
map_len -= 2;
if (avio_r8(pb) != 0x0e0 || avio_r8(pb) != 0xff) {
av_log(s, AV_LOG_ERROR, "unknown version or invalid map preamble\n");
return 0;
}
map_len -= 2;
len = avio_rb16(pb); // length of material data section
if (len > map_len) {
av_log(s, AV_LOG_ERROR, "material data longer than map data\n");
return 0;
}
map_len -= len;
gxf_material_tags(pb, &len, &si);
avio_skip(pb, len);
map_len -= 2;
len = avio_rb16(pb); // length of track description
if (len > map_len) {
av_log(s, AV_LOG_ERROR, "track description longer than map data\n");
return 0;
}
map_len -= len;
while (len > 0) {
int track_type, track_id, track_len;
AVStream *st;
int idx;
len -= 4;
track_type = avio_r8(pb);
track_id = avio_r8(pb);
track_len = avio_rb16(pb);
len -= track_len;
gxf_track_tags(pb, &track_len, &si);
avio_skip(pb, track_len);
if (!(track_type & 0x80)) {
av_log(s, AV_LOG_ERROR, "invalid track type %x\n", track_type);
continue;
}
track_type &= 0x7f;
if ((track_id & 0xc0) != 0xc0) {
av_log(s, AV_LOG_ERROR, "invalid track id %x\n", track_id);
continue;
}
track_id &= 0x3f;
idx = get_sindex(s, track_id, track_type);
if (idx < 0) continue;
st = s->streams[idx];
if (!main_timebase.num || !main_timebase.den) {
main_timebase.num = si.frames_per_second.den;
main_timebase.den = si.frames_per_second.num * 2;
}
st->start_time = si.first_field;
if (si.first_field != AV_NOPTS_VALUE && si.last_field != AV_NOPTS_VALUE)
st->duration = si.last_field - si.first_field;
}
if (len < 0)
av_log(s, AV_LOG_ERROR, "invalid track description length specified\n");
if (map_len)
avio_skip(pb, map_len);
if (!parse_packet_header(pb, &pkt_type, &len)) {
av_log(s, AV_LOG_ERROR, "sync lost in header\n");
return -1;
}
if (pkt_type == PKT_FLT) {
gxf_read_index(s, len);
if (!parse_packet_header(pb, &pkt_type, &len)) {
av_log(s, AV_LOG_ERROR, "sync lost in header\n");
return -1;
}
}
if (pkt_type == PKT_UMF) {
if (len >= 0x39) {
AVRational fps;
len -= 0x39;
avio_skip(pb, 5); // preamble
avio_skip(pb, 0x30); // payload description
fps = fps_umf2avr(avio_rl32(pb));
if (!main_timebase.num || !main_timebase.den) {
// this may not always be correct, but simply the best we can get
main_timebase.num = fps.den;
main_timebase.den = fps.num * 2;
}
} else
av_log(s, AV_LOG_INFO, "UMF packet too short\n");
} else
av_log(s, AV_LOG_INFO, "UMF packet missing\n");
avio_skip(pb, len);
// set a fallback value, 60000/1001 is specified for audio-only files
// so use that regardless of why we do not know the video frame rate.
if (!main_timebase.num || !main_timebase.den)
main_timebase = (AVRational){1001, 60000};
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
av_set_pts_info(st, 32, main_timebase.num, main_timebase.den);
}
return 0;
}
#define READ_ONE() \
{ \
if (!max_interval-- || url_feof(pb)) \
goto out; \
tmp = tmp << 8 | avio_r8(pb); \
}
/**
* \brief resync the stream on the next media packet with specified properties
* \param max_interval how many bytes to search for matching packet at most
* \param track track id the media packet must belong to, -1 for any
* \param timestamp minimum timestamp (== field number) the packet must have, -1 for any
* \return timestamp of packet found
*/
static int64_t gxf_resync_media(AVFormatContext *s, uint64_t max_interval, int track, int timestamp) {
uint32_t tmp;
uint64_t last_pos;
uint64_t last_found_pos = 0;
int cur_track;
int64_t cur_timestamp = AV_NOPTS_VALUE;
int len;
AVIOContext *pb = s->pb;
GXFPktType type;
tmp = avio_rb32(pb);
start:
while (tmp)
READ_ONE();
READ_ONE();
if (tmp != 1)
goto start;
last_pos = avio_tell(pb);
if (avio_seek(pb, -5, SEEK_CUR) < 0)
goto out;
if (!parse_packet_header(pb, &type, &len) || type != PKT_MEDIA) {
if (avio_seek(pb, last_pos, SEEK_SET) < 0)
goto out;
goto start;
}
avio_r8(pb);
cur_track = avio_r8(pb);
cur_timestamp = avio_rb32(pb);
last_found_pos = avio_tell(pb) - 16 - 6;
if ((track >= 0 && track != cur_track) || (timestamp >= 0 && timestamp > cur_timestamp)) {
if (avio_seek(pb, last_pos, SEEK_SET) >= 0)
goto start;
}
out:
if (last_found_pos)
avio_seek(pb, last_found_pos, SEEK_SET);
return cur_timestamp;
}
static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
AVIOContext *pb = s->pb;
GXFPktType pkt_type;
int pkt_len;
while (!url_feof(pb)) {
AVStream *st;
int track_type, track_id, ret;
int field_nr, field_info, skip = 0;
int stream_index;
if (!parse_packet_header(pb, &pkt_type, &pkt_len)) {
if (!url_feof(pb))
av_log(s, AV_LOG_ERROR, "sync lost\n");
return -1;
}
if (pkt_type == PKT_FLT) {
gxf_read_index(s, pkt_len);
continue;
}
if (pkt_type != PKT_MEDIA) {
avio_skip(pb, pkt_len);
continue;
}
if (pkt_len < 16) {
av_log(s, AV_LOG_ERROR, "invalid media packet length\n");
continue;
}
pkt_len -= 16;
track_type = avio_r8(pb);
track_id = avio_r8(pb);
stream_index = get_sindex(s, track_id, track_type);
if (stream_index < 0)
return stream_index;
st = s->streams[stream_index];
field_nr = avio_rb32(pb);
field_info = avio_rb32(pb);
avio_rb32(pb); // "timeline" field number
avio_r8(pb); // flags
avio_r8(pb); // reserved
if (st->codec->codec_id == CODEC_ID_PCM_S24LE ||
st->codec->codec_id == CODEC_ID_PCM_S16LE) {
int first = field_info >> 16;
int last = field_info & 0xffff; // last is exclusive
int bps = av_get_bits_per_sample(st->codec->codec_id)>>3;
if (first <= last && last*bps <= pkt_len) {
avio_skip(pb, first*bps);
skip = pkt_len - last*bps;
pkt_len = (last-first)*bps;
} else
av_log(s, AV_LOG_ERROR, "invalid first and last sample values\n");
}
ret = av_get_packet(pb, pkt, pkt_len);
if (skip)
avio_skip(pb, skip);
pkt->stream_index = stream_index;
pkt->dts = field_nr;
return ret;
}
return AVERROR(EIO);
}
static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
int res = 0;
uint64_t pos;
uint64_t maxlen = 100 * 1024 * 1024;
AVStream *st = s->streams[0];
int64_t start_time = s->streams[stream_index]->start_time;
int64_t found;
int idx;
if (timestamp < start_time) timestamp = start_time;
idx = av_index_search_timestamp(st, timestamp - start_time,
AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
if (idx < 0)
return -1;
pos = st->index_entries[idx].pos;
if (idx < st->nb_index_entries - 2)
maxlen = st->index_entries[idx + 2].pos - pos;
maxlen = FFMAX(maxlen, 200 * 1024);
res = avio_seek(s->pb, pos, SEEK_SET);
if (res < 0)
return res;
found = gxf_resync_media(s, maxlen, -1, timestamp);
if (FFABS(found - timestamp) > 4)
return -1;
return 0;
}
static int64_t gxf_read_timestamp(AVFormatContext *s, int stream_index,
int64_t *pos, int64_t pos_limit) {
AVIOContext *pb = s->pb;
int64_t res;
if (avio_seek(pb, *pos, SEEK_SET) < 0)
return AV_NOPTS_VALUE;
res = gxf_resync_media(s, pos_limit - *pos, -1, -1);
*pos = avio_tell(pb);
return res;
}
AVInputFormat ff_gxf_demuxer = {
"gxf",
NULL_IF_CONFIG_SMALL("GXF format"),
0,
gxf_probe,
gxf_header,
gxf_packet,
NULL,
gxf_seek,
gxf_read_timestamp,
};
| mit |
The-Cypherfunks/The-Cypherfunks | src/zmq/zmqnotificationinterface.cpp | 31 | 5547 | // Copyright (c) 2015-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zmqnotificationinterface.h"
#include "zmqpublishnotifier.h"
#include "version.h"
#include "validation.h"
#include "streams.h"
#include "util.h"
void zmqError(const char *str)
{
LogPrint(BCLog::ZMQ, "zmq: Error: %s, errno=%s\n", str, zmq_strerror(errno));
}
CZMQNotificationInterface::CZMQNotificationInterface() : pcontext(nullptr)
{
}
CZMQNotificationInterface::~CZMQNotificationInterface()
{
Shutdown();
for (std::list<CZMQAbstractNotifier*>::iterator i=notifiers.begin(); i!=notifiers.end(); ++i)
{
delete *i;
}
}
CZMQNotificationInterface* CZMQNotificationInterface::Create()
{
CZMQNotificationInterface* notificationInterface = nullptr;
std::map<std::string, CZMQNotifierFactory> factories;
std::list<CZMQAbstractNotifier*> notifiers;
factories["pubhashblock"] = CZMQAbstractNotifier::Create<CZMQPublishHashBlockNotifier>;
factories["pubhashtx"] = CZMQAbstractNotifier::Create<CZMQPublishHashTransactionNotifier>;
factories["pubrawblock"] = CZMQAbstractNotifier::Create<CZMQPublishRawBlockNotifier>;
factories["pubrawtx"] = CZMQAbstractNotifier::Create<CZMQPublishRawTransactionNotifier>;
for (std::map<std::string, CZMQNotifierFactory>::const_iterator i=factories.begin(); i!=factories.end(); ++i)
{
std::string arg("-zmq" + i->first);
if (gArgs.IsArgSet(arg))
{
CZMQNotifierFactory factory = i->second;
std::string address = gArgs.GetArg(arg, "");
CZMQAbstractNotifier *notifier = factory();
notifier->SetType(i->first);
notifier->SetAddress(address);
notifiers.push_back(notifier);
}
}
if (!notifiers.empty())
{
notificationInterface = new CZMQNotificationInterface();
notificationInterface->notifiers = notifiers;
if (!notificationInterface->Initialize())
{
delete notificationInterface;
notificationInterface = nullptr;
}
}
return notificationInterface;
}
// Called at startup to conditionally set up ZMQ socket(s)
bool CZMQNotificationInterface::Initialize()
{
LogPrint(BCLog::ZMQ, "zmq: Initialize notification interface\n");
assert(!pcontext);
pcontext = zmq_init(1);
if (!pcontext)
{
zmqError("Unable to initialize context");
return false;
}
std::list<CZMQAbstractNotifier*>::iterator i=notifiers.begin();
for (; i!=notifiers.end(); ++i)
{
CZMQAbstractNotifier *notifier = *i;
if (notifier->Initialize(pcontext))
{
LogPrint(BCLog::ZMQ, " Notifier %s ready (address = %s)\n", notifier->GetType(), notifier->GetAddress());
}
else
{
LogPrint(BCLog::ZMQ, " Notifier %s failed (address = %s)\n", notifier->GetType(), notifier->GetAddress());
break;
}
}
if (i!=notifiers.end())
{
return false;
}
return true;
}
// Called during shutdown sequence
void CZMQNotificationInterface::Shutdown()
{
LogPrint(BCLog::ZMQ, "zmq: Shutdown notification interface\n");
if (pcontext)
{
for (std::list<CZMQAbstractNotifier*>::iterator i=notifiers.begin(); i!=notifiers.end(); ++i)
{
CZMQAbstractNotifier *notifier = *i;
LogPrint(BCLog::ZMQ, " Shutdown notifier %s at %s\n", notifier->GetType(), notifier->GetAddress());
notifier->Shutdown();
}
zmq_ctx_destroy(pcontext);
pcontext = 0;
}
}
void CZMQNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
{
if (fInitialDownload || pindexNew == pindexFork) // In IBD or blocks were disconnected without any new ones
return;
for (std::list<CZMQAbstractNotifier*>::iterator i = notifiers.begin(); i!=notifiers.end(); )
{
CZMQAbstractNotifier *notifier = *i;
if (notifier->NotifyBlock(pindexNew))
{
i++;
}
else
{
notifier->Shutdown();
i = notifiers.erase(i);
}
}
}
void CZMQNotificationInterface::TransactionAddedToMempool(const CTransactionRef& ptx)
{
// Used by BlockConnected and BlockDisconnected as well, because they're
// all the same external callback.
const CTransaction& tx = *ptx;
for (std::list<CZMQAbstractNotifier*>::iterator i = notifiers.begin(); i!=notifiers.end(); )
{
CZMQAbstractNotifier *notifier = *i;
if (notifier->NotifyTransaction(tx))
{
i++;
}
else
{
notifier->Shutdown();
i = notifiers.erase(i);
}
}
}
void CZMQNotificationInterface::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected, const std::vector<CTransactionRef>& vtxConflicted)
{
for (const CTransactionRef& ptx : pblock->vtx) {
// Do a normal notify for each transaction added in the block
TransactionAddedToMempool(ptx);
}
}
void CZMQNotificationInterface::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock)
{
for (const CTransactionRef& ptx : pblock->vtx) {
// Do a normal notify for each transaction removed in block disconnection
TransactionAddedToMempool(ptx);
}
}
| mit |
darklost/quick-ng | cocos/editor-support/cocostudio/CCSGUIReader.cpp | 33 | 62116 | /****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "cocostudio/CCSGUIReader.h"
#include "ui/CocosGUI.h"
#include "cocostudio/CCActionManagerEx.h"
#include <fstream>
#include <iostream>
#include "WidgetReader/ButtonReader/ButtonReader.h"
#include "WidgetReader/CheckBoxReader/CheckBoxReader.h"
#include "WidgetReader/SliderReader/SliderReader.h"
#include "WidgetReader/ImageViewReader/ImageViewReader.h"
#include "WidgetReader/LoadingBarReader/LoadingBarReader.h"
#include "WidgetReader/TextAtlasReader/TextAtlasReader.h"
#include "WidgetReader/TextReader/TextReader.h"
#include "WidgetReader/TextBMFontReader/TextBMFontReader.h"
#include "WidgetReader/TextFieldReader/TextFieldReader.h"
#include "WidgetReader/LayoutReader/LayoutReader.h"
#include "WidgetReader/PageViewReader/PageViewReader.h"
#include "WidgetReader/ScrollViewReader/ScrollViewReader.h"
#include "WidgetReader/ListViewReader/ListViewReader.h"
#include "cocostudio/CocoLoader.h"
#include "ui/CocosGUI.h"
#include "tinyxml2.h"
using namespace cocos2d;
using namespace cocos2d::ui;
namespace cocostudio {
static GUIReader* sharedReader = nullptr;
GUIReader::GUIReader():
m_strFilePath("")
{
ObjectFactory* factoryCreate = ObjectFactory::getInstance();
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(ButtonReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(CheckBoxReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(SliderReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(ImageViewReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(LoadingBarReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(TextAtlasReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(TextReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(TextBMFontReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(TextFieldReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(LayoutReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(PageViewReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(ScrollViewReader));
factoryCreate->registerType(CREATE_CLASS_WIDGET_READER_INFO(ListViewReader));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(Button));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(CheckBox));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(ImageView));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(Text));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(TextAtlas));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(TextBMFont));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(LoadingBar));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(Slider));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(TextField));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(Layout));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(ListView));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(PageView));
factoryCreate->registerType(CREATE_CLASS_GUI_INFO(ScrollView));
}
GUIReader::~GUIReader()
{
}
GUIReader* GUIReader::getInstance()
{
if (!sharedReader)
{
sharedReader = new (std::nothrow) GUIReader();
}
return sharedReader;
}
void GUIReader::destroyInstance()
{
CC_SAFE_DELETE(sharedReader);
}
int GUIReader::getVersionInteger(const char *str)
{
std::string strVersion = str;
size_t length = strVersion.length();
if (length < 7)
{
return 0;
}
size_t pos = strVersion.find_first_of(".");
std::string t = strVersion.substr(0,pos);
strVersion = strVersion.substr(pos+1,strVersion.length()-1);
pos = strVersion.find_first_of(".");
std::string h = strVersion.substr(0,pos);
strVersion = strVersion.substr(pos+1,strVersion.length()-1);
pos = strVersion.find_first_of(".");
std::string te = strVersion.substr(0,pos);
strVersion = strVersion.substr(pos+1,strVersion.length()-1);
pos = strVersion.find_first_of(".");
std::string s = strVersion.substr(0,pos);
int it = atoi(t.c_str());
int ih = atoi(h.c_str());
int ite = atoi(te.c_str());
int is = atoi(s.c_str());
int iVersion = it*1000+ih*100+ite*10+is;
// CCLOG("iversion %d",iVersion);
return iVersion;
/************************/
}
void GUIReader::storeFileDesignSize(const char *fileName, const cocos2d::Size &size)
{
std::string keyWidth = fileName;
keyWidth.append("width");
std::string keyHeight = fileName;
keyHeight.append("height");
_fileDesignSizes[keyWidth] = cocos2d::Value(size.width);
_fileDesignSizes[keyHeight] = cocos2d::Value(size.height);
}
const cocos2d::Size GUIReader::getFileDesignSize(const char* fileName) const
{
std::string keyWidth = fileName;
keyWidth.append("width");
std::string keyHeight = fileName;
keyHeight.append("height");
float w = _fileDesignSizes.at(keyWidth).asFloat();
float h = _fileDesignSizes.at(keyHeight).asFloat();
return Size(w, h);
}
void GUIReader::registerTypeAndCallBack(const std::string& classType,
ObjectFactory::Instance ins,
Ref *object,
SEL_ParseEvent callBack)
{
ObjectFactory* factoryCreate = ObjectFactory::getInstance();
ObjectFactory::TInfo t(classType, ins);
factoryCreate->registerType(t);
if (object)
{
_mapObject.insert(ParseObjectMap::value_type(classType, object));
}
if (callBack)
{
_mapParseSelector.insert(ParseCallBackMap::value_type(classType, callBack));
}
}
void GUIReader::registerTypeAndCallBack(const std::string& classType,
ObjectFactory::InstanceFunc ins,
Ref *object,
SEL_ParseEvent callBack)
{
ObjectFactory* factoryCreate = ObjectFactory::getInstance();
ObjectFactory::TInfo t(classType, ins);
factoryCreate->registerType(t);
if (object)
{
_mapObject.insert(ParseObjectMap::value_type(classType, object));
}
if (callBack)
{
_mapParseSelector.insert(ParseCallBackMap::value_type(classType, callBack));
}
}
Widget* GUIReader::widgetFromJsonFile(const char *fileName)
{
std::string jsonpath;
rapidjson::Document jsonDict;
jsonpath = fileName;
// jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
size_t pos = jsonpath.find_last_of('/');
m_strFilePath = jsonpath.substr(0,pos+1);
std::string contentStr = FileUtils::getInstance()->getStringFromFile(jsonpath);
jsonDict.Parse<0>(contentStr.c_str());
if (jsonDict.HasParseError())
{
CCLOG("GetParseError %s\n",jsonDict.GetParseError());
}
Widget* widget = nullptr;
const char* fileVersion = DICTOOL->getStringValue_json(jsonDict, "version");
WidgetPropertiesReader * pReader = nullptr;
if (fileVersion)
{
int versionInteger = getVersionInteger(fileVersion);
if (versionInteger < 250)
{
pReader = new (std::nothrow) WidgetPropertiesReader0250();
widget = pReader->createWidget(jsonDict, m_strFilePath.c_str(), fileName);
}
else
{
pReader = new (std::nothrow) WidgetPropertiesReader0300();
widget = pReader->createWidget(jsonDict, m_strFilePath.c_str(), fileName);
}
}
else
{
pReader = new (std::nothrow) WidgetPropertiesReader0250();
widget = pReader->createWidget(jsonDict, m_strFilePath.c_str(), fileName);
}
CC_SAFE_DELETE(pReader);
return widget;
}
std::string WidgetPropertiesReader::getWidgetReaderClassName(Widget* widget)
{
std::string readerName;
// 1st., custom widget parse properties of parent widget with parent widget reader
if (dynamic_cast<Button*>(widget))
{
readerName = "ButtonReader";
}
else if (dynamic_cast<CheckBox*>(widget))
{
readerName = "CheckBoxReader";
}
else if (dynamic_cast<ImageView*>(widget))
{
readerName = "ImageViewReader";
}
else if (dynamic_cast<TextAtlas*>(widget))
{
readerName = "TextAtlasReader";
}
else if (dynamic_cast<TextBMFont*>(widget))
{
readerName = "TextBMFontReader";
}
else if (dynamic_cast<Text*>(widget))
{
readerName = "TextReader";
}
else if (dynamic_cast<LoadingBar*>(widget))
{
readerName = "LoadingBarReader";
}
else if (dynamic_cast<Slider*>(widget))
{
readerName = "SliderReader";
}
else if (dynamic_cast<TextField*>(widget))
{
readerName = "TextFieldReader";
}
else if (dynamic_cast<ListView*>(widget))
{
readerName = "ListViewReader";
}
else if (dynamic_cast<PageView*>(widget))
{
readerName = "PageViewReader";
}
else if (dynamic_cast<ScrollView*>(widget))
{
readerName = "ScrollViewReader";
}
else if (dynamic_cast<Layout*>(widget))
{
readerName = "LayoutReader";
}
else if (dynamic_cast<Widget*>(widget))
{
readerName = "WidgetReader";
}
return readerName;
}
std::string WidgetPropertiesReader::getGUIClassName(const std::string &name)
{
std::string convertedClassName = name;
if (name == "Panel")
{
convertedClassName = "Layout";
}
else if (name == "TextArea")
{
convertedClassName = "Text";
}
else if (name == "TextButton")
{
convertedClassName = "Button";
}
else if (name == "Label")
{
convertedClassName = "Text";
}
else if (name == "LabelAtlas")
{
convertedClassName = "TextAtlas";
}
else if (name == "LabelBMFont")
{
convertedClassName = "TextBMFont";
}
return convertedClassName;
}
cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(const std::string &classname)
{
std::string name = this->getGUIClassName(classname);
Ref* object = ObjectFactory::getInstance()->createObject(name);
return dynamic_cast<ui::Widget*>(object);
}
WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(const std::string &classname)
{
Ref* object = ObjectFactory::getInstance()->createObject(classname);
return dynamic_cast<WidgetReaderProtocol*>(object);
}
Widget* GUIReader::widgetFromBinaryFile(const char *fileName)
{
std::string jsonpath;
rapidjson::Document jsonDict;
jsonpath = fileName;
// jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
size_t pos = jsonpath.find_last_of('/');
m_strFilePath = jsonpath.substr(0,pos+1);
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName);
auto fileData = FileUtils::getInstance()->getDataFromFile(fullPath);
auto fileDataBytes = fileData.getBytes();
auto fileDataSize = fileData.getSize();
const char* fileVersion = "";
ui::Widget* widget = nullptr;
if (fileDataBytes != nullptr && fileDataSize > 0)
{
CocoLoader tCocoLoader;
if(true == tCocoLoader.ReadCocoBinBuff((char*)fileDataBytes))
{
stExpCocoNode* tpRootCocoNode = tCocoLoader.GetRootCocoNode();
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType || rapidjson::kArrayType == tType)
{
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
for (int i = 0; i < tpRootCocoNode->GetChildNum(); ++i) {
std::string key = tpChildArray[i].GetName(&tCocoLoader);
if (key == "version") {
fileVersion = tpChildArray[i].GetValue(&tCocoLoader);
break;
}
}
WidgetPropertiesReader * pReader = nullptr;
if (fileVersion)
{
int versionInteger = getVersionInteger(fileVersion);
if (versionInteger < 250)
{
CCASSERT(0, "You current studio doesn't support binary format, please upgrade to the latest version!");
pReader = new (std::nothrow) WidgetPropertiesReader0250();
widget = pReader->createWidgetFromBinary(&tCocoLoader, tpRootCocoNode, fileName);
}
else
{
pReader = new (std::nothrow) WidgetPropertiesReader0300();
widget = pReader->createWidgetFromBinary(&tCocoLoader, tpRootCocoNode, fileName);
}
}
else
{
pReader = new (std::nothrow) WidgetPropertiesReader0250();
widget = pReader->createWidgetFromBinary(&tCocoLoader, tpRootCocoNode, fileName);
}
CC_SAFE_DELETE(pReader);
}
}
}
return widget;
}
std::string WidgetPropertiesReader::getWidgetReaderClassName(const std::string& classname)
{
// create widget reader to parse properties of widget
std::string readerName = classname;
if (readerName == "Panel")
{
readerName = "Layout";
}
else if (readerName == "TextArea")
{
readerName = "Text";
}
else if (readerName == "TextButton")
{
readerName = "Button";
}
else if (readerName == "Label")
{
readerName = "Text";
}
else if (readerName == "LabelAtlas")
{
readerName = "TextAtlas";
}
else if (readerName == "LabelBMFont")
{
readerName = "TextBMFont";
}
readerName.append("Reader");
return readerName;
}
void WidgetPropertiesReader::setAnchorPointForWidget(cocos2d::ui::Widget *widget, const rapidjson::Value &options)
{
bool isAnchorPointXExists = DICTOOL->checkObjectExist_json(options, "anchorPointX");
float anchorPointXInFile;
if (isAnchorPointXExists) {
anchorPointXInFile = DICTOOL->getFloatValue_json(options, "anchorPointX");
}else{
anchorPointXInFile = widget->getAnchorPoint().x;
}
bool isAnchorPointYExists = DICTOOL->checkObjectExist_json(options, "anchorPointY");
float anchorPointYInFile;
if (isAnchorPointYExists) {
anchorPointYInFile = DICTOOL->getFloatValue_json(options, "anchorPointY");
}
else{
anchorPointYInFile = widget->getAnchorPoint().y;
}
if (isAnchorPointXExists || isAnchorPointYExists) {
widget->setAnchorPoint(Vec2(anchorPointXInFile, anchorPointYInFile));
}
}
Widget* WidgetPropertiesReader0250::createWidget(const rapidjson::Value& data, const char* fullPath, const char* fileName)
{
m_strFilePath = fullPath;
int texturesCount = DICTOOL->getArrayCount_json(data, "textures");
for (int i=0; i<texturesCount; i++)
{
const char* file = DICTOOL->getStringValueFromArray_json(data, "textures", i);
std::string tp = fullPath;
tp.append(file);
CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str());
}
float fileDesignWidth = DICTOOL->getFloatValue_json(data, "designWidth");
float fileDesignHeight = DICTOOL->getFloatValue_json(data, "designHeight");
if (fileDesignWidth <= 0 || fileDesignHeight <= 0) {
CCLOGERROR("Read design size error!\n");
Size winSize = Director::getInstance()->getWinSize();
GUIReader::getInstance()->storeFileDesignSize(fileName, winSize);
}
else
{
GUIReader::getInstance()->storeFileDesignSize(fileName, Size(fileDesignWidth, fileDesignHeight));
}
const rapidjson::Value& widgetTree = DICTOOL->getSubDictionary_json(data, "widgetTree");
Widget* widget = widgetFromJsonDictionary(widgetTree);
/* *********temp********* */
if (widget->getContentSize().equals(Size::ZERO))
{
Layout* rootWidget = dynamic_cast<Layout*>(widget);
rootWidget->setContentSize(Size(fileDesignWidth, fileDesignHeight));
}
/* ********************** */
// widget->setFileDesignSize(Size(fileDesignWidth, fileDesignHeight));
const rapidjson::Value& actions = DICTOOL->getSubDictionary_json(data, "animation");
/* *********temp********* */
// ActionManager::getInstance()->releaseActions();
/* ********************** */
// CCLOG("file name == [%s]",fileName);
Ref* rootWidget = (Ref*) widget;
ActionManagerEx::getInstance()->initWithDictionary(fileName,actions,rootWidget);
return widget;
}
Widget* WidgetPropertiesReader0250::widgetFromJsonDictionary(const rapidjson::Value&data)
{
Widget* widget = nullptr;
const char* classname = DICTOOL->getStringValue_json(data, "classname");
const rapidjson::Value& uiOptions = DICTOOL->getSubDictionary_json(data, "options");
if (classname && strcmp(classname, "Button") == 0)
{
widget = cocos2d::ui::Button::create();
setPropsForButtonFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "CheckBox") == 0)
{
widget = CheckBox::create();
setPropsForCheckBoxFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "Label") == 0)
{
widget = cocos2d::ui::Text::create();
setPropsForLabelFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "LabelAtlas") == 0)
{
widget = cocos2d::ui::TextAtlas::create();
setPropsForLabelAtlasFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "LoadingBar") == 0)
{
widget = cocos2d::ui::LoadingBar::create();
setPropsForLoadingBarFromJsonDictionary(widget, uiOptions);
}else if (classname && strcmp(classname, "ScrollView") == 0){
widget = cocos2d::ui::ScrollView::create();
setPropsForScrollViewFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "TextArea") == 0)
{
widget = cocos2d::ui::Text::create();
setPropsForLabelFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "TextButton") == 0)
{
widget = cocos2d::ui::Button::create();
setPropsForButtonFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "TextField") == 0)
{
widget = cocos2d::ui::TextField::create();
setPropsForTextFieldFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "ImageView") == 0)
{
widget = cocos2d::ui::ImageView::create();
setPropsForImageViewFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "Panel") == 0)
{
widget = Layout::create();
setPropsForLayoutFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "Slider") == 0)
{
widget = cocos2d::ui::Slider::create();
setPropsForSliderFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "LabelBMFont") == 0)
{
widget = cocos2d::ui::TextBMFont::create();
setPropsForLabelBMFontFromJsonDictionary(widget, uiOptions);
}
else if (classname && strcmp(classname, "DragPanel") == 0)
{
widget = cocos2d::ui::ScrollView::create();
setPropsForScrollViewFromJsonDictionary(widget, uiOptions);
}
int childrenCount = DICTOOL->getArrayCount_json(data, "children");
for (int i=0;i<childrenCount;i++)
{
const rapidjson::Value& subData = DICTOOL->getDictionaryFromArray_json(data, "children", i);
Widget* child = widgetFromJsonDictionary(subData);
if (child)
{
widget->addChild(child);
}
}
return widget;
}
void WidgetPropertiesReader0250::setPropsForWidgetFromJsonDictionary(Widget*widget,const rapidjson::Value&options)
{
bool ignoreSizeExsit = DICTOOL->checkObjectExist_json(options, "ignoreSize");
if (ignoreSizeExsit)
{
widget->ignoreContentAdaptWithSize(DICTOOL->getBooleanValue_json(options, "ignoreSize"));
}
float w = DICTOOL->getFloatValue_json(options, "width");
float h = DICTOOL->getFloatValue_json(options, "height");
widget->setContentSize(Size(w, h));
widget->setTag(DICTOOL->getIntValue_json(options, "tag"));
widget->setActionTag(DICTOOL->getIntValue_json(options, "actiontag"));
widget->setTouchEnabled(DICTOOL->getBooleanValue_json(options, "touchAble"));
const char* name = DICTOOL->getStringValue_json(options, "name");
const char* widgetName = name?name:"default";
widget->setName(widgetName);
float x = DICTOOL->getFloatValue_json(options, "x");
float y = DICTOOL->getFloatValue_json(options, "y");
widget->setPosition(Vec2(x,y));
bool sx = DICTOOL->checkObjectExist_json(options, "scaleX");
if (sx)
{
widget->setScaleX(DICTOOL->getFloatValue_json(options, "scaleX"));
}
bool sy = DICTOOL->checkObjectExist_json(options, "scaleY");
if (sy)
{
widget->setScaleY(DICTOOL->getFloatValue_json(options, "scaleY"));
}
bool rt = DICTOOL->checkObjectExist_json(options, "rotation");
if (rt)
{
widget->setRotation(DICTOOL->getFloatValue_json(options, "rotation"));
}
bool vb = DICTOOL->checkObjectExist_json(options, "visible");
if (vb)
{
widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible"));
}
int z = DICTOOL->getIntValue_json(options, "ZOrder");
widget->setLocalZOrder(z);
}
void WidgetPropertiesReader0250::setColorPropsForWidgetFromJsonDictionary(Widget *widget, const rapidjson::Value&options)
{
bool op = DICTOOL->checkObjectExist_json(options, "opacity");
if (op)
{
widget->setOpacity(DICTOOL->getIntValue_json(options, "opacity"));
}
bool cr = DICTOOL->checkObjectExist_json(options, "colorR");
bool cg = DICTOOL->checkObjectExist_json(options, "colorG");
bool cb = DICTOOL->checkObjectExist_json(options, "colorB");
int colorR = cr ? DICTOOL->getIntValue_json(options, "colorR") : 255;
int colorG = cg ? DICTOOL->getIntValue_json(options, "colorG") : 255;
int colorB = cb ? DICTOOL->getIntValue_json(options, "colorB") : 255;
widget->setColor(Color3B(colorR, colorG, colorB));
this->setAnchorPointForWidget(widget, options);
bool flipX = DICTOOL->getBooleanValue_json(options, "flipX");
bool flipY = DICTOOL->getBooleanValue_json(options, "flipY");
widget->setFlippedX(flipX);
widget->setFlippedY(flipY);
}
void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::Button* button = static_cast<Button*>(widget);
bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable");
button->setScale9Enabled(scale9Enable);
std::string tp_n = m_strFilePath;
std::string tp_p = m_strFilePath;
std::string tp_d = m_strFilePath;
const char* normalFileName = DICTOOL->getStringValue_json(options, "normal");
const char* pressedFileName = DICTOOL->getStringValue_json(options, "pressed");
const char* disabledFileName = DICTOOL->getStringValue_json(options, "disabled");
const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():nullptr;
const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():nullptr;
const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():nullptr;
bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture");
if (scale9Enable)
{
float cx = DICTOOL->getFloatValue_json(options, "capInsetsX");
float cy = DICTOOL->getFloatValue_json(options, "capInsetsY");
float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth");
float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight");
if (useMergedTexture)
{
button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST);
}
else
{
button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp);
}
button->setCapInsets(Rect(cx, cy, cw, ch));
bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width");
bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height");
if (sw && sh)
{
float swf = DICTOOL->getFloatValue_json(options, "scale9Width");
float shf = DICTOOL->getFloatValue_json(options, "scale9Height");
button->setContentSize(Size(swf, shf));
}
}
else
{
if (useMergedTexture)
{
button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST);
}
else
{
button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp);
}
}
bool tt = DICTOOL->checkObjectExist_json(options, "text");
if (tt)
{
const char* text = DICTOOL->getStringValue_json(options, "text");
if (text)
{
button->setTitleText(text);
}
}
bool cr = DICTOOL->checkObjectExist_json(options, "textColorR");
bool cg = DICTOOL->checkObjectExist_json(options, "textColorG");
bool cb = DICTOOL->checkObjectExist_json(options, "textColorB");
int cri = cr?DICTOOL->getIntValue_json(options, "textColorR"):255;
int cgi = cg?DICTOOL->getIntValue_json(options, "textColorG"):255;
int cbi = cb?DICTOOL->getIntValue_json(options, "textColorB"):255;
button->setTitleColor(Color3B(cri,cgi,cbi));
bool fs = DICTOOL->checkObjectExist_json(options, "fontSize");
if (fs)
{
button->setTitleFontSize(DICTOOL->getIntValue_json(options, "fontSize"));
}
bool fn = DICTOOL->checkObjectExist_json(options, "fontName");
if (fn)
{
button->setTitleFontName(DICTOOL->getStringValue_json(options, "fontName"));
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForCheckBoxFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
CheckBox* checkBox = static_cast<CheckBox*>(widget);
const char* backGroundFileName = DICTOOL->getStringValue_json(options, "backGroundBox");
const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(options, "backGroundBoxSelected");
const char* frontCrossFileName = DICTOOL->getStringValue_json(options, "frontCross");
const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(options, "backGroundBoxDisabled");
const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "frontCrossDisabled");
std::string tp_b = m_strFilePath;
std::string tp_bs = m_strFilePath;
std::string tp_c = m_strFilePath;
std::string tp_bd = m_strFilePath;
std::string tp_cd = m_strFilePath;
const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():nullptr;
const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():nullptr;
const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():nullptr;
const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():nullptr;
const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():nullptr;
bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture");
if (useMergedTexture)
{
checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,TextureResType::PLIST);
}
else
{
checkBox->loadTextures(backGroundFileName_tp, backGroundSelectedFileName_tp, frontCrossFileName_tp,backGroundDisabledFileName_tp,frontCrossDisabledFileName_tp);
}
checkBox->setSelected(DICTOOL->getBooleanValue_json(options, "selectedState"));
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::ImageView* imageView = static_cast<ImageView*>(widget);
const char* imageFileName = DICTOOL->getStringValue_json(options, "fileName");
bool scale9EnableExist = DICTOOL->checkObjectExist_json(options, "scale9Enable");
bool scale9Enable = false;
if (scale9EnableExist)
{
scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable");
}
imageView->setScale9Enabled(scale9Enable);
std::string tp_i = m_strFilePath;
const char* imageFileName_tp = nullptr;
if (imageFileName && (strcmp(imageFileName, "") != 0))
{
imageFileName_tp = tp_i.append(imageFileName).c_str();
}
bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture");
if (scale9Enable)
{
if (useMergedTexture)
{
imageView->loadTexture(imageFileName,TextureResType::PLIST);
}
else
{
imageView->loadTexture(imageFileName_tp);
}
bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width");
bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height");
if (sw && sh)
{
float swf = DICTOOL->getFloatValue_json(options, "scale9Width");
float shf = DICTOOL->getFloatValue_json(options, "scale9Height");
imageView->setContentSize(Size(swf, shf));
}
float cx = DICTOOL->getFloatValue_json(options, "capInsetsX");
float cy = DICTOOL->getFloatValue_json(options, "capInsetsY");
float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth");
float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight");
imageView->setCapInsets(Rect(cx, cy, cw, ch));
}
else
{
if (useMergedTexture)
{
imageView->loadTexture(imageFileName,TextureResType::PLIST);
}
else
{
imageView->loadTexture(imageFileName_tp);
}
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForLabelFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::Text* label = static_cast<cocos2d::ui::Text*>(widget);
bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, "touchScaleEnable");
label->setTouchScaleChangeEnabled(touchScaleChangeAble);
const char* text = DICTOOL->getStringValue_json(options, "text");
label->setString(text);
bool fs = DICTOOL->checkObjectExist_json(options, "fontSize");
if (fs)
{
label->setFontSize(DICTOOL->getIntValue_json(options, "fontSize"));
}
bool fn = DICTOOL->checkObjectExist_json(options, "fontName");
if (fn)
{
label->setFontName(DICTOOL->getStringValue_json(options, "fontName"));
}
bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth");
bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight");
if (aw && ah)
{
Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight"));
label->setTextAreaSize(size);
}
bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment");
if (ha)
{
label->setTextHorizontalAlignment((TextHAlignment)DICTOOL->getIntValue_json(options, "hAlignment"));
}
bool va = DICTOOL->checkObjectExist_json(options, "vAlignment");
if (va)
{
label->setTextVerticalAlignment((TextVAlignment)DICTOOL->getIntValue_json(options, "vAlignment"));
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForLabelAtlasFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::TextAtlas* labelAtlas = static_cast<cocos2d::ui::TextAtlas*>(widget);
bool sv = DICTOOL->checkObjectExist_json(options, "stringValue");
bool cmf = DICTOOL->checkObjectExist_json(options, "charMapFile");
bool iw = DICTOOL->checkObjectExist_json(options, "itemWidth");
bool ih = DICTOOL->checkObjectExist_json(options, "itemHeight");
bool scm = DICTOOL->checkObjectExist_json(options, "startCharMap");
if (sv && cmf && iw && ih && scm && (strcmp(DICTOOL->getStringValue_json(options, "charMapFile"), "") != 0))
{
std::string tp_c = m_strFilePath;
const char* cmf_tp = nullptr;
const char* cmft = DICTOOL->getStringValue_json(options, "charMapFile");
cmf_tp = tp_c.append(cmft).c_str();
labelAtlas->setProperty(DICTOOL->getStringValue_json(options, "stringValue"),cmf_tp,DICTOOL->getIntValue_json(options, "itemWidth"),DICTOOL->getIntValue_json(options,"itemHeight"),DICTOOL->getStringValue_json(options, "startCharMap"));
labelAtlas->setProperty(DICTOOL->getStringValue_json(options, "stringValue"),cmf_tp,DICTOOL->getIntValue_json(options, "itemWidth") / CC_CONTENT_SCALE_FACTOR() ,DICTOOL->getIntValue_json(options,"itemHeight") / CC_CONTENT_SCALE_FACTOR(), DICTOOL->getStringValue_json(options, "startCharMap"));
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
Layout* containerWidget = static_cast<Layout*>(widget);
if (!dynamic_cast<cocos2d::ui::ScrollView*>(containerWidget)
&& !dynamic_cast<cocos2d::ui::ListView*>(containerWidget))
{
containerWidget->setClippingEnabled(DICTOOL->getBooleanValue_json(options, "clipAble"));
}
Layout* panel = (Layout*)widget;
bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable");
panel->setBackGroundImageScale9Enabled(backGroundScale9Enable);
int cr = DICTOOL->getIntValue_json(options, "bgColorR");
int cg = DICTOOL->getIntValue_json(options, "bgColorG");
int cb = DICTOOL->getIntValue_json(options, "bgColorB");
int scr = DICTOOL->getIntValue_json(options, "bgStartColorR");
int scg = DICTOOL->getIntValue_json(options, "bgStartColorG");
int scb = DICTOOL->getIntValue_json(options, "bgStartColorB");
int ecr = DICTOOL->getIntValue_json(options, "bgEndColorR");
int ecg = DICTOOL->getIntValue_json(options, "bgEndColorG");
int ecb = DICTOOL->getIntValue_json(options, "bgEndColorB");
float bgcv1 = DICTOOL->getFloatValue_json(options, "vectorX");
float bgcv2 = DICTOOL->getFloatValue_json(options, "vectorY");
panel->setBackGroundColorVector(Vec2(bgcv1, bgcv2));
int co = DICTOOL->getIntValue_json(options, "bgColorOpacity");
int colorType = DICTOOL->getIntValue_json(options, "colorType");
panel->setBackGroundColorType(Layout::BackGroundColorType(colorType));
panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb));
panel->setBackGroundColor(Color3B(cr, cg, cb));
panel->setBackGroundColorOpacity(co);
std::string tp_b = m_strFilePath;
const char* imageFileName = DICTOOL->getStringValue_json(options, "backGroundImage");
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture");
if (backGroundScale9Enable)
{
float cx = DICTOOL->getFloatValue_json(options, "capInsetsX");
float cy = DICTOOL->getFloatValue_json(options, "capInsetsY");
float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth");
float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight");
if (useMergedTexture)
{
panel->setBackGroundImage(imageFileName,TextureResType::PLIST);
}
else
{
panel->setBackGroundImage(imageFileName_tp);
}
panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch));
}
else
{
if (useMergedTexture)
{
panel->setBackGroundImage(imageFileName,TextureResType::PLIST);
}
else
{
panel->setBackGroundImage(imageFileName_tp);
}
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForScrollViewFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForLayoutFromJsonDictionary(widget, options);
cocos2d::ui::ScrollView* scrollView = static_cast<cocos2d::ui::ScrollView*>(widget);
float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth");
float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight");
scrollView->setInnerContainerSize(Size(innerWidth, innerHeight));
int direction = DICTOOL->getFloatValue_json(options, "direction");
scrollView->setDirection((ScrollView::Direction)direction);
scrollView->setBounceEnabled(DICTOOL->getBooleanValue_json(options, "bounceEnable"));
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::Slider* slider = static_cast<cocos2d::ui::Slider*>(widget);
bool barTextureScale9Enable = DICTOOL->getBooleanValue_json(options, "barTextureScale9Enable");
slider->setScale9Enabled(barTextureScale9Enable);
bool bt = DICTOOL->checkObjectExist_json(options, "barFileName");
float barLength = DICTOOL->getFloatValue_json(options, "length");
bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture");
if (bt)
{
if (barTextureScale9Enable)
{
std::string tp_b = m_strFilePath;
const char* imageFileName = DICTOOL->getStringValue_json(options, "barFileName");
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadBarTexture(imageFileName,TextureResType::PLIST);
}
else
{
slider->loadBarTexture(imageFileName_tp);
}
slider->setContentSize(Size(barLength, slider->getContentSize().height));
}
else
{
std::string tp_b = m_strFilePath;
const char* imageFileName = DICTOOL->getStringValue_json(options, "barFileName");
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadBarTexture(imageFileName,TextureResType::PLIST);
}
else
{
slider->loadBarTexture(imageFileName_tp);
}
}
}
std::string tp_n = m_strFilePath;
std::string tp_p = m_strFilePath;
std::string tp_d = m_strFilePath;
const char* normalFileName = DICTOOL->getStringValue_json(options, "ballNormal");
const char* pressedFileName = DICTOOL->getStringValue_json(options, "ballPressed");
const char* disabledFileName = DICTOOL->getStringValue_json(options, "ballDisabled");
const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():nullptr;
const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():nullptr;
const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,TextureResType::PLIST);
}
else
{
slider->loadSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp);
}
slider->setPercent(DICTOOL->getIntValue_json(options, "percent"));
std::string tp_b = m_strFilePath;
const char* imageFileName = DICTOOL->getStringValue_json(options, "progressBarFileName");
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadProgressBarTexture(imageFileName, TextureResType::PLIST);
}
else
{
slider->loadProgressBarTexture(imageFileName_tp);
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForTextFieldFromJsonDictionary(Widget*widget,const rapidjson::Value& options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::TextField* textField = static_cast<cocos2d::ui::TextField*>(widget);
bool ph = DICTOOL->checkObjectExist_json(options, "placeHolder");
if (ph)
{
textField->setPlaceHolder(DICTOOL->getStringValue_json(options, "placeHolder"));
}
textField->setString(DICTOOL->getStringValue_json(options, "text"));
bool fs = DICTOOL->checkObjectExist_json(options, "fontSize");
if (fs)
{
textField->setFontSize(DICTOOL->getIntValue_json(options, "fontSize"));
}
bool fn = DICTOOL->checkObjectExist_json(options, "fontName");
if (fn)
{
textField->setFontName(DICTOOL->getStringValue_json(options, "fontName"));
}
bool tsw = DICTOOL->checkObjectExist_json(options, "touchSizeWidth");
bool tsh = DICTOOL->checkObjectExist_json(options, "touchSizeHeight");
if (tsw && tsh)
{
textField->setTouchSize(Size(DICTOOL->getFloatValue_json(options, "touchSizeWidth"), DICTOOL->getFloatValue_json(options,"touchSizeHeight")));
}
float dw = DICTOOL->getFloatValue_json(options, "width");
float dh = DICTOOL->getFloatValue_json(options, "height");
if (dw > 0.0f || dh > 0.0f)
{
//textField->setSize(Size(dw, dh));
}
bool maxLengthEnable = DICTOOL->getBooleanValue_json(options, "maxLengthEnable");
textField->setMaxLengthEnabled(maxLengthEnable);
if (maxLengthEnable)
{
int maxLength = DICTOOL->getIntValue_json(options, "maxLength");
textField->setMaxLength(maxLength);
}
bool passwordEnable = DICTOOL->getBooleanValue_json(options, "passwordEnable");
textField->setPasswordEnabled(passwordEnable);
if (passwordEnable)
{
textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, "passwordStyleText"));
}
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForLoadingBarFromJsonDictionary(Widget *widget, const rapidjson::Value&options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::LoadingBar* loadingBar = static_cast<cocos2d::ui::LoadingBar*>(widget);
bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture");
std::string tp_b = m_strFilePath;
const char*imageFileName = DICTOOL->getStringValue_json(options, "texture");
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
loadingBar->loadTexture(imageFileName,TextureResType::PLIST);
}
else
{
loadingBar->loadTexture(imageFileName_tp);
}
loadingBar->setDirection(LoadingBar::Direction(DICTOOL->getIntValue_json(options, "direction")));
loadingBar->setPercent(DICTOOL->getIntValue_json(options, "percent"));
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForLabelBMFontFromJsonDictionary(Widget *widget, const rapidjson::Value&options)
{
setPropsForWidgetFromJsonDictionary(widget, options);
cocos2d::ui::TextBMFont* labelBMFont = static_cast<cocos2d::ui::TextBMFont*>(widget);
std::string tp_c = m_strFilePath;
const char* cmf_tp = nullptr;
const char* cmft = DICTOOL->getStringValue_json(options, "fileName");
cmf_tp = tp_c.append(cmft).c_str();
labelBMFont->setFntFile(cmf_tp);
const char* text = DICTOOL->getStringValue_json(options, "text");
labelBMFont->setString(text);
setColorPropsForWidgetFromJsonDictionary(widget,options);
}
void WidgetPropertiesReader0250::setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol *reader, Widget *widget, const rapidjson::Value &options)
{
}
void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(const std::string &classType,
cocos2d::ui::Widget *widget,
const rapidjson::Value &customOptions)
{
}
/*0.3.0.0~1.0.0.0*/
Widget* WidgetPropertiesReader0300::createWidget(const rapidjson::Value& data, const char* fullPath, const char* fileName)
{
m_strFilePath = fullPath;
int texturesCount = DICTOOL->getArrayCount_json(data, "textures");
for (int i=0; i<texturesCount; i++)
{
const char* file = DICTOOL->getStringValueFromArray_json(data, "textures", i);
std::string tp = fullPath;
tp.append(file);
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str());
}
float fileDesignWidth = DICTOOL->getFloatValue_json(data, "designWidth");
float fileDesignHeight = DICTOOL->getFloatValue_json(data, "designHeight");
if (fileDesignWidth <= 0 || fileDesignHeight <= 0) {
CCLOGERROR("Read design size error!\n");
Size winSize = Director::getInstance()->getWinSize();
GUIReader::getInstance()->storeFileDesignSize(fileName, winSize);
}
else
{
GUIReader::getInstance()->storeFileDesignSize(fileName, Size(fileDesignWidth, fileDesignHeight));
}
const rapidjson::Value& widgetTree = DICTOOL->getSubDictionary_json(data, "widgetTree");
Widget* widget = widgetFromJsonDictionary(widgetTree);
/* *********temp********* */
if (widget->getContentSize().equals(Size::ZERO))
{
Layout* rootWidget = dynamic_cast<Layout*>(widget);
rootWidget->setContentSize(Size(fileDesignWidth, fileDesignHeight));
}
/* ********************** */
// widget->setFileDesignSize(Size(fileDesignWidth, fileDesignHeight));
const rapidjson::Value& actions = DICTOOL->getSubDictionary_json(data, "animation");
/* *********temp********* */
// ActionManager::getInstance()->releaseActions();
/* ********************** */
// CCLOG("file name == [%s]",fileName);
Ref* rootWidget = (Ref*) widget;
ActionManagerEx::getInstance()->initWithDictionary(fileName,actions,rootWidget);
return widget;
}
cocos2d::ui::Widget* WidgetPropertiesReader0300::createWidgetFromBinary(CocoLoader* cocoLoader,stExpCocoNode* cocoNode, const char* fileName)
{
stExpCocoNode *tpChildArray = cocoNode->GetChildArray(cocoLoader);
float fileDesignWidth;
float fileDesignHeight;
Widget* widget = nullptr;
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = tpChildArray[i].GetName(cocoLoader);
if (key == "textures") {
int texturesCount = tpChildArray[i].GetChildNum();
for (int j=0; j<texturesCount; j++)
{
std::string file;
stExpCocoNode *textureCountsArray = tpChildArray[i].GetChildArray(cocoLoader);
file = textureCountsArray[j].GetValue(cocoLoader);
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(file);
}
}else if (key == "designWidth"){
fileDesignWidth = utils::atof(tpChildArray[i].GetValue(cocoLoader));
}else if (key == "designHeight"){
fileDesignHeight = utils::atof(tpChildArray[i].GetValue(cocoLoader));
}else if (key == "widgetTree"){
if (fileDesignWidth <= 0 || fileDesignHeight <= 0) {
CCLOGERROR("Read design size error!\n");
Size winSize = Director::getInstance()->getWinSize();
GUIReader::getInstance()->storeFileDesignSize(fileName, winSize);
}
else
{
GUIReader::getInstance()->storeFileDesignSize(fileName, Size(fileDesignWidth, fileDesignHeight));
}
stExpCocoNode *widgetTreeNode = &tpChildArray[i];
rapidjson::Type tType = tpChildArray[i].GetType(cocoLoader);
if (rapidjson::kObjectType == tType)
{
widget = widgetFromBinary(cocoLoader, widgetTreeNode);
}
if (widget->getContentSize().equals(Size::ZERO))
{
Layout* rootWidget = dynamic_cast<Layout*>(widget);
rootWidget->setContentSize(Size(fileDesignWidth, fileDesignHeight));
}
}
}
/* ********************** */
/* ********************** */
stExpCocoNode *optionChildNode = cocoNode->GetChildArray(cocoLoader);
for (int k = 0; k < cocoNode->GetChildNum(); ++k) {
std::string key = optionChildNode[k].GetName(cocoLoader);
if (key == "animation") {
Ref* rootWidget = (Ref*) widget;
ActionManagerEx::getInstance()->initWithBinary(fileName,rootWidget,cocoLoader, &optionChildNode[k]);
break;
}
}
return widget;
}
Widget* WidgetPropertiesReader0300::widgetFromBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNode)
{
Widget* widget = nullptr;
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
stExpCocoNode *optionsNode = nullptr;
stExpCocoNode *childrenNode = nullptr;
int elementCount = cocoNode->GetChildNum();
std::string classname;
for (int i = 0; i < elementCount; ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue(cocoLoader);
if (key == "classname" )
{
if (!value.empty())
{
classname = value;
widget = this->createGUI(classname);
}
else
{
CCLOG("Warning!!! classname not found!");
}
}else if(key == "children"){
childrenNode = &stChildArray[i];
}else if(key == "options"){
optionsNode = &stChildArray[i];
}
}
std::string readerName = this->getWidgetReaderClassName(classname);
WidgetReaderProtocol* reader = this->createWidgetReaderProtocol(readerName);
if (reader)
{
// widget parse with widget reader
setPropsForAllWidgetFromBinary(reader, widget, cocoLoader,optionsNode);
}
else
{
// 1st., custom widget parse properties of parent widget with parent widget reader
readerName = this->getWidgetReaderClassName(widget);
reader = this->createWidgetReaderProtocol(readerName);
if (reader && widget) {
setPropsForAllWidgetFromBinary(reader, widget, cocoLoader, optionsNode);
// 2nd., custom widget parse with custom reader
//2nd. parse custom property
const char* customProperty = nullptr;
stExpCocoNode *optionChildNode = optionsNode->GetChildArray(cocoLoader);
for (int k = 0; k < optionsNode->GetChildNum(); ++k) {
std::string key = optionChildNode[k].GetName(cocoLoader);
if (key == "customProperty") {
customProperty = optionChildNode[k].GetValue(cocoLoader);
break;
}
}
rapidjson::Document customJsonDict;
customJsonDict.Parse<0>(customProperty);
if (customJsonDict.HasParseError())
{
CCLOG("GetParseError %s\n", customJsonDict.GetParseError());
}
setPropsForAllCustomWidgetFromJsonDictionary(classname, widget, customJsonDict);
}else{
CCLOG("Widget or WidgetReader doesn't exists!!! Please check your csb file.");
}
}
//parse children
if (nullptr != childrenNode) {
rapidjson::Type tType22 = childrenNode->GetType(cocoLoader);
if (tType22 == rapidjson::kArrayType) {
int childrenCount = childrenNode->GetChildNum();
stExpCocoNode* innerChildArray = childrenNode->GetChildArray(cocoLoader);
for (int i=0; i < childrenCount; ++i) {
rapidjson::Type tType = innerChildArray[i].GetType(cocoLoader);
if (tType == rapidjson::kObjectType) {
Widget *child = widgetFromBinary(cocoLoader, &innerChildArray[i]);
if (child)
{
PageView* pageView = dynamic_cast<PageView*>(widget);
if (pageView)
{
pageView->addPage(static_cast<Layout*>(child));
}
else
{
ListView* listView = dynamic_cast<ListView*>(widget);
if (listView)
{
listView->pushBackCustomItem(child);
}
else
{
if (dynamic_cast<Layout*>(widget))
{
if (child->getPositionType() == ui::Widget::PositionType::PERCENT)
{
child->setPositionPercent(Vec2(child->getPositionPercent().x + widget->getAnchorPoint().x,
child->getPositionPercent().y + widget->getAnchorPoint().y));
}
child->setPosition(Vec2(child->getPositionX() + widget->getAnchorPointInPoints().x,
child->getPositionY() + widget->getAnchorPointInPoints().y));
}
widget->addChild(child);
}
}
}
}
}
}
}
return widget;
}
void WidgetPropertiesReader0300::setPropsForAllWidgetFromBinary(WidgetReaderProtocol* reader,
cocos2d::ui::Widget* widget,
CocoLoader* cocoLoader,
stExpCocoNode* cocoNode)
{
reader->setPropsFromBinary(widget, cocoLoader, cocoNode);
}
Widget* WidgetPropertiesReader0300::widgetFromJsonDictionary(const rapidjson::Value& data)
{
const char* classname = DICTOOL->getStringValue_json(data, "classname");
const rapidjson::Value& uiOptions = DICTOOL->getSubDictionary_json(data, "options");
Widget* widget = this->createGUI(classname);
// CCLOG("classname = %s", classname);
std::string readerName = this->getWidgetReaderClassName(classname);
WidgetReaderProtocol* reader = this->createWidgetReaderProtocol(readerName);
if (reader)
{
// widget parse with widget reader
setPropsForAllWidgetFromJsonDictionary(reader, widget, uiOptions);
}
else
{
readerName = this->getWidgetReaderClassName(widget);
reader = dynamic_cast<WidgetReaderProtocol*>(ObjectFactory::getInstance()->createObject(readerName));
if (reader && widget) {
setPropsForAllWidgetFromJsonDictionary(reader, widget, uiOptions);
// 2nd., custom widget parse with custom reader
const char* customProperty = DICTOOL->getStringValue_json(uiOptions, "customProperty");
rapidjson::Document customJsonDict;
customJsonDict.Parse<0>(customProperty);
if (customJsonDict.HasParseError())
{
CCLOG("GetParseError %s\n", customJsonDict.GetParseError());
}
setPropsForAllCustomWidgetFromJsonDictionary(classname, widget, customJsonDict);
}else{
CCLOG("Widget or WidgetReader doesn't exists!!! Please check your json file.");
}
}
int childrenCount = DICTOOL->getArrayCount_json(data, "children");
for (int i = 0; i < childrenCount; i++)
{
const rapidjson::Value& subData = DICTOOL->getDictionaryFromArray_json(data, "children", i);
cocos2d::ui::Widget* child = widgetFromJsonDictionary(subData);
if (child)
{
PageView* pageView = dynamic_cast<PageView*>(widget);
if (pageView)
{
pageView->addPage(static_cast<Layout*>(child));
}
else
{
ListView* listView = dynamic_cast<ListView*>(widget);
if (listView)
{
listView->pushBackCustomItem(child);
}
else
{
if (dynamic_cast<Layout*>(widget))
{
if (child->getPositionType() == ui::Widget::PositionType::PERCENT)
{
child->setPositionPercent(Vec2(child->getPositionPercent().x + widget->getAnchorPoint().x, child->getPositionPercent().y + widget->getAnchorPoint().y));
}
child->setPosition(Vec2(child->getPositionX() + widget->getAnchorPointInPoints().x, child->getPositionY() + widget->getAnchorPointInPoints().y));
}
widget->addChild(child);
}
}
}
}
return widget;
}
void WidgetPropertiesReader0300::setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol *reader, Widget *widget, const rapidjson::Value &options)
{
reader->setPropsFromJsonDictionary(widget, options);
}
void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(const std::string &classType,
cocos2d::ui::Widget *widget,
const rapidjson::Value &customOptions)
{
GUIReader* guiReader = GUIReader::getInstance();
std::map<std::string, Ref*> *object_map = guiReader->getParseObjectMap();
Ref* object = (*object_map)[classType];
std::map<std::string, SEL_ParseEvent> *selector_map = guiReader->getParseCallBackMap();
SEL_ParseEvent selector = (*selector_map)[classType];
if (object && selector)
{
(object->*selector)(classType, widget, customOptions);
}
}
}
| mit |
publicloudapp/csrutil | linux-4.3/arch/mips/pci/ops-lantiq.c | 1825 | 2930 | /*
* 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.
*
* Copyright (C) 2010 John Crispin <blogic@openwrt.org>
*/
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <asm/addrspace.h>
#include <linux/vmalloc.h>
#include <lantiq_soc.h>
#include "pci-lantiq.h"
#define LTQ_PCI_CFG_BUSNUM_SHF 16
#define LTQ_PCI_CFG_DEVNUM_SHF 11
#define LTQ_PCI_CFG_FUNNUM_SHF 8
#define PCI_ACCESS_READ 0
#define PCI_ACCESS_WRITE 1
static int ltq_pci_config_access(unsigned char access_type, struct pci_bus *bus,
unsigned int devfn, unsigned int where, u32 *data)
{
unsigned long cfg_base;
unsigned long flags;
u32 temp;
/* we support slot from 0 to 15 dev_fn & 0x68 (AD29) is the
SoC itself */
if ((bus->number != 0) || ((devfn & 0xf8) > 0x78)
|| ((devfn & 0xf8) == 0) || ((devfn & 0xf8) == 0x68))
return 1;
spin_lock_irqsave(&ebu_lock, flags);
cfg_base = (unsigned long) ltq_pci_mapped_cfg;
cfg_base |= (bus->number << LTQ_PCI_CFG_BUSNUM_SHF) | (devfn <<
LTQ_PCI_CFG_FUNNUM_SHF) | (where & ~0x3);
/* Perform access */
if (access_type == PCI_ACCESS_WRITE) {
ltq_w32(swab32(*data), ((u32 *)cfg_base));
} else {
*data = ltq_r32(((u32 *)(cfg_base)));
*data = swab32(*data);
}
wmb();
/* clean possible Master abort */
cfg_base = (unsigned long) ltq_pci_mapped_cfg;
cfg_base |= (0x0 << LTQ_PCI_CFG_FUNNUM_SHF) + 4;
temp = ltq_r32(((u32 *)(cfg_base)));
temp = swab32(temp);
cfg_base = (unsigned long) ltq_pci_mapped_cfg;
cfg_base |= (0x68 << LTQ_PCI_CFG_FUNNUM_SHF) + 4;
ltq_w32(temp, ((u32 *)cfg_base));
spin_unlock_irqrestore(&ebu_lock, flags);
if (((*data) == 0xffffffff) && (access_type == PCI_ACCESS_READ))
return 1;
return 0;
}
int ltq_pci_read_config_dword(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
u32 data = 0;
if (ltq_pci_config_access(PCI_ACCESS_READ, bus, devfn, where, &data))
return PCIBIOS_DEVICE_NOT_FOUND;
if (size == 1)
*val = (data >> ((where & 3) << 3)) & 0xff;
else if (size == 2)
*val = (data >> ((where & 3) << 3)) & 0xffff;
else
*val = data;
return PCIBIOS_SUCCESSFUL;
}
int ltq_pci_write_config_dword(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
u32 data = 0;
if (size == 4) {
data = val;
} else {
if (ltq_pci_config_access(PCI_ACCESS_READ, bus,
devfn, where, &data))
return PCIBIOS_DEVICE_NOT_FOUND;
if (size == 1)
data = (data & ~(0xff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else if (size == 2)
data = (data & ~(0xffff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
}
if (ltq_pci_config_access(PCI_ACCESS_WRITE, bus, devfn, where, &data))
return PCIBIOS_DEVICE_NOT_FOUND;
return PCIBIOS_SUCCESSFUL;
}
| mit |
jkeylu/node-mpg123-util | deps/mpg123/src/libmpg123/frame.c | 36 | 31608 | /*
frame: Heap of routines dealing with the core mpg123 data structure.
copyright 2008-2010 by the mpg123 project - free software under the terms of the LGPL 2.1
see COPYING and AUTHORS files in distribution or http://mpg123.org
initially written by Thomas Orgis
*/
#include "mpg123lib_intern.h"
#include "getcpuflags.h"
#include "debug.h"
static void frame_fixed_reset(mpg123_handle *fr);
/* that's doubled in decode_ntom.c */
#define NTOM_MUL (32768)
#define aligned_pointer(p, type, alignment) align_the_pointer(p, alignment)
static void *align_the_pointer(void *base, unsigned int alignment)
{
/*
Work in unsigned integer realm, explicitly.
Tricking the compiler into integer operations like % by invoking base-NULL is dangerous: It results into ptrdiff_t, which gets negative on big addresses. Big screw up, that.
I try to do it "properly" here: Casting only to uintptr_t and no artihmethic with void*.
*/
uintptr_t baseval = (uintptr_t)(char*)base;
uintptr_t aoff = baseval % alignment;
debug3("align_the_pointer: pointer %p is off by %u from %u",
base, (unsigned int)aoff, alignment);
if(aoff) return (char*)base+alignment-aoff;
else return base;
}
static void frame_default_pars(mpg123_pars *mp)
{
mp->outscale = 1.0;
mp->flags = 0;
#ifdef GAPLESS
mp->flags |= MPG123_GAPLESS;
#endif
mp->flags |= MPG123_AUTO_RESAMPLE;
#ifndef NO_NTOM
mp->force_rate = 0;
#endif
mp->down_sample = 0;
mp->rva = 0;
mp->halfspeed = 0;
mp->doublespeed = 0;
mp->verbose = 0;
#ifndef NO_ICY
mp->icy_interval = 0;
#endif
mp->timeout = 0;
mp->resync_limit = 1024;
#ifdef FRAME_INDEX
mp->index_size = INDEX_SIZE;
#endif
mp->preframes = 4; /* That's good for layer 3 ISO compliance bitstream. */
mpg123_fmt_all(mp);
/* Default of keeping some 4K buffers at hand, should cover the "usual" use case (using 16K pipe buffers as role model). */
#ifndef NO_FEEDER
mp->feedpool = 5;
mp->feedbuffer = 4096;
#endif
}
void frame_init(mpg123_handle *fr)
{
frame_init_par(fr, NULL);
}
void frame_init_par(mpg123_handle *fr, mpg123_pars *mp)
{
fr->own_buffer = TRUE;
fr->buffer.data = NULL;
fr->buffer.rdata = NULL;
fr->buffer.fill = 0;
fr->buffer.size = 0;
fr->rawbuffs = NULL;
fr->rawbuffss = 0;
fr->rawdecwin = NULL;
fr->rawdecwins = 0;
#ifndef NO_8BIT
fr->conv16to8_buf = NULL;
#endif
#ifdef OPT_DITHER
fr->dithernoise = NULL;
#endif
fr->layerscratch = NULL;
fr->xing_toc = NULL;
fr->cpu_opts.type = defdec();
fr->cpu_opts.class = decclass(fr->cpu_opts.type);
#ifndef NO_NTOM
/* these two look unnecessary, check guarantee for synth_ntom_set_step (in control_generic, even)! */
fr->ntom_val[0] = NTOM_MUL>>1;
fr->ntom_val[1] = NTOM_MUL>>1;
fr->ntom_step = NTOM_MUL;
#endif
/* unnecessary: fr->buffer.size = fr->buffer.fill = 0; */
mpg123_reset_eq(fr);
init_icy(&fr->icy);
init_id3(fr);
/* frame_outbuffer is missing... */
/* frame_buffers is missing... that one needs cpu opt setting! */
/* after these... frame_reset is needed before starting full decode */
invalidate_format(&fr->af);
fr->rdat.r_read = NULL;
fr->rdat.r_lseek = NULL;
fr->rdat.iohandle = NULL;
fr->rdat.r_read_handle = NULL;
fr->rdat.r_lseek_handle = NULL;
fr->rdat.cleanup_handle = NULL;
fr->wrapperdata = NULL;
fr->wrapperclean = NULL;
fr->decoder_change = 1;
fr->err = MPG123_OK;
if(mp == NULL) frame_default_pars(&fr->p);
else memcpy(&fr->p, mp, sizeof(struct mpg123_pars_struct));
#ifndef NO_FEEDER
bc_prepare(&fr->rdat.buffer, fr->p.feedpool, fr->p.feedbuffer);
#endif
fr->down_sample = 0; /* Initialize to silence harmless errors when debugging. */
frame_fixed_reset(fr); /* Reset only the fixed data, dynamic buffers are not there yet! */
fr->synth = NULL;
fr->synth_mono = NULL;
fr->make_decode_tables = NULL;
#ifdef FRAME_INDEX
fi_init(&fr->index);
frame_index_setup(fr); /* Apply the size setting. */
#endif
}
#ifdef OPT_DITHER
/* Also, only allocate the memory for the table on demand.
In future, one could create special noise for different sampling frequencies(?). */
int frame_dither_init(mpg123_handle *fr)
{
/* run-time dither noise table generation */
if(fr->dithernoise == NULL)
{
fr->dithernoise = malloc(sizeof(float)*DITHERSIZE);
if(fr->dithernoise == NULL) return 0;
dither_table_init(fr->dithernoise);
}
return 1;
}
#endif
mpg123_pars attribute_align_arg *mpg123_new_pars(int *error)
{
mpg123_pars *mp = malloc(sizeof(struct mpg123_pars_struct));
if(mp != NULL){ frame_default_pars(mp); if(error != NULL) *error = MPG123_OK; }
else if(error != NULL) *error = MPG123_OUT_OF_MEM;
return mp;
}
void attribute_align_arg mpg123_delete_pars(mpg123_pars* mp)
{
if(mp != NULL) free(mp);
}
int attribute_align_arg mpg123_reset_eq(mpg123_handle *mh)
{
int i;
mh->have_eq_settings = 0;
for(i=0; i < 32; ++i) mh->equalizer[0][i] = mh->equalizer[1][i] = DOUBLE_TO_REAL(1.0);
return MPG123_OK;
}
int frame_outbuffer(mpg123_handle *fr)
{
size_t size = fr->outblock;
if(!fr->own_buffer)
{
if(fr->buffer.size < size)
{
fr->err = MPG123_BAD_BUFFER;
if(NOQUIET) error2("have external buffer of size %"SIZE_P", need %"SIZE_P, (size_p)fr->buffer.size, size);
return MPG123_ERR;
}
}
debug1("need frame buffer of %"SIZE_P, (size_p)size);
if(fr->buffer.rdata != NULL && fr->buffer.size != size)
{
free(fr->buffer.rdata);
fr->buffer.rdata = NULL;
}
fr->buffer.size = size;
fr->buffer.data = NULL;
/* be generous: use 16 byte alignment */
if(fr->buffer.rdata == NULL) fr->buffer.rdata = (unsigned char*) malloc(fr->buffer.size+15);
if(fr->buffer.rdata == NULL)
{
fr->err = MPG123_OUT_OF_MEM;
return MPG123_ERR;
}
fr->buffer.data = aligned_pointer(fr->buffer.rdata, unsigned char*, 16);
fr->own_buffer = TRUE;
fr->buffer.fill = 0;
return MPG123_OK;
}
int attribute_align_arg mpg123_replace_buffer(mpg123_handle *mh, unsigned char *data, size_t size)
{
debug2("replace buffer with %p size %"SIZE_P, data, (size_p)size);
/* Will accept any size, the error comes later... */
if(data == NULL)
{
mh->err = MPG123_BAD_BUFFER;
return MPG123_ERR;
}
if(mh->buffer.rdata != NULL) free(mh->buffer.rdata);
mh->own_buffer = FALSE;
mh->buffer.rdata = NULL;
mh->buffer.data = data;
mh->buffer.size = size;
mh->buffer.fill = 0;
return MPG123_OK;
}
#ifdef FRAME_INDEX
int frame_index_setup(mpg123_handle *fr)
{
int ret = MPG123_ERR;
if(fr->p.index_size >= 0)
{ /* Simple fixed index. */
fr->index.grow_size = 0;
debug1("resizing index to %li", fr->p.index_size);
ret = fi_resize(&fr->index, (size_t)fr->p.index_size);
debug2("index resized... %lu at %p", (unsigned long)fr->index.size, (void*)fr->index.data);
}
else
{ /* A growing index. We give it a start, though. */
fr->index.grow_size = (size_t)(- fr->p.index_size);
if(fr->index.size < fr->index.grow_size)
ret = fi_resize(&fr->index, fr->index.grow_size);
else
ret = MPG123_OK; /* We have minimal size already... and since growing is OK... */
}
debug2("set up frame index of size %lu (ret=%i)", (unsigned long)fr->index.size, ret);
return ret;
}
#endif
static void frame_decode_buffers_reset(mpg123_handle *fr)
{
memset(fr->rawbuffs, 0, fr->rawbuffss);
}
int frame_buffers(mpg123_handle *fr)
{
int buffssize = 0;
debug1("frame %p buffer", (void*)fr);
/*
the used-to-be-static buffer of the synth functions, has some subtly different types/sizes
2to1, 4to1, ntom, generic, i386: real[2][2][0x110]
mmx, sse: short[2][2][0x110]
i586(_dither): 4352 bytes; int/long[2][2][0x110]
i486: int[2][2][17*FIR_BUFFER_SIZE]
altivec: static real __attribute__ ((aligned (16))) buffs[4][4][0x110]
Huh, altivec looks like fun. Well, let it be large... then, the 16 byte alignment seems to be implicit on MacOSX malloc anyway.
Let's make a reasonable attempt to allocate enough memory...
Keep in mind: biggest ones are i486 and altivec (mutually exclusive!), then follows i586 and normal real.
mmx/sse use short but also real for resampling.
Thus, minimum is 2*2*0x110*sizeof(real).
*/
if(fr->cpu_opts.type == altivec) buffssize = 4*4*0x110*sizeof(real);
#ifdef OPT_I486
else if(fr->cpu_opts.type == ivier) buffssize = 2*2*17*FIR_BUFFER_SIZE*sizeof(int);
#endif
else if(fr->cpu_opts.type == ifuenf || fr->cpu_opts.type == ifuenf_dither || fr->cpu_opts.type == dreidnow)
buffssize = 2*2*0x110*4; /* don't rely on type real, we need 4352 bytes */
if(2*2*0x110*sizeof(real) > buffssize)
buffssize = 2*2*0x110*sizeof(real);
buffssize += 15; /* For 16-byte alignment (SSE likes that). */
if(fr->rawbuffs != NULL && fr->rawbuffss != buffssize)
{
free(fr->rawbuffs);
fr->rawbuffs = NULL;
}
if(fr->rawbuffs == NULL) fr->rawbuffs = (unsigned char*) malloc(buffssize);
if(fr->rawbuffs == NULL) return -1;
fr->rawbuffss = buffssize;
fr->short_buffs[0][0] = aligned_pointer(fr->rawbuffs,short,16);
fr->short_buffs[0][1] = fr->short_buffs[0][0] + 0x110;
fr->short_buffs[1][0] = fr->short_buffs[0][1] + 0x110;
fr->short_buffs[1][1] = fr->short_buffs[1][0] + 0x110;
fr->real_buffs[0][0] = aligned_pointer(fr->rawbuffs,real,16);
fr->real_buffs[0][1] = fr->real_buffs[0][0] + 0x110;
fr->real_buffs[1][0] = fr->real_buffs[0][1] + 0x110;
fr->real_buffs[1][1] = fr->real_buffs[1][0] + 0x110;
#ifdef OPT_I486
if(fr->cpu_opts.type == ivier)
{
fr->int_buffs[0][0] = (int*) fr->rawbuffs;
fr->int_buffs[0][1] = fr->int_buffs[0][0] + 17*FIR_BUFFER_SIZE;
fr->int_buffs[1][0] = fr->int_buffs[0][1] + 17*FIR_BUFFER_SIZE;
fr->int_buffs[1][1] = fr->int_buffs[1][0] + 17*FIR_BUFFER_SIZE;
}
#endif
#ifdef OPT_ALTIVEC
if(fr->cpu_opts.type == altivec)
{
int i,j;
fr->areal_buffs[0][0] = (real*) fr->rawbuffs;
for(i=0; i<4; ++i) for(j=0; j<4; ++j)
fr->areal_buffs[i][j] = fr->areal_buffs[0][0] + (i*4+j)*0x110;
}
#endif
/* now the different decwins... all of the same size, actually */
/* The MMX ones want 32byte alignment, which I'll try to ensure manually */
{
int decwin_size = (512+32)*sizeof(real);
#ifdef OPT_MMXORSSE
#ifdef OPT_MULTI
if(fr->cpu_opts.class == mmxsse)
{
#endif
/* decwin_mmx will share, decwins will be appended ... sizeof(float)==4 */
if(decwin_size < (512+32)*4) decwin_size = (512+32)*4;
/* the second window + alignment zone -- we align for 32 bytes for SSE as
requirement, 64 byte for matching cache line size (that matters!) */
decwin_size += (512+32)*4 + 63;
/* (512+32)*4/32 == 2176/32 == 68, so one decwin block retains alignment for 32 or 64 bytes */
#ifdef OPT_MULTI
}
#endif
#endif
#if defined(OPT_ALTIVEC) || defined(OPT_ARM)
/* sizeof(real) >= 4 ... yes, it could be 8, for example.
We got it intialized to at least (512+32)*sizeof(real).*/
decwin_size += 512*sizeof(real);
#endif
/* Hm, that's basically realloc() ... */
if(fr->rawdecwin != NULL && fr->rawdecwins != decwin_size)
{
free(fr->rawdecwin);
fr->rawdecwin = NULL;
}
if(fr->rawdecwin == NULL)
fr->rawdecwin = (unsigned char*) malloc(decwin_size);
if(fr->rawdecwin == NULL) return -1;
fr->rawdecwins = decwin_size;
fr->decwin = (real*) fr->rawdecwin;
#ifdef OPT_MMXORSSE
#ifdef OPT_MULTI
if(fr->cpu_opts.class == mmxsse)
{
#endif
/* align decwin, assign that to decwin_mmx, append decwins */
/* I need to add to decwin what is missing to the next full 64 byte -- also I want to make gcc -pedantic happy... */
fr->decwin = aligned_pointer(fr->rawdecwin,real,64);
debug1("aligned decwin: %p", (void*)fr->decwin);
fr->decwin_mmx = (float*)fr->decwin;
fr->decwins = fr->decwin_mmx+512+32;
#ifdef OPT_MULTI
}
else debug("no decwins/decwin_mmx for that class");
#endif
#endif
}
/* Layer scratch buffers are of compile-time fixed size, so allocate only once. */
if(fr->layerscratch == NULL)
{
/* Allocate specific layer1/2/3 buffers, so that we know they'll work for SSE. */
size_t scratchsize = 0;
real *scratcher;
#ifndef NO_LAYER1
scratchsize += sizeof(real) * 2 * SBLIMIT;
#endif
#ifndef NO_LAYER2
scratchsize += sizeof(real) * 2 * 4 * SBLIMIT;
#endif
#ifndef NO_LAYER3
scratchsize += sizeof(real) * 2 * SBLIMIT * SSLIMIT; /* hybrid_in */
scratchsize += sizeof(real) * 2 * SSLIMIT * SBLIMIT; /* hybrid_out */
#endif
/*
Now figure out correct alignment:
We need 16 byte minimum, smallest unit of the blocks is 2*SBLIMIT*sizeof(real), which is 64*4=256. Let's do 64bytes as heuristic for cache line (as proven useful in buffs above).
*/
fr->layerscratch = malloc(scratchsize+63);
if(fr->layerscratch == NULL) return -1;
/* Get aligned part of the memory, then divide it up. */
scratcher = aligned_pointer(fr->layerscratch,real,64);
/* Those funky pointer casts silence compilers...
One might change the code at hand to really just use 1D arrays, but in practice, that would not make a (positive) difference. */
#ifndef NO_LAYER1
fr->layer1.fraction = (real(*)[SBLIMIT])scratcher;
scratcher += 2 * SBLIMIT;
#endif
#ifndef NO_LAYER2
fr->layer2.fraction = (real(*)[4][SBLIMIT])scratcher;
scratcher += 2 * 4 * SBLIMIT;
#endif
#ifndef NO_LAYER3
fr->layer3.hybrid_in = (real(*)[SBLIMIT][SSLIMIT])scratcher;
scratcher += 2 * SBLIMIT * SSLIMIT;
fr->layer3.hybrid_out = (real(*)[SSLIMIT][SBLIMIT])scratcher;
scratcher += 2 * SSLIMIT * SBLIMIT;
#endif
/* Note: These buffers don't need resetting here. */
}
/* Only reset the buffers we created just now. */
frame_decode_buffers_reset(fr);
debug1("frame %p buffer done", (void*)fr);
return 0;
}
int frame_buffers_reset(mpg123_handle *fr)
{
fr->buffer.fill = 0; /* hm, reset buffer fill... did we do a flush? */
fr->bsnum = 0;
/* Wondering: could it be actually _wanted_ to retain buffer contents over different files? (special gapless / cut stuff) */
fr->bsbuf = fr->bsspace[1];
fr->bsbufold = fr->bsbuf;
fr->bitreservoir = 0;
frame_decode_buffers_reset(fr);
memset(fr->bsspace, 0, 2*(MAXFRAMESIZE+512));
memset(fr->ssave, 0, 34);
fr->hybrid_blc[0] = fr->hybrid_blc[1] = 0;
memset(fr->hybrid_block, 0, sizeof(real)*2*2*SBLIMIT*SSLIMIT);
return 0;
}
static void frame_icy_reset(mpg123_handle* fr)
{
#ifndef NO_ICY
if(fr->icy.data != NULL) free(fr->icy.data);
fr->icy.data = NULL;
fr->icy.interval = 0;
fr->icy.next = 0;
#endif
}
static void frame_free_toc(mpg123_handle *fr)
{
if(fr->xing_toc != NULL){ free(fr->xing_toc); fr->xing_toc = NULL; }
}
/* Just copy the Xing TOC over... */
int frame_fill_toc(mpg123_handle *fr, unsigned char* in)
{
if(fr->xing_toc == NULL) fr->xing_toc = malloc(100);
if(fr->xing_toc != NULL)
{
memcpy(fr->xing_toc, in, 100);
#ifdef DEBUG
debug("Got a TOC! Showing the values...");
{
int i;
for(i=0; i<100; ++i)
debug2("entry %i = %i", i, fr->xing_toc[i]);
}
#endif
return TRUE;
}
return FALSE;
}
/* Prepare the handle for a new track.
Reset variables, buffers... */
int frame_reset(mpg123_handle* fr)
{
frame_buffers_reset(fr);
frame_fixed_reset(fr);
frame_free_toc(fr);
#ifdef FRAME_INDEX
fi_reset(&fr->index);
#endif
return 0;
}
/* Reset everythign except dynamic memory. */
static void frame_fixed_reset(mpg123_handle *fr)
{
frame_icy_reset(fr);
open_bad(fr);
fr->to_decode = FALSE;
fr->to_ignore = FALSE;
fr->metaflags = 0;
fr->outblock = 0; /* This will be set before decoding! */
fr->num = -1;
fr->input_offset = -1;
fr->playnum = -1;
fr->state_flags = FRAME_ACCURATE;
fr->silent_resync = 0;
fr->audio_start = 0;
fr->clip = 0;
fr->oldhead = 0;
fr->firsthead = 0;
fr->vbr = MPG123_CBR;
fr->abr_rate = 0;
fr->track_frames = 0;
fr->track_samples = -1;
fr->framesize=0;
fr->mean_frames = 0;
fr->mean_framesize = 0;
fr->freesize = 0;
fr->lastscale = -1;
fr->rva.level[0] = -1;
fr->rva.level[1] = -1;
fr->rva.gain[0] = 0;
fr->rva.gain[1] = 0;
fr->rva.peak[0] = 0;
fr->rva.peak[1] = 0;
fr->fsizeold = 0;
fr->firstframe = 0;
fr->ignoreframe = fr->firstframe-fr->p.preframes;
fr->lastframe = -1;
fr->fresh = 1;
fr->new_format = 0;
#ifdef GAPLESS
frame_gapless_init(fr,-1,0,0);
fr->lastoff = 0;
fr->firstoff = 0;
#endif
#ifdef OPT_I486
fr->i486bo[0] = fr->i486bo[1] = FIR_SIZE-1;
#endif
fr->bo = 1; /* the usual bo */
#ifdef OPT_DITHER
fr->ditherindex = 0;
#endif
reset_id3(fr);
reset_icy(&fr->icy);
/* ICY stuff should go into icy.c, eh? */
#ifndef NO_ICY
fr->icy.interval = 0;
fr->icy.next = 0;
#endif
fr->halfphase = 0; /* here or indeed only on first-time init? */
fr->error_protection = 0;
fr->freeformat_framesize = -1;
}
static void frame_free_buffers(mpg123_handle *fr)
{
if(fr->rawbuffs != NULL) free(fr->rawbuffs);
fr->rawbuffs = NULL;
fr->rawbuffss = 0;
if(fr->rawdecwin != NULL) free(fr->rawdecwin);
fr->rawdecwin = NULL;
fr->rawdecwins = 0;
#ifndef NO_8BIT
if(fr->conv16to8_buf != NULL) free(fr->conv16to8_buf);
fr->conv16to8_buf = NULL;
#endif
if(fr->layerscratch != NULL) free(fr->layerscratch);
}
void frame_exit(mpg123_handle *fr)
{
if(fr->buffer.rdata != NULL)
{
debug1("freeing buffer at %p", (void*)fr->buffer.rdata);
free(fr->buffer.rdata);
}
fr->buffer.rdata = NULL;
frame_free_buffers(fr);
frame_free_toc(fr);
#ifdef FRAME_INDEX
fi_exit(&fr->index);
#endif
#ifdef OPT_DITHER
if(fr->dithernoise != NULL)
{
free(fr->dithernoise);
fr->dithernoise = NULL;
}
#endif
exit_id3(fr);
clear_icy(&fr->icy);
/* Clean up possible mess from LFS wrapper. */
if(fr->wrapperclean != NULL)
{
fr->wrapperclean(fr->wrapperdata);
fr->wrapperdata = NULL;
}
#ifndef NO_FEEDER
bc_cleanup(&fr->rdat.buffer);
#endif
}
int attribute_align_arg mpg123_info(mpg123_handle *mh, struct mpg123_frameinfo *mi)
{
if(mh == NULL) return MPG123_ERR;
if(mi == NULL)
{
mh->err = MPG123_ERR_NULL;
return MPG123_ERR;
}
mi->version = mh->mpeg25 ? MPG123_2_5 : (mh->lsf ? MPG123_2_0 : MPG123_1_0);
mi->layer = mh->lay;
mi->rate = frame_freq(mh);
switch(mh->mode)
{
case 0: mi->mode = MPG123_M_STEREO; break;
case 1: mi->mode = MPG123_M_JOINT; break;
case 2: mi->mode = MPG123_M_DUAL; break;
case 3: mi->mode = MPG123_M_MONO; break;
default: error("That mode cannot be!");
}
mi->mode_ext = mh->mode_ext;
mi->framesize = mh->framesize+4; /* Include header. */
mi->flags = 0;
if(mh->error_protection) mi->flags |= MPG123_CRC;
if(mh->copyright) mi->flags |= MPG123_COPYRIGHT;
if(mh->extension) mi->flags |= MPG123_PRIVATE;
if(mh->original) mi->flags |= MPG123_ORIGINAL;
mi->emphasis = mh->emphasis;
mi->bitrate = frame_bitrate(mh);
mi->abr_rate = mh->abr_rate;
mi->vbr = mh->vbr;
return MPG123_OK;
}
int attribute_align_arg mpg123_framedata(mpg123_handle *mh, unsigned long *header, unsigned char **bodydata, size_t *bodybytes)
{
if(mh == NULL) return MPG123_ERR;
if(!mh->to_decode) return MPG123_ERR;
if(header != NULL) *header = mh->oldhead;
if(bodydata != NULL) *bodydata = mh->bsbuf;
if(bodybytes != NULL) *bodybytes = mh->framesize;
return MPG123_OK;
}
/*
Fuzzy frame offset searching (guessing).
When we don't have an accurate position, we may use an inaccurate one.
Possibilities:
- use approximate positions from Xing TOC (not yet parsed)
- guess wildly from mean framesize and offset of first frame / beginning of file.
*/
static off_t frame_fuzzy_find(mpg123_handle *fr, off_t want_frame, off_t* get_frame)
{
/* Default is to go to the beginning. */
off_t ret = fr->audio_start;
*get_frame = 0;
/* But we try to find something better. */
/* Xing VBR TOC works with relative positions, both in terms of audio frames and stream bytes.
Thus, it only works when whe know the length of things.
Oh... I assume the offsets are relative to the _total_ file length. */
if(fr->xing_toc != NULL && fr->track_frames > 0 && fr->rdat.filelen > 0)
{
/* One could round... */
int toc_entry = (int) ((double)want_frame*100./fr->track_frames);
/* It is an index in the 100-entry table. */
if(toc_entry < 0) toc_entry = 0;
if(toc_entry > 99) toc_entry = 99;
/* Now estimate back what frame we get. */
*get_frame = (off_t) ((double)toc_entry/100. * fr->track_frames);
fr->state_flags &= ~FRAME_ACCURATE;
fr->silent_resync = 1;
/* Question: Is the TOC for whole file size (with/without ID3) or the "real" audio data only?
ID3v1 info could also matter. */
ret = (off_t) ((double)fr->xing_toc[toc_entry]/256.* fr->rdat.filelen);
}
else if(fr->mean_framesize > 0)
{ /* Just guess with mean framesize (may be exact with CBR files). */
/* Query filelen here or not? */
fr->state_flags &= ~FRAME_ACCURATE; /* Fuzzy! */
fr->silent_resync = 1;
*get_frame = want_frame;
ret = (off_t) (fr->audio_start+fr->mean_framesize*want_frame);
}
debug5("fuzzy: want %li of %li, get %li at %li B of %li B",
(long)want_frame, (long)fr->track_frames, (long)*get_frame, (long)ret, (long)(fr->rdat.filelen-fr->audio_start));
return ret;
}
/*
find the best frame in index just before the wanted one, seek to there
then step to just before wanted one with read_frame
do not care tabout the stuff that was in buffer but not played back
everything that left the decoder is counted as played
Decide if you want low latency reaction and accurate timing info or stable long-time playback with buffer!
*/
off_t frame_index_find(mpg123_handle *fr, off_t want_frame, off_t* get_frame)
{
/* default is file start if no index position */
off_t gopos = 0;
*get_frame = 0;
#ifdef FRAME_INDEX
/* Possibly use VBRI index, too? I'd need an example for this... */
if(fr->index.fill)
{
/* find in index */
size_t fi;
/* at index fi there is frame step*fi... */
fi = want_frame/fr->index.step;
if(fi >= fr->index.fill) /* If we are beyond the end of frame index...*/
{
/* When fuzzy seek is allowed, we have some limited tolerance for the frames we want to read rather then jump over. */
if(fr->p.flags & MPG123_FUZZY && want_frame - (fr->index.fill-1)*fr->index.step > 10)
{
gopos = frame_fuzzy_find(fr, want_frame, get_frame);
if(gopos > fr->audio_start) return gopos; /* Only in that case, we have a useful guess. */
/* Else... just continue, fuzzyness didn't help. */
}
/* Use the last available position, slowly advancing from that one. */
fi = fr->index.fill - 1;
}
/* We have index position, that yields frame and byte offsets. */
*get_frame = fi*fr->index.step;
gopos = fr->index.data[fi];
fr->state_flags |= FRAME_ACCURATE; /* When using the frame index, we are accurate. */
}
else
{
#endif
if(fr->p.flags & MPG123_FUZZY)
return frame_fuzzy_find(fr, want_frame, get_frame);
/* A bit hackish here... but we need to be fresh when looking for the first header again. */
fr->firsthead = 0;
fr->oldhead = 0;
#ifdef FRAME_INDEX
}
#endif
debug2("index: 0x%lx for frame %li", (unsigned long)gopos, (long) *get_frame);
return gopos;
}
off_t frame_ins2outs(mpg123_handle *fr, off_t ins)
{
off_t outs = 0;
switch(fr->down_sample)
{
case 0:
# ifndef NO_DOWNSAMPLE
case 1:
case 2:
# endif
outs = ins>>fr->down_sample;
break;
# ifndef NO_NTOM
case 3: outs = ntom_ins2outs(fr, ins); break;
# endif
default: error1("Bad down_sample (%i) ... should not be possible!!", fr->down_sample);
}
return outs;
}
off_t frame_outs(mpg123_handle *fr, off_t num)
{
off_t outs = 0;
switch(fr->down_sample)
{
case 0:
# ifndef NO_DOWNSAMPLE
case 1:
case 2:
# endif
outs = (spf(fr)>>fr->down_sample)*num;
break;
#ifndef NO_NTOM
case 3: outs = ntom_frmouts(fr, num); break;
#endif
default: error1("Bad down_sample (%i) ... should not be possible!!", fr->down_sample);
}
return outs;
}
/* Compute the number of output samples we expect from this frame.
This is either simple spf() or a tad more elaborate for ntom. */
off_t frame_expect_outsamples(mpg123_handle *fr)
{
off_t outs = 0;
switch(fr->down_sample)
{
case 0:
# ifndef NO_DOWNSAMPLE
case 1:
case 2:
# endif
outs = spf(fr)>>fr->down_sample;
break;
#ifndef NO_NTOM
case 3: outs = ntom_frame_outsamples(fr); break;
#endif
default: error1("Bad down_sample (%i) ... should not be possible!!", fr->down_sample);
}
return outs;
}
off_t frame_offset(mpg123_handle *fr, off_t outs)
{
off_t num = 0;
switch(fr->down_sample)
{
case 0:
# ifndef NO_DOWNSAMPLE
case 1:
case 2:
# endif
num = outs/(spf(fr)>>fr->down_sample);
break;
#ifndef NO_NTOM
case 3: num = ntom_frameoff(fr, outs); break;
#endif
default: error("Bad down_sample ... should not be possible!!");
}
return num;
}
#ifdef GAPLESS
/* input in _input_ samples */
void frame_gapless_init(mpg123_handle *fr, off_t framecount, off_t bskip, off_t eskip)
{
debug3("frame_gaples_init: given %"OFF_P" frames, skip %"OFF_P" and %"OFF_P, (off_p)framecount, (off_p)bskip, (off_p)eskip);
fr->gapless_frames = framecount;
if(fr->gapless_frames > 0)
{
fr->begin_s = bskip+GAPLESS_DELAY;
fr->end_s = framecount*spf(fr)-eskip+GAPLESS_DELAY;
}
else fr->begin_s = fr->end_s = 0;
/* These will get proper values later, from above plus resampling info. */
fr->begin_os = 0;
fr->end_os = 0;
fr->fullend_os = 0;
debug2("frame_gapless_init: from %"OFF_P" to %"OFF_P" samples", (off_p)fr->begin_s, (off_p)fr->end_s);
}
void frame_gapless_realinit(mpg123_handle *fr)
{
fr->begin_os = frame_ins2outs(fr, fr->begin_s);
fr->end_os = frame_ins2outs(fr, fr->end_s);
fr->fullend_os = frame_ins2outs(fr, fr->gapless_frames*spf(fr));
debug2("frame_gapless_realinit: from %"OFF_P" to %"OFF_P" samples", (off_p)fr->begin_os, (off_p)fr->end_os);
}
/* At least note when there is trouble... */
void frame_gapless_update(mpg123_handle *fr, off_t total_samples)
{
off_t gapless_samples = fr->gapless_frames*spf(fr);
debug2("gapless update with new sample count %"OFF_P" as opposed to known %"OFF_P, total_samples, gapless_samples);
if(NOQUIET && total_samples != gapless_samples)
fprintf(stderr, "\nWarning: Real sample count differs from given gapless sample count. Frankenstein stream?\n");
if(gapless_samples > total_samples)
{
if(NOQUIET) error2("End sample count smaller than gapless end! (%"OFF_P" < %"OFF_P"). Disabling gapless mode from now on.", (off_p)total_samples, (off_p)fr->end_s);
/* This invalidates the current position... but what should I do? */
frame_gapless_init(fr, -1, 0, 0);
frame_gapless_realinit(fr);
fr->lastframe = -1;
fr->lastoff = 0;
}
}
#endif
/* Compute the needed frame to ignore from, for getting accurate/consistent output for intended firstframe. */
static off_t ignoreframe(mpg123_handle *fr)
{
off_t preshift = fr->p.preframes;
/* Layer 3 _really_ needs at least one frame before. */
if(fr->lay==3 && preshift < 1) preshift = 1;
/* Layer 1 & 2 reall do not need more than 2. */
if(fr->lay!=3 && preshift > 2) preshift = 2;
return fr->firstframe - preshift;
}
/* The frame seek... This is not simply the seek to fe*spf(fr) samples in output because we think of _input_ frames here.
Seek to frame offset 1 may be just seek to 200 samples offset in output since the beginning of first frame is delay/padding.
Hm, is that right? OK for the padding stuff, but actually, should the decoder delay be better totally hidden or not?
With gapless, even the whole frame position could be advanced further than requested (since Homey don't play dat). */
void frame_set_frameseek(mpg123_handle *fr, off_t fe)
{
fr->firstframe = fe;
#ifdef GAPLESS
if(fr->p.flags & MPG123_GAPLESS && fr->gapless_frames > 0)
{
/* Take care of the beginning... */
off_t beg_f = frame_offset(fr, fr->begin_os);
if(fe <= beg_f)
{
fr->firstframe = beg_f;
fr->firstoff = fr->begin_os - frame_outs(fr, beg_f);
}
else fr->firstoff = 0;
/* The end is set once for a track at least, on the frame_set_frameseek called in get_next_frame() */
if(fr->end_os > 0)
{
fr->lastframe = frame_offset(fr,fr->end_os);
fr->lastoff = fr->end_os - frame_outs(fr, fr->lastframe);
} else {fr->lastframe = -1; fr->lastoff = 0; }
} else { fr->firstoff = fr->lastoff = 0; fr->lastframe = -1; }
#endif
fr->ignoreframe = ignoreframe(fr);
#ifdef GAPLESS
debug5("frame_set_frameseek: begin at %li frames and %li samples, end at %li and %li; ignore from %li",
(long) fr->firstframe, (long) fr->firstoff,
(long) fr->lastframe, (long) fr->lastoff, (long) fr->ignoreframe);
#else
debug3("frame_set_frameseek: begin at %li frames, end at %li; ignore from %li",
(long) fr->firstframe, (long) fr->lastframe, (long) fr->ignoreframe);
#endif
}
void frame_skip(mpg123_handle *fr)
{
#ifndef NO_LAYER3
if(fr->lay == 3) set_pointer(fr, 512);
#endif
}
/* Sample accurate seek prepare for decoder. */
/* This gets unadjusted output samples and takes resampling into account */
void frame_set_seek(mpg123_handle *fr, off_t sp)
{
fr->firstframe = frame_offset(fr, sp);
debug1("frame_set_seek: from %"OFF_P, fr->num);
#ifndef NO_NTOM
if(fr->down_sample == 3) ntom_set_ntom(fr, fr->firstframe);
#endif
fr->ignoreframe = ignoreframe(fr);
#ifdef GAPLESS /* The sample offset is used for non-gapless mode, too! */
fr->firstoff = sp - frame_outs(fr, fr->firstframe);
debug5("frame_set_seek: begin at %li frames and %li samples, end at %li and %li; ignore from %li",
(long) fr->firstframe, (long) fr->firstoff,
(long) fr->lastframe, (long) fr->lastoff, (long) fr->ignoreframe);
#else
debug3("frame_set_seek: begin at %li frames, end at %li; ignore from %li",
(long) fr->firstframe, (long) fr->lastframe, (long) fr->ignoreframe);
#endif
}
int attribute_align_arg mpg123_volume_change(mpg123_handle *mh, double change)
{
if(mh == NULL) return MPG123_ERR;
return mpg123_volume(mh, change + (double) mh->p.outscale);
}
int attribute_align_arg mpg123_volume(mpg123_handle *mh, double vol)
{
if(mh == NULL) return MPG123_ERR;
if(vol >= 0) mh->p.outscale = vol;
else mh->p.outscale = 0.;
do_rva(mh);
return MPG123_OK;
}
static int get_rva(mpg123_handle *fr, double *peak, double *gain)
{
double p = -1;
double g = 0;
int ret = 0;
if(fr->p.rva)
{
int rt = 0;
/* Should one assume a zero RVA as no RVA? */
if(fr->p.rva == 2 && fr->rva.level[1] != -1) rt = 1;
if(fr->rva.level[rt] != -1)
{
p = fr->rva.peak[rt];
g = fr->rva.gain[rt];
ret = 1; /* Success. */
}
}
if(peak != NULL) *peak = p;
if(gain != NULL) *gain = g;
return ret;
}
/* adjust the volume, taking both fr->outscale and rva values into account */
void do_rva(mpg123_handle *fr)
{
double peak = 0;
double gain = 0;
double newscale;
double rvafact = 1;
if(get_rva(fr, &peak, &gain))
{
if(NOQUIET && fr->p.verbose > 1) fprintf(stderr, "Note: doing RVA with gain %f\n", gain);
rvafact = pow(10,gain/20);
}
newscale = fr->p.outscale*rvafact;
/* if peak is unknown (== 0) this check won't hurt */
if((peak*newscale) > 1.0)
{
newscale = 1.0/peak;
warning2("limiting scale value to %f to prevent clipping with indicated peak factor of %f", newscale, peak);
}
/* first rva setting is forced with fr->lastscale < 0 */
if(newscale != fr->lastscale || fr->decoder_change)
{
debug3("changing scale value from %f to %f (peak estimated to %f)", fr->lastscale != -1 ? fr->lastscale : fr->p.outscale, newscale, (double) (newscale*peak));
fr->lastscale = newscale;
/* It may be too early, actually. */
if(fr->make_decode_tables != NULL) fr->make_decode_tables(fr); /* the actual work */
}
}
int attribute_align_arg mpg123_getvolume(mpg123_handle *mh, double *base, double *really, double *rva_db)
{
if(mh == NULL) return MPG123_ERR;
if(base) *base = mh->p.outscale;
if(really) *really = mh->lastscale;
get_rva(mh, NULL, rva_db);
return MPG123_OK;
}
off_t attribute_align_arg mpg123_framepos(mpg123_handle *mh)
{
if(mh == NULL) return MPG123_ERR;
return mh->input_offset;
}
| mit |
Ultraschall/Soundboard | src/JuceLibraryCode/modules/juce_graphics/image_formats/jpglib/jcmarker.c | 43 | 16135 | /*
* jcmarker.c
*
* Copyright (C) 1991-1998, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to write JPEG datastream markers.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Private state */
typedef struct {
struct jpeg_marker_writer pub; /* public fields */
unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
} my_marker_writer;
typedef my_marker_writer * my_marker_ptr;
/*
* Basic output routines.
*
* Note that we do not support suspension while writing a marker.
* Therefore, an application using suspension must ensure that there is
* enough buffer space for the initial markers (typ. 600-700 bytes) before
* calling jpeg_start_compress, and enough space to write the trailing EOI
* (a few bytes) before calling jpeg_finish_compress. Multipass compression
* modes are not supported at all with suspension, so those two are the only
* points where markers will be written.
*/
LOCAL(void)
emit_byte (j_compress_ptr cinfo, int val)
/* Emit a byte */
{
struct jpeg_destination_mgr * dest = cinfo->dest;
*(dest->next_output_byte)++ = (JOCTET) val;
if (--dest->free_in_buffer == 0) {
if (! (*dest->empty_output_buffer) (cinfo))
ERREXIT(cinfo, JERR_CANT_SUSPEND);
}
}
LOCAL(void)
emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
/* Emit a marker code */
{
emit_byte(cinfo, 0xFF);
emit_byte(cinfo, (int) mark);
}
LOCAL(void)
emit_2bytes (j_compress_ptr cinfo, int value)
/* Emit a 2-byte integer; these are always MSB first in JPEG files */
{
emit_byte(cinfo, (value >> 8) & 0xFF);
emit_byte(cinfo, value & 0xFF);
}
/*
* Routines to write specific marker types.
*/
LOCAL(int)
emit_dqt (j_compress_ptr cinfo, int index)
/* Emit a DQT marker */
/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
{
JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
int prec;
int i;
if (qtbl == NULL)
ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
prec = 0;
for (i = 0; i < DCTSIZE2; i++) {
if (qtbl->quantval[i] > 255)
prec = 1;
}
if (! qtbl->sent_table) {
emit_marker(cinfo, M_DQT);
emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
emit_byte(cinfo, index + (prec<<4));
for (i = 0; i < DCTSIZE2; i++) {
/* The table entries must be emitted in zigzag order. */
unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
if (prec)
emit_byte(cinfo, (int) (qval >> 8));
emit_byte(cinfo, (int) (qval & 0xFF));
}
qtbl->sent_table = TRUE;
}
return prec;
}
LOCAL(void)
emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
/* Emit a DHT marker */
{
JHUFF_TBL * htbl;
int length, i;
if (is_ac) {
htbl = cinfo->ac_huff_tbl_ptrs[index];
index += 0x10; /* output index has AC bit set */
} else {
htbl = cinfo->dc_huff_tbl_ptrs[index];
}
if (htbl == NULL)
ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
if (! htbl->sent_table) {
emit_marker(cinfo, M_DHT);
length = 0;
for (i = 1; i <= 16; i++)
length += htbl->bits[i];
emit_2bytes(cinfo, length + 2 + 1 + 16);
emit_byte(cinfo, index);
for (i = 1; i <= 16; i++)
emit_byte(cinfo, htbl->bits[i]);
for (i = 0; i < length; i++)
emit_byte(cinfo, htbl->huffval[i]);
htbl->sent_table = TRUE;
}
}
LOCAL(void)
emit_dac (j_compress_ptr)
/* Emit a DAC marker */
/* Since the useful info is so small, we want to emit all the tables in */
/* one DAC marker. Therefore this routine does its own scan of the table. */
{
#ifdef C_ARITH_CODING_SUPPORTED
char dc_in_use[NUM_ARITH_TBLS];
char ac_in_use[NUM_ARITH_TBLS];
int length, i;
jpeg_component_info *compptr;
for (i = 0; i < NUM_ARITH_TBLS; i++)
dc_in_use[i] = ac_in_use[i] = 0;
for (i = 0; i < cinfo->comps_in_scan; i++) {
compptr = cinfo->cur_comp_info[i];
dc_in_use[compptr->dc_tbl_no] = 1;
ac_in_use[compptr->ac_tbl_no] = 1;
}
length = 0;
for (i = 0; i < NUM_ARITH_TBLS; i++)
length += dc_in_use[i] + ac_in_use[i];
emit_marker(cinfo, M_DAC);
emit_2bytes(cinfo, length*2 + 2);
for (i = 0; i < NUM_ARITH_TBLS; i++) {
if (dc_in_use[i]) {
emit_byte(cinfo, i);
emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
}
if (ac_in_use[i]) {
emit_byte(cinfo, i + 0x10);
emit_byte(cinfo, cinfo->arith_ac_K[i]);
}
}
#endif /* C_ARITH_CODING_SUPPORTED */
}
LOCAL(void)
emit_dri (j_compress_ptr cinfo)
/* Emit a DRI marker */
{
emit_marker(cinfo, M_DRI);
emit_2bytes(cinfo, 4); /* fixed length */
emit_2bytes(cinfo, (int) cinfo->restart_interval);
}
LOCAL(void)
emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
/* Emit a SOF marker */
{
int ci;
jpeg_component_info *compptr;
emit_marker(cinfo, code);
emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
/* Make sure image isn't bigger than SOF field can handle */
if ((long) cinfo->image_height > 65535L ||
(long) cinfo->image_width > 65535L)
ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
emit_byte(cinfo, cinfo->data_precision);
emit_2bytes(cinfo, (int) cinfo->image_height);
emit_2bytes(cinfo, (int) cinfo->image_width);
emit_byte(cinfo, cinfo->num_components);
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
emit_byte(cinfo, compptr->component_id);
emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
emit_byte(cinfo, compptr->quant_tbl_no);
}
}
LOCAL(void)
emit_sos (j_compress_ptr cinfo)
/* Emit a SOS marker */
{
int i, td, ta;
jpeg_component_info *compptr;
emit_marker(cinfo, M_SOS);
emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
emit_byte(cinfo, cinfo->comps_in_scan);
for (i = 0; i < cinfo->comps_in_scan; i++) {
compptr = cinfo->cur_comp_info[i];
emit_byte(cinfo, compptr->component_id);
td = compptr->dc_tbl_no;
ta = compptr->ac_tbl_no;
if (cinfo->progressive_mode) {
/* Progressive mode: only DC or only AC tables are used in one scan;
* furthermore, Huffman coding of DC refinement uses no table at all.
* We emit 0 for unused field(s); this is recommended by the P&M text
* but does not seem to be specified in the standard.
*/
if (cinfo->Ss == 0) {
ta = 0; /* DC scan */
if (cinfo->Ah != 0 && !cinfo->arith_code)
td = 0; /* no DC table either */
} else {
td = 0; /* AC scan */
}
}
emit_byte(cinfo, (td << 4) + ta);
}
emit_byte(cinfo, cinfo->Ss);
emit_byte(cinfo, cinfo->Se);
emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
}
LOCAL(void)
emit_jfif_app0 (j_compress_ptr cinfo)
/* Emit a JFIF-compliant APP0 marker */
{
/*
* Length of APP0 block (2 bytes)
* Block ID (4 bytes - ASCII "JFIF")
* Zero byte (1 byte to terminate the ID string)
* Version Major, Minor (2 bytes - major first)
* Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
* Xdpu (2 bytes - dots per unit horizontal)
* Ydpu (2 bytes - dots per unit vertical)
* Thumbnail X size (1 byte)
* Thumbnail Y size (1 byte)
*/
emit_marker(cinfo, M_APP0);
emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
emit_byte(cinfo, 0x46);
emit_byte(cinfo, 0x49);
emit_byte(cinfo, 0x46);
emit_byte(cinfo, 0);
emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
emit_byte(cinfo, cinfo->JFIF_minor_version);
emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
emit_2bytes(cinfo, (int) cinfo->X_density);
emit_2bytes(cinfo, (int) cinfo->Y_density);
emit_byte(cinfo, 0); /* No thumbnail image */
emit_byte(cinfo, 0);
}
LOCAL(void)
emit_adobe_app14 (j_compress_ptr cinfo)
/* Emit an Adobe APP14 marker */
{
/*
* Length of APP14 block (2 bytes)
* Block ID (5 bytes - ASCII "Adobe")
* Version Number (2 bytes - currently 100)
* Flags0 (2 bytes - currently 0)
* Flags1 (2 bytes - currently 0)
* Color transform (1 byte)
*
* Although Adobe TN 5116 mentions Version = 101, all the Adobe files
* now in circulation seem to use Version = 100, so that's what we write.
*
* We write the color transform byte as 1 if the JPEG color space is
* YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
* whether the encoder performed a transformation, which is pretty useless.
*/
emit_marker(cinfo, M_APP14);
emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
emit_byte(cinfo, 0x64);
emit_byte(cinfo, 0x6F);
emit_byte(cinfo, 0x62);
emit_byte(cinfo, 0x65);
emit_2bytes(cinfo, 100); /* Version */
emit_2bytes(cinfo, 0); /* Flags0 */
emit_2bytes(cinfo, 0); /* Flags1 */
switch (cinfo->jpeg_color_space) {
case JCS_YCbCr:
emit_byte(cinfo, 1); /* Color transform = 1 */
break;
case JCS_YCCK:
emit_byte(cinfo, 2); /* Color transform = 2 */
break;
default:
emit_byte(cinfo, 0); /* Color transform = 0 */
break;
}
}
/*
* These routines allow writing an arbitrary marker with parameters.
* The only intended use is to emit COM or APPn markers after calling
* write_file_header and before calling write_frame_header.
* Other uses are not guaranteed to produce desirable results.
* Counting the parameter bytes properly is the caller's responsibility.
*/
METHODDEF(void)
write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
/* Emit an arbitrary marker header */
{
if (datalen > (unsigned int) 65533) /* safety check */
ERREXIT(cinfo, JERR_BAD_LENGTH);
emit_marker(cinfo, (JPEG_MARKER) marker);
emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
}
METHODDEF(void)
write_marker_byte (j_compress_ptr cinfo, int val)
/* Emit one byte of marker parameters following write_marker_header */
{
emit_byte(cinfo, val);
}
/*
* Write datastream header.
* This consists of an SOI and optional APPn markers.
* We recommend use of the JFIF marker, but not the Adobe marker,
* when using YCbCr or grayscale data. The JFIF marker should NOT
* be used for any other JPEG colorspace. The Adobe marker is helpful
* to distinguish RGB, CMYK, and YCCK colorspaces.
* Note that an application can write additional header markers after
* jpeg_start_compress returns.
*/
METHODDEF(void)
write_file_header (j_compress_ptr cinfo)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
emit_marker(cinfo, M_SOI); /* first the SOI */
/* SOI is defined to reset restart interval to 0 */
marker->last_restart_interval = 0;
if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
emit_jfif_app0(cinfo);
if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
emit_adobe_app14(cinfo);
}
/*
* Write frame header.
* This consists of DQT and SOFn markers.
* Note that we do not emit the SOF until we have emitted the DQT(s).
* This avoids compatibility problems with incorrect implementations that
* try to error-check the quant table numbers as soon as they see the SOF.
*/
METHODDEF(void)
write_frame_header (j_compress_ptr cinfo)
{
int ci, prec;
boolean is_baseline;
jpeg_component_info *compptr;
/* Emit DQT for each quantization table.
* Note that emit_dqt() suppresses any duplicate tables.
*/
prec = 0;
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
prec += emit_dqt(cinfo, compptr->quant_tbl_no);
}
/* now prec is nonzero iff there are any 16-bit quant tables. */
/* Check for a non-baseline specification.
* Note we assume that Huffman table numbers won't be changed later.
*/
if (cinfo->arith_code || cinfo->progressive_mode ||
cinfo->data_precision != 8) {
is_baseline = FALSE;
} else {
is_baseline = TRUE;
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
is_baseline = FALSE;
}
if (prec && is_baseline) {
is_baseline = FALSE;
/* If it's baseline except for quantizer size, warn the user */
TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
}
}
/* Emit the proper SOF marker */
if (cinfo->arith_code) {
emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
} else {
if (cinfo->progressive_mode)
emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
else if (is_baseline)
emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
else
emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
}
}
/*
* Write scan header.
* This consists of DHT or DAC markers, optional DRI, and SOS.
* Compressed data will be written following the SOS.
*/
METHODDEF(void)
write_scan_header (j_compress_ptr cinfo)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
int i;
jpeg_component_info *compptr;
if (cinfo->arith_code) {
/* Emit arith conditioning info. We may have some duplication
* if the file has multiple scans, but it's so small it's hardly
* worth worrying about.
*/
emit_dac(cinfo);
} else {
/* Emit Huffman tables.
* Note that emit_dht() suppresses any duplicate tables.
*/
for (i = 0; i < cinfo->comps_in_scan; i++) {
compptr = cinfo->cur_comp_info[i];
if (cinfo->progressive_mode) {
/* Progressive mode: only DC or only AC tables are used in one scan */
if (cinfo->Ss == 0) {
if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
} else {
emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
}
} else {
/* Sequential mode: need both DC and AC tables */
emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
}
}
}
/* Emit DRI if required --- note that DRI value could change for each scan.
* We avoid wasting space with unnecessary DRIs, however.
*/
if (cinfo->restart_interval != marker->last_restart_interval) {
emit_dri(cinfo);
marker->last_restart_interval = cinfo->restart_interval;
}
emit_sos(cinfo);
}
/*
* Write datastream trailer.
*/
METHODDEF(void)
write_file_trailer (j_compress_ptr cinfo)
{
emit_marker(cinfo, M_EOI);
}
/*
* Write an abbreviated table-specification datastream.
* This consists of SOI, DQT and DHT tables, and EOI.
* Any table that is defined and not marked sent_table = TRUE will be
* emitted. Note that all tables will be marked sent_table = TRUE at exit.
*/
METHODDEF(void)
write_tables_only (j_compress_ptr cinfo)
{
int i;
emit_marker(cinfo, M_SOI);
for (i = 0; i < NUM_QUANT_TBLS; i++) {
if (cinfo->quant_tbl_ptrs[i] != NULL)
(void) emit_dqt(cinfo, i);
}
if (! cinfo->arith_code) {
for (i = 0; i < NUM_HUFF_TBLS; i++) {
if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
emit_dht(cinfo, i, FALSE);
if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
emit_dht(cinfo, i, TRUE);
}
}
emit_marker(cinfo, M_EOI);
}
/*
* Initialize the marker writer module.
*/
GLOBAL(void)
jinit_marker_writer (j_compress_ptr cinfo)
{
my_marker_ptr marker;
/* Create the subobject */
marker = (my_marker_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_marker_writer));
cinfo->marker = (struct jpeg_marker_writer *) marker;
/* Initialize method pointers */
marker->pub.write_file_header = write_file_header;
marker->pub.write_frame_header = write_frame_header;
marker->pub.write_scan_header = write_scan_header;
marker->pub.write_file_trailer = write_file_trailer;
marker->pub.write_tables_only = write_tables_only;
marker->pub.write_marker_header = write_marker_header;
marker->pub.write_marker_byte = write_marker_byte;
/* Initialize private state */
marker->last_restart_interval = 0;
}
| mit |
ThangBK2009/android-source-browsing.platform--external--libffi | testsuite/libffi.call/cls_19byte.c | 44 | 3034 | /* Area: ffi_call, closure_call
Purpose: Check structure passing with different structure size.
Depending on the ABI. Double alignment check on darwin.
Limitations: none.
PR: none.
Originator: <andreast@gcc.gnu.org> 20030915 */
/* { dg-do run } */
#include "ffitest.h"
typedef struct cls_struct_19byte {
double a;
unsigned char b;
unsigned char c;
double d;
unsigned char e;
} cls_struct_19byte;
cls_struct_19byte cls_struct_19byte_fn(struct cls_struct_19byte a1,
struct cls_struct_19byte a2)
{
struct cls_struct_19byte result;
result.a = a1.a + a2.a;
result.b = a1.b + a2.b;
result.c = a1.c + a2.c;
result.d = a1.d + a2.d;
result.e = a1.e + a2.e;
printf("%g %d %d %g %d %g %d %d %g %d: %g %d %d %g %d\n",
a1.a, a1.b, a1.c, a1.d, a1.e,
a2.a, a2.b, a2.c, a2.d, a2.e,
result.a, result.b, result.c, result.d, result.e);
return result;
}
static void
cls_struct_19byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata __UNUSED__)
{
struct cls_struct_19byte a1, a2;
a1 = *(struct cls_struct_19byte*)(args[0]);
a2 = *(struct cls_struct_19byte*)(args[1]);
*(cls_struct_19byte*)resp = cls_struct_19byte_fn(a1, a2);
}
int main (void)
{
ffi_cif cif;
#ifndef USING_MMAP
static ffi_closure cl;
#endif
ffi_closure *pcl;
void* args_dbl[3];
ffi_type* cls_struct_fields[6];
ffi_type cls_struct_type;
ffi_type* dbl_arg_types[3];
#ifdef USING_MMAP
pcl = allocate_mmap (sizeof(ffi_closure));
#else
pcl = &cl;
#endif
cls_struct_type.size = 0;
cls_struct_type.alignment = 0;
cls_struct_type.type = FFI_TYPE_STRUCT;
cls_struct_type.elements = cls_struct_fields;
struct cls_struct_19byte g_dbl = { 1.0, 127, 126, 3.0, 120 };
struct cls_struct_19byte f_dbl = { 4.0, 125, 124, 5.0, 119 };
struct cls_struct_19byte res_dbl;
cls_struct_fields[0] = &ffi_type_double;
cls_struct_fields[1] = &ffi_type_uchar;
cls_struct_fields[2] = &ffi_type_uchar;
cls_struct_fields[3] = &ffi_type_double;
cls_struct_fields[4] = &ffi_type_uchar;
cls_struct_fields[5] = NULL;
dbl_arg_types[0] = &cls_struct_type;
dbl_arg_types[1] = &cls_struct_type;
dbl_arg_types[2] = NULL;
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
dbl_arg_types) == FFI_OK);
args_dbl[0] = &g_dbl;
args_dbl[1] = &f_dbl;
args_dbl[2] = NULL;
ffi_call(&cif, FFI_FN(cls_struct_19byte_fn), &res_dbl, args_dbl);
/* { dg-output "1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */
printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
res_dbl.d, res_dbl.e);
/* { dg-output "\nres: 5 252 250 8 239" } */
CHECK(ffi_prep_closure(pcl, &cif, cls_struct_19byte_gn, NULL) == FFI_OK);
res_dbl = ((cls_struct_19byte(*)(cls_struct_19byte, cls_struct_19byte))(pcl))(g_dbl, f_dbl);
/* { dg-output "\n1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */
printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
res_dbl.d, res_dbl.e);
/* { dg-output "\nres: 5 252 250 8 239" } */
exit(0);
}
| mit |
ShowingCloud/Alniyat | plugins/com.phonegap.plugins.barcodescanner/src/ios/ZXingWidgetLibrary/ZXingWidgetLibrary/core/zxing/ResultIO.cpp | 45 | 1053 | // -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
* ResultIO.cpp
* zxing
*
* Created by Christian Brunschen on 13/05/2008.
* Copyright 2008 ZXing authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <zxing/Result.h>
using zxing::Result;
using std::ostream;
ostream& zxing::operator<<(ostream &out, Result& result) {
if (result.text_ != 0) {
out << result.text_->getText();
} else {
out << "[" << result.rawBytes_->size() << " bytes]";
}
return out;
}
| mit |
spoiledsport/coreclr | src/md/winmd/winmdimport.cpp | 54 | 93701 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "stdafx.h"
#include "winmdinterfaces.h"
#include "metadataexports.h"
#include "inc/adapter.h"
#include "strsafe.h"
//========================================================================================
// This metadata importer is exposed publically via CoCreateInstance(CLSID_CorMetaDataDispenser...).
// when the target is a .winmd file. It applies a small number of on-the-fly
// conversions to make the .winmd file look like a regular .NET assembly.
//
// Despite what the MSDN docs say, this importer only supports the reader interfaces and
// a subset of them at that. Supporting the whole set would not be practical with an
// on-the-fly translation strategy.
//========================================================================================
class WinMDImport : public IMetaDataImport2
, IMetaDataAssemblyImport
, IMetaDataWinMDImport
, IMetaDataValidate
, IMDCommon
, IMetaModelCommon
, IWinMDImport
#ifdef FEATURE_METADATA_INTERNAL_APIS
, IGetIMDInternalImport
#endif //FEATURE_METADATA_INTERNAL_APIS
{
public:
//=========================================================
// Factory
//=========================================================
static HRESULT Create(IMDCommon *pRawMDCommon, WinMDImport **ppWinMDImport)
{
HRESULT hr;
*ppWinMDImport = NULL;
WinMDImport *pNewWinMDImport = new (nothrow) WinMDImport(pRawMDCommon);
IfFailGo(pNewWinMDImport->m_pRawMDCommon->QueryInterface(IID_IMetaDataImport2, (void**)&pNewWinMDImport->m_pRawImport));
IfFailGo(pNewWinMDImport->m_pRawImport->QueryInterface(IID_IMetaDataAssemblyImport, (void**)&pNewWinMDImport->m_pRawAssemblyImport));
if (FAILED(pNewWinMDImport->m_pRawImport->QueryInterface(IID_IMetaDataValidate, (void**)&pNewWinMDImport->m_pRawValidate)))
{
pNewWinMDImport->m_pRawValidate = nullptr;
}
pNewWinMDImport->m_pRawMetaModelCommonRO = pRawMDCommon->GetMetaModelCommonRO();
IfFailGo(WinMDAdapter::Create(pRawMDCommon, &pNewWinMDImport->m_pWinMDAdapter));
(*ppWinMDImport = pNewWinMDImport)->AddRef();
hr = S_OK;
ErrExit:
if (pNewWinMDImport)
pNewWinMDImport->Release();
return hr;
}
private:
//=========================================================
// Ctors, Dtors
//=========================================================
WinMDImport(IMDCommon * pRawMDCommon)
{
m_cRef = 1;
m_pRawImport = NULL;
m_pWinMDAdapter = NULL;
m_pRawAssemblyImport = NULL;
m_pFreeThreadedMarshaler = NULL;
(m_pRawMDCommon = pRawMDCommon)->AddRef();
}
//---------------------------------------------------------
~WinMDImport()
{
if (m_pRawMDCommon)
m_pRawMDCommon->Release();
if (m_pRawImport)
m_pRawImport->Release();
if (m_pRawAssemblyImport)
m_pRawAssemblyImport->Release();
if (m_pRawValidate)
m_pRawValidate->Release();
if (m_pFreeThreadedMarshaler)
m_pFreeThreadedMarshaler->Release();
delete m_pWinMDAdapter;
}
//---------------------------------------------------------
BOOL IsValidNonNilToken(mdToken token, DWORD tkKind)
{
DWORD tkKindActual = TypeFromToken(token);
DWORD rid = RidFromToken(token);
if (tkKindActual != tkKind)
return FALSE;
if (rid == 0)
return FALSE;
ULONG ulRowCount = m_pRawMetaModelCommonRO->CommonGetRowCount(tkKind);
if (tkKind == mdtAssemblyRef)
return rid <= ulRowCount + m_pWinMDAdapter->GetExtraAssemblyRefCount();
else
return rid <= ulRowCount;
}
public:
//=========================================================
// IUnknown methods
//=========================================================
STDMETHODIMP QueryInterface(REFIID riid, void** ppUnk)
{
HRESULT hr;
*ppUnk = 0;
if (riid == IID_IUnknown || riid == IID_IWinMDImport)
*ppUnk = (IWinMDImport*)this;
else if (riid == IID_IMetaDataImport || riid == IID_IMetaDataImport2)
*ppUnk = (IMetaDataImport*)this;
else if (riid == IID_IMetaDataWinMDImport)
*ppUnk = (IMetaDataWinMDImport*)this;
else if (riid == IID_IMetaDataAssemblyImport)
*ppUnk = (IMetaDataAssemblyImport*)this;
else if (riid == IID_IMDCommon)
*ppUnk = (IMDCommon*)this;
else if (riid == IID_IMetaDataValidate)
{
if (m_pRawValidate == NULL)
{
return E_NOINTERFACE;
}
*ppUnk = (IMetaDataValidate*)this;
}
#ifdef FEATURE_METADATA_INTERNAL_APIS
else if (riid == IID_IGetIMDInternalImport)
*ppUnk = (IGetIMDInternalImport*)this;
#endif // FEATURE_METADATA_INTERNAL_APIS
else if (riid == IID_IMarshal)
{
if (m_pFreeThreadedMarshaler == NULL)
{
ReleaseHolder<IUnknown> pFreeThreadedMarshaler = NULL;
IfFailRet(CoCreateFreeThreadedMarshaler((IUnknown *)(IMetaDataImport *)this, &pFreeThreadedMarshaler));
if (InterlockedCompareExchangeT<IUnknown *>(&m_pFreeThreadedMarshaler, pFreeThreadedMarshaler, NULL) == NULL)
{ // We won the initialization race
pFreeThreadedMarshaler.SuppressRelease();
}
}
return m_pFreeThreadedMarshaler->QueryInterface(riid, ppUnk);
}
else
{
#ifndef DACCESS_COMPILE
#ifdef _DEBUG
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_WinMD_AssertOnIllegalUsage))
{
if (riid == IID_IMetaDataTables)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataTables) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataTables2)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataTables2) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataInfo)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataInfo) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataEmit)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataEmit) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataEmit2)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataEmit2) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataAssemblyEmit)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataAssemblyEmit) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataValidate)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataValidate) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataFilter)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataFilter) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataHelper)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataHelper) returning E_NOINTERFACE");
else if (riid == IID_IMDInternalEmit)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMDInternalEmit) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataEmitHelper)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataEmitHelper) returning E_NOINTERFACE");
else if (riid == IID_IMetaDataCorProfileData)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataCorProfileData) returning E_NOINTERFACE");
else if (riid == IID_IMDInternalMetadataReorderingOptions)
_ASSERTE(!"WinMDImport::QueryInterface(IID_IMDInternalMetadataReorderingOptions) returning E_NOINTERFACE");
else
_ASSERTE(!"WinMDImport::QueryInterface() returning E_NOINTERFACE");
}
#endif //_DEBUG
#endif
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
//---------------------------------------------------------
STDMETHODIMP_(ULONG) AddRef(void)
{
return InterlockedIncrement(&m_cRef);
}
//---------------------------------------------------------
STDMETHODIMP_(ULONG) Release(void)
{
ULONG cRef = InterlockedDecrement(&m_cRef);
if (!cRef)
delete this;
return cRef;
}
public:
//=========================================================
// IWinMDImport methods
//=========================================================
STDMETHODIMP IsScenarioWinMDExp(BOOL *pbResult)
{
if (pbResult == NULL)
return E_POINTER;
*pbResult = m_pWinMDAdapter->IsScenarioWinMDExp();
return S_OK;
}
STDMETHODIMP IsRuntimeClassImplementation(mdTypeDef tkTypeDef, BOOL *pbResult)
{
if (pbResult == NULL)
return E_POINTER;
return m_pWinMDAdapter->IsRuntimeClassImplementation(tkTypeDef, pbResult);
}
//=========================================================
// IMetaDataImport methods
//=========================================================
STDMETHODIMP_(void) CloseEnum(HCORENUM hEnum)
{
m_pRawImport->CloseEnum(hEnum);
}
STDMETHODIMP CountEnum(HCORENUM hEnum, ULONG *pulCount)
{
_ASSERTE(pulCount != NULL); // Crash on NULL pulCount (just like real RegMeta)
if (hEnum != NULL)
{
HENUMInternal *henuminternal = static_cast<HENUMInternal*>(hEnum);
// Special case: We hijack MethodImpl enum's
if (henuminternal->m_tkKind == (TBL_MethodImpl << 24))
{
*pulCount = henuminternal->m_ulCount / 2; // MethodImpl enum's are weird - their entries are body/decl pairs so the internal count is twice the number the caller wants to see.
return S_OK;
}
}
return m_pRawImport->CountEnum(hEnum, pulCount);
}
STDMETHODIMP ResetEnum(HCORENUM hEnum, ULONG ulPos)
{
return m_pRawImport->ResetEnum(hEnum, ulPos);
}
STDMETHODIMP EnumTypeDefs(HCORENUM *phEnum, mdTypeDef rTypeDefs[],
ULONG cMax, ULONG *pcTypeDefs)
{
return m_pRawImport->EnumTypeDefs(phEnum, rTypeDefs, cMax, pcTypeDefs);
}
STDMETHODIMP EnumInterfaceImpls(HCORENUM *phEnum, mdTypeDef td,
mdInterfaceImpl rImpls[], ULONG cMax,
ULONG* pcImpls)
{
return m_pRawImport->EnumInterfaceImpls(phEnum, td, rImpls, cMax, pcImpls);
}
STDMETHODIMP EnumTypeRefs(HCORENUM *phEnum, mdTypeRef rTypeRefs[],
ULONG cMax, ULONG* pcTypeRefs)
{
// No trick needed: a previous call to EnumTypeRefs must have already taken care of the
// extra type refs.
return m_pRawImport->EnumTypeRefs(phEnum, rTypeRefs, cMax, pcTypeRefs);
}
STDMETHODIMP FindTypeDefByName( // S_OK or error.
LPCWSTR wszTypeDef, // [IN] Name of the Type.
mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef for Enclosing class.
mdTypeDef *ptd) // [OUT] Put the TypeDef token here.
{
if (wszTypeDef == NULL) // E_INVALIDARG on NULL szTypeDef (just like real RegMeta)
return E_INVALIDARG;
_ASSERTE(ptd != NULL); // AV on NULL ptd (just like real RegMeta)
*ptd = mdTypeDefNil;
LPUTF8 szFullName;
LPCUTF8 szNamespace;
LPCUTF8 szName;
// Convert the name to UTF8.
UTF8STR(wszTypeDef, szFullName);
ns::SplitInline(szFullName, szNamespace, szName);
return m_pWinMDAdapter->FindTypeDef(szNamespace, szName, tkEnclosingClass, ptd);
}
STDMETHODIMP GetScopeProps( // S_OK or error.
__out_ecount_part_opt(cchName, *pchName)
LPWSTR szName, // [OUT] Put the name here.
ULONG cchName, // [IN] Size of name buffer in wide chars.
ULONG *pchName, // [OUT] Put size of name (wide chars) here.
GUID *pmvid) // [OUT, OPTIONAL] Put MVID here.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetScopeProps(szName, cchName, pchName, pmvid);
}
STDMETHODIMP GetModuleFromScope( // S_OK.
mdModule *pmd) // [OUT] Put mdModule token here.
{
return m_pRawImport->GetModuleFromScope(pmd);
}
STDMETHODIMP GetTypeDefProps( // S_OK or error.
mdTypeDef td, // [IN] TypeDef token for inquiry.
__out_ecount_part_opt(cchTypeDef, *pchTypeDef)
LPWSTR szTypeDef, // [OUT] Put name here.
ULONG cchTypeDef, // [IN] size of name buffer in wide chars.
ULONG *pchTypeDef, // [OUT] put size of name (wide chars) here.
DWORD *pdwTypeDefFlags, // [OUT] Put flags here.
mdToken *ptkExtends) // [OUT] Put base class TypeDef/TypeRef here.
{
HRESULT hr;
LPCSTR szNamespace;
LPCSTR szName;
if (!IsValidNonNilToken(td, mdtTypeDef))
{
// Idiosyncractic edge cases - delegate straight through to inherit the correct idiosyncractic edge results
return m_pRawImport->GetTypeDefProps(td, szTypeDef, cchTypeDef, pchTypeDef, pdwTypeDefFlags, ptkExtends);
}
IfFailRet(m_pWinMDAdapter->GetTypeDefProps(td, &szNamespace, &szName, pdwTypeDefFlags, ptkExtends));
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return DeliverUtf8NamespaceAndName(szNamespace, szName, szTypeDef, cchTypeDef, pchTypeDef);
}
STDMETHODIMP GetInterfaceImplProps( // S_OK or error.
mdInterfaceImpl iiImpl, // [IN] InterfaceImpl token.
mdTypeDef *pClass, // [OUT] Put implementing class token here.
mdToken *ptkIface) // [OUT] Put implemented interface token here.
{
return m_pRawImport->GetInterfaceImplProps(iiImpl, pClass, ptkIface);
}
STDMETHODIMP GetTypeRefProps( // S_OK or error.
mdTypeRef tr, // [IN] TypeRef token.
mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef.
__out_ecount_part_opt(cchName, *pchName)
LPWSTR szName, // [OUT] Name of the TypeRef.
ULONG cchName, // [IN] Size of buffer.
ULONG *pchName) // [OUT] Size of Name.
{
HRESULT hr;
if (!IsValidNonNilToken(tr, mdtTypeRef))
{
// Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result
return m_pRawImport->GetTypeRefProps(tr, ptkResolutionScope, szName, cchName, pchName);
}
LPCUTF8 szUtf8Namespace;
LPCUTF8 szUtf8Name;
mdToken tkResolutionScope;
IfFailRet(CommonGetTypeRefProps(tr, &szUtf8Namespace, &szUtf8Name, &tkResolutionScope));
if (ptkResolutionScope != NULL)
{
*ptkResolutionScope = tkResolutionScope;
}
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return DeliverUtf8NamespaceAndName(szUtf8Namespace, szUtf8Name, szName, cchName, pchName);
}
STDMETHODIMP ResolveTypeRef(mdTypeRef tr, REFIID riid, IUnknown **ppIScope, mdTypeDef *ptd)
{
WINMD_COMPAT_ASSERT("IMetaDataImport::ResolveTypeRef() not supported on .winmd files.");
return E_NOTIMPL;
}
STDMETHODIMP EnumMembers( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef cl, // [IN] TypeDef to scope the enumeration.
mdToken rMembers[], // [OUT] Put MemberDefs here.
ULONG cMax, // [IN] Max MemberDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumMembers(phEnum, cl, rMembers, cMax, pcTokens);
}
STDMETHODIMP EnumMembersWithName( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef cl, // [IN] TypeDef to scope the enumeration.
LPCWSTR szName, // [IN] Limit results to those with this name.
mdToken rMembers[], // [OUT] Put MemberDefs here.
ULONG cMax, // [IN] Max MemberDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumMembersWithName(phEnum, cl, szName, rMembers, cMax, pcTokens);
}
STDMETHODIMP EnumMethods( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef cl, // [IN] TypeDef to scope the enumeration.
mdMethodDef rMethods[], // [OUT] Put MethodDefs here.
ULONG cMax, // [IN] Max MethodDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumMethods(phEnum, cl, rMethods, cMax, pcTokens);
}
STDMETHODIMP EnumMethodsWithName( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef cl, // [IN] TypeDef to scope the enumeration.
LPCWSTR szName, // [IN] Limit results to those with this name.
mdMethodDef rMethods[], // [OU] Put MethodDefs here.
ULONG cMax, // [IN] Max MethodDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumMethodsWithName(phEnum, cl, szName, rMethods, cMax, pcTokens);
}
STDMETHODIMP EnumFields( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef cl, // [IN] TypeDef to scope the enumeration.
mdFieldDef rFields[], // [OUT] Put FieldDefs here.
ULONG cMax, // [IN] Max FieldDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumFields(phEnum, cl, rFields, cMax, pcTokens);
}
STDMETHODIMP EnumFieldsWithName( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef cl, // [IN] TypeDef to scope the enumeration.
LPCWSTR szName, // [IN] Limit results to those with this name.
mdFieldDef rFields[], // [OUT] Put MemberDefs here.
ULONG cMax, // [IN] Max MemberDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumFieldsWithName(phEnum, cl, szName, rFields, cMax, pcTokens);
}
STDMETHODIMP EnumParams( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdMethodDef mb, // [IN] MethodDef to scope the enumeration.
mdParamDef rParams[], // [OUT] Put ParamDefs here.
ULONG cMax, // [IN] Max ParamDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumParams(phEnum, mb, rParams, cMax, pcTokens);
}
STDMETHODIMP EnumMemberRefs( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdToken tkParent, // [IN] Parent token to scope the enumeration.
mdMemberRef rMemberRefs[], // [OUT] Put MemberRefs here.
ULONG cMax, // [IN] Max MemberRefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumMemberRefs(phEnum, tkParent, rMemberRefs, cMax, pcTokens);
}
STDMETHODIMP EnumMethodImpls( // S_OK, S_FALSE, or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef td, // [IN] TypeDef to scope the enumeration.
mdToken rMethodBody[], // [OUT] Put Method Body tokens here.
mdToken rMethodDecl[], // [OUT] Put Method Declaration tokens here.
ULONG cMax, // [IN] Max tokens to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
// Note: This wrapper emulates the underlying RegMeta's parameter validation semantics:
// Pass a bad phEnum: Instant AV
// Pass out of range typedef: returns S_FALSE (i.e. generates empty list)
// Pass non-typedef: returns S_FALSE with assert
// Pass bad output ptr for bodies or decls, AV
// Pass bad output ptr for pcTokens, AV (but NULL is allowed.)
HRESULT hr;
HENUMInternal **ppmdEnum = reinterpret_cast<HENUMInternal **> (phEnum);
HENUMInternal *pEnum = *ppmdEnum;
if ( pEnum == 0 )
{
// Create the enumerator, DynamicArrayEnum does not use the token type.
IfFailGo( HENUMInternal::CreateDynamicArrayEnum( (TBL_MethodImpl << 24), &pEnum) );
IfFailGo( m_pWinMDAdapter->AddMethodImplsToEnum(td, pEnum));
// set the output parameter
*ppmdEnum = pEnum;
}
// fill the output token buffer
hr = HENUMInternal::EnumWithCount(pEnum, cMax, rMethodBody, rMethodDecl, pcTokens);
ErrExit:
HENUMInternal::DestroyEnumIfEmpty(ppmdEnum);
return hr;
}
STDMETHODIMP EnumPermissionSets( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdToken tk, // [IN] if !NIL, token to scope the enumeration.
DWORD dwActions, // [IN] if !0, return only these actions.
mdPermission rPermission[], // [OUT] Put Permissions here.
ULONG cMax, // [IN] Max Permissions to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumPermissionSets(phEnum, tk, dwActions, rPermission, cMax, pcTokens);
}
STDMETHODIMP FindMember(
mdTypeDef td, // [IN] given typedef
LPCWSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
mdToken *pmb) // [OUT] matching memberdef
{
HRESULT hr = FindMethod(
td,
szName,
pvSigBlob,
cbSigBlob,
pmb);
if (hr == CLDB_E_RECORD_NOTFOUND)
{
// now try field table
hr = FindField(
td,
szName,
pvSigBlob,
cbSigBlob,
pmb);
}
return hr;
}
STDMETHODIMP FindMethod(
mdTypeDef td, // [IN] given typedef
LPCWSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
mdMethodDef *pmb) // [OUT] matching memberdef
{
if (pvSigBlob == NULL || cbSigBlob == 0)
{
// if signature matching is not needed, we can delegate to the underlying implementation
return m_pRawImport->FindMethod(td, szName, pvSigBlob, cbSigBlob, pmb);
}
// The following code emulates RegMeta::FindMethod. We cannot call the underlying
// implementation because we need to compare pvSigBlob to reinterpreted signatures.
HRESULT hr = S_OK;
HCORENUM hEnum = NULL;
CQuickBytes qbSig; // holds non-varargs signature
CQuickArray<WCHAR> rName;
if (szName == NULL || pmb == NULL)
IfFailGo(E_INVALIDARG);
*pmb = mdMethodDefNil;
// check to see if this is a vararg signature
PCCOR_SIGNATURE pvSigTemp = pvSigBlob;
if (isCallConv(CorSigUncompressCallingConv(pvSigTemp), IMAGE_CEE_CS_CALLCONV_VARARG))
{
// Get the fixed part of VARARG signature
IfFailGo(_GetFixedSigOfVarArg(pvSigBlob, cbSigBlob, &qbSig, &cbSigBlob));
pvSigBlob = (PCCOR_SIGNATURE) qbSig.Ptr();
}
// now iterate all methods in td and compare name and signature
IfNullGo(rName.AllocNoThrow(wcslen(szName) + 1));
mdMethodDef md;
ULONG count;
while ((hr = EnumMethods(&hEnum, td, &md, 1, &count)) == S_OK)
{
PCCOR_SIGNATURE pvMethodSigBlob;
ULONG cbMethodSigBlob;
ULONG chMethodName;
DWORD dwMethodAttr;
IfFailGo(GetMethodProps(md, NULL, rName.Ptr(), (ULONG)rName.Size(), &chMethodName, &dwMethodAttr, &pvMethodSigBlob, &cbMethodSigBlob, NULL, NULL));
if (chMethodName == rName.Size() && wcscmp(szName, rName.Ptr()) == 0)
{
// we have a name match, check signature
if (cbSigBlob != cbMethodSigBlob || memcmp(pvSigBlob, pvMethodSigBlob, cbSigBlob) != 0)
continue;
// ignore PrivateScope methods
if (IsMdPrivateScope(dwMethodAttr))
continue;
// we found the method
*pmb = md;
goto ErrExit;
}
}
IfFailGo(hr);
hr = CLDB_E_RECORD_NOTFOUND;
ErrExit:
if (hEnum != NULL)
CloseEnum(hEnum);
return hr;
}
STDMETHODIMP FindField(
mdTypeDef td, // [IN] given typedef
LPCWSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
mdFieldDef *pmb) // [OUT] matching memberdef
{
if (pvSigBlob == NULL || cbSigBlob == 0)
{
// if signature matching is not needed, we can delegate to the underlying implementation
return m_pRawImport->FindField(td, szName, pvSigBlob, cbSigBlob, pmb);
}
// The following code emulates RegMeta::FindField. We cannot call the underlying
// implementation because we need to compare pvSigBlob to reinterpreted signatures.
HRESULT hr = S_OK;
HCORENUM hEnum = NULL;
CQuickArray<WCHAR> rName;
if (szName == NULL || pmb == NULL)
IfFailGo(E_INVALIDARG);
*pmb = mdFieldDefNil;
// now iterate all fields in td and compare name and signature
IfNullGo(rName.AllocNoThrow(wcslen(szName) + 1));
mdFieldDef fd;
ULONG count;
while ((hr = EnumFields(&hEnum, td, &fd, 1, &count)) == S_OK)
{
PCCOR_SIGNATURE pvFieldSigBlob;
ULONG cbFieldSigBlob;
ULONG chFieldName;
DWORD dwFieldAttr;
IfFailGo(GetFieldProps(fd, NULL, rName.Ptr(), (ULONG)rName.Size(), &chFieldName, &dwFieldAttr, &pvFieldSigBlob, &cbFieldSigBlob, NULL, NULL, NULL));
if (chFieldName == rName.Size() && wcscmp(szName, rName.Ptr()) == 0)
{
// we have a name match, check signature
if (cbSigBlob != cbFieldSigBlob || memcmp(pvSigBlob, pvFieldSigBlob, cbSigBlob) != 0)
continue;
// ignore PrivateScope fields
if (IsFdPrivateScope(dwFieldAttr))
continue;
// we found the field
*pmb = fd;
goto ErrExit;
}
}
IfFailGo(hr);
hr = CLDB_E_RECORD_NOTFOUND;
ErrExit:
if (hEnum != NULL)
CloseEnum(hEnum);
return hr;
}
STDMETHODIMP FindMemberRef(
mdTypeRef td, // [IN] given typeRef
LPCWSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
mdMemberRef *pmr) // [OUT] matching memberref
{
if (pvSigBlob == NULL || cbSigBlob == 0)
{
// if signature matching is not needed, we can delegate to the underlying implementation
return m_pRawImport->FindMemberRef(td, szName, pvSigBlob, cbSigBlob, pmr);
}
// The following code emulates RegMeta::FindMemberRef. We cannot call the underlying
// implementation because we need to compare pvSigBlob to reinterpreted signatures.
HRESULT hr = S_OK;
HCORENUM hEnum = NULL;
CQuickArray<WCHAR> rName;
if (szName == NULL || pmr == NULL)
IfFailGo(CLDB_E_RECORD_NOTFOUND);
*pmr = mdMemberRefNil;
// now iterate all members in td and compare name and signature
IfNullGo(rName.AllocNoThrow(wcslen(szName) + 1));
mdMemberRef rd;
ULONG count;
while ((hr = EnumMemberRefs(&hEnum, td, &rd, 1, &count)) == S_OK)
{
PCCOR_SIGNATURE pvMemberSigBlob;
ULONG cbMemberSigBlob;
ULONG chMemberName;
IfFailGo(GetMemberRefProps(rd, NULL, rName.Ptr(), (ULONG)rName.Size(), &chMemberName, &pvMemberSigBlob, &cbMemberSigBlob));
if (chMemberName == rName.Size() && wcscmp(szName, rName.Ptr()) == 0)
{
// we have a name match, check signature
if (cbSigBlob != cbMemberSigBlob || memcmp(pvSigBlob, pvMemberSigBlob, cbSigBlob) != 0)
continue;
// we found the member
*pmr = rd;
goto ErrExit;
}
}
IfFailGo(hr);
hr = CLDB_E_RECORD_NOTFOUND;
ErrExit:
if (hEnum != NULL)
CloseEnum(hEnum);
return hr;
}
STDMETHODIMP GetMethodProps(
mdMethodDef mb, // The method for which to get props.
mdTypeDef *pClass, // Put method's class here.
__out_ecount_part_opt(cchMethod, *pchMethod)
LPWSTR szMethod, // Put method's name here.
ULONG cchMethod, // Size of szMethod buffer in wide chars.
ULONG *pchMethod, // Put actual size here
DWORD *pdwAttr, // Put flags here.
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data
ULONG *pcbSigBlob, // [OUT] actual size of signature blob
ULONG *pulCodeRVA, // [OUT] codeRVA
DWORD *pdwImplFlags) // [OUT] Impl. Flags
{
HRESULT hr;
HRESULT hrNameTruncation;
if (!IsValidNonNilToken(mb, mdtMethodDef))
{
// Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result
return m_pRawImport->GetMethodProps(mb, pClass, szMethod, cchMethod, pchMethod, pdwAttr, ppvSigBlob, pcbSigBlob, pulCodeRVA, pdwImplFlags);
}
ULONG cbOrigSigBlob = (ULONG)(-1);
PCCOR_SIGNATURE pOrigSig = NULL;
IfFailRet(hrNameTruncation = m_pRawImport->GetMethodProps(mb, pClass, szMethod, cchMethod, pchMethod, pdwAttr, &pOrigSig, &cbOrigSigBlob, pulCodeRVA, pdwImplFlags));
IfFailRet((m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtMethodDef>(
mb,
&pOrigSig, // ppOrigSig
&cbOrigSigBlob, // pcbOrigSig
ppvSigBlob,
pcbSigBlob,
m_pRawImport)));
LPCSTR szNewName = NULL;
IfFailRet(m_pWinMDAdapter->ModifyMethodProps(mb, pdwAttr, pdwImplFlags, pulCodeRVA, &szNewName));
if (szNewName != NULL)
{
// We want to return name truncation status from the method that really fills the output buffer, rewrite the previous value
IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szMethod, cchMethod, pchMethod));
}
// Return the success code from name filling (S_OK or CLDB_S_TRUNCATION)
return hrNameTruncation;
}
STDMETHODIMP GetMemberRefProps( // S_OK or error.
mdMemberRef mr, // [IN] given memberref
mdToken *ptk, // [OUT] Put classref or classdef here.
__out_ecount_part_opt(cchMember, *pchMember)
LPWSTR szMember, // [OUT] buffer to fill for member's name
ULONG cchMember, // [IN] the count of char of szMember
ULONG *pchMember, // [OUT] actual count of char in member name
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to meta data blob value
ULONG *pbSig) // [OUT] actual size of signature blob
{
HRESULT hr = S_OK;
HRESULT hrNameTruncation;
ULONG cbOrigSigBlob = (ULONG)(-1);
PCCOR_SIGNATURE pOrigSig = NULL;
IfFailRet(hrNameTruncation = m_pRawImport->GetMemberRefProps(mr, ptk, szMember, cchMember, pchMember, &pOrigSig, &cbOrigSigBlob));
LPCSTR szNewName = NULL;
IfFailRet(m_pWinMDAdapter->ModifyMemberProps(mr, NULL, NULL, NULL, &szNewName));
IfFailRet((m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtMemberRef>(
mr,
&pOrigSig, // ppOrigSig
&cbOrigSigBlob, // pcbOrigSig
ppvSigBlob,
pbSig,
m_pRawImport)));
if (szNewName != NULL)
{
// We want to return name truncation status from the method that really fills the output buffer, rewrite the previous value
IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szMember, cchMember, pchMember));
}
// Return the success code from name filling (S_OK or CLDB_S_TRUNCATION)
return hrNameTruncation;
}
STDMETHODIMP EnumProperties( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef td, // [IN] TypeDef to scope the enumeration.
mdProperty rProperties[], // [OUT] Put Properties here.
ULONG cMax, // [IN] Max properties to put.
ULONG *pcProperties) // [OUT] Put # put here.
{
return m_pRawImport->EnumProperties(phEnum, td, rProperties, cMax, pcProperties);
}
STDMETHODIMP EnumEvents( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdTypeDef td, // [IN] TypeDef to scope the enumeration.
mdEvent rEvents[], // [OUT] Put events here.
ULONG cMax, // [IN] Max events to put.
ULONG *pcEvents) // [OUT] Put # put here.
{
return m_pRawImport->EnumEvents(phEnum, td, rEvents, cMax, pcEvents);
}
STDMETHODIMP GetEventProps( // S_OK, S_FALSE, or error.
mdEvent ev, // [IN] event token
mdTypeDef *pClass, // [OUT] typedef containing the event declarion.
LPCWSTR szEvent, // [OUT] Event name
ULONG cchEvent, // [IN] the count of wchar of szEvent
ULONG *pchEvent, // [OUT] actual count of wchar for event's name
DWORD *pdwEventFlags, // [OUT] Event flags.
mdToken *ptkEventType, // [OUT] EventType class
mdMethodDef *pmdAddOn, // [OUT] AddOn method of the event
mdMethodDef *pmdRemoveOn, // [OUT] RemoveOn method of the event
mdMethodDef *pmdFire, // [OUT] Fire method of the event
mdMethodDef rmdOtherMethod[], // [OUT] other method of the event
ULONG cMax, // [IN] size of rmdOtherMethod
ULONG *pcOtherMethod) // [OUT] total number of other method of this event
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetEventProps(ev, pClass, szEvent, cchEvent, pchEvent, pdwEventFlags, ptkEventType, pmdAddOn, pmdRemoveOn, pmdFire, rmdOtherMethod, cMax, pcOtherMethod);
}
STDMETHODIMP EnumMethodSemantics( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdMethodDef mb, // [IN] MethodDef to scope the enumeration.
mdToken rEventProp[], // [OUT] Put Event/Property here.
ULONG cMax, // [IN] Max properties to put.
ULONG *pcEventProp) // [OUT] Put # put here.
{
return m_pRawImport->EnumMethodSemantics(phEnum, mb, rEventProp, cMax, pcEventProp);
}
STDMETHODIMP GetMethodSemantics( // S_OK, S_FALSE, or error.
mdMethodDef mb, // [IN] method token
mdToken tkEventProp, // [IN] event/property token.
DWORD *pdwSemanticsFlags) // [OUT] the role flags for the method/propevent pair
{
return m_pRawImport->GetMethodSemantics(mb, tkEventProp, pdwSemanticsFlags);
}
STDMETHODIMP GetClassLayout(
mdTypeDef td, // [IN] give typedef
DWORD *pdwPackSize, // [OUT] 1, 2, 4, 8, or 16
COR_FIELD_OFFSET rFieldOffset[], // [OUT] field offset array
ULONG cMax, // [IN] size of the array
ULONG *pcFieldOffset, // [OUT] needed array size
ULONG *pulClassSize) // [OUT] the size of the class
{
return m_pRawImport->GetClassLayout(td, pdwPackSize, rFieldOffset, cMax, pcFieldOffset, pulClassSize);
}
STDMETHODIMP GetFieldMarshal(
mdToken tk, // [IN] given a field's memberdef
PCCOR_SIGNATURE *ppvNativeType, // [OUT] native type of this field
ULONG *pcbNativeType) // [OUT] the count of bytes of *ppvNativeType
{
return m_pRawImport->GetFieldMarshal(tk, ppvNativeType, pcbNativeType);
}
STDMETHODIMP GetRVA( // S_OK or error.
mdToken tk, // Member for which to set offset
ULONG *pulCodeRVA, // The offset
DWORD *pdwImplFlags) // the implementation flags
{
HRESULT hr;
if (!IsValidNonNilToken(tk, mdtMethodDef))
{
// Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result
return m_pRawImport->GetRVA(tk, pulCodeRVA, pdwImplFlags);
}
IfFailRet(m_pRawImport->GetRVA(tk, pulCodeRVA, pdwImplFlags));
IfFailRet(m_pWinMDAdapter->ModifyMethodProps(tk, NULL, pdwImplFlags, pulCodeRVA, NULL));
return hr;
}
STDMETHODIMP GetPermissionSetProps(
mdPermission pm, // [IN] the permission token.
DWORD *pdwAction, // [OUT] CorDeclSecurity.
void const **ppvPermission, // [OUT] permission blob.
ULONG *pcbPermission) // [OUT] count of bytes of pvPermission.
{
return m_pRawImport->GetPermissionSetProps(pm, pdwAction, ppvPermission, pcbPermission);
}
STDMETHODIMP GetSigFromToken( // S_OK or error.
mdSignature mdSig, // [IN] Signature token.
PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token.
ULONG *pcbSig) // [OUT] return size of signature.
{
// mdSignature is not part of public WinMD surface, so it does not need signature rewriting
return m_pRawImport->GetSigFromToken(mdSig, ppvSig, pcbSig);
}
STDMETHODIMP GetModuleRefProps( // S_OK or error.
mdModuleRef mur, // [IN] moduleref token.
__out_ecount_part_opt(cchName, *pchName)
LPWSTR szName, // [OUT] buffer to fill with the moduleref name.
ULONG cchName, // [IN] size of szName in wide characters.
ULONG *pchName) // [OUT] actual count of characters in the name.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetModuleRefProps(mur, szName, cchName, pchName);
}
STDMETHODIMP EnumModuleRefs( // S_OK or error.
HCORENUM *phEnum, // [IN|OUT] pointer to the enum.
mdModuleRef rModuleRefs[], // [OUT] put modulerefs here.
ULONG cmax, // [IN] max memberrefs to put.
ULONG *pcModuleRefs) // [OUT] put # put here.
{
return m_pRawImport->EnumModuleRefs(phEnum, rModuleRefs, cmax, pcModuleRefs);
}
STDMETHODIMP GetTypeSpecFromToken( // S_OK or error.
mdTypeSpec typespec, // [IN] TypeSpec token.
PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to TypeSpec signature
ULONG *pcbSig) // [OUT] return size of signature.
{
return m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtTypeSpec>(
typespec,
NULL, // ppOrigSig
NULL, // pcbOrigSig
ppvSig,
pcbSig,
m_pRawImport);
}
STDMETHODIMP GetNameFromToken( // Not Recommended! May be removed!
mdToken tk, // [IN] Token to get name from. Must have a name.
MDUTF8CSTR *pszUtf8NamePtr) // [OUT] Return pointer to UTF8 name in heap.
{
HRESULT hr;
if (!IsValidNonNilToken(tk, mdtTypeRef))
{
// Handle corner error case
IfFailGo(m_pRawImport->GetNameFromToken(tk, pszUtf8NamePtr));
}
else
{
IfFailGo(m_pWinMDAdapter->GetTypeRefProps(tk, NULL, pszUtf8NamePtr, NULL));
}
ErrExit:
return hr;
}
STDMETHODIMP EnumUnresolvedMethods( // S_OK, S_FALSE, or error.
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdToken rMethods[], // [OUT] Put MemberDefs here.
ULONG cMax, // [IN] Max MemberDefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawImport->EnumUnresolvedMethods(phEnum, rMethods, cMax, pcTokens);
}
STDMETHODIMP GetUserString( // S_OK or error.
mdString stk, // [IN] String token.
__out_ecount_part_opt(cchString, *pchString)
LPWSTR szString, // [OUT] Copy of string.
ULONG cchString, // [IN] Max chars of room in szString.
ULONG *pchString) // [OUT] How many chars in actual string.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetUserString(stk, szString, cchString, pchString);
}
STDMETHODIMP GetPinvokeMap( // S_OK or error.
mdToken tk, // [IN] FieldDef or MethodDef.
DWORD *pdwMappingFlags, // [OUT] Flags used for mapping.
__out_ecount_part_opt(cchImportName, *pchImportName)
LPWSTR szImportName, // [OUT] Import name.
ULONG cchImportName, // [IN] Size of the name buffer.
ULONG *pchImportName, // [OUT] Actual number of characters stored.
mdModuleRef *pmrImportDLL) // [OUT] ModuleRef token for the target DLL.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetPinvokeMap(tk, pdwMappingFlags, szImportName, cchImportName, pchImportName, pmrImportDLL);
}
STDMETHODIMP EnumSignatures( // S_OK or error.
HCORENUM *phEnum, // [IN|OUT] pointer to the enum.
mdSignature rSignatures[], // [OUT] put signatures here.
ULONG cmax, // [IN] max signatures to put.
ULONG *pcSignatures) // [OUT] put # put here.
{
return m_pRawImport->EnumSignatures(phEnum, rSignatures, cmax, pcSignatures);
}
STDMETHODIMP EnumTypeSpecs( // S_OK or error.
HCORENUM *phEnum, // [IN|OUT] pointer to the enum.
mdTypeSpec rTypeSpecs[], // [OUT] put TypeSpecs here.
ULONG cmax, // [IN] max TypeSpecs to put.
ULONG *pcTypeSpecs) // [OUT] put # put here.
{
return m_pRawImport->EnumTypeSpecs(phEnum, rTypeSpecs, cmax, pcTypeSpecs);
}
STDMETHODIMP EnumUserStrings( // S_OK or error.
HCORENUM *phEnum, // [IN/OUT] pointer to the enum.
mdString rStrings[], // [OUT] put Strings here.
ULONG cmax, // [IN] max Strings to put.
ULONG *pcStrings) // [OUT] put # put here.
{
return m_pRawImport->EnumUserStrings(phEnum, rStrings, cmax, pcStrings);
}
STDMETHODIMP GetParamForMethodIndex( // S_OK or error.
mdMethodDef md, // [IN] Method token.
ULONG ulParamSeq, // [IN] Parameter sequence.
mdParamDef *ppd) // [IN] Put Param token here.
{
return m_pRawImport->GetParamForMethodIndex(md, ulParamSeq, ppd);
}
STDMETHODIMP EnumCustomAttributes( // S_OK or error.
HCORENUM *phEnum, // [IN, OUT] COR enumerator.
mdToken tk, // [IN] Token to scope the enumeration, 0 for all.
mdToken tkType, // [IN] Type of interest, 0 for all.
mdCustomAttribute rCustomAttributes[], // [OUT] Put custom attribute tokens here.
ULONG cMax, // [IN] Size of rCustomAttributes.
ULONG *pcCustomAttributes) // [OUT, OPTIONAL] Put count of token values here.
{
return m_pRawImport->EnumCustomAttributes(phEnum, tk, tkType, rCustomAttributes, cMax, pcCustomAttributes);
}
STDMETHODIMP GetCustomAttributeProps( // S_OK or error.
mdCustomAttribute cv, // [IN] CustomAttribute token.
mdToken *ptkObj, // [OUT, OPTIONAL] Put object token here.
mdToken *ptkType, // [OUT, OPTIONAL] Put AttrType token here.
void const **ppBlob, // [OUT, OPTIONAL] Put pointer to data here.
ULONG *pcbSize) // [OUT, OPTIONAL] Put size of date here.
{
HRESULT hr;
if (!IsValidNonNilToken(cv, mdtCustomAttribute))
{
// Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result
return m_pRawImport->GetCustomAttributeProps(cv, ptkObj, ptkType, ppBlob, pcbSize);
}
IfFailRet(m_pRawImport->GetCustomAttributeProps(cv, ptkObj, ptkType, NULL, NULL));
IfFailRet(m_pWinMDAdapter->GetCustomAttributeBlob(cv, ppBlob, pcbSize));
return hr;
}
STDMETHODIMP FindTypeRef(
mdToken tkResolutionScope, // [IN] ModuleRef, AssemblyRef or TypeRef.
LPCWSTR wzTypeName, // [IN] TypeRef Name.
mdTypeRef *ptr) // [OUT] matching TypeRef.
{
HRESULT hr;
LPUTF8 szFullName;
LPCUTF8 szNamespace;
LPCUTF8 szName;
_ASSERTE(wzTypeName && ptr);
*ptr = mdTypeRefNil; // AV if caller passes NULL: just like the real RegMeta.
// Convert the name to UTF8.
PREFIX_ASSUME(wzTypeName != NULL); // caller might pass NULL, but they'll AV (just like the real RegMeta)
UTF8STR(wzTypeName, szFullName);
ns::SplitInline(szFullName, szNamespace, szName);
hr = m_pWinMDAdapter->FindTypeRef(szNamespace, szName, tkResolutionScope, ptr);
return hr;
}
STDMETHODIMP GetMemberProps(
mdToken mb, // The member for which to get props.
mdTypeDef *pClass, // Put member's class here.
__out_ecount_part_opt(cchMember, *pchMember)
LPWSTR szMember, // Put member's name here.
ULONG cchMember, // Size of szMember buffer in wide chars.
ULONG *pchMember, // Put actual size here
DWORD *pdwAttr, // Put flags here.
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data
ULONG *pcbSigBlob, // [OUT] actual size of signature blob
ULONG *pulCodeRVA, // [OUT] codeRVA
DWORD *pdwImplFlags, // [OUT] Impl. Flags
DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_*
UVCP_CONSTANT *ppValue, // [OUT] constant value
ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings.
{
HRESULT hr;
HRESULT hrNameTruncation;
if (!IsValidNonNilToken(mb, mdtMethodDef) && !IsValidNonNilToken(mb, mdtFieldDef))
{
// Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result
return m_pRawImport->GetMemberProps(mb, pClass, szMember, cchMember, pchMember, pdwAttr, ppvSigBlob, pcbSigBlob, pulCodeRVA, pdwImplFlags, pdwCPlusTypeFlag, ppValue, pcchValue);
}
PCCOR_SIGNATURE pOrigSig;
ULONG cbOrigSig;
IfFailRet(hrNameTruncation = m_pRawImport->GetMemberProps(mb, pClass, szMember, cchMember, pchMember, pdwAttr, &pOrigSig, &cbOrigSig, pulCodeRVA, pdwImplFlags, pdwCPlusTypeFlag, ppValue, pcchValue));
LPCSTR szNewName = NULL;
IfFailRet(m_pWinMDAdapter->ModifyMemberProps(mb, pdwAttr, pdwImplFlags, pulCodeRVA, &szNewName));
if (IsValidNonNilToken(mb, mdtMethodDef))
{
IfFailRet((m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtMethodDef>(
mb,
&pOrigSig, // ppOrigSig
&cbOrigSig, // pcbOrigSig
ppvSigBlob,
pcbSigBlob,
m_pRawImport)));
}
else if (IsValidNonNilToken(mb, mdtFieldDef))
{
IfFailRet((m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtFieldDef>(
mb,
&pOrigSig, // ppOrigSig
&cbOrigSig, // pcbOrigSig
ppvSigBlob,
pcbSigBlob,
m_pRawImport)));
}
else
{
if (ppvSigBlob != NULL)
*ppvSigBlob = pOrigSig;
if (pcbSigBlob != NULL)
*pcbSigBlob = cbOrigSig;
}
if (szNewName != NULL)
{
// We want to return name truncation status from the method that really fills the output buffer, rewrite the previous value
IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szMember, cchMember, pchMember));
}
// Return the success code from name filling (S_OK or CLDB_S_TRUNCATION)
return hrNameTruncation;
}
STDMETHODIMP GetFieldProps(
mdFieldDef mb, // The field for which to get props.
mdTypeDef *pClass, // Put field's class here.
__out_ecount_part_opt(cchField, *pchField)
LPWSTR szField, // Put field's name here.
ULONG cchField, // Size of szField buffer in wide chars.
ULONG *pchField, // Put actual size here
DWORD *pdwAttr, // Put flags here.
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data
ULONG *pcbSigBlob, // [OUT] actual size of signature blob
DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_*
UVCP_CONSTANT *ppValue, // [OUT] constant value
ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings.
{
HRESULT hr;
HRESULT hrNameTruncation;
PCCOR_SIGNATURE pOrigSig;
ULONG cbOrigSig;
IfFailRet(hrNameTruncation = m_pRawImport->GetFieldProps(mb, pClass, szField, cchField, pchField, pdwAttr, &pOrigSig, &cbOrigSig, pdwCPlusTypeFlag, ppValue, pcchValue));
IfFailRet(m_pWinMDAdapter->ModifyFieldDefProps(mb, pdwAttr));
IfFailRet((m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtFieldDef>(
mb,
&pOrigSig,
&cbOrigSig,
ppvSigBlob,
pcbSigBlob,
m_pRawImport)));
// Return the success code from name filling (S_OK or CLDB_S_TRUNCATION)
return hrNameTruncation;
}
STDMETHODIMP GetPropertyProps( // S_OK, S_FALSE, or error.
mdProperty prop, // [IN] property token
mdTypeDef *pClass, // [OUT] typedef containing the property declarion.
LPCWSTR szProperty, // [OUT] Property name
ULONG cchProperty, // [IN] the count of wchar of szProperty
ULONG *pchProperty, // [OUT] actual count of wchar for property name
DWORD *pdwPropFlags, // [OUT] property flags.
PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob
ULONG *pbSig, // [OUT] count of bytes in *ppvSig
DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_*
UVCP_CONSTANT *ppDefaultValue, // [OUT] constant value
ULONG *pcchDefaultValue, // [OUT] size of constant string in chars, 0 for non-strings.
mdMethodDef *pmdSetter, // [OUT] setter method of the property
mdMethodDef *pmdGetter, // [OUT] getter method of the property
mdMethodDef rmdOtherMethod[], // [OUT] other method of the property
ULONG cMax, // [IN] size of rmdOtherMethod
ULONG *pcOtherMethod) // [OUT] total number of other method of this property
{
HRESULT hr = S_OK;
HRESULT hrNameTruncation;
ULONG cbOrigSigBlob = (ULONG)(-1);
PCCOR_SIGNATURE pOrigSig = NULL;
IfFailRet(hrNameTruncation = m_pRawImport->GetPropertyProps(prop, pClass, szProperty, cchProperty, pchProperty, pdwPropFlags, &pOrigSig, &cbOrigSigBlob, pdwCPlusTypeFlag, ppDefaultValue, pcchDefaultValue, pmdSetter, pmdGetter, rmdOtherMethod, cMax, pcOtherMethod));
IfFailRet((m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtProperty>(
prop,
&pOrigSig, // ppOrigSig
&cbOrigSigBlob, // pcbOrigSig
ppvSig,
pbSig,
m_pRawImport)));
// Return the success code from name filling (S_OK or CLDB_S_TRUNCATION)
return hrNameTruncation;
}
STDMETHODIMP GetParamProps( // S_OK or error.
mdParamDef tk, // [IN]The Parameter.
mdMethodDef *pmd, // [OUT] Parent Method token.
ULONG *pulSequence, // [OUT] Parameter sequence.
__out_ecount_part_opt(cchName, *pchName)
LPWSTR szName, // [OUT] Put name here.
ULONG cchName, // [OUT] Size of name buffer.
ULONG *pchName, // [OUT] Put actual size of name here.
DWORD *pdwAttr, // [OUT] Put flags here.
DWORD *pdwCPlusTypeFlag, // [OUT] Flag for value type. selected ELEMENT_TYPE_*.
UVCP_CONSTANT *ppValue, // [OUT] Constant value.
ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetParamProps(tk, pmd, pulSequence, szName, cchName, pchName, pdwAttr, pdwCPlusTypeFlag, ppValue, pcchValue);
}
STDMETHODIMP GetCustomAttributeByName( // S_OK or error.
mdToken tkObj, // [IN] Object with Custom Attribute.
LPCWSTR wszName, // [IN] Name of desired Custom Attribute.
const void **ppData, // [OUT] Put pointer to data here.
ULONG *pcbData) // [OUT] Put size of data here.
{
HRESULT hr;
if (wszName == NULL)
{
hr = S_FALSE; // Questionable response but maintains compatibility with RegMeta
}
else
{
MAKE_UTF8PTR_FROMWIDE_NOTHROW(szName, wszName);
IfNullGo(szName);
IfFailGo(CommonGetCustomAttributeByName(tkObj, szName, ppData, pcbData));
}
ErrExit:
return hr;
}
STDMETHODIMP_(BOOL) IsValidToken( // True or False.
mdToken tk) // [IN] Given token.
{
mdToken tokenType = TypeFromToken(tk);
if (tokenType == mdtAssemblyRef)
return m_pWinMDAdapter->IsValidAssemblyRefToken(tk);
return m_pRawImport->IsValidToken(tk);
}
STDMETHODIMP GetNestedClassProps( // S_OK or error.
mdTypeDef tdNestedClass, // [IN] NestedClass token.
mdTypeDef *ptdEnclosingClass) // [OUT] EnclosingClass token.
{
return m_pRawImport->GetNestedClassProps(tdNestedClass, ptdEnclosingClass);
}
STDMETHODIMP GetNativeCallConvFromSig( // S_OK or error.
void const *pvSig, // [IN] Pointer to signature.
ULONG cbSig, // [IN] Count of signature bytes.
ULONG *pCallConv) // [OUT] Put calling conv here (see CorPinvokemap).
{
return m_pRawImport->GetNativeCallConvFromSig(pvSig, cbSig, pCallConv);
}
STDMETHODIMP IsGlobal( // S_OK or error.
mdToken pd, // [IN] Type, Field, or Method token.
int *pbGlobal) // [OUT] Put 1 if global, 0 otherwise.
{
return m_pRawImport->IsGlobal(pd, pbGlobal);
}
public:
// ========================================================
// IMetaDataWinMDImport methods
// ========================================================
// This method returns the RAW view of the metadata. Essentially removing the Adapter's projection support for the typeRef.
STDMETHODIMP GetUntransformedTypeRefProps(
mdTypeRef tr, // [IN] TypeRef token.
mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef.
__out_ecount_part_opt(cchName, *pchName)
LPWSTR szName, // [OUT] Unprojected name of the TypeRef.
ULONG cchName, // [IN] Size of buffer.
ULONG *pchName) // [OUT] Size of Name.
{
// By-pass the call to the raw importer, removing the adapter layer.
return m_pRawImport->GetTypeRefProps(tr, ptkResolutionScope, szName, cchName, pchName);
}
//=========================================================
// IMetaDataImport2 methods
//=========================================================
STDMETHODIMP EnumGenericParams(
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdToken tk, // [IN] TypeDef or MethodDef whose generic parameters are requested
mdGenericParam rGenericParams[], // [OUT] Put GenericParams here.
ULONG cMax, // [IN] Max GenericParams to put.
ULONG *pcGenericParams) // [OUT] Put # put here.
{
return m_pRawImport->EnumGenericParams(phEnum, tk, rGenericParams, cMax, pcGenericParams);
}
STDMETHODIMP GetGenericParamProps( // S_OK or error.
mdGenericParam gp, // [IN] GenericParam
ULONG *pulParamSeq, // [OUT] Index of the type parameter
DWORD *pdwParamFlags, // [OUT] Flags, for future use (e.g. variance)
mdToken *ptOwner, // [OUT] Owner (TypeDef or MethodDef)
DWORD *reserved, // [OUT] For future use (e.g. non-type parameters)
__out_ecount_part_opt(cchName, *pchName)
LPWSTR wzname, // [OUT] Put name here
ULONG cchName, // [IN] Size of buffer
ULONG *pchName) // [OUT] Put size of name (wide chars) here.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawImport->GetGenericParamProps(gp, pulParamSeq, pdwParamFlags, ptOwner, reserved, wzname, cchName, pchName);
}
STDMETHODIMP GetMethodSpecProps(
mdMethodSpec mi, // [IN] The method instantiation
mdToken *tkParent, // [OUT] MethodDef or MemberRef
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data
ULONG *pcbSigBlob) // [OUT] actual size of signature blob
{
HRESULT hr = S_OK;
ULONG cbOrigSigBlob = (ULONG)(-1);
PCCOR_SIGNATURE pOrigSig = NULL;
IfFailRet(m_pRawImport->GetMethodSpecProps(mi, tkParent, &pOrigSig, &cbOrigSigBlob));
return m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtMethodSpec>(
mi,
&pOrigSig, // ppOrigSig
&cbOrigSigBlob, // pcbOrigSig
ppvSigBlob,
pcbSigBlob,
m_pRawImport);
}
STDMETHODIMP EnumGenericParamConstraints(
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdGenericParam tk, // [IN] GenericParam whose constraints are requested
mdGenericParamConstraint rGenericParamConstraints[], // [OUT] Put GenericParamConstraints here.
ULONG cMax, // [IN] Max GenericParamConstraints to put.
ULONG *pcGenericParamConstraints) // [OUT] Put # put here.
{
return m_pRawImport->EnumGenericParamConstraints(phEnum, tk, rGenericParamConstraints, cMax, pcGenericParamConstraints);
}
STDMETHODIMP GetGenericParamConstraintProps( // S_OK or error.
mdGenericParamConstraint gpc, // [IN] GenericParamConstraint
mdGenericParam *ptGenericParam, // [OUT] GenericParam that is constrained
mdToken *ptkConstraintType) // [OUT] TypeDef/Ref/Spec constraint
{
return m_pRawImport->GetGenericParamConstraintProps(gpc, ptGenericParam, ptkConstraintType);
}
STDMETHODIMP GetPEKind( // S_OK or error.
DWORD* pdwPEKind, // [OUT] The kind of PE (0 - not a PE)
DWORD* pdwMachine) // [OUT] Machine as defined in NT header
{
return m_pRawImport->GetPEKind(pdwPEKind, pdwMachine);
}
STDMETHODIMP GetVersionString( // S_OK or error.
__out_ecount_part_opt(ccBufSize, *pccBufSize)
LPWSTR pwzBuf, // [OUT] Put version string here.
DWORD ccBufSize, // [IN] size of the buffer, in wide chars
DWORD *pccBufSize) // [OUT] Size of the version string, wide chars, including terminating nul.
{
HRESULT hr;
LPCSTR szVersion;
IfFailRet(GetVersionString(&szVersion));
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return DeliverUtf8String(szVersion, pwzBuf, ccBufSize, pccBufSize);
}
STDMETHODIMP EnumMethodSpecs(
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdToken tk, // [IN] MethodDef or MemberRef whose MethodSpecs are requested
mdMethodSpec rMethodSpecs[], // [OUT] Put MethodSpecs here.
ULONG cMax, // [IN] Max tokens to put.
ULONG *pcMethodSpecs) // [OUT] Put actual count here.
{
return m_pRawImport->EnumMethodSpecs(phEnum, tk, rMethodSpecs, cMax, pcMethodSpecs);
}
public:
//=========================================================
// IMetaDataAssemblyImport methods
//=========================================================
STDMETHODIMP GetAssemblyProps( // S_OK or error.
mdAssembly mda, // [IN] The Assembly for which to get the properties.
const void **ppbPublicKey, // [OUT] Pointer to the public key.
ULONG *pcbPublicKey, // [OUT] Count of bytes in the public key.
ULONG *pulHashAlgId, // [OUT] Hash Algorithm.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with assembly's simply name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
ASSEMBLYMETADATA *pMetaData, // [OUT] Assembly MetaData.
DWORD *pdwAssemblyFlags) // [OUT] Flags.
{
return m_pRawAssemblyImport->GetAssemblyProps(mda, ppbPublicKey, pcbPublicKey, pulHashAlgId, szName, cchName, pchName, pMetaData, pdwAssemblyFlags);
}
STDMETHODIMP GetAssemblyRefProps( // S_OK or error.
mdAssemblyRef mdar, // [IN] The AssemblyRef for which to get the properties.
const void **ppbPublicKeyOrToken, // [OUT] Pointer to the public key or token.
ULONG *pcbPublicKeyOrToken, // [OUT] Count of bytes in the public key or token.
__out_ecount_part_opt(cchName, *pchName)LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
ASSEMBLYMETADATA *pMetaData, // [OUT] Assembly MetaData.
const void **ppbHashValue, // [OUT] Hash blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the hash blob.
DWORD *pdwAssemblyRefFlags) // [OUT] Flags.
{
HRESULT hr;
HRESULT hrNameTruncation;
if (!IsValidNonNilToken(mdar, mdtAssemblyRef))
{
// Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result
return m_pRawAssemblyImport->GetAssemblyRefProps(mdar, ppbPublicKeyOrToken, pcbPublicKeyOrToken, szName, cchName, pchName, pMetaData, ppbHashValue, pcbHashValue, pdwAssemblyRefFlags);
}
mdAssemblyRef md = mdar;
if (RidFromToken(md) > m_pWinMDAdapter->GetRawAssemblyRefCount())
{
// The extra framework assemblies we add references to should all have the
// same verion, key, culture, etc as those of mscorlib.
// So we retrieve the mscorlib properties and change the name.
md = m_pWinMDAdapter->GetAssemblyRefMscorlib();
}
IfFailRet(hrNameTruncation = m_pRawAssemblyImport->GetAssemblyRefProps(md, ppbPublicKeyOrToken, pcbPublicKeyOrToken, szName, cchName, pchName, pMetaData, ppbHashValue, pcbHashValue, pdwAssemblyRefFlags));
LPCSTR szNewName = nullptr;
USHORT *pusMajorVersion = nullptr;
USHORT *pusMinorVersion = nullptr;
USHORT *pusBuildNumber = nullptr;
USHORT *pusRevisionNumber = nullptr;
if (pMetaData != nullptr)
{
pusMajorVersion = &pMetaData->usMajorVersion;
pusMinorVersion = &pMetaData->usMinorVersion;
pusBuildNumber = &pMetaData->usBuildNumber;
pusRevisionNumber = &pMetaData->usRevisionNumber;
}
m_pWinMDAdapter->ModifyAssemblyRefProps(
mdar,
ppbPublicKeyOrToken,
pcbPublicKeyOrToken,
&szNewName,
pusMajorVersion,
pusMinorVersion,
pusBuildNumber,
pusRevisionNumber,
ppbHashValue,
pcbHashValue);
if (szNewName != nullptr)
{
IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szName, cchName, pchName));
}
// Return the success code from name filling (S_OK or CLDB_S_TRUNCATION)
return hrNameTruncation;
}
STDMETHODIMP GetFileProps( // S_OK or error.
mdFile mdf, // [IN] The File for which to get the properties.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
const void **ppbHashValue, // [OUT] Pointer to the Hash Value Blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the Hash Value Blob.
DWORD *pdwFileFlags) // [OUT] Flags.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawAssemblyImport->GetFileProps(mdf, szName, cchName, pchName, ppbHashValue, pcbHashValue, pdwFileFlags);
}
STDMETHODIMP GetExportedTypeProps( // S_OK or error.
mdExportedType mdct, // [IN] The ExportedType for which to get the properties.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef or mdExportedType.
mdTypeDef *ptkTypeDef, // [OUT] TypeDef token within the file.
DWORD *pdwExportedTypeFlags) // [OUT] Flags.
{
HRESULT hr;
LPCSTR szUtf8Namespace;
LPCSTR szUtf8Name;
if (!IsValidNonNilToken(mdct, mdtExportedType))
{
// Idiosyncractic edge cases - delegate straight through to inherit the correct idiosyncractic edge results
return m_pRawAssemblyImport->GetExportedTypeProps(mdct, szName, cchName, pchName, ptkImplementation, ptkTypeDef, pdwExportedTypeFlags);
}
IfFailRet(m_pRawAssemblyImport->GetExportedTypeProps(mdct, NULL, 0, NULL, NULL, ptkTypeDef, pdwExportedTypeFlags));
IfFailRet(this->CommonGetExportedTypeProps(mdct, &szUtf8Namespace, &szUtf8Name, ptkImplementation));
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return DeliverUtf8NamespaceAndName(szUtf8Namespace, szUtf8Name, szName, cchName, pchName);
}
STDMETHODIMP GetManifestResourceProps( // S_OK or error.
mdManifestResource mdmr, // [IN] The ManifestResource for which to get the properties.
__out_ecount_part_opt(cchName, *pchName)LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ManifestResource.
DWORD *pdwOffset, // [OUT] Offset to the beginning of the resource within the file.
DWORD *pdwResourceFlags) // [OUT] Flags.
{
// Returns error code from name filling (may be CLDB_S_TRUNCTATION)
return m_pRawAssemblyImport->GetManifestResourceProps(mdmr, szName, cchName, pchName, ptkImplementation, pdwOffset, pdwResourceFlags);
}
STDMETHODIMP EnumAssemblyRefs( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdAssemblyRef rAssemblyRefs[], // [OUT] Put AssemblyRefs here.
ULONG cMax, // [IN] Max AssemblyRefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
if (*phEnum != NULL)
{
// No trick needed: a previous call to EnumAssemblyRefs must have already taken care of the
// extra assembly refs.
return m_pRawAssemblyImport->EnumAssemblyRefs(phEnum, rAssemblyRefs, cMax, pcTokens);
}
else
{
// if *phEnum is NULL, we need create the HENUMInternal, adjust the assembly ref count,
// and enumerate the number of assembly refs requested. This is done in three steps:
HRESULT hr;
// Step 1: Call EnumAssemblyRefs with an empty buffer to create the HENUMInternal
IfFailGo(m_pRawAssemblyImport->EnumAssemblyRefs(phEnum, NULL, 0, NULL));
// Step 2: Increment the cound to include the extra assembly refs
HENUMInternal *phInternalEnum = static_cast<HENUMInternal*>(*phEnum);
_ASSERTE(phInternalEnum->m_EnumType == MDSimpleEnum);
_ASSERTE( phInternalEnum->m_ulCount == m_pWinMDAdapter->GetRawAssemblyRefCount());
int n = m_pWinMDAdapter->GetExtraAssemblyRefCount();
phInternalEnum->m_ulCount += n;
phInternalEnum->u.m_ulEnd += n;
// Step 3: Call EnumAssemblyRefs again and pass in the modifed HENUMInternal and the real buffer
IfFailGo(m_pRawAssemblyImport->EnumAssemblyRefs(phEnum, rAssemblyRefs, cMax, pcTokens));
ErrExit:
return hr;
}
}
STDMETHODIMP EnumFiles( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdFile rFiles[], // [OUT] Put Files here.
ULONG cMax, // [IN] Max Files to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawAssemblyImport->EnumFiles(phEnum, rFiles, cMax, pcTokens);
}
STDMETHODIMP EnumExportedTypes( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdExportedType rExportedTypes[], // [OUT] Put ExportedTypes here.
ULONG cMax, // [IN] Max ExportedTypes to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawAssemblyImport->EnumExportedTypes(phEnum, rExportedTypes, cMax, pcTokens);
}
STDMETHODIMP EnumManifestResources( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdManifestResource rManifestResources[], // [OUT] Put ManifestResources here.
ULONG cMax, // [IN] Max Resources to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
return m_pRawAssemblyImport->EnumManifestResources(phEnum, rManifestResources, cMax, pcTokens);
}
STDMETHODIMP GetAssemblyFromScope( // S_OK or error
mdAssembly *ptkAssembly) // [OUT] Put token here.
{
return m_pRawAssemblyImport->GetAssemblyFromScope(ptkAssembly);
}
STDMETHODIMP FindExportedTypeByName( // S_OK or error
LPCWSTR wszName, // [IN] Name of the ExportedType.
mdToken mdtExportedType, // [IN] ExportedType for the enclosing class.
mdExportedType *ptkExportedType) // [OUT] Put the ExportedType token here.
{
if (wszName == NULL)
return E_INVALIDARG;
LPUTF8 szFullName;
LPCUTF8 szNamespace;
LPCUTF8 szName;
// Convert the name to UTF8.
UTF8STR(wszName, szFullName);
ns::SplitInline(szFullName, szNamespace, szName);
return this->CommonFindExportedType(szNamespace, szName, mdtExportedType, ptkExportedType);
}
STDMETHODIMP FindManifestResourceByName( // S_OK or error
LPCWSTR szName, // [IN] Name of the ManifestResource.
mdManifestResource *ptkManifestResource) // [OUT] Put the ManifestResource token here.
{
return m_pRawAssemblyImport->FindManifestResourceByName(szName, ptkManifestResource);
}
STDMETHODIMP FindAssembliesByName( // S_OK or error
LPCWSTR szAppBase, // [IN] optional - can be NULL
LPCWSTR szPrivateBin, // [IN] optional - can be NULL
LPCWSTR szAssemblyName, // [IN] required - this is the assembly you are requesting
IUnknown *ppIUnk[], // [OUT] put IMetaDataAssemblyImport pointers here
ULONG cMax, // [IN] The max number to put
ULONG *pcAssemblies) // [OUT] The number of assemblies returned.
{
return m_pRawAssemblyImport->FindAssembliesByName(szAppBase, szPrivateBin, szAssemblyName, ppIUnk, cMax, pcAssemblies);
}
//=========================================================
// IMetaDataValidate
//=========================================================
STDMETHODIMP ValidatorInit( // S_OK or error.
DWORD dwModuleType, // [IN] Specifies the type of the module.
IUnknown *pUnk) // [IN] Validation error handler.
{
if (m_pRawValidate == nullptr)
return E_NOTIMPL;
return m_pRawValidate->ValidatorInit(dwModuleType, pUnk);
}
STDMETHODIMP ValidateMetaData() // S_OK or error.
{
if (m_pRawValidate == nullptr)
return E_NOTIMPL;
return m_pRawValidate->ValidateMetaData();
}
//=========================================================
// IMDCommon methods
//=========================================================
STDMETHODIMP_(IMetaModelCommon*) GetMetaModelCommon()
{
return this;
}
STDMETHODIMP_(IMetaModelCommonRO*) GetMetaModelCommonRO()
{
_ASSERTE(!"WinMDImport does not support GetMetaModelCommonRO(). The most likely cause of this assert is that you're trying to wrap a WinMD adapter around another WinMD adapter.");
return NULL;
}
STDMETHODIMP GetVersionString(LPCSTR *pszVersionString)
{
return m_pWinMDAdapter->GetVersionString(pszVersionString);
}
//=========================================================
// IMetaModelCommon methods
//=========================================================
__checkReturn
virtual HRESULT CommonGetScopeProps(
LPCUTF8 *pszName,
GUID *pMvid)
{
return m_pRawMetaModelCommonRO->CommonGetScopeProps(pszName, pMvid);
}
__checkReturn
virtual HRESULT CommonGetTypeRefProps(
mdTypeRef tr,
LPCUTF8 *pszNamespace,
LPCUTF8 *pszName,
mdToken *ptkResolution)
{
return m_pWinMDAdapter->GetTypeRefProps(tr, pszNamespace, pszName, ptkResolution);
}
__checkReturn
virtual HRESULT CommonGetTypeDefProps(
mdTypeDef td,
LPCUTF8 *pszNameSpace,
LPCUTF8 *pszName,
DWORD *pdwFlags,
mdToken *pdwExtends,
ULONG *pMethodList)
{
HRESULT hr;
IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(td, NULL, NULL, NULL, NULL, pMethodList));
IfFailGo(m_pWinMDAdapter->GetTypeDefProps(td, pszNameSpace, pszName, pdwFlags, pdwExtends));
ErrExit:
return hr;
}
__checkReturn
virtual HRESULT CommonGetTypeSpecProps(
mdTypeSpec ts,
PCCOR_SIGNATURE *ppvSig,
ULONG *pcbSig)
{
return m_pWinMDAdapter->GetSignatureForToken<IMetaDataImport2, mdtTypeSpec>(
ts,
NULL, // ppOrigSig
NULL, // pcbOrigSig
ppvSig,
pcbSig,
m_pRawImport);
}
__checkReturn
virtual HRESULT CommonGetEnclosingClassOfTypeDef(
mdTypeDef td,
mdTypeDef *ptkEnclosingTypeDef)
{
return m_pRawMetaModelCommonRO->CommonGetEnclosingClassOfTypeDef(td, ptkEnclosingTypeDef);
}
__checkReturn
virtual HRESULT CommonGetAssemblyProps(
USHORT *pusMajorVersion,
USHORT *pusMinorVersion,
USHORT *pusBuildNumber,
USHORT *pusRevisionNumber,
DWORD *pdwFlags,
const void **ppbPublicKey,
ULONG *pcbPublicKey,
LPCUTF8 *pszName,
LPCUTF8 *pszLocale)
{
return m_pRawMetaModelCommonRO->CommonGetAssemblyProps(pusMajorVersion, pusMinorVersion, pusBuildNumber, pusRevisionNumber, pdwFlags, ppbPublicKey, pcbPublicKey, pszName, pszLocale);
}
__checkReturn
virtual HRESULT CommonGetAssemblyRefProps(
mdAssemblyRef tkAssemRef,
USHORT *pusMajorVersion,
USHORT *pusMinorVersion,
USHORT *pusBuildNumber,
USHORT *pusRevisionNumber,
DWORD *pdwFlags,
const void **ppbPublicKeyOrToken,
ULONG *pcbPublicKeyOrToken,
LPCUTF8 *pszName,
LPCUTF8 *pszLocale,
const void **ppbHashValue,
ULONG *pcbHashValue)
{
HRESULT hr;
mdAssemblyRef md = tkAssemRef;
if (RidFromToken(md) > m_pWinMDAdapter->GetRawAssemblyRefCount())
{
// The extra framework assemblies we add references to should all have the
// same verion, key, culture, etc as those of mscorlib.
// So we retrieve the mscorlib properties and change the name.
md = m_pWinMDAdapter->GetAssemblyRefMscorlib();
}
IfFailRet(m_pRawMetaModelCommonRO->CommonGetAssemblyRefProps(
md,
pusMajorVersion,
pusMinorVersion,
pusBuildNumber,
pusRevisionNumber,
pdwFlags,
ppbPublicKeyOrToken,
pcbPublicKeyOrToken,
pszName,
pszLocale,
ppbHashValue,
pcbHashValue));
m_pWinMDAdapter->ModifyAssemblyRefProps(
tkAssemRef,
ppbPublicKeyOrToken,
pcbPublicKeyOrToken,
pszName,
pusMajorVersion,
pusMinorVersion,
pusBuildNumber,
pusRevisionNumber,
ppbHashValue,
pcbHashValue);
return hr;
}
__checkReturn
virtual HRESULT CommonGetModuleRefProps(
mdModuleRef tkModuleRef,
LPCUTF8 *pszName)
{
return m_pRawMetaModelCommonRO->CommonGetModuleRefProps(tkModuleRef, pszName);
}
__checkReturn
virtual HRESULT CommonFindExportedType(
LPCUTF8 szNamespace,
LPCUTF8 szName,
mdToken tkEnclosingType,
mdExportedType *ptkExportedType)
{
return m_pWinMDAdapter->FindExportedType(szNamespace, szName, tkEnclosingType, ptkExportedType);
}
__checkReturn
virtual HRESULT CommonGetExportedTypeProps(
mdToken tkExportedType,
LPCUTF8 *pszNamespace,
LPCUTF8 *pszName,
mdToken *ptkImpl)
{
HRESULT hr;
IfFailRet(m_pRawMetaModelCommonRO->CommonGetExportedTypeProps(tkExportedType, pszNamespace, pszName, ptkImpl));
IfFailRet(m_pWinMDAdapter->ModifyExportedTypeName(tkExportedType, pszNamespace, pszName));
return hr;
}
virtual int CommonIsRo()
{
return m_pRawMetaModelCommonRO->CommonIsRo();
}
__checkReturn
virtual HRESULT CommonGetCustomAttributeByNameEx( // S_OK or error.
mdToken tkObj, // [IN] Object with Custom Attribute.
LPCUTF8 szName, // [IN] Name of desired Custom Attribute.
mdCustomAttribute *ptkCA, // [OUT] put custom attribute token here
const void **ppData, // [OUT] Put pointer to data here.
ULONG *pcbData) // [OUT] Put size of data here.
{
return m_pWinMDAdapter->GetCustomAttributeByName(tkObj, szName, ptkCA, ppData, pcbData);
}
__checkReturn
virtual HRESULT FindParentOfMethodHelper(mdMethodDef md, mdTypeDef *ptd)
{
return m_pRawMetaModelCommonRO->FindParentOfMethodHelper(md, ptd);
}
public:
//=========================================================
// IGetIMDInternalImport methods
//=========================================================
STDMETHODIMP GetIMDInternalImport(IMDInternalImport ** ppIMDInternalImport)
{
HRESULT hr = S_OK;
ReleaseHolder<IMDCommon> pMDCommon;
ReleaseHolder<IUnknown> pRawMDInternalImport;
*ppIMDInternalImport = NULL;
// Get the raw IMDInternalImport
IfFailGo(GetMDInternalInterfaceFromPublic(m_pRawImport, IID_IMDInternalImport, (LPVOID*)(&pRawMDInternalImport)));
// Create an adapter around the internal raw interface
IfFailGo(pRawMDInternalImport->QueryInterface(IID_IMDCommon, (LPVOID*)(&pMDCommon)));
IfFailGo(CreateWinMDInternalImportRO(pMDCommon, IID_IMDInternalImport, (void**)ppIMDInternalImport));
ErrExit:
return hr;
}
//=========================================================
// Private methods
//=========================================================
//------------------------------------------------------------------------------------------------------
// Deliver a result string (Unicode) to a caller's sized output buffer using the standard convention
// followed by all metadata api.
//------------------------------------------------------------------------------------------------------
static HRESULT DeliverUnicodeString(LPCWSTR wszResult, __out_ecount_part(cchCallerBuffer, *pchSizeNeeded) LPWSTR wszCallerBuffer, ULONG cchCallerBuffer, ULONG *pchSizeNeeded)
{
ULONG cchActual = (ULONG)(wcslen(wszResult) + 1);
if (pchSizeNeeded)
{
*pchSizeNeeded = cchActual;
}
if (wszCallerBuffer == NULL || cchCallerBuffer < cchActual)
{
if (wszCallerBuffer != NULL)
{
memcpy(wszCallerBuffer, wszResult, cchCallerBuffer * sizeof(WCHAR)); // If buffer too small, return truncated result to be compatible with metadata api conventions
if (cchCallerBuffer > 0)
{ // null-terminate the truncated output string
wszCallerBuffer[cchCallerBuffer - 1] = W('\0');
}
}
return CLDB_S_TRUNCATION;
}
else
{
memcpy(wszCallerBuffer, wszResult, cchActual * sizeof(WCHAR));
return S_OK;
}
}
//------------------------------------------------------------------------------------------------------
// Deliver a result string (Utf8) to a caller's sized output buffer using the standard convention
// followed by all metadata api.
//------------------------------------------------------------------------------------------------------
static HRESULT DeliverUtf8String(LPCSTR szUtf8Result, __out_ecount_part(cchCallerBuffer, *pchSizeNeeded) LPWSTR wszCallerBuffer, ULONG cchCallerBuffer, ULONG *pchSizeNeeded)
{
MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzResult, szUtf8Result);
if (wzResult == NULL)
return E_OUTOFMEMORY;
return DeliverUnicodeString(wzResult, wszCallerBuffer, cchCallerBuffer, pchSizeNeeded);
}
//------------------------------------------------------------------------------------------------------
// Combine a result namespace/name string pair (Utf8) to a Unicode fullname and deliver to a caller's
// sized output buffer using the standard convention followed by all metadata api.
//------------------------------------------------------------------------------------------------------
static HRESULT DeliverUtf8NamespaceAndName(LPCSTR szUtf8Namespace, LPCSTR szUtf8Name, __out_ecount_part(cchCallerBuffer, *pchSizeNeeded) LPWSTR wszCallerBuffer, ULONG cchCallerBuffer, ULONG *pchSizeNeeded)
{
HRESULT hr;
if (wszCallerBuffer != NULL || pchSizeNeeded != NULL)
{
MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzNamespace, szUtf8Namespace);
IfNullRet(wzNamespace);
MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzName, szUtf8Name);
IfNullRet(wzName);
BOOL fTruncation = FALSE;
if (wszCallerBuffer != NULL)
{
fTruncation = !(ns::MakePath(wszCallerBuffer, cchCallerBuffer, wzNamespace, wzName));
if (fTruncation && (cchCallerBuffer > 0))
{ // null-terminate the truncated output string
wszCallerBuffer[cchCallerBuffer - 1] = W('\0');
}
}
if (pchSizeNeeded != NULL)
{
if (fTruncation || (wszCallerBuffer == NULL))
{
*pchSizeNeeded = ns::GetFullLength(wzNamespace, wzName);
}
else
{
*pchSizeNeeded = (ULONG)(wcslen(wszCallerBuffer) + 1);
}
}
hr = fTruncation ? CLDB_S_TRUNCATION : S_OK;
}
else
{
hr = S_OK; // Caller did not request name back.
}
return hr;
}
private:
//=========================================================
// Private instance data
//=========================================================
IMDCommon *m_pRawMDCommon;
IMetaDataImport2 *m_pRawImport;
IMetaDataAssemblyImport *m_pRawAssemblyImport;
IMetaDataValidate *m_pRawValidate;
IMetaModelCommonRO *m_pRawMetaModelCommonRO;
IUnknown *m_pFreeThreadedMarshaler;
WinMDAdapter *m_pWinMDAdapter;
LONG m_cRef;
}; // class WinMDImport
//========================================================================================
// Entrypoint called by IMetaDataDispenser::OpenScope()
//========================================================================================
HRESULT CreateWinMDImport(IMDCommon * pRawMDCommon, REFIID riid, /*[out]*/ void **ppWinMDImport)
{
HRESULT hr;
*ppWinMDImport = NULL;
WinMDImport *pWinMDImport = NULL;
IfFailGo(WinMDImport::Create(pRawMDCommon, &pWinMDImport));
IfFailGo(pWinMDImport->QueryInterface(riid, ppWinMDImport));
hr = S_OK;
ErrExit:
if (pWinMDImport)
pWinMDImport->Release();
return hr;
}
| mit |
travisg/lk | external/lib/lwip/netif/ppp/fsm.c | 569 | 23702 | /*****************************************************************************
* fsm.c - Network Control Protocol Finite State Machine program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 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.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-01 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original based on BSD fsm.c.
*****************************************************************************/
/*
* fsm.c - {Link, IP} Control Protocol Finite State Machine.
*
* Copyright (c) 1989 Carnegie Mellon University.
* 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 Carnegie Mellon University. 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/*
* TODO:
* Randomize fsm id on link/init.
* Deal with variable outgoing MTU.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp_impl.h"
#include "pppdebug.h"
#include "fsm.h"
#include <string.h>
#if PPP_DEBUG
static const char *ppperr_strerr[] = {
"LS_INITIAL", /* LS_INITIAL 0 */
"LS_STARTING", /* LS_STARTING 1 */
"LS_CLOSED", /* LS_CLOSED 2 */
"LS_STOPPED", /* LS_STOPPED 3 */
"LS_CLOSING", /* LS_CLOSING 4 */
"LS_STOPPING", /* LS_STOPPING 5 */
"LS_REQSENT", /* LS_REQSENT 6 */
"LS_ACKRCVD", /* LS_ACKRCVD 7 */
"LS_ACKSENT", /* LS_ACKSENT 8 */
"LS_OPENED" /* LS_OPENED 9 */
};
#endif /* PPP_DEBUG */
static void fsm_timeout (void *);
static void fsm_rconfreq (fsm *, u_char, u_char *, int);
static void fsm_rconfack (fsm *, int, u_char *, int);
static void fsm_rconfnakrej (fsm *, int, int, u_char *, int);
static void fsm_rtermreq (fsm *, int, u_char *, int);
static void fsm_rtermack (fsm *);
static void fsm_rcoderej (fsm *, u_char *, int);
static void fsm_sconfreq (fsm *, int);
#define PROTO_NAME(f) ((f)->callbacks->proto_name)
int peer_mru[NUM_PPP];
/*
* fsm_init - Initialize fsm.
*
* Initialize fsm state.
*/
void
fsm_init(fsm *f)
{
f->state = LS_INITIAL;
f->flags = 0;
f->id = 0; /* XXX Start with random id? */
f->timeouttime = FSM_DEFTIMEOUT;
f->maxconfreqtransmits = FSM_DEFMAXCONFREQS;
f->maxtermtransmits = FSM_DEFMAXTERMREQS;
f->maxnakloops = FSM_DEFMAXNAKLOOPS;
f->term_reason_len = 0;
}
/*
* fsm_lowerup - The lower layer is up.
*/
void
fsm_lowerup(fsm *f)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
switch( f->state ) {
case LS_INITIAL:
f->state = LS_CLOSED;
break;
case LS_STARTING:
if( f->flags & OPT_SILENT ) {
f->state = LS_STOPPED;
} else {
/* Send an initial configure-request */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
}
break;
default:
FSMDEBUG(LOG_INFO, ("%s: Up event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
FSMDEBUG(LOG_INFO, ("%s: lowerup state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_lowerdown - The lower layer is down.
*
* Cancel all timeouts and inform upper layers.
*/
void
fsm_lowerdown(fsm *f)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
switch( f->state ) {
case LS_CLOSED:
f->state = LS_INITIAL;
break;
case LS_STOPPED:
f->state = LS_STARTING;
if( f->callbacks->starting ) {
(*f->callbacks->starting)(f);
}
break;
case LS_CLOSING:
f->state = LS_INITIAL;
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
break;
case LS_STOPPING:
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
f->state = LS_STARTING;
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
break;
case LS_OPENED:
if( f->callbacks->down ) {
(*f->callbacks->down)(f);
}
f->state = LS_STARTING;
break;
default:
FSMDEBUG(LOG_INFO, ("%s: Down event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
FSMDEBUG(LOG_INFO, ("%s: lowerdown state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_open - Link is allowed to come up.
*/
void
fsm_open(fsm *f)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
switch( f->state ) {
case LS_INITIAL:
f->state = LS_STARTING;
if( f->callbacks->starting ) {
(*f->callbacks->starting)(f);
}
break;
case LS_CLOSED:
if( f->flags & OPT_SILENT ) {
f->state = LS_STOPPED;
} else {
/* Send an initial configure-request */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
}
break;
case LS_CLOSING:
f->state = LS_STOPPING;
/* fall through */
case LS_STOPPED:
case LS_OPENED:
if( f->flags & OPT_RESTART ) {
fsm_lowerdown(f);
fsm_lowerup(f);
}
break;
}
FSMDEBUG(LOG_INFO, ("%s: open state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
#if 0 /* backport pppd 2.4.4b1; */
/*
* terminate_layer - Start process of shutting down the FSM
*
* Cancel any timeout running, notify upper layers we're done, and
* send a terminate-request message as configured.
*/
static void
terminate_layer(fsm *f, int nextstate)
{
/* @todo */
}
#endif
/*
* fsm_close - Start closing connection.
*
* Cancel timeouts and either initiate close or possibly go directly to
* the LS_CLOSED state.
*/
void
fsm_close(fsm *f, char *reason)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
f->term_reason = reason;
f->term_reason_len = (reason == NULL ? 0 : (int)strlen(reason));
switch( f->state ) {
case LS_STARTING:
f->state = LS_INITIAL;
break;
case LS_STOPPED:
f->state = LS_CLOSED;
break;
case LS_STOPPING:
f->state = LS_CLOSING;
break;
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
case LS_OPENED:
if( f->state != LS_OPENED ) {
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
} else if( f->callbacks->down ) {
(*f->callbacks->down)(f); /* Inform upper layers we're down */
}
/* Init restart counter, send Terminate-Request */
f->retransmits = f->maxtermtransmits;
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, f->timeouttime);
--f->retransmits;
f->state = LS_CLOSING;
break;
}
FSMDEBUG(LOG_INFO, ("%s: close reason=%s state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), reason, oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_timeout - Timeout expired.
*/
static void
fsm_timeout(void *arg)
{
fsm *f = (fsm *) arg;
switch (f->state) {
case LS_CLOSING:
case LS_STOPPING:
if( f->retransmits <= 0 ) {
FSMDEBUG(LOG_WARNING, ("%s: timeout sending Terminate-Request state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
/*
* We've waited for an ack long enough. Peer probably heard us.
*/
f->state = (f->state == LS_CLOSING)? LS_CLOSED: LS_STOPPED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
} else {
FSMDEBUG(LOG_WARNING, ("%s: timeout resending Terminate-Requests state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
/* Send Terminate-Request */
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, f->timeouttime);
--f->retransmits;
}
break;
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
if (f->retransmits <= 0) {
FSMDEBUG(LOG_WARNING, ("%s: timeout sending Config-Requests state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
f->state = LS_STOPPED;
if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
} else {
FSMDEBUG(LOG_WARNING, ("%s: timeout resending Config-Request state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
/* Retransmit the configure-request */
if (f->callbacks->retransmit) {
(*f->callbacks->retransmit)(f);
}
fsm_sconfreq(f, 1); /* Re-send Configure-Request */
if( f->state == LS_ACKRCVD ) {
f->state = LS_REQSENT;
}
}
break;
default:
FSMDEBUG(LOG_INFO, ("%s: UNHANDLED timeout event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
}
/*
* fsm_input - Input packet.
*/
void
fsm_input(fsm *f, u_char *inpacket, int l)
{
u_char *inp = inpacket;
u_char code, id;
int len;
/*
* Parse header (code, id and length).
* If packet too short, drop it.
*/
if (l < HEADERLEN) {
FSMDEBUG(LOG_WARNING, ("fsm_input(%x): Rcvd short header.\n",
f->protocol));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
GETSHORT(len, inp);
if (len < HEADERLEN) {
FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd illegal length.\n",
f->protocol));
return;
}
if (len > l) {
FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd short packet.\n",
f->protocol));
return;
}
len -= HEADERLEN; /* subtract header length */
if( f->state == LS_INITIAL || f->state == LS_STARTING ) {
FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd packet in state %d (%s).\n",
f->protocol, f->state, ppperr_strerr[f->state]));
return;
}
FSMDEBUG(LOG_INFO, ("fsm_input(%s):%d,%d,%d\n", PROTO_NAME(f), code, id, l));
/*
* Action depends on code.
*/
switch (code) {
case CONFREQ:
fsm_rconfreq(f, id, inp, len);
break;
case CONFACK:
fsm_rconfack(f, id, inp, len);
break;
case CONFNAK:
case CONFREJ:
fsm_rconfnakrej(f, code, id, inp, len);
break;
case TERMREQ:
fsm_rtermreq(f, id, inp, len);
break;
case TERMACK:
fsm_rtermack(f);
break;
case CODEREJ:
fsm_rcoderej(f, inp, len);
break;
default:
FSMDEBUG(LOG_INFO, ("fsm_input(%s): default: \n", PROTO_NAME(f)));
if( !f->callbacks->extcode ||
!(*f->callbacks->extcode)(f, code, id, inp, len) ) {
fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN);
}
break;
}
}
/*
* fsm_rconfreq - Receive Configure-Request.
*/
static void
fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len)
{
int code, reject_if_disagree;
FSMDEBUG(LOG_INFO, ("fsm_rconfreq(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
switch( f->state ) {
case LS_CLOSED:
/* Go away, we're closed */
fsm_sdata(f, TERMACK, id, NULL, 0);
return;
case LS_CLOSING:
case LS_STOPPING:
return;
case LS_OPENED:
/* Go down and restart negotiation */
if( f->callbacks->down ) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
break;
case LS_STOPPED:
/* Negotiation started by our peer */
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = LS_REQSENT;
break;
}
/*
* Pass the requested configuration options
* to protocol-specific code for checking.
*/
if (f->callbacks->reqci) { /* Check CI */
reject_if_disagree = (f->nakloops >= f->maxnakloops);
code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree);
} else if (len) {
code = CONFREJ; /* Reject all CI */
} else {
code = CONFACK;
}
/* send the Ack, Nak or Rej to the peer */
fsm_sdata(f, (u_char)code, id, inp, len);
if (code == CONFACK) {
if (f->state == LS_ACKRCVD) {
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
f->state = LS_OPENED;
if (f->callbacks->up) {
(*f->callbacks->up)(f); /* Inform upper layers */
}
} else {
f->state = LS_ACKSENT;
}
f->nakloops = 0;
} else {
/* we sent CONFACK or CONFREJ */
if (f->state != LS_ACKRCVD) {
f->state = LS_REQSENT;
}
if( code == CONFNAK ) {
++f->nakloops;
}
}
}
/*
* fsm_rconfack - Receive Configure-Ack.
*/
static void
fsm_rconfack(fsm *f, int id, u_char *inp, int len)
{
FSMDEBUG(LOG_INFO, ("fsm_rconfack(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
if (id != f->reqid || f->seen_ack) { /* Expected id? */
return; /* Nope, toss... */
}
if( !(f->callbacks->ackci? (*f->callbacks->ackci)(f, inp, len): (len == 0)) ) {
/* Ack is bad - ignore it */
FSMDEBUG(LOG_INFO, ("%s: received bad Ack (length %d)\n",
PROTO_NAME(f), len));
return;
}
f->seen_ack = 1;
switch (f->state) {
case LS_CLOSED:
case LS_STOPPED:
fsm_sdata(f, TERMACK, (u_char)id, NULL, 0);
break;
case LS_REQSENT:
f->state = LS_ACKRCVD;
f->retransmits = f->maxconfreqtransmits;
break;
case LS_ACKRCVD:
/* Huh? an extra valid Ack? oh well... */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
break;
case LS_ACKSENT:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
f->state = LS_OPENED;
f->retransmits = f->maxconfreqtransmits;
if (f->callbacks->up) {
(*f->callbacks->up)(f); /* Inform upper layers */
}
break;
case LS_OPENED:
/* Go down and restart negotiation */
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = LS_REQSENT;
break;
}
}
/*
* fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject.
*/
static void
fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len)
{
int (*proc) (fsm *, u_char *, int);
int ret;
FSMDEBUG(LOG_INFO, ("fsm_rconfnakrej(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
if (id != f->reqid || f->seen_ack) { /* Expected id? */
return; /* Nope, toss... */
}
proc = (code == CONFNAK)? f->callbacks->nakci: f->callbacks->rejci;
if (!proc || !((ret = proc(f, inp, len)))) {
/* Nak/reject is bad - ignore it */
FSMDEBUG(LOG_INFO, ("%s: received bad %s (length %d)\n",
PROTO_NAME(f), (code==CONFNAK? "Nak": "reject"), len));
return;
}
f->seen_ack = 1;
switch (f->state) {
case LS_CLOSED:
case LS_STOPPED:
fsm_sdata(f, TERMACK, (u_char)id, NULL, 0);
break;
case LS_REQSENT:
case LS_ACKSENT:
/* They didn't agree to what we wanted - try another request */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
if (ret < 0) {
f->state = LS_STOPPED; /* kludge for stopping CCP */
} else {
fsm_sconfreq(f, 0); /* Send Configure-Request */
}
break;
case LS_ACKRCVD:
/* Got a Nak/reject when we had already had an Ack?? oh well... */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
break;
case LS_OPENED:
/* Go down and restart negotiation */
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = LS_REQSENT;
break;
}
}
/*
* fsm_rtermreq - Receive Terminate-Req.
*/
static void
fsm_rtermreq(fsm *f, int id, u_char *p, int len)
{
LWIP_UNUSED_ARG(p);
FSMDEBUG(LOG_INFO, ("fsm_rtermreq(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
switch (f->state) {
case LS_ACKRCVD:
case LS_ACKSENT:
f->state = LS_REQSENT; /* Start over but keep trying */
break;
case LS_OPENED:
if (len > 0) {
FSMDEBUG(LOG_INFO, ("%s terminated by peer (%p)\n", PROTO_NAME(f), p));
} else {
FSMDEBUG(LOG_INFO, ("%s terminated by peer\n", PROTO_NAME(f)));
}
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
f->retransmits = 0;
f->state = LS_STOPPING;
TIMEOUT(fsm_timeout, f, f->timeouttime);
break;
}
fsm_sdata(f, TERMACK, (u_char)id, NULL, 0);
}
/*
* fsm_rtermack - Receive Terminate-Ack.
*/
static void
fsm_rtermack(fsm *f)
{
FSMDEBUG(LOG_INFO, ("fsm_rtermack(%s): state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
switch (f->state) {
case LS_CLOSING:
UNTIMEOUT(fsm_timeout, f);
f->state = LS_CLOSED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_STOPPING:
UNTIMEOUT(fsm_timeout, f);
f->state = LS_STOPPED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_ACKRCVD:
f->state = LS_REQSENT;
break;
case LS_OPENED:
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0);
break;
default:
FSMDEBUG(LOG_INFO, ("fsm_rtermack(%s): UNHANDLED state=%d (%s)!!!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
}
/*
* fsm_rcoderej - Receive an Code-Reject.
*/
static void
fsm_rcoderej(fsm *f, u_char *inp, int len)
{
u_char code, id;
FSMDEBUG(LOG_INFO, ("fsm_rcoderej(%s): state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
if (len < HEADERLEN) {
FSMDEBUG(LOG_INFO, ("fsm_rcoderej: Rcvd short Code-Reject packet!\n"));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
FSMDEBUG(LOG_WARNING, ("%s: Rcvd Code-Reject for code %d, id %d\n",
PROTO_NAME(f), code, id));
if( f->state == LS_ACKRCVD ) {
f->state = LS_REQSENT;
}
}
/*
* fsm_protreject - Peer doesn't speak this protocol.
*
* Treat this as a catastrophic error (RXJ-).
*/
void
fsm_protreject(fsm *f)
{
switch( f->state ) {
case LS_CLOSING:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
/* fall through */
case LS_CLOSED:
f->state = LS_CLOSED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_STOPPING:
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
/* fall through */
case LS_STOPPED:
f->state = LS_STOPPED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_OPENED:
if( f->callbacks->down ) {
(*f->callbacks->down)(f);
}
/* Init restart counter, send Terminate-Request */
f->retransmits = f->maxtermtransmits;
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, f->timeouttime);
--f->retransmits;
f->state = LS_STOPPING;
break;
default:
FSMDEBUG(LOG_INFO, ("%s: Protocol-reject event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
}
/*
* fsm_sconfreq - Send a Configure-Request.
*/
static void
fsm_sconfreq(fsm *f, int retransmit)
{
u_char *outp;
int cilen;
if( f->state != LS_REQSENT && f->state != LS_ACKRCVD && f->state != LS_ACKSENT ) {
/* Not currently negotiating - reset options */
if( f->callbacks->resetci ) {
(*f->callbacks->resetci)(f);
}
f->nakloops = 0;
}
if( !retransmit ) {
/* New request - reset retransmission counter, use new ID */
f->retransmits = f->maxconfreqtransmits;
f->reqid = ++f->id;
}
f->seen_ack = 0;
/*
* Make up the request packet
*/
outp = outpacket_buf[f->unit] + PPP_HDRLEN + HEADERLEN;
if( f->callbacks->cilen && f->callbacks->addci ) {
cilen = (*f->callbacks->cilen)(f);
if( cilen > peer_mru[f->unit] - (int)HEADERLEN ) {
cilen = peer_mru[f->unit] - HEADERLEN;
}
if (f->callbacks->addci) {
(*f->callbacks->addci)(f, outp, &cilen);
}
} else {
cilen = 0;
}
/* send the request to our peer */
fsm_sdata(f, CONFREQ, f->reqid, outp, cilen);
/* start the retransmit timer */
--f->retransmits;
TIMEOUT(fsm_timeout, f, f->timeouttime);
FSMDEBUG(LOG_INFO, ("%s: sending Configure-Request, id %d\n",
PROTO_NAME(f), f->reqid));
}
/*
* fsm_sdata - Send some data.
*
* Used for all packets sent to our peer by this module.
*/
void
fsm_sdata( fsm *f, u_char code, u_char id, u_char *data, int datalen)
{
u_char *outp;
int outlen;
/* Adjust length to be smaller than MTU */
outp = outpacket_buf[f->unit];
if (datalen > peer_mru[f->unit] - (int)HEADERLEN) {
datalen = peer_mru[f->unit] - HEADERLEN;
}
if (datalen && data != outp + PPP_HDRLEN + HEADERLEN) {
BCOPY(data, outp + PPP_HDRLEN + HEADERLEN, datalen);
}
outlen = datalen + HEADERLEN;
MAKEHEADER(outp, f->protocol);
PUTCHAR(code, outp);
PUTCHAR(id, outp);
PUTSHORT(outlen, outp);
pppWrite(f->unit, outpacket_buf[f->unit], outlen + PPP_HDRLEN);
FSMDEBUG(LOG_INFO, ("fsm_sdata(%s): Sent code %d,%d,%d.\n",
PROTO_NAME(f), code, id, outlen));
}
#endif /* PPP_SUPPORT */
| mit |
nawawi/poedit | deps/boost/libs/config/test/no_cxx11_allocator_pass.cpp | 61 | 1094 | // This file was automatically generated on Sun Apr 22 11:15:42 2012
// by libs/config/tools/generate.cpp
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.//
// Revision $Id: generate.cpp 72327 2011-06-01 14:51:03Z eric_niebler $
//
// Test file for macro BOOST_NO_CXX11_ALLOCATOR
// This file should compile, if it does not then
// BOOST_NO_CXX11_ALLOCATOR should be defined.
// See file boost_no_cxx11_allocator.ipp for details
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifndef BOOST_NO_CXX11_ALLOCATOR
#include "boost_no_cxx11_allocator.ipp"
#else
namespace boost_no_cxx11_allocator = empty_boost;
#endif
int main( int, char *[] )
{
return boost_no_cxx11_allocator::test();
}
| mit |
c72578/poedit | deps/boost/libs/iostreams/test/grep_test.cpp | 62 | 8938 | /*
* Distributed under the Boost Software License, Version 1.0.(See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
*
* See http://www.boost.org/libs/iostreams for documentation.
* File: libs/iostreams/test/grep_test.cpp
* Date: Mon May 26 17:48:45 MDT 2008
* Copyright: 2008 CodeRage, LLC
* Author: Jonathan Turkanis
* Contact: turkanis at coderage dot com
*
* Tests the class template basic_grep_filter.
*/
#include <iostream>
#include <boost/config.hpp> // Make sure ptrdiff_t is in std.
#include <algorithm>
#include <cstddef> // std::ptrdiff_t
#include <string>
#include <boost/iostreams/compose.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/filter/grep.hpp>
#include <boost/iostreams/filter/test.hpp>
#include <boost/ref.hpp>
#include <boost/regex.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost;
using namespace boost::iostreams;
namespace io = boost::iostreams;
using boost::unit_test::test_suite;
// List of addresses of US Appeals Courts, from uscourts.gov
std::string addresses =
"John Joseph Moakley United States Courthouse, Suite 2500\n"
"One Courthouse Way\n"
"Boston, MA 02210-3002\n"
"\n"
"Thurgood Marshall United States Courthouse, 18th Floor\n"
"40 Centre Street\n"
"New York, NY 10007-1501\n"
"\n"
"21400 James A. Byrne United States Courthouse\n"
"601 Market Street\n"
"Philadelphia, PA 19106-1729\n"
"\n"
"Lewis F. Powell, Jr. United States Courthouse Annex, Suite 501\n"
"1100 East Main Street\n"
"Richmond, VA 23219-3525\n"
"\n"
"F. Edward Hebert Federal Bldg\n"
"600 South Maestri Place\n"
"New Orleans, LA 70130\n"
"\n"
"Bob Casey United States Courthouse, 1st Floor\n"
"515 Rusk Street\n"
"Houston, TX 77002-2600\n"
"\n"
"Potter Stewart United States Courthouse, Suite 540\n"
"100 East Fifth Street\n"
"Cincinnati, OH 45202\n"
"\n"
"2722 Everett McKinley Dirksen United States Courthouse\n"
"219 South Dearborn Street\n"
"Chicago, IL 60604\n";
// Lines containing "United States Courthouse"
std::string us_courthouse =
"John Joseph Moakley United States Courthouse, Suite 2500\n"
"Thurgood Marshall United States Courthouse, 18th Floor\n"
"21400 James A. Byrne United States Courthouse\n"
"Lewis F. Powell, Jr. United States Courthouse Annex, Suite 501\n"
"Bob Casey United States Courthouse, 1st Floor\n"
"Potter Stewart United States Courthouse, Suite 540\n"
"2722 Everett McKinley Dirksen United States Courthouse\n";
// Lines not containing "United States Courthouse"
std::string us_courthouse_inv =
"One Courthouse Way\n"
"Boston, MA 02210-3002\n"
"\n"
"40 Centre Street\n"
"New York, NY 10007-1501\n"
"\n"
"601 Market Street\n"
"Philadelphia, PA 19106-1729\n"
"\n"
"1100 East Main Street\n"
"Richmond, VA 23219-3525\n"
"\n"
"F. Edward Hebert Federal Bldg\n"
"600 South Maestri Place\n"
"New Orleans, LA 70130\n"
"\n"
"515 Rusk Street\n"
"Houston, TX 77002-2600\n"
"\n"
"100 East Fifth Street\n"
"Cincinnati, OH 45202\n"
"\n"
"219 South Dearborn Street\n"
"Chicago, IL 60604\n";
// Lines containing a state and zip
std::string state_and_zip =
"Boston, MA 02210-3002\n"
"New York, NY 10007-1501\n"
"Philadelphia, PA 19106-1729\n"
"Richmond, VA 23219-3525\n"
"New Orleans, LA 70130\n"
"Houston, TX 77002-2600\n"
"Cincinnati, OH 45202\n"
"Chicago, IL 60604\n";
// Lines not containing a state and zip
std::string state_and_zip_inv =
"John Joseph Moakley United States Courthouse, Suite 2500\n"
"One Courthouse Way\n"
"\n"
"Thurgood Marshall United States Courthouse, 18th Floor\n"
"40 Centre Street\n"
"\n"
"21400 James A. Byrne United States Courthouse\n"
"601 Market Street\n"
"\n"
"Lewis F. Powell, Jr. United States Courthouse Annex, Suite 501\n"
"1100 East Main Street\n"
"\n"
"F. Edward Hebert Federal Bldg\n"
"600 South Maestri Place\n"
"\n"
"Bob Casey United States Courthouse, 1st Floor\n"
"515 Rusk Street\n"
"\n"
"Potter Stewart United States Courthouse, Suite 540\n"
"100 East Fifth Street\n"
"\n"
"2722 Everett McKinley Dirksen United States Courthouse\n"
"219 South Dearborn Street\n";
// Lines containing at least three words
std::string three_words =
"John Joseph Moakley United States Courthouse, Suite 2500\n"
"One Courthouse Way\n"
"Thurgood Marshall United States Courthouse, 18th Floor\n"
"40 Centre Street\n"
"21400 James A. Byrne United States Courthouse\n"
"601 Market Street\n"
"Lewis F. Powell, Jr. United States Courthouse Annex, Suite 501\n"
"1100 East Main Street\n"
"F. Edward Hebert Federal Bldg\n"
"600 South Maestri Place\n"
"Bob Casey United States Courthouse, 1st Floor\n"
"515 Rusk Street\n"
"Potter Stewart United States Courthouse, Suite 540\n"
"100 East Fifth Street\n"
"2722 Everett McKinley Dirksen United States Courthouse\n"
"219 South Dearborn Street\n";
// Lines containing exactly three words
std::string exactly_three_words =
"One Courthouse Way\n"
"40 Centre Street\n"
"601 Market Street\n"
"515 Rusk Street\n";
// Lines that don't contain exactly three words
std::string exactly_three_words_inv =
"John Joseph Moakley United States Courthouse, Suite 2500\n"
"Boston, MA 02210-3002\n"
"\n"
"Thurgood Marshall United States Courthouse, 18th Floor\n"
"New York, NY 10007-1501\n"
"\n"
"21400 James A. Byrne United States Courthouse\n"
"Philadelphia, PA 19106-1729\n"
"\n"
"Lewis F. Powell, Jr. United States Courthouse Annex, Suite 501\n"
"1100 East Main Street\n"
"Richmond, VA 23219-3525\n"
"\n"
"F. Edward Hebert Federal Bldg\n"
"600 South Maestri Place\n"
"New Orleans, LA 70130\n"
"\n"
"Bob Casey United States Courthouse, 1st Floor\n"
"Houston, TX 77002-2600\n"
"\n"
"Potter Stewart United States Courthouse, Suite 540\n"
"100 East Fifth Street\n"
"Cincinnati, OH 45202\n"
"\n"
"2722 Everett McKinley Dirksen United States Courthouse\n"
"219 South Dearborn Street\n"
"Chicago, IL 60604\n";
void test_filter( grep_filter grep,
const std::string& input,
const std::string& output );
void grep_filter_test()
{
regex match_us_courthouse("\\bUnited States Courthouse\\b");
regex match_state_and_zip("\\b[A-Z]{2}\\s+[0-9]{5}(-[0-9]{4})?\\b");
regex match_three_words("\\b\\w+\\s+\\w+\\s+\\w+\\b");
regex_constants::match_flag_type match_default =
regex_constants::match_default;
{
grep_filter grep(match_us_courthouse);
test_filter(grep, addresses, us_courthouse);
}
{
grep_filter grep(match_us_courthouse, match_default, grep::invert);
test_filter(grep, addresses, us_courthouse_inv);
}
{
grep_filter grep(match_state_and_zip);
test_filter(grep, addresses, state_and_zip);
}
{
grep_filter grep(match_state_and_zip, match_default, grep::invert);
test_filter(grep, addresses, state_and_zip_inv);
}
{
grep_filter grep(match_three_words);
test_filter(grep, addresses, three_words);
}
{
grep_filter grep(match_three_words, match_default, grep::whole_line);
test_filter(grep, addresses, exactly_three_words);
}
{
int options = grep::whole_line | grep::invert;
grep_filter grep(match_three_words, match_default, options);
test_filter(grep, addresses, exactly_three_words_inv);
}
}
void test_filter( grep_filter grep,
const std::string& input,
const std::string& output )
{
// Count lines in output
std::ptrdiff_t count = std::count(output.begin(), output.end(), '\n');
// Test as input filter
{
array_source src(input.data(), input.data() + input.size());
std::string dest;
io::copy(compose(boost::ref(grep), src), io::back_inserter(dest));
BOOST_CHECK(dest == output);
BOOST_CHECK(grep.count() == count);
}
// Test as output filter
{
array_source src(input.data(), input.data() + input.size());
std::string dest;
io::copy(src, compose(boost::ref(grep), io::back_inserter(dest)));
BOOST_CHECK(dest == output);
BOOST_CHECK(grep.count() == count);
}
}
test_suite* init_unit_test_suite(int, char* [])
{
test_suite* test = BOOST_TEST_SUITE("grep_filter test");
test->add(BOOST_TEST_CASE(&grep_filter_test));
return test;
}
| mit |
goldcoin/gldcoin | BuildDeps/deps/boost/libs/spirit/example/qi/num_list1.cpp | 64 | 2934 | /*=============================================================================
Copyright (c) 2002-2010 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
// This sample demontrates a parser for a comma separated list of numbers.
// No actions.
//
// [ JDG May 10, 2002 ] spirit1
// [ JDG March 24, 2007 ] spirit2
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
#include <vector>
namespace client
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
///////////////////////////////////////////////////////////////////////////
// Our number list parser
///////////////////////////////////////////////////////////////////////////
//[tutorial_numlist1
template <typename Iterator>
bool parse_numbers(Iterator first, Iterator last)
{
using qi::double_;
using qi::phrase_parse;
using ascii::space;
bool r = phrase_parse(
first, /*< start iterator >*/
last, /*< end iterator >*/
double_ >> *(',' >> double_), /*< the parser >*/
space /*< the skip-parser >*/
);
if (first != last) // fail if we did not get a full match
return false;
return r;
}
//]
}
////////////////////////////////////////////////////////////////////////////
// Main program
////////////////////////////////////////////////////////////////////////////
int
main()
{
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "\t\tA comma separated list parser for Spirit...\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Give me a comma separated list of numbers.\n";
std::cout << "Type [q or Q] to quit\n\n";
std::string str;
while (getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
if (client::parse_numbers(str.begin(), str.end()))
{
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
std::cout << str << " Parses OK: " << std::endl;
}
else
{
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "-------------------------\n";
}
}
std::cout << "Bye... :-) \n\n";
return 0;
}
| mit |
chcbaram/arduino_1.5_win | hardware/arduino/avr/cores/arduino/hooks.c | 325 | 1142 | /*
Copyright (c) 2012 Arduino. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* Empty yield() hook.
*
* This function is intended to be used by library writers to build
* libraries or sketches that supports cooperative threads.
*
* Its defined as a weak symbol and it can be redefined to implement a
* real cooperative scheduler.
*/
static void __empty() {
// Empty
}
void yield(void) __attribute__ ((weak, alias("__empty")));
| mit |
BogusCurry/godot | drivers/speex/vq.c | 70 | 4071 | /* Copyright (C) 2002 Jean-Marc Valin
File: vq.c
Vector quantization
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 Xiph.org Foundation 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 FOUNDATION 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 "config.h"
#include "vq.h"
#include "stack_alloc.h"
#include "arch.h"
#ifdef _USE_SSE
#include <xmmintrin.h>
#include "vq_sse.h"
#elif defined(SHORTCUTS) && (defined(ARM4_ASM) || defined(ARM5E_ASM))
#include "vq_arm4.h"
#elif defined(BFIN_ASM)
#include "vq_bfin.h"
#endif
int scal_quant(spx_word16_t in, const spx_word16_t *boundary, int entries)
{
int i=0;
while (i<entries-1 && in>boundary[0])
{
boundary++;
i++;
}
return i;
}
int scal_quant32(spx_word32_t in, const spx_word32_t *boundary, int entries)
{
int i=0;
while (i<entries-1 && in>boundary[0])
{
boundary++;
i++;
}
return i;
}
#ifndef OVERRIDE_VQ_NBEST
/*Finds the indices of the n-best entries in a codebook*/
void vq_nbest(spx_word16_t *in, const spx_word16_t *codebook, int len, int entries, spx_word32_t *E, int N, int *nbest, spx_word32_t *best_dist, char *stack)
{
int i,j,k,used;
used = 0;
for (i=0;i<entries;i++)
{
spx_word32_t dist=0;
for (j=0;j<len;j++)
dist = MAC16_16(dist,in[j],*codebook++);
#ifdef FIXED_POINT
dist=SUB32(SHR32(E[i],1),dist);
#else
dist=.5f*E[i]-dist;
#endif
if (i<N || dist<best_dist[N-1])
{
for (k=N-1; (k >= 1) && (k > used || dist < best_dist[k-1]); k--)
{
best_dist[k]=best_dist[k-1];
nbest[k] = nbest[k-1];
}
best_dist[k]=dist;
nbest[k]=i;
used++;
}
}
}
#endif
#ifndef OVERRIDE_VQ_NBEST_SIGN
/*Finds the indices of the n-best entries in a codebook with sign*/
void vq_nbest_sign(spx_word16_t *in, const spx_word16_t *codebook, int len, int entries, spx_word32_t *E, int N, int *nbest, spx_word32_t *best_dist, char *stack)
{
int i,j,k, sign, used;
used=0;
for (i=0;i<entries;i++)
{
spx_word32_t dist=0;
for (j=0;j<len;j++)
dist = MAC16_16(dist,in[j],*codebook++);
if (dist>0)
{
sign=0;
dist=-dist;
} else
{
sign=1;
}
#ifdef FIXED_POINT
dist = ADD32(dist,SHR32(E[i],1));
#else
dist = ADD32(dist,.5f*E[i]);
#endif
if (i<N || dist<best_dist[N-1])
{
for (k=N-1; (k >= 1) && (k > used || dist < best_dist[k-1]); k--)
{
best_dist[k]=best_dist[k-1];
nbest[k] = nbest[k-1];
}
best_dist[k]=dist;
nbest[k]=i;
used++;
if (sign)
nbest[k]+=entries;
}
}
}
#endif
| mit |
comitservice/nodmcu | app/lwip/api/netifapi.c | 583 | 4836 | /**
* @file
* Network Interface Sequential API module
*
*/
/*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
*/
#include "lwip/opt.h"
#if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */
#include "lwip/netifapi.h"
#include "lwip/tcpip.h"
/**
* Call netif_add() inside the tcpip_thread context.
*/
void
do_netifapi_netif_add(struct netifapi_msg_msg *msg)
{
if (!netif_add( msg->netif,
msg->msg.add.ipaddr,
msg->msg.add.netmask,
msg->msg.add.gw,
msg->msg.add.state,
msg->msg.add.init,
msg->msg.add.input)) {
msg->err = ERR_IF;
} else {
msg->err = ERR_OK;
}
TCPIP_NETIFAPI_ACK(msg);
}
/**
* Call netif_set_addr() inside the tcpip_thread context.
*/
void
do_netifapi_netif_set_addr(struct netifapi_msg_msg *msg)
{
netif_set_addr( msg->netif,
msg->msg.add.ipaddr,
msg->msg.add.netmask,
msg->msg.add.gw);
msg->err = ERR_OK;
TCPIP_NETIFAPI_ACK(msg);
}
/**
* Call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) inside the
* tcpip_thread context.
*/
void
do_netifapi_netif_common(struct netifapi_msg_msg *msg)
{
if (msg->msg.common.errtfunc != NULL) {
msg->err = msg->msg.common.errtfunc(msg->netif);
} else {
msg->err = ERR_OK;
msg->msg.common.voidfunc(msg->netif);
}
TCPIP_NETIFAPI_ACK(msg);
}
/**
* Call netif_add() in a thread-safe way by running that function inside the
* tcpip_thread context.
*
* @note for params @see netif_add()
*/
err_t
netifapi_netif_add(struct netif *netif,
ip_addr_t *ipaddr,
ip_addr_t *netmask,
ip_addr_t *gw,
void *state,
netif_init_fn init,
netif_input_fn input)
{
struct netifapi_msg msg;
msg.function = do_netifapi_netif_add;
msg.msg.netif = netif;
msg.msg.msg.add.ipaddr = ipaddr;
msg.msg.msg.add.netmask = netmask;
msg.msg.msg.add.gw = gw;
msg.msg.msg.add.state = state;
msg.msg.msg.add.init = init;
msg.msg.msg.add.input = input;
TCPIP_NETIFAPI(&msg);
return msg.msg.err;
}
/**
* Call netif_set_addr() in a thread-safe way by running that function inside the
* tcpip_thread context.
*
* @note for params @see netif_set_addr()
*/
err_t
netifapi_netif_set_addr(struct netif *netif,
ip_addr_t *ipaddr,
ip_addr_t *netmask,
ip_addr_t *gw)
{
struct netifapi_msg msg;
msg.function = do_netifapi_netif_set_addr;
msg.msg.netif = netif;
msg.msg.msg.add.ipaddr = ipaddr;
msg.msg.msg.add.netmask = netmask;
msg.msg.msg.add.gw = gw;
TCPIP_NETIFAPI(&msg);
return msg.msg.err;
}
/**
* call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) in a thread-safe
* way by running that function inside the tcpip_thread context.
*
* @note use only for functions where there is only "netif" parameter.
*/
err_t
netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc,
netifapi_errt_fn errtfunc)
{
struct netifapi_msg msg;
msg.function = do_netifapi_netif_common;
msg.msg.netif = netif;
msg.msg.msg.common.voidfunc = voidfunc;
msg.msg.msg.common.errtfunc = errtfunc;
TCPIP_NETIFAPI(&msg);
return msg.msg.err;
}
#endif /* LWIP_NETIF_API */
| mit |
yaukeywang/slua | build/luajit-2.0.4/src/lib_ffi.c | 74 | 22541 | /*
** FFI library.
** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
*/
#define lib_ffi_c
#define LUA_LIB
#include <errno.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lj_obj.h"
#if LJ_HASFFI
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_meta.h"
#include "lj_ctype.h"
#include "lj_cparse.h"
#include "lj_cdata.h"
#include "lj_cconv.h"
#include "lj_carith.h"
#include "lj_ccall.h"
#include "lj_ccallback.h"
#include "lj_clib.h"
#include "lj_ff.h"
#include "lj_lib.h"
/* -- C type checks ------------------------------------------------------- */
/* Check first argument for a C type and returns its ID. */
static CTypeID ffi_checkctype(lua_State *L, CTState *cts, TValue *param)
{
TValue *o = L->base;
if (!(o < L->top)) {
err_argtype:
lj_err_argtype(L, 1, "C type");
}
if (tvisstr(o)) { /* Parse an abstract C type declaration. */
GCstr *s = strV(o);
CPState cp;
int errcode;
cp.L = L;
cp.cts = cts;
cp.srcname = strdata(s);
cp.p = strdata(s);
cp.param = param;
cp.mode = CPARSE_MODE_ABSTRACT|CPARSE_MODE_NOIMPLICIT;
errcode = lj_cparse(&cp);
if (errcode) lj_err_throw(L, errcode); /* Propagate errors. */
return cp.val.id;
} else {
GCcdata *cd;
if (!tviscdata(o)) goto err_argtype;
if (param && param < L->top) lj_err_arg(L, 1, LJ_ERR_FFI_NUMPARAM);
cd = cdataV(o);
return cd->ctypeid == CTID_CTYPEID ? *(CTypeID *)cdataptr(cd) : cd->ctypeid;
}
}
/* Check argument for C data and return it. */
static GCcdata *ffi_checkcdata(lua_State *L, int narg)
{
TValue *o = L->base + narg-1;
if (!(o < L->top && tviscdata(o)))
lj_err_argt(L, narg, LUA_TCDATA);
return cdataV(o);
}
/* Convert argument to C pointer. */
static void *ffi_checkptr(lua_State *L, int narg, CTypeID id)
{
CTState *cts = ctype_cts(L);
TValue *o = L->base + narg-1;
void *p;
if (o >= L->top)
lj_err_arg(L, narg, LJ_ERR_NOVAL);
lj_cconv_ct_tv(cts, ctype_get(cts, id), (uint8_t *)&p, o, CCF_ARG(narg));
return p;
}
/* Convert argument to int32_t. */
static int32_t ffi_checkint(lua_State *L, int narg)
{
CTState *cts = ctype_cts(L);
TValue *o = L->base + narg-1;
int32_t i;
if (o >= L->top)
lj_err_arg(L, narg, LJ_ERR_NOVAL);
lj_cconv_ct_tv(cts, ctype_get(cts, CTID_INT32), (uint8_t *)&i, o,
CCF_ARG(narg));
return i;
}
/* -- C type metamethods -------------------------------------------------- */
#define LJLIB_MODULE_ffi_meta
/* Handle ctype __index/__newindex metamethods. */
static int ffi_index_meta(lua_State *L, CTState *cts, CType *ct, MMS mm)
{
CTypeID id = ctype_typeid(cts, ct);
cTValue *tv = lj_ctype_meta(cts, id, mm);
TValue *base = L->base;
if (!tv) {
const char *s;
err_index:
s = strdata(lj_ctype_repr(L, id, NULL));
if (tvisstr(L->base+1)) {
lj_err_callerv(L, LJ_ERR_FFI_BADMEMBER, s, strVdata(L->base+1));
} else {
const char *key = tviscdata(L->base+1) ?
strdata(lj_ctype_repr(L, cdataV(L->base+1)->ctypeid, NULL)) :
lj_typename(L->base+1);
lj_err_callerv(L, LJ_ERR_FFI_BADIDXW, s, key);
}
}
if (!tvisfunc(tv)) {
if (mm == MM_index) {
cTValue *o = lj_meta_tget(L, tv, base+1);
if (o) {
if (tvisnil(o)) goto err_index;
copyTV(L, L->top-1, o);
return 1;
}
} else {
TValue *o = lj_meta_tset(L, tv, base+1);
if (o) {
copyTV(L, o, base+2);
return 0;
}
}
copyTV(L, base, L->top);
tv = L->top-1;
}
return lj_meta_tailcall(L, tv);
}
LJLIB_CF(ffi_meta___index) LJLIB_REC(cdata_index 0)
{
CTState *cts = ctype_cts(L);
CTInfo qual = 0;
CType *ct;
uint8_t *p;
TValue *o = L->base;
if (!(o+1 < L->top && tviscdata(o))) /* Also checks for presence of key. */
lj_err_argt(L, 1, LUA_TCDATA);
ct = lj_cdata_index(cts, cdataV(o), o+1, &p, &qual);
if ((qual & 1))
return ffi_index_meta(L, cts, ct, MM_index);
if (lj_cdata_get(cts, ct, L->top-1, p))
lj_gc_check(L);
return 1;
}
LJLIB_CF(ffi_meta___newindex) LJLIB_REC(cdata_index 1)
{
CTState *cts = ctype_cts(L);
CTInfo qual = 0;
CType *ct;
uint8_t *p;
TValue *o = L->base;
if (!(o+2 < L->top && tviscdata(o))) /* Also checks for key and value. */
lj_err_argt(L, 1, LUA_TCDATA);
ct = lj_cdata_index(cts, cdataV(o), o+1, &p, &qual);
if ((qual & 1)) {
if ((qual & CTF_CONST))
lj_err_caller(L, LJ_ERR_FFI_WRCONST);
return ffi_index_meta(L, cts, ct, MM_newindex);
}
lj_cdata_set(cts, ct, p, o+2, qual);
return 0;
}
/* Common handler for cdata arithmetic. */
static int ffi_arith(lua_State *L)
{
MMS mm = (MMS)(curr_func(L)->c.ffid - (int)FF_ffi_meta___eq + (int)MM_eq);
return lj_carith_op(L, mm);
}
/* The following functions must be in contiguous ORDER MM. */
LJLIB_CF(ffi_meta___eq) LJLIB_REC(cdata_arith MM_eq)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___len) LJLIB_REC(cdata_arith MM_len)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___lt) LJLIB_REC(cdata_arith MM_lt)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___le) LJLIB_REC(cdata_arith MM_le)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___concat) LJLIB_REC(cdata_arith MM_concat)
{
return ffi_arith(L);
}
/* Forward declaration. */
static int lj_cf_ffi_new(lua_State *L);
LJLIB_CF(ffi_meta___call) LJLIB_REC(cdata_call)
{
CTState *cts = ctype_cts(L);
GCcdata *cd = ffi_checkcdata(L, 1);
CTypeID id = cd->ctypeid;
CType *ct;
cTValue *tv;
MMS mm = MM_call;
if (cd->ctypeid == CTID_CTYPEID) {
id = *(CTypeID *)cdataptr(cd);
mm = MM_new;
} else {
int ret = lj_ccall_func(L, cd);
if (ret >= 0)
return ret;
}
/* Handle ctype __call/__new metamethod. */
ct = ctype_raw(cts, id);
if (ctype_isptr(ct->info)) id = ctype_cid(ct->info);
tv = lj_ctype_meta(cts, id, mm);
if (tv)
return lj_meta_tailcall(L, tv);
else if (mm == MM_call)
lj_err_callerv(L, LJ_ERR_FFI_BADCALL, strdata(lj_ctype_repr(L, id, NULL)));
return lj_cf_ffi_new(L);
}
LJLIB_CF(ffi_meta___add) LJLIB_REC(cdata_arith MM_add)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___sub) LJLIB_REC(cdata_arith MM_sub)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___mul) LJLIB_REC(cdata_arith MM_mul)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___div) LJLIB_REC(cdata_arith MM_div)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___mod) LJLIB_REC(cdata_arith MM_mod)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___pow) LJLIB_REC(cdata_arith MM_pow)
{
return ffi_arith(L);
}
LJLIB_CF(ffi_meta___unm) LJLIB_REC(cdata_arith MM_unm)
{
return ffi_arith(L);
}
/* End of contiguous ORDER MM. */
LJLIB_CF(ffi_meta___tostring)
{
GCcdata *cd = ffi_checkcdata(L, 1);
const char *msg = "cdata<%s>: %p";
CTypeID id = cd->ctypeid;
void *p = cdataptr(cd);
if (id == CTID_CTYPEID) {
msg = "ctype<%s>";
id = *(CTypeID *)p;
} else {
CTState *cts = ctype_cts(L);
CType *ct = ctype_raw(cts, id);
if (ctype_isref(ct->info)) {
p = *(void **)p;
ct = ctype_rawchild(cts, ct);
}
if (ctype_iscomplex(ct->info)) {
setstrV(L, L->top-1, lj_ctype_repr_complex(L, cdataptr(cd), ct->size));
goto checkgc;
} else if (ct->size == 8 && ctype_isinteger(ct->info)) {
setstrV(L, L->top-1, lj_ctype_repr_int64(L, *(uint64_t *)cdataptr(cd),
(ct->info & CTF_UNSIGNED)));
goto checkgc;
} else if (ctype_isfunc(ct->info)) {
p = *(void **)p;
} else if (ctype_isenum(ct->info)) {
msg = "cdata<%s>: %d";
p = (void *)(uintptr_t)*(uint32_t **)p;
} else {
if (ctype_isptr(ct->info)) {
p = cdata_getptr(p, ct->size);
ct = ctype_rawchild(cts, ct);
}
if (ctype_isstruct(ct->info) || ctype_isvector(ct->info)) {
/* Handle ctype __tostring metamethod. */
cTValue *tv = lj_ctype_meta(cts, ctype_typeid(cts, ct), MM_tostring);
if (tv)
return lj_meta_tailcall(L, tv);
}
}
}
lj_str_pushf(L, msg, strdata(lj_ctype_repr(L, id, NULL)), p);
checkgc:
lj_gc_check(L);
return 1;
}
static int ffi_pairs(lua_State *L, MMS mm)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkcdata(L, 1)->ctypeid;
CType *ct = ctype_raw(cts, id);
cTValue *tv;
if (ctype_isptr(ct->info)) id = ctype_cid(ct->info);
tv = lj_ctype_meta(cts, id, mm);
if (!tv)
lj_err_callerv(L, LJ_ERR_FFI_BADMM, strdata(lj_ctype_repr(L, id, NULL)),
strdata(mmname_str(G(L), mm)));
return lj_meta_tailcall(L, tv);
}
LJLIB_CF(ffi_meta___pairs)
{
return ffi_pairs(L, MM_pairs);
}
LJLIB_CF(ffi_meta___ipairs)
{
return ffi_pairs(L, MM_ipairs);
}
LJLIB_PUSH("ffi") LJLIB_SET(__metatable)
#include "lj_libdef.h"
/* -- C library metamethods ----------------------------------------------- */
#define LJLIB_MODULE_ffi_clib
/* Index C library by a name. */
static TValue *ffi_clib_index(lua_State *L)
{
TValue *o = L->base;
CLibrary *cl;
if (!(o < L->top && tvisudata(o) && udataV(o)->udtype == UDTYPE_FFI_CLIB))
lj_err_argt(L, 1, LUA_TUSERDATA);
cl = (CLibrary *)uddata(udataV(o));
if (!(o+1 < L->top && tvisstr(o+1)))
lj_err_argt(L, 2, LUA_TSTRING);
return lj_clib_index(L, cl, strV(o+1));
}
LJLIB_CF(ffi_clib___index) LJLIB_REC(clib_index 1)
{
TValue *tv = ffi_clib_index(L);
if (tviscdata(tv)) {
CTState *cts = ctype_cts(L);
GCcdata *cd = cdataV(tv);
CType *s = ctype_get(cts, cd->ctypeid);
if (ctype_isextern(s->info)) {
CTypeID sid = ctype_cid(s->info);
void *sp = *(void **)cdataptr(cd);
CType *ct = ctype_raw(cts, sid);
if (lj_cconv_tv_ct(cts, ct, sid, L->top-1, sp))
lj_gc_check(L);
return 1;
}
}
copyTV(L, L->top-1, tv);
return 1;
}
LJLIB_CF(ffi_clib___newindex) LJLIB_REC(clib_index 0)
{
TValue *tv = ffi_clib_index(L);
TValue *o = L->base+2;
if (o < L->top && tviscdata(tv)) {
CTState *cts = ctype_cts(L);
GCcdata *cd = cdataV(tv);
CType *d = ctype_get(cts, cd->ctypeid);
if (ctype_isextern(d->info)) {
CTInfo qual = 0;
for (;;) { /* Skip attributes and collect qualifiers. */
d = ctype_child(cts, d);
if (!ctype_isattrib(d->info)) break;
if (ctype_attrib(d->info) == CTA_QUAL) qual |= d->size;
}
if (!((d->info|qual) & CTF_CONST)) {
lj_cconv_ct_tv(cts, d, *(void **)cdataptr(cd), o, 0);
return 0;
}
}
}
lj_err_caller(L, LJ_ERR_FFI_WRCONST);
return 0; /* unreachable */
}
LJLIB_CF(ffi_clib___gc)
{
TValue *o = L->base;
if (o < L->top && tvisudata(o) && udataV(o)->udtype == UDTYPE_FFI_CLIB)
lj_clib_unload((CLibrary *)uddata(udataV(o)));
return 0;
}
#include "lj_libdef.h"
/* -- Callback function metamethods --------------------------------------- */
#define LJLIB_MODULE_ffi_callback
static int ffi_callback_set(lua_State *L, GCfunc *fn)
{
GCcdata *cd = ffi_checkcdata(L, 1);
CTState *cts = ctype_cts(L);
CType *ct = ctype_raw(cts, cd->ctypeid);
if (ctype_isptr(ct->info) && (LJ_32 || ct->size == 8)) {
MSize slot = lj_ccallback_ptr2slot(cts, *(void **)cdataptr(cd));
if (slot < cts->cb.sizeid && cts->cb.cbid[slot] != 0) {
GCtab *t = cts->miscmap;
TValue *tv = lj_tab_setint(L, t, (int32_t)slot);
if (fn) {
setfuncV(L, tv, fn);
lj_gc_anybarriert(L, t);
} else {
setnilV(tv);
cts->cb.cbid[slot] = 0;
cts->cb.topid = slot < cts->cb.topid ? slot : cts->cb.topid;
}
return 0;
}
}
lj_err_caller(L, LJ_ERR_FFI_BADCBACK);
return 0;
}
LJLIB_CF(ffi_callback_free)
{
return ffi_callback_set(L, NULL);
}
LJLIB_CF(ffi_callback_set)
{
GCfunc *fn = lj_lib_checkfunc(L, 2);
return ffi_callback_set(L, fn);
}
LJLIB_PUSH(top-1) LJLIB_SET(__index)
#include "lj_libdef.h"
/* -- FFI library functions ----------------------------------------------- */
#define LJLIB_MODULE_ffi
LJLIB_CF(ffi_cdef)
{
GCstr *s = lj_lib_checkstr(L, 1);
CPState cp;
int errcode;
cp.L = L;
cp.cts = ctype_cts(L);
cp.srcname = strdata(s);
cp.p = strdata(s);
cp.param = L->base+1;
cp.mode = CPARSE_MODE_MULTI|CPARSE_MODE_DIRECT;
errcode = lj_cparse(&cp);
if (errcode) lj_err_throw(L, errcode); /* Propagate errors. */
lj_gc_check(L);
return 0;
}
LJLIB_CF(ffi_new) LJLIB_REC(.)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, NULL);
CType *ct = ctype_raw(cts, id);
CTSize sz;
CTInfo info = lj_ctype_info(cts, id, &sz);
TValue *o = L->base+1;
GCcdata *cd;
if ((info & CTF_VLA)) {
o++;
sz = lj_ctype_vlsize(cts, ct, (CTSize)ffi_checkint(L, 2));
}
if (sz == CTSIZE_INVALID)
lj_err_arg(L, 1, LJ_ERR_FFI_INVSIZE);
if (!(info & CTF_VLA) && ctype_align(info) <= CT_MEMALIGN)
cd = lj_cdata_new(cts, id, sz);
else
cd = lj_cdata_newv(cts, id, sz, ctype_align(info));
setcdataV(L, o-1, cd); /* Anchor the uninitialized cdata. */
lj_cconv_ct_init(cts, ct, sz, cdataptr(cd),
o, (MSize)(L->top - o)); /* Initialize cdata. */
if (ctype_isstruct(ct->info)) {
/* Handle ctype __gc metamethod. Use the fast lookup here. */
cTValue *tv = lj_tab_getinth(cts->miscmap, -(int32_t)id);
if (tv && tvistab(tv) && (tv = lj_meta_fast(L, tabV(tv), MM_gc))) {
GCtab *t = cts->finalizer;
if (gcref(t->metatable)) {
/* Add to finalizer table, if still enabled. */
copyTV(L, lj_tab_set(L, t, o-1), tv);
lj_gc_anybarriert(L, t);
cd->marked |= LJ_GC_CDATA_FIN;
}
}
}
L->top = o; /* Only return the cdata itself. */
lj_gc_check(L);
return 1;
}
LJLIB_CF(ffi_cast) LJLIB_REC(ffi_new)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, NULL);
CType *d = ctype_raw(cts, id);
TValue *o = lj_lib_checkany(L, 2);
L->top = o+1; /* Make sure this is the last item on the stack. */
if (!(ctype_isnum(d->info) || ctype_isptr(d->info) || ctype_isenum(d->info)))
lj_err_arg(L, 1, LJ_ERR_FFI_INVTYPE);
if (!(tviscdata(o) && cdataV(o)->ctypeid == id)) {
GCcdata *cd = lj_cdata_new(cts, id, d->size);
lj_cconv_ct_tv(cts, d, cdataptr(cd), o, CCF_CAST);
setcdataV(L, o, cd);
lj_gc_check(L);
}
return 1;
}
LJLIB_CF(ffi_typeof) LJLIB_REC(.)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, L->base+1);
GCcdata *cd = lj_cdata_new(cts, CTID_CTYPEID, 4);
*(CTypeID *)cdataptr(cd) = id;
setcdataV(L, L->top-1, cd);
lj_gc_check(L);
return 1;
}
LJLIB_CF(ffi_istype) LJLIB_REC(.)
{
CTState *cts = ctype_cts(L);
CTypeID id1 = ffi_checkctype(L, cts, NULL);
TValue *o = lj_lib_checkany(L, 2);
int b = 0;
if (tviscdata(o)) {
GCcdata *cd = cdataV(o);
CTypeID id2 = cd->ctypeid == CTID_CTYPEID ? *(CTypeID *)cdataptr(cd) :
cd->ctypeid;
CType *ct1 = lj_ctype_rawref(cts, id1);
CType *ct2 = lj_ctype_rawref(cts, id2);
if (ct1 == ct2) {
b = 1;
} else if (ctype_type(ct1->info) == ctype_type(ct2->info) &&
ct1->size == ct2->size) {
if (ctype_ispointer(ct1->info))
b = lj_cconv_compatptr(cts, ct1, ct2, CCF_IGNQUAL);
else if (ctype_isnum(ct1->info) || ctype_isvoid(ct1->info))
b = (((ct1->info ^ ct2->info) & ~(CTF_QUAL|CTF_LONG)) == 0);
} else if (ctype_isstruct(ct1->info) && ctype_isptr(ct2->info) &&
ct1 == ctype_rawchild(cts, ct2)) {
b = 1;
}
}
setboolV(L->top-1, b);
setboolV(&G(L)->tmptv2, b); /* Remember for trace recorder. */
return 1;
}
LJLIB_CF(ffi_sizeof) LJLIB_REC(ffi_xof FF_ffi_sizeof)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, NULL);
CTSize sz;
if (LJ_UNLIKELY(tviscdata(L->base) && cdataisv(cdataV(L->base)))) {
sz = cdatavlen(cdataV(L->base));
} else {
CType *ct = lj_ctype_rawref(cts, id);
if (ctype_isvltype(ct->info))
sz = lj_ctype_vlsize(cts, ct, (CTSize)ffi_checkint(L, 2));
else
sz = ctype_hassize(ct->info) ? ct->size : CTSIZE_INVALID;
if (LJ_UNLIKELY(sz == CTSIZE_INVALID)) {
setnilV(L->top-1);
return 1;
}
}
setintV(L->top-1, (int32_t)sz);
return 1;
}
LJLIB_CF(ffi_alignof) LJLIB_REC(ffi_xof FF_ffi_alignof)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, NULL);
CTSize sz = 0;
CTInfo info = lj_ctype_info(cts, id, &sz);
setintV(L->top-1, 1 << ctype_align(info));
return 1;
}
LJLIB_CF(ffi_offsetof) LJLIB_REC(ffi_xof FF_ffi_offsetof)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, NULL);
GCstr *name = lj_lib_checkstr(L, 2);
CType *ct = lj_ctype_rawref(cts, id);
CTSize ofs;
if (ctype_isstruct(ct->info) && ct->size != CTSIZE_INVALID) {
CType *fct = lj_ctype_getfield(cts, ct, name, &ofs);
if (fct) {
setintV(L->top-1, ofs);
if (ctype_isfield(fct->info)) {
return 1;
} else if (ctype_isbitfield(fct->info)) {
setintV(L->top++, ctype_bitpos(fct->info));
setintV(L->top++, ctype_bitbsz(fct->info));
return 3;
}
}
}
return 0;
}
LJLIB_CF(ffi_errno) LJLIB_REC(.)
{
int err = errno;
if (L->top > L->base)
errno = ffi_checkint(L, 1);
setintV(L->top++, err);
return 1;
}
LJLIB_CF(ffi_string) LJLIB_REC(.)
{
CTState *cts = ctype_cts(L);
TValue *o = lj_lib_checkany(L, 1);
const char *p;
size_t len;
if (o+1 < L->top && !tvisnil(o+1)) {
len = (size_t)ffi_checkint(L, 2);
lj_cconv_ct_tv(cts, ctype_get(cts, CTID_P_CVOID), (uint8_t *)&p, o,
CCF_ARG(1));
} else {
lj_cconv_ct_tv(cts, ctype_get(cts, CTID_P_CCHAR), (uint8_t *)&p, o,
CCF_ARG(1));
len = strlen(p);
}
L->top = o+1; /* Make sure this is the last item on the stack. */
setstrV(L, o, lj_str_new(L, p, len));
lj_gc_check(L);
return 1;
}
LJLIB_CF(ffi_copy) LJLIB_REC(.)
{
void *dp = ffi_checkptr(L, 1, CTID_P_VOID);
void *sp = ffi_checkptr(L, 2, CTID_P_CVOID);
TValue *o = L->base+1;
CTSize len;
if (tvisstr(o) && o+1 >= L->top)
len = strV(o)->len+1; /* Copy Lua string including trailing '\0'. */
else
len = (CTSize)ffi_checkint(L, 3);
memcpy(dp, sp, len);
return 0;
}
LJLIB_CF(ffi_fill) LJLIB_REC(.)
{
void *dp = ffi_checkptr(L, 1, CTID_P_VOID);
CTSize len = (CTSize)ffi_checkint(L, 2);
int32_t fill = 0;
if (L->base+2 < L->top && !tvisnil(L->base+2)) fill = ffi_checkint(L, 3);
memset(dp, fill, len);
return 0;
}
#define H_(le, be) LJ_ENDIAN_SELECT(0x##le, 0x##be)
/* Test ABI string. */
LJLIB_CF(ffi_abi) LJLIB_REC(.)
{
GCstr *s = lj_lib_checkstr(L, 1);
int b = 0;
switch (s->hash) {
#if LJ_64
case H_(849858eb,ad35fd06): b = 1; break; /* 64bit */
#else
case H_(662d3c79,d0e22477): b = 1; break; /* 32bit */
#endif
#if LJ_ARCH_HASFPU
case H_(e33ee463,e33ee463): b = 1; break; /* fpu */
#endif
#if LJ_ABI_SOFTFP
case H_(61211a23,c2e8c81c): b = 1; break; /* softfp */
#else
case H_(539417a8,8ce0812f): b = 1; break; /* hardfp */
#endif
#if LJ_ABI_EABI
case H_(2182df8f,f2ed1152): b = 1; break; /* eabi */
#endif
#if LJ_ABI_WIN
case H_(4ab624a8,4ab624a8): b = 1; break; /* win */
#endif
case H_(3af93066,1f001464): b = 1; break; /* le/be */
default:
break;
}
setboolV(L->top-1, b);
setboolV(&G(L)->tmptv2, b); /* Remember for trace recorder. */
return 1;
}
#undef H_
LJLIB_PUSH(top-8) LJLIB_SET(!) /* Store reference to miscmap table. */
LJLIB_CF(ffi_metatype)
{
CTState *cts = ctype_cts(L);
CTypeID id = ffi_checkctype(L, cts, NULL);
GCtab *mt = lj_lib_checktab(L, 2);
GCtab *t = cts->miscmap;
CType *ct = ctype_get(cts, id); /* Only allow raw types. */
TValue *tv;
GCcdata *cd;
if (!(ctype_isstruct(ct->info) || ctype_iscomplex(ct->info) ||
ctype_isvector(ct->info)))
lj_err_arg(L, 1, LJ_ERR_FFI_INVTYPE);
tv = lj_tab_setinth(L, t, -(int32_t)id);
if (!tvisnil(tv))
lj_err_caller(L, LJ_ERR_PROTMT);
settabV(L, tv, mt);
lj_gc_anybarriert(L, t);
cd = lj_cdata_new(cts, CTID_CTYPEID, 4);
*(CTypeID *)cdataptr(cd) = id;
setcdataV(L, L->top-1, cd);
lj_gc_check(L);
return 1;
}
LJLIB_PUSH(top-7) LJLIB_SET(!) /* Store reference to finalizer table. */
LJLIB_CF(ffi_gc) LJLIB_REC(.)
{
GCcdata *cd = ffi_checkcdata(L, 1);
TValue *fin = lj_lib_checkany(L, 2);
CTState *cts = ctype_cts(L);
GCtab *t = cts->finalizer;
CType *ct = ctype_raw(cts, cd->ctypeid);
if (!(ctype_isptr(ct->info) || ctype_isstruct(ct->info) ||
ctype_isrefarray(ct->info)))
lj_err_arg(L, 1, LJ_ERR_FFI_INVTYPE);
if (gcref(t->metatable)) { /* Update finalizer table, if still enabled. */
copyTV(L, lj_tab_set(L, t, L->base), fin);
lj_gc_anybarriert(L, t);
if (!tvisnil(fin))
cd->marked |= LJ_GC_CDATA_FIN;
else
cd->marked &= ~LJ_GC_CDATA_FIN;
}
L->top = L->base+1; /* Pass through the cdata object. */
return 1;
}
LJLIB_PUSH(top-5) LJLIB_SET(!) /* Store clib metatable in func environment. */
LJLIB_CF(ffi_load)
{
GCstr *name = lj_lib_checkstr(L, 1);
int global = (L->base+1 < L->top && tvistruecond(L->base+1));
lj_clib_load(L, tabref(curr_func(L)->c.env), name, global);
return 1;
}
LJLIB_PUSH(top-4) LJLIB_SET(C)
LJLIB_PUSH(top-3) LJLIB_SET(os)
LJLIB_PUSH(top-2) LJLIB_SET(arch)
#include "lj_libdef.h"
/* ------------------------------------------------------------------------ */
/* Create special weak-keyed finalizer table. */
static GCtab *ffi_finalizer(lua_State *L)
{
/* NOBARRIER: The table is new (marked white). */
GCtab *t = lj_tab_new(L, 0, 1);
settabV(L, L->top++, t);
setgcref(t->metatable, obj2gco(t));
setstrV(L, lj_tab_setstr(L, t, lj_str_newlit(L, "__mode")),
lj_str_newlit(L, "K"));
t->nomm = (uint8_t)(~(1u<<MM_mode));
return t;
}
/* Register FFI module as loaded. */
static void ffi_register_module(lua_State *L)
{
cTValue *tmp = lj_tab_getstr(tabV(registry(L)), lj_str_newlit(L, "_LOADED"));
if (tmp && tvistab(tmp)) {
GCtab *t = tabV(tmp);
copyTV(L, lj_tab_setstr(L, t, lj_str_newlit(L, LUA_FFILIBNAME)), L->top-1);
lj_gc_anybarriert(L, t);
}
}
LUALIB_API int luaopen_ffi(lua_State *L)
{
CTState *cts = lj_ctype_init(L);
settabV(L, L->top++, (cts->miscmap = lj_tab_new(L, 0, 1)));
cts->finalizer = ffi_finalizer(L);
LJ_LIB_REG(L, NULL, ffi_meta);
/* NOBARRIER: basemt is a GC root. */
setgcref(basemt_it(G(L), LJ_TCDATA), obj2gco(tabV(L->top-1)));
LJ_LIB_REG(L, NULL, ffi_clib);
LJ_LIB_REG(L, NULL, ffi_callback);
/* NOBARRIER: the key is new and lj_tab_newkey() handles the barrier. */
settabV(L, lj_tab_setstr(L, cts->miscmap, &cts->g->strempty), tabV(L->top-1));
L->top--;
lj_clib_default(L, tabV(L->top-1)); /* Create ffi.C default namespace. */
lua_pushliteral(L, LJ_OS_NAME);
lua_pushliteral(L, LJ_ARCH_NAME);
LJ_LIB_REG(L, NULL, ffi); /* Note: no global "ffi" created! */
ffi_register_module(L);
return 1;
}
#endif
| mit |
Neuromancer2701/mbedROS2_STF7 | mbed-os/hal/targets/cmsis/TARGET_Atmel/TARGET_SAM_CortexM4/utils/cmsis/TARGET_SAMG55/source/system_samg55.c | 79 | 5945 | /**
* \file
*
* \brief Provides the low-level initialization functions that called
* on chip startup.
*
* Copyright (c) 2014-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include "system_samg55.h"
#include "samg55.h"
/* @cond 0 */
/**INDENT-OFF**/
#ifdef __cplusplus
extern "C" {
#endif
/**INDENT-ON**/
/* @endcond */
/* Clock Settings (120MHz) */
#define SYS_BOARD_PLLAR (CKGR_PLLAR_MULA(0xe4eU) \
| CKGR_PLLAR_PLLACOUNT(0x3fU) \
| CKGR_PLLAR_PLLAEN(0x1U))
#define SYS_BOARD_MCKR (PMC_MCKR_PRES_CLK_1 | PMC_MCKR_CSS_PLLA_CLK)
/* Key to unlock MOR register */
#define SYS_CKGR_MOR_KEY_VALUE CKGR_MOR_KEY(0x37)
/* External oscillator definition, to be overriden by application */
#define CHIP_FREQ_XTAL_12M (12000000UL)
#if (!defined CHIP_FREQ_XTAL)
# define CHIP_FREQ_XTAL CHIP_FREQ_XTAL_12M
#endif
uint32_t SystemCoreClock = CHIP_FREQ_MAINCK_RC_8MHZ;
/**
* \brief Setup the microcontroller system.
* Initialize the System and update the SystemFrequency variable.
*/
void SystemInit(void)
{
/* Set FWS according to SYS_BOARD_MCKR configuration */
EFC->EEFC_FMR = EEFC_FMR_FWS(8)|EEFC_FMR_CLOE;
/* Initialize PLLA */
PMC->CKGR_PLLAR = SYS_BOARD_PLLAR;
while (!(PMC->PMC_SR & PMC_SR_LOCKA)) {
}
/* Switch to PLLA */
PMC->PMC_MCKR = SYS_BOARD_MCKR;
while (!(PMC->PMC_SR & PMC_SR_MCKRDY)) {
}
SystemCoreClock = CHIP_FREQ_CPU_MAX;
}
void SystemCoreClockUpdate(void)
{
/* Determine clock frequency according to clock register values */
switch (PMC->PMC_MCKR & (uint32_t) PMC_MCKR_CSS_Msk) {
case PMC_MCKR_CSS_SLOW_CLK: /* Slow clock */
if (SUPC->SUPC_SR & SUPC_SR_OSCSEL) {
SystemCoreClock = CHIP_FREQ_XTAL_32K;
} else {
SystemCoreClock = CHIP_FREQ_SLCK_RC;
}
break;
case PMC_MCKR_CSS_MAIN_CLK: /* Main clock */
if (PMC->CKGR_MOR & CKGR_MOR_MOSCSEL) {
SystemCoreClock = CHIP_FREQ_XTAL;
} else {
SystemCoreClock = CHIP_FREQ_MAINCK_RC_8MHZ;
switch (PMC->CKGR_MOR & CKGR_MOR_MOSCRCF_Msk) {
case CKGR_MOR_MOSCRCF_8_MHz:
break;
case CKGR_MOR_MOSCRCF_16_MHz:
SystemCoreClock *= 2U;
break;
case CKGR_MOR_MOSCRCF_24_MHz:
SystemCoreClock *= 3U;
break;
default:
break;
}
}
break;
case PMC_MCKR_CSS_PLLA_CLK: /* PLLA clock */
if (SUPC->SUPC_SR & SUPC_SR_OSCSEL) {
SystemCoreClock = CHIP_FREQ_XTAL_32K;
} else {
SystemCoreClock = CHIP_FREQ_SLCK_RC;
}
if ((uint32_t) (PMC->PMC_MCKR & (uint32_t) PMC_MCKR_CSS_Msk) == PMC_MCKR_CSS_PLLA_CLK) {
SystemCoreClock *= ((((PMC->CKGR_PLLAR) & CKGR_PLLAR_MULA_Msk) >>
CKGR_PLLAR_MULA_Pos) + 1U);
}
break;
default:
break;
}
if ((PMC->PMC_MCKR & PMC_MCKR_PRES_Msk) == PMC_MCKR_PRES_CLK_3) {
SystemCoreClock /= 3U;
} else {
SystemCoreClock >>= ((PMC->PMC_MCKR & PMC_MCKR_PRES_Msk) >> PMC_MCKR_PRES_Pos);
}
}
/**
* Initialize flash.
*/
void system_init_flash(uint32_t ul_clk)
{
/* Set FWS for embedded Flash access according to operating frequency */
if (ul_clk < CHIP_FREQ_FWS_0) {
EFC->EEFC_FMR = EEFC_FMR_FWS(0)|EEFC_FMR_CLOE;
} else if (ul_clk < CHIP_FREQ_FWS_1) {
EFC->EEFC_FMR = EEFC_FMR_FWS(1)|EEFC_FMR_CLOE;
} else if (ul_clk < CHIP_FREQ_FWS_2) {
EFC->EEFC_FMR = EEFC_FMR_FWS(2)|EEFC_FMR_CLOE;
} else if (ul_clk < CHIP_FREQ_FWS_3) {
EFC->EEFC_FMR = EEFC_FMR_FWS(3)|EEFC_FMR_CLOE;
} else if (ul_clk < CHIP_FREQ_FWS_4) {
EFC->EEFC_FMR = EEFC_FMR_FWS(4)|EEFC_FMR_CLOE;
} else {
EFC->EEFC_FMR = EEFC_FMR_FWS(5)|EEFC_FMR_CLOE;
}
}
/* @cond 0 */
/**INDENT-OFF**/
#ifdef __cplusplus
}
#endif
/**INDENT-ON**/
/* @endcond */
| mit |
Paulloz/godot | thirdparty/libvpx/vp8/decoder/dboolhuff.c | 79 | 2129 | /*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "dboolhuff.h"
#include "vp8/common/common.h"
#include "vpx_dsp/vpx_dsp_common.h"
int vp8dx_start_decode(BOOL_DECODER *br,
const unsigned char *source,
unsigned int source_sz,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state)
{
br->user_buffer_end = source+source_sz;
br->user_buffer = source;
br->value = 0;
br->count = -8;
br->range = 255;
br->decrypt_cb = decrypt_cb;
br->decrypt_state = decrypt_state;
if (source_sz && !source)
return 1;
/* Populate the buffer */
vp8dx_bool_decoder_fill(br);
return 0;
}
void vp8dx_bool_decoder_fill(BOOL_DECODER *br)
{
const unsigned char *bufptr = br->user_buffer;
VP8_BD_VALUE value = br->value;
int count = br->count;
int shift = VP8_BD_VALUE_SIZE - CHAR_BIT - (count + CHAR_BIT);
size_t bytes_left = br->user_buffer_end - bufptr;
size_t bits_left = bytes_left * CHAR_BIT;
int x = shift + CHAR_BIT - (int)bits_left;
int loop_end = 0;
unsigned char decrypted[sizeof(VP8_BD_VALUE) + 1];
if (br->decrypt_cb) {
size_t n = VPXMIN(sizeof(decrypted), bytes_left);
br->decrypt_cb(br->decrypt_state, bufptr, decrypted, (int)n);
bufptr = decrypted;
}
if(x >= 0)
{
count += VP8_LOTS_OF_BITS;
loop_end = x;
}
if (x < 0 || bits_left)
{
while(shift >= loop_end)
{
count += CHAR_BIT;
value |= (VP8_BD_VALUE)*bufptr << shift;
++bufptr;
++br->user_buffer;
shift -= CHAR_BIT;
}
}
br->value = value;
br->count = count;
}
| mit |
swordfeng/node-sodium | deps/libsodium/src/libsodium/crypto_stream/salsa20/ref/stream_salsa20_ref.c | 93 | 1127 | /*
version 20140420
D. J. Bernstein
Public domain.
*/
#include "api.h"
#include "crypto_core_salsa20.h"
#include "utils.h"
#ifndef HAVE_AMD64_ASM
typedef unsigned int uint32;
static const unsigned char sigma[16] = {
'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', '2', '-', 'b', 'y', 't', 'e', ' ', 'k'
};
int crypto_stream(
unsigned char *c,unsigned long long clen,
const unsigned char *n,
const unsigned char *k
)
{
unsigned char in[16];
unsigned char block[64];
unsigned char kcopy[32];
unsigned int i;
unsigned int u;
if (!clen) return 0;
for (i = 0;i < 32;++i) kcopy[i] = k[i];
for (i = 0;i < 8;++i) in[i] = n[i];
for (i = 8;i < 16;++i) in[i] = 0;
while (clen >= 64) {
crypto_core_salsa20(c,in,kcopy,sigma);
u = 1;
for (i = 8;i < 16;++i) {
u += (unsigned int) in[i];
in[i] = u;
u >>= 8;
}
clen -= 64;
c += 64;
}
if (clen) {
crypto_core_salsa20(block,in,kcopy,sigma);
for (i = 0;i < (unsigned int) clen;++i) c[i] = block[i];
}
sodium_memzero(block, sizeof block);
sodium_memzero(kcopy, sizeof kcopy);
return 0;
}
#endif
| mit |
ragmani/coreclr | src/pal/src/arch/amd64/processor.cpp | 93 | 1239 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Module Name:
processor.cpp
Abstract:
Implementation of processor related functions for the Intel x86/x64
platforms. These functions are processor dependent.
--*/
#include "pal/palinternal.h"
/*++
Function:
XmmYmmStateSupport
Check if OS has enabled both XMM and YMM state support
Return value:
1 if XMM and YMM are enabled, 0 otherwise
--*/
extern "C" unsigned int XmmYmmStateSupport()
{
unsigned int eax;
__asm(" mov $1, %%eax\n" \
" cpuid\n" \
" xor %%eax, %%eax\n" \
" and $0x18000000, %%ecx\n" /* check for xsave feature set and that it is enabled by the OS */ \
" cmp $0x18000000, %%ecx\n" \
" jne end\n" \
" xor %%ecx, %%ecx\n" \
" xgetbv\n" \
"end:\n" \
: "=a"(eax) /* output in eax */ \
: /* no inputs */ \
: "ebx", "ecx", "edx" /* registers that are clobbered */
);
// Check OS has enabled both XMM and YMM state support
return ((eax & 0x06) == 0x06) ? 1 : 0;
}
| mit |
BarrelfishOS/barrelfish | lib/lwip2/src/core/ipv4/ip4_addr.c | 95 | 9000 | /**
* @file
* This is the IPv4 address tools implementation.
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#if LWIP_IPV4
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
/* used by IP4_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */
const ip_addr_t ip_addr_any = IPADDR4_INIT(IPADDR_ANY);
const ip_addr_t ip_addr_broadcast = IPADDR4_INIT(IPADDR_BROADCAST);
/**
* Determine if an address is a broadcast address on a network interface
*
* @param addr address to be checked
* @param netif the network interface against which the address is checked
* @return returns non-zero if the address is a broadcast address
*/
u8_t
ip4_addr_isbroadcast_u32(u32_t addr, const struct netif *netif)
{
ip4_addr_t ipaddr;
ip4_addr_set_u32(&ipaddr, addr);
/* all ones (broadcast) or all zeroes (old skool broadcast) */
if ((~addr == IPADDR_ANY) ||
(addr == IPADDR_ANY)) {
return 1;
/* no broadcast support on this network interface? */
} else if ((netif->flags & NETIF_FLAG_BROADCAST) == 0) {
/* the given address cannot be a broadcast address
* nor can we check against any broadcast addresses */
return 0;
/* address matches network interface address exactly? => no broadcast */
} else if (addr == ip4_addr_get_u32(netif_ip4_addr(netif))) {
return 0;
/* on the same (sub) network... */
} else if (ip4_addr_netcmp(&ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif))
/* ...and host identifier bits are all ones? =>... */
&& ((addr & ~ip4_addr_get_u32(netif_ip4_netmask(netif))) ==
(IPADDR_BROADCAST & ~ip4_addr_get_u32(netif_ip4_netmask(netif))))) {
/* => network broadcast address */
return 1;
} else {
return 0;
}
}
/** Checks if a netmask is valid (starting with ones, then only zeros)
*
* @param netmask the IPv4 netmask to check (in network byte order!)
* @return 1 if the netmask is valid, 0 if it is not
*/
u8_t
ip4_addr_netmask_valid(u32_t netmask)
{
u32_t mask;
u32_t nm_hostorder = lwip_htonl(netmask);
/* first, check for the first zero */
for (mask = 1UL << 31 ; mask != 0; mask >>= 1) {
if ((nm_hostorder & mask) == 0) {
break;
}
}
/* then check that there is no one */
for (; mask != 0; mask >>= 1) {
if ((nm_hostorder & mask) != 0) {
/* there is a one after the first zero -> invalid */
return 0;
}
}
/* no one after the first zero -> valid */
return 1;
}
/* Here for now until needed in other places in lwIP */
#ifndef isprint
#define in_range(c, lo, up) ((u8_t)c >= lo && (u8_t)c <= up)
#define isprint(c) in_range(c, 0x20, 0x7f)
#define isdigit(c) in_range(c, '0', '9')
#define isxdigit(c) (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F'))
#define islower(c) in_range(c, 'a', 'z')
#define isspace(c) (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v')
#endif
/**
* Ascii internet address interpretation routine.
* The value returned is in network order.
*
* @param cp IP address in ascii representation (e.g. "127.0.0.1")
* @return ip address in network order
*/
u32_t
ipaddr_addr(const char *cp)
{
ip4_addr_t val;
if (ip4addr_aton(cp, &val)) {
return ip4_addr_get_u32(&val);
}
return (IPADDR_NONE);
}
/**
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*
* @param cp IP address in ascii representation (e.g. "127.0.0.1")
* @param addr pointer to which to save the ip address in network order
* @return 1 if cp could be converted to addr, 0 on failure
*/
int
ip4addr_aton(const char *cp, ip4_addr_t *addr)
{
u32_t val;
u8_t base;
char c;
u32_t parts[4];
u32_t *pp = parts;
c = *cp;
for (;;) {
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, 1-9=decimal.
*/
if (!isdigit(c)) {
return 0;
}
val = 0;
base = 10;
if (c == '0') {
c = *++cp;
if (c == 'x' || c == 'X') {
base = 16;
c = *++cp;
} else {
base = 8;
}
}
for (;;) {
if (isdigit(c)) {
val = (val * base) + (u32_t)(c - '0');
c = *++cp;
} else if (base == 16 && isxdigit(c)) {
val = (val << 4) | (u32_t)(c + 10 - (islower(c) ? 'a' : 'A'));
c = *++cp;
} else {
break;
}
}
if (c == '.') {
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if (pp >= parts + 3) {
return 0;
}
*pp++ = val;
c = *++cp;
} else {
break;
}
}
/*
* Check for trailing characters.
*/
if (c != '\0' && !isspace(c)) {
return 0;
}
/*
* Concoct the address according to
* the number of parts specified.
*/
switch (pp - parts + 1) {
case 0:
return 0; /* initial nondigit */
case 1: /* a -- 32 bits */
break;
case 2: /* a.b -- 8.24 bits */
if (val > 0xffffffUL) {
return 0;
}
if (parts[0] > 0xff) {
return 0;
}
val |= parts[0] << 24;
break;
case 3: /* a.b.c -- 8.8.16 bits */
if (val > 0xffff) {
return 0;
}
if ((parts[0] > 0xff) || (parts[1] > 0xff)) {
return 0;
}
val |= (parts[0] << 24) | (parts[1] << 16);
break;
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if (val > 0xff) {
return 0;
}
if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff)) {
return 0;
}
val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
break;
default:
LWIP_ASSERT("unhandled", 0);
break;
}
if (addr) {
ip4_addr_set_u32(addr, lwip_htonl(val));
}
return 1;
}
/**
* Convert numeric IP address into decimal dotted ASCII representation.
* returns ptr to static buffer; not reentrant!
*
* @param addr ip address in network order to convert
* @return pointer to a global static (!) buffer that holds the ASCII
* representation of addr
*/
char*
ip4addr_ntoa(const ip4_addr_t *addr)
{
static char str[IP4ADDR_STRLEN_MAX];
return ip4addr_ntoa_r(addr, str, IP4ADDR_STRLEN_MAX);
}
/**
* Same as ipaddr_ntoa, but reentrant since a user-supplied buffer is used.
*
* @param addr ip address in network order to convert
* @param buf target buffer where the string is stored
* @param buflen length of buf
* @return either pointer to buf which now holds the ASCII
* representation of addr or NULL if buf was too small
*/
char*
ip4addr_ntoa_r(const ip4_addr_t *addr, char *buf, int buflen)
{
u32_t s_addr;
char inv[3];
char *rp;
u8_t *ap;
u8_t rem;
u8_t n;
u8_t i;
int len = 0;
s_addr = ip4_addr_get_u32(addr);
rp = buf;
ap = (u8_t *)&s_addr;
for (n = 0; n < 4; n++) {
i = 0;
do {
rem = *ap % (u8_t)10;
*ap /= (u8_t)10;
inv[i++] = (char)('0' + rem);
} while (*ap);
while (i--) {
if (len++ >= buflen) {
return NULL;
}
*rp++ = inv[i];
}
if (len++ >= buflen) {
return NULL;
}
*rp++ = '.';
ap++;
}
*--rp = 0;
return buf;
}
#endif /* LWIP_IPV4 */
| mit |
Will-of-the-Wisp/Torque3D | Engine/lib/sdl/test/testgesture.c | 100 | 8114 | /*
Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Usage:
* Spacebar to begin recording a gesture on all touches.
* s to save all touches into "./gestureSave"
* l to load all touches from "./gestureSave"
*/
#include "SDL.h"
#include <stdlib.h> /* for exit() */
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#define WIDTH 640
#define HEIGHT 480
#define BPP 4
#define DEPTH 32
/* MUST BE A POWER OF 2! */
#define EVENT_BUF_SIZE 256
#define VERBOSE 0
static SDL_Event events[EVENT_BUF_SIZE];
static int eventWrite;
static int colors[7] = {0xFF,0xFF00,0xFF0000,0xFFFF00,0x00FFFF,0xFF00FF,0xFFFFFF};
SDL_Surface *screen;
SDL_Window *window;
SDL_bool quitting = SDL_FALSE;
typedef struct {
float x,y;
} Point;
typedef struct {
float ang,r;
Point p;
} Knob;
static Knob knob;
void setpix(SDL_Surface *screen, float _x, float _y, unsigned int col)
{
Uint32 *pixmem32;
Uint32 colour;
Uint8 r,g,b;
int x = (int)_x;
int y = (int)_y;
float a;
if(x < 0 || x >= screen->w) return;
if(y < 0 || y >= screen->h) return;
pixmem32 = (Uint32*) screen->pixels + y*screen->pitch/BPP + x;
SDL_memcpy(&colour,pixmem32,screen->format->BytesPerPixel);
SDL_GetRGB(colour,screen->format,&r,&g,&b);
/* r = 0;g = 0; b = 0; */
a = (float)((col>>24)&0xFF);
if(a == 0) a = 0xFF; /* Hack, to make things easier. */
a /= 0xFF;
r = (Uint8)(r*(1-a) + ((col>>16)&0xFF)*(a));
g = (Uint8)(g*(1-a) + ((col>> 8)&0xFF)*(a));
b = (Uint8)(b*(1-a) + ((col>> 0)&0xFF)*(a));
colour = SDL_MapRGB( screen->format,r, g, b);
*pixmem32 = colour;
}
void drawLine(SDL_Surface *screen,float x0,float y0,float x1,float y1,unsigned int col) {
float t;
for(t=0;t<1;t+=(float)(1.f/SDL_max(SDL_fabs(x0-x1),SDL_fabs(y0-y1))))
setpix(screen,x1+t*(x0-x1),y1+t*(y0-y1),col);
}
void drawCircle(SDL_Surface* screen,float x,float y,float r,unsigned int c)
{
float tx,ty;
float xr;
for(ty = (float)-SDL_fabs(r);ty <= (float)SDL_fabs((int)r);ty++) {
xr = (float)SDL_sqrt(r*r - ty*ty);
if(r > 0) { /* r > 0 ==> filled circle */
for(tx=-xr+.5f;tx<=xr-.5;tx++) {
setpix(screen,x+tx,y+ty,c);
}
}
else {
setpix(screen,x-xr+.5f,y+ty,c);
setpix(screen,x+xr-.5f,y+ty,c);
}
}
}
void drawKnob(SDL_Surface* screen,Knob k) {
drawCircle(screen,k.p.x*screen->w,k.p.y*screen->h,k.r*screen->w,0xFFFFFF);
drawCircle(screen,(k.p.x+k.r/2*SDL_cosf(k.ang))*screen->w,
(k.p.y+k.r/2*SDL_sinf(k.ang))*screen->h,k.r/4*screen->w,0);
}
void DrawScreen(SDL_Surface* screen, SDL_Window* window)
{
int i;
#if 1
SDL_FillRect(screen, NULL, 0);
#else
int x, y;
for(y = 0;y < screen->h;y++)
for(x = 0;x < screen->w;x++)
setpix(screen,(float)x,(float)y,((x%255)<<16) + ((y%255)<<8) + (x+y)%255);
#endif
/* draw Touch History */
for(i = eventWrite; i < eventWrite+EVENT_BUF_SIZE; ++i) {
const SDL_Event *event = &events[i&(EVENT_BUF_SIZE-1)];
float age = (float)(i - eventWrite) / EVENT_BUF_SIZE;
float x, y;
unsigned int c, col;
if(event->type == SDL_FINGERMOTION ||
event->type == SDL_FINGERDOWN ||
event->type == SDL_FINGERUP) {
x = event->tfinger.x;
y = event->tfinger.y;
/* draw the touch: */
c = colors[event->tfinger.fingerId%7];
col = ((unsigned int)(c*(.1+.85))) | (unsigned int)(0xFF*age)<<24;
if(event->type == SDL_FINGERMOTION)
drawCircle(screen,x*screen->w,y*screen->h,5,col);
else if(event->type == SDL_FINGERDOWN)
drawCircle(screen,x*screen->w,y*screen->h,-10,col);
}
}
if(knob.p.x > 0)
drawKnob(screen,knob);
SDL_UpdateWindowSurface(window);
}
/* Returns a new SDL_Window if window is NULL or window if not. */
SDL_Window* initWindow(SDL_Window *window, int width,int height)
{
if (!window) {
window = SDL_CreateWindow("Gesture Test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height, SDL_WINDOW_RESIZABLE);
}
return window;
}
void loop()
{
SDL_Event event;
SDL_RWops *stream;
while(SDL_PollEvent(&event))
{
/* Record _all_ events */
events[eventWrite & (EVENT_BUF_SIZE-1)] = event;
eventWrite++;
switch (event.type)
{
case SDL_QUIT:
quitting = SDL_TRUE;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_i:
{
int i;
for (i = 0; i < SDL_GetNumTouchDevices(); ++i) {
SDL_TouchID id = SDL_GetTouchDevice(i);
SDL_Log("Fingers Down on device %"SDL_PRIs64": %d", id, SDL_GetNumTouchFingers(id));
}
break;
}
case SDLK_SPACE:
SDL_RecordGesture(-1);
break;
case SDLK_s:
stream = SDL_RWFromFile("gestureSave", "w");
SDL_Log("Wrote %i templates", SDL_SaveAllDollarTemplates(stream));
SDL_RWclose(stream);
break;
case SDLK_l:
stream = SDL_RWFromFile("gestureSave", "r");
SDL_Log("Loaded: %i", SDL_LoadDollarTemplates(-1, stream));
SDL_RWclose(stream);
break;
case SDLK_ESCAPE:
quitting = SDL_TRUE;
break;
}
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
if (!(window = initWindow(window, event.window.data1, event.window.data2)) ||
!(screen = SDL_GetWindowSurface(window)))
{
SDL_Quit();
exit(1);
}
}
break;
case SDL_FINGERMOTION:
#if VERBOSE
SDL_Log("Finger: %"SDL_PRIs64",x: %f, y: %f",event.tfinger.fingerId,
event.tfinger.x,event.tfinger.y);
#endif
break;
case SDL_FINGERDOWN:
#if VERBOSE
SDL_Log("Finger: %"SDL_PRIs64" down - x: %f, y: %f",
event.tfinger.fingerId,event.tfinger.x,event.tfinger.y);
#endif
break;
case SDL_FINGERUP:
#if VERBOSE
SDL_Log("Finger: %"SDL_PRIs64" up - x: %f, y: %f",
event.tfinger.fingerId,event.tfinger.x,event.tfinger.y);
#endif
break;
case SDL_MULTIGESTURE:
#if VERBOSE
SDL_Log("Multi Gesture: x = %f, y = %f, dAng = %f, dR = %f",
event.mgesture.x,
event.mgesture.y,
event.mgesture.dTheta,
event.mgesture.dDist);
SDL_Log("MG: numDownTouch = %i",event.mgesture.numFingers);
#endif
knob.p.x = event.mgesture.x;
knob.p.y = event.mgesture.y;
knob.ang += event.mgesture.dTheta;
knob.r += event.mgesture.dDist;
break;
case SDL_DOLLARGESTURE:
SDL_Log("Gesture %"SDL_PRIs64" performed, error: %f",
event.dgesture.gestureId,
event.dgesture.error);
break;
case SDL_DOLLARRECORD:
SDL_Log("Recorded gesture: %"SDL_PRIs64"",event.dgesture.gestureId);
break;
}
}
DrawScreen(screen, window);
#ifdef __EMSCRIPTEN__
if (quitting) {
emscripten_cancel_main_loop();
}
#endif
}
int main(int argc, char* argv[])
{
window = NULL;
screen = NULL;
quitting = SDL_FALSE;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* gesture variables */
knob.r = .1f;
knob.ang = 0;
if (SDL_Init(SDL_INIT_VIDEO) < 0 ) return 1;
if (!(window = initWindow(window, WIDTH, HEIGHT)) ||
!(screen = SDL_GetWindowSurface(window)))
{
SDL_Quit();
return 1;
}
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while(!quitting) {
loop();
}
#endif
SDL_Quit();
return 0;
}
| mit |
mxrrow/zaicoin | src/deps/boost/libs/bind/test/ref_fn_test.cpp | 103 | 1416 | #include <boost/config.hpp>
#if defined(BOOST_MSVC)
#pragma warning(disable: 4786) // identifier truncated in debug info
#pragma warning(disable: 4710) // function not inlined
#pragma warning(disable: 4711) // function selected for automatic inline expansion
#pragma warning(disable: 4514) // unreferenced inline removed
#endif
// ref_fn_test.cpp: ref( f )
//
// Copyright (c) 2008 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/ref.hpp>
#include <boost/detail/lightweight_test.hpp>
void f0()
{
}
void f1(int)
{
}
void f2(int, int)
{
}
void f3(int, int, int)
{
}
void f4(int, int, int, int)
{
}
void f5(int, int, int, int, int)
{
}
void f6(int, int, int, int, int, int)
{
}
void f7(int, int, int, int, int, int, int)
{
}
void f8(int, int, int, int, int, int, int, int)
{
}
void f9(int, int, int, int, int, int, int, int, int)
{
}
#define BOOST_TEST_REF( f ) BOOST_TEST( &boost::ref( f ).get() == &f )
int main()
{
int v = 0;
BOOST_TEST_REF( v );
BOOST_TEST_REF( f0 );
BOOST_TEST_REF( f1 );
BOOST_TEST_REF( f2 );
BOOST_TEST_REF( f3 );
BOOST_TEST_REF( f4 );
BOOST_TEST_REF( f5 );
BOOST_TEST_REF( f6 );
BOOST_TEST_REF( f7 );
BOOST_TEST_REF( f8 );
BOOST_TEST_REF( f9 );
return boost::report_errors();
}
| mit |
wanghuan1115/sdkbox-facebook-sample | cpp/cocos2d/extensions/Particle3D/PU/CCPUObserverTranslator.cpp | 105 | 7584 | /****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCPUObserverTranslator.h"
#include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
#include "extensions/Particle3D/PU/CCPUObserverManager.h"
#include "extensions/Particle3D/PU/CCPUObserver.h"
NS_CC_BEGIN
PUObserverTranslator::PUObserverTranslator()
:_observer(nullptr)
{
}
//-------------------------------------------------------------------------
void PUObserverTranslator::translate(PUScriptCompiler* compiler, PUAbstractNode *node)
{
PUObjectAbstractNode* obj = reinterpret_cast<PUObjectAbstractNode*>(node);
PUObjectAbstractNode* parent = obj->parent ? reinterpret_cast<PUObjectAbstractNode*>(obj->parent) : 0;
// The name of the obj is the type of the Observer
// Remark: This can be solved by using a listener, so that obj->values is filled with type + name. Something for later
std::string type;
if(!obj->name.empty())
{
type = obj->name;
}
else
{
//compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line);
return;
}
// Get the factory
//ParticleObserverFactory* particleObserverFactory = ParticleSystemManager::getSingletonPtr()->getObserverFactory(type);
//if (!particleObserverFactory)
//{
// //compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line);
// return;
//}
PUScriptTranslator *particleObserverTranlator = PUObserverManager::Instance()->getTranslator(type);
if (!particleObserverTranlator) return;
// Create the Observer
_observer = PUObserverManager::Instance()->createObserver(type);
if (!_observer)
{
//compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line);
return;
}
_observer->setObserverType(type);
if (parent && parent->context)
{
PUParticleSystem3D* system = static_cast<PUParticleSystem3D *>(parent->context);
system->addObserver(_observer);
}
else
{
//// It is an alias
//mObserver->setAliasName(parent->name);
//ParticleSystemManager::getSingletonPtr()->addAlias(mObserver);
}
// The first value is the (optional) name
std::string name;
if(!obj->values.empty())
{
getString(*obj->values.front(), &name);
_observer->setName(name);
}
// Set it in the context
obj->context = _observer;
// Run through properties
for(PUAbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)
{
if((*i)->type == ANT_PROPERTY)
{
PUPropertyAbstractNode* prop = reinterpret_cast<PUPropertyAbstractNode*>((*i));
if (prop->name == token[TOKEN_ENABLED])
{
// Property: enabled
if (passValidateProperty(compiler, prop, token[TOKEN_ENABLED], VAL_BOOL))
{
bool val;
if(getBoolean(*prop->values.front(), &val))
{
_observer->setEnabled(val);
}
}
}
else if (prop->name == token[TOKEN_OBSERVE_PARTICLE_TYPE])
{
// Property: observe_particle_type
if (passValidateProperty(compiler, prop, token[TOKEN_OBSERVE_PARTICLE_TYPE], VAL_STRING))
{
std::string val;
if(getString(*prop->values.front(), &val))
{
if (val == token[TOKEN_VISUAL_PARTICLE])
{
_observer->setParticleTypeToObserve(PUParticle3D::PT_VISUAL);
}
else if (val == token[TOKEN_EMITTER_PARTICLE])
{
_observer->setParticleTypeToObserve(PUParticle3D::PT_EMITTER);
}
else if (val == token[TOKEN_AFFECTOR_PARTICLE])
{
_observer->setParticleTypeToObserve(PUParticle3D::PT_AFFECTOR);
}
else if (val == token[TOKEN_TECHNIQUE_PARTICLE])
{
_observer->setParticleTypeToObserve(PUParticle3D::PT_TECHNIQUE);
}
else if (val == token[TOKEN_SYSTEM_PARTICLE])
{
_observer->setParticleTypeToObserve(PUParticle3D::PT_SYSTEM);
}
}
}
}
else if (prop->name == token[TOKEN_OBSERVE_INTERVAL])
{
// Property: observe_interval
if (passValidateProperty(compiler, prop, token[TOKEN_OBSERVE_INTERVAL], VAL_REAL))
{
float val;
if(getFloat(*prop->values.front(), &val))
{
_observer->setObserverInterval(val);
}
}
}
else if (prop->name == token[TOKEN_OBSERVE_UNTIL_EVENT])
{
// Property: observe_until_event
if (passValidateProperty(compiler, prop, token[TOKEN_OBSERVE_UNTIL_EVENT], VAL_BOOL))
{
bool val;
if(getBoolean(*prop->values.front(), &val))
{
_observer->setObserveUntilEvent(val);
}
}
}
else if (particleObserverTranlator->translateChildProperty(compiler, *i))
{
// Parsed the property by another translator; do nothing
}
else
{
errorUnexpectedProperty(compiler, prop);
}
}
else if((*i)->type == ANT_OBJECT)
{
if (particleObserverTranlator->translateChildObject(compiler, *i))
{
// Parsed the object by another translator; do nothing
}
else
{
processNode(compiler, *i);
}
}
else
{
errorUnexpectedToken(compiler, *i);
}
}
}
NS_CC_END
| mit |
CedarLogic/WinObjC | deps/3rdparty/iculegacy/source/layout/loengine.cpp | 362 | 3090 | /*
*
* (C) Copyright IBM Corp. 1998-2007 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "loengine.h"
#include "LayoutEngine.h"
/**
* \file
* \brief C API for complex text layout.
*/
U_NAMESPACE_USE
U_CAPI le_engine * U_EXPORT2
le_create(const le_font *font,
le_int32 scriptCode,
le_int32 languageCode,
le_int32 typo_flags,
LEErrorCode *success)
{
LEFontInstance *fontInstance = (LEFontInstance *) font;
return (le_engine *) LayoutEngine::layoutEngineFactory(fontInstance, scriptCode, languageCode, typo_flags, *success);
}
U_CAPI void U_EXPORT2
le_close(le_engine *engine)
{
LayoutEngine *le = (LayoutEngine *) engine;
delete le;
}
U_CAPI le_int32 U_EXPORT2
le_layoutChars(le_engine *engine,
const LEUnicode chars[],
le_int32 offset,
le_int32 count,
le_int32 max,
le_bool rightToLeft,
float x,
float y,
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return -1;
}
return le->layoutChars(chars, offset, count, max, rightToLeft, x, y, *success);
}
U_CAPI le_int32 U_EXPORT2
le_getGlyphCount(le_engine *engine,
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return -1;
}
return le->getGlyphCount();
}
U_CAPI void U_EXPORT2
le_getGlyphs(le_engine *engine,
LEGlyphID glyphs[],
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return;
}
le->getGlyphs(glyphs, *success);
}
U_CAPI void U_EXPORT2
le_getCharIndices(le_engine *engine,
le_int32 charIndices[],
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return;
}
le->getCharIndices(charIndices, *success);
}
U_CAPI void U_EXPORT2
le_getCharIndicesWithBase(le_engine *engine,
le_int32 charIndices[],
le_int32 indexBase,
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return;
}
le->getCharIndices(charIndices, indexBase, *success);
}
U_CAPI void U_EXPORT2
le_getGlyphPositions(le_engine *engine,
float positions[],
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return;
}
le->getGlyphPositions(positions, *success);
}
U_CAPI void U_EXPORT2
le_getGlyphPosition(le_engine *engine,
le_int32 glyphIndex,
float *x,
float *y,
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return;
}
le->getGlyphPosition(glyphIndex, *x, *y, *success);
}
U_CAPI void U_EXPORT2
le_reset(le_engine *engine,
LEErrorCode *success)
{
LayoutEngine *le = (LayoutEngine *) engine;
if (le == NULL) {
*success = LE_ILLEGAL_ARGUMENT_ERROR;
return;
}
le->reset();
}
| mit |
Torque3D-GameEngine/Torque3D | Engine/lib/sdl/src/video/directfb/SDL_DirectFB_shape.c | 107 | 4363 | /*
Simple DirectMedia Layer
Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_DIRECTFB
#include "SDL_assert.h"
#include "SDL_DirectFB_video.h"
#include "SDL_DirectFB_shape.h"
#include "SDL_DirectFB_window.h"
#include "../SDL_shape_internals.h"
SDL_Window*
DirectFB_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags) {
return SDL_CreateWindow(title,x,y,w,h,flags /* | SDL_DFB_WINDOW_SHAPED */);
}
SDL_WindowShaper*
DirectFB_CreateShaper(SDL_Window* window) {
SDL_WindowShaper* result = NULL;
result = malloc(sizeof(SDL_WindowShaper));
result->window = window;
result->mode.mode = ShapeModeDefault;
result->mode.parameters.binarizationCutoff = 1;
result->userx = result->usery = 0;
SDL_ShapeData* data = SDL_malloc(sizeof(SDL_ShapeData));
result->driverdata = data;
data->surface = NULL;
window->shaper = result;
int resized_properly = DirectFB_ResizeWindowShape(window);
SDL_assert(resized_properly == 0);
return result;
}
int
DirectFB_ResizeWindowShape(SDL_Window* window) {
SDL_ShapeData* data = window->shaper->driverdata;
SDL_assert(data != NULL);
if (window->x != -1000)
{
window->shaper->userx = window->x;
window->shaper->usery = window->y;
}
SDL_SetWindowPosition(window,-1000,-1000);
return 0;
}
int
DirectFB_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode) {
if(shaper == NULL || shape == NULL || shaper->driverdata == NULL)
return -1;
if(shape->format->Amask == 0 && SDL_SHAPEMODEALPHA(shape_mode->mode))
return -2;
if(shape->w != shaper->window->w || shape->h != shaper->window->h)
return -3;
{
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(shaper->window);
SDL_DFB_DEVICEDATA(display->device);
Uint32 *pixels;
Sint32 pitch;
Uint32 h,w;
Uint8 *src, *bitmap;
DFBSurfaceDescription dsc;
SDL_ShapeData *data = shaper->driverdata;
SDL_DFB_RELEASE(data->surface);
dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS;
dsc.width = shape->w;
dsc.height = shape->h;
dsc.caps = DSCAPS_PREMULTIPLIED;
dsc.pixelformat = DSPF_ARGB;
SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc, &data->surface));
/* Assume that shaper->alphacutoff already has a value, because SDL_SetWindowShape() should have given it one. */
SDL_DFB_ALLOC_CLEAR(bitmap, shape->w * shape->h);
SDL_CalculateShapeBitmap(shaper->mode,shape,bitmap,1);
src = bitmap;
SDL_DFB_CHECK(data->surface->Lock(data->surface, DSLF_WRITE | DSLF_READ, (void **) &pixels, &pitch));
h = shaper->window->h;
while (h--) {
for (w = 0; w < shaper->window->w; w++) {
if (*src)
pixels[w] = 0xFFFFFFFF;
else
pixels[w] = 0;
src++;
}
pixels += (pitch >> 2);
}
SDL_DFB_CHECK(data->surface->Unlock(data->surface));
SDL_DFB_FREE(bitmap);
/* FIXME: Need to call this here - Big ?? */
DirectFB_WM_RedrawLayout(SDL_GetDisplayForWindow(shaper->window)->device, shaper->window);
}
return 0;
error:
return -1;
}
#endif /* SDL_VIDEO_DRIVER_DIRECTFB */
| mit |
Duion/Torque3D | Engine/lib/sdl/src/video/SDL_blit_N.c | 110 | 93384 | /*
Simple DirectMedia Layer
Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
#include "SDL_video.h"
#include "SDL_endian.h"
#include "SDL_cpuinfo.h"
#include "SDL_blit.h"
#include "SDL_assert.h"
/* Functions to blit from N-bit surfaces to other surfaces */
#if SDL_ALTIVEC_BLITTERS
#ifdef HAVE_ALTIVEC_H
#include <altivec.h>
#endif
#ifdef __MACOSX__
#include <sys/sysctl.h>
static size_t
GetL3CacheSize(void)
{
const char key[] = "hw.l3cachesize";
u_int64_t result = 0;
size_t typeSize = sizeof(result);
int err = sysctlbyname(key, &result, &typeSize, NULL, 0);
if (0 != err)
return 0;
return result;
}
#else
static size_t
GetL3CacheSize(void)
{
/* XXX: Just guess G4 */
return 2097152;
}
#endif /* __MACOSX__ */
#if (defined(__MACOSX__) && (__GNUC__ < 4))
#define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \
(vector unsigned char) ( a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p )
#define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \
(vector unsigned short) ( a,b,c,d,e,f,g,h )
#else
#define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \
(vector unsigned char) { a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p }
#define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \
(vector unsigned short) { a,b,c,d,e,f,g,h }
#endif
#define UNALIGNED_PTR(x) (((size_t) x) & 0x0000000F)
#define VSWIZZLE32(a,b,c,d) (vector unsigned char) \
( 0x00+a, 0x00+b, 0x00+c, 0x00+d, \
0x04+a, 0x04+b, 0x04+c, 0x04+d, \
0x08+a, 0x08+b, 0x08+c, 0x08+d, \
0x0C+a, 0x0C+b, 0x0C+c, 0x0C+d )
#define MAKE8888(dstfmt, r, g, b, a) \
( ((r<<dstfmt->Rshift)&dstfmt->Rmask) | \
((g<<dstfmt->Gshift)&dstfmt->Gmask) | \
((b<<dstfmt->Bshift)&dstfmt->Bmask) | \
((a<<dstfmt->Ashift)&dstfmt->Amask) )
/*
* Data Stream Touch...Altivec cache prefetching.
*
* Don't use this on a G5...however, the speed boost is very significant
* on a G4.
*/
#define DST_CHAN_SRC 1
#define DST_CHAN_DEST 2
/* macro to set DST control word value... */
#define DST_CTRL(size, count, stride) \
(((size) << 24) | ((count) << 16) | (stride))
#define VEC_ALIGNER(src) ((UNALIGNED_PTR(src)) \
? vec_lvsl(0, src) \
: vec_add(vec_lvsl(8, src), vec_splat_u8(8)))
/* Calculate the permute vector used for 32->32 swizzling */
static vector unsigned char
calc_swizzle32(const SDL_PixelFormat * srcfmt, const SDL_PixelFormat * dstfmt)
{
/*
* We have to assume that the bits that aren't used by other
* colors is alpha, and it's one complete byte, since some formats
* leave alpha with a zero mask, but we should still swizzle the bits.
*/
/* ARGB */
const static const struct SDL_PixelFormat default_pixel_format = {
0, NULL, 0, 0,
{0, 0},
0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000,
0, 0, 0, 0,
16, 8, 0, 24,
0, NULL
};
if (!srcfmt) {
srcfmt = &default_pixel_format;
}
if (!dstfmt) {
dstfmt = &default_pixel_format;
}
const vector unsigned char plus = VECUINT8_LITERAL(0x00, 0x00, 0x00, 0x00,
0x04, 0x04, 0x04, 0x04,
0x08, 0x08, 0x08, 0x08,
0x0C, 0x0C, 0x0C,
0x0C);
vector unsigned char vswiz;
vector unsigned int srcvec;
#define RESHIFT(X) (3 - ((X) >> 3))
Uint32 rmask = RESHIFT(srcfmt->Rshift) << (dstfmt->Rshift);
Uint32 gmask = RESHIFT(srcfmt->Gshift) << (dstfmt->Gshift);
Uint32 bmask = RESHIFT(srcfmt->Bshift) << (dstfmt->Bshift);
Uint32 amask;
/* Use zero for alpha if either surface doesn't have alpha */
if (dstfmt->Amask) {
amask =
((srcfmt->Amask) ? RESHIFT(srcfmt->
Ashift) : 0x10) << (dstfmt->Ashift);
} else {
amask =
0x10101010 & ((dstfmt->Rmask | dstfmt->Gmask | dstfmt->Bmask) ^
0xFFFFFFFF);
}
#undef RESHIFT
((unsigned int *) (char *) &srcvec)[0] = (rmask | gmask | bmask | amask);
vswiz = vec_add(plus, (vector unsigned char) vec_splat(srcvec, 0));
return (vswiz);
}
static void Blit_RGB888_RGB565(SDL_BlitInfo * info);
static void
Blit_RGB888_RGB565Altivec(SDL_BlitInfo * info)
{
int height = info->dst_h;
Uint8 *src = (Uint8 *) info->src;
int srcskip = info->src_skip;
Uint8 *dst = (Uint8 *) info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
vector unsigned char valpha = vec_splat_u8(0);
vector unsigned char vpermute = calc_swizzle32(srcfmt, NULL);
vector unsigned char vgmerge = VECUINT8_LITERAL(0x00, 0x02, 0x00, 0x06,
0x00, 0x0a, 0x00, 0x0e,
0x00, 0x12, 0x00, 0x16,
0x00, 0x1a, 0x00, 0x1e);
vector unsigned short v1 = vec_splat_u16(1);
vector unsigned short v3 = vec_splat_u16(3);
vector unsigned short v3f =
VECUINT16_LITERAL(0x003f, 0x003f, 0x003f, 0x003f,
0x003f, 0x003f, 0x003f, 0x003f);
vector unsigned short vfc =
VECUINT16_LITERAL(0x00fc, 0x00fc, 0x00fc, 0x00fc,
0x00fc, 0x00fc, 0x00fc, 0x00fc);
vector unsigned short vf800 = (vector unsigned short) vec_splat_u8(-7);
vf800 = vec_sl(vf800, vec_splat_u16(8));
while (height--) {
vector unsigned char valigner;
vector unsigned char voverflow;
vector unsigned char vsrc;
int width = info->dst_w;
int extrawidth;
/* do scalar until we can align... */
#define ONE_PIXEL_BLEND(condition, widthvar) \
while (condition) { \
Uint32 Pixel; \
unsigned sR, sG, sB, sA; \
DISEMBLE_RGBA((Uint8 *)src, 4, srcfmt, Pixel, \
sR, sG, sB, sA); \
*(Uint16 *)(dst) = (((sR << 8) & 0x0000F800) | \
((sG << 3) & 0x000007E0) | \
((sB >> 3) & 0x0000001F)); \
dst += 2; \
src += 4; \
widthvar--; \
}
ONE_PIXEL_BLEND(((UNALIGNED_PTR(dst)) && (width)), width);
/* After all that work, here's the vector part! */
extrawidth = (width % 8); /* trailing unaligned stores */
width -= extrawidth;
vsrc = vec_ld(0, src);
valigner = VEC_ALIGNER(src);
while (width) {
vector unsigned short vpixel, vrpixel, vgpixel, vbpixel;
vector unsigned int vsrc1, vsrc2;
vector unsigned char vdst;
voverflow = vec_ld(15, src);
vsrc = vec_perm(vsrc, voverflow, valigner);
vsrc1 = (vector unsigned int) vec_perm(vsrc, valpha, vpermute);
src += 16;
vsrc = voverflow;
voverflow = vec_ld(15, src);
vsrc = vec_perm(vsrc, voverflow, valigner);
vsrc2 = (vector unsigned int) vec_perm(vsrc, valpha, vpermute);
/* 1555 */
vpixel = (vector unsigned short) vec_packpx(vsrc1, vsrc2);
vgpixel = (vector unsigned short) vec_perm(vsrc1, vsrc2, vgmerge);
vgpixel = vec_and(vgpixel, vfc);
vgpixel = vec_sl(vgpixel, v3);
vrpixel = vec_sl(vpixel, v1);
vrpixel = vec_and(vrpixel, vf800);
vbpixel = vec_and(vpixel, v3f);
vdst =
vec_or((vector unsigned char) vrpixel,
(vector unsigned char) vgpixel);
/* 565 */
vdst = vec_or(vdst, (vector unsigned char) vbpixel);
vec_st(vdst, 0, dst);
width -= 8;
src += 16;
dst += 16;
vsrc = voverflow;
}
SDL_assert(width == 0);
/* do scalar until we can align... */
ONE_PIXEL_BLEND((extrawidth), extrawidth);
#undef ONE_PIXEL_BLEND
src += srcskip; /* move to next row, accounting for pitch. */
dst += dstskip;
}
}
static void
Blit_RGB565_32Altivec(SDL_BlitInfo * info)
{
int height = info->dst_h;
Uint8 *src = (Uint8 *) info->src;
int srcskip = info->src_skip;
Uint8 *dst = (Uint8 *) info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
unsigned alpha;
vector unsigned char valpha;
vector unsigned char vpermute;
vector unsigned short vf800;
vector unsigned int v8 = vec_splat_u32(8);
vector unsigned int v16 = vec_add(v8, v8);
vector unsigned short v2 = vec_splat_u16(2);
vector unsigned short v3 = vec_splat_u16(3);
/*
0x10 - 0x1f is the alpha
0x00 - 0x0e evens are the red
0x01 - 0x0f odds are zero
*/
vector unsigned char vredalpha1 = VECUINT8_LITERAL(0x10, 0x00, 0x01, 0x01,
0x10, 0x02, 0x01, 0x01,
0x10, 0x04, 0x01, 0x01,
0x10, 0x06, 0x01,
0x01);
vector unsigned char vredalpha2 =
(vector unsigned
char) (vec_add((vector unsigned int) vredalpha1, vec_sl(v8, v16))
);
/*
0x00 - 0x0f is ARxx ARxx ARxx ARxx
0x11 - 0x0f odds are blue
*/
vector unsigned char vblue1 = VECUINT8_LITERAL(0x00, 0x01, 0x02, 0x11,
0x04, 0x05, 0x06, 0x13,
0x08, 0x09, 0x0a, 0x15,
0x0c, 0x0d, 0x0e, 0x17);
vector unsigned char vblue2 =
(vector unsigned char) (vec_add((vector unsigned int) vblue1, v8)
);
/*
0x00 - 0x0f is ARxB ARxB ARxB ARxB
0x10 - 0x0e evens are green
*/
vector unsigned char vgreen1 = VECUINT8_LITERAL(0x00, 0x01, 0x10, 0x03,
0x04, 0x05, 0x12, 0x07,
0x08, 0x09, 0x14, 0x0b,
0x0c, 0x0d, 0x16, 0x0f);
vector unsigned char vgreen2 =
(vector unsigned
char) (vec_add((vector unsigned int) vgreen1, vec_sl(v8, v8))
);
SDL_assert(srcfmt->BytesPerPixel == 2);
SDL_assert(dstfmt->BytesPerPixel == 4);
vf800 = (vector unsigned short) vec_splat_u8(-7);
vf800 = vec_sl(vf800, vec_splat_u16(8));
if (dstfmt->Amask && info->a) {
((unsigned char *) &valpha)[0] = alpha = info->a;
valpha = vec_splat(valpha, 0);
} else {
alpha = 0;
valpha = vec_splat_u8(0);
}
vpermute = calc_swizzle32(NULL, dstfmt);
while (height--) {
vector unsigned char valigner;
vector unsigned char voverflow;
vector unsigned char vsrc;
int width = info->dst_w;
int extrawidth;
/* do scalar until we can align... */
#define ONE_PIXEL_BLEND(condition, widthvar) \
while (condition) { \
unsigned sR, sG, sB; \
unsigned short Pixel = *((unsigned short *)src); \
sR = (Pixel >> 8) & 0xf8; \
sG = (Pixel >> 3) & 0xfc; \
sB = (Pixel << 3) & 0xf8; \
ASSEMBLE_RGBA(dst, 4, dstfmt, sR, sG, sB, alpha); \
src += 2; \
dst += 4; \
widthvar--; \
}
ONE_PIXEL_BLEND(((UNALIGNED_PTR(dst)) && (width)), width);
/* After all that work, here's the vector part! */
extrawidth = (width % 8); /* trailing unaligned stores */
width -= extrawidth;
vsrc = vec_ld(0, src);
valigner = VEC_ALIGNER(src);
while (width) {
vector unsigned short vR, vG, vB;
vector unsigned char vdst1, vdst2;
voverflow = vec_ld(15, src);
vsrc = vec_perm(vsrc, voverflow, valigner);
vR = vec_and((vector unsigned short) vsrc, vf800);
vB = vec_sl((vector unsigned short) vsrc, v3);
vG = vec_sl(vB, v2);
vdst1 =
(vector unsigned char) vec_perm((vector unsigned char) vR,
valpha, vredalpha1);
vdst1 = vec_perm(vdst1, (vector unsigned char) vB, vblue1);
vdst1 = vec_perm(vdst1, (vector unsigned char) vG, vgreen1);
vdst1 = vec_perm(vdst1, valpha, vpermute);
vec_st(vdst1, 0, dst);
vdst2 =
(vector unsigned char) vec_perm((vector unsigned char) vR,
valpha, vredalpha2);
vdst2 = vec_perm(vdst2, (vector unsigned char) vB, vblue2);
vdst2 = vec_perm(vdst2, (vector unsigned char) vG, vgreen2);
vdst2 = vec_perm(vdst2, valpha, vpermute);
vec_st(vdst2, 16, dst);
width -= 8;
dst += 32;
src += 16;
vsrc = voverflow;
}
SDL_assert(width == 0);
/* do scalar until we can align... */
ONE_PIXEL_BLEND((extrawidth), extrawidth);
#undef ONE_PIXEL_BLEND
src += srcskip; /* move to next row, accounting for pitch. */
dst += dstskip;
}
}
static void
Blit_RGB555_32Altivec(SDL_BlitInfo * info)
{
int height = info->dst_h;
Uint8 *src = (Uint8 *) info->src;
int srcskip = info->src_skip;
Uint8 *dst = (Uint8 *) info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
unsigned alpha;
vector unsigned char valpha;
vector unsigned char vpermute;
vector unsigned short vf800;
vector unsigned int v8 = vec_splat_u32(8);
vector unsigned int v16 = vec_add(v8, v8);
vector unsigned short v1 = vec_splat_u16(1);
vector unsigned short v3 = vec_splat_u16(3);
/*
0x10 - 0x1f is the alpha
0x00 - 0x0e evens are the red
0x01 - 0x0f odds are zero
*/
vector unsigned char vredalpha1 = VECUINT8_LITERAL(0x10, 0x00, 0x01, 0x01,
0x10, 0x02, 0x01, 0x01,
0x10, 0x04, 0x01, 0x01,
0x10, 0x06, 0x01,
0x01);
vector unsigned char vredalpha2 =
(vector unsigned
char) (vec_add((vector unsigned int) vredalpha1, vec_sl(v8, v16))
);
/*
0x00 - 0x0f is ARxx ARxx ARxx ARxx
0x11 - 0x0f odds are blue
*/
vector unsigned char vblue1 = VECUINT8_LITERAL(0x00, 0x01, 0x02, 0x11,
0x04, 0x05, 0x06, 0x13,
0x08, 0x09, 0x0a, 0x15,
0x0c, 0x0d, 0x0e, 0x17);
vector unsigned char vblue2 =
(vector unsigned char) (vec_add((vector unsigned int) vblue1, v8)
);
/*
0x00 - 0x0f is ARxB ARxB ARxB ARxB
0x10 - 0x0e evens are green
*/
vector unsigned char vgreen1 = VECUINT8_LITERAL(0x00, 0x01, 0x10, 0x03,
0x04, 0x05, 0x12, 0x07,
0x08, 0x09, 0x14, 0x0b,
0x0c, 0x0d, 0x16, 0x0f);
vector unsigned char vgreen2 =
(vector unsigned
char) (vec_add((vector unsigned int) vgreen1, vec_sl(v8, v8))
);
SDL_assert(srcfmt->BytesPerPixel == 2);
SDL_assert(dstfmt->BytesPerPixel == 4);
vf800 = (vector unsigned short) vec_splat_u8(-7);
vf800 = vec_sl(vf800, vec_splat_u16(8));
if (dstfmt->Amask && info->a) {
((unsigned char *) &valpha)[0] = alpha = info->a;
valpha = vec_splat(valpha, 0);
} else {
alpha = 0;
valpha = vec_splat_u8(0);
}
vpermute = calc_swizzle32(NULL, dstfmt);
while (height--) {
vector unsigned char valigner;
vector unsigned char voverflow;
vector unsigned char vsrc;
int width = info->dst_w;
int extrawidth;
/* do scalar until we can align... */
#define ONE_PIXEL_BLEND(condition, widthvar) \
while (condition) { \
unsigned sR, sG, sB; \
unsigned short Pixel = *((unsigned short *)src); \
sR = (Pixel >> 7) & 0xf8; \
sG = (Pixel >> 2) & 0xf8; \
sB = (Pixel << 3) & 0xf8; \
ASSEMBLE_RGBA(dst, 4, dstfmt, sR, sG, sB, alpha); \
src += 2; \
dst += 4; \
widthvar--; \
}
ONE_PIXEL_BLEND(((UNALIGNED_PTR(dst)) && (width)), width);
/* After all that work, here's the vector part! */
extrawidth = (width % 8); /* trailing unaligned stores */
width -= extrawidth;
vsrc = vec_ld(0, src);
valigner = VEC_ALIGNER(src);
while (width) {
vector unsigned short vR, vG, vB;
vector unsigned char vdst1, vdst2;
voverflow = vec_ld(15, src);
vsrc = vec_perm(vsrc, voverflow, valigner);
vR = vec_and(vec_sl((vector unsigned short) vsrc, v1), vf800);
vB = vec_sl((vector unsigned short) vsrc, v3);
vG = vec_sl(vB, v3);
vdst1 =
(vector unsigned char) vec_perm((vector unsigned char) vR,
valpha, vredalpha1);
vdst1 = vec_perm(vdst1, (vector unsigned char) vB, vblue1);
vdst1 = vec_perm(vdst1, (vector unsigned char) vG, vgreen1);
vdst1 = vec_perm(vdst1, valpha, vpermute);
vec_st(vdst1, 0, dst);
vdst2 =
(vector unsigned char) vec_perm((vector unsigned char) vR,
valpha, vredalpha2);
vdst2 = vec_perm(vdst2, (vector unsigned char) vB, vblue2);
vdst2 = vec_perm(vdst2, (vector unsigned char) vG, vgreen2);
vdst2 = vec_perm(vdst2, valpha, vpermute);
vec_st(vdst2, 16, dst);
width -= 8;
dst += 32;
src += 16;
vsrc = voverflow;
}
SDL_assert(width == 0);
/* do scalar until we can align... */
ONE_PIXEL_BLEND((extrawidth), extrawidth);
#undef ONE_PIXEL_BLEND
src += srcskip; /* move to next row, accounting for pitch. */
dst += dstskip;
}
}
static void BlitNtoNKey(SDL_BlitInfo * info);
static void BlitNtoNKeyCopyAlpha(SDL_BlitInfo * info);
static void
Blit32to32KeyAltivec(SDL_BlitInfo * info)
{
int height = info->dst_h;
Uint32 *srcp = (Uint32 *) info->src;
int srcskip = info->src_skip / 4;
Uint32 *dstp = (Uint32 *) info->dst;
int dstskip = info->dst_skip / 4;
SDL_PixelFormat *srcfmt = info->src_fmt;
int srcbpp = srcfmt->BytesPerPixel;
SDL_PixelFormat *dstfmt = info->dst_fmt;
int dstbpp = dstfmt->BytesPerPixel;
int copy_alpha = (srcfmt->Amask && dstfmt->Amask);
unsigned alpha = dstfmt->Amask ? info->a : 0;
Uint32 rgbmask = srcfmt->Rmask | srcfmt->Gmask | srcfmt->Bmask;
Uint32 ckey = info->colorkey;
vector unsigned int valpha;
vector unsigned char vpermute;
vector unsigned char vzero;
vector unsigned int vckey;
vector unsigned int vrgbmask;
vpermute = calc_swizzle32(srcfmt, dstfmt);
if (info->dst_w < 16) {
if (copy_alpha) {
BlitNtoNKeyCopyAlpha(info);
} else {
BlitNtoNKey(info);
}
return;
}
vzero = vec_splat_u8(0);
if (alpha) {
((unsigned char *) &valpha)[0] = (unsigned char) alpha;
valpha =
(vector unsigned int) vec_splat((vector unsigned char) valpha, 0);
} else {
valpha = (vector unsigned int) vzero;
}
ckey &= rgbmask;
((unsigned int *) (char *) &vckey)[0] = ckey;
vckey = vec_splat(vckey, 0);
((unsigned int *) (char *) &vrgbmask)[0] = rgbmask;
vrgbmask = vec_splat(vrgbmask, 0);
while (height--) {
#define ONE_PIXEL_BLEND(condition, widthvar) \
if (copy_alpha) { \
while (condition) { \
Uint32 Pixel; \
unsigned sR, sG, sB, sA; \
DISEMBLE_RGBA((Uint8 *)srcp, srcbpp, srcfmt, Pixel, \
sR, sG, sB, sA); \
if ( (Pixel & rgbmask) != ckey ) { \
ASSEMBLE_RGBA((Uint8 *)dstp, dstbpp, dstfmt, \
sR, sG, sB, sA); \
} \
dstp = (Uint32 *) (((Uint8 *) dstp) + dstbpp); \
srcp = (Uint32 *) (((Uint8 *) srcp) + srcbpp); \
widthvar--; \
} \
} else { \
while (condition) { \
Uint32 Pixel; \
unsigned sR, sG, sB; \
RETRIEVE_RGB_PIXEL((Uint8 *)srcp, srcbpp, Pixel); \
if ( Pixel != ckey ) { \
RGB_FROM_PIXEL(Pixel, srcfmt, sR, sG, sB); \
ASSEMBLE_RGBA((Uint8 *)dstp, dstbpp, dstfmt, \
sR, sG, sB, alpha); \
} \
dstp = (Uint32 *) (((Uint8 *)dstp) + dstbpp); \
srcp = (Uint32 *) (((Uint8 *)srcp) + srcbpp); \
widthvar--; \
} \
}
int width = info->dst_w;
ONE_PIXEL_BLEND((UNALIGNED_PTR(dstp)) && (width), width);
SDL_assert(width > 0);
if (width > 0) {
int extrawidth = (width % 4);
vector unsigned char valigner = VEC_ALIGNER(srcp);
vector unsigned int vs = vec_ld(0, srcp);
width -= extrawidth;
SDL_assert(width >= 4);
while (width) {
vector unsigned char vsel;
vector unsigned int vd;
vector unsigned int voverflow = vec_ld(15, srcp);
/* load the source vec */
vs = vec_perm(vs, voverflow, valigner);
/* vsel is set for items that match the key */
vsel = (vector unsigned char) vec_and(vs, vrgbmask);
vsel = (vector unsigned char) vec_cmpeq(vs, vckey);
/* permute the src vec to the dest format */
vs = vec_perm(vs, valpha, vpermute);
/* load the destination vec */
vd = vec_ld(0, dstp);
/* select the source and dest into vs */
vd = (vector unsigned int) vec_sel((vector unsigned char) vs,
(vector unsigned char) vd,
vsel);
vec_st(vd, 0, dstp);
srcp += 4;
width -= 4;
dstp += 4;
vs = voverflow;
}
ONE_PIXEL_BLEND((extrawidth), extrawidth);
#undef ONE_PIXEL_BLEND
srcp += srcskip;
dstp += dstskip;
}
}
}
/* Altivec code to swizzle one 32-bit surface to a different 32-bit format. */
/* Use this on a G5 */
static void
ConvertAltivec32to32_noprefetch(SDL_BlitInfo * info)
{
int height = info->dst_h;
Uint32 *src = (Uint32 *) info->src;
int srcskip = info->src_skip / 4;
Uint32 *dst = (Uint32 *) info->dst;
int dstskip = info->dst_skip / 4;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
vector unsigned int vzero = vec_splat_u32(0);
vector unsigned char vpermute = calc_swizzle32(srcfmt, dstfmt);
if (dstfmt->Amask && !srcfmt->Amask) {
if (info->a) {
vector unsigned char valpha;
((unsigned char *) &valpha)[0] = info->a;
vzero = (vector unsigned int) vec_splat(valpha, 0);
}
}
SDL_assert(srcfmt->BytesPerPixel == 4);
SDL_assert(dstfmt->BytesPerPixel == 4);
while (height--) {
vector unsigned char valigner;
vector unsigned int vbits;
vector unsigned int voverflow;
Uint32 bits;
Uint8 r, g, b, a;
int width = info->dst_w;
int extrawidth;
/* do scalar until we can align... */
while ((UNALIGNED_PTR(dst)) && (width)) {
bits = *(src++);
RGBA_FROM_8888(bits, srcfmt, r, g, b, a);
if(!srcfmt->Amask)
a = info->a;
*(dst++) = MAKE8888(dstfmt, r, g, b, a);
width--;
}
/* After all that work, here's the vector part! */
extrawidth = (width % 4);
width -= extrawidth;
valigner = VEC_ALIGNER(src);
vbits = vec_ld(0, src);
while (width) {
voverflow = vec_ld(15, src);
src += 4;
width -= 4;
vbits = vec_perm(vbits, voverflow, valigner); /* src is ready. */
vbits = vec_perm(vbits, vzero, vpermute); /* swizzle it. */
vec_st(vbits, 0, dst); /* store it back out. */
dst += 4;
vbits = voverflow;
}
SDL_assert(width == 0);
/* cover pixels at the end of the row that didn't fit in 16 bytes. */
while (extrawidth) {
bits = *(src++); /* max 7 pixels, don't bother with prefetch. */
RGBA_FROM_8888(bits, srcfmt, r, g, b, a);
if(!srcfmt->Amask)
a = info->a;
*(dst++) = MAKE8888(dstfmt, r, g, b, a);
extrawidth--;
}
src += srcskip;
dst += dstskip;
}
}
/* Altivec code to swizzle one 32-bit surface to a different 32-bit format. */
/* Use this on a G4 */
static void
ConvertAltivec32to32_prefetch(SDL_BlitInfo * info)
{
const int scalar_dst_lead = sizeof(Uint32) * 4;
const int vector_dst_lead = sizeof(Uint32) * 16;
int height = info->dst_h;
Uint32 *src = (Uint32 *) info->src;
int srcskip = info->src_skip / 4;
Uint32 *dst = (Uint32 *) info->dst;
int dstskip = info->dst_skip / 4;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
vector unsigned int vzero = vec_splat_u32(0);
vector unsigned char vpermute = calc_swizzle32(srcfmt, dstfmt);
if (dstfmt->Amask && !srcfmt->Amask) {
if (info->a) {
vector unsigned char valpha;
((unsigned char *) &valpha)[0] = info->a;
vzero = (vector unsigned int) vec_splat(valpha, 0);
}
}
SDL_assert(srcfmt->BytesPerPixel == 4);
SDL_assert(dstfmt->BytesPerPixel == 4);
while (height--) {
vector unsigned char valigner;
vector unsigned int vbits;
vector unsigned int voverflow;
Uint32 bits;
Uint8 r, g, b, a;
int width = info->dst_w;
int extrawidth;
/* do scalar until we can align... */
while ((UNALIGNED_PTR(dst)) && (width)) {
vec_dstt(src + scalar_dst_lead, DST_CTRL(2, 32, 1024),
DST_CHAN_SRC);
vec_dstst(dst + scalar_dst_lead, DST_CTRL(2, 32, 1024),
DST_CHAN_DEST);
bits = *(src++);
RGBA_FROM_8888(bits, srcfmt, r, g, b, a);
if(!srcfmt->Amask)
a = info->a;
*(dst++) = MAKE8888(dstfmt, r, g, b, a);
width--;
}
/* After all that work, here's the vector part! */
extrawidth = (width % 4);
width -= extrawidth;
valigner = VEC_ALIGNER(src);
vbits = vec_ld(0, src);
while (width) {
vec_dstt(src + vector_dst_lead, DST_CTRL(2, 32, 1024),
DST_CHAN_SRC);
vec_dstst(dst + vector_dst_lead, DST_CTRL(2, 32, 1024),
DST_CHAN_DEST);
voverflow = vec_ld(15, src);
src += 4;
width -= 4;
vbits = vec_perm(vbits, voverflow, valigner); /* src is ready. */
vbits = vec_perm(vbits, vzero, vpermute); /* swizzle it. */
vec_st(vbits, 0, dst); /* store it back out. */
dst += 4;
vbits = voverflow;
}
SDL_assert(width == 0);
/* cover pixels at the end of the row that didn't fit in 16 bytes. */
while (extrawidth) {
bits = *(src++); /* max 7 pixels, don't bother with prefetch. */
RGBA_FROM_8888(bits, srcfmt, r, g, b, a);
if(!srcfmt->Amask)
a = info->a;
*(dst++) = MAKE8888(dstfmt, r, g, b, a);
extrawidth--;
}
src += srcskip;
dst += dstskip;
}
vec_dss(DST_CHAN_SRC);
vec_dss(DST_CHAN_DEST);
}
static Uint32
GetBlitFeatures(void)
{
static Uint32 features = 0xffffffff;
if (features == 0xffffffff) {
/* Provide an override for testing .. */
char *override = SDL_getenv("SDL_ALTIVEC_BLIT_FEATURES");
if (override) {
features = 0;
SDL_sscanf(override, "%u", &features);
} else {
features = (0
/* Feature 1 is has-MMX */
| ((SDL_HasMMX())? 1 : 0)
/* Feature 2 is has-AltiVec */
| ((SDL_HasAltiVec())? 2 : 0)
/* Feature 4 is dont-use-prefetch */
/* !!!! FIXME: Check for G5 or later, not the cache size! Always prefetch on a G4. */
| ((GetL3CacheSize() == 0) ? 4 : 0)
);
}
}
return features;
}
#if __MWERKS__
#pragma altivec_model off
#endif
#else
/* Feature 1 is has-MMX */
#define GetBlitFeatures() ((Uint32)(SDL_HasMMX() ? 1 : 0))
#endif
/* This is now endian dependent */
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define HI 1
#define LO 0
#else /* SDL_BYTEORDER == SDL_BIG_ENDIAN */
#define HI 0
#define LO 1
#endif
/* Special optimized blit for RGB 8-8-8 --> RGB 3-3-2 */
#define RGB888_RGB332(dst, src) { \
dst = (Uint8)((((src)&0x00E00000)>>16)| \
(((src)&0x0000E000)>>11)| \
(((src)&0x000000C0)>>6)); \
}
static void
Blit_RGB888_index8(SDL_BlitInfo * info)
{
#ifndef USE_DUFFS_LOOP
int c;
#endif
int width, height;
Uint32 *src;
const Uint8 *map;
Uint8 *dst;
int srcskip, dstskip;
/* Set up some basic variables */
width = info->dst_w;
height = info->dst_h;
src = (Uint32 *) info->src;
srcskip = info->src_skip / 4;
dst = info->dst;
dstskip = info->dst_skip;
map = info->table;
if (map == NULL) {
while (height--) {
#ifdef USE_DUFFS_LOOP
/* *INDENT-OFF* */
DUFFS_LOOP(
RGB888_RGB332(*dst++, *src);
, width);
/* *INDENT-ON* */
#else
for (c = width / 4; c; --c) {
/* Pack RGB into 8bit pixel */
++src;
RGB888_RGB332(*dst++, *src);
++src;
RGB888_RGB332(*dst++, *src);
++src;
RGB888_RGB332(*dst++, *src);
++src;
}
switch (width & 3) {
case 3:
RGB888_RGB332(*dst++, *src);
++src;
case 2:
RGB888_RGB332(*dst++, *src);
++src;
case 1:
RGB888_RGB332(*dst++, *src);
++src;
}
#endif /* USE_DUFFS_LOOP */
src += srcskip;
dst += dstskip;
}
} else {
int Pixel;
while (height--) {
#ifdef USE_DUFFS_LOOP
/* *INDENT-OFF* */
DUFFS_LOOP(
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
, width);
/* *INDENT-ON* */
#else
for (c = width / 4; c; --c) {
/* Pack RGB into 8bit pixel */
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
}
switch (width & 3) {
case 3:
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
case 2:
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
case 1:
RGB888_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
}
#endif /* USE_DUFFS_LOOP */
src += srcskip;
dst += dstskip;
}
}
}
/* Special optimized blit for RGB 10-10-10 --> RGB 3-3-2 */
#define RGB101010_RGB332(dst, src) { \
dst = (Uint8)((((src)&0x38000000)>>22)| \
(((src)&0x000E0000)>>15)| \
(((src)&0x00000300)>>8)); \
}
static void
Blit_RGB101010_index8(SDL_BlitInfo * info)
{
#ifndef USE_DUFFS_LOOP
int c;
#endif
int width, height;
Uint32 *src;
const Uint8 *map;
Uint8 *dst;
int srcskip, dstskip;
/* Set up some basic variables */
width = info->dst_w;
height = info->dst_h;
src = (Uint32 *) info->src;
srcskip = info->src_skip / 4;
dst = info->dst;
dstskip = info->dst_skip;
map = info->table;
if (map == NULL) {
while (height--) {
#ifdef USE_DUFFS_LOOP
/* *INDENT-OFF* */
DUFFS_LOOP(
RGB101010_RGB332(*dst++, *src);
, width);
/* *INDENT-ON* */
#else
for (c = width / 4; c; --c) {
/* Pack RGB into 8bit pixel */
++src;
RGB101010_RGB332(*dst++, *src);
++src;
RGB101010_RGB332(*dst++, *src);
++src;
RGB101010_RGB332(*dst++, *src);
++src;
}
switch (width & 3) {
case 3:
RGB101010_RGB332(*dst++, *src);
++src;
case 2:
RGB101010_RGB332(*dst++, *src);
++src;
case 1:
RGB101010_RGB332(*dst++, *src);
++src;
}
#endif /* USE_DUFFS_LOOP */
src += srcskip;
dst += dstskip;
}
} else {
int Pixel;
while (height--) {
#ifdef USE_DUFFS_LOOP
/* *INDENT-OFF* */
DUFFS_LOOP(
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
, width);
/* *INDENT-ON* */
#else
for (c = width / 4; c; --c) {
/* Pack RGB into 8bit pixel */
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
}
switch (width & 3) {
case 3:
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
case 2:
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
case 1:
RGB101010_RGB332(Pixel, *src);
*dst++ = map[Pixel];
++src;
}
#endif /* USE_DUFFS_LOOP */
src += srcskip;
dst += dstskip;
}
}
}
/* Special optimized blit for RGB 8-8-8 --> RGB 5-5-5 */
#define RGB888_RGB555(dst, src) { \
*(Uint16 *)(dst) = (Uint16)((((*src)&0x00F80000)>>9)| \
(((*src)&0x0000F800)>>6)| \
(((*src)&0x000000F8)>>3)); \
}
#define RGB888_RGB555_TWO(dst, src) { \
*(Uint32 *)(dst) = (((((src[HI])&0x00F80000)>>9)| \
(((src[HI])&0x0000F800)>>6)| \
(((src[HI])&0x000000F8)>>3))<<16)| \
(((src[LO])&0x00F80000)>>9)| \
(((src[LO])&0x0000F800)>>6)| \
(((src[LO])&0x000000F8)>>3); \
}
static void
Blit_RGB888_RGB555(SDL_BlitInfo * info)
{
#ifndef USE_DUFFS_LOOP
int c;
#endif
int width, height;
Uint32 *src;
Uint16 *dst;
int srcskip, dstskip;
/* Set up some basic variables */
width = info->dst_w;
height = info->dst_h;
src = (Uint32 *) info->src;
srcskip = info->src_skip / 4;
dst = (Uint16 *) info->dst;
dstskip = info->dst_skip / 2;
#ifdef USE_DUFFS_LOOP
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
RGB888_RGB555(dst, src);
++src;
++dst;
, width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
#else
/* Memory align at 4-byte boundary, if necessary */
if ((long) dst & 0x03) {
/* Don't do anything if width is 0 */
if (width == 0) {
return;
}
--width;
while (height--) {
/* Perform copy alignment */
RGB888_RGB555(dst, src);
++src;
++dst;
/* Copy in 4 pixel chunks */
for (c = width / 4; c; --c) {
RGB888_RGB555_TWO(dst, src);
src += 2;
dst += 2;
RGB888_RGB555_TWO(dst, src);
src += 2;
dst += 2;
}
/* Get any leftovers */
switch (width & 3) {
case 3:
RGB888_RGB555(dst, src);
++src;
++dst;
case 2:
RGB888_RGB555_TWO(dst, src);
src += 2;
dst += 2;
break;
case 1:
RGB888_RGB555(dst, src);
++src;
++dst;
break;
}
src += srcskip;
dst += dstskip;
}
} else {
while (height--) {
/* Copy in 4 pixel chunks */
for (c = width / 4; c; --c) {
RGB888_RGB555_TWO(dst, src);
src += 2;
dst += 2;
RGB888_RGB555_TWO(dst, src);
src += 2;
dst += 2;
}
/* Get any leftovers */
switch (width & 3) {
case 3:
RGB888_RGB555(dst, src);
++src;
++dst;
case 2:
RGB888_RGB555_TWO(dst, src);
src += 2;
dst += 2;
break;
case 1:
RGB888_RGB555(dst, src);
++src;
++dst;
break;
}
src += srcskip;
dst += dstskip;
}
}
#endif /* USE_DUFFS_LOOP */
}
/* Special optimized blit for RGB 8-8-8 --> RGB 5-6-5 */
#define RGB888_RGB565(dst, src) { \
*(Uint16 *)(dst) = (Uint16)((((*src)&0x00F80000)>>8)| \
(((*src)&0x0000FC00)>>5)| \
(((*src)&0x000000F8)>>3)); \
}
#define RGB888_RGB565_TWO(dst, src) { \
*(Uint32 *)(dst) = (((((src[HI])&0x00F80000)>>8)| \
(((src[HI])&0x0000FC00)>>5)| \
(((src[HI])&0x000000F8)>>3))<<16)| \
(((src[LO])&0x00F80000)>>8)| \
(((src[LO])&0x0000FC00)>>5)| \
(((src[LO])&0x000000F8)>>3); \
}
static void
Blit_RGB888_RGB565(SDL_BlitInfo * info)
{
#ifndef USE_DUFFS_LOOP
int c;
#endif
int width, height;
Uint32 *src;
Uint16 *dst;
int srcskip, dstskip;
/* Set up some basic variables */
width = info->dst_w;
height = info->dst_h;
src = (Uint32 *) info->src;
srcskip = info->src_skip / 4;
dst = (Uint16 *) info->dst;
dstskip = info->dst_skip / 2;
#ifdef USE_DUFFS_LOOP
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
RGB888_RGB565(dst, src);
++src;
++dst;
, width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
#else
/* Memory align at 4-byte boundary, if necessary */
if ((long) dst & 0x03) {
/* Don't do anything if width is 0 */
if (width == 0) {
return;
}
--width;
while (height--) {
/* Perform copy alignment */
RGB888_RGB565(dst, src);
++src;
++dst;
/* Copy in 4 pixel chunks */
for (c = width / 4; c; --c) {
RGB888_RGB565_TWO(dst, src);
src += 2;
dst += 2;
RGB888_RGB565_TWO(dst, src);
src += 2;
dst += 2;
}
/* Get any leftovers */
switch (width & 3) {
case 3:
RGB888_RGB565(dst, src);
++src;
++dst;
case 2:
RGB888_RGB565_TWO(dst, src);
src += 2;
dst += 2;
break;
case 1:
RGB888_RGB565(dst, src);
++src;
++dst;
break;
}
src += srcskip;
dst += dstskip;
}
} else {
while (height--) {
/* Copy in 4 pixel chunks */
for (c = width / 4; c; --c) {
RGB888_RGB565_TWO(dst, src);
src += 2;
dst += 2;
RGB888_RGB565_TWO(dst, src);
src += 2;
dst += 2;
}
/* Get any leftovers */
switch (width & 3) {
case 3:
RGB888_RGB565(dst, src);
++src;
++dst;
case 2:
RGB888_RGB565_TWO(dst, src);
src += 2;
dst += 2;
break;
case 1:
RGB888_RGB565(dst, src);
++src;
++dst;
break;
}
src += srcskip;
dst += dstskip;
}
}
#endif /* USE_DUFFS_LOOP */
}
/* Special optimized blit for RGB 5-6-5 --> 32-bit RGB surfaces */
#define RGB565_32(dst, src, map) (map[src[LO]*2] + map[src[HI]*2+1])
static void
Blit_RGB565_32(SDL_BlitInfo * info, const Uint32 * map)
{
#ifndef USE_DUFFS_LOOP
int c;
#endif
int width, height;
Uint8 *src;
Uint32 *dst;
int srcskip, dstskip;
/* Set up some basic variables */
width = info->dst_w;
height = info->dst_h;
src = (Uint8 *) info->src;
srcskip = info->src_skip;
dst = (Uint32 *) info->dst;
dstskip = info->dst_skip / 4;
#ifdef USE_DUFFS_LOOP
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
*dst++ = RGB565_32(dst, src, map);
src += 2;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
#else
while (height--) {
/* Copy in 4 pixel chunks */
for (c = width / 4; c; --c) {
*dst++ = RGB565_32(dst, src, map);
src += 2;
*dst++ = RGB565_32(dst, src, map);
src += 2;
*dst++ = RGB565_32(dst, src, map);
src += 2;
*dst++ = RGB565_32(dst, src, map);
src += 2;
}
/* Get any leftovers */
switch (width & 3) {
case 3:
*dst++ = RGB565_32(dst, src, map);
src += 2;
case 2:
*dst++ = RGB565_32(dst, src, map);
src += 2;
case 1:
*dst++ = RGB565_32(dst, src, map);
src += 2;
break;
}
src += srcskip;
dst += dstskip;
}
#endif /* USE_DUFFS_LOOP */
}
/* Special optimized blit for RGB 5-6-5 --> ARGB 8-8-8-8 */
static const Uint32 RGB565_ARGB8888_LUT[512] = {
0x00000000, 0xff000000, 0x00000008, 0xff002000,
0x00000010, 0xff004000, 0x00000018, 0xff006100,
0x00000020, 0xff008100, 0x00000029, 0xff00a100,
0x00000031, 0xff00c200, 0x00000039, 0xff00e200,
0x00000041, 0xff080000, 0x0000004a, 0xff082000,
0x00000052, 0xff084000, 0x0000005a, 0xff086100,
0x00000062, 0xff088100, 0x0000006a, 0xff08a100,
0x00000073, 0xff08c200, 0x0000007b, 0xff08e200,
0x00000083, 0xff100000, 0x0000008b, 0xff102000,
0x00000094, 0xff104000, 0x0000009c, 0xff106100,
0x000000a4, 0xff108100, 0x000000ac, 0xff10a100,
0x000000b4, 0xff10c200, 0x000000bd, 0xff10e200,
0x000000c5, 0xff180000, 0x000000cd, 0xff182000,
0x000000d5, 0xff184000, 0x000000de, 0xff186100,
0x000000e6, 0xff188100, 0x000000ee, 0xff18a100,
0x000000f6, 0xff18c200, 0x000000ff, 0xff18e200,
0x00000400, 0xff200000, 0x00000408, 0xff202000,
0x00000410, 0xff204000, 0x00000418, 0xff206100,
0x00000420, 0xff208100, 0x00000429, 0xff20a100,
0x00000431, 0xff20c200, 0x00000439, 0xff20e200,
0x00000441, 0xff290000, 0x0000044a, 0xff292000,
0x00000452, 0xff294000, 0x0000045a, 0xff296100,
0x00000462, 0xff298100, 0x0000046a, 0xff29a100,
0x00000473, 0xff29c200, 0x0000047b, 0xff29e200,
0x00000483, 0xff310000, 0x0000048b, 0xff312000,
0x00000494, 0xff314000, 0x0000049c, 0xff316100,
0x000004a4, 0xff318100, 0x000004ac, 0xff31a100,
0x000004b4, 0xff31c200, 0x000004bd, 0xff31e200,
0x000004c5, 0xff390000, 0x000004cd, 0xff392000,
0x000004d5, 0xff394000, 0x000004de, 0xff396100,
0x000004e6, 0xff398100, 0x000004ee, 0xff39a100,
0x000004f6, 0xff39c200, 0x000004ff, 0xff39e200,
0x00000800, 0xff410000, 0x00000808, 0xff412000,
0x00000810, 0xff414000, 0x00000818, 0xff416100,
0x00000820, 0xff418100, 0x00000829, 0xff41a100,
0x00000831, 0xff41c200, 0x00000839, 0xff41e200,
0x00000841, 0xff4a0000, 0x0000084a, 0xff4a2000,
0x00000852, 0xff4a4000, 0x0000085a, 0xff4a6100,
0x00000862, 0xff4a8100, 0x0000086a, 0xff4aa100,
0x00000873, 0xff4ac200, 0x0000087b, 0xff4ae200,
0x00000883, 0xff520000, 0x0000088b, 0xff522000,
0x00000894, 0xff524000, 0x0000089c, 0xff526100,
0x000008a4, 0xff528100, 0x000008ac, 0xff52a100,
0x000008b4, 0xff52c200, 0x000008bd, 0xff52e200,
0x000008c5, 0xff5a0000, 0x000008cd, 0xff5a2000,
0x000008d5, 0xff5a4000, 0x000008de, 0xff5a6100,
0x000008e6, 0xff5a8100, 0x000008ee, 0xff5aa100,
0x000008f6, 0xff5ac200, 0x000008ff, 0xff5ae200,
0x00000c00, 0xff620000, 0x00000c08, 0xff622000,
0x00000c10, 0xff624000, 0x00000c18, 0xff626100,
0x00000c20, 0xff628100, 0x00000c29, 0xff62a100,
0x00000c31, 0xff62c200, 0x00000c39, 0xff62e200,
0x00000c41, 0xff6a0000, 0x00000c4a, 0xff6a2000,
0x00000c52, 0xff6a4000, 0x00000c5a, 0xff6a6100,
0x00000c62, 0xff6a8100, 0x00000c6a, 0xff6aa100,
0x00000c73, 0xff6ac200, 0x00000c7b, 0xff6ae200,
0x00000c83, 0xff730000, 0x00000c8b, 0xff732000,
0x00000c94, 0xff734000, 0x00000c9c, 0xff736100,
0x00000ca4, 0xff738100, 0x00000cac, 0xff73a100,
0x00000cb4, 0xff73c200, 0x00000cbd, 0xff73e200,
0x00000cc5, 0xff7b0000, 0x00000ccd, 0xff7b2000,
0x00000cd5, 0xff7b4000, 0x00000cde, 0xff7b6100,
0x00000ce6, 0xff7b8100, 0x00000cee, 0xff7ba100,
0x00000cf6, 0xff7bc200, 0x00000cff, 0xff7be200,
0x00001000, 0xff830000, 0x00001008, 0xff832000,
0x00001010, 0xff834000, 0x00001018, 0xff836100,
0x00001020, 0xff838100, 0x00001029, 0xff83a100,
0x00001031, 0xff83c200, 0x00001039, 0xff83e200,
0x00001041, 0xff8b0000, 0x0000104a, 0xff8b2000,
0x00001052, 0xff8b4000, 0x0000105a, 0xff8b6100,
0x00001062, 0xff8b8100, 0x0000106a, 0xff8ba100,
0x00001073, 0xff8bc200, 0x0000107b, 0xff8be200,
0x00001083, 0xff940000, 0x0000108b, 0xff942000,
0x00001094, 0xff944000, 0x0000109c, 0xff946100,
0x000010a4, 0xff948100, 0x000010ac, 0xff94a100,
0x000010b4, 0xff94c200, 0x000010bd, 0xff94e200,
0x000010c5, 0xff9c0000, 0x000010cd, 0xff9c2000,
0x000010d5, 0xff9c4000, 0x000010de, 0xff9c6100,
0x000010e6, 0xff9c8100, 0x000010ee, 0xff9ca100,
0x000010f6, 0xff9cc200, 0x000010ff, 0xff9ce200,
0x00001400, 0xffa40000, 0x00001408, 0xffa42000,
0x00001410, 0xffa44000, 0x00001418, 0xffa46100,
0x00001420, 0xffa48100, 0x00001429, 0xffa4a100,
0x00001431, 0xffa4c200, 0x00001439, 0xffa4e200,
0x00001441, 0xffac0000, 0x0000144a, 0xffac2000,
0x00001452, 0xffac4000, 0x0000145a, 0xffac6100,
0x00001462, 0xffac8100, 0x0000146a, 0xffaca100,
0x00001473, 0xffacc200, 0x0000147b, 0xfface200,
0x00001483, 0xffb40000, 0x0000148b, 0xffb42000,
0x00001494, 0xffb44000, 0x0000149c, 0xffb46100,
0x000014a4, 0xffb48100, 0x000014ac, 0xffb4a100,
0x000014b4, 0xffb4c200, 0x000014bd, 0xffb4e200,
0x000014c5, 0xffbd0000, 0x000014cd, 0xffbd2000,
0x000014d5, 0xffbd4000, 0x000014de, 0xffbd6100,
0x000014e6, 0xffbd8100, 0x000014ee, 0xffbda100,
0x000014f6, 0xffbdc200, 0x000014ff, 0xffbde200,
0x00001800, 0xffc50000, 0x00001808, 0xffc52000,
0x00001810, 0xffc54000, 0x00001818, 0xffc56100,
0x00001820, 0xffc58100, 0x00001829, 0xffc5a100,
0x00001831, 0xffc5c200, 0x00001839, 0xffc5e200,
0x00001841, 0xffcd0000, 0x0000184a, 0xffcd2000,
0x00001852, 0xffcd4000, 0x0000185a, 0xffcd6100,
0x00001862, 0xffcd8100, 0x0000186a, 0xffcda100,
0x00001873, 0xffcdc200, 0x0000187b, 0xffcde200,
0x00001883, 0xffd50000, 0x0000188b, 0xffd52000,
0x00001894, 0xffd54000, 0x0000189c, 0xffd56100,
0x000018a4, 0xffd58100, 0x000018ac, 0xffd5a100,
0x000018b4, 0xffd5c200, 0x000018bd, 0xffd5e200,
0x000018c5, 0xffde0000, 0x000018cd, 0xffde2000,
0x000018d5, 0xffde4000, 0x000018de, 0xffde6100,
0x000018e6, 0xffde8100, 0x000018ee, 0xffdea100,
0x000018f6, 0xffdec200, 0x000018ff, 0xffdee200,
0x00001c00, 0xffe60000, 0x00001c08, 0xffe62000,
0x00001c10, 0xffe64000, 0x00001c18, 0xffe66100,
0x00001c20, 0xffe68100, 0x00001c29, 0xffe6a100,
0x00001c31, 0xffe6c200, 0x00001c39, 0xffe6e200,
0x00001c41, 0xffee0000, 0x00001c4a, 0xffee2000,
0x00001c52, 0xffee4000, 0x00001c5a, 0xffee6100,
0x00001c62, 0xffee8100, 0x00001c6a, 0xffeea100,
0x00001c73, 0xffeec200, 0x00001c7b, 0xffeee200,
0x00001c83, 0xfff60000, 0x00001c8b, 0xfff62000,
0x00001c94, 0xfff64000, 0x00001c9c, 0xfff66100,
0x00001ca4, 0xfff68100, 0x00001cac, 0xfff6a100,
0x00001cb4, 0xfff6c200, 0x00001cbd, 0xfff6e200,
0x00001cc5, 0xffff0000, 0x00001ccd, 0xffff2000,
0x00001cd5, 0xffff4000, 0x00001cde, 0xffff6100,
0x00001ce6, 0xffff8100, 0x00001cee, 0xffffa100,
0x00001cf6, 0xffffc200, 0x00001cff, 0xffffe200
};
static void
Blit_RGB565_ARGB8888(SDL_BlitInfo * info)
{
Blit_RGB565_32(info, RGB565_ARGB8888_LUT);
}
/* Special optimized blit for RGB 5-6-5 --> ABGR 8-8-8-8 */
static const Uint32 RGB565_ABGR8888_LUT[512] = {
0xff000000, 0x00000000, 0xff080000, 0x00002000,
0xff100000, 0x00004000, 0xff180000, 0x00006100,
0xff200000, 0x00008100, 0xff290000, 0x0000a100,
0xff310000, 0x0000c200, 0xff390000, 0x0000e200,
0xff410000, 0x00000008, 0xff4a0000, 0x00002008,
0xff520000, 0x00004008, 0xff5a0000, 0x00006108,
0xff620000, 0x00008108, 0xff6a0000, 0x0000a108,
0xff730000, 0x0000c208, 0xff7b0000, 0x0000e208,
0xff830000, 0x00000010, 0xff8b0000, 0x00002010,
0xff940000, 0x00004010, 0xff9c0000, 0x00006110,
0xffa40000, 0x00008110, 0xffac0000, 0x0000a110,
0xffb40000, 0x0000c210, 0xffbd0000, 0x0000e210,
0xffc50000, 0x00000018, 0xffcd0000, 0x00002018,
0xffd50000, 0x00004018, 0xffde0000, 0x00006118,
0xffe60000, 0x00008118, 0xffee0000, 0x0000a118,
0xfff60000, 0x0000c218, 0xffff0000, 0x0000e218,
0xff000400, 0x00000020, 0xff080400, 0x00002020,
0xff100400, 0x00004020, 0xff180400, 0x00006120,
0xff200400, 0x00008120, 0xff290400, 0x0000a120,
0xff310400, 0x0000c220, 0xff390400, 0x0000e220,
0xff410400, 0x00000029, 0xff4a0400, 0x00002029,
0xff520400, 0x00004029, 0xff5a0400, 0x00006129,
0xff620400, 0x00008129, 0xff6a0400, 0x0000a129,
0xff730400, 0x0000c229, 0xff7b0400, 0x0000e229,
0xff830400, 0x00000031, 0xff8b0400, 0x00002031,
0xff940400, 0x00004031, 0xff9c0400, 0x00006131,
0xffa40400, 0x00008131, 0xffac0400, 0x0000a131,
0xffb40400, 0x0000c231, 0xffbd0400, 0x0000e231,
0xffc50400, 0x00000039, 0xffcd0400, 0x00002039,
0xffd50400, 0x00004039, 0xffde0400, 0x00006139,
0xffe60400, 0x00008139, 0xffee0400, 0x0000a139,
0xfff60400, 0x0000c239, 0xffff0400, 0x0000e239,
0xff000800, 0x00000041, 0xff080800, 0x00002041,
0xff100800, 0x00004041, 0xff180800, 0x00006141,
0xff200800, 0x00008141, 0xff290800, 0x0000a141,
0xff310800, 0x0000c241, 0xff390800, 0x0000e241,
0xff410800, 0x0000004a, 0xff4a0800, 0x0000204a,
0xff520800, 0x0000404a, 0xff5a0800, 0x0000614a,
0xff620800, 0x0000814a, 0xff6a0800, 0x0000a14a,
0xff730800, 0x0000c24a, 0xff7b0800, 0x0000e24a,
0xff830800, 0x00000052, 0xff8b0800, 0x00002052,
0xff940800, 0x00004052, 0xff9c0800, 0x00006152,
0xffa40800, 0x00008152, 0xffac0800, 0x0000a152,
0xffb40800, 0x0000c252, 0xffbd0800, 0x0000e252,
0xffc50800, 0x0000005a, 0xffcd0800, 0x0000205a,
0xffd50800, 0x0000405a, 0xffde0800, 0x0000615a,
0xffe60800, 0x0000815a, 0xffee0800, 0x0000a15a,
0xfff60800, 0x0000c25a, 0xffff0800, 0x0000e25a,
0xff000c00, 0x00000062, 0xff080c00, 0x00002062,
0xff100c00, 0x00004062, 0xff180c00, 0x00006162,
0xff200c00, 0x00008162, 0xff290c00, 0x0000a162,
0xff310c00, 0x0000c262, 0xff390c00, 0x0000e262,
0xff410c00, 0x0000006a, 0xff4a0c00, 0x0000206a,
0xff520c00, 0x0000406a, 0xff5a0c00, 0x0000616a,
0xff620c00, 0x0000816a, 0xff6a0c00, 0x0000a16a,
0xff730c00, 0x0000c26a, 0xff7b0c00, 0x0000e26a,
0xff830c00, 0x00000073, 0xff8b0c00, 0x00002073,
0xff940c00, 0x00004073, 0xff9c0c00, 0x00006173,
0xffa40c00, 0x00008173, 0xffac0c00, 0x0000a173,
0xffb40c00, 0x0000c273, 0xffbd0c00, 0x0000e273,
0xffc50c00, 0x0000007b, 0xffcd0c00, 0x0000207b,
0xffd50c00, 0x0000407b, 0xffde0c00, 0x0000617b,
0xffe60c00, 0x0000817b, 0xffee0c00, 0x0000a17b,
0xfff60c00, 0x0000c27b, 0xffff0c00, 0x0000e27b,
0xff001000, 0x00000083, 0xff081000, 0x00002083,
0xff101000, 0x00004083, 0xff181000, 0x00006183,
0xff201000, 0x00008183, 0xff291000, 0x0000a183,
0xff311000, 0x0000c283, 0xff391000, 0x0000e283,
0xff411000, 0x0000008b, 0xff4a1000, 0x0000208b,
0xff521000, 0x0000408b, 0xff5a1000, 0x0000618b,
0xff621000, 0x0000818b, 0xff6a1000, 0x0000a18b,
0xff731000, 0x0000c28b, 0xff7b1000, 0x0000e28b,
0xff831000, 0x00000094, 0xff8b1000, 0x00002094,
0xff941000, 0x00004094, 0xff9c1000, 0x00006194,
0xffa41000, 0x00008194, 0xffac1000, 0x0000a194,
0xffb41000, 0x0000c294, 0xffbd1000, 0x0000e294,
0xffc51000, 0x0000009c, 0xffcd1000, 0x0000209c,
0xffd51000, 0x0000409c, 0xffde1000, 0x0000619c,
0xffe61000, 0x0000819c, 0xffee1000, 0x0000a19c,
0xfff61000, 0x0000c29c, 0xffff1000, 0x0000e29c,
0xff001400, 0x000000a4, 0xff081400, 0x000020a4,
0xff101400, 0x000040a4, 0xff181400, 0x000061a4,
0xff201400, 0x000081a4, 0xff291400, 0x0000a1a4,
0xff311400, 0x0000c2a4, 0xff391400, 0x0000e2a4,
0xff411400, 0x000000ac, 0xff4a1400, 0x000020ac,
0xff521400, 0x000040ac, 0xff5a1400, 0x000061ac,
0xff621400, 0x000081ac, 0xff6a1400, 0x0000a1ac,
0xff731400, 0x0000c2ac, 0xff7b1400, 0x0000e2ac,
0xff831400, 0x000000b4, 0xff8b1400, 0x000020b4,
0xff941400, 0x000040b4, 0xff9c1400, 0x000061b4,
0xffa41400, 0x000081b4, 0xffac1400, 0x0000a1b4,
0xffb41400, 0x0000c2b4, 0xffbd1400, 0x0000e2b4,
0xffc51400, 0x000000bd, 0xffcd1400, 0x000020bd,
0xffd51400, 0x000040bd, 0xffde1400, 0x000061bd,
0xffe61400, 0x000081bd, 0xffee1400, 0x0000a1bd,
0xfff61400, 0x0000c2bd, 0xffff1400, 0x0000e2bd,
0xff001800, 0x000000c5, 0xff081800, 0x000020c5,
0xff101800, 0x000040c5, 0xff181800, 0x000061c5,
0xff201800, 0x000081c5, 0xff291800, 0x0000a1c5,
0xff311800, 0x0000c2c5, 0xff391800, 0x0000e2c5,
0xff411800, 0x000000cd, 0xff4a1800, 0x000020cd,
0xff521800, 0x000040cd, 0xff5a1800, 0x000061cd,
0xff621800, 0x000081cd, 0xff6a1800, 0x0000a1cd,
0xff731800, 0x0000c2cd, 0xff7b1800, 0x0000e2cd,
0xff831800, 0x000000d5, 0xff8b1800, 0x000020d5,
0xff941800, 0x000040d5, 0xff9c1800, 0x000061d5,
0xffa41800, 0x000081d5, 0xffac1800, 0x0000a1d5,
0xffb41800, 0x0000c2d5, 0xffbd1800, 0x0000e2d5,
0xffc51800, 0x000000de, 0xffcd1800, 0x000020de,
0xffd51800, 0x000040de, 0xffde1800, 0x000061de,
0xffe61800, 0x000081de, 0xffee1800, 0x0000a1de,
0xfff61800, 0x0000c2de, 0xffff1800, 0x0000e2de,
0xff001c00, 0x000000e6, 0xff081c00, 0x000020e6,
0xff101c00, 0x000040e6, 0xff181c00, 0x000061e6,
0xff201c00, 0x000081e6, 0xff291c00, 0x0000a1e6,
0xff311c00, 0x0000c2e6, 0xff391c00, 0x0000e2e6,
0xff411c00, 0x000000ee, 0xff4a1c00, 0x000020ee,
0xff521c00, 0x000040ee, 0xff5a1c00, 0x000061ee,
0xff621c00, 0x000081ee, 0xff6a1c00, 0x0000a1ee,
0xff731c00, 0x0000c2ee, 0xff7b1c00, 0x0000e2ee,
0xff831c00, 0x000000f6, 0xff8b1c00, 0x000020f6,
0xff941c00, 0x000040f6, 0xff9c1c00, 0x000061f6,
0xffa41c00, 0x000081f6, 0xffac1c00, 0x0000a1f6,
0xffb41c00, 0x0000c2f6, 0xffbd1c00, 0x0000e2f6,
0xffc51c00, 0x000000ff, 0xffcd1c00, 0x000020ff,
0xffd51c00, 0x000040ff, 0xffde1c00, 0x000061ff,
0xffe61c00, 0x000081ff, 0xffee1c00, 0x0000a1ff,
0xfff61c00, 0x0000c2ff, 0xffff1c00, 0x0000e2ff
};
static void
Blit_RGB565_ABGR8888(SDL_BlitInfo * info)
{
Blit_RGB565_32(info, RGB565_ABGR8888_LUT);
}
/* Special optimized blit for RGB 5-6-5 --> RGBA 8-8-8-8 */
static const Uint32 RGB565_RGBA8888_LUT[512] = {
0x000000ff, 0x00000000, 0x000008ff, 0x00200000,
0x000010ff, 0x00400000, 0x000018ff, 0x00610000,
0x000020ff, 0x00810000, 0x000029ff, 0x00a10000,
0x000031ff, 0x00c20000, 0x000039ff, 0x00e20000,
0x000041ff, 0x08000000, 0x00004aff, 0x08200000,
0x000052ff, 0x08400000, 0x00005aff, 0x08610000,
0x000062ff, 0x08810000, 0x00006aff, 0x08a10000,
0x000073ff, 0x08c20000, 0x00007bff, 0x08e20000,
0x000083ff, 0x10000000, 0x00008bff, 0x10200000,
0x000094ff, 0x10400000, 0x00009cff, 0x10610000,
0x0000a4ff, 0x10810000, 0x0000acff, 0x10a10000,
0x0000b4ff, 0x10c20000, 0x0000bdff, 0x10e20000,
0x0000c5ff, 0x18000000, 0x0000cdff, 0x18200000,
0x0000d5ff, 0x18400000, 0x0000deff, 0x18610000,
0x0000e6ff, 0x18810000, 0x0000eeff, 0x18a10000,
0x0000f6ff, 0x18c20000, 0x0000ffff, 0x18e20000,
0x000400ff, 0x20000000, 0x000408ff, 0x20200000,
0x000410ff, 0x20400000, 0x000418ff, 0x20610000,
0x000420ff, 0x20810000, 0x000429ff, 0x20a10000,
0x000431ff, 0x20c20000, 0x000439ff, 0x20e20000,
0x000441ff, 0x29000000, 0x00044aff, 0x29200000,
0x000452ff, 0x29400000, 0x00045aff, 0x29610000,
0x000462ff, 0x29810000, 0x00046aff, 0x29a10000,
0x000473ff, 0x29c20000, 0x00047bff, 0x29e20000,
0x000483ff, 0x31000000, 0x00048bff, 0x31200000,
0x000494ff, 0x31400000, 0x00049cff, 0x31610000,
0x0004a4ff, 0x31810000, 0x0004acff, 0x31a10000,
0x0004b4ff, 0x31c20000, 0x0004bdff, 0x31e20000,
0x0004c5ff, 0x39000000, 0x0004cdff, 0x39200000,
0x0004d5ff, 0x39400000, 0x0004deff, 0x39610000,
0x0004e6ff, 0x39810000, 0x0004eeff, 0x39a10000,
0x0004f6ff, 0x39c20000, 0x0004ffff, 0x39e20000,
0x000800ff, 0x41000000, 0x000808ff, 0x41200000,
0x000810ff, 0x41400000, 0x000818ff, 0x41610000,
0x000820ff, 0x41810000, 0x000829ff, 0x41a10000,
0x000831ff, 0x41c20000, 0x000839ff, 0x41e20000,
0x000841ff, 0x4a000000, 0x00084aff, 0x4a200000,
0x000852ff, 0x4a400000, 0x00085aff, 0x4a610000,
0x000862ff, 0x4a810000, 0x00086aff, 0x4aa10000,
0x000873ff, 0x4ac20000, 0x00087bff, 0x4ae20000,
0x000883ff, 0x52000000, 0x00088bff, 0x52200000,
0x000894ff, 0x52400000, 0x00089cff, 0x52610000,
0x0008a4ff, 0x52810000, 0x0008acff, 0x52a10000,
0x0008b4ff, 0x52c20000, 0x0008bdff, 0x52e20000,
0x0008c5ff, 0x5a000000, 0x0008cdff, 0x5a200000,
0x0008d5ff, 0x5a400000, 0x0008deff, 0x5a610000,
0x0008e6ff, 0x5a810000, 0x0008eeff, 0x5aa10000,
0x0008f6ff, 0x5ac20000, 0x0008ffff, 0x5ae20000,
0x000c00ff, 0x62000000, 0x000c08ff, 0x62200000,
0x000c10ff, 0x62400000, 0x000c18ff, 0x62610000,
0x000c20ff, 0x62810000, 0x000c29ff, 0x62a10000,
0x000c31ff, 0x62c20000, 0x000c39ff, 0x62e20000,
0x000c41ff, 0x6a000000, 0x000c4aff, 0x6a200000,
0x000c52ff, 0x6a400000, 0x000c5aff, 0x6a610000,
0x000c62ff, 0x6a810000, 0x000c6aff, 0x6aa10000,
0x000c73ff, 0x6ac20000, 0x000c7bff, 0x6ae20000,
0x000c83ff, 0x73000000, 0x000c8bff, 0x73200000,
0x000c94ff, 0x73400000, 0x000c9cff, 0x73610000,
0x000ca4ff, 0x73810000, 0x000cacff, 0x73a10000,
0x000cb4ff, 0x73c20000, 0x000cbdff, 0x73e20000,
0x000cc5ff, 0x7b000000, 0x000ccdff, 0x7b200000,
0x000cd5ff, 0x7b400000, 0x000cdeff, 0x7b610000,
0x000ce6ff, 0x7b810000, 0x000ceeff, 0x7ba10000,
0x000cf6ff, 0x7bc20000, 0x000cffff, 0x7be20000,
0x001000ff, 0x83000000, 0x001008ff, 0x83200000,
0x001010ff, 0x83400000, 0x001018ff, 0x83610000,
0x001020ff, 0x83810000, 0x001029ff, 0x83a10000,
0x001031ff, 0x83c20000, 0x001039ff, 0x83e20000,
0x001041ff, 0x8b000000, 0x00104aff, 0x8b200000,
0x001052ff, 0x8b400000, 0x00105aff, 0x8b610000,
0x001062ff, 0x8b810000, 0x00106aff, 0x8ba10000,
0x001073ff, 0x8bc20000, 0x00107bff, 0x8be20000,
0x001083ff, 0x94000000, 0x00108bff, 0x94200000,
0x001094ff, 0x94400000, 0x00109cff, 0x94610000,
0x0010a4ff, 0x94810000, 0x0010acff, 0x94a10000,
0x0010b4ff, 0x94c20000, 0x0010bdff, 0x94e20000,
0x0010c5ff, 0x9c000000, 0x0010cdff, 0x9c200000,
0x0010d5ff, 0x9c400000, 0x0010deff, 0x9c610000,
0x0010e6ff, 0x9c810000, 0x0010eeff, 0x9ca10000,
0x0010f6ff, 0x9cc20000, 0x0010ffff, 0x9ce20000,
0x001400ff, 0xa4000000, 0x001408ff, 0xa4200000,
0x001410ff, 0xa4400000, 0x001418ff, 0xa4610000,
0x001420ff, 0xa4810000, 0x001429ff, 0xa4a10000,
0x001431ff, 0xa4c20000, 0x001439ff, 0xa4e20000,
0x001441ff, 0xac000000, 0x00144aff, 0xac200000,
0x001452ff, 0xac400000, 0x00145aff, 0xac610000,
0x001462ff, 0xac810000, 0x00146aff, 0xaca10000,
0x001473ff, 0xacc20000, 0x00147bff, 0xace20000,
0x001483ff, 0xb4000000, 0x00148bff, 0xb4200000,
0x001494ff, 0xb4400000, 0x00149cff, 0xb4610000,
0x0014a4ff, 0xb4810000, 0x0014acff, 0xb4a10000,
0x0014b4ff, 0xb4c20000, 0x0014bdff, 0xb4e20000,
0x0014c5ff, 0xbd000000, 0x0014cdff, 0xbd200000,
0x0014d5ff, 0xbd400000, 0x0014deff, 0xbd610000,
0x0014e6ff, 0xbd810000, 0x0014eeff, 0xbda10000,
0x0014f6ff, 0xbdc20000, 0x0014ffff, 0xbde20000,
0x001800ff, 0xc5000000, 0x001808ff, 0xc5200000,
0x001810ff, 0xc5400000, 0x001818ff, 0xc5610000,
0x001820ff, 0xc5810000, 0x001829ff, 0xc5a10000,
0x001831ff, 0xc5c20000, 0x001839ff, 0xc5e20000,
0x001841ff, 0xcd000000, 0x00184aff, 0xcd200000,
0x001852ff, 0xcd400000, 0x00185aff, 0xcd610000,
0x001862ff, 0xcd810000, 0x00186aff, 0xcda10000,
0x001873ff, 0xcdc20000, 0x00187bff, 0xcde20000,
0x001883ff, 0xd5000000, 0x00188bff, 0xd5200000,
0x001894ff, 0xd5400000, 0x00189cff, 0xd5610000,
0x0018a4ff, 0xd5810000, 0x0018acff, 0xd5a10000,
0x0018b4ff, 0xd5c20000, 0x0018bdff, 0xd5e20000,
0x0018c5ff, 0xde000000, 0x0018cdff, 0xde200000,
0x0018d5ff, 0xde400000, 0x0018deff, 0xde610000,
0x0018e6ff, 0xde810000, 0x0018eeff, 0xdea10000,
0x0018f6ff, 0xdec20000, 0x0018ffff, 0xdee20000,
0x001c00ff, 0xe6000000, 0x001c08ff, 0xe6200000,
0x001c10ff, 0xe6400000, 0x001c18ff, 0xe6610000,
0x001c20ff, 0xe6810000, 0x001c29ff, 0xe6a10000,
0x001c31ff, 0xe6c20000, 0x001c39ff, 0xe6e20000,
0x001c41ff, 0xee000000, 0x001c4aff, 0xee200000,
0x001c52ff, 0xee400000, 0x001c5aff, 0xee610000,
0x001c62ff, 0xee810000, 0x001c6aff, 0xeea10000,
0x001c73ff, 0xeec20000, 0x001c7bff, 0xeee20000,
0x001c83ff, 0xf6000000, 0x001c8bff, 0xf6200000,
0x001c94ff, 0xf6400000, 0x001c9cff, 0xf6610000,
0x001ca4ff, 0xf6810000, 0x001cacff, 0xf6a10000,
0x001cb4ff, 0xf6c20000, 0x001cbdff, 0xf6e20000,
0x001cc5ff, 0xff000000, 0x001ccdff, 0xff200000,
0x001cd5ff, 0xff400000, 0x001cdeff, 0xff610000,
0x001ce6ff, 0xff810000, 0x001ceeff, 0xffa10000,
0x001cf6ff, 0xffc20000, 0x001cffff, 0xffe20000,
};
static void
Blit_RGB565_RGBA8888(SDL_BlitInfo * info)
{
Blit_RGB565_32(info, RGB565_RGBA8888_LUT);
}
/* Special optimized blit for RGB 5-6-5 --> BGRA 8-8-8-8 */
static const Uint32 RGB565_BGRA8888_LUT[512] = {
0x00000000, 0x000000ff, 0x08000000, 0x002000ff,
0x10000000, 0x004000ff, 0x18000000, 0x006100ff,
0x20000000, 0x008100ff, 0x29000000, 0x00a100ff,
0x31000000, 0x00c200ff, 0x39000000, 0x00e200ff,
0x41000000, 0x000008ff, 0x4a000000, 0x002008ff,
0x52000000, 0x004008ff, 0x5a000000, 0x006108ff,
0x62000000, 0x008108ff, 0x6a000000, 0x00a108ff,
0x73000000, 0x00c208ff, 0x7b000000, 0x00e208ff,
0x83000000, 0x000010ff, 0x8b000000, 0x002010ff,
0x94000000, 0x004010ff, 0x9c000000, 0x006110ff,
0xa4000000, 0x008110ff, 0xac000000, 0x00a110ff,
0xb4000000, 0x00c210ff, 0xbd000000, 0x00e210ff,
0xc5000000, 0x000018ff, 0xcd000000, 0x002018ff,
0xd5000000, 0x004018ff, 0xde000000, 0x006118ff,
0xe6000000, 0x008118ff, 0xee000000, 0x00a118ff,
0xf6000000, 0x00c218ff, 0xff000000, 0x00e218ff,
0x00040000, 0x000020ff, 0x08040000, 0x002020ff,
0x10040000, 0x004020ff, 0x18040000, 0x006120ff,
0x20040000, 0x008120ff, 0x29040000, 0x00a120ff,
0x31040000, 0x00c220ff, 0x39040000, 0x00e220ff,
0x41040000, 0x000029ff, 0x4a040000, 0x002029ff,
0x52040000, 0x004029ff, 0x5a040000, 0x006129ff,
0x62040000, 0x008129ff, 0x6a040000, 0x00a129ff,
0x73040000, 0x00c229ff, 0x7b040000, 0x00e229ff,
0x83040000, 0x000031ff, 0x8b040000, 0x002031ff,
0x94040000, 0x004031ff, 0x9c040000, 0x006131ff,
0xa4040000, 0x008131ff, 0xac040000, 0x00a131ff,
0xb4040000, 0x00c231ff, 0xbd040000, 0x00e231ff,
0xc5040000, 0x000039ff, 0xcd040000, 0x002039ff,
0xd5040000, 0x004039ff, 0xde040000, 0x006139ff,
0xe6040000, 0x008139ff, 0xee040000, 0x00a139ff,
0xf6040000, 0x00c239ff, 0xff040000, 0x00e239ff,
0x00080000, 0x000041ff, 0x08080000, 0x002041ff,
0x10080000, 0x004041ff, 0x18080000, 0x006141ff,
0x20080000, 0x008141ff, 0x29080000, 0x00a141ff,
0x31080000, 0x00c241ff, 0x39080000, 0x00e241ff,
0x41080000, 0x00004aff, 0x4a080000, 0x00204aff,
0x52080000, 0x00404aff, 0x5a080000, 0x00614aff,
0x62080000, 0x00814aff, 0x6a080000, 0x00a14aff,
0x73080000, 0x00c24aff, 0x7b080000, 0x00e24aff,
0x83080000, 0x000052ff, 0x8b080000, 0x002052ff,
0x94080000, 0x004052ff, 0x9c080000, 0x006152ff,
0xa4080000, 0x008152ff, 0xac080000, 0x00a152ff,
0xb4080000, 0x00c252ff, 0xbd080000, 0x00e252ff,
0xc5080000, 0x00005aff, 0xcd080000, 0x00205aff,
0xd5080000, 0x00405aff, 0xde080000, 0x00615aff,
0xe6080000, 0x00815aff, 0xee080000, 0x00a15aff,
0xf6080000, 0x00c25aff, 0xff080000, 0x00e25aff,
0x000c0000, 0x000062ff, 0x080c0000, 0x002062ff,
0x100c0000, 0x004062ff, 0x180c0000, 0x006162ff,
0x200c0000, 0x008162ff, 0x290c0000, 0x00a162ff,
0x310c0000, 0x00c262ff, 0x390c0000, 0x00e262ff,
0x410c0000, 0x00006aff, 0x4a0c0000, 0x00206aff,
0x520c0000, 0x00406aff, 0x5a0c0000, 0x00616aff,
0x620c0000, 0x00816aff, 0x6a0c0000, 0x00a16aff,
0x730c0000, 0x00c26aff, 0x7b0c0000, 0x00e26aff,
0x830c0000, 0x000073ff, 0x8b0c0000, 0x002073ff,
0x940c0000, 0x004073ff, 0x9c0c0000, 0x006173ff,
0xa40c0000, 0x008173ff, 0xac0c0000, 0x00a173ff,
0xb40c0000, 0x00c273ff, 0xbd0c0000, 0x00e273ff,
0xc50c0000, 0x00007bff, 0xcd0c0000, 0x00207bff,
0xd50c0000, 0x00407bff, 0xde0c0000, 0x00617bff,
0xe60c0000, 0x00817bff, 0xee0c0000, 0x00a17bff,
0xf60c0000, 0x00c27bff, 0xff0c0000, 0x00e27bff,
0x00100000, 0x000083ff, 0x08100000, 0x002083ff,
0x10100000, 0x004083ff, 0x18100000, 0x006183ff,
0x20100000, 0x008183ff, 0x29100000, 0x00a183ff,
0x31100000, 0x00c283ff, 0x39100000, 0x00e283ff,
0x41100000, 0x00008bff, 0x4a100000, 0x00208bff,
0x52100000, 0x00408bff, 0x5a100000, 0x00618bff,
0x62100000, 0x00818bff, 0x6a100000, 0x00a18bff,
0x73100000, 0x00c28bff, 0x7b100000, 0x00e28bff,
0x83100000, 0x000094ff, 0x8b100000, 0x002094ff,
0x94100000, 0x004094ff, 0x9c100000, 0x006194ff,
0xa4100000, 0x008194ff, 0xac100000, 0x00a194ff,
0xb4100000, 0x00c294ff, 0xbd100000, 0x00e294ff,
0xc5100000, 0x00009cff, 0xcd100000, 0x00209cff,
0xd5100000, 0x00409cff, 0xde100000, 0x00619cff,
0xe6100000, 0x00819cff, 0xee100000, 0x00a19cff,
0xf6100000, 0x00c29cff, 0xff100000, 0x00e29cff,
0x00140000, 0x0000a4ff, 0x08140000, 0x0020a4ff,
0x10140000, 0x0040a4ff, 0x18140000, 0x0061a4ff,
0x20140000, 0x0081a4ff, 0x29140000, 0x00a1a4ff,
0x31140000, 0x00c2a4ff, 0x39140000, 0x00e2a4ff,
0x41140000, 0x0000acff, 0x4a140000, 0x0020acff,
0x52140000, 0x0040acff, 0x5a140000, 0x0061acff,
0x62140000, 0x0081acff, 0x6a140000, 0x00a1acff,
0x73140000, 0x00c2acff, 0x7b140000, 0x00e2acff,
0x83140000, 0x0000b4ff, 0x8b140000, 0x0020b4ff,
0x94140000, 0x0040b4ff, 0x9c140000, 0x0061b4ff,
0xa4140000, 0x0081b4ff, 0xac140000, 0x00a1b4ff,
0xb4140000, 0x00c2b4ff, 0xbd140000, 0x00e2b4ff,
0xc5140000, 0x0000bdff, 0xcd140000, 0x0020bdff,
0xd5140000, 0x0040bdff, 0xde140000, 0x0061bdff,
0xe6140000, 0x0081bdff, 0xee140000, 0x00a1bdff,
0xf6140000, 0x00c2bdff, 0xff140000, 0x00e2bdff,
0x00180000, 0x0000c5ff, 0x08180000, 0x0020c5ff,
0x10180000, 0x0040c5ff, 0x18180000, 0x0061c5ff,
0x20180000, 0x0081c5ff, 0x29180000, 0x00a1c5ff,
0x31180000, 0x00c2c5ff, 0x39180000, 0x00e2c5ff,
0x41180000, 0x0000cdff, 0x4a180000, 0x0020cdff,
0x52180000, 0x0040cdff, 0x5a180000, 0x0061cdff,
0x62180000, 0x0081cdff, 0x6a180000, 0x00a1cdff,
0x73180000, 0x00c2cdff, 0x7b180000, 0x00e2cdff,
0x83180000, 0x0000d5ff, 0x8b180000, 0x0020d5ff,
0x94180000, 0x0040d5ff, 0x9c180000, 0x0061d5ff,
0xa4180000, 0x0081d5ff, 0xac180000, 0x00a1d5ff,
0xb4180000, 0x00c2d5ff, 0xbd180000, 0x00e2d5ff,
0xc5180000, 0x0000deff, 0xcd180000, 0x0020deff,
0xd5180000, 0x0040deff, 0xde180000, 0x0061deff,
0xe6180000, 0x0081deff, 0xee180000, 0x00a1deff,
0xf6180000, 0x00c2deff, 0xff180000, 0x00e2deff,
0x001c0000, 0x0000e6ff, 0x081c0000, 0x0020e6ff,
0x101c0000, 0x0040e6ff, 0x181c0000, 0x0061e6ff,
0x201c0000, 0x0081e6ff, 0x291c0000, 0x00a1e6ff,
0x311c0000, 0x00c2e6ff, 0x391c0000, 0x00e2e6ff,
0x411c0000, 0x0000eeff, 0x4a1c0000, 0x0020eeff,
0x521c0000, 0x0040eeff, 0x5a1c0000, 0x0061eeff,
0x621c0000, 0x0081eeff, 0x6a1c0000, 0x00a1eeff,
0x731c0000, 0x00c2eeff, 0x7b1c0000, 0x00e2eeff,
0x831c0000, 0x0000f6ff, 0x8b1c0000, 0x0020f6ff,
0x941c0000, 0x0040f6ff, 0x9c1c0000, 0x0061f6ff,
0xa41c0000, 0x0081f6ff, 0xac1c0000, 0x00a1f6ff,
0xb41c0000, 0x00c2f6ff, 0xbd1c0000, 0x00e2f6ff,
0xc51c0000, 0x0000ffff, 0xcd1c0000, 0x0020ffff,
0xd51c0000, 0x0040ffff, 0xde1c0000, 0x0061ffff,
0xe61c0000, 0x0081ffff, 0xee1c0000, 0x00a1ffff,
0xf61c0000, 0x00c2ffff, 0xff1c0000, 0x00e2ffff
};
static void
Blit_RGB565_BGRA8888(SDL_BlitInfo * info)
{
Blit_RGB565_32(info, RGB565_BGRA8888_LUT);
}
static void
BlitNto1(SDL_BlitInfo * info)
{
#ifndef USE_DUFFS_LOOP
int c;
#endif
int width, height;
Uint8 *src;
const Uint8 *map;
Uint8 *dst;
int srcskip, dstskip;
int srcbpp;
Uint32 Pixel;
int sR, sG, sB;
SDL_PixelFormat *srcfmt;
/* Set up some basic variables */
width = info->dst_w;
height = info->dst_h;
src = info->src;
srcskip = info->src_skip;
dst = info->dst;
dstskip = info->dst_skip;
map = info->table;
srcfmt = info->src_fmt;
srcbpp = srcfmt->BytesPerPixel;
if (map == NULL) {
while (height--) {
#ifdef USE_DUFFS_LOOP
/* *INDENT-OFF* */
DUFFS_LOOP(
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel,
sR, sG, sB);
if ( 1 ) {
/* Pack RGB into 8bit pixel */
*dst = ((sR>>5)<<(3+2))|
((sG>>5)<<(2)) |
((sB>>6)<<(0)) ;
}
dst++;
src += srcbpp;
, width);
/* *INDENT-ON* */
#else
for (c = width; c; --c) {
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB);
if (1) {
/* Pack RGB into 8bit pixel */
*dst = ((sR >> 5) << (3 + 2)) |
((sG >> 5) << (2)) | ((sB >> 6) << (0));
}
dst++;
src += srcbpp;
}
#endif
src += srcskip;
dst += dstskip;
}
} else {
while (height--) {
#ifdef USE_DUFFS_LOOP
/* *INDENT-OFF* */
DUFFS_LOOP(
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel,
sR, sG, sB);
if ( 1 ) {
/* Pack RGB into 8bit pixel */
*dst = map[((sR>>5)<<(3+2))|
((sG>>5)<<(2)) |
((sB>>6)<<(0)) ];
}
dst++;
src += srcbpp;
, width);
/* *INDENT-ON* */
#else
for (c = width; c; --c) {
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB);
if (1) {
/* Pack RGB into 8bit pixel */
*dst = map[((sR >> 5) << (3 + 2)) |
((sG >> 5) << (2)) | ((sB >> 6) << (0))];
}
dst++;
src += srcbpp;
}
#endif /* USE_DUFFS_LOOP */
src += srcskip;
dst += dstskip;
}
}
}
/* blits 32 bit RGB<->RGBA with both surfaces having the same R,G,B fields */
static void
Blit4to4MaskAlpha(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint32 *src = (Uint32 *) info->src;
int srcskip = info->src_skip;
Uint32 *dst = (Uint32 *) info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
if (dstfmt->Amask) {
/* RGB->RGBA, SET_ALPHA */
Uint32 mask = (info->a >> dstfmt->Aloss) << dstfmt->Ashift;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
*dst = *src | mask;
++dst;
++src;
},
width);
/* *INDENT-ON* */
src = (Uint32 *) ((Uint8 *) src + srcskip);
dst = (Uint32 *) ((Uint8 *) dst + dstskip);
}
} else {
/* RGBA->RGB, NO_ALPHA */
Uint32 mask = srcfmt->Rmask | srcfmt->Gmask | srcfmt->Bmask;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
*dst = *src & mask;
++dst;
++src;
},
width);
/* *INDENT-ON* */
src = (Uint32 *) ((Uint8 *) src + srcskip);
dst = (Uint32 *) ((Uint8 *) dst + dstskip);
}
}
}
/* blits 32 bit RGBA<->RGBA with both surfaces having the same R,G,B,A fields */
static void
Blit4to4CopyAlpha(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint32 *src = (Uint32 *) info->src;
int srcskip = info->src_skip;
Uint32 *dst = (Uint32 *) info->dst;
int dstskip = info->dst_skip;
/* RGBA->RGBA, COPY_ALPHA */
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
*dst = *src;
++dst;
++src;
},
width);
/* *INDENT-ON* */
src = (Uint32 *) ((Uint8 *) src + srcskip);
dst = (Uint32 *) ((Uint8 *) dst + dstskip);
}
}
static void
BlitNtoN(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
int srcbpp = srcfmt->BytesPerPixel;
SDL_PixelFormat *dstfmt = info->dst_fmt;
int dstbpp = dstfmt->BytesPerPixel;
unsigned alpha = dstfmt->Amask ? info->a : 0;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
Uint32 Pixel;
unsigned sR;
unsigned sG;
unsigned sB;
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB);
ASSEMBLE_RGBA(dst, dstbpp, dstfmt, sR, sG, sB, alpha);
dst += dstbpp;
src += srcbpp;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
}
static void
BlitNtoNCopyAlpha(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
int srcbpp = srcfmt->BytesPerPixel;
SDL_PixelFormat *dstfmt = info->dst_fmt;
int dstbpp = dstfmt->BytesPerPixel;
int c;
while (height--) {
for (c = width; c; --c) {
Uint32 Pixel;
unsigned sR, sG, sB, sA;
DISEMBLE_RGBA(src, srcbpp, srcfmt, Pixel, sR, sG, sB, sA);
ASSEMBLE_RGBA(dst, dstbpp, dstfmt, sR, sG, sB, sA);
dst += dstbpp;
src += srcbpp;
}
src += srcskip;
dst += dstskip;
}
}
static void
BlitNto1Key(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
const Uint8 *palmap = info->table;
Uint32 ckey = info->colorkey;
Uint32 rgbmask = ~srcfmt->Amask;
int srcbpp;
Uint32 Pixel;
unsigned sR, sG, sB;
/* Set up some basic variables */
srcbpp = srcfmt->BytesPerPixel;
ckey &= rgbmask;
if (palmap == NULL) {
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel,
sR, sG, sB);
if ( (Pixel & rgbmask) != ckey ) {
/* Pack RGB into 8bit pixel */
*dst = (Uint8)(((sR>>5)<<(3+2))|
((sG>>5)<<(2)) |
((sB>>6)<<(0)));
}
dst++;
src += srcbpp;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
} else {
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel,
sR, sG, sB);
if ( (Pixel & rgbmask) != ckey ) {
/* Pack RGB into 8bit pixel */
*dst = (Uint8)palmap[((sR>>5)<<(3+2))|
((sG>>5)<<(2)) |
((sB>>6)<<(0)) ];
}
dst++;
src += srcbpp;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
}
}
static void
Blit2to2Key(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint16 *srcp = (Uint16 *) info->src;
int srcskip = info->src_skip;
Uint16 *dstp = (Uint16 *) info->dst;
int dstskip = info->dst_skip;
Uint32 ckey = info->colorkey;
Uint32 rgbmask = ~info->src_fmt->Amask;
/* Set up some basic variables */
srcskip /= 2;
dstskip /= 2;
ckey &= rgbmask;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
if ( (*srcp & rgbmask) != ckey ) {
*dstp = *srcp;
}
dstp++;
srcp++;
},
width);
/* *INDENT-ON* */
srcp += srcskip;
dstp += dstskip;
}
}
static void
BlitNtoNKey(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
Uint32 ckey = info->colorkey;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
int srcbpp = srcfmt->BytesPerPixel;
int dstbpp = dstfmt->BytesPerPixel;
unsigned alpha = dstfmt->Amask ? info->a : 0;
Uint32 rgbmask = ~srcfmt->Amask;
/* Set up some basic variables */
ckey &= rgbmask;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
Uint32 Pixel;
unsigned sR;
unsigned sG;
unsigned sB;
RETRIEVE_RGB_PIXEL(src, srcbpp, Pixel);
if ( (Pixel & rgbmask) != ckey ) {
RGB_FROM_PIXEL(Pixel, srcfmt, sR, sG, sB);
ASSEMBLE_RGBA(dst, dstbpp, dstfmt, sR, sG, sB, alpha);
}
dst += dstbpp;
src += srcbpp;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
}
static void
BlitNtoNKeyCopyAlpha(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
Uint32 ckey = info->colorkey;
SDL_PixelFormat *srcfmt = info->src_fmt;
SDL_PixelFormat *dstfmt = info->dst_fmt;
Uint32 rgbmask = ~srcfmt->Amask;
Uint8 srcbpp;
Uint8 dstbpp;
Uint32 Pixel;
unsigned sR, sG, sB, sA;
/* Set up some basic variables */
srcbpp = srcfmt->BytesPerPixel;
dstbpp = dstfmt->BytesPerPixel;
ckey &= rgbmask;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
DISEMBLE_RGBA(src, srcbpp, srcfmt, Pixel, sR, sG, sB, sA);
if ( (Pixel & rgbmask) != ckey ) {
ASSEMBLE_RGBA(dst, dstbpp, dstfmt, sR, sG, sB, sA);
}
dst += dstbpp;
src += srcbpp;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
}
/* Special optimized blit for ARGB 2-10-10-10 --> RGBA */
static void
Blit2101010toN(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *dstfmt = info->dst_fmt;
int dstbpp = dstfmt->BytesPerPixel;
Uint32 Pixel;
unsigned sR, sG, sB, sA;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
Pixel = *(Uint32 *)src;
RGBA_FROM_ARGB2101010(Pixel, sR, sG, sB, sA);
ASSEMBLE_RGBA(dst, dstbpp, dstfmt, sR, sG, sB, sA);
dst += dstbpp;
src += 4;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
}
/* Special optimized blit for RGBA --> ARGB 2-10-10-10 */
static void
BlitNto2101010(SDL_BlitInfo * info)
{
int width = info->dst_w;
int height = info->dst_h;
Uint8 *src = info->src;
int srcskip = info->src_skip;
Uint8 *dst = info->dst;
int dstskip = info->dst_skip;
SDL_PixelFormat *srcfmt = info->src_fmt;
int srcbpp = srcfmt->BytesPerPixel;
Uint32 Pixel;
unsigned sR, sG, sB, sA;
while (height--) {
/* *INDENT-OFF* */
DUFFS_LOOP(
{
DISEMBLE_RGBA(src, srcbpp, srcfmt, Pixel, sR, sG, sB, sA);
ARGB2101010_FROM_RGBA(Pixel, sR, sG, sB, sA);
*(Uint32 *)dst = Pixel;
dst += 4;
src += srcbpp;
},
width);
/* *INDENT-ON* */
src += srcskip;
dst += dstskip;
}
}
/* Normal N to N optimized blitters */
struct blit_table
{
Uint32 srcR, srcG, srcB;
int dstbpp;
Uint32 dstR, dstG, dstB;
Uint32 blit_features;
SDL_BlitFunc blitfunc;
enum
{ NO_ALPHA = 1, SET_ALPHA = 2, COPY_ALPHA = 4 } alpha;
};
static const struct blit_table normal_blit_1[] = {
/* Default for 8-bit RGB source, never optimized */
{0, 0, 0, 0, 0, 0, 0, 0, BlitNtoN, 0}
};
static const struct blit_table normal_blit_2[] = {
#if SDL_ALTIVEC_BLITTERS
/* has-altivec */
{0x0000F800, 0x000007E0, 0x0000001F, 4, 0x00000000, 0x00000000, 0x00000000,
2, Blit_RGB565_32Altivec, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
{0x00007C00, 0x000003E0, 0x0000001F, 4, 0x00000000, 0x00000000, 0x00000000,
2, Blit_RGB555_32Altivec, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
#endif
{0x0000F800, 0x000007E0, 0x0000001F, 4, 0x00FF0000, 0x0000FF00, 0x000000FF,
0, Blit_RGB565_ARGB8888, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
{0x0000F800, 0x000007E0, 0x0000001F, 4, 0x000000FF, 0x0000FF00, 0x00FF0000,
0, Blit_RGB565_ABGR8888, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
{0x0000F800, 0x000007E0, 0x0000001F, 4, 0xFF000000, 0x00FF0000, 0x0000FF00,
0, Blit_RGB565_RGBA8888, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
{0x0000F800, 0x000007E0, 0x0000001F, 4, 0x0000FF00, 0x00FF0000, 0xFF000000,
0, Blit_RGB565_BGRA8888, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
/* Default for 16-bit RGB source, used if no other blitter matches */
{0, 0, 0, 0, 0, 0, 0, 0, BlitNtoN, 0}
};
static const struct blit_table normal_blit_3[] = {
/* Default for 24-bit RGB source, never optimized */
{0, 0, 0, 0, 0, 0, 0, 0, BlitNtoN, 0}
};
static const struct blit_table normal_blit_4[] = {
#if SDL_ALTIVEC_BLITTERS
/* has-altivec | dont-use-prefetch */
{0x00000000, 0x00000000, 0x00000000, 4, 0x00000000, 0x00000000, 0x00000000,
6, ConvertAltivec32to32_noprefetch, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
/* has-altivec */
{0x00000000, 0x00000000, 0x00000000, 4, 0x00000000, 0x00000000, 0x00000000,
2, ConvertAltivec32to32_prefetch, NO_ALPHA | COPY_ALPHA | SET_ALPHA},
/* has-altivec */
{0x00000000, 0x00000000, 0x00000000, 2, 0x0000F800, 0x000007E0, 0x0000001F,
2, Blit_RGB888_RGB565Altivec, NO_ALPHA},
#endif
{0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000F800, 0x000007E0, 0x0000001F,
0, Blit_RGB888_RGB565, NO_ALPHA},
{0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x00007C00, 0x000003E0, 0x0000001F,
0, Blit_RGB888_RGB555, NO_ALPHA},
/* Default for 32-bit RGB source, used if no other blitter matches */
{0, 0, 0, 0, 0, 0, 0, 0, BlitNtoN, 0}
};
static const struct blit_table *const normal_blit[] = {
normal_blit_1, normal_blit_2, normal_blit_3, normal_blit_4
};
/* Mask matches table, or table entry is zero */
#define MASKOK(x, y) (((x) == (y)) || ((y) == 0x00000000))
SDL_BlitFunc
SDL_CalculateBlitN(SDL_Surface * surface)
{
SDL_PixelFormat *srcfmt;
SDL_PixelFormat *dstfmt;
const struct blit_table *table;
int which;
SDL_BlitFunc blitfun;
/* Set up data for choosing the blit */
srcfmt = surface->format;
dstfmt = surface->map->dst->format;
/* We don't support destinations less than 8-bits */
if (dstfmt->BitsPerPixel < 8) {
return (NULL);
}
switch (surface->map->info.flags & ~SDL_COPY_RLE_MASK) {
case 0:
blitfun = NULL;
if (dstfmt->BitsPerPixel == 8) {
if ((srcfmt->BytesPerPixel == 4) &&
(srcfmt->Rmask == 0x00FF0000) &&
(srcfmt->Gmask == 0x0000FF00) &&
(srcfmt->Bmask == 0x000000FF)) {
blitfun = Blit_RGB888_index8;
} else if ((srcfmt->BytesPerPixel == 4) &&
(srcfmt->Rmask == 0x3FF00000) &&
(srcfmt->Gmask == 0x000FFC00) &&
(srcfmt->Bmask == 0x000003FF)) {
blitfun = Blit_RGB101010_index8;
} else {
blitfun = BlitNto1;
}
} else {
/* Now the meat, choose the blitter we want */
int a_need = NO_ALPHA;
if (dstfmt->Amask)
a_need = srcfmt->Amask ? COPY_ALPHA : SET_ALPHA;
table = normal_blit[srcfmt->BytesPerPixel - 1];
for (which = 0; table[which].dstbpp; ++which) {
if (MASKOK(srcfmt->Rmask, table[which].srcR) &&
MASKOK(srcfmt->Gmask, table[which].srcG) &&
MASKOK(srcfmt->Bmask, table[which].srcB) &&
MASKOK(dstfmt->Rmask, table[which].dstR) &&
MASKOK(dstfmt->Gmask, table[which].dstG) &&
MASKOK(dstfmt->Bmask, table[which].dstB) &&
dstfmt->BytesPerPixel == table[which].dstbpp &&
(a_need & table[which].alpha) == a_need &&
((table[which].blit_features & GetBlitFeatures()) ==
table[which].blit_features))
break;
}
blitfun = table[which].blitfunc;
if (blitfun == BlitNtoN) { /* default C fallback catch-all. Slow! */
if (srcfmt->format == SDL_PIXELFORMAT_ARGB2101010) {
blitfun = Blit2101010toN;
} else if (dstfmt->format == SDL_PIXELFORMAT_ARGB2101010) {
blitfun = BlitNto2101010;
} else if (srcfmt->BytesPerPixel == 4 &&
dstfmt->BytesPerPixel == 4 &&
srcfmt->Rmask == dstfmt->Rmask &&
srcfmt->Gmask == dstfmt->Gmask &&
srcfmt->Bmask == dstfmt->Bmask) {
if (a_need == COPY_ALPHA) {
if (srcfmt->Amask == dstfmt->Amask) {
/* Fastpath C fallback: 32bit RGBA<->RGBA blit with matching RGBA */
blitfun = Blit4to4CopyAlpha;
} else {
blitfun = BlitNtoNCopyAlpha;
}
} else {
/* Fastpath C fallback: 32bit RGB<->RGBA blit with matching RGB */
blitfun = Blit4to4MaskAlpha;
}
} else if (a_need == COPY_ALPHA) {
blitfun = BlitNtoNCopyAlpha;
}
}
}
return (blitfun);
case SDL_COPY_COLORKEY:
/* colorkey blit: Here we don't have too many options, mostly
because RLE is the preferred fast way to deal with this.
If a particular case turns out to be useful we'll add it. */
if (srcfmt->BytesPerPixel == 2 && surface->map->identity)
return Blit2to2Key;
else if (dstfmt->BytesPerPixel == 1)
return BlitNto1Key;
else {
#if SDL_ALTIVEC_BLITTERS
if ((srcfmt->BytesPerPixel == 4) && (dstfmt->BytesPerPixel == 4)
&& SDL_HasAltiVec()) {
return Blit32to32KeyAltivec;
} else
#endif
if (srcfmt->Amask && dstfmt->Amask) {
return BlitNtoNKeyCopyAlpha;
} else {
return BlitNtoNKey;
}
}
}
return NULL;
}
/* vi: set ts=4 sw=4 expandtab: */
| mit |
hdou731/Windows-universal-samples | Samples/XamlCloudFontIntegration/cpp/Scenario_Document2.xaml.cpp | 111 | 1558 | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario_Document2.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
Scenario_Document2::Scenario_Document2()
{
InitializeComponent();
}
void Scenario_Document2::Page_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Font formatting is being applied on page load rather than in XAML markup
// so that the on-demand cloud font behavior can be experienced when the
// app runs rather than when the XAML file is viewed in Visual Studio.
// Formatting will be applied to all content elements in the page that don't
// already have FontFamily set.
this->FontFamily = ref new Windows::UI::Xaml::Media::FontFamily("FangSong");
}
| mit |
WhiteVell/Amber | node-v0.10.20/deps/openssl/openssl/crypto/engine/tb_rsa.c | 885 | 4189 | /* ====================================================================
* Copyright (c) 2000 The OpenSSL Project. 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "eng_int.h"
/* If this symbol is defined then ENGINE_get_default_RSA(), the function that is
* used by RSA to hook in implementation code and cache defaults (etc), will
* display brief debugging summaries to stderr with the 'nid'. */
/* #define ENGINE_RSA_DEBUG */
static ENGINE_TABLE *rsa_table = NULL;
static const int dummy_nid = 1;
void ENGINE_unregister_RSA(ENGINE *e)
{
engine_table_unregister(&rsa_table, e);
}
static void engine_unregister_all_RSA(void)
{
engine_table_cleanup(&rsa_table);
}
int ENGINE_register_RSA(ENGINE *e)
{
if(e->rsa_meth)
return engine_table_register(&rsa_table,
engine_unregister_all_RSA, e, &dummy_nid, 1, 0);
return 1;
}
void ENGINE_register_all_RSA()
{
ENGINE *e;
for(e=ENGINE_get_first() ; e ; e=ENGINE_get_next(e))
ENGINE_register_RSA(e);
}
int ENGINE_set_default_RSA(ENGINE *e)
{
if(e->rsa_meth)
return engine_table_register(&rsa_table,
engine_unregister_all_RSA, e, &dummy_nid, 1, 1);
return 1;
}
/* Exposed API function to get a functional reference from the implementation
* table (ie. try to get a functional reference from the tabled structural
* references). */
ENGINE *ENGINE_get_default_RSA(void)
{
return engine_table_select(&rsa_table, dummy_nid);
}
/* Obtains an RSA implementation from an ENGINE functional reference */
const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e)
{
return e->rsa_meth;
}
/* Sets an RSA implementation in an ENGINE structure */
int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth)
{
e->rsa_meth = rsa_meth;
return 1;
}
| mit |
kheops/pyramidscoin | src/test/canonical_tests.cpp | 1657 | 2439 | //
// Unit tests for canonical signatures
#include "json/json_spirit_writer_template.h"
#include <boost/test/unit_test.hpp>
#include <openssl/ecdsa.h>
#include "key.h"
#include "script.h"
#include "util.h"
using namespace std;
using namespace json_spirit;
// In script_tests.cpp
extern Array read_json(const std::string& filename);
BOOST_AUTO_TEST_SUITE(canonical_tests)
// OpenSSL-based test for canonical signature (without test for hashtype byte)
bool static IsCanonicalSignature_OpenSSL_inner(const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() == 0)
return false;
const unsigned char *input = &vchSig[0];
ECDSA_SIG *psig = NULL;
d2i_ECDSA_SIG(&psig, &input, vchSig.size());
if (psig == NULL)
return false;
unsigned char buf[256];
unsigned char *pbuf = buf;
unsigned int nLen = i2d_ECDSA_SIG(psig, NULL);
if (nLen != vchSig.size()) {
ECDSA_SIG_free(psig);
return false;
}
nLen = i2d_ECDSA_SIG(psig, &pbuf);
ECDSA_SIG_free(psig);
return (memcmp(&vchSig[0], &buf[0], nLen) == 0);
}
// OpenSSL-based test for canonical signature
bool static IsCanonicalSignature_OpenSSL(const std::vector<unsigned char> &vchSignature) {
if (vchSignature.size() < 1)
return false;
if (vchSignature.size() > 127)
return false;
if (vchSignature[vchSignature.size() - 1] & 0x7C)
return false;
std::vector<unsigned char> vchSig(vchSignature);
vchSig.pop_back();
if (!IsCanonicalSignature_OpenSSL_inner(vchSig))
return false;
return true;
}
BOOST_AUTO_TEST_CASE(script_canon)
{
Array tests = read_json("sig_canonical.json");
BOOST_FOREACH(Value &tv, tests) {
string test = tv.get_str();
if (IsHex(test)) {
std::vector<unsigned char> sig = ParseHex(test);
BOOST_CHECK_MESSAGE(IsCanonicalSignature(sig), test);
BOOST_CHECK_MESSAGE(IsCanonicalSignature_OpenSSL(sig), test);
}
}
}
BOOST_AUTO_TEST_CASE(script_noncanon)
{
Array tests = read_json("sig_noncanonical.json");
BOOST_FOREACH(Value &tv, tests) {
string test = tv.get_str();
if (IsHex(test)) {
std::vector<unsigned char> sig = ParseHex(test);
BOOST_CHECK_MESSAGE(!IsCanonicalSignature(sig), test);
BOOST_CHECK_MESSAGE(!IsCanonicalSignature_OpenSSL(sig), test);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
mediapiglet/piglet | node_modules/exec-sync/node_modules/ffi/deps/pthreads-win32/tests/self1.c | 122 | 2147 | /*
* self1.c
*
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* --------------------------------------------------------------------------
*
* Test for pthread_self().
*
* Depends on API functions:
* pthread_self()
*
* Implicitly depends on:
* pthread_getspecific()
* pthread_setspecific()
*/
#include "test.h"
int
main(int argc, char * argv[])
{
/*
* This should always succeed unless the system has no
* resources (memory) left.
*/
pthread_t self;
#if defined(PTW32_STATIC_LIB) && !(defined(_MSC_VER) || defined(__MINGW32__))
pthread_win32_process_attach_np();
#endif
self = pthread_self();
assert(self.p != NULL);
#if defined(PTW32_STATIC_LIB) && !(defined(_MSC_VER) || defined(__MINGW32__))
pthread_win32_process_detach_np();
#endif
return 0;
}
| mit |
yupcoin/yupcoin | src/netbase.cpp | 1163 | 31527 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "util.h"
#include "sync.h"
#include "hash.h"
#ifndef WIN32
#include <sys/fcntl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
using namespace std;
// Settings
static proxyType proxyInfo[NET_MAX];
static proxyType nameproxyInfo;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = 5000;
bool fNameLookup = false;
static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
enum Network ParseNetwork(std::string net) {
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor") return NET_TOR;
return NET_UNROUTABLE;
}
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
char *endp = NULL;
int n = strtol(in.c_str() + colon + 1, &endp, 10);
if (endp && *endp == 0 && n >= 0) {
in = in.substr(0, colon);
if (n > 0 && n < 0x10000)
portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
hostOut = in.substr(1, in.size()-2);
else
hostOut = in;
}
bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
#ifdef USE_IPV6
aiHint.ai_family = AF_UNSPEC;
#else
aiHint.ai_family = AF_INET;
#endif
#ifdef WIN32
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo *aiRes = NULL;
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
if (nErr)
return false;
struct addrinfo *aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
{
if (aiTrav->ai_family == AF_INET)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
#ifdef USE_IPV6
if (aiTrav->ai_family == AF_INET6)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
#endif
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
std::string strHost(pszName);
if (strHost.empty())
return false;
if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
{
strHost = strHost.substr(1, strHost.size() - 2);
}
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
{
return LookupHost(pszName, vIP, nMaxSolutions, false);
}
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
bool static Socks4(const CService &addrDest, SOCKET& hSocket)
{
printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
if (!addrDest.IsIPv4())
{
closesocket(hSocket);
return error("Proxy destination is not IPv4");
}
char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
{
closesocket(hSocket);
return error("Cannot get proxy destination address");
}
memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
char* pszSocks4 = pszSocks4IP;
int nSize = sizeof(pszSocks4IP);
int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
if (ret != nSize)
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet[8];
if (recv(hSocket, pchRet, 8, 0) != 8)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet[1] != 0x5a)
{
closesocket(hSocket);
if (pchRet[1] != 0x5b)
printf("ERROR: Proxy returned error %d\n", pchRet[1]);
return false;
}
printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
return true;
}
bool static Socks5(string strDest, int port, SOCKET& hSocket)
{
printf("SOCKS5 connecting %s\n", strDest.c_str());
if (strDest.size() > 255)
{
closesocket(hSocket);
return error("Hostname too long");
}
char pszSocks5Init[] = "\5\1\0";
ssize_t nSize = sizeof(pszSocks5Init) - 1;
ssize_t ret = send(hSocket, pszSocks5Init, nSize, MSG_NOSIGNAL);
if (ret != nSize)
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if (recv(hSocket, pchRet1, 2, 0) != 2)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
{
closesocket(hSocket);
return error("Proxy failed to initialize");
}
string strSocks5("\5\1");
strSocks5 += '\000'; strSocks5 += '\003';
strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
strSocks5 += strDest;
strSocks5 += static_cast<char>((port >> 8) & 0xFF);
strSocks5 += static_cast<char>((port >> 0) & 0xFF);
ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)strSocks5.size())
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if (recv(hSocket, pchRet2, 4, 0) != 4)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05)
{
closesocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00)
{
closesocket(hSocket);
switch (pchRet2[1])
{
case 0x01: return error("Proxy error: general failure");
case 0x02: return error("Proxy error: connection not allowed");
case 0x03: return error("Proxy error: network unreachable");
case 0x04: return error("Proxy error: host unreachable");
case 0x05: return error("Proxy error: connection refused");
case 0x06: return error("Proxy error: TTL expired");
case 0x07: return error("Proxy error: protocol error");
case 0x08: return error("Proxy error: address type not supported");
default: return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00)
{
closesocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3])
{
case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
case 0x03:
{
ret = recv(hSocket, pchRet3, 1, 0) != 1;
if (ret)
return error("Error reading from proxy");
int nRecv = pchRet3[0];
ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
break;
}
default: closesocket(hSocket); return error("Error: malformed proxy response");
}
if (ret)
{
closesocket(hSocket);
return error("Error reading from proxy");
}
if (recv(hSocket, pchRet3, 2, 0) != 2)
{
closesocket(hSocket);
return error("Error reading from proxy");
}
printf("SOCKS5 connected %s\n", strDest.c_str());
return true;
}
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
#ifdef SO_NOSIGPIPE
int set = 1;
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
#ifdef WIN32
u_long fNonblock = 1;
if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
{
closesocket(hSocket);
return false;
}
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
// WSAEINVAL is here because some legacy version of winsock uses it
if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0)
{
printf("connection timeout\n");
closesocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR)
{
printf("select() for connection failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
if (nRet != 0)
{
printf("connect() failed after select(): %s\n",strerror(nRet));
closesocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
printf("connect() failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
}
// this isn't even strictly necessary
// CNode::ConnectNode immediately turns the socket back to non-blocking
// but we'll turn it back to blocking just in case
#ifdef WIN32
fNonblock = 0;
if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
#endif
{
closesocket(hSocket);
return false;
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
assert(net >= 0 && net < NET_MAX);
if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
return false;
if (nSocksVersion != 0 && !addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
return true;
}
bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
if (!proxyInfo[net].second)
return false;
proxyInfoOut = proxyInfo[net];
return true;
}
bool SetNameProxy(CService addrProxy, int nSocksVersion) {
if (nSocksVersion != 0 && nSocksVersion != 5)
return false;
if (nSocksVersion != 0 && !addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
return true;
}
bool GetNameProxy(proxyType &nameproxyInfoOut) {
LOCK(cs_proxyInfos);
if (!nameproxyInfo.second)
return false;
nameproxyInfoOut = nameproxyInfo;
return true;
}
bool HaveNameProxy() {
LOCK(cs_proxyInfos);
return nameproxyInfo.second != 0;
}
bool IsProxy(const CNetAddr &addr) {
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
return true;
}
return false;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
proxyType proxy;
// no proxy needed
if (!GetProxy(addrDest.GetNetwork(), proxy))
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
return false;
// do socks negotiation
switch (proxy.second) {
case 4:
if (!Socks4(addrDest, hSocket))
return false;
break;
case 5:
if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
return false;
break;
default:
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
{
string strDest;
int port = portDefault;
SplitHostPort(string(pszDest), port, strDest);
SOCKET hSocket = INVALID_SOCKET;
proxyType nameproxy;
GetNameProxy(nameproxy);
CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
addr = CService("0.0.0.0:0");
if (!nameproxy.second)
return false;
if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
return false;
switch(nameproxy.second) {
default:
case 4: return false;
case 5:
if (!Socks5(strDest, port, hSocket))
return false;
break;
}
hSocketRet = hSocket;
return true;
}
void CNetAddr::Init()
{
memset(ip, 0, sizeof(ip));
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
}
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
bool CNetAddr::SetSpecial(const std::string &strName)
{
if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16-sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
memcpy(ip, pchIPv4, 12);
memcpy(ip+12, &ipv4Addr, 4);
}
#ifdef USE_IPV6
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
memcpy(ip, &ipv6Addr, 16);
}
#endif
CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
unsigned int CNetAddr::GetByte(int n) const
{
return ip[15-n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (
GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
|| (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
// Cleanup 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4())
{
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
CService serv(*this, 0);
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip+12, 4);
return true;
}
#ifdef USE_IPV6
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
#endif
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal())
{
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable())
{
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052())
{
nClass = NET_IPV4;
nStartByte = 12;
}
// for 6to4 tunnelled addresses, use the encapsulated IPv4 address
else if (IsRFC3964())
{
nClass = NET_IPV4;
nStartByte = 2;
}
// for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380())
{
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
}
else if (IsTor())
{
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8)
{
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
return vchRet;
}
uint64 CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64 nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
void CNetAddr::print() const
{
printf("CNetAddr(%s)\n", ToString().c_str());
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch(theirNet) {
case NET_IPV4:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4;
}
case NET_IPV6:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV4: return REACH_IPV4;
case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
}
case NET_TOR:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR: return REACH_PRIVATE;
}
case NET_TEREDO:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
}
}
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
#ifdef USE_IPV6
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
#endif
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
#ifdef USE_IPV6
CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
#endif
bool CService::SetSockAddr(const struct sockaddr *paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
#ifdef USE_IPV6
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
#endif
default:
return false;
}
}
CService::CService(const char *pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
#ifdef USE_IPV6
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
#endif
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%u", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
void CService::print() const
{
printf("CService(%s)\n", ToString().c_str());
}
void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
| mit |
jimmy54/WinObjC | deps/3rdparty/iculegacy/source/test/thaitest/thaitest.cpp | 397 | 16065 | /*
******************************************************************************
* Copyright (C) 1998-2003, 2006, International Business Machines Corporation *
* and others. All Rights Reserved. *
******************************************************************************
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "unicode/utypes.h"
#include "unicode/uchar.h"
#include "unicode/uchriter.h"
#include "unicode/brkiter.h"
#include "unicode/locid.h"
#include "unicode/unistr.h"
#include "unicode/uniset.h"
#include "unicode/ustring.h"
/*
* This program takes a Unicode text file containing Thai text with
* spaces inserted where the word breaks are. It computes a copy of
* the text without spaces and uses a word instance of a Thai BreakIterator
* to compute the word breaks. The program reports any differences in the
* breaks.
*
* NOTE: by it's very nature, Thai word breaking is not exact, so it is
* exptected that this program will always report some differences.
*/
/*
* This class is a break iterator that counts words and spaces.
*/
class SpaceBreakIterator
{
public:
// The constructor:
// text - pointer to an array of UChars to iterate over
// count - the number of UChars in text
SpaceBreakIterator(const UChar *text, int32_t count);
// the destructor
~SpaceBreakIterator();
// return next break position
int32_t next();
// return current word count
int32_t getWordCount();
// return current space count
int32_t getSpaceCount();
private:
// No arg constructor: private so clients can't call it.
SpaceBreakIterator();
// The underlying BreakIterator
BreakIterator *fBreakIter;
// address of the UChar array
const UChar *fText;
// number of UChars in fText
int32_t fTextCount;
// current word count
int32_t fWordCount;
// current space count
int32_t fSpaceCount;
// UnicodeSet of SA characters
UnicodeSet fComplexContext;
// true when fBreakIter has returned DONE
UBool fDone;
};
/*
* This is the main class. It compares word breaks and reports the differences.
*/
class ThaiWordbreakTest
{
public:
// The main constructor:
// spaces - pointer to a UChar array for the text with spaces
// spaceCount - the number of characters in the spaces array
// noSpaces - pointer to a UChar array for the text without spaces
// noSpaceCount - the number of characters in the noSpaces array
// verbose - report all breaks if true, otherwise just report differences
ThaiWordbreakTest(const UChar *spaces, int32_t spaceCount, const UChar *noSpaces, int32_t noSpaceCount, UBool verbose);
~ThaiWordbreakTest();
// returns the number of breaks that are in the spaces array
// but aren't found in the noSpaces array
int32_t getBreaksNotFound();
// returns the number of breaks which are found in the noSpaces
// array but aren't in the spaces array
int32_t getInvalidBreaks();
// returns the number of words found in the spaces array
int32_t getWordCount();
// reads the input Unicode text file:
// fileName - the path name of the file
// charCount - set to the number of UChars read from the file
// returns - the address of the UChar array containing the characters
static const UChar *readFile(char *fileName, int32_t &charCount);
// removes spaces form the input UChar array:
// spaces - pointer to the input UChar array
// count - number of UChars in the spaces array
// nonSpaceCount - the number of UChars in the result array
// returns - the address of the UChar array with spaces removed
static const UChar *crunchSpaces(const UChar *spaces, int32_t count, int32_t &nonSpaceCount);
private:
// The no arg constructor - private so clients can't call it
ThaiWordbreakTest();
// This does the actual comparison:
// spaces - the address of the UChar array for the text with spaces
// spaceCount - the number of UChars in the spaces array
// noSpaces - the address of the UChar array for the text without spaces
// noSpaceCount - the number of UChars in the noSpaces array
// returns - true if all breaks match, FALSE otherwise
UBool compareWordBreaks(const UChar *spaces, int32_t spaceCount,
const UChar *noSpaces, int32_t noSpaceCount);
// helper method to report a break in the spaces
// array that's not found in the noSpaces array
void breakNotFound(int32_t br);
// helper method to report a break that's found in
// the noSpaces array that's not in the spaces array
void foundInvalidBreak(int32_t br);
// count of breaks in the spaces array that
// aren't found in the noSpaces array
int32_t fBreaksNotFound;
// count of breaks found in the noSpaces array
// that aren't in the spaces array
int32_t fInvalidBreaks;
// number of words found in the spaces array
int32_t fWordCount;
// report all breaks if true, otherwise just report differences
UBool fVerbose;
};
/*
* The main constructor: it calls compareWordBreaks and reports any differences
*/
ThaiWordbreakTest::ThaiWordbreakTest(const UChar *spaces, int32_t spaceCount,
const UChar *noSpaces, int32_t noSpaceCount, UBool verbose)
: fBreaksNotFound(0), fInvalidBreaks(0), fWordCount(0), fVerbose(verbose)
{
compareWordBreaks(spaces, spaceCount, noSpaces, noSpaceCount);
}
/*
* The no arg constructor
*/
ThaiWordbreakTest::ThaiWordbreakTest()
{
// nothing
}
/*
* The destructor
*/
ThaiWordbreakTest::~ThaiWordbreakTest()
{
// nothing?
}
/*
* returns the number of breaks in the spaces array
* that aren't found in the noSpaces array
*/
inline int32_t ThaiWordbreakTest::getBreaksNotFound()
{
return fBreaksNotFound;
}
/*
* Returns the number of breaks found in the noSpaces
* array that aren't in the spaces array
*/
inline int32_t ThaiWordbreakTest::getInvalidBreaks()
{
return fInvalidBreaks;
}
/*
* Returns the number of words found in the spaces array
*/
inline int32_t ThaiWordbreakTest::getWordCount()
{
return fWordCount;
}
/*
* This method does the acutal break comparison and reports the results.
* It uses a SpaceBreakIterator to iterate over the text with spaces,
* and a word instance of a Thai BreakIterator to iterate over the text
* without spaces.
*/
UBool ThaiWordbreakTest::compareWordBreaks(const UChar *spaces, int32_t spaceCount,
const UChar *noSpaces, int32_t noSpaceCount)
{
UBool result = TRUE;
Locale thai("th");
UCharCharacterIterator *noSpaceIter = new UCharCharacterIterator(noSpaces, noSpaceCount);
UErrorCode status = U_ZERO_ERROR;
BreakIterator *breakIter = BreakIterator::createWordInstance(thai, status);
breakIter->adoptText(noSpaceIter);
SpaceBreakIterator spaceIter(spaces, spaceCount);
int32_t nextBreak = 0;
int32_t nextSpaceBreak = 0;
int32_t iterCount = 0;
while (TRUE) {
nextSpaceBreak = spaceIter.next();
nextBreak = breakIter->next();
if (nextSpaceBreak == BreakIterator::DONE || nextBreak == BreakIterator::DONE) {
if (nextBreak != BreakIterator::DONE) {
fprintf(stderr, "break iterator didn't end.\n");
} else if (nextSpaceBreak != BreakIterator::DONE) {
fprintf(stderr, "premature break iterator end.\n");
}
break;
}
while (nextSpaceBreak != nextBreak &&
nextSpaceBreak != BreakIterator::DONE && nextBreak != BreakIterator::DONE) {
if (nextSpaceBreak < nextBreak) {
breakNotFound(nextSpaceBreak);
result = FALSE;
nextSpaceBreak = spaceIter.next();
} else if (nextSpaceBreak > nextBreak) {
foundInvalidBreak(nextBreak);
result = FALSE;
nextBreak = breakIter->next();
}
}
if (fVerbose) {
printf("%d %d\n", nextSpaceBreak, nextBreak);
}
}
fWordCount = spaceIter.getWordCount();
delete breakIter;
return result;
}
/*
* Report a break that's in the text with spaces but
* not found in the text without spaces.
*/
void ThaiWordbreakTest::breakNotFound(int32_t br)
{
if (fVerbose) {
printf("%d ****\n", br);
} else {
fprintf(stderr, "break not found: %d\n", br);
}
fBreaksNotFound += 1;
}
/*
* Report a break that's found in the text without spaces
* that isn't in the text with spaces.
*/
void ThaiWordbreakTest::foundInvalidBreak(int32_t br)
{
if (fVerbose) {
printf("**** %d\n", br);
} else {
fprintf(stderr, "found invalid break: %d\n", br);
}
fInvalidBreaks += 1;
}
/*
* Read the text from a file. The text must start with a Unicode Byte
* Order Mark (BOM) so that we know what order to read the bytes in.
*/
const UChar *ThaiWordbreakTest::readFile(char *fileName, int32_t &charCount)
{
FILE *f;
int32_t fileSize;
UChar *buffer;
char *bufferChars;
f = fopen(fileName, "rb");
if( f == NULL ) {
fprintf(stderr,"Couldn't open %s reason: %s \n", fileName, strerror(errno));
return 0;
}
fseek(f, 0, SEEK_END);
fileSize = ftell(f);
fseek(f, 0, SEEK_SET);
bufferChars = new char[fileSize];
if(bufferChars == 0) {
fprintf(stderr,"Couldn't get memory for reading %s reason: %s \n", fileName, strerror(errno));
fclose(f);
return 0;
}
fread(bufferChars, sizeof(char), fileSize, f);
if( ferror(f) ) {
fprintf(stderr,"Couldn't read %s reason: %s \n", fileName, strerror(errno));
fclose(f);
delete[] bufferChars;
return 0;
}
fclose(f);
UnicodeString myText(bufferChars, fileSize, "UTF-8");
delete[] bufferChars;
charCount = myText.length();
buffer = new UChar[charCount];
if(buffer == 0) {
fprintf(stderr,"Couldn't get memory for reading %s reason: %s \n", fileName, strerror(errno));
return 0;
}
myText.extract(1, myText.length(), buffer);
charCount--; // skip the BOM
buffer[charCount] = 0; // NULL terminate for easier reading in the debugger
return buffer;
}
/*
* Remove spaces from the input UChar array.
*
* We check explicitly for a Unicode code value of 0x0020
* because Unicode::isSpaceChar returns true for CR, LF, etc.
*
*/
const UChar *ThaiWordbreakTest::crunchSpaces(const UChar *spaces, int32_t count, int32_t &nonSpaceCount)
{
int32_t i, out, spaceCount;
spaceCount = 0;
for (i = 0; i < count; i += 1) {
if (spaces[i] == 0x0020 /*Unicode::isSpaceChar(spaces[i])*/) {
spaceCount += 1;
}
}
nonSpaceCount = count - spaceCount;
UChar *noSpaces = new UChar[nonSpaceCount];
if (noSpaces == 0) {
fprintf(stderr, "Couldn't allocate memory for the space stripped text.\n");
return 0;
}
for (out = 0, i = 0; i < count; i += 1) {
if (spaces[i] != 0x0020 /*! Unicode::isSpaceChar(spaces[i])*/) {
noSpaces[out++] = spaces[i];
}
}
return noSpaces;
}
/*
* Generate a text file with spaces in it from a file without.
*/
int generateFile(const UChar *chars, int32_t length) {
Locale root("");
UCharCharacterIterator *noSpaceIter = new UCharCharacterIterator(chars, length);
UErrorCode status = U_ZERO_ERROR;
UnicodeSet complexContext(UNICODE_STRING_SIMPLE("[:LineBreak=SA:]"), status);
BreakIterator *breakIter = BreakIterator::createWordInstance(root, status);
breakIter->adoptText(noSpaceIter);
char outbuf[1024];
int32_t strlength;
UChar bom = 0xFEFF;
printf("%s", u_strToUTF8(outbuf, sizeof(outbuf), &strlength, &bom, 1, &status));
int32_t prevbreak = 0;
while (U_SUCCESS(status)) {
int32_t nextbreak = breakIter->next();
if (nextbreak == BreakIterator::DONE) {
break;
}
printf("%s", u_strToUTF8(outbuf, sizeof(outbuf), &strlength, &chars[prevbreak],
nextbreak-prevbreak, &status));
if (nextbreak > 0 && complexContext.contains(chars[nextbreak-1])
&& complexContext.contains(chars[nextbreak])) {
printf(" ");
}
prevbreak = nextbreak;
}
if (U_FAILURE(status)) {
fprintf(stderr, "generate failed: %s\n", u_errorName(status));
return status;
}
else {
return 0;
}
}
/*
* The main routine. Read the command line arguments, read the text file,
* remove the spaces, do the comparison and report the final results
*/
int main(int argc, char **argv)
{
char *fileName = "space.txt";
int arg = 1;
UBool verbose = FALSE;
UBool generate = FALSE;
if (argc >= 2 && strcmp(argv[1], "-generate") == 0) {
generate = TRUE;
arg += 1;
}
if (argc >= 2 && strcmp(argv[1], "-verbose") == 0) {
verbose = TRUE;
arg += 1;
}
if (arg == argc - 1) {
fileName = argv[arg++];
}
if (arg != argc) {
fprintf(stderr, "Usage: %s [-verbose] [<file>]\n", argv[0]);
return 1;
}
int32_t spaceCount, nonSpaceCount;
const UChar *spaces, *noSpaces;
spaces = ThaiWordbreakTest::readFile(fileName, spaceCount);
if (spaces == 0) {
return 1;
}
if (generate) {
return generateFile(spaces, spaceCount);
}
noSpaces = ThaiWordbreakTest::crunchSpaces(spaces, spaceCount, nonSpaceCount);
if (noSpaces == 0) {
return 1;
}
ThaiWordbreakTest test(spaces, spaceCount, noSpaces, nonSpaceCount, verbose);
printf("word count: %d\n", test.getWordCount());
printf("breaks not found: %d\n", test.getBreaksNotFound());
printf("invalid breaks found: %d\n", test.getInvalidBreaks());
return 0;
}
/*
* The main constructor. Clear all the counts and construct a default
* word instance of a BreakIterator.
*/
SpaceBreakIterator::SpaceBreakIterator(const UChar *text, int32_t count)
: fBreakIter(0), fText(text), fTextCount(count), fWordCount(0), fSpaceCount(0), fDone(FALSE)
{
UCharCharacterIterator *iter = new UCharCharacterIterator(text, count);
UErrorCode status = U_ZERO_ERROR;
fComplexContext.applyPattern(UNICODE_STRING_SIMPLE("[:LineBreak=SA:]"), status);
Locale root("");
fBreakIter = BreakIterator::createWordInstance(root, status);
fBreakIter->adoptText(iter);
}
SpaceBreakIterator::SpaceBreakIterator()
{
// nothing
}
/*
* The destructor. delete the underlying BreakIterator
*/
SpaceBreakIterator::~SpaceBreakIterator()
{
delete fBreakIter;
}
/*
* Return the next break, counting words and spaces.
*/
int32_t SpaceBreakIterator::next()
{
if (fDone) {
return BreakIterator::DONE;
}
int32_t nextBreak;
do {
nextBreak = fBreakIter->next();
if (nextBreak == BreakIterator::DONE) {
fDone = TRUE;
return BreakIterator::DONE;
}
}
while(nextBreak > 0 && fComplexContext.contains(fText[nextBreak-1])
&& fComplexContext.contains(fText[nextBreak]));
int32_t result = nextBreak - fSpaceCount;
if (nextBreak < fTextCount) {
if (fText[nextBreak] == 0x0020 /*Unicode::isSpaceChar(fText[nextBreak])*/) {
fSpaceCount += fBreakIter->next() - nextBreak;
}
}
fWordCount += 1;
return result;
}
/*
* Returns the current space count
*/
int32_t SpaceBreakIterator::getSpaceCount()
{
return fSpaceCount;
}
/*
* Returns the current word count
*/
int32_t SpaceBreakIterator::getWordCount()
{
return fWordCount;
}
| mit |
wilseypa/odroidNetworking | linux/fs/nfs/nfs4xdr.c | 657 | 188924 | /*
* fs/nfs/nfs4xdr.c
*
* Client-side XDR for NFSv4.
*
* Copyright (c) 2002 The Regents of the University of Michigan.
* All rights reserved.
*
* Kendrick Smith <kmsmith@umich.edu>
* Andy Adamson <andros@umich.edu>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/param.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/in.h>
#include <linux/pagemap.h>
#include <linux/proc_fs.h>
#include <linux/kdev_t.h>
#include <linux/module.h>
#include <linux/utsname.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/msg_prot.h>
#include <linux/sunrpc/gss_api.h>
#include <linux/nfs.h>
#include <linux/nfs4.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_idmap.h>
#include "nfs4_fs.h"
#include "internal.h"
#include "pnfs.h"
#define NFSDBG_FACILITY NFSDBG_XDR
/* Mapping from NFS error code to "errno" error code. */
#define errno_NFSERR_IO EIO
static int nfs4_stat_to_errno(int);
/* NFSv4 COMPOUND tags are only wanted for debugging purposes */
#ifdef DEBUG
#define NFS4_MAXTAGLEN 20
#else
#define NFS4_MAXTAGLEN 0
#endif
/* lock,open owner id:
* we currently use size 2 (u64) out of (NFS4_OPAQUE_LIMIT >> 2)
*/
#define open_owner_id_maxsz (1 + 2 + 1 + 1 + 2)
#define lock_owner_id_maxsz (1 + 1 + 4)
#define decode_lockowner_maxsz (1 + XDR_QUADLEN(IDMAP_NAMESZ))
#define compound_encode_hdr_maxsz (3 + (NFS4_MAXTAGLEN >> 2))
#define compound_decode_hdr_maxsz (3 + (NFS4_MAXTAGLEN >> 2))
#define op_encode_hdr_maxsz (1)
#define op_decode_hdr_maxsz (2)
#define encode_stateid_maxsz (XDR_QUADLEN(NFS4_STATEID_SIZE))
#define decode_stateid_maxsz (XDR_QUADLEN(NFS4_STATEID_SIZE))
#define encode_verifier_maxsz (XDR_QUADLEN(NFS4_VERIFIER_SIZE))
#define decode_verifier_maxsz (XDR_QUADLEN(NFS4_VERIFIER_SIZE))
#define encode_putfh_maxsz (op_encode_hdr_maxsz + 1 + \
(NFS4_FHSIZE >> 2))
#define decode_putfh_maxsz (op_decode_hdr_maxsz)
#define encode_putrootfh_maxsz (op_encode_hdr_maxsz)
#define decode_putrootfh_maxsz (op_decode_hdr_maxsz)
#define encode_getfh_maxsz (op_encode_hdr_maxsz)
#define decode_getfh_maxsz (op_decode_hdr_maxsz + 1 + \
((3+NFS4_FHSIZE) >> 2))
#define nfs4_fattr_bitmap_maxsz 4
#define encode_getattr_maxsz (op_encode_hdr_maxsz + nfs4_fattr_bitmap_maxsz)
#define nfs4_name_maxsz (1 + ((3 + NFS4_MAXNAMLEN) >> 2))
#define nfs4_path_maxsz (1 + ((3 + NFS4_MAXPATHLEN) >> 2))
#define nfs4_owner_maxsz (1 + XDR_QUADLEN(IDMAP_NAMESZ))
#define nfs4_group_maxsz (1 + XDR_QUADLEN(IDMAP_NAMESZ))
/* This is based on getfattr, which uses the most attributes: */
#define nfs4_fattr_value_maxsz (1 + (1 + 2 + 2 + 4 + 2 + 1 + 1 + 2 + 2 + \
3 + 3 + 3 + nfs4_owner_maxsz + nfs4_group_maxsz))
#define nfs4_fattr_maxsz (nfs4_fattr_bitmap_maxsz + \
nfs4_fattr_value_maxsz)
#define decode_getattr_maxsz (op_decode_hdr_maxsz + nfs4_fattr_maxsz)
#define encode_attrs_maxsz (nfs4_fattr_bitmap_maxsz + \
1 + 2 + 1 + \
nfs4_owner_maxsz + \
nfs4_group_maxsz + \
4 + 4)
#define encode_savefh_maxsz (op_encode_hdr_maxsz)
#define decode_savefh_maxsz (op_decode_hdr_maxsz)
#define encode_restorefh_maxsz (op_encode_hdr_maxsz)
#define decode_restorefh_maxsz (op_decode_hdr_maxsz)
#define encode_fsinfo_maxsz (encode_getattr_maxsz)
/* The 5 accounts for the PNFS attributes, and assumes that at most three
* layout types will be returned.
*/
#define decode_fsinfo_maxsz (op_decode_hdr_maxsz + \
nfs4_fattr_bitmap_maxsz + 4 + 8 + 5)
#define encode_renew_maxsz (op_encode_hdr_maxsz + 3)
#define decode_renew_maxsz (op_decode_hdr_maxsz)
#define encode_setclientid_maxsz \
(op_encode_hdr_maxsz + \
XDR_QUADLEN(NFS4_VERIFIER_SIZE) + \
XDR_QUADLEN(NFS4_SETCLIENTID_NAMELEN) + \
1 /* sc_prog */ + \
XDR_QUADLEN(RPCBIND_MAXNETIDLEN) + \
XDR_QUADLEN(RPCBIND_MAXUADDRLEN) + \
1) /* sc_cb_ident */
#define decode_setclientid_maxsz \
(op_decode_hdr_maxsz + \
2 + \
1024) /* large value for CLID_INUSE */
#define encode_setclientid_confirm_maxsz \
(op_encode_hdr_maxsz + \
3 + (NFS4_VERIFIER_SIZE >> 2))
#define decode_setclientid_confirm_maxsz \
(op_decode_hdr_maxsz)
#define encode_lookup_maxsz (op_encode_hdr_maxsz + nfs4_name_maxsz)
#define decode_lookup_maxsz (op_decode_hdr_maxsz)
#define encode_share_access_maxsz \
(2)
#define encode_createmode_maxsz (1 + encode_attrs_maxsz + encode_verifier_maxsz)
#define encode_opentype_maxsz (1 + encode_createmode_maxsz)
#define encode_claim_null_maxsz (1 + nfs4_name_maxsz)
#define encode_open_maxsz (op_encode_hdr_maxsz + \
2 + encode_share_access_maxsz + 2 + \
open_owner_id_maxsz + \
encode_opentype_maxsz + \
encode_claim_null_maxsz)
#define decode_ace_maxsz (3 + nfs4_owner_maxsz)
#define decode_delegation_maxsz (1 + decode_stateid_maxsz + 1 + \
decode_ace_maxsz)
#define decode_change_info_maxsz (5)
#define decode_open_maxsz (op_decode_hdr_maxsz + \
decode_stateid_maxsz + \
decode_change_info_maxsz + 1 + \
nfs4_fattr_bitmap_maxsz + \
decode_delegation_maxsz)
#define encode_open_confirm_maxsz \
(op_encode_hdr_maxsz + \
encode_stateid_maxsz + 1)
#define decode_open_confirm_maxsz \
(op_decode_hdr_maxsz + \
decode_stateid_maxsz)
#define encode_open_downgrade_maxsz \
(op_encode_hdr_maxsz + \
encode_stateid_maxsz + 1 + \
encode_share_access_maxsz)
#define decode_open_downgrade_maxsz \
(op_decode_hdr_maxsz + \
decode_stateid_maxsz)
#define encode_close_maxsz (op_encode_hdr_maxsz + \
1 + encode_stateid_maxsz)
#define decode_close_maxsz (op_decode_hdr_maxsz + \
decode_stateid_maxsz)
#define encode_setattr_maxsz (op_encode_hdr_maxsz + \
encode_stateid_maxsz + \
encode_attrs_maxsz)
#define decode_setattr_maxsz (op_decode_hdr_maxsz + \
nfs4_fattr_bitmap_maxsz)
#define encode_read_maxsz (op_encode_hdr_maxsz + \
encode_stateid_maxsz + 3)
#define decode_read_maxsz (op_decode_hdr_maxsz + 2)
#define encode_readdir_maxsz (op_encode_hdr_maxsz + \
2 + encode_verifier_maxsz + 5)
#define decode_readdir_maxsz (op_decode_hdr_maxsz + \
decode_verifier_maxsz)
#define encode_readlink_maxsz (op_encode_hdr_maxsz)
#define decode_readlink_maxsz (op_decode_hdr_maxsz + 1)
#define encode_write_maxsz (op_encode_hdr_maxsz + \
encode_stateid_maxsz + 4)
#define decode_write_maxsz (op_decode_hdr_maxsz + \
2 + decode_verifier_maxsz)
#define encode_commit_maxsz (op_encode_hdr_maxsz + 3)
#define decode_commit_maxsz (op_decode_hdr_maxsz + \
decode_verifier_maxsz)
#define encode_remove_maxsz (op_encode_hdr_maxsz + \
nfs4_name_maxsz)
#define decode_remove_maxsz (op_decode_hdr_maxsz + \
decode_change_info_maxsz)
#define encode_rename_maxsz (op_encode_hdr_maxsz + \
2 * nfs4_name_maxsz)
#define decode_rename_maxsz (op_decode_hdr_maxsz + \
decode_change_info_maxsz + \
decode_change_info_maxsz)
#define encode_link_maxsz (op_encode_hdr_maxsz + \
nfs4_name_maxsz)
#define decode_link_maxsz (op_decode_hdr_maxsz + decode_change_info_maxsz)
#define encode_lockowner_maxsz (7)
#define encode_lock_maxsz (op_encode_hdr_maxsz + \
7 + \
1 + encode_stateid_maxsz + 1 + \
encode_lockowner_maxsz)
#define decode_lock_denied_maxsz \
(8 + decode_lockowner_maxsz)
#define decode_lock_maxsz (op_decode_hdr_maxsz + \
decode_lock_denied_maxsz)
#define encode_lockt_maxsz (op_encode_hdr_maxsz + 5 + \
encode_lockowner_maxsz)
#define decode_lockt_maxsz (op_decode_hdr_maxsz + \
decode_lock_denied_maxsz)
#define encode_locku_maxsz (op_encode_hdr_maxsz + 3 + \
encode_stateid_maxsz + \
4)
#define decode_locku_maxsz (op_decode_hdr_maxsz + \
decode_stateid_maxsz)
#define encode_release_lockowner_maxsz \
(op_encode_hdr_maxsz + \
encode_lockowner_maxsz)
#define decode_release_lockowner_maxsz \
(op_decode_hdr_maxsz)
#define encode_access_maxsz (op_encode_hdr_maxsz + 1)
#define decode_access_maxsz (op_decode_hdr_maxsz + 2)
#define encode_symlink_maxsz (op_encode_hdr_maxsz + \
1 + nfs4_name_maxsz + \
1 + \
nfs4_fattr_maxsz)
#define decode_symlink_maxsz (op_decode_hdr_maxsz + 8)
#define encode_create_maxsz (op_encode_hdr_maxsz + \
1 + 2 + nfs4_name_maxsz + \
encode_attrs_maxsz)
#define decode_create_maxsz (op_decode_hdr_maxsz + \
decode_change_info_maxsz + \
nfs4_fattr_bitmap_maxsz)
#define encode_statfs_maxsz (encode_getattr_maxsz)
#define decode_statfs_maxsz (decode_getattr_maxsz)
#define encode_delegreturn_maxsz (op_encode_hdr_maxsz + 4)
#define decode_delegreturn_maxsz (op_decode_hdr_maxsz)
#define encode_getacl_maxsz (encode_getattr_maxsz)
#define decode_getacl_maxsz (op_decode_hdr_maxsz + \
nfs4_fattr_bitmap_maxsz + 1)
#define encode_setacl_maxsz (op_encode_hdr_maxsz + \
encode_stateid_maxsz + 3)
#define decode_setacl_maxsz (decode_setattr_maxsz)
#define encode_fs_locations_maxsz \
(encode_getattr_maxsz)
#define decode_fs_locations_maxsz \
(0)
#define encode_secinfo_maxsz (op_encode_hdr_maxsz + nfs4_name_maxsz)
#define decode_secinfo_maxsz (op_decode_hdr_maxsz + 1 + ((NFS_MAX_SECFLAVORS * (16 + GSS_OID_MAX_LEN)) / 4))
#if defined(CONFIG_NFS_V4_1)
#define NFS4_MAX_MACHINE_NAME_LEN (64)
#define encode_exchange_id_maxsz (op_encode_hdr_maxsz + \
encode_verifier_maxsz + \
1 /* co_ownerid.len */ + \
XDR_QUADLEN(NFS4_EXCHANGE_ID_LEN) + \
1 /* flags */ + \
1 /* spa_how */ + \
0 /* SP4_NONE (for now) */ + \
1 /* implementation id array of size 1 */ + \
1 /* nii_domain */ + \
XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + \
1 /* nii_name */ + \
XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + \
3 /* nii_date */)
#define decode_exchange_id_maxsz (op_decode_hdr_maxsz + \
2 /* eir_clientid */ + \
1 /* eir_sequenceid */ + \
1 /* eir_flags */ + \
1 /* spr_how */ + \
0 /* SP4_NONE (for now) */ + \
2 /* eir_server_owner.so_minor_id */ + \
/* eir_server_owner.so_major_id<> */ \
XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + 1 + \
/* eir_server_scope<> */ \
XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + 1 + \
1 /* eir_server_impl_id array length */ + \
1 /* nii_domain */ + \
XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + \
1 /* nii_name */ + \
XDR_QUADLEN(NFS4_OPAQUE_LIMIT) + \
3 /* nii_date */)
#define encode_channel_attrs_maxsz (6 + 1 /* ca_rdma_ird.len (0) */)
#define decode_channel_attrs_maxsz (6 + \
1 /* ca_rdma_ird.len */ + \
1 /* ca_rdma_ird */)
#define encode_create_session_maxsz (op_encode_hdr_maxsz + \
2 /* csa_clientid */ + \
1 /* csa_sequence */ + \
1 /* csa_flags */ + \
encode_channel_attrs_maxsz + \
encode_channel_attrs_maxsz + \
1 /* csa_cb_program */ + \
1 /* csa_sec_parms.len (1) */ + \
1 /* cb_secflavor (AUTH_SYS) */ + \
1 /* stamp */ + \
1 /* machinename.len */ + \
XDR_QUADLEN(NFS4_MAX_MACHINE_NAME_LEN) + \
1 /* uid */ + \
1 /* gid */ + \
1 /* gids.len (0) */)
#define decode_create_session_maxsz (op_decode_hdr_maxsz + \
XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
1 /* csr_sequence */ + \
1 /* csr_flags */ + \
decode_channel_attrs_maxsz + \
decode_channel_attrs_maxsz)
#define encode_destroy_session_maxsz (op_encode_hdr_maxsz + 4)
#define decode_destroy_session_maxsz (op_decode_hdr_maxsz)
#define encode_sequence_maxsz (op_encode_hdr_maxsz + \
XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + 4)
#define decode_sequence_maxsz (op_decode_hdr_maxsz + \
XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + 5)
#define encode_reclaim_complete_maxsz (op_encode_hdr_maxsz + 4)
#define decode_reclaim_complete_maxsz (op_decode_hdr_maxsz + 4)
#define encode_getdevicelist_maxsz (op_encode_hdr_maxsz + 4 + \
encode_verifier_maxsz)
#define decode_getdevicelist_maxsz (op_decode_hdr_maxsz + \
2 /* nfs_cookie4 gdlr_cookie */ + \
decode_verifier_maxsz \
/* verifier4 gdlr_verifier */ + \
1 /* gdlr_deviceid_list count */ + \
XDR_QUADLEN(NFS4_PNFS_GETDEVLIST_MAXNUM * \
NFS4_DEVICEID4_SIZE) \
/* gdlr_deviceid_list */ + \
1 /* bool gdlr_eof */)
#define encode_getdeviceinfo_maxsz (op_encode_hdr_maxsz + 4 + \
XDR_QUADLEN(NFS4_DEVICEID4_SIZE))
#define decode_getdeviceinfo_maxsz (op_decode_hdr_maxsz + \
1 /* layout type */ + \
1 /* opaque devaddr4 length */ + \
/* devaddr4 payload is read into page */ \
1 /* notification bitmap length */ + \
1 /* notification bitmap */)
#define encode_layoutget_maxsz (op_encode_hdr_maxsz + 10 + \
encode_stateid_maxsz)
#define decode_layoutget_maxsz (op_decode_hdr_maxsz + 8 + \
decode_stateid_maxsz + \
XDR_QUADLEN(PNFS_LAYOUT_MAXSIZE))
#define encode_layoutcommit_maxsz (op_encode_hdr_maxsz + \
2 /* offset */ + \
2 /* length */ + \
1 /* reclaim */ + \
encode_stateid_maxsz + \
1 /* new offset (true) */ + \
2 /* last byte written */ + \
1 /* nt_timechanged (false) */ + \
1 /* layoutupdate4 layout type */ + \
1 /* NULL filelayout layoutupdate4 payload */)
#define decode_layoutcommit_maxsz (op_decode_hdr_maxsz + 3)
#define encode_layoutreturn_maxsz (8 + op_encode_hdr_maxsz + \
encode_stateid_maxsz + \
1 /* FIXME: opaque lrf_body always empty at the moment */)
#define decode_layoutreturn_maxsz (op_decode_hdr_maxsz + \
1 + decode_stateid_maxsz)
#define encode_secinfo_no_name_maxsz (op_encode_hdr_maxsz + 1)
#define decode_secinfo_no_name_maxsz decode_secinfo_maxsz
#define encode_test_stateid_maxsz (op_encode_hdr_maxsz + 2 + \
XDR_QUADLEN(NFS4_STATEID_SIZE))
#define decode_test_stateid_maxsz (op_decode_hdr_maxsz + 2 + 1)
#define encode_free_stateid_maxsz (op_encode_hdr_maxsz + 1 + \
XDR_QUADLEN(NFS4_STATEID_SIZE))
#define decode_free_stateid_maxsz (op_decode_hdr_maxsz + 1)
#else /* CONFIG_NFS_V4_1 */
#define encode_sequence_maxsz 0
#define decode_sequence_maxsz 0
#endif /* CONFIG_NFS_V4_1 */
#define NFS4_enc_compound_sz (1024) /* XXX: large enough? */
#define NFS4_dec_compound_sz (1024) /* XXX: large enough? */
#define NFS4_enc_read_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_read_maxsz)
#define NFS4_dec_read_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_read_maxsz)
#define NFS4_enc_readlink_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_readlink_maxsz)
#define NFS4_dec_readlink_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_readlink_maxsz)
#define NFS4_enc_readdir_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_readdir_maxsz)
#define NFS4_dec_readdir_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_readdir_maxsz)
#define NFS4_enc_write_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_write_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_write_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_write_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_commit_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_commit_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_commit_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_commit_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_open_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_savefh_maxsz + \
encode_open_maxsz + \
encode_getfh_maxsz + \
encode_getattr_maxsz + \
encode_restorefh_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_open_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_savefh_maxsz + \
decode_open_maxsz + \
decode_getfh_maxsz + \
decode_getattr_maxsz + \
decode_restorefh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_open_confirm_sz \
(compound_encode_hdr_maxsz + \
encode_putfh_maxsz + \
encode_open_confirm_maxsz)
#define NFS4_dec_open_confirm_sz \
(compound_decode_hdr_maxsz + \
decode_putfh_maxsz + \
decode_open_confirm_maxsz)
#define NFS4_enc_open_noattr_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_open_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_open_noattr_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_open_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_open_downgrade_sz \
(compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_open_downgrade_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_open_downgrade_sz \
(compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_open_downgrade_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_close_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_close_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_close_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_close_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_setattr_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_setattr_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_setattr_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_setattr_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_fsinfo_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_fsinfo_maxsz)
#define NFS4_dec_fsinfo_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_fsinfo_maxsz)
#define NFS4_enc_renew_sz (compound_encode_hdr_maxsz + \
encode_renew_maxsz)
#define NFS4_dec_renew_sz (compound_decode_hdr_maxsz + \
decode_renew_maxsz)
#define NFS4_enc_setclientid_sz (compound_encode_hdr_maxsz + \
encode_setclientid_maxsz)
#define NFS4_dec_setclientid_sz (compound_decode_hdr_maxsz + \
decode_setclientid_maxsz)
#define NFS4_enc_setclientid_confirm_sz \
(compound_encode_hdr_maxsz + \
encode_setclientid_confirm_maxsz + \
encode_putrootfh_maxsz + \
encode_fsinfo_maxsz)
#define NFS4_dec_setclientid_confirm_sz \
(compound_decode_hdr_maxsz + \
decode_setclientid_confirm_maxsz + \
decode_putrootfh_maxsz + \
decode_fsinfo_maxsz)
#define NFS4_enc_lock_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_lock_maxsz)
#define NFS4_dec_lock_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_lock_maxsz)
#define NFS4_enc_lockt_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_lockt_maxsz)
#define NFS4_dec_lockt_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_lockt_maxsz)
#define NFS4_enc_locku_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_locku_maxsz)
#define NFS4_dec_locku_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_locku_maxsz)
#define NFS4_enc_release_lockowner_sz \
(compound_encode_hdr_maxsz + \
encode_lockowner_maxsz)
#define NFS4_dec_release_lockowner_sz \
(compound_decode_hdr_maxsz + \
decode_lockowner_maxsz)
#define NFS4_enc_access_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_access_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_access_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_access_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_getattr_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_getattr_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_lookup_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_lookup_maxsz + \
encode_getattr_maxsz + \
encode_getfh_maxsz)
#define NFS4_dec_lookup_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_lookup_maxsz + \
decode_getattr_maxsz + \
decode_getfh_maxsz)
#define NFS4_enc_lookup_root_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putrootfh_maxsz + \
encode_getattr_maxsz + \
encode_getfh_maxsz)
#define NFS4_dec_lookup_root_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putrootfh_maxsz + \
decode_getattr_maxsz + \
decode_getfh_maxsz)
#define NFS4_enc_remove_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_remove_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_remove_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_remove_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_rename_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_savefh_maxsz + \
encode_putfh_maxsz + \
encode_rename_maxsz + \
encode_getattr_maxsz + \
encode_restorefh_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_rename_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_savefh_maxsz + \
decode_putfh_maxsz + \
decode_rename_maxsz + \
decode_getattr_maxsz + \
decode_restorefh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_link_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_savefh_maxsz + \
encode_putfh_maxsz + \
encode_link_maxsz + \
decode_getattr_maxsz + \
encode_restorefh_maxsz + \
decode_getattr_maxsz)
#define NFS4_dec_link_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_savefh_maxsz + \
decode_putfh_maxsz + \
decode_link_maxsz + \
decode_getattr_maxsz + \
decode_restorefh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_symlink_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_symlink_maxsz + \
encode_getattr_maxsz + \
encode_getfh_maxsz)
#define NFS4_dec_symlink_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_symlink_maxsz + \
decode_getattr_maxsz + \
decode_getfh_maxsz)
#define NFS4_enc_create_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_savefh_maxsz + \
encode_create_maxsz + \
encode_getfh_maxsz + \
encode_getattr_maxsz + \
encode_restorefh_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_create_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_savefh_maxsz + \
decode_create_maxsz + \
decode_getfh_maxsz + \
decode_getattr_maxsz + \
decode_restorefh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_pathconf_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_pathconf_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_statfs_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_statfs_maxsz)
#define NFS4_dec_statfs_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_statfs_maxsz)
#define NFS4_enc_server_caps_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_server_caps_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_delegreturn_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_delegreturn_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_delegreturn_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_delegreturn_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_getacl_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_getacl_maxsz)
#define NFS4_dec_getacl_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_getacl_maxsz)
#define NFS4_enc_setacl_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_setacl_maxsz)
#define NFS4_dec_setacl_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_setacl_maxsz)
#define NFS4_enc_fs_locations_sz \
(compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_lookup_maxsz + \
encode_fs_locations_maxsz)
#define NFS4_dec_fs_locations_sz \
(compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_lookup_maxsz + \
decode_fs_locations_maxsz)
#define NFS4_enc_secinfo_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_secinfo_maxsz)
#define NFS4_dec_secinfo_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_secinfo_maxsz)
#if defined(CONFIG_NFS_V4_1)
#define NFS4_enc_exchange_id_sz \
(compound_encode_hdr_maxsz + \
encode_exchange_id_maxsz)
#define NFS4_dec_exchange_id_sz \
(compound_decode_hdr_maxsz + \
decode_exchange_id_maxsz)
#define NFS4_enc_create_session_sz \
(compound_encode_hdr_maxsz + \
encode_create_session_maxsz)
#define NFS4_dec_create_session_sz \
(compound_decode_hdr_maxsz + \
decode_create_session_maxsz)
#define NFS4_enc_destroy_session_sz (compound_encode_hdr_maxsz + \
encode_destroy_session_maxsz)
#define NFS4_dec_destroy_session_sz (compound_decode_hdr_maxsz + \
decode_destroy_session_maxsz)
#define NFS4_enc_sequence_sz \
(compound_decode_hdr_maxsz + \
encode_sequence_maxsz)
#define NFS4_dec_sequence_sz \
(compound_decode_hdr_maxsz + \
decode_sequence_maxsz)
#define NFS4_enc_get_lease_time_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putrootfh_maxsz + \
encode_fsinfo_maxsz)
#define NFS4_dec_get_lease_time_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putrootfh_maxsz + \
decode_fsinfo_maxsz)
#define NFS4_enc_reclaim_complete_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_reclaim_complete_maxsz)
#define NFS4_dec_reclaim_complete_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_reclaim_complete_maxsz)
#define NFS4_enc_getdevicelist_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_getdevicelist_maxsz)
#define NFS4_dec_getdevicelist_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_getdevicelist_maxsz)
#define NFS4_enc_getdeviceinfo_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz +\
encode_getdeviceinfo_maxsz)
#define NFS4_dec_getdeviceinfo_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_getdeviceinfo_maxsz)
#define NFS4_enc_layoutget_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_layoutget_maxsz)
#define NFS4_dec_layoutget_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_layoutget_maxsz)
#define NFS4_enc_layoutcommit_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz +\
encode_putfh_maxsz + \
encode_layoutcommit_maxsz + \
encode_getattr_maxsz)
#define NFS4_dec_layoutcommit_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_layoutcommit_maxsz + \
decode_getattr_maxsz)
#define NFS4_enc_layoutreturn_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putfh_maxsz + \
encode_layoutreturn_maxsz)
#define NFS4_dec_layoutreturn_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putfh_maxsz + \
decode_layoutreturn_maxsz)
#define NFS4_enc_secinfo_no_name_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_putrootfh_maxsz +\
encode_secinfo_no_name_maxsz)
#define NFS4_dec_secinfo_no_name_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_putrootfh_maxsz + \
decode_secinfo_no_name_maxsz)
#define NFS4_enc_test_stateid_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_test_stateid_maxsz)
#define NFS4_dec_test_stateid_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_test_stateid_maxsz)
#define NFS4_enc_free_stateid_sz (compound_encode_hdr_maxsz + \
encode_sequence_maxsz + \
encode_free_stateid_maxsz)
#define NFS4_dec_free_stateid_sz (compound_decode_hdr_maxsz + \
decode_sequence_maxsz + \
decode_free_stateid_maxsz)
const u32 nfs41_maxwrite_overhead = ((RPC_MAX_HEADER_WITH_AUTH +
compound_encode_hdr_maxsz +
encode_sequence_maxsz +
encode_putfh_maxsz +
encode_getattr_maxsz) *
XDR_UNIT);
const u32 nfs41_maxread_overhead = ((RPC_MAX_HEADER_WITH_AUTH +
compound_decode_hdr_maxsz +
decode_sequence_maxsz +
decode_putfh_maxsz) *
XDR_UNIT);
#endif /* CONFIG_NFS_V4_1 */
static unsigned short send_implementation_id = 1;
module_param(send_implementation_id, ushort, 0644);
MODULE_PARM_DESC(send_implementation_id,
"Send implementation ID with NFSv4.1 exchange_id");
static const umode_t nfs_type2fmt[] = {
[NF4BAD] = 0,
[NF4REG] = S_IFREG,
[NF4DIR] = S_IFDIR,
[NF4BLK] = S_IFBLK,
[NF4CHR] = S_IFCHR,
[NF4LNK] = S_IFLNK,
[NF4SOCK] = S_IFSOCK,
[NF4FIFO] = S_IFIFO,
[NF4ATTRDIR] = 0,
[NF4NAMEDATTR] = 0,
};
struct compound_hdr {
int32_t status;
uint32_t nops;
__be32 * nops_p;
uint32_t taglen;
char * tag;
uint32_t replen; /* expected reply words */
u32 minorversion;
};
static __be32 *reserve_space(struct xdr_stream *xdr, size_t nbytes)
{
__be32 *p = xdr_reserve_space(xdr, nbytes);
BUG_ON(!p);
return p;
}
static void encode_opaque_fixed(struct xdr_stream *xdr, const void *buf, size_t len)
{
__be32 *p;
p = xdr_reserve_space(xdr, len);
xdr_encode_opaque_fixed(p, buf, len);
}
static void encode_string(struct xdr_stream *xdr, unsigned int len, const char *str)
{
__be32 *p;
p = reserve_space(xdr, 4 + len);
xdr_encode_opaque(p, str, len);
}
static void encode_uint32(struct xdr_stream *xdr, u32 n)
{
__be32 *p;
p = reserve_space(xdr, 4);
*p = cpu_to_be32(n);
}
static void encode_uint64(struct xdr_stream *xdr, u64 n)
{
__be32 *p;
p = reserve_space(xdr, 8);
xdr_encode_hyper(p, n);
}
static void encode_nfs4_seqid(struct xdr_stream *xdr,
const struct nfs_seqid *seqid)
{
encode_uint32(xdr, seqid->sequence->counter);
}
static void encode_compound_hdr(struct xdr_stream *xdr,
struct rpc_rqst *req,
struct compound_hdr *hdr)
{
__be32 *p;
struct rpc_auth *auth = req->rq_cred->cr_auth;
/* initialize running count of expected bytes in reply.
* NOTE: the replied tag SHOULD be the same is the one sent,
* but this is not required as a MUST for the server to do so. */
hdr->replen = RPC_REPHDRSIZE + auth->au_rslack + 3 + hdr->taglen;
BUG_ON(hdr->taglen > NFS4_MAXTAGLEN);
encode_string(xdr, hdr->taglen, hdr->tag);
p = reserve_space(xdr, 8);
*p++ = cpu_to_be32(hdr->minorversion);
hdr->nops_p = p;
*p = cpu_to_be32(hdr->nops);
}
static void encode_op_hdr(struct xdr_stream *xdr, enum nfs_opnum4 op,
uint32_t replen,
struct compound_hdr *hdr)
{
encode_uint32(xdr, op);
hdr->nops++;
hdr->replen += replen;
}
static void encode_nops(struct compound_hdr *hdr)
{
BUG_ON(hdr->nops > NFS4_MAX_OPS);
*hdr->nops_p = htonl(hdr->nops);
}
static void encode_nfs4_stateid(struct xdr_stream *xdr, const nfs4_stateid *stateid)
{
encode_opaque_fixed(xdr, stateid, NFS4_STATEID_SIZE);
}
static void encode_nfs4_verifier(struct xdr_stream *xdr, const nfs4_verifier *verf)
{
encode_opaque_fixed(xdr, verf->data, NFS4_VERIFIER_SIZE);
}
static void encode_attrs(struct xdr_stream *xdr, const struct iattr *iap, const struct nfs_server *server)
{
char owner_name[IDMAP_NAMESZ];
char owner_group[IDMAP_NAMESZ];
int owner_namelen = 0;
int owner_grouplen = 0;
__be32 *p;
__be32 *q;
int len;
uint32_t bmval0 = 0;
uint32_t bmval1 = 0;
/*
* We reserve enough space to write the entire attribute buffer at once.
* In the worst-case, this would be
* 12(bitmap) + 4(attrlen) + 8(size) + 4(mode) + 4(atime) + 4(mtime)
* = 36 bytes, plus any contribution from variable-length fields
* such as owner/group.
*/
len = 16;
/* Sigh */
if (iap->ia_valid & ATTR_SIZE)
len += 8;
if (iap->ia_valid & ATTR_MODE)
len += 4;
if (iap->ia_valid & ATTR_UID) {
owner_namelen = nfs_map_uid_to_name(server, iap->ia_uid, owner_name, IDMAP_NAMESZ);
if (owner_namelen < 0) {
dprintk("nfs: couldn't resolve uid %d to string\n",
iap->ia_uid);
/* XXX */
strcpy(owner_name, "nobody");
owner_namelen = sizeof("nobody") - 1;
/* goto out; */
}
len += 4 + (XDR_QUADLEN(owner_namelen) << 2);
}
if (iap->ia_valid & ATTR_GID) {
owner_grouplen = nfs_map_gid_to_group(server, iap->ia_gid, owner_group, IDMAP_NAMESZ);
if (owner_grouplen < 0) {
dprintk("nfs: couldn't resolve gid %d to string\n",
iap->ia_gid);
strcpy(owner_group, "nobody");
owner_grouplen = sizeof("nobody") - 1;
/* goto out; */
}
len += 4 + (XDR_QUADLEN(owner_grouplen) << 2);
}
if (iap->ia_valid & ATTR_ATIME_SET)
len += 16;
else if (iap->ia_valid & ATTR_ATIME)
len += 4;
if (iap->ia_valid & ATTR_MTIME_SET)
len += 16;
else if (iap->ia_valid & ATTR_MTIME)
len += 4;
p = reserve_space(xdr, len);
/*
* We write the bitmap length now, but leave the bitmap and the attribute
* buffer length to be backfilled at the end of this routine.
*/
*p++ = cpu_to_be32(2);
q = p;
p += 3;
if (iap->ia_valid & ATTR_SIZE) {
bmval0 |= FATTR4_WORD0_SIZE;
p = xdr_encode_hyper(p, iap->ia_size);
}
if (iap->ia_valid & ATTR_MODE) {
bmval1 |= FATTR4_WORD1_MODE;
*p++ = cpu_to_be32(iap->ia_mode & S_IALLUGO);
}
if (iap->ia_valid & ATTR_UID) {
bmval1 |= FATTR4_WORD1_OWNER;
p = xdr_encode_opaque(p, owner_name, owner_namelen);
}
if (iap->ia_valid & ATTR_GID) {
bmval1 |= FATTR4_WORD1_OWNER_GROUP;
p = xdr_encode_opaque(p, owner_group, owner_grouplen);
}
if (iap->ia_valid & ATTR_ATIME_SET) {
bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET;
*p++ = cpu_to_be32(NFS4_SET_TO_CLIENT_TIME);
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(iap->ia_atime.tv_sec);
*p++ = cpu_to_be32(iap->ia_atime.tv_nsec);
}
else if (iap->ia_valid & ATTR_ATIME) {
bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET;
*p++ = cpu_to_be32(NFS4_SET_TO_SERVER_TIME);
}
if (iap->ia_valid & ATTR_MTIME_SET) {
bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET;
*p++ = cpu_to_be32(NFS4_SET_TO_CLIENT_TIME);
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(iap->ia_mtime.tv_sec);
*p++ = cpu_to_be32(iap->ia_mtime.tv_nsec);
}
else if (iap->ia_valid & ATTR_MTIME) {
bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET;
*p++ = cpu_to_be32(NFS4_SET_TO_SERVER_TIME);
}
/*
* Now we backfill the bitmap and the attribute buffer length.
*/
if (len != ((char *)p - (char *)q) + 4) {
printk(KERN_ERR "NFS: Attr length error, %u != %Zu\n",
len, ((char *)p - (char *)q) + 4);
BUG();
}
len = (char *)p - (char *)q - 12;
*q++ = htonl(bmval0);
*q++ = htonl(bmval1);
*q = htonl(len);
/* out: */
}
static void encode_access(struct xdr_stream *xdr, u32 access, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_ACCESS, decode_access_maxsz, hdr);
encode_uint32(xdr, access);
}
static void encode_close(struct xdr_stream *xdr, const struct nfs_closeargs *arg, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_CLOSE, decode_close_maxsz, hdr);
encode_nfs4_seqid(xdr, arg->seqid);
encode_nfs4_stateid(xdr, arg->stateid);
}
static void encode_commit(struct xdr_stream *xdr, const struct nfs_writeargs *args, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_COMMIT, decode_commit_maxsz, hdr);
p = reserve_space(xdr, 12);
p = xdr_encode_hyper(p, args->offset);
*p = cpu_to_be32(args->count);
}
static void encode_create(struct xdr_stream *xdr, const struct nfs4_create_arg *create, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_CREATE, decode_create_maxsz, hdr);
encode_uint32(xdr, create->ftype);
switch (create->ftype) {
case NF4LNK:
p = reserve_space(xdr, 4);
*p = cpu_to_be32(create->u.symlink.len);
xdr_write_pages(xdr, create->u.symlink.pages, 0, create->u.symlink.len);
break;
case NF4BLK: case NF4CHR:
p = reserve_space(xdr, 8);
*p++ = cpu_to_be32(create->u.device.specdata1);
*p = cpu_to_be32(create->u.device.specdata2);
break;
default:
break;
}
encode_string(xdr, create->name->len, create->name->name);
encode_attrs(xdr, create->attrs, create->server);
}
static void encode_getattr_one(struct xdr_stream *xdr, uint32_t bitmap, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_GETATTR, decode_getattr_maxsz, hdr);
p = reserve_space(xdr, 8);
*p++ = cpu_to_be32(1);
*p = cpu_to_be32(bitmap);
}
static void encode_getattr_two(struct xdr_stream *xdr, uint32_t bm0, uint32_t bm1, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_GETATTR, decode_getattr_maxsz, hdr);
p = reserve_space(xdr, 12);
*p++ = cpu_to_be32(2);
*p++ = cpu_to_be32(bm0);
*p = cpu_to_be32(bm1);
}
static void
encode_getattr_three(struct xdr_stream *xdr,
uint32_t bm0, uint32_t bm1, uint32_t bm2,
struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_GETATTR, decode_getattr_maxsz, hdr);
if (bm2) {
p = reserve_space(xdr, 16);
*p++ = cpu_to_be32(3);
*p++ = cpu_to_be32(bm0);
*p++ = cpu_to_be32(bm1);
*p = cpu_to_be32(bm2);
} else if (bm1) {
p = reserve_space(xdr, 12);
*p++ = cpu_to_be32(2);
*p++ = cpu_to_be32(bm0);
*p = cpu_to_be32(bm1);
} else {
p = reserve_space(xdr, 8);
*p++ = cpu_to_be32(1);
*p = cpu_to_be32(bm0);
}
}
static void encode_getfattr(struct xdr_stream *xdr, const u32* bitmask, struct compound_hdr *hdr)
{
encode_getattr_two(xdr, bitmask[0] & nfs4_fattr_bitmap[0],
bitmask[1] & nfs4_fattr_bitmap[1], hdr);
}
static void encode_fsinfo(struct xdr_stream *xdr, const u32* bitmask, struct compound_hdr *hdr)
{
encode_getattr_three(xdr,
bitmask[0] & nfs4_fsinfo_bitmap[0],
bitmask[1] & nfs4_fsinfo_bitmap[1],
bitmask[2] & nfs4_fsinfo_bitmap[2],
hdr);
}
static void encode_fs_locations(struct xdr_stream *xdr, const u32* bitmask, struct compound_hdr *hdr)
{
encode_getattr_two(xdr, bitmask[0] & nfs4_fs_locations_bitmap[0],
bitmask[1] & nfs4_fs_locations_bitmap[1], hdr);
}
static void encode_getfh(struct xdr_stream *xdr, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_GETFH, decode_getfh_maxsz, hdr);
}
static void encode_link(struct xdr_stream *xdr, const struct qstr *name, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_LINK, decode_link_maxsz, hdr);
encode_string(xdr, name->len, name->name);
}
static inline int nfs4_lock_type(struct file_lock *fl, int block)
{
if ((fl->fl_type & (F_RDLCK|F_WRLCK|F_UNLCK)) == F_RDLCK)
return block ? NFS4_READW_LT : NFS4_READ_LT;
return block ? NFS4_WRITEW_LT : NFS4_WRITE_LT;
}
static inline uint64_t nfs4_lock_length(struct file_lock *fl)
{
if (fl->fl_end == OFFSET_MAX)
return ~(uint64_t)0;
return fl->fl_end - fl->fl_start + 1;
}
static void encode_lockowner(struct xdr_stream *xdr, const struct nfs_lowner *lowner)
{
__be32 *p;
p = reserve_space(xdr, 32);
p = xdr_encode_hyper(p, lowner->clientid);
*p++ = cpu_to_be32(20);
p = xdr_encode_opaque_fixed(p, "lock id:", 8);
*p++ = cpu_to_be32(lowner->s_dev);
xdr_encode_hyper(p, lowner->id);
}
/*
* opcode,type,reclaim,offset,length,new_lock_owner = 32
* open_seqid,open_stateid,lock_seqid,lock_owner.clientid, lock_owner.id = 40
*/
static void encode_lock(struct xdr_stream *xdr, const struct nfs_lock_args *args, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_LOCK, decode_lock_maxsz, hdr);
p = reserve_space(xdr, 28);
*p++ = cpu_to_be32(nfs4_lock_type(args->fl, args->block));
*p++ = cpu_to_be32(args->reclaim);
p = xdr_encode_hyper(p, args->fl->fl_start);
p = xdr_encode_hyper(p, nfs4_lock_length(args->fl));
*p = cpu_to_be32(args->new_lock_owner);
if (args->new_lock_owner){
encode_nfs4_seqid(xdr, args->open_seqid);
encode_nfs4_stateid(xdr, args->open_stateid);
encode_nfs4_seqid(xdr, args->lock_seqid);
encode_lockowner(xdr, &args->lock_owner);
}
else {
encode_nfs4_stateid(xdr, args->lock_stateid);
encode_nfs4_seqid(xdr, args->lock_seqid);
}
}
static void encode_lockt(struct xdr_stream *xdr, const struct nfs_lockt_args *args, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_LOCKT, decode_lockt_maxsz, hdr);
p = reserve_space(xdr, 20);
*p++ = cpu_to_be32(nfs4_lock_type(args->fl, 0));
p = xdr_encode_hyper(p, args->fl->fl_start);
p = xdr_encode_hyper(p, nfs4_lock_length(args->fl));
encode_lockowner(xdr, &args->lock_owner);
}
static void encode_locku(struct xdr_stream *xdr, const struct nfs_locku_args *args, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_LOCKU, decode_locku_maxsz, hdr);
encode_uint32(xdr, nfs4_lock_type(args->fl, 0));
encode_nfs4_seqid(xdr, args->seqid);
encode_nfs4_stateid(xdr, args->stateid);
p = reserve_space(xdr, 16);
p = xdr_encode_hyper(p, args->fl->fl_start);
xdr_encode_hyper(p, nfs4_lock_length(args->fl));
}
static void encode_release_lockowner(struct xdr_stream *xdr, const struct nfs_lowner *lowner, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_RELEASE_LOCKOWNER, decode_release_lockowner_maxsz, hdr);
encode_lockowner(xdr, lowner);
}
static void encode_lookup(struct xdr_stream *xdr, const struct qstr *name, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_LOOKUP, decode_lookup_maxsz, hdr);
encode_string(xdr, name->len, name->name);
}
static void encode_share_access(struct xdr_stream *xdr, fmode_t fmode)
{
__be32 *p;
p = reserve_space(xdr, 8);
switch (fmode & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
*p++ = cpu_to_be32(NFS4_SHARE_ACCESS_READ);
break;
case FMODE_WRITE:
*p++ = cpu_to_be32(NFS4_SHARE_ACCESS_WRITE);
break;
case FMODE_READ|FMODE_WRITE:
*p++ = cpu_to_be32(NFS4_SHARE_ACCESS_BOTH);
break;
default:
*p++ = cpu_to_be32(0);
}
*p = cpu_to_be32(0); /* for linux, share_deny = 0 always */
}
static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg)
{
__be32 *p;
/*
* opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4,
* owner 4 = 32
*/
encode_nfs4_seqid(xdr, arg->seqid);
encode_share_access(xdr, arg->fmode);
p = reserve_space(xdr, 36);
p = xdr_encode_hyper(p, arg->clientid);
*p++ = cpu_to_be32(24);
p = xdr_encode_opaque_fixed(p, "open id:", 8);
*p++ = cpu_to_be32(arg->server->s_dev);
*p++ = cpu_to_be32(arg->id.uniquifier);
xdr_encode_hyper(p, arg->id.create_time);
}
static inline void encode_createmode(struct xdr_stream *xdr, const struct nfs_openargs *arg)
{
__be32 *p;
struct nfs_client *clp;
p = reserve_space(xdr, 4);
switch(arg->open_flags & O_EXCL) {
case 0:
*p = cpu_to_be32(NFS4_CREATE_UNCHECKED);
encode_attrs(xdr, arg->u.attrs, arg->server);
break;
default:
clp = arg->server->nfs_client;
if (clp->cl_mvops->minor_version > 0) {
if (nfs4_has_persistent_session(clp)) {
*p = cpu_to_be32(NFS4_CREATE_GUARDED);
encode_attrs(xdr, arg->u.attrs, arg->server);
} else {
struct iattr dummy;
*p = cpu_to_be32(NFS4_CREATE_EXCLUSIVE4_1);
encode_nfs4_verifier(xdr, &arg->u.verifier);
dummy.ia_valid = 0;
encode_attrs(xdr, &dummy, arg->server);
}
} else {
*p = cpu_to_be32(NFS4_CREATE_EXCLUSIVE);
encode_nfs4_verifier(xdr, &arg->u.verifier);
}
}
}
static void encode_opentype(struct xdr_stream *xdr, const struct nfs_openargs *arg)
{
__be32 *p;
p = reserve_space(xdr, 4);
switch (arg->open_flags & O_CREAT) {
case 0:
*p = cpu_to_be32(NFS4_OPEN_NOCREATE);
break;
default:
BUG_ON(arg->claim != NFS4_OPEN_CLAIM_NULL);
*p = cpu_to_be32(NFS4_OPEN_CREATE);
encode_createmode(xdr, arg);
}
}
static inline void encode_delegation_type(struct xdr_stream *xdr, fmode_t delegation_type)
{
__be32 *p;
p = reserve_space(xdr, 4);
switch (delegation_type) {
case 0:
*p = cpu_to_be32(NFS4_OPEN_DELEGATE_NONE);
break;
case FMODE_READ:
*p = cpu_to_be32(NFS4_OPEN_DELEGATE_READ);
break;
case FMODE_WRITE|FMODE_READ:
*p = cpu_to_be32(NFS4_OPEN_DELEGATE_WRITE);
break;
default:
BUG();
}
}
static inline void encode_claim_null(struct xdr_stream *xdr, const struct qstr *name)
{
__be32 *p;
p = reserve_space(xdr, 4);
*p = cpu_to_be32(NFS4_OPEN_CLAIM_NULL);
encode_string(xdr, name->len, name->name);
}
static inline void encode_claim_previous(struct xdr_stream *xdr, fmode_t type)
{
__be32 *p;
p = reserve_space(xdr, 4);
*p = cpu_to_be32(NFS4_OPEN_CLAIM_PREVIOUS);
encode_delegation_type(xdr, type);
}
static inline void encode_claim_delegate_cur(struct xdr_stream *xdr, const struct qstr *name, const nfs4_stateid *stateid)
{
__be32 *p;
p = reserve_space(xdr, 4);
*p = cpu_to_be32(NFS4_OPEN_CLAIM_DELEGATE_CUR);
encode_nfs4_stateid(xdr, stateid);
encode_string(xdr, name->len, name->name);
}
static void encode_open(struct xdr_stream *xdr, const struct nfs_openargs *arg, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_OPEN, decode_open_maxsz, hdr);
encode_openhdr(xdr, arg);
encode_opentype(xdr, arg);
switch (arg->claim) {
case NFS4_OPEN_CLAIM_NULL:
encode_claim_null(xdr, arg->name);
break;
case NFS4_OPEN_CLAIM_PREVIOUS:
encode_claim_previous(xdr, arg->u.delegation_type);
break;
case NFS4_OPEN_CLAIM_DELEGATE_CUR:
encode_claim_delegate_cur(xdr, arg->name, &arg->u.delegation);
break;
default:
BUG();
}
}
static void encode_open_confirm(struct xdr_stream *xdr, const struct nfs_open_confirmargs *arg, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_OPEN_CONFIRM, decode_open_confirm_maxsz, hdr);
encode_nfs4_stateid(xdr, arg->stateid);
encode_nfs4_seqid(xdr, arg->seqid);
}
static void encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_OPEN_DOWNGRADE, decode_open_downgrade_maxsz, hdr);
encode_nfs4_stateid(xdr, arg->stateid);
encode_nfs4_seqid(xdr, arg->seqid);
encode_share_access(xdr, arg->fmode);
}
static void
encode_putfh(struct xdr_stream *xdr, const struct nfs_fh *fh, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_PUTFH, decode_putfh_maxsz, hdr);
encode_string(xdr, fh->size, fh->data);
}
static void encode_putrootfh(struct xdr_stream *xdr, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_PUTROOTFH, decode_putrootfh_maxsz, hdr);
}
static void encode_open_stateid(struct xdr_stream *xdr,
const struct nfs_open_context *ctx,
const struct nfs_lock_context *l_ctx,
fmode_t fmode,
int zero_seqid)
{
nfs4_stateid stateid;
if (ctx->state != NULL) {
nfs4_select_rw_stateid(&stateid, ctx->state,
fmode, l_ctx->lockowner, l_ctx->pid);
if (zero_seqid)
stateid.seqid = 0;
encode_nfs4_stateid(xdr, &stateid);
} else
encode_nfs4_stateid(xdr, &zero_stateid);
}
static void encode_read(struct xdr_stream *xdr, const struct nfs_readargs *args, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_READ, decode_read_maxsz, hdr);
encode_open_stateid(xdr, args->context, args->lock_context,
FMODE_READ, hdr->minorversion);
p = reserve_space(xdr, 12);
p = xdr_encode_hyper(p, args->offset);
*p = cpu_to_be32(args->count);
}
static void encode_readdir(struct xdr_stream *xdr, const struct nfs4_readdir_arg *readdir, struct rpc_rqst *req, struct compound_hdr *hdr)
{
uint32_t attrs[2] = {
FATTR4_WORD0_RDATTR_ERROR,
FATTR4_WORD1_MOUNTED_ON_FILEID,
};
uint32_t dircount = readdir->count >> 1;
__be32 *p, verf[2];
if (readdir->plus) {
attrs[0] |= FATTR4_WORD0_TYPE|FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE|
FATTR4_WORD0_FSID|FATTR4_WORD0_FILEHANDLE|FATTR4_WORD0_FILEID;
attrs[1] |= FATTR4_WORD1_MODE|FATTR4_WORD1_NUMLINKS|FATTR4_WORD1_OWNER|
FATTR4_WORD1_OWNER_GROUP|FATTR4_WORD1_RAWDEV|
FATTR4_WORD1_SPACE_USED|FATTR4_WORD1_TIME_ACCESS|
FATTR4_WORD1_TIME_METADATA|FATTR4_WORD1_TIME_MODIFY;
dircount >>= 1;
}
/* Use mounted_on_fileid only if the server supports it */
if (!(readdir->bitmask[1] & FATTR4_WORD1_MOUNTED_ON_FILEID))
attrs[0] |= FATTR4_WORD0_FILEID;
encode_op_hdr(xdr, OP_READDIR, decode_readdir_maxsz, hdr);
encode_uint64(xdr, readdir->cookie);
encode_nfs4_verifier(xdr, &readdir->verifier);
p = reserve_space(xdr, 20);
*p++ = cpu_to_be32(dircount);
*p++ = cpu_to_be32(readdir->count);
*p++ = cpu_to_be32(2);
*p++ = cpu_to_be32(attrs[0] & readdir->bitmask[0]);
*p = cpu_to_be32(attrs[1] & readdir->bitmask[1]);
memcpy(verf, readdir->verifier.data, sizeof(verf));
dprintk("%s: cookie = %Lu, verifier = %08x:%08x, bitmap = %08x:%08x\n",
__func__,
(unsigned long long)readdir->cookie,
verf[0], verf[1],
attrs[0] & readdir->bitmask[0],
attrs[1] & readdir->bitmask[1]);
}
static void encode_readlink(struct xdr_stream *xdr, const struct nfs4_readlink *readlink, struct rpc_rqst *req, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_READLINK, decode_readlink_maxsz, hdr);
}
static void encode_remove(struct xdr_stream *xdr, const struct qstr *name, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_REMOVE, decode_remove_maxsz, hdr);
encode_string(xdr, name->len, name->name);
}
static void encode_rename(struct xdr_stream *xdr, const struct qstr *oldname, const struct qstr *newname, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_RENAME, decode_rename_maxsz, hdr);
encode_string(xdr, oldname->len, oldname->name);
encode_string(xdr, newname->len, newname->name);
}
static void encode_renew(struct xdr_stream *xdr, clientid4 clid,
struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_RENEW, decode_renew_maxsz, hdr);
encode_uint64(xdr, clid);
}
static void
encode_restorefh(struct xdr_stream *xdr, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_RESTOREFH, decode_restorefh_maxsz, hdr);
}
static void
encode_setacl(struct xdr_stream *xdr, struct nfs_setaclargs *arg, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_SETATTR, decode_setacl_maxsz, hdr);
encode_nfs4_stateid(xdr, &zero_stateid);
p = reserve_space(xdr, 2*4);
*p++ = cpu_to_be32(1);
*p = cpu_to_be32(FATTR4_WORD0_ACL);
BUG_ON(arg->acl_len % 4);
p = reserve_space(xdr, 4);
*p = cpu_to_be32(arg->acl_len);
xdr_write_pages(xdr, arg->acl_pages, arg->acl_pgbase, arg->acl_len);
}
static void
encode_savefh(struct xdr_stream *xdr, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_SAVEFH, decode_savefh_maxsz, hdr);
}
static void encode_setattr(struct xdr_stream *xdr, const struct nfs_setattrargs *arg, const struct nfs_server *server, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_SETATTR, decode_setattr_maxsz, hdr);
encode_nfs4_stateid(xdr, &arg->stateid);
encode_attrs(xdr, arg->iap, server);
}
static void encode_setclientid(struct xdr_stream *xdr, const struct nfs4_setclientid *setclientid, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_SETCLIENTID, decode_setclientid_maxsz, hdr);
encode_nfs4_verifier(xdr, setclientid->sc_verifier);
encode_string(xdr, setclientid->sc_name_len, setclientid->sc_name);
p = reserve_space(xdr, 4);
*p = cpu_to_be32(setclientid->sc_prog);
encode_string(xdr, setclientid->sc_netid_len, setclientid->sc_netid);
encode_string(xdr, setclientid->sc_uaddr_len, setclientid->sc_uaddr);
p = reserve_space(xdr, 4);
*p = cpu_to_be32(setclientid->sc_cb_ident);
}
static void encode_setclientid_confirm(struct xdr_stream *xdr, const struct nfs4_setclientid_res *arg, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_SETCLIENTID_CONFIRM,
decode_setclientid_confirm_maxsz, hdr);
encode_uint64(xdr, arg->clientid);
encode_nfs4_verifier(xdr, &arg->confirm);
}
static void encode_write(struct xdr_stream *xdr, const struct nfs_writeargs *args, struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_WRITE, decode_write_maxsz, hdr);
encode_open_stateid(xdr, args->context, args->lock_context,
FMODE_WRITE, hdr->minorversion);
p = reserve_space(xdr, 16);
p = xdr_encode_hyper(p, args->offset);
*p++ = cpu_to_be32(args->stable);
*p = cpu_to_be32(args->count);
xdr_write_pages(xdr, args->pages, args->pgbase, args->count);
}
static void encode_delegreturn(struct xdr_stream *xdr, const nfs4_stateid *stateid, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_DELEGRETURN, decode_delegreturn_maxsz, hdr);
encode_nfs4_stateid(xdr, stateid);
}
static void encode_secinfo(struct xdr_stream *xdr, const struct qstr *name, struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_SECINFO, decode_secinfo_maxsz, hdr);
encode_string(xdr, name->len, name->name);
}
#if defined(CONFIG_NFS_V4_1)
/* NFSv4.1 operations */
static void encode_exchange_id(struct xdr_stream *xdr,
struct nfs41_exchange_id_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
char impl_name[NFS4_OPAQUE_LIMIT];
int len = 0;
encode_op_hdr(xdr, OP_EXCHANGE_ID, decode_exchange_id_maxsz, hdr);
encode_nfs4_verifier(xdr, args->verifier);
encode_string(xdr, args->id_len, args->id);
p = reserve_space(xdr, 12);
*p++ = cpu_to_be32(args->flags);
*p++ = cpu_to_be32(0); /* zero length state_protect4_a */
if (send_implementation_id &&
sizeof(CONFIG_NFS_V4_1_IMPLEMENTATION_ID_DOMAIN) > 1 &&
sizeof(CONFIG_NFS_V4_1_IMPLEMENTATION_ID_DOMAIN)
<= NFS4_OPAQUE_LIMIT + 1)
len = snprintf(impl_name, sizeof(impl_name), "%s %s %s %s",
utsname()->sysname, utsname()->release,
utsname()->version, utsname()->machine);
if (len > 0) {
*p = cpu_to_be32(1); /* implementation id array length=1 */
encode_string(xdr,
sizeof(CONFIG_NFS_V4_1_IMPLEMENTATION_ID_DOMAIN) - 1,
CONFIG_NFS_V4_1_IMPLEMENTATION_ID_DOMAIN);
encode_string(xdr, len, impl_name);
/* just send zeros for nii_date - the date is in nii_name */
p = reserve_space(xdr, 12);
p = xdr_encode_hyper(p, 0);
*p = cpu_to_be32(0);
} else
*p = cpu_to_be32(0); /* implementation id array length=0 */
}
static void encode_create_session(struct xdr_stream *xdr,
struct nfs41_create_session_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
char machine_name[NFS4_MAX_MACHINE_NAME_LEN];
uint32_t len;
struct nfs_client *clp = args->client;
u32 max_resp_sz_cached;
/*
* Assumes OPEN is the biggest non-idempotent compound.
* 2 is the verifier.
*/
max_resp_sz_cached = (NFS4_dec_open_sz + RPC_REPHDRSIZE +
RPC_MAX_AUTH_SIZE + 2) * XDR_UNIT;
len = scnprintf(machine_name, sizeof(machine_name), "%s",
clp->cl_ipaddr);
encode_op_hdr(xdr, OP_CREATE_SESSION, decode_create_session_maxsz, hdr);
p = reserve_space(xdr, 16 + 2*28 + 20 + len + 12);
p = xdr_encode_hyper(p, clp->cl_clientid);
*p++ = cpu_to_be32(clp->cl_seqid); /*Sequence id */
*p++ = cpu_to_be32(args->flags); /*flags */
/* Fore Channel */
*p++ = cpu_to_be32(0); /* header padding size */
*p++ = cpu_to_be32(args->fc_attrs.max_rqst_sz); /* max req size */
*p++ = cpu_to_be32(args->fc_attrs.max_resp_sz); /* max resp size */
*p++ = cpu_to_be32(max_resp_sz_cached); /* Max resp sz cached */
*p++ = cpu_to_be32(args->fc_attrs.max_ops); /* max operations */
*p++ = cpu_to_be32(args->fc_attrs.max_reqs); /* max requests */
*p++ = cpu_to_be32(0); /* rdmachannel_attrs */
/* Back Channel */
*p++ = cpu_to_be32(0); /* header padding size */
*p++ = cpu_to_be32(args->bc_attrs.max_rqst_sz); /* max req size */
*p++ = cpu_to_be32(args->bc_attrs.max_resp_sz); /* max resp size */
*p++ = cpu_to_be32(args->bc_attrs.max_resp_sz_cached); /* Max resp sz cached */
*p++ = cpu_to_be32(args->bc_attrs.max_ops); /* max operations */
*p++ = cpu_to_be32(args->bc_attrs.max_reqs); /* max requests */
*p++ = cpu_to_be32(0); /* rdmachannel_attrs */
*p++ = cpu_to_be32(args->cb_program); /* cb_program */
*p++ = cpu_to_be32(1);
*p++ = cpu_to_be32(RPC_AUTH_UNIX); /* auth_sys */
/* authsys_parms rfc1831 */
*p++ = cpu_to_be32((u32)clp->cl_boot_time.tv_nsec); /* stamp */
p = xdr_encode_opaque(p, machine_name, len);
*p++ = cpu_to_be32(0); /* UID */
*p++ = cpu_to_be32(0); /* GID */
*p = cpu_to_be32(0); /* No more gids */
}
static void encode_destroy_session(struct xdr_stream *xdr,
struct nfs4_session *session,
struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_DESTROY_SESSION, decode_destroy_session_maxsz, hdr);
encode_opaque_fixed(xdr, session->sess_id.data, NFS4_MAX_SESSIONID_LEN);
}
static void encode_reclaim_complete(struct xdr_stream *xdr,
struct nfs41_reclaim_complete_args *args,
struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_RECLAIM_COMPLETE, decode_reclaim_complete_maxsz, hdr);
encode_uint32(xdr, args->one_fs);
}
#endif /* CONFIG_NFS_V4_1 */
static void encode_sequence(struct xdr_stream *xdr,
const struct nfs4_sequence_args *args,
struct compound_hdr *hdr)
{
#if defined(CONFIG_NFS_V4_1)
struct nfs4_session *session = args->sa_session;
struct nfs4_slot_table *tp;
struct nfs4_slot *slot;
__be32 *p;
if (!session)
return;
tp = &session->fc_slot_table;
WARN_ON(args->sa_slotid == NFS4_MAX_SLOT_TABLE);
slot = tp->slots + args->sa_slotid;
encode_op_hdr(xdr, OP_SEQUENCE, decode_sequence_maxsz, hdr);
/*
* Sessionid + seqid + slotid + max slotid + cache_this
*/
dprintk("%s: sessionid=%u:%u:%u:%u seqid=%d slotid=%d "
"max_slotid=%d cache_this=%d\n",
__func__,
((u32 *)session->sess_id.data)[0],
((u32 *)session->sess_id.data)[1],
((u32 *)session->sess_id.data)[2],
((u32 *)session->sess_id.data)[3],
slot->seq_nr, args->sa_slotid,
tp->highest_used_slotid, args->sa_cache_this);
p = reserve_space(xdr, NFS4_MAX_SESSIONID_LEN + 16);
p = xdr_encode_opaque_fixed(p, session->sess_id.data, NFS4_MAX_SESSIONID_LEN);
*p++ = cpu_to_be32(slot->seq_nr);
*p++ = cpu_to_be32(args->sa_slotid);
*p++ = cpu_to_be32(tp->highest_used_slotid);
*p = cpu_to_be32(args->sa_cache_this);
#endif /* CONFIG_NFS_V4_1 */
}
#ifdef CONFIG_NFS_V4_1
static void
encode_getdevicelist(struct xdr_stream *xdr,
const struct nfs4_getdevicelist_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
nfs4_verifier dummy = {
.data = "dummmmmy",
};
encode_op_hdr(xdr, OP_GETDEVICELIST, decode_getdevicelist_maxsz, hdr);
p = reserve_space(xdr, 16);
*p++ = cpu_to_be32(args->layoutclass);
*p++ = cpu_to_be32(NFS4_PNFS_GETDEVLIST_MAXNUM);
xdr_encode_hyper(p, 0ULL); /* cookie */
encode_nfs4_verifier(xdr, &dummy);
}
static void
encode_getdeviceinfo(struct xdr_stream *xdr,
const struct nfs4_getdeviceinfo_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_GETDEVICEINFO, decode_getdeviceinfo_maxsz, hdr);
p = reserve_space(xdr, 12 + NFS4_DEVICEID4_SIZE);
p = xdr_encode_opaque_fixed(p, args->pdev->dev_id.data,
NFS4_DEVICEID4_SIZE);
*p++ = cpu_to_be32(args->pdev->layout_type);
*p++ = cpu_to_be32(args->pdev->pglen); /* gdia_maxcount */
*p++ = cpu_to_be32(0); /* bitmap length 0 */
}
static void
encode_layoutget(struct xdr_stream *xdr,
const struct nfs4_layoutget_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_LAYOUTGET, decode_layoutget_maxsz, hdr);
p = reserve_space(xdr, 36);
*p++ = cpu_to_be32(0); /* Signal layout available */
*p++ = cpu_to_be32(args->type);
*p++ = cpu_to_be32(args->range.iomode);
p = xdr_encode_hyper(p, args->range.offset);
p = xdr_encode_hyper(p, args->range.length);
p = xdr_encode_hyper(p, args->minlength);
encode_nfs4_stateid(xdr, &args->stateid);
encode_uint32(xdr, args->maxcount);
dprintk("%s: 1st type:0x%x iomode:%d off:%lu len:%lu mc:%d\n",
__func__,
args->type,
args->range.iomode,
(unsigned long)args->range.offset,
(unsigned long)args->range.length,
args->maxcount);
}
static int
encode_layoutcommit(struct xdr_stream *xdr,
struct inode *inode,
const struct nfs4_layoutcommit_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
dprintk("%s: lbw: %llu type: %d\n", __func__, args->lastbytewritten,
NFS_SERVER(args->inode)->pnfs_curr_ld->id);
encode_op_hdr(xdr, OP_LAYOUTCOMMIT, decode_layoutcommit_maxsz, hdr);
p = reserve_space(xdr, 20);
/* Only whole file layouts */
p = xdr_encode_hyper(p, 0); /* offset */
p = xdr_encode_hyper(p, args->lastbytewritten + 1); /* length */
*p = cpu_to_be32(0); /* reclaim */
encode_nfs4_stateid(xdr, &args->stateid);
p = reserve_space(xdr, 20);
*p++ = cpu_to_be32(1); /* newoffset = TRUE */
p = xdr_encode_hyper(p, args->lastbytewritten);
*p++ = cpu_to_be32(0); /* Never send time_modify_changed */
*p++ = cpu_to_be32(NFS_SERVER(args->inode)->pnfs_curr_ld->id);/* type */
if (NFS_SERVER(inode)->pnfs_curr_ld->encode_layoutcommit)
NFS_SERVER(inode)->pnfs_curr_ld->encode_layoutcommit(
NFS_I(inode)->layout, xdr, args);
else
encode_uint32(xdr, 0); /* no layout-type payload */
return 0;
}
static void
encode_layoutreturn(struct xdr_stream *xdr,
const struct nfs4_layoutreturn_args *args,
struct compound_hdr *hdr)
{
__be32 *p;
encode_op_hdr(xdr, OP_LAYOUTRETURN, decode_layoutreturn_maxsz, hdr);
p = reserve_space(xdr, 16);
*p++ = cpu_to_be32(0); /* reclaim. always 0 for now */
*p++ = cpu_to_be32(args->layout_type);
*p++ = cpu_to_be32(IOMODE_ANY);
*p = cpu_to_be32(RETURN_FILE);
p = reserve_space(xdr, 16);
p = xdr_encode_hyper(p, 0);
p = xdr_encode_hyper(p, NFS4_MAX_UINT64);
spin_lock(&args->inode->i_lock);
encode_nfs4_stateid(xdr, &args->stateid);
spin_unlock(&args->inode->i_lock);
if (NFS_SERVER(args->inode)->pnfs_curr_ld->encode_layoutreturn) {
NFS_SERVER(args->inode)->pnfs_curr_ld->encode_layoutreturn(
NFS_I(args->inode)->layout, xdr, args);
} else
encode_uint32(xdr, 0);
}
static int
encode_secinfo_no_name(struct xdr_stream *xdr,
const struct nfs41_secinfo_no_name_args *args,
struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_SECINFO_NO_NAME, decode_secinfo_no_name_maxsz, hdr);
encode_uint32(xdr, args->style);
return 0;
}
static void encode_test_stateid(struct xdr_stream *xdr,
struct nfs41_test_stateid_args *args,
struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_TEST_STATEID, decode_test_stateid_maxsz, hdr);
encode_uint32(xdr, 1);
encode_nfs4_stateid(xdr, args->stateid);
}
static void encode_free_stateid(struct xdr_stream *xdr,
struct nfs41_free_stateid_args *args,
struct compound_hdr *hdr)
{
encode_op_hdr(xdr, OP_FREE_STATEID, decode_free_stateid_maxsz, hdr);
encode_nfs4_stateid(xdr, args->stateid);
}
#endif /* CONFIG_NFS_V4_1 */
/*
* END OF "GENERIC" ENCODE ROUTINES.
*/
static u32 nfs4_xdr_minorversion(const struct nfs4_sequence_args *args)
{
#if defined(CONFIG_NFS_V4_1)
if (args->sa_session)
return args->sa_session->clp->cl_mvops->minor_version;
#endif /* CONFIG_NFS_V4_1 */
return 0;
}
/*
* Encode an ACCESS request
*/
static void nfs4_xdr_enc_access(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_accessargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_access(xdr, args->access, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode LOOKUP request
*/
static void nfs4_xdr_enc_lookup(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_lookup_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->dir_fh, &hdr);
encode_lookup(xdr, args->name, &hdr);
encode_getfh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode LOOKUP_ROOT request
*/
static void nfs4_xdr_enc_lookup_root(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nfs4_lookup_root_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putrootfh(xdr, &hdr);
encode_getfh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode REMOVE request
*/
static void nfs4_xdr_enc_remove(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs_removeargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_remove(xdr, &args->name, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode RENAME request
*/
static void nfs4_xdr_enc_rename(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs_renameargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->old_dir, &hdr);
encode_savefh(xdr, &hdr);
encode_putfh(xdr, args->new_dir, &hdr);
encode_rename(xdr, args->old_name, args->new_name, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_restorefh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode LINK request
*/
static void nfs4_xdr_enc_link(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_link_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_savefh(xdr, &hdr);
encode_putfh(xdr, args->dir_fh, &hdr);
encode_link(xdr, args->name, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_restorefh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode CREATE request
*/
static void nfs4_xdr_enc_create(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_create_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->dir_fh, &hdr);
encode_savefh(xdr, &hdr);
encode_create(xdr, args, &hdr);
encode_getfh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_restorefh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode SYMLINK request
*/
static void nfs4_xdr_enc_symlink(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_create_arg *args)
{
nfs4_xdr_enc_create(req, xdr, args);
}
/*
* Encode GETATTR request
*/
static void nfs4_xdr_enc_getattr(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_getattr_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode a CLOSE request
*/
static void nfs4_xdr_enc_close(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_closeargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_close(xdr, args, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode an OPEN request
*/
static void nfs4_xdr_enc_open(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_openargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_savefh(xdr, &hdr);
encode_open(xdr, args, &hdr);
encode_getfh(xdr, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_restorefh(xdr, &hdr);
encode_getfattr(xdr, args->dir_bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode an OPEN_CONFIRM request
*/
static void nfs4_xdr_enc_open_confirm(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs_open_confirmargs *args)
{
struct compound_hdr hdr = {
.nops = 0,
};
encode_compound_hdr(xdr, req, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_open_confirm(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode an OPEN request with no attributes.
*/
static void nfs4_xdr_enc_open_noattr(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs_openargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_open(xdr, args, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode an OPEN_DOWNGRADE request
*/
static void nfs4_xdr_enc_open_downgrade(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs_closeargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_open_downgrade(xdr, args, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode a LOCK request
*/
static void nfs4_xdr_enc_lock(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_lock_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_lock(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode a LOCKT request
*/
static void nfs4_xdr_enc_lockt(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_lockt_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_lockt(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode a LOCKU request
*/
static void nfs4_xdr_enc_locku(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_locku_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_locku(xdr, args, &hdr);
encode_nops(&hdr);
}
static void nfs4_xdr_enc_release_lockowner(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs_release_lockowner_args *args)
{
struct compound_hdr hdr = {
.minorversion = 0,
};
encode_compound_hdr(xdr, req, &hdr);
encode_release_lockowner(xdr, &args->lock_owner, &hdr);
encode_nops(&hdr);
}
/*
* Encode a READLINK request
*/
static void nfs4_xdr_enc_readlink(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_readlink *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_readlink(xdr, args, req, &hdr);
xdr_inline_pages(&req->rq_rcv_buf, hdr.replen << 2, args->pages,
args->pgbase, args->pglen);
encode_nops(&hdr);
}
/*
* Encode a READDIR request
*/
static void nfs4_xdr_enc_readdir(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_readdir_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_readdir(xdr, args, req, &hdr);
xdr_inline_pages(&req->rq_rcv_buf, hdr.replen << 2, args->pages,
args->pgbase, args->count);
dprintk("%s: inlined page args = (%u, %p, %u, %u)\n",
__func__, hdr.replen << 2, args->pages,
args->pgbase, args->count);
encode_nops(&hdr);
}
/*
* Encode a READ request
*/
static void nfs4_xdr_enc_read(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_readargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_read(xdr, args, &hdr);
xdr_inline_pages(&req->rq_rcv_buf, hdr.replen << 2,
args->pages, args->pgbase, args->count);
req->rq_rcv_buf.flags |= XDRBUF_READ;
encode_nops(&hdr);
}
/*
* Encode an SETATTR request
*/
static void nfs4_xdr_enc_setattr(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_setattrargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_setattr(xdr, args, args->server, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode a GETACL request
*/
static void nfs4_xdr_enc_getacl(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_getaclargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
uint32_t replen;
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
replen = hdr.replen + op_decode_hdr_maxsz + 1;
encode_getattr_two(xdr, FATTR4_WORD0_ACL, 0, &hdr);
xdr_inline_pages(&req->rq_rcv_buf, replen << 2,
args->acl_pages, args->acl_pgbase, args->acl_len);
encode_nops(&hdr);
}
/*
* Encode a WRITE request
*/
static void nfs4_xdr_enc_write(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_writeargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_write(xdr, args, &hdr);
req->rq_snd_buf.flags |= XDRBUF_WRITE;
if (args->bitmask)
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* a COMMIT request
*/
static void nfs4_xdr_enc_commit(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_writeargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_commit(xdr, args, &hdr);
if (args->bitmask)
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* FSINFO request
*/
static void nfs4_xdr_enc_fsinfo(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs4_fsinfo_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_fsinfo(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* a PATHCONF request
*/
static void nfs4_xdr_enc_pathconf(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_pathconf_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_getattr_one(xdr, args->bitmask[0] & nfs4_pathconf_bitmap[0],
&hdr);
encode_nops(&hdr);
}
/*
* a STATFS request
*/
static void nfs4_xdr_enc_statfs(struct rpc_rqst *req, struct xdr_stream *xdr,
const struct nfs4_statfs_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_getattr_two(xdr, args->bitmask[0] & nfs4_statfs_bitmap[0],
args->bitmask[1] & nfs4_statfs_bitmap[1], &hdr);
encode_nops(&hdr);
}
/*
* GETATTR_BITMAP request
*/
static void nfs4_xdr_enc_server_caps(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_server_caps_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fhandle, &hdr);
encode_getattr_one(xdr, FATTR4_WORD0_SUPPORTED_ATTRS|
FATTR4_WORD0_FH_EXPIRE_TYPE|
FATTR4_WORD0_LINK_SUPPORT|
FATTR4_WORD0_SYMLINK_SUPPORT|
FATTR4_WORD0_ACLSUPPORT, &hdr);
encode_nops(&hdr);
}
/*
* a RENEW request
*/
static void nfs4_xdr_enc_renew(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_client *clp)
{
struct compound_hdr hdr = {
.nops = 0,
};
encode_compound_hdr(xdr, req, &hdr);
encode_renew(xdr, clp->cl_clientid, &hdr);
encode_nops(&hdr);
}
/*
* a SETCLIENTID request
*/
static void nfs4_xdr_enc_setclientid(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_setclientid *sc)
{
struct compound_hdr hdr = {
.nops = 0,
};
encode_compound_hdr(xdr, req, &hdr);
encode_setclientid(xdr, sc, &hdr);
encode_nops(&hdr);
}
/*
* a SETCLIENTID_CONFIRM request
*/
static void nfs4_xdr_enc_setclientid_confirm(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_setclientid_res *arg)
{
struct compound_hdr hdr = {
.nops = 0,
};
const u32 lease_bitmap[3] = { FATTR4_WORD0_LEASE_TIME };
encode_compound_hdr(xdr, req, &hdr);
encode_setclientid_confirm(xdr, arg, &hdr);
encode_putrootfh(xdr, &hdr);
encode_fsinfo(xdr, lease_bitmap, &hdr);
encode_nops(&hdr);
}
/*
* DELEGRETURN request
*/
static void nfs4_xdr_enc_delegreturn(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nfs4_delegreturnargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fhandle, &hdr);
encode_delegreturn(xdr, args->stateid, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode FS_LOCATIONS request
*/
static void nfs4_xdr_enc_fs_locations(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_fs_locations_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
uint32_t replen;
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->dir_fh, &hdr);
encode_lookup(xdr, args->name, &hdr);
replen = hdr.replen; /* get the attribute into args->page */
encode_fs_locations(xdr, args->bitmask, &hdr);
xdr_inline_pages(&req->rq_rcv_buf, replen << 2, &args->page,
0, PAGE_SIZE);
encode_nops(&hdr);
}
/*
* Encode SECINFO request
*/
static void nfs4_xdr_enc_secinfo(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_secinfo_arg *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->dir_fh, &hdr);
encode_secinfo(xdr, args->name, &hdr);
encode_nops(&hdr);
}
#if defined(CONFIG_NFS_V4_1)
/*
* EXCHANGE_ID request
*/
static void nfs4_xdr_enc_exchange_id(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs41_exchange_id_args *args)
{
struct compound_hdr hdr = {
.minorversion = args->client->cl_mvops->minor_version,
};
encode_compound_hdr(xdr, req, &hdr);
encode_exchange_id(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* a CREATE_SESSION request
*/
static void nfs4_xdr_enc_create_session(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs41_create_session_args *args)
{
struct compound_hdr hdr = {
.minorversion = args->client->cl_mvops->minor_version,
};
encode_compound_hdr(xdr, req, &hdr);
encode_create_session(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* a DESTROY_SESSION request
*/
static void nfs4_xdr_enc_destroy_session(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_session *session)
{
struct compound_hdr hdr = {
.minorversion = session->clp->cl_mvops->minor_version,
};
encode_compound_hdr(xdr, req, &hdr);
encode_destroy_session(xdr, session, &hdr);
encode_nops(&hdr);
}
/*
* a SEQUENCE request
*/
static void nfs4_xdr_enc_sequence(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs4_sequence_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* a GET_LEASE_TIME request
*/
static void nfs4_xdr_enc_get_lease_time(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_get_lease_time_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->la_seq_args),
};
const u32 lease_bitmap[3] = { FATTR4_WORD0_LEASE_TIME };
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->la_seq_args, &hdr);
encode_putrootfh(xdr, &hdr);
encode_fsinfo(xdr, lease_bitmap, &hdr);
encode_nops(&hdr);
}
/*
* a RECLAIM_COMPLETE request
*/
static void nfs4_xdr_enc_reclaim_complete(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs41_reclaim_complete_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args)
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_reclaim_complete(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode GETDEVICELIST request
*/
static void nfs4_xdr_enc_getdevicelist(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_getdevicelist_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_getdevicelist(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode GETDEVICEINFO request
*/
static void nfs4_xdr_enc_getdeviceinfo(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_getdeviceinfo_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_getdeviceinfo(xdr, args, &hdr);
/* set up reply kvec. Subtract notification bitmap max size (2)
* so that notification bitmap is put in xdr_buf tail */
xdr_inline_pages(&req->rq_rcv_buf, (hdr.replen - 2) << 2,
args->pdev->pages, args->pdev->pgbase,
args->pdev->pglen);
encode_nops(&hdr);
}
/*
* Encode LAYOUTGET request
*/
static void nfs4_xdr_enc_layoutget(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_layoutget_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, NFS_FH(args->inode), &hdr);
encode_layoutget(xdr, args, &hdr);
xdr_inline_pages(&req->rq_rcv_buf, hdr.replen << 2,
args->layout.pages, 0, args->layout.pglen);
encode_nops(&hdr);
}
/*
* Encode LAYOUTCOMMIT request
*/
static void nfs4_xdr_enc_layoutcommit(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_layoutcommit_args *args)
{
struct nfs4_layoutcommit_data *data =
container_of(args, struct nfs4_layoutcommit_data, args);
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, NFS_FH(args->inode), &hdr);
encode_layoutcommit(xdr, data->args.inode, args, &hdr);
encode_getfattr(xdr, args->bitmask, &hdr);
encode_nops(&hdr);
}
/*
* Encode LAYOUTRETURN request
*/
static void nfs4_xdr_enc_layoutreturn(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_layoutreturn_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, NFS_FH(args->inode), &hdr);
encode_layoutreturn(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode SECINFO_NO_NAME request
*/
static int nfs4_xdr_enc_secinfo_no_name(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs41_secinfo_no_name_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putrootfh(xdr, &hdr);
encode_secinfo_no_name(xdr, args, &hdr);
encode_nops(&hdr);
return 0;
}
/*
* Encode TEST_STATEID request
*/
static void nfs4_xdr_enc_test_stateid(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs41_test_stateid_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_test_stateid(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Encode FREE_STATEID request
*/
static void nfs4_xdr_enc_free_stateid(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs41_free_stateid_args *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_free_stateid(xdr, args, &hdr);
encode_nops(&hdr);
}
#endif /* CONFIG_NFS_V4_1 */
static void print_overflow_msg(const char *func, const struct xdr_stream *xdr)
{
dprintk("nfs: %s: prematurely hit end of receive buffer. "
"Remaining buffer length is %tu words.\n",
func, xdr->end - xdr->p);
}
static int decode_opaque_inline(struct xdr_stream *xdr, unsigned int *len, char **string)
{
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*len = be32_to_cpup(p);
p = xdr_inline_decode(xdr, *len);
if (unlikely(!p))
goto out_overflow;
*string = (char *)p;
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_compound_hdr(struct xdr_stream *xdr, struct compound_hdr *hdr)
{
__be32 *p;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
hdr->status = be32_to_cpup(p++);
hdr->taglen = be32_to_cpup(p);
p = xdr_inline_decode(xdr, hdr->taglen + 4);
if (unlikely(!p))
goto out_overflow;
hdr->tag = (char *)p;
p += XDR_QUADLEN(hdr->taglen);
hdr->nops = be32_to_cpup(p);
if (unlikely(hdr->nops < 1))
return nfs4_stat_to_errno(hdr->status);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_op_hdr(struct xdr_stream *xdr, enum nfs_opnum4 expected)
{
__be32 *p;
uint32_t opnum;
int32_t nfserr;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
opnum = be32_to_cpup(p++);
if (opnum != expected) {
dprintk("nfs: Server returned operation"
" %d but we issued a request for %d\n",
opnum, expected);
return -EIO;
}
nfserr = be32_to_cpup(p);
if (nfserr != NFS_OK)
return nfs4_stat_to_errno(nfserr);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
/* Dummy routine */
static int decode_ace(struct xdr_stream *xdr, void *ace, struct nfs_client *clp)
{
__be32 *p;
unsigned int strlen;
char *str;
p = xdr_inline_decode(xdr, 12);
if (likely(p))
return decode_opaque_inline(xdr, &strlen, &str);
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_bitmap(struct xdr_stream *xdr, uint32_t *bitmap)
{
uint32_t bmlen;
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
bmlen = be32_to_cpup(p);
bitmap[0] = bitmap[1] = bitmap[2] = 0;
p = xdr_inline_decode(xdr, (bmlen << 2));
if (unlikely(!p))
goto out_overflow;
if (bmlen > 0) {
bitmap[0] = be32_to_cpup(p++);
if (bmlen > 1) {
bitmap[1] = be32_to_cpup(p++);
if (bmlen > 2)
bitmap[2] = be32_to_cpup(p);
}
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static inline int decode_attr_length(struct xdr_stream *xdr, uint32_t *attrlen, __be32 **savep)
{
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*attrlen = be32_to_cpup(p);
*savep = xdr->p;
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_supported(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *bitmask)
{
if (likely(bitmap[0] & FATTR4_WORD0_SUPPORTED_ATTRS)) {
int ret;
ret = decode_attr_bitmap(xdr, bitmask);
if (unlikely(ret < 0))
return ret;
bitmap[0] &= ~FATTR4_WORD0_SUPPORTED_ATTRS;
} else
bitmask[0] = bitmask[1] = bitmask[2] = 0;
dprintk("%s: bitmask=%08x:%08x:%08x\n", __func__,
bitmask[0], bitmask[1], bitmask[2]);
return 0;
}
static int decode_attr_type(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *type)
{
__be32 *p;
int ret = 0;
*type = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_TYPE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_TYPE)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*type = be32_to_cpup(p);
if (*type < NF4REG || *type > NF4NAMEDATTR) {
dprintk("%s: bad type %d\n", __func__, *type);
return -EIO;
}
bitmap[0] &= ~FATTR4_WORD0_TYPE;
ret = NFS_ATTR_FATTR_TYPE;
}
dprintk("%s: type=0%o\n", __func__, nfs_type2fmt[*type]);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_fh_expire_type(struct xdr_stream *xdr,
uint32_t *bitmap, uint32_t *type)
{
__be32 *p;
*type = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FH_EXPIRE_TYPE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FH_EXPIRE_TYPE)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*type = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_FH_EXPIRE_TYPE;
}
dprintk("%s: expire type=0x%x\n", __func__, *type);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_change(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *change)
{
__be32 *p;
int ret = 0;
*change = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_CHANGE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_CHANGE)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, change);
bitmap[0] &= ~FATTR4_WORD0_CHANGE;
ret = NFS_ATTR_FATTR_CHANGE;
}
dprintk("%s: change attribute=%Lu\n", __func__,
(unsigned long long)*change);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_size(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *size)
{
__be32 *p;
int ret = 0;
*size = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_SIZE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_SIZE)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, size);
bitmap[0] &= ~FATTR4_WORD0_SIZE;
ret = NFS_ATTR_FATTR_SIZE;
}
dprintk("%s: file size=%Lu\n", __func__, (unsigned long long)*size);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_link_support(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res)
{
__be32 *p;
*res = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_LINK_SUPPORT - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_LINK_SUPPORT)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*res = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_LINK_SUPPORT;
}
dprintk("%s: link support=%s\n", __func__, *res == 0 ? "false" : "true");
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_symlink_support(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res)
{
__be32 *p;
*res = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_SYMLINK_SUPPORT - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_SYMLINK_SUPPORT)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*res = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_SYMLINK_SUPPORT;
}
dprintk("%s: symlink support=%s\n", __func__, *res == 0 ? "false" : "true");
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_fsid(struct xdr_stream *xdr, uint32_t *bitmap, struct nfs_fsid *fsid)
{
__be32 *p;
int ret = 0;
fsid->major = 0;
fsid->minor = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FSID - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FSID)) {
p = xdr_inline_decode(xdr, 16);
if (unlikely(!p))
goto out_overflow;
p = xdr_decode_hyper(p, &fsid->major);
xdr_decode_hyper(p, &fsid->minor);
bitmap[0] &= ~FATTR4_WORD0_FSID;
ret = NFS_ATTR_FATTR_FSID;
}
dprintk("%s: fsid=(0x%Lx/0x%Lx)\n", __func__,
(unsigned long long)fsid->major,
(unsigned long long)fsid->minor);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_lease_time(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res)
{
__be32 *p;
*res = 60;
if (unlikely(bitmap[0] & (FATTR4_WORD0_LEASE_TIME - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_LEASE_TIME)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*res = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_LEASE_TIME;
}
dprintk("%s: file size=%u\n", __func__, (unsigned int)*res);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_error(struct xdr_stream *xdr, uint32_t *bitmap, int32_t *res)
{
__be32 *p;
if (unlikely(bitmap[0] & (FATTR4_WORD0_RDATTR_ERROR - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_RDATTR_ERROR)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
bitmap[0] &= ~FATTR4_WORD0_RDATTR_ERROR;
*res = -be32_to_cpup(p);
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_filehandle(struct xdr_stream *xdr, uint32_t *bitmap, struct nfs_fh *fh)
{
__be32 *p;
int len;
if (fh != NULL)
memset(fh, 0, sizeof(*fh));
if (unlikely(bitmap[0] & (FATTR4_WORD0_FILEHANDLE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FILEHANDLE)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
if (len > NFS4_FHSIZE)
return -EIO;
p = xdr_inline_decode(xdr, len);
if (unlikely(!p))
goto out_overflow;
if (fh != NULL) {
memcpy(fh->data, p, len);
fh->size = len;
}
bitmap[0] &= ~FATTR4_WORD0_FILEHANDLE;
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_aclsupport(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res)
{
__be32 *p;
*res = ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL;
if (unlikely(bitmap[0] & (FATTR4_WORD0_ACLSUPPORT - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_ACLSUPPORT)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*res = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_ACLSUPPORT;
}
dprintk("%s: ACLs supported=%u\n", __func__, (unsigned int)*res);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_fileid(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *fileid)
{
__be32 *p;
int ret = 0;
*fileid = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FILEID - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FILEID)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, fileid);
bitmap[0] &= ~FATTR4_WORD0_FILEID;
ret = NFS_ATTR_FATTR_FILEID;
}
dprintk("%s: fileid=%Lu\n", __func__, (unsigned long long)*fileid);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_mounted_on_fileid(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *fileid)
{
__be32 *p;
int ret = 0;
*fileid = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_MOUNTED_ON_FILEID - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_MOUNTED_ON_FILEID)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, fileid);
bitmap[1] &= ~FATTR4_WORD1_MOUNTED_ON_FILEID;
ret = NFS_ATTR_FATTR_MOUNTED_ON_FILEID;
}
dprintk("%s: fileid=%Lu\n", __func__, (unsigned long long)*fileid);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_files_avail(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FILES_AVAIL - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FILES_AVAIL)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[0] &= ~FATTR4_WORD0_FILES_AVAIL;
}
dprintk("%s: files avail=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_files_free(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FILES_FREE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FILES_FREE)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[0] &= ~FATTR4_WORD0_FILES_FREE;
}
dprintk("%s: files free=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_files_total(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FILES_TOTAL - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_FILES_TOTAL)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[0] &= ~FATTR4_WORD0_FILES_TOTAL;
}
dprintk("%s: files total=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_pathname(struct xdr_stream *xdr, struct nfs4_pathname *path)
{
u32 n;
__be32 *p;
int status = 0;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
n = be32_to_cpup(p);
if (n == 0)
goto root_path;
dprintk("pathname4: ");
path->ncomponents = 0;
while (path->ncomponents < n) {
struct nfs4_string *component = &path->components[path->ncomponents];
status = decode_opaque_inline(xdr, &component->len, &component->data);
if (unlikely(status != 0))
goto out_eio;
ifdebug (XDR)
pr_cont("%s%.*s ",
(path->ncomponents != n ? "/ " : ""),
component->len, component->data);
if (path->ncomponents < NFS4_PATHNAME_MAXCOMPONENTS)
path->ncomponents++;
else {
dprintk("cannot parse %d components in path\n", n);
goto out_eio;
}
}
out:
return status;
root_path:
/* a root pathname is sent as a zero component4 */
path->ncomponents = 1;
path->components[0].len=0;
path->components[0].data=NULL;
dprintk("pathname4: /\n");
goto out;
out_eio:
dprintk(" status %d", status);
status = -EIO;
goto out;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_fs_locations(struct xdr_stream *xdr, uint32_t *bitmap, struct nfs4_fs_locations *res)
{
int n;
__be32 *p;
int status = -EIO;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FS_LOCATIONS -1U)))
goto out;
status = 0;
if (unlikely(!(bitmap[0] & FATTR4_WORD0_FS_LOCATIONS)))
goto out;
status = -EIO;
/* Ignore borken servers that return unrequested attrs */
if (unlikely(res == NULL))
goto out;
dprintk("%s: fsroot:\n", __func__);
status = decode_pathname(xdr, &res->fs_path);
if (unlikely(status != 0))
goto out;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
n = be32_to_cpup(p);
if (n <= 0)
goto out_eio;
res->nlocations = 0;
while (res->nlocations < n) {
u32 m;
struct nfs4_fs_location *loc = &res->locations[res->nlocations];
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
m = be32_to_cpup(p);
loc->nservers = 0;
dprintk("%s: servers:\n", __func__);
while (loc->nservers < m) {
struct nfs4_string *server = &loc->servers[loc->nservers];
status = decode_opaque_inline(xdr, &server->len, &server->data);
if (unlikely(status != 0))
goto out_eio;
dprintk("%s ", server->data);
if (loc->nservers < NFS4_FS_LOCATION_MAXSERVERS)
loc->nservers++;
else {
unsigned int i;
dprintk("%s: using first %u of %u servers "
"returned for location %u\n",
__func__,
NFS4_FS_LOCATION_MAXSERVERS,
m, res->nlocations);
for (i = loc->nservers; i < m; i++) {
unsigned int len;
char *data;
status = decode_opaque_inline(xdr, &len, &data);
if (unlikely(status != 0))
goto out_eio;
}
}
}
status = decode_pathname(xdr, &loc->rootpath);
if (unlikely(status != 0))
goto out_eio;
if (res->nlocations < NFS4_FS_LOCATIONS_MAXENTRIES)
res->nlocations++;
}
if (res->nlocations != 0)
status = NFS_ATTR_FATTR_V4_LOCATIONS;
out:
dprintk("%s: fs_locations done, error = %d\n", __func__, status);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
out_eio:
status = -EIO;
goto out;
}
static int decode_attr_maxfilesize(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[0] & (FATTR4_WORD0_MAXFILESIZE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_MAXFILESIZE)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[0] &= ~FATTR4_WORD0_MAXFILESIZE;
}
dprintk("%s: maxfilesize=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_maxlink(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *maxlink)
{
__be32 *p;
int status = 0;
*maxlink = 1;
if (unlikely(bitmap[0] & (FATTR4_WORD0_MAXLINK - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_MAXLINK)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*maxlink = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_MAXLINK;
}
dprintk("%s: maxlink=%u\n", __func__, *maxlink);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_maxname(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *maxname)
{
__be32 *p;
int status = 0;
*maxname = 1024;
if (unlikely(bitmap[0] & (FATTR4_WORD0_MAXNAME - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_MAXNAME)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*maxname = be32_to_cpup(p);
bitmap[0] &= ~FATTR4_WORD0_MAXNAME;
}
dprintk("%s: maxname=%u\n", __func__, *maxname);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_maxread(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res)
{
__be32 *p;
int status = 0;
*res = 1024;
if (unlikely(bitmap[0] & (FATTR4_WORD0_MAXREAD - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_MAXREAD)) {
uint64_t maxread;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, &maxread);
if (maxread > 0x7FFFFFFF)
maxread = 0x7FFFFFFF;
*res = (uint32_t)maxread;
bitmap[0] &= ~FATTR4_WORD0_MAXREAD;
}
dprintk("%s: maxread=%lu\n", __func__, (unsigned long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_maxwrite(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res)
{
__be32 *p;
int status = 0;
*res = 1024;
if (unlikely(bitmap[0] & (FATTR4_WORD0_MAXWRITE - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_MAXWRITE)) {
uint64_t maxwrite;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, &maxwrite);
if (maxwrite > 0x7FFFFFFF)
maxwrite = 0x7FFFFFFF;
*res = (uint32_t)maxwrite;
bitmap[0] &= ~FATTR4_WORD0_MAXWRITE;
}
dprintk("%s: maxwrite=%lu\n", __func__, (unsigned long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_mode(struct xdr_stream *xdr, uint32_t *bitmap, umode_t *mode)
{
uint32_t tmp;
__be32 *p;
int ret = 0;
*mode = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_MODE - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_MODE)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
tmp = be32_to_cpup(p);
*mode = tmp & ~S_IFMT;
bitmap[1] &= ~FATTR4_WORD1_MODE;
ret = NFS_ATTR_FATTR_MODE;
}
dprintk("%s: file mode=0%o\n", __func__, (unsigned int)*mode);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_nlink(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *nlink)
{
__be32 *p;
int ret = 0;
*nlink = 1;
if (unlikely(bitmap[1] & (FATTR4_WORD1_NUMLINKS - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_NUMLINKS)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
*nlink = be32_to_cpup(p);
bitmap[1] &= ~FATTR4_WORD1_NUMLINKS;
ret = NFS_ATTR_FATTR_NLINK;
}
dprintk("%s: nlink=%u\n", __func__, (unsigned int)*nlink);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_owner(struct xdr_stream *xdr, uint32_t *bitmap,
const struct nfs_server *server, uint32_t *uid,
struct nfs4_string *owner_name)
{
uint32_t len;
__be32 *p;
int ret = 0;
*uid = -2;
if (unlikely(bitmap[1] & (FATTR4_WORD1_OWNER - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_OWNER)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
p = xdr_inline_decode(xdr, len);
if (unlikely(!p))
goto out_overflow;
if (owner_name != NULL) {
owner_name->data = kmemdup(p, len, GFP_NOWAIT);
if (owner_name->data != NULL) {
owner_name->len = len;
ret = NFS_ATTR_FATTR_OWNER_NAME;
}
} else if (len < XDR_MAX_NETOBJ) {
if (nfs_map_name_to_uid(server, (char *)p, len, uid) == 0)
ret = NFS_ATTR_FATTR_OWNER;
else
dprintk("%s: nfs_map_name_to_uid failed!\n",
__func__);
} else
dprintk("%s: name too long (%u)!\n",
__func__, len);
bitmap[1] &= ~FATTR4_WORD1_OWNER;
}
dprintk("%s: uid=%d\n", __func__, (int)*uid);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_group(struct xdr_stream *xdr, uint32_t *bitmap,
const struct nfs_server *server, uint32_t *gid,
struct nfs4_string *group_name)
{
uint32_t len;
__be32 *p;
int ret = 0;
*gid = -2;
if (unlikely(bitmap[1] & (FATTR4_WORD1_OWNER_GROUP - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_OWNER_GROUP)) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
p = xdr_inline_decode(xdr, len);
if (unlikely(!p))
goto out_overflow;
if (group_name != NULL) {
group_name->data = kmemdup(p, len, GFP_NOWAIT);
if (group_name->data != NULL) {
group_name->len = len;
ret = NFS_ATTR_FATTR_GROUP_NAME;
}
} else if (len < XDR_MAX_NETOBJ) {
if (nfs_map_group_to_gid(server, (char *)p, len, gid) == 0)
ret = NFS_ATTR_FATTR_GROUP;
else
dprintk("%s: nfs_map_group_to_gid failed!\n",
__func__);
} else
dprintk("%s: name too long (%u)!\n",
__func__, len);
bitmap[1] &= ~FATTR4_WORD1_OWNER_GROUP;
}
dprintk("%s: gid=%d\n", __func__, (int)*gid);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_rdev(struct xdr_stream *xdr, uint32_t *bitmap, dev_t *rdev)
{
uint32_t major = 0, minor = 0;
__be32 *p;
int ret = 0;
*rdev = MKDEV(0,0);
if (unlikely(bitmap[1] & (FATTR4_WORD1_RAWDEV - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_RAWDEV)) {
dev_t tmp;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
major = be32_to_cpup(p++);
minor = be32_to_cpup(p);
tmp = MKDEV(major, minor);
if (MAJOR(tmp) == major && MINOR(tmp) == minor)
*rdev = tmp;
bitmap[1] &= ~ FATTR4_WORD1_RAWDEV;
ret = NFS_ATTR_FATTR_RDEV;
}
dprintk("%s: rdev=(0x%x:0x%x)\n", __func__, major, minor);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_space_avail(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_SPACE_AVAIL - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_SPACE_AVAIL)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[1] &= ~FATTR4_WORD1_SPACE_AVAIL;
}
dprintk("%s: space avail=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_space_free(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_SPACE_FREE - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_SPACE_FREE)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[1] &= ~FATTR4_WORD1_SPACE_FREE;
}
dprintk("%s: space free=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_space_total(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
__be32 *p;
int status = 0;
*res = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_SPACE_TOTAL - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_SPACE_TOTAL)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, res);
bitmap[1] &= ~FATTR4_WORD1_SPACE_TOTAL;
}
dprintk("%s: space total=%Lu\n", __func__, (unsigned long long)*res);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_space_used(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *used)
{
__be32 *p;
int ret = 0;
*used = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_SPACE_USED - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_SPACE_USED)) {
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, used);
bitmap[1] &= ~FATTR4_WORD1_SPACE_USED;
ret = NFS_ATTR_FATTR_SPACE_USED;
}
dprintk("%s: space used=%Lu\n", __func__,
(unsigned long long)*used);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_time(struct xdr_stream *xdr, struct timespec *time)
{
__be32 *p;
uint64_t sec;
uint32_t nsec;
p = xdr_inline_decode(xdr, 12);
if (unlikely(!p))
goto out_overflow;
p = xdr_decode_hyper(p, &sec);
nsec = be32_to_cpup(p);
time->tv_sec = (time_t)sec;
time->tv_nsec = (long)nsec;
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_attr_time_access(struct xdr_stream *xdr, uint32_t *bitmap, struct timespec *time)
{
int status = 0;
time->tv_sec = 0;
time->tv_nsec = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_TIME_ACCESS - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_TIME_ACCESS)) {
status = decode_attr_time(xdr, time);
if (status == 0)
status = NFS_ATTR_FATTR_ATIME;
bitmap[1] &= ~FATTR4_WORD1_TIME_ACCESS;
}
dprintk("%s: atime=%ld\n", __func__, (long)time->tv_sec);
return status;
}
static int decode_attr_time_metadata(struct xdr_stream *xdr, uint32_t *bitmap, struct timespec *time)
{
int status = 0;
time->tv_sec = 0;
time->tv_nsec = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_TIME_METADATA - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_TIME_METADATA)) {
status = decode_attr_time(xdr, time);
if (status == 0)
status = NFS_ATTR_FATTR_CTIME;
bitmap[1] &= ~FATTR4_WORD1_TIME_METADATA;
}
dprintk("%s: ctime=%ld\n", __func__, (long)time->tv_sec);
return status;
}
static int decode_attr_time_delta(struct xdr_stream *xdr, uint32_t *bitmap,
struct timespec *time)
{
int status = 0;
time->tv_sec = 0;
time->tv_nsec = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_TIME_DELTA - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_TIME_DELTA)) {
status = decode_attr_time(xdr, time);
bitmap[1] &= ~FATTR4_WORD1_TIME_DELTA;
}
dprintk("%s: time_delta=%ld %ld\n", __func__, (long)time->tv_sec,
(long)time->tv_nsec);
return status;
}
static int decode_attr_time_modify(struct xdr_stream *xdr, uint32_t *bitmap, struct timespec *time)
{
int status = 0;
time->tv_sec = 0;
time->tv_nsec = 0;
if (unlikely(bitmap[1] & (FATTR4_WORD1_TIME_MODIFY - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_TIME_MODIFY)) {
status = decode_attr_time(xdr, time);
if (status == 0)
status = NFS_ATTR_FATTR_MTIME;
bitmap[1] &= ~FATTR4_WORD1_TIME_MODIFY;
}
dprintk("%s: mtime=%ld\n", __func__, (long)time->tv_sec);
return status;
}
static int verify_attr_len(struct xdr_stream *xdr, __be32 *savep, uint32_t attrlen)
{
unsigned int attrwords = XDR_QUADLEN(attrlen);
unsigned int nwords = xdr->p - savep;
if (unlikely(attrwords != nwords)) {
dprintk("%s: server returned incorrect attribute length: "
"%u %c %u\n",
__func__,
attrwords << 2,
(attrwords < nwords) ? '<' : '>',
nwords << 2);
return -EIO;
}
return 0;
}
static int decode_change_info(struct xdr_stream *xdr, struct nfs4_change_info *cinfo)
{
__be32 *p;
p = xdr_inline_decode(xdr, 20);
if (unlikely(!p))
goto out_overflow;
cinfo->atomic = be32_to_cpup(p++);
p = xdr_decode_hyper(p, &cinfo->before);
xdr_decode_hyper(p, &cinfo->after);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_access(struct xdr_stream *xdr, struct nfs4_accessres *access)
{
__be32 *p;
uint32_t supp, acc;
int status;
status = decode_op_hdr(xdr, OP_ACCESS);
if (status)
return status;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
supp = be32_to_cpup(p++);
acc = be32_to_cpup(p);
access->supported = supp;
access->access = acc;
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_opaque_fixed(struct xdr_stream *xdr, void *buf, size_t len)
{
__be32 *p;
p = xdr_inline_decode(xdr, len);
if (likely(p)) {
memcpy(buf, p, len);
return 0;
}
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_stateid(struct xdr_stream *xdr, nfs4_stateid *stateid)
{
return decode_opaque_fixed(xdr, stateid, NFS4_STATEID_SIZE);
}
static int decode_close(struct xdr_stream *xdr, struct nfs_closeres *res)
{
int status;
status = decode_op_hdr(xdr, OP_CLOSE);
if (status != -EIO)
nfs_increment_open_seqid(status, res->seqid);
if (!status)
status = decode_stateid(xdr, &res->stateid);
return status;
}
static int decode_verifier(struct xdr_stream *xdr, void *verifier)
{
return decode_opaque_fixed(xdr, verifier, NFS4_VERIFIER_SIZE);
}
static int decode_commit(struct xdr_stream *xdr, struct nfs_writeres *res)
{
int status;
status = decode_op_hdr(xdr, OP_COMMIT);
if (!status)
status = decode_verifier(xdr, res->verf->verifier);
return status;
}
static int decode_create(struct xdr_stream *xdr, struct nfs4_change_info *cinfo)
{
__be32 *p;
uint32_t bmlen;
int status;
status = decode_op_hdr(xdr, OP_CREATE);
if (status)
return status;
if ((status = decode_change_info(xdr, cinfo)))
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
bmlen = be32_to_cpup(p);
p = xdr_inline_decode(xdr, bmlen << 2);
if (likely(p))
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_server_caps(struct xdr_stream *xdr, struct nfs4_server_caps_res *res)
{
__be32 *savep;
uint32_t attrlen, bitmap[3] = {0};
int status;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto xdr_error;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto xdr_error;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto xdr_error;
if ((status = decode_attr_supported(xdr, bitmap, res->attr_bitmask)) != 0)
goto xdr_error;
if ((status = decode_attr_fh_expire_type(xdr, bitmap,
&res->fh_expire_type)) != 0)
goto xdr_error;
if ((status = decode_attr_link_support(xdr, bitmap, &res->has_links)) != 0)
goto xdr_error;
if ((status = decode_attr_symlink_support(xdr, bitmap, &res->has_symlinks)) != 0)
goto xdr_error;
if ((status = decode_attr_aclsupport(xdr, bitmap, &res->acl_bitmask)) != 0)
goto xdr_error;
status = verify_attr_len(xdr, savep, attrlen);
xdr_error:
dprintk("%s: xdr returned %d!\n", __func__, -status);
return status;
}
static int decode_statfs(struct xdr_stream *xdr, struct nfs_fsstat *fsstat)
{
__be32 *savep;
uint32_t attrlen, bitmap[3] = {0};
int status;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto xdr_error;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto xdr_error;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto xdr_error;
if ((status = decode_attr_files_avail(xdr, bitmap, &fsstat->afiles)) != 0)
goto xdr_error;
if ((status = decode_attr_files_free(xdr, bitmap, &fsstat->ffiles)) != 0)
goto xdr_error;
if ((status = decode_attr_files_total(xdr, bitmap, &fsstat->tfiles)) != 0)
goto xdr_error;
if ((status = decode_attr_space_avail(xdr, bitmap, &fsstat->abytes)) != 0)
goto xdr_error;
if ((status = decode_attr_space_free(xdr, bitmap, &fsstat->fbytes)) != 0)
goto xdr_error;
if ((status = decode_attr_space_total(xdr, bitmap, &fsstat->tbytes)) != 0)
goto xdr_error;
status = verify_attr_len(xdr, savep, attrlen);
xdr_error:
dprintk("%s: xdr returned %d!\n", __func__, -status);
return status;
}
static int decode_pathconf(struct xdr_stream *xdr, struct nfs_pathconf *pathconf)
{
__be32 *savep;
uint32_t attrlen, bitmap[3] = {0};
int status;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto xdr_error;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto xdr_error;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto xdr_error;
if ((status = decode_attr_maxlink(xdr, bitmap, &pathconf->max_link)) != 0)
goto xdr_error;
if ((status = decode_attr_maxname(xdr, bitmap, &pathconf->max_namelen)) != 0)
goto xdr_error;
status = verify_attr_len(xdr, savep, attrlen);
xdr_error:
dprintk("%s: xdr returned %d!\n", __func__, -status);
return status;
}
static int decode_getfattr_attrs(struct xdr_stream *xdr, uint32_t *bitmap,
struct nfs_fattr *fattr, struct nfs_fh *fh,
struct nfs4_fs_locations *fs_loc,
const struct nfs_server *server)
{
int status;
umode_t fmode = 0;
uint32_t type;
int32_t err;
status = decode_attr_type(xdr, bitmap, &type);
if (status < 0)
goto xdr_error;
fattr->mode = 0;
if (status != 0) {
fattr->mode |= nfs_type2fmt[type];
fattr->valid |= status;
}
status = decode_attr_change(xdr, bitmap, &fattr->change_attr);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_size(xdr, bitmap, &fattr->size);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_fsid(xdr, bitmap, &fattr->fsid);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
err = 0;
status = decode_attr_error(xdr, bitmap, &err);
if (status < 0)
goto xdr_error;
status = decode_attr_filehandle(xdr, bitmap, fh);
if (status < 0)
goto xdr_error;
status = decode_attr_fileid(xdr, bitmap, &fattr->fileid);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_fs_locations(xdr, bitmap, fs_loc);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_mode(xdr, bitmap, &fmode);
if (status < 0)
goto xdr_error;
if (status != 0) {
fattr->mode |= fmode;
fattr->valid |= status;
}
status = decode_attr_nlink(xdr, bitmap, &fattr->nlink);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_owner(xdr, bitmap, server, &fattr->uid, fattr->owner_name);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_group(xdr, bitmap, server, &fattr->gid, fattr->group_name);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_rdev(xdr, bitmap, &fattr->rdev);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_space_used(xdr, bitmap, &fattr->du.nfs3.used);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_time_access(xdr, bitmap, &fattr->atime);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_time_metadata(xdr, bitmap, &fattr->ctime);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_time_modify(xdr, bitmap, &fattr->mtime);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
status = decode_attr_mounted_on_fileid(xdr, bitmap, &fattr->mounted_on_fileid);
if (status < 0)
goto xdr_error;
fattr->valid |= status;
xdr_error:
dprintk("%s: xdr returned %d\n", __func__, -status);
return status;
}
static int decode_getfattr_generic(struct xdr_stream *xdr, struct nfs_fattr *fattr,
struct nfs_fh *fh, struct nfs4_fs_locations *fs_loc,
const struct nfs_server *server)
{
__be32 *savep;
uint32_t attrlen,
bitmap[3] = {0};
int status;
status = decode_op_hdr(xdr, OP_GETATTR);
if (status < 0)
goto xdr_error;
status = decode_attr_bitmap(xdr, bitmap);
if (status < 0)
goto xdr_error;
status = decode_attr_length(xdr, &attrlen, &savep);
if (status < 0)
goto xdr_error;
status = decode_getfattr_attrs(xdr, bitmap, fattr, fh, fs_loc, server);
if (status < 0)
goto xdr_error;
status = verify_attr_len(xdr, savep, attrlen);
xdr_error:
dprintk("%s: xdr returned %d\n", __func__, -status);
return status;
}
static int decode_getfattr(struct xdr_stream *xdr, struct nfs_fattr *fattr,
const struct nfs_server *server)
{
return decode_getfattr_generic(xdr, fattr, NULL, NULL, server);
}
/*
* Decode potentially multiple layout types. Currently we only support
* one layout driver per file system.
*/
static int decode_first_pnfs_layout_type(struct xdr_stream *xdr,
uint32_t *layouttype)
{
uint32_t *p;
int num;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
num = be32_to_cpup(p);
/* pNFS is not supported by the underlying file system */
if (num == 0) {
*layouttype = 0;
return 0;
}
if (num > 1)
printk(KERN_INFO "NFS: %s: Warning: Multiple pNFS layout "
"drivers per filesystem not supported\n", __func__);
/* Decode and set first layout type, move xdr->p past unused types */
p = xdr_inline_decode(xdr, num * 4);
if (unlikely(!p))
goto out_overflow;
*layouttype = be32_to_cpup(p);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
/*
* The type of file system exported.
* Note we must ensure that layouttype is set in any non-error case.
*/
static int decode_attr_pnfstype(struct xdr_stream *xdr, uint32_t *bitmap,
uint32_t *layouttype)
{
int status = 0;
dprintk("%s: bitmap is %x\n", __func__, bitmap[1]);
if (unlikely(bitmap[1] & (FATTR4_WORD1_FS_LAYOUT_TYPES - 1U)))
return -EIO;
if (bitmap[1] & FATTR4_WORD1_FS_LAYOUT_TYPES) {
status = decode_first_pnfs_layout_type(xdr, layouttype);
bitmap[1] &= ~FATTR4_WORD1_FS_LAYOUT_TYPES;
} else
*layouttype = 0;
return status;
}
/*
* The prefered block size for layout directed io
*/
static int decode_attr_layout_blksize(struct xdr_stream *xdr, uint32_t *bitmap,
uint32_t *res)
{
__be32 *p;
dprintk("%s: bitmap is %x\n", __func__, bitmap[2]);
*res = 0;
if (bitmap[2] & FATTR4_WORD2_LAYOUT_BLKSIZE) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p)) {
print_overflow_msg(__func__, xdr);
return -EIO;
}
*res = be32_to_cpup(p);
bitmap[2] &= ~FATTR4_WORD2_LAYOUT_BLKSIZE;
}
return 0;
}
static int decode_fsinfo(struct xdr_stream *xdr, struct nfs_fsinfo *fsinfo)
{
__be32 *savep;
uint32_t attrlen, bitmap[3];
int status;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto xdr_error;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto xdr_error;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto xdr_error;
fsinfo->rtmult = fsinfo->wtmult = 512; /* ??? */
if ((status = decode_attr_lease_time(xdr, bitmap, &fsinfo->lease_time)) != 0)
goto xdr_error;
if ((status = decode_attr_maxfilesize(xdr, bitmap, &fsinfo->maxfilesize)) != 0)
goto xdr_error;
if ((status = decode_attr_maxread(xdr, bitmap, &fsinfo->rtmax)) != 0)
goto xdr_error;
fsinfo->rtpref = fsinfo->dtpref = fsinfo->rtmax;
if ((status = decode_attr_maxwrite(xdr, bitmap, &fsinfo->wtmax)) != 0)
goto xdr_error;
fsinfo->wtpref = fsinfo->wtmax;
status = decode_attr_time_delta(xdr, bitmap, &fsinfo->time_delta);
if (status != 0)
goto xdr_error;
status = decode_attr_pnfstype(xdr, bitmap, &fsinfo->layouttype);
if (status != 0)
goto xdr_error;
status = decode_attr_layout_blksize(xdr, bitmap, &fsinfo->blksize);
if (status)
goto xdr_error;
status = verify_attr_len(xdr, savep, attrlen);
xdr_error:
dprintk("%s: xdr returned %d!\n", __func__, -status);
return status;
}
static int decode_getfh(struct xdr_stream *xdr, struct nfs_fh *fh)
{
__be32 *p;
uint32_t len;
int status;
/* Zero handle first to allow comparisons */
memset(fh, 0, sizeof(*fh));
status = decode_op_hdr(xdr, OP_GETFH);
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
if (len > NFS4_FHSIZE)
return -EIO;
fh->size = len;
p = xdr_inline_decode(xdr, len);
if (unlikely(!p))
goto out_overflow;
memcpy(fh->data, p, len);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_link(struct xdr_stream *xdr, struct nfs4_change_info *cinfo)
{
int status;
status = decode_op_hdr(xdr, OP_LINK);
if (status)
return status;
return decode_change_info(xdr, cinfo);
}
/*
* We create the owner, so we know a proper owner.id length is 4.
*/
static int decode_lock_denied (struct xdr_stream *xdr, struct file_lock *fl)
{
uint64_t offset, length, clientid;
__be32 *p;
uint32_t namelen, type;
p = xdr_inline_decode(xdr, 32); /* read 32 bytes */
if (unlikely(!p))
goto out_overflow;
p = xdr_decode_hyper(p, &offset); /* read 2 8-byte long words */
p = xdr_decode_hyper(p, &length);
type = be32_to_cpup(p++); /* 4 byte read */
if (fl != NULL) { /* manipulate file lock */
fl->fl_start = (loff_t)offset;
fl->fl_end = fl->fl_start + (loff_t)length - 1;
if (length == ~(uint64_t)0)
fl->fl_end = OFFSET_MAX;
fl->fl_type = F_WRLCK;
if (type & 1)
fl->fl_type = F_RDLCK;
fl->fl_pid = 0;
}
p = xdr_decode_hyper(p, &clientid); /* read 8 bytes */
namelen = be32_to_cpup(p); /* read 4 bytes */ /* have read all 32 bytes now */
p = xdr_inline_decode(xdr, namelen); /* variable size field */
if (likely(p))
return -NFS4ERR_DENIED;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_lock(struct xdr_stream *xdr, struct nfs_lock_res *res)
{
int status;
status = decode_op_hdr(xdr, OP_LOCK);
if (status == -EIO)
goto out;
if (status == 0) {
status = decode_stateid(xdr, &res->stateid);
if (unlikely(status))
goto out;
} else if (status == -NFS4ERR_DENIED)
status = decode_lock_denied(xdr, NULL);
if (res->open_seqid != NULL)
nfs_increment_open_seqid(status, res->open_seqid);
nfs_increment_lock_seqid(status, res->lock_seqid);
out:
return status;
}
static int decode_lockt(struct xdr_stream *xdr, struct nfs_lockt_res *res)
{
int status;
status = decode_op_hdr(xdr, OP_LOCKT);
if (status == -NFS4ERR_DENIED)
return decode_lock_denied(xdr, res->denied);
return status;
}
static int decode_locku(struct xdr_stream *xdr, struct nfs_locku_res *res)
{
int status;
status = decode_op_hdr(xdr, OP_LOCKU);
if (status != -EIO)
nfs_increment_lock_seqid(status, res->seqid);
if (status == 0)
status = decode_stateid(xdr, &res->stateid);
return status;
}
static int decode_release_lockowner(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_RELEASE_LOCKOWNER);
}
static int decode_lookup(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_LOOKUP);
}
/* This is too sick! */
static int decode_space_limit(struct xdr_stream *xdr, u64 *maxsize)
{
__be32 *p;
uint32_t limit_type, nblocks, blocksize;
p = xdr_inline_decode(xdr, 12);
if (unlikely(!p))
goto out_overflow;
limit_type = be32_to_cpup(p++);
switch (limit_type) {
case 1:
xdr_decode_hyper(p, maxsize);
break;
case 2:
nblocks = be32_to_cpup(p++);
blocksize = be32_to_cpup(p);
*maxsize = (uint64_t)nblocks * (uint64_t)blocksize;
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_delegation(struct xdr_stream *xdr, struct nfs_openres *res)
{
__be32 *p;
uint32_t delegation_type;
int status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
delegation_type = be32_to_cpup(p);
if (delegation_type == NFS4_OPEN_DELEGATE_NONE) {
res->delegation_type = 0;
return 0;
}
status = decode_stateid(xdr, &res->delegation);
if (unlikely(status))
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->do_recall = be32_to_cpup(p);
switch (delegation_type) {
case NFS4_OPEN_DELEGATE_READ:
res->delegation_type = FMODE_READ;
break;
case NFS4_OPEN_DELEGATE_WRITE:
res->delegation_type = FMODE_WRITE|FMODE_READ;
if (decode_space_limit(xdr, &res->maxsize) < 0)
return -EIO;
}
return decode_ace(xdr, NULL, res->server->nfs_client);
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_open(struct xdr_stream *xdr, struct nfs_openres *res)
{
__be32 *p;
uint32_t savewords, bmlen, i;
int status;
status = decode_op_hdr(xdr, OP_OPEN);
if (status != -EIO)
nfs_increment_open_seqid(status, res->seqid);
if (!status)
status = decode_stateid(xdr, &res->stateid);
if (unlikely(status))
return status;
decode_change_info(xdr, &res->cinfo);
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
res->rflags = be32_to_cpup(p++);
bmlen = be32_to_cpup(p);
if (bmlen > 10)
goto xdr_error;
p = xdr_inline_decode(xdr, bmlen << 2);
if (unlikely(!p))
goto out_overflow;
savewords = min_t(uint32_t, bmlen, NFS4_BITMAP_SIZE);
for (i = 0; i < savewords; ++i)
res->attrset[i] = be32_to_cpup(p++);
for (; i < NFS4_BITMAP_SIZE; i++)
res->attrset[i] = 0;
return decode_delegation(xdr, res);
xdr_error:
dprintk("%s: Bitmap too large! Length = %u\n", __func__, bmlen);
return -EIO;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_open_confirm(struct xdr_stream *xdr, struct nfs_open_confirmres *res)
{
int status;
status = decode_op_hdr(xdr, OP_OPEN_CONFIRM);
if (status != -EIO)
nfs_increment_open_seqid(status, res->seqid);
if (!status)
status = decode_stateid(xdr, &res->stateid);
return status;
}
static int decode_open_downgrade(struct xdr_stream *xdr, struct nfs_closeres *res)
{
int status;
status = decode_op_hdr(xdr, OP_OPEN_DOWNGRADE);
if (status != -EIO)
nfs_increment_open_seqid(status, res->seqid);
if (!status)
status = decode_stateid(xdr, &res->stateid);
return status;
}
static int decode_putfh(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_PUTFH);
}
static int decode_putrootfh(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_PUTROOTFH);
}
static int decode_read(struct xdr_stream *xdr, struct rpc_rqst *req, struct nfs_readres *res)
{
struct kvec *iov = req->rq_rcv_buf.head;
__be32 *p;
uint32_t count, eof, recvd, hdrlen;
int status;
status = decode_op_hdr(xdr, OP_READ);
if (status)
return status;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
eof = be32_to_cpup(p++);
count = be32_to_cpup(p);
hdrlen = (u8 *) xdr->p - (u8 *) iov->iov_base;
recvd = req->rq_rcv_buf.len - hdrlen;
if (count > recvd) {
dprintk("NFS: server cheating in read reply: "
"count %u > recvd %u\n", count, recvd);
count = recvd;
eof = 0;
}
xdr_read_pages(xdr, count);
res->eof = eof;
res->count = count;
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_readdir(struct xdr_stream *xdr, struct rpc_rqst *req, struct nfs4_readdir_res *readdir)
{
struct xdr_buf *rcvbuf = &req->rq_rcv_buf;
struct kvec *iov = rcvbuf->head;
size_t hdrlen;
u32 recvd, pglen = rcvbuf->page_len;
int status;
__be32 verf[2];
status = decode_op_hdr(xdr, OP_READDIR);
if (!status)
status = decode_verifier(xdr, readdir->verifier.data);
if (unlikely(status))
return status;
memcpy(verf, readdir->verifier.data, sizeof(verf));
dprintk("%s: verifier = %08x:%08x\n",
__func__, verf[0], verf[1]);
hdrlen = (char *) xdr->p - (char *) iov->iov_base;
recvd = rcvbuf->len - hdrlen;
if (pglen > recvd)
pglen = recvd;
xdr_read_pages(xdr, pglen);
return pglen;
}
static int decode_readlink(struct xdr_stream *xdr, struct rpc_rqst *req)
{
struct xdr_buf *rcvbuf = &req->rq_rcv_buf;
struct kvec *iov = rcvbuf->head;
size_t hdrlen;
u32 len, recvd;
__be32 *p;
int status;
status = decode_op_hdr(xdr, OP_READLINK);
if (status)
return status;
/* Convert length of symlink */
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
if (len >= rcvbuf->page_len || len <= 0) {
dprintk("nfs: server returned giant symlink!\n");
return -ENAMETOOLONG;
}
hdrlen = (char *) xdr->p - (char *) iov->iov_base;
recvd = req->rq_rcv_buf.len - hdrlen;
if (recvd < len) {
dprintk("NFS: server cheating in readlink reply: "
"count %u > recvd %u\n", len, recvd);
return -EIO;
}
xdr_read_pages(xdr, len);
/*
* The XDR encode routine has set things up so that
* the link text will be copied directly into the
* buffer. We just have to do overflow-checking,
* and and null-terminate the text (the VFS expects
* null-termination).
*/
xdr_terminate_string(rcvbuf, len);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_remove(struct xdr_stream *xdr, struct nfs4_change_info *cinfo)
{
int status;
status = decode_op_hdr(xdr, OP_REMOVE);
if (status)
goto out;
status = decode_change_info(xdr, cinfo);
out:
return status;
}
static int decode_rename(struct xdr_stream *xdr, struct nfs4_change_info *old_cinfo,
struct nfs4_change_info *new_cinfo)
{
int status;
status = decode_op_hdr(xdr, OP_RENAME);
if (status)
goto out;
if ((status = decode_change_info(xdr, old_cinfo)))
goto out;
status = decode_change_info(xdr, new_cinfo);
out:
return status;
}
static int decode_renew(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_RENEW);
}
static int
decode_restorefh(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_RESTOREFH);
}
static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req,
struct nfs_getaclres *res)
{
__be32 *savep, *bm_p;
uint32_t attrlen,
bitmap[3] = {0};
struct kvec *iov = req->rq_rcv_buf.head;
int status;
size_t page_len = xdr->buf->page_len;
res->acl_len = 0;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto out;
bm_p = xdr->p;
res->acl_data_offset = be32_to_cpup(bm_p) + 2;
res->acl_data_offset <<= 2;
/* Check if the acl data starts beyond the allocated buffer */
if (res->acl_data_offset > page_len)
return -ERANGE;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto out;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto out;
if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_ACL)) {
size_t hdrlen;
/* The bitmap (xdr len + bitmaps) and the attr xdr len words
* are stored with the acl data to handle the problem of
* variable length bitmaps.*/
xdr->p = bm_p;
/* We ignore &savep and don't do consistency checks on
* the attr length. Let userspace figure it out.... */
hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base;
attrlen += res->acl_data_offset;
if (attrlen > page_len) {
if (res->acl_flags & NFS4_ACL_LEN_REQUEST) {
/* getxattr interface called with a NULL buf */
res->acl_len = attrlen;
goto out;
}
dprintk("NFS: acl reply: attrlen %u > page_len %zu\n",
attrlen, page_len);
return -EINVAL;
}
xdr_read_pages(xdr, attrlen);
res->acl_len = attrlen;
} else
status = -EOPNOTSUPP;
out:
return status;
}
static int
decode_savefh(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_SAVEFH);
}
static int decode_setattr(struct xdr_stream *xdr)
{
__be32 *p;
uint32_t bmlen;
int status;
status = decode_op_hdr(xdr, OP_SETATTR);
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
bmlen = be32_to_cpup(p);
p = xdr_inline_decode(xdr, bmlen << 2);
if (likely(p))
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_setclientid(struct xdr_stream *xdr, struct nfs4_setclientid_res *res)
{
__be32 *p;
uint32_t opnum;
int32_t nfserr;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
opnum = be32_to_cpup(p++);
if (opnum != OP_SETCLIENTID) {
dprintk("nfs: decode_setclientid: Server returned operation"
" %d\n", opnum);
return -EIO;
}
nfserr = be32_to_cpup(p);
if (nfserr == NFS_OK) {
p = xdr_inline_decode(xdr, 8 + NFS4_VERIFIER_SIZE);
if (unlikely(!p))
goto out_overflow;
p = xdr_decode_hyper(p, &res->clientid);
memcpy(res->confirm.data, p, NFS4_VERIFIER_SIZE);
} else if (nfserr == NFSERR_CLID_INUSE) {
uint32_t len;
/* skip netid string */
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
p = xdr_inline_decode(xdr, len);
if (unlikely(!p))
goto out_overflow;
/* skip uaddr string */
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
p = xdr_inline_decode(xdr, len);
if (unlikely(!p))
goto out_overflow;
return -NFSERR_CLID_INUSE;
} else
return nfs4_stat_to_errno(nfserr);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_setclientid_confirm(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_SETCLIENTID_CONFIRM);
}
static int decode_write(struct xdr_stream *xdr, struct nfs_writeres *res)
{
__be32 *p;
int status;
status = decode_op_hdr(xdr, OP_WRITE);
if (status)
return status;
p = xdr_inline_decode(xdr, 16);
if (unlikely(!p))
goto out_overflow;
res->count = be32_to_cpup(p++);
res->verf->committed = be32_to_cpup(p++);
memcpy(res->verf->verifier, p, NFS4_VERIFIER_SIZE);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_delegreturn(struct xdr_stream *xdr)
{
return decode_op_hdr(xdr, OP_DELEGRETURN);
}
static int decode_secinfo_gss(struct xdr_stream *xdr, struct nfs4_secinfo_flavor *flavor)
{
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
flavor->gss.sec_oid4.len = be32_to_cpup(p);
if (flavor->gss.sec_oid4.len > GSS_OID_MAX_LEN)
goto out_err;
p = xdr_inline_decode(xdr, flavor->gss.sec_oid4.len);
if (unlikely(!p))
goto out_overflow;
memcpy(flavor->gss.sec_oid4.data, p, flavor->gss.sec_oid4.len);
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
flavor->gss.qop4 = be32_to_cpup(p++);
flavor->gss.service = be32_to_cpup(p);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
out_err:
return -EINVAL;
}
static int decode_secinfo_common(struct xdr_stream *xdr, struct nfs4_secinfo_res *res)
{
struct nfs4_secinfo_flavor *sec_flavor;
int status;
__be32 *p;
int i, num_flavors;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->flavors->num_flavors = 0;
num_flavors = be32_to_cpup(p);
for (i = 0; i < num_flavors; i++) {
sec_flavor = &res->flavors->flavors[i];
if ((char *)&sec_flavor[1] - (char *)res->flavors > PAGE_SIZE)
break;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
sec_flavor->flavor = be32_to_cpup(p);
if (sec_flavor->flavor == RPC_AUTH_GSS) {
status = decode_secinfo_gss(xdr, sec_flavor);
if (status)
goto out;
}
res->flavors->num_flavors++;
}
status = 0;
out:
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_secinfo(struct xdr_stream *xdr, struct nfs4_secinfo_res *res)
{
int status = decode_op_hdr(xdr, OP_SECINFO);
if (status)
return status;
return decode_secinfo_common(xdr, res);
}
#if defined(CONFIG_NFS_V4_1)
static int decode_secinfo_no_name(struct xdr_stream *xdr, struct nfs4_secinfo_res *res)
{
int status = decode_op_hdr(xdr, OP_SECINFO_NO_NAME);
if (status)
return status;
return decode_secinfo_common(xdr, res);
}
static int decode_exchange_id(struct xdr_stream *xdr,
struct nfs41_exchange_id_res *res)
{
__be32 *p;
uint32_t dummy;
char *dummy_str;
int status;
struct nfs_client *clp = res->client;
uint32_t impl_id_count;
status = decode_op_hdr(xdr, OP_EXCHANGE_ID);
if (status)
return status;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
xdr_decode_hyper(p, &clp->cl_clientid);
p = xdr_inline_decode(xdr, 12);
if (unlikely(!p))
goto out_overflow;
clp->cl_seqid = be32_to_cpup(p++);
clp->cl_exchange_flags = be32_to_cpup(p++);
/* We ask for SP4_NONE */
dummy = be32_to_cpup(p);
if (dummy != SP4_NONE)
return -EIO;
/* Throw away minor_id */
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
/* Throw away Major id */
status = decode_opaque_inline(xdr, &dummy, &dummy_str);
if (unlikely(status))
return status;
/* Save server_scope */
status = decode_opaque_inline(xdr, &dummy, &dummy_str);
if (unlikely(status))
return status;
if (unlikely(dummy > NFS4_OPAQUE_LIMIT))
return -EIO;
memcpy(res->server_scope->server_scope, dummy_str, dummy);
res->server_scope->server_scope_sz = dummy;
/* Implementation Id */
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
impl_id_count = be32_to_cpup(p++);
if (impl_id_count) {
/* nii_domain */
status = decode_opaque_inline(xdr, &dummy, &dummy_str);
if (unlikely(status))
return status;
if (unlikely(dummy > NFS4_OPAQUE_LIMIT))
return -EIO;
memcpy(res->impl_id->domain, dummy_str, dummy);
/* nii_name */
status = decode_opaque_inline(xdr, &dummy, &dummy_str);
if (unlikely(status))
return status;
if (unlikely(dummy > NFS4_OPAQUE_LIMIT))
return -EIO;
memcpy(res->impl_id->name, dummy_str, dummy);
/* nii_date */
p = xdr_inline_decode(xdr, 12);
if (unlikely(!p))
goto out_overflow;
p = xdr_decode_hyper(p, &res->impl_id->date.seconds);
res->impl_id->date.nseconds = be32_to_cpup(p);
/* if there's more than one entry, ignore the rest */
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_chan_attrs(struct xdr_stream *xdr,
struct nfs4_channel_attrs *attrs)
{
__be32 *p;
u32 nr_attrs, val;
p = xdr_inline_decode(xdr, 28);
if (unlikely(!p))
goto out_overflow;
val = be32_to_cpup(p++); /* headerpadsz */
if (val)
return -EINVAL; /* no support for header padding yet */
attrs->max_rqst_sz = be32_to_cpup(p++);
attrs->max_resp_sz = be32_to_cpup(p++);
attrs->max_resp_sz_cached = be32_to_cpup(p++);
attrs->max_ops = be32_to_cpup(p++);
attrs->max_reqs = be32_to_cpup(p++);
nr_attrs = be32_to_cpup(p);
if (unlikely(nr_attrs > 1)) {
printk(KERN_WARNING "NFS: %s: Invalid rdma channel attrs "
"count %u\n", __func__, nr_attrs);
return -EINVAL;
}
if (nr_attrs == 1) {
p = xdr_inline_decode(xdr, 4); /* skip rdma_attrs */
if (unlikely(!p))
goto out_overflow;
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_sessionid(struct xdr_stream *xdr, struct nfs4_sessionid *sid)
{
return decode_opaque_fixed(xdr, sid->data, NFS4_MAX_SESSIONID_LEN);
}
static int decode_create_session(struct xdr_stream *xdr,
struct nfs41_create_session_res *res)
{
__be32 *p;
int status;
struct nfs_client *clp = res->client;
struct nfs4_session *session = clp->cl_session;
status = decode_op_hdr(xdr, OP_CREATE_SESSION);
if (!status)
status = decode_sessionid(xdr, &session->sess_id);
if (unlikely(status))
return status;
/* seqid, flags */
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
clp->cl_seqid = be32_to_cpup(p++);
session->flags = be32_to_cpup(p);
/* Channel attributes */
status = decode_chan_attrs(xdr, &session->fc_attrs);
if (!status)
status = decode_chan_attrs(xdr, &session->bc_attrs);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_destroy_session(struct xdr_stream *xdr, void *dummy)
{
return decode_op_hdr(xdr, OP_DESTROY_SESSION);
}
static int decode_reclaim_complete(struct xdr_stream *xdr, void *dummy)
{
return decode_op_hdr(xdr, OP_RECLAIM_COMPLETE);
}
#endif /* CONFIG_NFS_V4_1 */
static int decode_sequence(struct xdr_stream *xdr,
struct nfs4_sequence_res *res,
struct rpc_rqst *rqstp)
{
#if defined(CONFIG_NFS_V4_1)
struct nfs4_sessionid id;
u32 dummy;
int status;
__be32 *p;
if (!res->sr_session)
return 0;
status = decode_op_hdr(xdr, OP_SEQUENCE);
if (!status)
status = decode_sessionid(xdr, &id);
if (unlikely(status))
goto out_err;
/*
* If the server returns different values for sessionID, slotID or
* sequence number, the server is looney tunes.
*/
status = -EREMOTEIO;
if (memcmp(id.data, res->sr_session->sess_id.data,
NFS4_MAX_SESSIONID_LEN)) {
dprintk("%s Invalid session id\n", __func__);
goto out_err;
}
p = xdr_inline_decode(xdr, 20);
if (unlikely(!p))
goto out_overflow;
/* seqid */
dummy = be32_to_cpup(p++);
if (dummy != res->sr_slot->seq_nr) {
dprintk("%s Invalid sequence number\n", __func__);
goto out_err;
}
/* slot id */
dummy = be32_to_cpup(p++);
if (dummy != res->sr_slot - res->sr_session->fc_slot_table.slots) {
dprintk("%s Invalid slot id\n", __func__);
goto out_err;
}
/* highest slot id - currently not processed */
dummy = be32_to_cpup(p++);
/* target highest slot id - currently not processed */
dummy = be32_to_cpup(p++);
/* result flags */
res->sr_status_flags = be32_to_cpup(p);
status = 0;
out_err:
res->sr_status = status;
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
status = -EIO;
goto out_err;
#else /* CONFIG_NFS_V4_1 */
return 0;
#endif /* CONFIG_NFS_V4_1 */
}
#if defined(CONFIG_NFS_V4_1)
/*
* TODO: Need to handle case when EOF != true;
*/
static int decode_getdevicelist(struct xdr_stream *xdr,
struct pnfs_devicelist *res)
{
__be32 *p;
int status, i;
struct nfs_writeverf verftemp;
status = decode_op_hdr(xdr, OP_GETDEVICELIST);
if (status)
return status;
p = xdr_inline_decode(xdr, 8 + 8 + 4);
if (unlikely(!p))
goto out_overflow;
/* TODO: Skip cookie for now */
p += 2;
/* Read verifier */
p = xdr_decode_opaque_fixed(p, verftemp.verifier, NFS4_VERIFIER_SIZE);
res->num_devs = be32_to_cpup(p);
dprintk("%s: num_dev %d\n", __func__, res->num_devs);
if (res->num_devs > NFS4_PNFS_GETDEVLIST_MAXNUM) {
printk(KERN_ERR "NFS: %s too many result dev_num %u\n",
__func__, res->num_devs);
return -EIO;
}
p = xdr_inline_decode(xdr,
res->num_devs * NFS4_DEVICEID4_SIZE + 4);
if (unlikely(!p))
goto out_overflow;
for (i = 0; i < res->num_devs; i++)
p = xdr_decode_opaque_fixed(p, res->dev_id[i].data,
NFS4_DEVICEID4_SIZE);
res->eof = be32_to_cpup(p);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_getdeviceinfo(struct xdr_stream *xdr,
struct pnfs_device *pdev)
{
__be32 *p;
uint32_t len, type;
int status;
status = decode_op_hdr(xdr, OP_GETDEVICEINFO);
if (status) {
if (status == -ETOOSMALL) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
pdev->mincount = be32_to_cpup(p);
dprintk("%s: Min count too small. mincnt = %u\n",
__func__, pdev->mincount);
}
return status;
}
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
type = be32_to_cpup(p++);
if (type != pdev->layout_type) {
dprintk("%s: layout mismatch req: %u pdev: %u\n",
__func__, pdev->layout_type, type);
return -EINVAL;
}
/*
* Get the length of the opaque device_addr4. xdr_read_pages places
* the opaque device_addr4 in the xdr_buf->pages (pnfs_device->pages)
* and places the remaining xdr data in xdr_buf->tail
*/
pdev->mincount = be32_to_cpup(p);
xdr_read_pages(xdr, pdev->mincount); /* include space for the length */
/* Parse notification bitmap, verifying that it is zero. */
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
len = be32_to_cpup(p);
if (len) {
uint32_t i;
p = xdr_inline_decode(xdr, 4 * len);
if (unlikely(!p))
goto out_overflow;
for (i = 0; i < len; i++, p++) {
if (be32_to_cpup(p)) {
dprintk("%s: notifications not supported\n",
__func__);
return -EIO;
}
}
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_layoutget(struct xdr_stream *xdr, struct rpc_rqst *req,
struct nfs4_layoutget_res *res)
{
__be32 *p;
int status;
u32 layout_count;
struct xdr_buf *rcvbuf = &req->rq_rcv_buf;
struct kvec *iov = rcvbuf->head;
u32 hdrlen, recvd;
status = decode_op_hdr(xdr, OP_LAYOUTGET);
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->return_on_close = be32_to_cpup(p);
decode_stateid(xdr, &res->stateid);
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
layout_count = be32_to_cpup(p);
if (!layout_count) {
dprintk("%s: server responded with empty layout array\n",
__func__);
return -EINVAL;
}
p = xdr_inline_decode(xdr, 28);
if (unlikely(!p))
goto out_overflow;
p = xdr_decode_hyper(p, &res->range.offset);
p = xdr_decode_hyper(p, &res->range.length);
res->range.iomode = be32_to_cpup(p++);
res->type = be32_to_cpup(p++);
res->layoutp->len = be32_to_cpup(p);
dprintk("%s roff:%lu rlen:%lu riomode:%d, lo_type:0x%x, lo.len:%d\n",
__func__,
(unsigned long)res->range.offset,
(unsigned long)res->range.length,
res->range.iomode,
res->type,
res->layoutp->len);
hdrlen = (u8 *) xdr->p - (u8 *) iov->iov_base;
recvd = req->rq_rcv_buf.len - hdrlen;
if (res->layoutp->len > recvd) {
dprintk("NFS: server cheating in layoutget reply: "
"layout len %u > recvd %u\n",
res->layoutp->len, recvd);
return -EINVAL;
}
xdr_read_pages(xdr, res->layoutp->len);
if (layout_count > 1) {
/* We only handle a length one array at the moment. Any
* further entries are just ignored. Note that this means
* the client may see a response that is less than the
* minimum it requested.
*/
dprintk("%s: server responded with %d layouts, dropping tail\n",
__func__, layout_count);
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_layoutreturn(struct xdr_stream *xdr,
struct nfs4_layoutreturn_res *res)
{
__be32 *p;
int status;
status = decode_op_hdr(xdr, OP_LAYOUTRETURN);
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->lrs_present = be32_to_cpup(p);
if (res->lrs_present)
status = decode_stateid(xdr, &res->stateid);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_layoutcommit(struct xdr_stream *xdr,
struct rpc_rqst *req,
struct nfs4_layoutcommit_res *res)
{
__be32 *p;
__u32 sizechanged;
int status;
status = decode_op_hdr(xdr, OP_LAYOUTCOMMIT);
res->status = status;
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
sizechanged = be32_to_cpup(p);
if (sizechanged) {
/* throw away new size */
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
}
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
static int decode_test_stateid(struct xdr_stream *xdr,
struct nfs41_test_stateid_res *res)
{
__be32 *p;
int status;
int num_res;
status = decode_op_hdr(xdr, OP_TEST_STATEID);
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
num_res = be32_to_cpup(p++);
if (num_res != 1)
goto out;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->status = be32_to_cpup(p++);
return status;
out_overflow:
print_overflow_msg(__func__, xdr);
out:
return -EIO;
}
static int decode_free_stateid(struct xdr_stream *xdr,
struct nfs41_free_stateid_res *res)
{
__be32 *p;
int status;
status = decode_op_hdr(xdr, OP_FREE_STATEID);
if (status)
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->status = be32_to_cpup(p++);
return res->status;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
#endif /* CONFIG_NFS_V4_1 */
/*
* END OF "GENERIC" DECODE ROUTINES.
*/
/*
* Decode OPEN_DOWNGRADE response
*/
static int nfs4_xdr_dec_open_downgrade(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs_closeres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_open_downgrade(xdr, res);
if (status != 0)
goto out;
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode ACCESS response
*/
static int nfs4_xdr_dec_access(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_accessres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status != 0)
goto out;
status = decode_access(xdr, res);
if (status != 0)
goto out;
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode LOOKUP response
*/
static int nfs4_xdr_dec_lookup(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_lookup_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_lookup(xdr);
if (status)
goto out;
status = decode_getfh(xdr, res->fh);
if (status)
goto out;
status = decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode LOOKUP_ROOT response
*/
static int nfs4_xdr_dec_lookup_root(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_lookup_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putrootfh(xdr);
if (status)
goto out;
status = decode_getfh(xdr, res->fh);
if (status == 0)
status = decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode REMOVE response
*/
static int nfs4_xdr_dec_remove(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_removeres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_remove(xdr, &res->cinfo);
if (status)
goto out;
decode_getfattr(xdr, res->dir_attr, res->server);
out:
return status;
}
/*
* Decode RENAME response
*/
static int nfs4_xdr_dec_rename(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_renameres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_savefh(xdr);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_rename(xdr, &res->old_cinfo, &res->new_cinfo);
if (status)
goto out;
/* Current FH is target directory */
if (decode_getfattr(xdr, res->new_fattr, res->server))
goto out;
status = decode_restorefh(xdr);
if (status)
goto out;
decode_getfattr(xdr, res->old_fattr, res->server);
out:
return status;
}
/*
* Decode LINK response
*/
static int nfs4_xdr_dec_link(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_link_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_savefh(xdr);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_link(xdr, &res->cinfo);
if (status)
goto out;
/*
* Note order: OP_LINK leaves the directory as the current
* filehandle.
*/
if (decode_getfattr(xdr, res->dir_attr, res->server))
goto out;
status = decode_restorefh(xdr);
if (status)
goto out;
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode CREATE response
*/
static int nfs4_xdr_dec_create(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_create_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_savefh(xdr);
if (status)
goto out;
status = decode_create(xdr, &res->dir_cinfo);
if (status)
goto out;
status = decode_getfh(xdr, res->fh);
if (status)
goto out;
if (decode_getfattr(xdr, res->fattr, res->server))
goto out;
status = decode_restorefh(xdr);
if (status)
goto out;
decode_getfattr(xdr, res->dir_fattr, res->server);
out:
return status;
}
/*
* Decode SYMLINK response
*/
static int nfs4_xdr_dec_symlink(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_create_res *res)
{
return nfs4_xdr_dec_create(rqstp, xdr, res);
}
/*
* Decode GETATTR response
*/
static int nfs4_xdr_dec_getattr(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_getattr_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Encode an SETACL request
*/
static void nfs4_xdr_enc_setacl(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs_setaclargs *args)
{
struct compound_hdr hdr = {
.minorversion = nfs4_xdr_minorversion(&args->seq_args),
};
encode_compound_hdr(xdr, req, &hdr);
encode_sequence(xdr, &args->seq_args, &hdr);
encode_putfh(xdr, args->fh, &hdr);
encode_setacl(xdr, args, &hdr);
encode_nops(&hdr);
}
/*
* Decode SETACL response
*/
static int
nfs4_xdr_dec_setacl(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_setaclres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_setattr(xdr);
out:
return status;
}
/*
* Decode GETACL response
*/
static int
nfs4_xdr_dec_getacl(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_getaclres *res)
{
struct compound_hdr hdr;
int status;
if (res->acl_scratch != NULL) {
void *p = page_address(res->acl_scratch);
xdr_set_scratch_buffer(xdr, p, PAGE_SIZE);
}
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_getacl(xdr, rqstp, res);
out:
return status;
}
/*
* Decode CLOSE response
*/
static int nfs4_xdr_dec_close(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_closeres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_close(xdr, res);
if (status != 0)
goto out;
/*
* Note: Server may do delete on close for this file
* in which case the getattr call will fail with
* an ESTALE error. Shouldn't be a problem,
* though, since fattr->valid will remain unset.
*/
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode OPEN response
*/
static int nfs4_xdr_dec_open(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_openres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_savefh(xdr);
if (status)
goto out;
status = decode_open(xdr, res);
if (status)
goto out;
status = decode_getfh(xdr, &res->fh);
if (status)
goto out;
if (decode_getfattr(xdr, res->f_attr, res->server) != 0)
goto out;
if (decode_restorefh(xdr) != 0)
goto out;
decode_getfattr(xdr, res->dir_attr, res->server);
out:
return status;
}
/*
* Decode OPEN_CONFIRM response
*/
static int nfs4_xdr_dec_open_confirm(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs_open_confirmres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_open_confirm(xdr, res);
out:
return status;
}
/*
* Decode OPEN response
*/
static int nfs4_xdr_dec_open_noattr(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs_openres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_open(xdr, res);
if (status)
goto out;
decode_getfattr(xdr, res->f_attr, res->server);
out:
return status;
}
/*
* Decode SETATTR response
*/
static int nfs4_xdr_dec_setattr(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs_setattrres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_setattr(xdr);
if (status)
goto out;
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode LOCK response
*/
static int nfs4_xdr_dec_lock(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_lock_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_lock(xdr, res);
out:
return status;
}
/*
* Decode LOCKT response
*/
static int nfs4_xdr_dec_lockt(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_lockt_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_lockt(xdr, res);
out:
return status;
}
/*
* Decode LOCKU response
*/
static int nfs4_xdr_dec_locku(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_locku_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_locku(xdr, res);
out:
return status;
}
static int nfs4_xdr_dec_release_lockowner(struct rpc_rqst *rqstp,
struct xdr_stream *xdr, void *dummy)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_release_lockowner(xdr);
return status;
}
/*
* Decode READLINK response
*/
static int nfs4_xdr_dec_readlink(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_readlink_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_readlink(xdr, rqstp);
out:
return status;
}
/*
* Decode READDIR response
*/
static int nfs4_xdr_dec_readdir(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_readdir_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_readdir(xdr, rqstp, res);
out:
return status;
}
/*
* Decode Read response
*/
static int nfs4_xdr_dec_read(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_readres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_read(xdr, rqstp, res);
if (!status)
status = res->count;
out:
return status;
}
/*
* Decode WRITE response
*/
static int nfs4_xdr_dec_write(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_writeres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_write(xdr, res);
if (status)
goto out;
if (res->fattr)
decode_getfattr(xdr, res->fattr, res->server);
if (!status)
status = res->count;
out:
return status;
}
/*
* Decode COMMIT response
*/
static int nfs4_xdr_dec_commit(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_writeres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_commit(xdr, res);
if (status)
goto out;
if (res->fattr)
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode FSINFO response
*/
static int nfs4_xdr_dec_fsinfo(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs4_fsinfo_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_sequence(xdr, &res->seq_res, req);
if (!status)
status = decode_putfh(xdr);
if (!status)
status = decode_fsinfo(xdr, res->fsinfo);
return status;
}
/*
* Decode PATHCONF response
*/
static int nfs4_xdr_dec_pathconf(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs4_pathconf_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_sequence(xdr, &res->seq_res, req);
if (!status)
status = decode_putfh(xdr);
if (!status)
status = decode_pathconf(xdr, res->pathconf);
return status;
}
/*
* Decode STATFS response
*/
static int nfs4_xdr_dec_statfs(struct rpc_rqst *req, struct xdr_stream *xdr,
struct nfs4_statfs_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_sequence(xdr, &res->seq_res, req);
if (!status)
status = decode_putfh(xdr);
if (!status)
status = decode_statfs(xdr, res->fsstat);
return status;
}
/*
* Decode GETATTR_BITMAP response
*/
static int nfs4_xdr_dec_server_caps(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_server_caps_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, req);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_server_caps(xdr, res);
out:
return status;
}
/*
* Decode RENEW response
*/
static int nfs4_xdr_dec_renew(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
void *__unused)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_renew(xdr);
return status;
}
/*
* Decode SETCLIENTID response
*/
static int nfs4_xdr_dec_setclientid(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_setclientid_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_setclientid(xdr, res);
return status;
}
/*
* Decode SETCLIENTID_CONFIRM response
*/
static int nfs4_xdr_dec_setclientid_confirm(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs_fsinfo *fsinfo)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_setclientid_confirm(xdr);
if (!status)
status = decode_putrootfh(xdr);
if (!status)
status = decode_fsinfo(xdr, fsinfo);
return status;
}
/*
* Decode DELEGRETURN response
*/
static int nfs4_xdr_dec_delegreturn(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_delegreturnres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status != 0)
goto out;
status = decode_delegreturn(xdr);
if (status != 0)
goto out;
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode FS_LOCATIONS response
*/
static int nfs4_xdr_dec_fs_locations(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nfs4_fs_locations_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, req);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_lookup(xdr);
if (status)
goto out;
xdr_enter_page(xdr, PAGE_SIZE);
status = decode_getfattr_generic(xdr, &res->fs_locations->fattr,
NULL, res->fs_locations,
res->fs_locations->server);
out:
return status;
}
/*
* Decode SECINFO response
*/
static int nfs4_xdr_dec_secinfo(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_secinfo_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_secinfo(xdr, res);
out:
return status;
}
#if defined(CONFIG_NFS_V4_1)
/*
* Decode EXCHANGE_ID response
*/
static int nfs4_xdr_dec_exchange_id(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
void *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_exchange_id(xdr, res);
return status;
}
/*
* Decode CREATE_SESSION response
*/
static int nfs4_xdr_dec_create_session(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs41_create_session_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_create_session(xdr, res);
return status;
}
/*
* Decode DESTROY_SESSION response
*/
static int nfs4_xdr_dec_destroy_session(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
void *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_destroy_session(xdr, res);
return status;
}
/*
* Decode SEQUENCE response
*/
static int nfs4_xdr_dec_sequence(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_sequence_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_sequence(xdr, res, rqstp);
return status;
}
/*
* Decode GET_LEASE_TIME response
*/
static int nfs4_xdr_dec_get_lease_time(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_get_lease_time_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_sequence(xdr, &res->lr_seq_res, rqstp);
if (!status)
status = decode_putrootfh(xdr);
if (!status)
status = decode_fsinfo(xdr, res->lr_fsinfo);
return status;
}
/*
* Decode RECLAIM_COMPLETE response
*/
static int nfs4_xdr_dec_reclaim_complete(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs41_reclaim_complete_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (!status)
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (!status)
status = decode_reclaim_complete(xdr, (void *)NULL);
return status;
}
/*
* Decode GETDEVICELIST response
*/
static int nfs4_xdr_dec_getdevicelist(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_getdevicelist_res *res)
{
struct compound_hdr hdr;
int status;
dprintk("encoding getdevicelist!\n");
status = decode_compound_hdr(xdr, &hdr);
if (status != 0)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status != 0)
goto out;
status = decode_putfh(xdr);
if (status != 0)
goto out;
status = decode_getdevicelist(xdr, res->devlist);
out:
return status;
}
/*
* Decode GETDEVINFO response
*/
static int nfs4_xdr_dec_getdeviceinfo(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_getdeviceinfo_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status != 0)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status != 0)
goto out;
status = decode_getdeviceinfo(xdr, res->pdev);
out:
return status;
}
/*
* Decode LAYOUTGET response
*/
static int nfs4_xdr_dec_layoutget(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_layoutget_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_layoutget(xdr, rqstp, res);
out:
return status;
}
/*
* Decode LAYOUTRETURN response
*/
static int nfs4_xdr_dec_layoutreturn(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_layoutreturn_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_layoutreturn(xdr, res);
out:
return status;
}
/*
* Decode LAYOUTCOMMIT response
*/
static int nfs4_xdr_dec_layoutcommit(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_layoutcommit_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_layoutcommit(xdr, rqstp, res);
if (status)
goto out;
decode_getfattr(xdr, res->fattr, res->server);
out:
return status;
}
/*
* Decode SECINFO_NO_NAME response
*/
static int nfs4_xdr_dec_secinfo_no_name(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs4_secinfo_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putrootfh(xdr);
if (status)
goto out;
status = decode_secinfo_no_name(xdr, res);
out:
return status;
}
/*
* Decode TEST_STATEID response
*/
static int nfs4_xdr_dec_test_stateid(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs41_test_stateid_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_test_stateid(xdr, res);
out:
return status;
}
/*
* Decode FREE_STATEID response
*/
static int nfs4_xdr_dec_free_stateid(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs41_free_stateid_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_free_stateid(xdr, res);
out:
return status;
}
#endif /* CONFIG_NFS_V4_1 */
/**
* nfs4_decode_dirent - Decode a single NFSv4 directory entry stored in
* the local page cache.
* @xdr: XDR stream where entry resides
* @entry: buffer to fill in with entry data
* @plus: boolean indicating whether this should be a readdirplus entry
*
* Returns zero if successful, otherwise a negative errno value is
* returned.
*
* This function is not invoked during READDIR reply decoding, but
* rather whenever an application invokes the getdents(2) system call
* on a directory already in our cache.
*/
int nfs4_decode_dirent(struct xdr_stream *xdr, struct nfs_entry *entry,
int plus)
{
uint32_t bitmap[3] = {0};
uint32_t len;
__be32 *p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
if (*p == xdr_zero) {
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
if (*p == xdr_zero)
return -EAGAIN;
entry->eof = 1;
return -EBADCOOKIE;
}
p = xdr_inline_decode(xdr, 12);
if (unlikely(!p))
goto out_overflow;
entry->prev_cookie = entry->cookie;
p = xdr_decode_hyper(p, &entry->cookie);
entry->len = be32_to_cpup(p);
p = xdr_inline_decode(xdr, entry->len);
if (unlikely(!p))
goto out_overflow;
entry->name = (const char *) p;
/*
* In case the server doesn't return an inode number,
* we fake one here. (We don't use inode number 0,
* since glibc seems to choke on it...)
*/
entry->ino = 1;
entry->fattr->valid = 0;
if (decode_attr_bitmap(xdr, bitmap) < 0)
goto out_overflow;
if (decode_attr_length(xdr, &len, &p) < 0)
goto out_overflow;
if (decode_getfattr_attrs(xdr, bitmap, entry->fattr, entry->fh,
NULL, entry->server) < 0)
goto out_overflow;
if (entry->fattr->valid & NFS_ATTR_FATTR_MOUNTED_ON_FILEID)
entry->ino = entry->fattr->mounted_on_fileid;
else if (entry->fattr->valid & NFS_ATTR_FATTR_FILEID)
entry->ino = entry->fattr->fileid;
entry->d_type = DT_UNKNOWN;
if (entry->fattr->valid & NFS_ATTR_FATTR_TYPE)
entry->d_type = nfs_umode_to_dtype(entry->fattr->mode);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EAGAIN;
}
/*
* We need to translate between nfs status return values and
* the local errno values which may not be the same.
*/
static struct {
int stat;
int errno;
} nfs_errtbl[] = {
{ NFS4_OK, 0 },
{ NFS4ERR_PERM, -EPERM },
{ NFS4ERR_NOENT, -ENOENT },
{ NFS4ERR_IO, -errno_NFSERR_IO},
{ NFS4ERR_NXIO, -ENXIO },
{ NFS4ERR_ACCESS, -EACCES },
{ NFS4ERR_EXIST, -EEXIST },
{ NFS4ERR_XDEV, -EXDEV },
{ NFS4ERR_NOTDIR, -ENOTDIR },
{ NFS4ERR_ISDIR, -EISDIR },
{ NFS4ERR_INVAL, -EINVAL },
{ NFS4ERR_FBIG, -EFBIG },
{ NFS4ERR_NOSPC, -ENOSPC },
{ NFS4ERR_ROFS, -EROFS },
{ NFS4ERR_MLINK, -EMLINK },
{ NFS4ERR_NAMETOOLONG, -ENAMETOOLONG },
{ NFS4ERR_NOTEMPTY, -ENOTEMPTY },
{ NFS4ERR_DQUOT, -EDQUOT },
{ NFS4ERR_STALE, -ESTALE },
{ NFS4ERR_BADHANDLE, -EBADHANDLE },
{ NFS4ERR_BAD_COOKIE, -EBADCOOKIE },
{ NFS4ERR_NOTSUPP, -ENOTSUPP },
{ NFS4ERR_TOOSMALL, -ETOOSMALL },
{ NFS4ERR_SERVERFAULT, -EREMOTEIO },
{ NFS4ERR_BADTYPE, -EBADTYPE },
{ NFS4ERR_LOCKED, -EAGAIN },
{ NFS4ERR_SYMLINK, -ELOOP },
{ NFS4ERR_OP_ILLEGAL, -EOPNOTSUPP },
{ NFS4ERR_DEADLOCK, -EDEADLK },
{ -1, -EIO }
};
/*
* Convert an NFS error code to a local one.
* This one is used jointly by NFSv2 and NFSv3.
*/
static int
nfs4_stat_to_errno(int stat)
{
int i;
for (i = 0; nfs_errtbl[i].stat != -1; i++) {
if (nfs_errtbl[i].stat == stat)
return nfs_errtbl[i].errno;
}
if (stat <= 10000 || stat > 10100) {
/* The server is looney tunes. */
return -EREMOTEIO;
}
/* If we cannot translate the error, the recovery routines should
* handle it.
* Note: remaining NFSv4 error codes have values > 10000, so should
* not conflict with native Linux error codes.
*/
return -stat;
}
#define PROC(proc, argtype, restype) \
[NFSPROC4_CLNT_##proc] = { \
.p_proc = NFSPROC4_COMPOUND, \
.p_encode = (kxdreproc_t)nfs4_xdr_##argtype, \
.p_decode = (kxdrdproc_t)nfs4_xdr_##restype, \
.p_arglen = NFS4_##argtype##_sz, \
.p_replen = NFS4_##restype##_sz, \
.p_statidx = NFSPROC4_CLNT_##proc, \
.p_name = #proc, \
}
struct rpc_procinfo nfs4_procedures[] = {
PROC(READ, enc_read, dec_read),
PROC(WRITE, enc_write, dec_write),
PROC(COMMIT, enc_commit, dec_commit),
PROC(OPEN, enc_open, dec_open),
PROC(OPEN_CONFIRM, enc_open_confirm, dec_open_confirm),
PROC(OPEN_NOATTR, enc_open_noattr, dec_open_noattr),
PROC(OPEN_DOWNGRADE, enc_open_downgrade, dec_open_downgrade),
PROC(CLOSE, enc_close, dec_close),
PROC(SETATTR, enc_setattr, dec_setattr),
PROC(FSINFO, enc_fsinfo, dec_fsinfo),
PROC(RENEW, enc_renew, dec_renew),
PROC(SETCLIENTID, enc_setclientid, dec_setclientid),
PROC(SETCLIENTID_CONFIRM, enc_setclientid_confirm, dec_setclientid_confirm),
PROC(LOCK, enc_lock, dec_lock),
PROC(LOCKT, enc_lockt, dec_lockt),
PROC(LOCKU, enc_locku, dec_locku),
PROC(ACCESS, enc_access, dec_access),
PROC(GETATTR, enc_getattr, dec_getattr),
PROC(LOOKUP, enc_lookup, dec_lookup),
PROC(LOOKUP_ROOT, enc_lookup_root, dec_lookup_root),
PROC(REMOVE, enc_remove, dec_remove),
PROC(RENAME, enc_rename, dec_rename),
PROC(LINK, enc_link, dec_link),
PROC(SYMLINK, enc_symlink, dec_symlink),
PROC(CREATE, enc_create, dec_create),
PROC(PATHCONF, enc_pathconf, dec_pathconf),
PROC(STATFS, enc_statfs, dec_statfs),
PROC(READLINK, enc_readlink, dec_readlink),
PROC(READDIR, enc_readdir, dec_readdir),
PROC(SERVER_CAPS, enc_server_caps, dec_server_caps),
PROC(DELEGRETURN, enc_delegreturn, dec_delegreturn),
PROC(GETACL, enc_getacl, dec_getacl),
PROC(SETACL, enc_setacl, dec_setacl),
PROC(FS_LOCATIONS, enc_fs_locations, dec_fs_locations),
PROC(RELEASE_LOCKOWNER, enc_release_lockowner, dec_release_lockowner),
PROC(SECINFO, enc_secinfo, dec_secinfo),
#if defined(CONFIG_NFS_V4_1)
PROC(EXCHANGE_ID, enc_exchange_id, dec_exchange_id),
PROC(CREATE_SESSION, enc_create_session, dec_create_session),
PROC(DESTROY_SESSION, enc_destroy_session, dec_destroy_session),
PROC(SEQUENCE, enc_sequence, dec_sequence),
PROC(GET_LEASE_TIME, enc_get_lease_time, dec_get_lease_time),
PROC(RECLAIM_COMPLETE, enc_reclaim_complete, dec_reclaim_complete),
PROC(GETDEVICEINFO, enc_getdeviceinfo, dec_getdeviceinfo),
PROC(LAYOUTGET, enc_layoutget, dec_layoutget),
PROC(LAYOUTCOMMIT, enc_layoutcommit, dec_layoutcommit),
PROC(LAYOUTRETURN, enc_layoutreturn, dec_layoutreturn),
PROC(SECINFO_NO_NAME, enc_secinfo_no_name, dec_secinfo_no_name),
PROC(TEST_STATEID, enc_test_stateid, dec_test_stateid),
PROC(FREE_STATEID, enc_free_stateid, dec_free_stateid),
PROC(GETDEVICELIST, enc_getdevicelist, dec_getdevicelist),
#endif /* CONFIG_NFS_V4_1 */
};
const struct rpc_version nfs_version4 = {
.number = 4,
.nrprocs = ARRAY_SIZE(nfs4_procedures),
.procs = nfs4_procedures
};
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| mit |
RobertABT/heightmap | build/scipy/scipy/interpolate/fitpack/fpfrno.f | 148 | 1697 | subroutine fpfrno(maxtr,up,left,right,info,point,merk,n1,
* count,ier)
c subroutine fpfrno collects the free nodes (up field zero) of the
c triply linked tree the information of which is kept in the arrays
c up,left,right and info. the maximal length of the branches of the
c tree is given by n1. if no free nodes are found, the error flag
c ier is set to 1.
c ..
c ..scalar arguments..
integer maxtr,point,merk,n1,count,ier
c ..array arguments..
integer up(maxtr),left(maxtr),right(maxtr),info(maxtr)
c ..local scalars
integer i,j,k,l,n,niveau
c ..
ier = 1
if(n1.eq.2) go to 140
niveau = 1
count = 2
10 j = 0
i = 1
20 if(j.eq.niveau) go to 30
k = 0
l = left(i)
if(l.eq.0) go to 110
i = l
j = j+1
go to 20
30 if (i.lt.count) go to 110
if (i.eq.count) go to 100
go to 40
40 if(up(count).eq.0) go to 50
count = count+1
go to 30
50 up(count) = up(i)
left(count) = left(i)
right(count) = right(i)
info(count) = info(i)
if(merk.eq.i) merk = count
if(point.eq.i) point = count
if(k.eq.0) go to 60
right(k) = count
go to 70
60 n = up(i)
left(n) = count
70 l = left(i)
80 if(l.eq.0) go to 90
up(l) = count
l = right(l)
go to 80
90 up(i) = 0
i = count
100 count = count+1
110 l = right(i)
k = i
if(l.eq.0) go to 120
i = l
go to 20
120 l = up(i)
j = j-1
if(j.eq.0) go to 130
i = l
go to 110
130 niveau = niveau+1
if(niveau.le.n1) go to 10
if(count.gt.maxtr) go to 140
ier = 0
140 return
end
| mit |
MitchellMintCoins/AutoCoin | src/qt/walletview.cpp | 161 | 8817 | /*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2013
*/
#include "walletview.h"
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "askpassphrasedialog.h"
#include "ui_interface.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QAction>
#include <QDesktopServices>
#include <QFileDialog>
#include <QPushButton>
WalletView::WalletView(QWidget *parent, BitcoinGUI *_gui):
QStackedWidget(parent),
gui(_gui),
clientModel(0),
walletModel(0)
{
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
QHBoxLayout *hbox_buttons = new QHBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
QPushButton *exportButton = new QPushButton(tr("&Export"), this);
exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
exportButton->setIcon(QIcon(":/icons/export"));
#endif
hbox_buttons->addStretch();
hbox_buttons->addWidget(exportButton);
vbox->addLayout(hbox_buttons);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(gui);
signVerifyMessageDialog = new SignVerifyMessageDialog(gui);
addWidget(overviewPage);
addWidget(transactionsPage);
addWidget(addressBookPage);
addWidget(receiveCoinsPage);
addWidget(sendCoinsPage);
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
// Clicking on "Send Coins" in the address book sends you to the send coins tab
connect(addressBookPage, SIGNAL(sendCoins(QString)), this, SLOT(gotoSendCoinsPage(QString)));
// Clicking on "Verify Message" in the address book opens the verify message tab in the Sign/Verify Message dialog
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page opens the sign message tab in the Sign/Verify Message dialog
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
// Clicking on "Export" allows to export the transaction list
connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));
gotoOverviewPage();
}
WalletView::~WalletView()
{
}
void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
this->gui = gui;
}
void WalletView::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if (clientModel)
{
overviewPage->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void WalletView::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if (walletModel)
{
// Receive and report messages from wallet thread
connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setWalletModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus();
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void WalletView::incomingTransaction(const QModelIndex& parent, int start, int /*end*/)
{
// Prevent balloon-spam when initial block download is in progress
if(!walletModel || !clientModel || clientModel->inInitialBlockDownload())
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();
gui->incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}
void WalletView::gotoOverviewPage()
{
gui->getOverviewAction()->setChecked(true);
setCurrentWidget(overviewPage);
}
void WalletView::gotoHistoryPage()
{
gui->getHistoryAction()->setChecked(true);
setCurrentWidget(transactionsPage);
}
void WalletView::gotoAddressBookPage()
{
gui->getAddressBookAction()->setChecked(true);
setCurrentWidget(addressBookPage);
}
void WalletView::gotoReceiveCoinsPage()
{
gui->getReceiveCoinsAction()->setChecked(true);
setCurrentWidget(receiveCoinsPage);
}
void WalletView::gotoSendCoinsPage(QString addr)
{
gui->getSendCoinsAction()->setChecked(true);
setCurrentWidget(sendCoinsPage);
if (!addr.isEmpty())
sendCoinsPage->setAddress(addr);
}
void WalletView::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void WalletView::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
bool WalletView::handleURI(const QString& strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
gotoSendCoinsPage();
emit showNormalIfMinimized();
return true;
}
else
return false;
}
void WalletView::showOutOfSyncWarning(bool fShow)
{
overviewPage->showOutOfSyncWarning(fShow);
}
void WalletView::setEncryptionStatus()
{
gui->setEncryptionStatus(walletModel->getEncryptionStatus());
}
void WalletView::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus();
}
void WalletView::backupWallet()
{
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if (!filename.isEmpty()) {
if (!walletModel->backupWallet(filename)) {
gui->message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."),
CClientUIInterface::MSG_ERROR);
}
else
gui->message(tr("Backup Successful"), tr("The wallet data was successfully saved to the new location."),
CClientUIInterface::MSG_INFORMATION);
}
}
void WalletView::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void WalletView::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if (walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
| mit |
hanjae/lumiab0 | lib/openssl/crypto/ui/ui_lib.c | 681 | 20587 | /* crypto/ui/ui_lib.c -*- mode:C; c-file-style: "eay" -*- */
/* Written by Richard Levitte (richard@levitte.org) for the OpenSSL
* project 2001.
*/
/* ====================================================================
* Copyright (c) 2001 The OpenSSL Project. 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <string.h>
#include "cryptlib.h"
#include <openssl/e_os2.h>
#include <openssl/buffer.h>
#include <openssl/ui.h>
#include <openssl/err.h>
#include "ui_locl.h"
IMPLEMENT_STACK_OF(UI_STRING_ST)
static const UI_METHOD *default_UI_meth=NULL;
UI *UI_new(void)
{
return(UI_new_method(NULL));
}
UI *UI_new_method(const UI_METHOD *method)
{
UI *ret;
ret=(UI *)OPENSSL_malloc(sizeof(UI));
if (ret == NULL)
{
UIerr(UI_F_UI_NEW_METHOD,ERR_R_MALLOC_FAILURE);
return NULL;
}
if (method == NULL)
ret->meth=UI_get_default_method();
else
ret->meth=method;
ret->strings=NULL;
ret->user_data=NULL;
ret->flags=0;
CRYPTO_new_ex_data(CRYPTO_EX_INDEX_UI, ret, &ret->ex_data);
return ret;
}
static void free_string(UI_STRING *uis)
{
if (uis->flags & OUT_STRING_FREEABLE)
{
OPENSSL_free((char *)uis->out_string);
switch(uis->type)
{
case UIT_BOOLEAN:
OPENSSL_free((char *)uis->_.boolean_data.action_desc);
OPENSSL_free((char *)uis->_.boolean_data.ok_chars);
OPENSSL_free((char *)uis->_.boolean_data.cancel_chars);
break;
default:
break;
}
}
OPENSSL_free(uis);
}
void UI_free(UI *ui)
{
if (ui == NULL)
return;
sk_UI_STRING_pop_free(ui->strings,free_string);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_UI, ui, &ui->ex_data);
OPENSSL_free(ui);
}
static int allocate_string_stack(UI *ui)
{
if (ui->strings == NULL)
{
ui->strings=sk_UI_STRING_new_null();
if (ui->strings == NULL)
{
return -1;
}
}
return 0;
}
static UI_STRING *general_allocate_prompt(UI *ui, const char *prompt,
int prompt_freeable, enum UI_string_types type, int input_flags,
char *result_buf)
{
UI_STRING *ret = NULL;
if (prompt == NULL)
{
UIerr(UI_F_GENERAL_ALLOCATE_PROMPT,ERR_R_PASSED_NULL_PARAMETER);
}
else if ((type == UIT_PROMPT || type == UIT_VERIFY
|| type == UIT_BOOLEAN) && result_buf == NULL)
{
UIerr(UI_F_GENERAL_ALLOCATE_PROMPT,UI_R_NO_RESULT_BUFFER);
}
else if ((ret = (UI_STRING *)OPENSSL_malloc(sizeof(UI_STRING))))
{
ret->out_string=prompt;
ret->flags=prompt_freeable ? OUT_STRING_FREEABLE : 0;
ret->input_flags=input_flags;
ret->type=type;
ret->result_buf=result_buf;
}
return ret;
}
static int general_allocate_string(UI *ui, const char *prompt,
int prompt_freeable, enum UI_string_types type, int input_flags,
char *result_buf, int minsize, int maxsize, const char *test_buf)
{
int ret = -1;
UI_STRING *s = general_allocate_prompt(ui, prompt, prompt_freeable,
type, input_flags, result_buf);
if (s)
{
if (allocate_string_stack(ui) >= 0)
{
s->_.string_data.result_minsize=minsize;
s->_.string_data.result_maxsize=maxsize;
s->_.string_data.test_buf=test_buf;
ret=sk_UI_STRING_push(ui->strings, s);
/* sk_push() returns 0 on error. Let's addapt that */
if (ret <= 0) ret--;
}
else
free_string(s);
}
return ret;
}
static int general_allocate_boolean(UI *ui,
const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int prompt_freeable, enum UI_string_types type, int input_flags,
char *result_buf)
{
int ret = -1;
UI_STRING *s;
const char *p;
if (ok_chars == NULL)
{
UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,ERR_R_PASSED_NULL_PARAMETER);
}
else if (cancel_chars == NULL)
{
UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,ERR_R_PASSED_NULL_PARAMETER);
}
else
{
for(p = ok_chars; *p; p++)
{
if (strchr(cancel_chars, *p))
{
UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,
UI_R_COMMON_OK_AND_CANCEL_CHARACTERS);
}
}
s = general_allocate_prompt(ui, prompt, prompt_freeable,
type, input_flags, result_buf);
if (s)
{
if (allocate_string_stack(ui) >= 0)
{
s->_.boolean_data.action_desc = action_desc;
s->_.boolean_data.ok_chars = ok_chars;
s->_.boolean_data.cancel_chars = cancel_chars;
ret=sk_UI_STRING_push(ui->strings, s);
/* sk_push() returns 0 on error.
Let's addapt that */
if (ret <= 0) ret--;
}
else
free_string(s);
}
}
return ret;
}
/* Returns the index to the place in the stack or -1 for error. Uses a
direct reference to the prompt. */
int UI_add_input_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize)
{
return general_allocate_string(ui, prompt, 0,
UIT_PROMPT, flags, result_buf, minsize, maxsize, NULL);
}
/* Same as UI_add_input_string(), excepts it takes a copy of the prompt */
int UI_dup_input_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize)
{
char *prompt_copy=NULL;
if (prompt)
{
prompt_copy=BUF_strdup(prompt);
if (prompt_copy == NULL)
{
UIerr(UI_F_UI_DUP_INPUT_STRING,ERR_R_MALLOC_FAILURE);
return 0;
}
}
return general_allocate_string(ui, prompt_copy, 1,
UIT_PROMPT, flags, result_buf, minsize, maxsize, NULL);
}
int UI_add_verify_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize, const char *test_buf)
{
return general_allocate_string(ui, prompt, 0,
UIT_VERIFY, flags, result_buf, minsize, maxsize, test_buf);
}
int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize, const char *test_buf)
{
char *prompt_copy=NULL;
if (prompt)
{
prompt_copy=BUF_strdup(prompt);
if (prompt_copy == NULL)
{
UIerr(UI_F_UI_DUP_VERIFY_STRING,ERR_R_MALLOC_FAILURE);
return -1;
}
}
return general_allocate_string(ui, prompt_copy, 1,
UIT_VERIFY, flags, result_buf, minsize, maxsize, test_buf);
}
int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int flags, char *result_buf)
{
return general_allocate_boolean(ui, prompt, action_desc,
ok_chars, cancel_chars, 0, UIT_BOOLEAN, flags, result_buf);
}
int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int flags, char *result_buf)
{
char *prompt_copy = NULL;
char *action_desc_copy = NULL;
char *ok_chars_copy = NULL;
char *cancel_chars_copy = NULL;
if (prompt)
{
prompt_copy=BUF_strdup(prompt);
if (prompt_copy == NULL)
{
UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (action_desc)
{
action_desc_copy=BUF_strdup(action_desc);
if (action_desc_copy == NULL)
{
UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (ok_chars)
{
ok_chars_copy=BUF_strdup(ok_chars);
if (ok_chars_copy == NULL)
{
UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (cancel_chars)
{
cancel_chars_copy=BUF_strdup(cancel_chars);
if (cancel_chars_copy == NULL)
{
UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE);
goto err;
}
}
return general_allocate_boolean(ui, prompt_copy, action_desc_copy,
ok_chars_copy, cancel_chars_copy, 1, UIT_BOOLEAN, flags,
result_buf);
err:
if (prompt_copy) OPENSSL_free(prompt_copy);
if (action_desc_copy) OPENSSL_free(action_desc_copy);
if (ok_chars_copy) OPENSSL_free(ok_chars_copy);
if (cancel_chars_copy) OPENSSL_free(cancel_chars_copy);
return -1;
}
int UI_add_info_string(UI *ui, const char *text)
{
return general_allocate_string(ui, text, 0, UIT_INFO, 0, NULL, 0, 0,
NULL);
}
int UI_dup_info_string(UI *ui, const char *text)
{
char *text_copy=NULL;
if (text)
{
text_copy=BUF_strdup(text);
if (text_copy == NULL)
{
UIerr(UI_F_UI_DUP_INFO_STRING,ERR_R_MALLOC_FAILURE);
return -1;
}
}
return general_allocate_string(ui, text_copy, 1, UIT_INFO, 0, NULL,
0, 0, NULL);
}
int UI_add_error_string(UI *ui, const char *text)
{
return general_allocate_string(ui, text, 0, UIT_ERROR, 0, NULL, 0, 0,
NULL);
}
int UI_dup_error_string(UI *ui, const char *text)
{
char *text_copy=NULL;
if (text)
{
text_copy=BUF_strdup(text);
if (text_copy == NULL)
{
UIerr(UI_F_UI_DUP_ERROR_STRING,ERR_R_MALLOC_FAILURE);
return -1;
}
}
return general_allocate_string(ui, text_copy, 1, UIT_ERROR, 0, NULL,
0, 0, NULL);
}
char *UI_construct_prompt(UI *ui, const char *object_desc,
const char *object_name)
{
char *prompt = NULL;
if (ui->meth->ui_construct_prompt)
prompt = ui->meth->ui_construct_prompt(ui,
object_desc, object_name);
else
{
char prompt1[] = "Enter ";
char prompt2[] = " for ";
char prompt3[] = ":";
int len = 0;
if (object_desc == NULL)
return NULL;
len = sizeof(prompt1) - 1 + strlen(object_desc);
if (object_name)
len += sizeof(prompt2) - 1 + strlen(object_name);
len += sizeof(prompt3) - 1;
prompt = (char *)OPENSSL_malloc(len + 1);
BUF_strlcpy(prompt, prompt1, len + 1);
BUF_strlcat(prompt, object_desc, len + 1);
if (object_name)
{
BUF_strlcat(prompt, prompt2, len + 1);
BUF_strlcat(prompt, object_name, len + 1);
}
BUF_strlcat(prompt, prompt3, len + 1);
}
return prompt;
}
void *UI_add_user_data(UI *ui, void *user_data)
{
void *old_data = ui->user_data;
ui->user_data = user_data;
return old_data;
}
void *UI_get0_user_data(UI *ui)
{
return ui->user_data;
}
const char *UI_get0_result(UI *ui, int i)
{
if (i < 0)
{
UIerr(UI_F_UI_GET0_RESULT,UI_R_INDEX_TOO_SMALL);
return NULL;
}
if (i >= sk_UI_STRING_num(ui->strings))
{
UIerr(UI_F_UI_GET0_RESULT,UI_R_INDEX_TOO_LARGE);
return NULL;
}
return UI_get0_result_string(sk_UI_STRING_value(ui->strings, i));
}
static int print_error(const char *str, size_t len, UI *ui)
{
UI_STRING uis;
memset(&uis, 0, sizeof(uis));
uis.type = UIT_ERROR;
uis.out_string = str;
if (ui->meth->ui_write_string
&& !ui->meth->ui_write_string(ui, &uis))
return -1;
return 0;
}
int UI_process(UI *ui)
{
int i, ok=0;
if (ui->meth->ui_open_session && !ui->meth->ui_open_session(ui))
return -1;
if (ui->flags & UI_FLAG_PRINT_ERRORS)
ERR_print_errors_cb(
(int (*)(const char *, size_t, void *))print_error,
(void *)ui);
for(i=0; i<sk_UI_STRING_num(ui->strings); i++)
{
if (ui->meth->ui_write_string
&& !ui->meth->ui_write_string(ui,
sk_UI_STRING_value(ui->strings, i)))
{
ok=-1;
goto err;
}
}
if (ui->meth->ui_flush)
switch(ui->meth->ui_flush(ui))
{
case -1: /* Interrupt/Cancel/something... */
ok = -2;
goto err;
case 0: /* Errors */
ok = -1;
goto err;
default: /* Success */
ok = 0;
break;
}
for(i=0; i<sk_UI_STRING_num(ui->strings); i++)
{
if (ui->meth->ui_read_string)
{
switch(ui->meth->ui_read_string(ui,
sk_UI_STRING_value(ui->strings, i)))
{
case -1: /* Interrupt/Cancel/something... */
ok = -2;
goto err;
case 0: /* Errors */
ok = -1;
goto err;
default: /* Success */
ok = 0;
break;
}
}
}
err:
if (ui->meth->ui_close_session && !ui->meth->ui_close_session(ui))
return -1;
return ok;
}
int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)(void))
{
if (ui == NULL)
{
UIerr(UI_F_UI_CTRL,ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
switch(cmd)
{
case UI_CTRL_PRINT_ERRORS:
{
int save_flag = !!(ui->flags & UI_FLAG_PRINT_ERRORS);
if (i)
ui->flags |= UI_FLAG_PRINT_ERRORS;
else
ui->flags &= ~UI_FLAG_PRINT_ERRORS;
return save_flag;
}
case UI_CTRL_IS_REDOABLE:
return !!(ui->flags & UI_FLAG_REDOABLE);
default:
break;
}
UIerr(UI_F_UI_CTRL,UI_R_UNKNOWN_CONTROL_COMMAND);
return -1;
}
int UI_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
{
return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, argl, argp,
new_func, dup_func, free_func);
}
int UI_set_ex_data(UI *r, int idx, void *arg)
{
return(CRYPTO_set_ex_data(&r->ex_data,idx,arg));
}
void *UI_get_ex_data(UI *r, int idx)
{
return(CRYPTO_get_ex_data(&r->ex_data,idx));
}
void UI_set_default_method(const UI_METHOD *meth)
{
default_UI_meth=meth;
}
const UI_METHOD *UI_get_default_method(void)
{
if (default_UI_meth == NULL)
{
default_UI_meth=UI_OpenSSL();
}
return default_UI_meth;
}
const UI_METHOD *UI_get_method(UI *ui)
{
return ui->meth;
}
const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth)
{
ui->meth=meth;
return ui->meth;
}
UI_METHOD *UI_create_method(char *name)
{
UI_METHOD *ui_method = (UI_METHOD *)OPENSSL_malloc(sizeof(UI_METHOD));
if (ui_method)
{
memset(ui_method, 0, sizeof(*ui_method));
ui_method->name = BUF_strdup(name);
}
return ui_method;
}
/* BIG FSCKING WARNING!!!! If you use this on a statically allocated method
(that is, it hasn't been allocated using UI_create_method(), you deserve
anything Murphy can throw at you and more! You have been warned. */
void UI_destroy_method(UI_METHOD *ui_method)
{
OPENSSL_free(ui_method->name);
ui_method->name = NULL;
OPENSSL_free(ui_method);
}
int UI_method_set_opener(UI_METHOD *method, int (*opener)(UI *ui))
{
if (method)
{
method->ui_open_session = opener;
return 0;
}
else
return -1;
}
int UI_method_set_writer(UI_METHOD *method, int (*writer)(UI *ui, UI_STRING *uis))
{
if (method)
{
method->ui_write_string = writer;
return 0;
}
else
return -1;
}
int UI_method_set_flusher(UI_METHOD *method, int (*flusher)(UI *ui))
{
if (method)
{
method->ui_flush = flusher;
return 0;
}
else
return -1;
}
int UI_method_set_reader(UI_METHOD *method, int (*reader)(UI *ui, UI_STRING *uis))
{
if (method)
{
method->ui_read_string = reader;
return 0;
}
else
return -1;
}
int UI_method_set_closer(UI_METHOD *method, int (*closer)(UI *ui))
{
if (method)
{
method->ui_close_session = closer;
return 0;
}
else
return -1;
}
int UI_method_set_prompt_constructor(UI_METHOD *method, char *(*prompt_constructor)(UI* ui, const char* object_desc, const char* object_name))
{
if (method)
{
method->ui_construct_prompt = prompt_constructor;
return 0;
}
else
return -1;
}
int (*UI_method_get_opener(UI_METHOD *method))(UI*)
{
if (method)
return method->ui_open_session;
else
return NULL;
}
int (*UI_method_get_writer(UI_METHOD *method))(UI*,UI_STRING*)
{
if (method)
return method->ui_write_string;
else
return NULL;
}
int (*UI_method_get_flusher(UI_METHOD *method))(UI*)
{
if (method)
return method->ui_flush;
else
return NULL;
}
int (*UI_method_get_reader(UI_METHOD *method))(UI*,UI_STRING*)
{
if (method)
return method->ui_read_string;
else
return NULL;
}
int (*UI_method_get_closer(UI_METHOD *method))(UI*)
{
if (method)
return method->ui_close_session;
else
return NULL;
}
char* (*UI_method_get_prompt_constructor(UI_METHOD *method))(UI*, const char*, const char*)
{
if (method)
return method->ui_construct_prompt;
else
return NULL;
}
enum UI_string_types UI_get_string_type(UI_STRING *uis)
{
if (!uis)
return UIT_NONE;
return uis->type;
}
int UI_get_input_flags(UI_STRING *uis)
{
if (!uis)
return 0;
return uis->input_flags;
}
const char *UI_get0_output_string(UI_STRING *uis)
{
if (!uis)
return NULL;
return uis->out_string;
}
const char *UI_get0_action_string(UI_STRING *uis)
{
if (!uis)
return NULL;
switch(uis->type)
{
case UIT_PROMPT:
case UIT_BOOLEAN:
return uis->_.boolean_data.action_desc;
default:
return NULL;
}
}
const char *UI_get0_result_string(UI_STRING *uis)
{
if (!uis)
return NULL;
switch(uis->type)
{
case UIT_PROMPT:
case UIT_VERIFY:
return uis->result_buf;
default:
return NULL;
}
}
const char *UI_get0_test_string(UI_STRING *uis)
{
if (!uis)
return NULL;
switch(uis->type)
{
case UIT_VERIFY:
return uis->_.string_data.test_buf;
default:
return NULL;
}
}
int UI_get_result_minsize(UI_STRING *uis)
{
if (!uis)
return -1;
switch(uis->type)
{
case UIT_PROMPT:
case UIT_VERIFY:
return uis->_.string_data.result_minsize;
default:
return -1;
}
}
int UI_get_result_maxsize(UI_STRING *uis)
{
if (!uis)
return -1;
switch(uis->type)
{
case UIT_PROMPT:
case UIT_VERIFY:
return uis->_.string_data.result_maxsize;
default:
return -1;
}
}
int UI_set_result(UI *ui, UI_STRING *uis, const char *result)
{
int l = strlen(result);
ui->flags &= ~UI_FLAG_REDOABLE;
if (!uis)
return -1;
switch (uis->type)
{
case UIT_PROMPT:
case UIT_VERIFY:
{
char number1[DECIMAL_SIZE(uis->_.string_data.result_minsize)+1];
char number2[DECIMAL_SIZE(uis->_.string_data.result_maxsize)+1];
BIO_snprintf(number1, sizeof(number1), "%d",
uis->_.string_data.result_minsize);
BIO_snprintf(number2, sizeof(number2), "%d",
uis->_.string_data.result_maxsize);
if (l < uis->_.string_data.result_minsize)
{
ui->flags |= UI_FLAG_REDOABLE;
UIerr(UI_F_UI_SET_RESULT,UI_R_RESULT_TOO_SMALL);
ERR_add_error_data(5,"You must type in ",
number1," to ",number2," characters");
return -1;
}
if (l > uis->_.string_data.result_maxsize)
{
ui->flags |= UI_FLAG_REDOABLE;
UIerr(UI_F_UI_SET_RESULT,UI_R_RESULT_TOO_LARGE);
ERR_add_error_data(5,"You must type in ",
number1," to ",number2," characters");
return -1;
}
}
if (!uis->result_buf)
{
UIerr(UI_F_UI_SET_RESULT,UI_R_NO_RESULT_BUFFER);
return -1;
}
BUF_strlcpy(uis->result_buf, result,
uis->_.string_data.result_maxsize + 1);
break;
case UIT_BOOLEAN:
{
const char *p;
if (!uis->result_buf)
{
UIerr(UI_F_UI_SET_RESULT,UI_R_NO_RESULT_BUFFER);
return -1;
}
uis->result_buf[0] = '\0';
for(p = result; *p; p++)
{
if (strchr(uis->_.boolean_data.ok_chars, *p))
{
uis->result_buf[0] =
uis->_.boolean_data.ok_chars[0];
break;
}
if (strchr(uis->_.boolean_data.cancel_chars, *p))
{
uis->result_buf[0] =
uis->_.boolean_data.cancel_chars[0];
break;
}
}
default:
break;
}
}
return 0;
}
| mit |
KitoHo/WinObjC | deps/3rdparty/icu/icu/source/layout/StateTableProcessor2.cpp | 174 | 9129 | /*
*
* (C) Copyright IBM Corp. and others 1998-2014 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "MorphTables.h"
#include "StateTables.h"
#include "MorphStateTables.h"
#include "SubtableProcessor2.h"
#include "StateTableProcessor2.h"
#include "LEGlyphStorage.h"
#include "LESwaps.h"
#include "LookupTables.h"
U_NAMESPACE_BEGIN
StateTableProcessor2::StateTableProcessor2()
{
}
StateTableProcessor2::StateTableProcessor2(const LEReferenceTo<MorphSubtableHeader2> &morphSubtableHeader, LEErrorCode &success)
: SubtableProcessor2(morphSubtableHeader, success),
dir(1),
format(0),
nClasses(0),
classTableOffset(0),
stateArrayOffset(0),
entryTableOffset(0),
classTable(),
stateArray(),
stateTableHeader(morphSubtableHeader, success),
stHeader(stateTableHeader, success, (const StateTableHeader2*)&stateTableHeader->stHeader)
{
if (LE_FAILURE(success)) {
return;
}
nClasses = SWAPL(stHeader->nClasses);
classTableOffset = SWAPL(stHeader->classTableOffset);
stateArrayOffset = SWAPL(stHeader->stateArrayOffset);
entryTableOffset = SWAPL(stHeader->entryTableOffset);
classTable = LEReferenceTo<LookupTable>(stHeader, success, classTableOffset);
format = SWAPW(classTable->format);
stateArray = LEReferenceToArrayOf<EntryTableIndex2>(stHeader, success, stateArrayOffset, LE_UNBOUNDED_ARRAY);
}
StateTableProcessor2::~StateTableProcessor2()
{
}
void StateTableProcessor2::process(LEGlyphStorage &glyphStorage, LEErrorCode &success)
{
if (LE_FAILURE(success)) return;
// Start at state 0
// XXX: How do we know when to start at state 1?
le_uint16 currentState = 0;
le_int32 glyphCount = glyphStorage.getGlyphCount();
LE_STATE_PATIENCE_INIT();
le_int32 currGlyph = 0;
if ((coverage & scfReverse2) != 0) { // process glyphs in descending order
currGlyph = glyphCount - 1;
dir = -1;
} else {
dir = 1;
}
beginStateTable();
switch (format) {
case ltfSimpleArray: {
#ifdef TEST_FORMAT
LEReferenceTo<SimpleArrayLookupTable> lookupTable0(classTable, success);
if(LE_FAILURE(success)) break;
while ((dir == 1 && currGlyph <= glyphCount) || (dir == -1 && currGlyph >= -1)) {
if (LE_FAILURE(success)) break;
if (LE_STATE_PATIENCE_DECR()) {
LE_DEBUG_BAD_FONT("patience exceeded - state table not moving")
break; // patience exceeded.
}
LookupValue classCode = classCodeOOB;
if (currGlyph == glyphCount || currGlyph == -1) {
// XXX: How do we handle EOT vs. EOL?
classCode = classCodeEOT;
} else {
LEGlyphID gid = glyphStorage[currGlyph];
TTGlyphID glyphCode = (TTGlyphID) LE_GET_GLYPH(gid);
if (glyphCode == 0xFFFF) {
classCode = classCodeDEL;
} else {
classCode = SWAPW(lookupTable0->valueArray[gid]);
}
}
EntryTableIndex2 entryTableIndex = SWAPW(stateArray(classCode + currentState * nClasses, success));
LE_STATE_PATIENCE_CURR(le_int32, currGlyph);
currentState = processStateEntry(glyphStorage, currGlyph, entryTableIndex); // return a zero-based index instead of a byte offset
LE_STATE_PATIENCE_INCR(currGlyph);
}
#endif
break;
}
case ltfSegmentSingle: {
LEReferenceTo<SegmentSingleLookupTable> lookupTable2(classTable, success);
if(LE_FAILURE(success)) break;
while ((dir == 1 && currGlyph <= glyphCount) || (dir == -1 && currGlyph >= -1)) {
if (LE_FAILURE(success)) break;
if (LE_STATE_PATIENCE_DECR()) {
LE_DEBUG_BAD_FONT("patience exceeded - state table not moving")
break; // patience exceeded.
}
LookupValue classCode = classCodeOOB;
if (currGlyph == glyphCount || currGlyph == -1) {
// XXX: How do we handle EOT vs. EOL?
classCode = classCodeEOT;
} else {
LEGlyphID gid = glyphStorage[currGlyph];
TTGlyphID glyphCode = (TTGlyphID) LE_GET_GLYPH(gid);
if (glyphCode == 0xFFFF) {
classCode = classCodeDEL;
} else {
const LookupSegment *segment =
lookupTable2->lookupSegment(lookupTable2, lookupTable2->segments, gid, success);
if (segment != NULL && LE_SUCCESS(success)) {
classCode = SWAPW(segment->value);
}
}
}
EntryTableIndex2 entryTableIndex = SWAPW(stateArray(classCode + currentState * nClasses,success));
LE_STATE_PATIENCE_CURR(le_int32, currGlyph);
currentState = processStateEntry(glyphStorage, currGlyph, entryTableIndex, success);
LE_STATE_PATIENCE_INCR(currGlyph);
}
break;
}
case ltfSegmentArray: {
//printf("Lookup Table Format4: specific interpretation needed!\n");
break;
}
case ltfSingleTable: {
LEReferenceTo<SingleTableLookupTable> lookupTable6(classTable, success);
while ((dir == 1 && currGlyph <= glyphCount) || (dir == -1 && currGlyph >= -1)) {
if (LE_FAILURE(success)) break;
if (LE_STATE_PATIENCE_DECR()) {
LE_DEBUG_BAD_FONT("patience exceeded - state table not moving")
break; // patience exceeded.
}
LookupValue classCode = classCodeOOB;
if (currGlyph == glyphCount || currGlyph == -1) {
// XXX: How do we handle EOT vs. EOL?
classCode = classCodeEOT;
} else if(currGlyph > glyphCount) {
// note if > glyphCount, we've run off the end (bad font)
currGlyph = glyphCount;
classCode = classCodeEOT;
} else {
LEGlyphID gid = glyphStorage[currGlyph];
TTGlyphID glyphCode = (TTGlyphID) LE_GET_GLYPH(gid);
if (glyphCode == 0xFFFF) {
classCode = classCodeDEL;
} else {
const LookupSingle *segment = lookupTable6->lookupSingle(lookupTable6, lookupTable6->entries, gid, success);
if (segment != NULL) {
classCode = SWAPW(segment->value);
}
}
}
EntryTableIndex2 entryTableIndex = SWAPW(stateArray(classCode + currentState * nClasses, success));
LE_STATE_PATIENCE_CURR(le_int32, currGlyph);
currentState = processStateEntry(glyphStorage, currGlyph, entryTableIndex, success);
LE_STATE_PATIENCE_INCR(currGlyph);
}
break;
}
case ltfTrimmedArray: {
LEReferenceTo<TrimmedArrayLookupTable> lookupTable8(classTable, success);
if (LE_FAILURE(success)) break;
TTGlyphID firstGlyph = SWAPW(lookupTable8->firstGlyph);
TTGlyphID lastGlyph = firstGlyph + SWAPW(lookupTable8->glyphCount);
while ((dir == 1 && currGlyph <= glyphCount) || (dir == -1 && currGlyph >= -1)) {
if(LE_STATE_PATIENCE_DECR()) {
LE_DEBUG_BAD_FONT("patience exceeded - state table not moving")
break; // patience exceeded.
}
LookupValue classCode = classCodeOOB;
if (currGlyph == glyphCount || currGlyph == -1) {
// XXX: How do we handle EOT vs. EOL?
classCode = classCodeEOT;
} else {
TTGlyphID glyphCode = (TTGlyphID) LE_GET_GLYPH(glyphStorage[currGlyph]);
if (glyphCode == 0xFFFF) {
classCode = classCodeDEL;
} else if ((glyphCode >= firstGlyph) && (glyphCode < lastGlyph)) {
classCode = SWAPW(lookupTable8->valueArray[glyphCode - firstGlyph]);
}
}
EntryTableIndex2 entryTableIndex = SWAPW(stateArray(classCode + currentState * nClasses, success));
LE_STATE_PATIENCE_CURR(le_int32, currGlyph);
currentState = processStateEntry(glyphStorage, currGlyph, entryTableIndex, success);
LE_STATE_PATIENCE_INCR(currGlyph);
}
break;
}
default:
break;
}
endStateTable();
}
U_NAMESPACE_END
| mit |
Jaberer/WinObjC | deps/3rdparty/icu/icu/source/test/intltest/plurults.cpp | 175 | 41414 | /*
*******************************************************************************
* Copyright (C) 2007-2014, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************************
* File PLURRULTS.cpp
*
********************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "unicode/localpointer.h"
#include "unicode/plurrule.h"
#include "unicode/stringpiece.h"
#include "cmemory.h"
#include "digitlst.h"
#include "plurrule_impl.h"
#include "plurults.h"
#include "uhash.h"
void setupResult(const int32_t testSource[], char result[], int32_t* max);
UBool checkEqual(const PluralRules &test, char *result, int32_t max);
UBool testEquality(const PluralRules &test);
// This is an API test, not a unit test. It doesn't test very many cases, and doesn't
// try to test the full functionality. It just calls each function in the class and
// verifies that it works on a basic level.
void PluralRulesTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
{
if (exec) logln("TestSuite PluralRulesAPI");
TESTCASE_AUTO_BEGIN;
TESTCASE_AUTO(testAPI);
// TESTCASE_AUTO(testGetUniqueKeywordValue);
TESTCASE_AUTO(testGetSamples);
TESTCASE_AUTO(testWithin);
TESTCASE_AUTO(testGetAllKeywordValues);
TESTCASE_AUTO(testOrdinal);
TESTCASE_AUTO(testSelect);
TESTCASE_AUTO(testAvailbleLocales);
TESTCASE_AUTO(testParseErrors);
TESTCASE_AUTO(testFixedDecimal);
TESTCASE_AUTO_END;
}
// Quick and dirty class for putting UnicodeStrings in char * messages.
// TODO: something like this should be generally available.
class US {
private:
char *buf;
public:
US(const UnicodeString &us) {
int32_t bufLen = us.extract((int32_t)0, us.length(), (char *)NULL, (uint32_t)0) + 1;
buf = (char *)uprv_malloc(bufLen);
us.extract(0, us.length(), buf, bufLen); };
const char *cstr() {return buf;};
~US() { uprv_free(buf);};
};
#define PLURAL_TEST_NUM 18
/**
* Test various generic API methods of PluralRules for API coverage.
*/
void PluralRulesTest::testAPI(/*char *par*/)
{
UnicodeString pluralTestData[PLURAL_TEST_NUM] = {
UNICODE_STRING_SIMPLE("a: n is 1"),
UNICODE_STRING_SIMPLE("a: n mod 10 is 2"),
UNICODE_STRING_SIMPLE("a: n is not 1"),
UNICODE_STRING_SIMPLE("a: n mod 3 is not 1"),
UNICODE_STRING_SIMPLE("a: n in 2..5"),
UNICODE_STRING_SIMPLE("a: n within 2..5"),
UNICODE_STRING_SIMPLE("a: n not in 2..5"),
UNICODE_STRING_SIMPLE("a: n not within 2..5"),
UNICODE_STRING_SIMPLE("a: n mod 10 in 2..5"),
UNICODE_STRING_SIMPLE("a: n mod 10 within 2..5"),
UNICODE_STRING_SIMPLE("a: n mod 10 is 2 and n is not 12"),
UNICODE_STRING_SIMPLE("a: n mod 10 in 2..3 or n mod 10 is 5"),
UNICODE_STRING_SIMPLE("a: n mod 10 within 2..3 or n mod 10 is 5"),
UNICODE_STRING_SIMPLE("a: n is 1 or n is 4 or n is 23"),
UNICODE_STRING_SIMPLE("a: n mod 2 is 1 and n is not 3 and n in 1..11"),
UNICODE_STRING_SIMPLE("a: n mod 2 is 1 and n is not 3 and n within 1..11"),
UNICODE_STRING_SIMPLE("a: n mod 2 is 1 or n mod 5 is 1 and n is not 6"),
"",
};
static const int32_t pluralTestResult[PLURAL_TEST_NUM][30] = {
{1, 0},
{2,12,22, 0},
{0,2,3,4,5,0},
{0,2,3,5,6,8,9,0},
{2,3,4,5,0},
{2,3,4,5,0},
{0,1,6,7,8, 0},
{0,1,6,7,8, 0},
{2,3,4,5,12,13,14,15,22,23,24,25,0},
{2,3,4,5,12,13,14,15,22,23,24,25,0},
{2,22,32,42,0},
{2,3,5,12,13,15,22,23,25,0},
{2,3,5,12,13,15,22,23,25,0},
{1,4,23,0},
{1,5,7,9,11,0},
{1,5,7,9,11,0},
{1,3,5,7,9,11,13,15,16,0},
};
UErrorCode status = U_ZERO_ERROR;
// ======= Test constructors
logln("Testing PluralRules constructors");
logln("\n start default locale test case ..\n");
PluralRules defRule(status);
LocalPointer<PluralRules> test(new PluralRules(status), status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create PluralRules (default) - exitting");
return;
}
LocalPointer<PluralRules> newEnPlural(test->forLocale(Locale::getEnglish(), status), status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create PluralRules (English) - exitting");
return;
}
// ======= Test clone, assignment operator && == operator.
LocalPointer<PluralRules> dupRule(defRule.clone());
if (dupRule==NULL) {
errln("ERROR: clone plural rules test failed!");
return;
} else {
if ( *dupRule != defRule ) {
errln("ERROR: clone plural rules test failed!");
}
}
*dupRule = *newEnPlural;
if (dupRule!=NULL) {
if ( *dupRule != *newEnPlural ) {
errln("ERROR: clone plural rules test failed!");
}
}
// ======= Test empty plural rules
logln("Testing Simple PluralRules");
LocalPointer<PluralRules> empRule(test->createRules(UNICODE_STRING_SIMPLE("a:n"), status));
UnicodeString key;
for (int32_t i=0; i<10; ++i) {
key = empRule->select(i);
if ( key.charAt(0)!= 0x61 ) { // 'a'
errln("ERROR: empty plural rules test failed! - exitting");
}
}
// ======= Test simple plural rules
logln("Testing Simple PluralRules");
char result[100];
int32_t max;
for (int32_t i=0; i<PLURAL_TEST_NUM-1; ++i) {
LocalPointer<PluralRules> newRules(test->createRules(pluralTestData[i], status));
setupResult(pluralTestResult[i], result, &max);
if ( !checkEqual(*newRules, result, max) ) {
errln("ERROR: simple plural rules failed! - exitting");
return;
}
}
// ======= Test complex plural rules
logln("Testing Complex PluralRules");
// TODO: the complex test data is hard coded. It's better to implement
// a parser to parse the test data.
UnicodeString complexRule = UNICODE_STRING_SIMPLE("a: n in 2..5; b: n in 5..8; c: n mod 2 is 1");
UnicodeString complexRule2 = UNICODE_STRING_SIMPLE("a: n within 2..5; b: n within 5..8; c: n mod 2 is 1");
char cRuleResult[] =
{
0x6F, // 'o'
0x63, // 'c'
0x61, // 'a'
0x61, // 'a'
0x61, // 'a'
0x61, // 'a'
0x62, // 'b'
0x62, // 'b'
0x62, // 'b'
0x63, // 'c'
0x6F, // 'o'
0x63 // 'c'
};
LocalPointer<PluralRules> newRules(test->createRules(complexRule, status));
if ( !checkEqual(*newRules, cRuleResult, 12) ) {
errln("ERROR: complex plural rules failed! - exitting");
return;
}
newRules.adoptInstead(test->createRules(complexRule2, status));
if ( !checkEqual(*newRules, cRuleResult, 12) ) {
errln("ERROR: complex plural rules failed! - exitting");
return;
}
// ======= Test decimal fractions plural rules
UnicodeString decimalRule= UNICODE_STRING_SIMPLE("a: n not in 0..100;");
UnicodeString KEYWORD_A = UNICODE_STRING_SIMPLE("a");
status = U_ZERO_ERROR;
newRules.adoptInstead(test->createRules(decimalRule, status));
if (U_FAILURE(status)) {
dataerrln("ERROR: Could not create PluralRules for testing fractions - exitting");
return;
}
double fData[] = {-101, -100, -1, -0.0, 0, 0.1, 1, 1.999, 2.0, 100, 100.001 };
UBool isKeywordA[] = {TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE };
for (int32_t i=0; i<UPRV_LENGTHOF(fData); i++) {
if ((newRules->select(fData[i])== KEYWORD_A) != isKeywordA[i]) {
errln("File %s, Line %d, ERROR: plural rules for decimal fractions test failed!\n"
" number = %g, expected %s", __FILE__, __LINE__, fData[i], isKeywordA[i]?"TRUE":"FALSE");
}
}
// ======= Test Equality
logln("Testing Equality of PluralRules");
if ( !testEquality(*test) ) {
errln("ERROR: complex plural rules failed! - exitting");
return;
}
// ======= Test getStaticClassID()
logln("Testing getStaticClassID()");
if(test->getDynamicClassID() != PluralRules::getStaticClassID()) {
errln("ERROR: getDynamicClassID() didn't return the expected value");
}
// ====== Test fallback to parent locale
LocalPointer<PluralRules> en_UK(test->forLocale(Locale::getUK(), status));
LocalPointer<PluralRules> en(test->forLocale(Locale::getEnglish(), status));
if (en_UK.isValid() && en.isValid()) {
if ( *en_UK != *en ) {
errln("ERROR: test locale fallback failed!");
}
}
LocalPointer<PluralRules> zh_Hant(test->forLocale(Locale::getTaiwan(), status));
LocalPointer<PluralRules> zh(test->forLocale(Locale::getChinese(), status));
if (zh_Hant.isValid() && zh.isValid()) {
if ( *zh_Hant != *zh ) {
errln("ERROR: test locale fallback failed!");
}
}
}
void setupResult(const int32_t testSource[], char result[], int32_t* max) {
int32_t i=0;
int32_t curIndex=0;
do {
while (curIndex < testSource[i]) {
result[curIndex++]=0x6F; //'o' other
}
result[curIndex++]=0x61; // 'a'
} while(testSource[++i]>0);
*max=curIndex;
}
UBool checkEqual(const PluralRules &test, char *result, int32_t max) {
UnicodeString key;
UBool isEqual = TRUE;
for (int32_t i=0; i<max; ++i) {
key= test.select(i);
if ( key.charAt(0)!=result[i] ) {
isEqual = FALSE;
}
}
return isEqual;
}
static const int32_t MAX_EQ_ROW = 2;
static const int32_t MAX_EQ_COL = 5;
UBool testEquality(const PluralRules &test) {
UnicodeString testEquRules[MAX_EQ_ROW][MAX_EQ_COL] = {
{ UNICODE_STRING_SIMPLE("a: n in 2..3"),
UNICODE_STRING_SIMPLE("a: n is 2 or n is 3"),
UNICODE_STRING_SIMPLE( "a:n is 3 and n in 2..5 or n is 2"),
"",
},
{ UNICODE_STRING_SIMPLE("a: n is 12; b:n mod 10 in 2..3"),
UNICODE_STRING_SIMPLE("b: n mod 10 in 2..3 and n is not 12; a: n in 12..12"),
UNICODE_STRING_SIMPLE("b: n is 13; a: n in 12..13; b: n mod 10 is 2 or n mod 10 is 3"),
"",
}
};
UErrorCode status = U_ZERO_ERROR;
UnicodeString key[MAX_EQ_COL];
UBool ret=TRUE;
for (int32_t i=0; i<MAX_EQ_ROW; ++i) {
PluralRules* rules[MAX_EQ_COL];
for (int32_t j=0; j<MAX_EQ_COL; ++j) {
rules[j]=NULL;
}
int32_t totalRules=0;
while((totalRules<MAX_EQ_COL) && (testEquRules[i][totalRules].length()>0) ) {
rules[totalRules]=test.createRules(testEquRules[i][totalRules], status);
totalRules++;
}
for (int32_t n=0; n<300 && ret ; ++n) {
for(int32_t j=0; j<totalRules;++j) {
key[j] = rules[j]->select(n);
}
for(int32_t j=0; j<totalRules-1;++j) {
if (key[j]!=key[j+1]) {
ret= FALSE;
break;
}
}
}
for (int32_t j=0; j<MAX_EQ_COL; ++j) {
if (rules[j]!=NULL) {
delete rules[j];
}
}
}
return ret;
}
void
PluralRulesTest::assertRuleValue(const UnicodeString& rule, double expected) {
assertRuleKeyValue("a:" + rule, "a", expected);
}
void
PluralRulesTest::assertRuleKeyValue(const UnicodeString& rule,
const UnicodeString& key, double expected) {
UErrorCode status = U_ZERO_ERROR;
PluralRules *pr = PluralRules::createRules(rule, status);
double result = pr->getUniqueKeywordValue(key);
delete pr;
if (expected != result) {
errln("expected %g but got %g", expected, result);
}
}
// TODO: UniqueKeywordValue() is not currently supported.
// If it never will be, this test code should be removed.
void PluralRulesTest::testGetUniqueKeywordValue() {
assertRuleValue("n is 1", 1);
assertRuleValue("n in 2..2", 2);
assertRuleValue("n within 2..2", 2);
assertRuleValue("n in 3..4", UPLRULES_NO_UNIQUE_VALUE);
assertRuleValue("n within 3..4", UPLRULES_NO_UNIQUE_VALUE);
assertRuleValue("n is 2 or n is 2", 2);
assertRuleValue("n is 2 and n is 2", 2);
assertRuleValue("n is 2 or n is 3", UPLRULES_NO_UNIQUE_VALUE);
assertRuleValue("n is 2 and n is 3", UPLRULES_NO_UNIQUE_VALUE);
assertRuleValue("n is 2 or n in 2..3", UPLRULES_NO_UNIQUE_VALUE);
assertRuleValue("n is 2 and n in 2..3", 2);
assertRuleKeyValue("a: n is 1", "not_defined", UPLRULES_NO_UNIQUE_VALUE); // key not defined
assertRuleKeyValue("a: n is 1", "other", UPLRULES_NO_UNIQUE_VALUE); // key matches default rule
}
void PluralRulesTest::testGetSamples() {
// TODO: fix samples, re-enable this test.
// no get functional equivalent API in ICU4C, so just
// test every locale...
UErrorCode status = U_ZERO_ERROR;
int32_t numLocales;
const Locale* locales = Locale::getAvailableLocales(numLocales);
double values[1000];
for (int32_t i = 0; U_SUCCESS(status) && i < numLocales; ++i) {
PluralRules *rules = PluralRules::forLocale(locales[i], status);
if (U_FAILURE(status)) {
break;
}
StringEnumeration *keywords = rules->getKeywords(status);
if (U_FAILURE(status)) {
delete rules;
break;
}
const UnicodeString* keyword;
while (NULL != (keyword = keywords->snext(status))) {
int32_t count = rules->getSamples(*keyword, values, UPRV_LENGTHOF(values), status);
if (U_FAILURE(status)) {
errln(UNICODE_STRING_SIMPLE("getSamples() failed for locale ") +
locales[i].getName() +
UNICODE_STRING_SIMPLE(", keyword ") + *keyword);
continue;
}
if (count == 0) {
// TODO: Lots of these.
// errln(UNICODE_STRING_SIMPLE("no samples for keyword ") + *keyword + UNICODE_STRING_SIMPLE(" in locale ") + locales[i].getName() );
}
if (count > UPRV_LENGTHOF(values)) {
errln(UNICODE_STRING_SIMPLE("getSamples()=") + count +
UNICODE_STRING_SIMPLE(", too many values, for locale ") +
locales[i].getName() +
UNICODE_STRING_SIMPLE(", keyword ") + *keyword);
count = UPRV_LENGTHOF(values);
}
for (int32_t j = 0; j < count; ++j) {
if (values[j] == UPLRULES_NO_UNIQUE_VALUE) {
errln("got 'no unique value' among values");
} else {
UnicodeString resultKeyword = rules->select(values[j]);
// if (strcmp(locales[i].getName(), "uk") == 0) { // Debug only.
// std::cout << " uk " << US(resultKeyword).cstr() << " " << values[j] << std::endl;
// }
if (*keyword != resultKeyword) {
errln("file %s, line %d, Locale %s, sample for keyword \"%s\": %g, select(%g) returns keyword \"%s\"",
__FILE__, __LINE__, locales[i].getName(), US(*keyword).cstr(), values[j], values[j], US(resultKeyword).cstr());
}
}
}
}
delete keywords;
delete rules;
}
}
void PluralRulesTest::testWithin() {
// goes to show you what lack of testing will do.
// of course, this has been broken for two years and no one has noticed...
UErrorCode status = U_ZERO_ERROR;
PluralRules *rules = PluralRules::createRules("a: n mod 10 in 5..8", status);
if (!rules) {
errln("couldn't instantiate rules");
return;
}
UnicodeString keyword = rules->select((int32_t)26);
if (keyword != "a") {
errln("expected 'a' for 26 but didn't get it.");
}
keyword = rules->select(26.5);
if (keyword != "other") {
errln("expected 'other' for 26.5 but didn't get it.");
}
delete rules;
}
void
PluralRulesTest::testGetAllKeywordValues() {
const char* data[] = {
"a: n in 2..5", "a: 2,3,4,5; other: null; b:",
"a: n not in 2..5", "a: null; other: null",
"a: n within 2..5", "a: null; other: null",
"a: n not within 2..5", "a: null; other: null",
"a: n in 2..5 or n within 6..8", "a: null", // ignore 'other' here on out, always null
"a: n in 2..5 and n within 6..8", "a:",
"a: n in 2..5 and n within 5..8", "a: 5",
"a: n within 2..5 and n within 6..8", "a:", // our sampling catches these
"a: n within 2..5 and n within 5..8", "a: 5", // ''
"a: n within 1..2 and n within 2..3 or n within 3..4 and n within 4..5", "a: 2,4",
"a: n within 1..2 and n within 2..3 or n within 3..4 and n within 4..5 "
"or n within 5..6 and n within 6..7", "a: null", // but not this...
"a: n mod 3 is 0", "a: null",
"a: n mod 3 is 0 and n within 1..2", "a:",
"a: n mod 3 is 0 and n within 0..5", "a: 0,3",
"a: n mod 3 is 0 and n within 0..6", "a: null", // similarly with mod, we don't catch...
"a: n mod 3 is 0 and n in 3..12", "a: 3,6,9,12",
NULL
};
for (int i = 0; data[i] != NULL; i += 2) {
UErrorCode status = U_ZERO_ERROR;
UnicodeString ruleDescription(data[i], -1, US_INV);
const char* result = data[i+1];
logln("[%d] %s", i >> 1, data[i]);
PluralRules *p = PluralRules::createRules(ruleDescription, status);
if (p == NULL || U_FAILURE(status)) {
errln("file %s, line %d: could not create rules from '%s'\n"
" ErrorCode: %s\n",
__FILE__, __LINE__, data[i], u_errorName(status));
continue;
}
// TODO: fix samples implementation, re-enable test.
(void)result;
#if 0
const char* rp = result;
while (*rp) {
while (*rp == ' ') ++rp;
if (!rp) {
break;
}
const char* ep = rp;
while (*ep && *ep != ':') ++ep;
status = U_ZERO_ERROR;
UnicodeString keyword(rp, ep - rp, US_INV);
double samples[4]; // no test above should have more samples than 4
int32_t count = p->getAllKeywordValues(keyword, &samples[0], 4, status);
if (U_FAILURE(status)) {
errln("error getting samples for %s", rp);
break;
}
if (count > 4) {
errln("count > 4 for keyword %s", rp);
count = 4;
}
if (*ep) {
++ep; // skip colon
while (*ep && *ep == ' ') ++ep; // and spaces
}
UBool ok = TRUE;
if (count == -1) {
if (*ep != 'n') {
errln("expected values for keyword %s but got -1 (%s)", rp, ep);
ok = FALSE;
}
} else if (*ep == 'n') {
errln("expected count of -1, got %d, for keyword %s (%s)", count, rp, ep);
ok = FALSE;
}
// We'll cheat a bit here. The samples happend to be in order and so are our
// expected values, so we'll just test in order until a failure. If the
// implementation changes to return samples in an arbitrary order, this test
// must change. There's no actual restriction on the order of the samples.
for (int j = 0; ok && j < count; ++j ) { // we've verified count < 4
double val = samples[j];
if (*ep == 0 || *ep == ';') {
errln("got unexpected value[%d]: %g", j, val);
ok = FALSE;
break;
}
char* xp;
double expectedVal = strtod(ep, &xp);
if (xp == ep) {
// internal error
errln("yikes!");
ok = FALSE;
break;
}
ep = xp;
if (expectedVal != val) {
errln("expected %g but got %g", expectedVal, val);
ok = FALSE;
break;
}
if (*ep == ',') ++ep;
}
if (ok && count != -1) {
if (!(*ep == 0 || *ep == ';')) {
errln("file: %s, line %d, didn't get expected value: %s", __FILE__, __LINE__, ep);
ok = FALSE;
}
}
while (*ep && *ep != ';') ++ep;
if (*ep == ';') ++ep;
rp = ep;
}
#endif
delete p;
}
}
void PluralRulesTest::testOrdinal() {
IcuTestErrorCode errorCode(*this, "testOrdinal");
LocalPointer<PluralRules> pr(PluralRules::forLocale("en", UPLURAL_TYPE_ORDINAL, errorCode));
if (errorCode.logIfFailureAndReset("PluralRules::forLocale(en, UPLURAL_TYPE_ORDINAL) failed")) {
return;
}
UnicodeString keyword = pr->select(2.);
if (keyword != UNICODE_STRING("two", 3)) {
dataerrln("PluralRules(en-ordinal).select(2) failed");
}
}
static const char * END_MARK = "999.999"; // Mark end of varargs data.
void PluralRulesTest::checkSelect(const LocalPointer<PluralRules> &rules, UErrorCode &status,
int32_t line, const char *keyword, ...) {
// The varargs parameters are a const char* strings, each being a decimal number.
// The formatting of the numbers as strings is significant, e.g.
// the difference between "2" and "2.0" can affect which rule matches (which keyword is selected).
// Note: rules parameter is a LocalPointer reference rather than a PluralRules * to avoid having
// to write getAlias() at every (numerous) call site.
if (U_FAILURE(status)) {
errln("file %s, line %d, ICU error status: %s.", __FILE__, line, u_errorName(status));
status = U_ZERO_ERROR;
return;
}
if (rules == NULL) {
errln("file %s, line %d: rules pointer is NULL", __FILE__, line);
return;
}
va_list ap;
va_start(ap, keyword);
for (;;) {
const char *num = va_arg(ap, const char *);
if (strcmp(num, END_MARK) == 0) {
break;
}
// DigitList is a convenient way to parse the decimal number string and get a double.
DigitList dl;
dl.set(StringPiece(num), status);
if (U_FAILURE(status)) {
errln("file %s, line %d, ICU error status: %s.", __FILE__, line, u_errorName(status));
status = U_ZERO_ERROR;
continue;
}
double numDbl = dl.getDouble();
const char *decimalPoint = strchr(num, '.');
int fractionDigitCount = decimalPoint == NULL ? 0 : (num + strlen(num) - 1) - decimalPoint;
int fractionDigits = fractionDigitCount == 0 ? 0 : atoi(decimalPoint + 1);
FixedDecimal ni(numDbl, fractionDigitCount, fractionDigits);
UnicodeString actualKeyword = rules->select(ni);
if (actualKeyword != UnicodeString(keyword)) {
errln("file %s, line %d, select(%s) returned incorrect keyword. Expected %s, got %s",
__FILE__, line, num, keyword, US(actualKeyword).cstr());
}
}
va_end(ap);
}
void PluralRulesTest::testSelect() {
UErrorCode status = U_ZERO_ERROR;
LocalPointer<PluralRules> pr(PluralRules::createRules("s: n in 1,3,4,6", status));
checkSelect(pr, status, __LINE__, "s", "1.0", "3.0", "4.0", "6.0", END_MARK);
checkSelect(pr, status, __LINE__, "other", "0.0", "2.0", "3.1", "7.0", END_MARK);
pr.adoptInstead(PluralRules::createRules("s: n not in 1,3,4,6", status));
checkSelect(pr, status, __LINE__, "other", "1.0", "3.0", "4.0", "6.0", END_MARK);
checkSelect(pr, status, __LINE__, "s", "0.0", "2.0", "3.1", "7.0", END_MARK);
pr.adoptInstead(PluralRules::createRules("r: n in 1..4, 7..10, 14 .. 17;"
"s: n is 29;", status));
checkSelect(pr, status, __LINE__, "r", "1.0", "3.0", "7.0", "8.0", "10.0", "14.0", "17.0", END_MARK);
checkSelect(pr, status, __LINE__, "s", "29.0", END_MARK);
checkSelect(pr, status, __LINE__, "other", "28.0", "29.1", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 is 1; b: n mod 100 is 0 ", status));
checkSelect(pr, status, __LINE__, "a", "1", "11", "41", "101", "301.00", END_MARK);
checkSelect(pr, status, __LINE__, "b", "0", "100", "200.0", "300.", "1000", "1100", "110000", END_MARK);
checkSelect(pr, status, __LINE__, "other", "0.01", "1.01", "0.99", "2", "3", "99", "102", END_MARK);
// Rules that end with or without a ';' and with or without trailing spaces.
// (There was a rule parser bug here with these.)
pr.adoptInstead(PluralRules::createRules("a: n is 1", status));
checkSelect(pr, status, __LINE__, "a", "1", END_MARK);
checkSelect(pr, status, __LINE__, "other", "2", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n is 1 ", status));
checkSelect(pr, status, __LINE__, "a", "1", END_MARK);
checkSelect(pr, status, __LINE__, "other", "2", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n is 1;", status));
checkSelect(pr, status, __LINE__, "a", "1", END_MARK);
checkSelect(pr, status, __LINE__, "other", "2", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n is 1 ; ", status));
checkSelect(pr, status, __LINE__, "a", "1", END_MARK);
checkSelect(pr, status, __LINE__, "other", "2", END_MARK);
// First match when rules for different keywords are not disjoint.
// Also try spacing variations around ':' and '..'
pr.adoptInstead(PluralRules::createRules("c: n in 5..15; b : n in 1..10 ;a:n in 10 .. 20", status));
checkSelect(pr, status, __LINE__, "a", "20", END_MARK);
checkSelect(pr, status, __LINE__, "b", "1", END_MARK);
checkSelect(pr, status, __LINE__, "c", "10", END_MARK);
checkSelect(pr, status, __LINE__, "other", "0", "21", "10.1", END_MARK);
// in vs within
pr.adoptInstead(PluralRules::createRules("a: n in 2..10; b: n within 8..15", status));
checkSelect(pr, status, __LINE__, "a", "2", "8", "10", END_MARK);
checkSelect(pr, status, __LINE__, "b", "8.01", "9.5", "11", "14.99", "15", END_MARK);
checkSelect(pr, status, __LINE__, "other", "1", "7.7", "15.01", "16", END_MARK);
// OR and AND chains.
pr.adoptInstead(PluralRules::createRules("a: n in 2..10 and n in 4..12 and n not in 5..7", status));
checkSelect(pr, status, __LINE__, "a", "4", "8", "9", "10", END_MARK);
checkSelect(pr, status, __LINE__, "other", "2", "3", "5", "7", "11", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n is 2 or n is 5 or n in 7..11 and n in 11..13", status));
checkSelect(pr, status, __LINE__, "a", "2", "5", "11", END_MARK);
checkSelect(pr, status, __LINE__, "other", "3", "4", "6", "8", "10", "12", "13", END_MARK);
// Number attributes -
// n: the number itself
// i: integer digits
// f: visible fraction digits
// t: f with trailing zeros removed.
// v: number of visible fraction digits
// j: = n if there are no visible fraction digits
// != anything if there are visible fraction digits
pr.adoptInstead(PluralRules::createRules("a: i is 123", status));
checkSelect(pr, status, __LINE__, "a", "123", "123.0", "123.1", "0123.99", END_MARK);
checkSelect(pr, status, __LINE__, "other", "124", "122.0", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: f is 120", status));
checkSelect(pr, status, __LINE__, "a", "1.120", "0.120", "11123.120", "0123.120", END_MARK);
checkSelect(pr, status, __LINE__, "other", "1.121", "122.1200", "1.12", "120", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: t is 12", status));
checkSelect(pr, status, __LINE__, "a", "1.120", "0.12", "11123.12000", "0123.1200000", END_MARK);
checkSelect(pr, status, __LINE__, "other", "1.121", "122.1200001", "1.11", "12", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: v is 3", status));
checkSelect(pr, status, __LINE__, "a", "1.120", "0.000", "11123.100", "0123.124", ".666", END_MARK);
checkSelect(pr, status, __LINE__, "other", "1.1212", "122.12", "1.1", "122", "0.0000", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: v is 0 and i is 123", status));
checkSelect(pr, status, __LINE__, "a", "123", "123.", END_MARK);
checkSelect(pr, status, __LINE__, "other", "123.0", "123.1", "123.123", "0.123", END_MARK);
// The reserved words from the rule syntax will also function as keywords.
pr.adoptInstead(PluralRules::createRules("a: n is 21; n: n is 22; i: n is 23; f: n is 24;"
"t: n is 25; v: n is 26; w: n is 27; j: n is 28"
, status));
checkSelect(pr, status, __LINE__, "other", "20", "29", END_MARK);
checkSelect(pr, status, __LINE__, "a", "21", END_MARK);
checkSelect(pr, status, __LINE__, "n", "22", END_MARK);
checkSelect(pr, status, __LINE__, "i", "23", END_MARK);
checkSelect(pr, status, __LINE__, "f", "24", END_MARK);
checkSelect(pr, status, __LINE__, "t", "25", END_MARK);
checkSelect(pr, status, __LINE__, "v", "26", END_MARK);
checkSelect(pr, status, __LINE__, "w", "27", END_MARK);
checkSelect(pr, status, __LINE__, "j", "28", END_MARK);
pr.adoptInstead(PluralRules::createRules("not: n=31; and: n=32; or: n=33; mod: n=34;"
"in: n=35; within: n=36;is:n=37"
, status));
checkSelect(pr, status, __LINE__, "other", "30", "39", END_MARK);
checkSelect(pr, status, __LINE__, "not", "31", END_MARK);
checkSelect(pr, status, __LINE__, "and", "32", END_MARK);
checkSelect(pr, status, __LINE__, "or", "33", END_MARK);
checkSelect(pr, status, __LINE__, "mod", "34", END_MARK);
checkSelect(pr, status, __LINE__, "in", "35", END_MARK);
checkSelect(pr, status, __LINE__, "within", "36", END_MARK);
checkSelect(pr, status, __LINE__, "is", "37", END_MARK);
// Test cases from ICU4J PluralRulesTest.parseTestData
pr.adoptInstead(PluralRules::createRules("a: n is 1", status));
checkSelect(pr, status, __LINE__, "a", "1", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 is 2", status));
checkSelect(pr, status, __LINE__, "a", "2", "12", "22", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n is not 1", status));
checkSelect(pr, status, __LINE__, "a", "0", "2", "3", "4", "5", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 3 is not 1", status));
checkSelect(pr, status, __LINE__, "a", "0", "2", "3", "5", "6", "8", "9", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n in 2..5", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n within 2..5", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n not in 2..5", status));
checkSelect(pr, status, __LINE__, "a", "0", "1", "6", "7", "8", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n not within 2..5", status));
checkSelect(pr, status, __LINE__, "a", "0", "1", "6", "7", "8", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 in 2..5", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", "12", "13", "14", "15", "22", "23", "24", "25", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 within 2..5", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", "12", "13", "14", "15", "22", "23", "24", "25", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 is 2 and n is not 12", status));
checkSelect(pr, status, __LINE__, "a", "2", "22", "32", "42", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 in 2..3 or n mod 10 is 5", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "5", "12", "13", "15", "22", "23", "25", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 within 2..3 or n mod 10 is 5", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "5", "12", "13", "15", "22", "23", "25", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n is 1 or n is 4 or n is 23", status));
checkSelect(pr, status, __LINE__, "a", "1", "4", "23", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 2 is 1 and n is not 3 and n in 1..11", status));
checkSelect(pr, status, __LINE__, "a", "1", "5", "7", "9", "11", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 2 is 1 and n is not 3 and n within 1..11", status));
checkSelect(pr, status, __LINE__, "a", "1", "5", "7", "9", "11", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 2 is 1 or n mod 5 is 1 and n is not 6", status));
checkSelect(pr, status, __LINE__, "a", "1", "3", "5", "7", "9", "11", "13", "15", "16", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n in 2..5; b: n in 5..8; c: n mod 2 is 1", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", END_MARK);
checkSelect(pr, status, __LINE__, "b", "6", "7", "8", END_MARK);
checkSelect(pr, status, __LINE__, "c", "1", "9", "11", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n within 2..5; b: n within 5..8; c: n mod 2 is 1", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", END_MARK);
checkSelect(pr, status, __LINE__, "b", "6", "7", "8", END_MARK);
checkSelect(pr, status, __LINE__, "c", "1", "9", "11", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n in 2, 4..6; b: n within 7..9,11..12,20", status));
checkSelect(pr, status, __LINE__, "a", "2", "4", "5", "6", END_MARK);
checkSelect(pr, status, __LINE__, "b", "7", "8", "9", "11", "12", "20", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n in 2..8, 12 and n not in 4..6", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "7", "8", "12", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n mod 10 in 2, 3,5..7 and n is not 12", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "5", "6", "7", "13", "15", "16", "17", END_MARK);
pr.adoptInstead(PluralRules::createRules("a: n in 2..6, 3..7", status));
checkSelect(pr, status, __LINE__, "a", "2", "3", "4", "5", "6", "7", END_MARK);
// Extended Syntax, with '=', '!=' and '%' operators.
pr.adoptInstead(PluralRules::createRules("a: n = 1..8 and n!= 2,3,4,5", status));
checkSelect(pr, status, __LINE__, "a", "1", "6", "7", "8", END_MARK);
checkSelect(pr, status, __LINE__, "other", "0", "2", "3", "4", "5", "9", END_MARK);
pr.adoptInstead(PluralRules::createRules("a:n % 10 != 1", status));
checkSelect(pr, status, __LINE__, "a", "2", "6", "7", "8", END_MARK);
checkSelect(pr, status, __LINE__, "other", "1", "21", "211", "91", END_MARK);
}
void PluralRulesTest::testAvailbleLocales() {
// Hash set of (char *) strings.
UErrorCode status = U_ZERO_ERROR;
UHashtable *localeSet = uhash_open(uhash_hashUnicodeString, uhash_compareUnicodeString, uhash_compareLong, &status);
uhash_setKeyDeleter(localeSet, uprv_deleteUObject);
if (U_FAILURE(status)) {
errln("file %s, line %d: Error status = %s", __FILE__, __LINE__, u_errorName(status));
return;
}
// Check that each locale returned by the iterator is unique.
StringEnumeration *localesEnum = PluralRules::getAvailableLocales(status);
int localeCount = 0;
for (;;) {
const char *locale = localesEnum->next(NULL, status);
if (U_FAILURE(status)) {
dataerrln("file %s, line %d: Error status = %s", __FILE__, __LINE__, u_errorName(status));
return;
}
if (locale == NULL) {
break;
}
localeCount++;
int32_t oldVal = uhash_puti(localeSet, new UnicodeString(locale), 1, &status);
if (oldVal != 0) {
errln("file %s, line %d: locale %s was seen before.", __FILE__, __LINE__, locale);
}
}
// Reset the iterator, verify that we get the same count.
localesEnum->reset(status);
int32_t localeCount2 = 0;
while (localesEnum->next(NULL, status) != NULL) {
if (U_FAILURE(status)) {
errln("file %s, line %d: Error status = %s", __FILE__, __LINE__, u_errorName(status));
break;
}
localeCount2++;
}
if (localeCount != localeCount2) {
errln("file %s, line %d: locale counts differ. They are (%d, %d)",
__FILE__, __LINE__, localeCount, localeCount2);
}
// Instantiate plural rules for each available locale.
localesEnum->reset(status);
for (;;) {
status = U_ZERO_ERROR;
const char *localeName = localesEnum->next(NULL, status);
if (U_FAILURE(status)) {
errln("file %s, line %d: Error status = %s, locale = %s",
__FILE__, __LINE__, u_errorName(status), localeName);
return;
}
if (localeName == NULL) {
break;
}
Locale locale = Locale::createFromName(localeName);
PluralRules *pr = PluralRules::forLocale(locale, status);
if (U_FAILURE(status)) {
errln("file %s, line %d: Error %s creating plural rules for locale %s",
__FILE__, __LINE__, u_errorName(status), localeName);
continue;
}
if (pr == NULL) {
errln("file %s, line %d: Null plural rules for locale %s", __FILE__, __LINE__, localeName);
continue;
}
// Pump some numbers through the plural rules. Can't check for correct results,
// mostly this to tickle any asserts or crashes that may be lurking.
for (double n=0; n<120.0; n+=0.5) {
UnicodeString keyword = pr->select(n);
if (keyword.length() == 0) {
errln("file %s, line %d, empty keyword for n = %g, locale %s",
__FILE__, __LINE__, n, localeName);
}
}
delete pr;
}
uhash_close(localeSet);
delete localesEnum;
}
void PluralRulesTest::testParseErrors() {
// Test rules with syntax errors.
// Creation of PluralRules from them should fail.
static const char *testCases[] = {
"a: n mod 10, is 1",
"a: q is 13",
"a n is 13",
"a: n is 13,",
"a: n is 13, 15, b: n is 4",
"a: n is 1, 3, 4.. ",
"a: n within 5..4",
"A: n is 13", // Uppercase keywords not allowed.
"a: n ! = 3", // spaces in != operator
"a: n = not 3", // '=' not exact equivalent of 'is'
"a: n ! in 3..4" // '!' not exact equivalent of 'not'
"a: n % 37 ! in 3..4"
};
for (int i=0; i<UPRV_LENGTHOF(testCases); i++) {
const char *rules = testCases[i];
UErrorCode status = U_ZERO_ERROR;
PluralRules *pr = PluralRules::createRules(UnicodeString(rules), status);
if (U_SUCCESS(status)) {
errln("file %s, line %d, expected failure with \"%s\".", __FILE__, __LINE__, rules);
}
if (pr != NULL) {
errln("file %s, line %d, expected NULL. Rules: \"%s\"", __FILE__, __LINE__, rules);
}
}
return;
}
void PluralRulesTest::testFixedDecimal() {
struct DoubleTestCase {
double n;
int32_t fractionDigitCount;
int64_t fractionDigits;
};
// Check that the internal functions for extracting the decimal fraction digits from
// a double value are working.
static DoubleTestCase testCases[] = {
{1.0, 0, 0},
{123456.0, 0, 0},
{1.1, 1, 1},
{1.23, 2, 23},
{1.234, 3, 234},
{1.2345, 4, 2345},
{1.23456, 5, 23456},
{.1234, 4, 1234},
{.01234, 5, 1234},
{.001234, 6, 1234},
{.0001234, 7, 1234},
{100.1234, 4, 1234},
{100.01234, 5, 1234},
{100.001234, 6, 1234},
{100.0001234, 7, 1234}
};
for (int i=0; i<UPRV_LENGTHOF(testCases); ++i) {
DoubleTestCase &tc = testCases[i];
int32_t numFractionDigits = FixedDecimal::decimals(tc.n);
if (numFractionDigits != tc.fractionDigitCount) {
errln("file %s, line %d: decimals(%g) expected %d, actual %d",
__FILE__, __LINE__, tc.n, tc.fractionDigitCount, numFractionDigits);
continue;
}
int64_t actualFractionDigits = FixedDecimal::getFractionalDigits(tc.n, numFractionDigits);
if (actualFractionDigits != tc.fractionDigits) {
errln("file %s, line %d: getFractionDigits(%g, %d): expected %ld, got %ld",
__FILE__, __LINE__, tc.n, numFractionDigits, tc.fractionDigits, actualFractionDigits);
}
}
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| mit |
jamescoineron/octane | src/qt/trafficgraphwidget.cpp | 176 | 4571 | #include "trafficgraphwidget.h"
#include "clientmodel.h"
#include <QPainter>
#include <QColor>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}
void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if(sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for(int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
if(fMax <= 0.0f) return;
QColor axisCol(Qt::gray);
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
const QString units = tr("KB/s");
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units));
for(float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if(fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units));
int count = 1;
for(float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if(count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if(!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if(!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while(vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while(vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
foreach(float f, vSamplesIn) {
if(f > tmax) tmax = f;
}
foreach(float f, vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if(clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
| mit |
herocodemaster/opencvr | 3rdparty/ffmpeg/libavcodec/eac3_data.c | 181 | 61257 | /*
* E-AC-3 tables
* Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Tables taken directly from the E-AC-3 spec.
*/
#include "eac3_data.h"
#include "ac3.h"
const uint8_t ff_eac3_bits_vs_hebap[20] = {
0, 2, 3, 4, 5, 7, 8, 9, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 14, 16,
};
/**
* Table E3.6, Gk=1
* No gain (Gk=1) inverse quantization, remapping scale factors
* ff_eac3_gaq_remap[hebap+8]
*/
const int16_t ff_eac3_gaq_remap_1[12] = {
4681, 2185, 1057, 520, 258, 129, 64, 32, 16, 8, 2, 0
};
/**
* Table E3.6, Gk=2 & Gk=4, A
* Large mantissa inverse quantization, remapping scale factors
* ff_eac3_gaq_remap_2_4_a[hebap-8][Gk=2,4]
*/
const int16_t ff_eac3_gaq_remap_2_4_a[9][2] = {
{ -10923, -4681 },
{ -14043, -6554 },
{ -15292, -7399 },
{ -15855, -7802 },
{ -16124, -7998 },
{ -16255, -8096 },
{ -16320, -8144 },
{ -16352, -8168 },
{ -16368, -8180 }
};
/**
* Table E3.6, Gk=2 & Gk=4, B
* Large mantissa inverse quantization, negative mantissa remapping offsets
* ff_eac3_gaq_remap_3_4_b[hebap-8][Gk=2,4]
*/
const int16_t ff_eac3_gaq_remap_2_4_b[9][2] = {
{ -5461, -1170 },
{ -11703, -4915 },
{ -14199, -6606 },
{ -15327, -7412 },
{ -15864, -7805 },
{ -16126, -7999 },
{ -16255, -8096 },
{ -16320, -8144 },
{ -16352, -8168 }
};
static const int16_t vq_hebap1[4][6] = {
{ 7167, 4739, 1106, 4269, 10412, 4820},
{ -5702, -3187, -14483, -1392, -2027, 849},
{ 633, 6199, 7009, -12779, -2306, -2636},
{ -1468, -7031, 7592, 10617, -5946, -3062},
};
static const int16_t vq_hebap2[8][6] = {
{ -12073, 608, -7019, 590, 4000, 869},
{ 6692, 15689, -6178, -9239, -74, 133},
{ 1855, -989, 20596, -2920, -4475, 225},
{ -1194, -3901, -821, -6566, -875, -20298},
{ -2762, -3181, -4094, -5623, -16945, 9765},
{ 1547, 6839, 1980, 20233, -1071, -4986},
{ 6221, -17915, -5516, 6266, 358, 1162},
{ 3753, -1066, 4283, -3227, 15928, 10186},
};
static const int16_t vq_hebap3[16][6] = {
{ -10028, 20779, 10982, -4560, 798, -68},
{ 11050, 20490, -6617, -5342, -1797, -1631},
{ 3977, -542, 7118, -1166, 18844, 14678},
{ -4320, -96, -7295, -492, -22050, -4277},
{ 2692, 5856, 5530, 21862, -7212, -5325},
{ -135, -23391, 962, 8115, -644, 382},
{ -1563, 3400, -3299, 4693, -6892, 22398},
{ 3535, 3030, 7296, 6214, 20476, -12099},
{ 57, -6823, 1848, -22349, -5919, 6823},
{ -821, -3655, -387, -6253, -1735, -22373},
{ -6046, 1586, -18890, -14392, 9214, 705},
{ -5716, 264, -17964, 14618, 7921, -337},
{ -110, 108, 8, 74, -89, -50},
{ 6612, -1517, 21687, -1658, -7949, -246},
{ 21667, -6335, -8290, -101, -1349, -22},
{ -22003, -6476, 7974, 648, 2054, -331},
};
static const int16_t vq_hebap4[32][6] = {
{ 6636, -4593, 14173, -17297, -16523, 864},
{ 3658, 22540, 104, -1763, -84, 6},
{ 21580, -17815, -7282, -1575, -2078, -320},
{ -2233, 10017, -2728, 14938, -13640, -17659},
{ -1564, -17738, -19161, 13735, 2757, 2951},
{ 4520, 5510, 7393, 10799, 19231, -13770},
{ 399, 2976, -1099, 5013, -1159, 22095},
{ 3624, -2359, 4680, -2238, 22702, 3765},
{ -4201, -8285, -6810, -12390, -18414, 15382},
{ -5198, -6869, -10047, -8364, -16022, -20562},
{ -142, -22671, -368, 4391, -464, -13},
{ 814, -1118, -1089, -22019, 74, 1553},
{ -1618, 19222, -17642, -13490, 842, -2309},
{ 4689, 16490, 20813, -15387, -4164, -3968},
{ -3308, 11214, -13542, 13599, -19473, 13770},
{ 1817, 854, 21225, -966, -1643, -268},
{ -2587, -107, -20154, 376, 1174, -304},
{ -2919, 453, -5390, 750, -22034, -978},
{ -19012, 16839, 10000, -3580, 2211, 1459},
{ 1363, -2658, -33, -4067, 1165, -21985},
{ -8592, -2760, -17520, -15985, 14897, 1323},
{ 652, -9331, 3253, -14622, 12181, 19692},
{ -6361, 5773, -15395, 17291, 16590, -2922},
{ -661, -601, 1609, 22610, 992, -1045},
{ 4961, 9107, 11225, 7829, 16320, 18627},
{ -21872, -1433, 138, 1470, -1891, -196},
{ -19499, -18203, 11056, -516, 2543, -2249},
{ -1196, -17574, 20150, 11462, -401, 2619},
{ 4638, -8154, 11891, -15759, 17615, -14955},
{ -83, 278, 323, 55, -154, 232},
{ 7788, 1462, 18395, 15296, -15763, -1131},
};
static const int16_t vq_hebap5[128][6] = {
{ -3394, -19730, 2963, 9590, 4660, 19673},
{ -15665, -6405, 17671, 3860, -8232, -19429},
{ 4467, 412, -17873, -8037, 691, -17307},
{ 3580, 2363, 6886, 3763, 6379, -20522},
{ -17230, -14133, -1396, -23939, 8373, -12537},
{ -8073, -21469, -15638, 3214, 8105, -5965},
{ 4343, 5169, 2683, -16822, -5146, -16558},
{ 6348, -10668, 12995, -25500, -22090, 4091},
{ -2880, -8366, -5968, -17158, -2638, 23132},
{ -5095, -14281, -22371, 21741, 3689, 2961},
{ -2443, -17739, 25155, 2707, 1594, 7},
{ -18379, 9010, 4270, 731, -426, -640},
{ -23695, 24732, 5642, 612, -308, -964},
{ -767, 1268, 225, 1635, 173, 916},
{ 5455, 6493, 4902, 10560, 23041, -17140},
{ 17219, -21054, -18716, 4936, -3420, 3357},
{ -1390, 15488, -21946, -14611, 1339, 542},
{ -6866, -2254, -12070, -3075, -19981, -20622},
{ -1803, 11775, 1343, 8917, 693, 24497},
{ -21610, 9462, 4681, 9254, -7815, 15904},
{ -5559, -3018, -9169, -1347, -22547, 12868},
{ -366, 5076, -1727, 20427, -283, -2923},
{ -1886, -6313, -939, -2081, -1399, 3513},
{ -3161, -537, -5075, 11268, 19396, 989},
{ 2345, 4153, 5769, -4273, 233, -399},
{ -21894, -1138, -16474, 5902, 5488, -3211},
{ 10007, -12530, 18829, 20932, -1158, 1790},
{ -1165, 5014, -1199, 6415, -8418, -21038},
{ 1892, -3534, 3815, -5846, 16427, 20288},
{ -2664, -11627, -4147, -18311, -22710, 14848},
{ 17256, 10419, 7764, 12040, 18956, 2525},
{ -21419, -18685, -10897, 4368, -7051, 4539},
{ -1574, 2050, 5760, 24756, 15983, 17678},
{ -538, -22867, 11067, 10301, 385, 528},
{ -8465, -3025, -16357, -23237, 16491, 3654},
{ 5840, 575, 11890, 1947, 25157, 6653},
{ 6625, -3516, -1964, 3850, -390, -116},
{ 18005, 20900, 14323, -7621, -10922, 11802},
{ -4857, -2932, -13334, -7815, 21622, 2267},
{ -579, -9431, -748, -21321, 12367, 8265},
{ -8317, 1375, -17847, 2921, 9062, 22046},
{ 18398, 8635, -1503, -2418, -18295, -14734},
{ -2987, 15129, -3331, 22300, 13878, -13639},
{ 5874, -19026, 15587, 11350, -20738, 1971},
{ 1581, -6955, -21440, 2455, 65, 414},
{ 515, -4468, -665, -4672, 125, -19222},
{ 21495, -20301, -1872, -1926, -211, -1022},
{ 5189, -12250, -1775, -23550, -4546, 5813},
{ 321, -6331, 14646, 6975, -1773, 867},
{ -13814, 3180, 7927, 444, 19552, 3146},
{ -6660, 12252, -1972, 17408, -24280, -12956},
{ -745, 14356, -1107, 23742, -9631, -18344},
{ 18284, -7909, -7531, 19118, 7721, -12659},
{ 1926, 15101, -12848, 2153, 21631, 1864},
{ -2130, 23416, 17056, -15597, -1544, 87},
{ 8314, -11824, 14581, -20591, 7891, -2099},
{ 19600, 22814, -17304, -2040, 285, -3863},
{ -8214, -18322, 10724, -13744, -13469, -1666},
{ 14351, 4880, -20034, 964, -4221, -180},
{ -24598, -16635, 19724, 5925, 4777, 4414},
{ -2495, 23493, -16141, 2918, -1038, -2010},
{ 18974, -2540, 13343, 1405, -6194, -1136},
{ 2489, 13670, 22638, -7311, -129, -2792},
{ -13962, 16775, 23012, 728, 3397, 162},
{ 3038, 993, 8774, -21969, -6609, 910},
{ -12444, -22386, -2626, -5295, 19520, 9872},
{ -1911, -18274, -18506, -14962, 4760, 7119},
{ 8298, -2978, 25886, 7660, -7897, 1020},
{ 6132, 15127, 18757, -24370, -6529, -6627},
{ 7924, 12125, -9459, -23962, 5502, 937},
{ -17056, -5373, 2522, 327, 1129, -390},
{ 15774, 19955, -10380, 11172, -3107, 14853},
{ -11904, -8091, -17928, -22287, -17237, -6803},
{ -12862, -2172, -6509, 5927, 12458, -22355},
{ -497, 322, 1038, -6643, -5404, 20311},
{ 1083, -22984, -8494, 12130, -762, 2623},
{ 5067, 19712, -1901, -30, -325, 85},
{ 987, -5830, 4212, -9030, 9121, -25038},
{ -7868, 7284, -12292, 12914, -21592, 20941},
{ -1630, -7694, -2187, -8525, -5604, -25196},
{ -6668, 388, -22535, 1526, 9082, 193},
{ -7867, -22308, 5163, 362, 944, -259},
{ 3824, -11850, 7591, -23176, 25342, 23771},
{ -10504, 4123, -21111, 21173, 22439, -838},
{ -4723, 21795, 6184, -122, 1642, -717},
{ 24504, 19887, -2043, 986, 7, -55},
{ -27313, -135, 2437, 259, 89, 307},
{ 24446, -3873, -5391, -820, -2387, 361},
{ 5529, 5784, 18682, 242, -21896, -4003},
{ 22304, 4483, 722, -12242, 7570, 15448},
{ 8673, 3009, 20437, 21108, -21100, -3080},
{ -1132, 2705, -1825, 5420, -785, 18532},
{ 16932, -13517, -16509, -14858, -20327, -14221},
{ 2219, 1380, 21474, -1128, 327, 83},
{ -2177, 21517, -3856, -14180, -204, -2191},
{ 953, -9426, 15874, -10710, -3231, 21030},
{ -421, -1377, 640, -8239, -20976, 2174},
{ 4309, 18514, -9100, -18319, -15518, 3704},
{ -5943, 449, -8387, 1075, -22210, -4992},
{ 2953, 12788, 18285, 1430, 14937, 21731},
{ -2913, 401, -4739, -20105, 1699, -1147},
{ 3449, 5241, 8853, 22134, -7547, 1451},
{ -2154, 8584, 18120, -15614, 19319, -5991},
{ 3501, 2841, 5897, 6397, 8630, 23018},
{ 2467, 2956, 379, 5703, -22047, -2189},
{ -16963, -594, 18822, -5295, 1640, 774},
{ 2896, -1424, 3586, -2292, 19910, -1822},
{ -18575, 21219, -14001, -12573, 16466, 635},
{ -1998, -19314, -16527, 12208, -16576, -7854},
{ -9674, 1012, -21645, 2883, -12712, 2321},
{ -1005, 471, -3629, 8045, -11087, 25533},
{ 4141, -21472, -2673, 756, -663, -523},
{ 6490, 8531, 19289, 18949, 6092, -9347},
{ 16965, 24599, 14024, 10072, -536, -10438},
{ -8147, 2145, -23028, -17073, 5451, -4401},
{ -14873, 20520, -18303, -9717, -11885, -17831},
{ -2290, -14120, 2070, 22467, 1671, 725},
{ -8538, 14629, 3521, -20577, 6673, 8200},
{ 20248, 4410, -1366, -585, 1229, -2449},
{ 7467, -7148, 13667, -8246, 22392, -17320},
{ -1932, 3875, -9064, -3812, 958, 265},
{ -4399, 2959, -15911, 19598, 4954, -1105},
{ 18009, -9923, -18137, -3862, 11178, 5821},
{ -14596, -1227, 9660, 21619, 11228, -11721},
{ -721, -1700, 109, -2142, 61, -6772},
{ -24619, -22520, 5608, -1957, -1761, -1012},
{ -23728, -4451, -2688, -14679, -4266, 9919},
{ 8495, -894, 20438, -13820, -17267, 139},
};
static const int16_t vq_hebap6[256][6] = {
{ 10154, 7365, 16861, 18681, -22893, -3636},
{ -2619, -3788, -5529, -5192, -9009, -20298},
{ -5583, -22800, 21297, 7012, 745, 720},
{ 428, -1459, 109, -3082, 361, -8403},
{ 8161, 22401, 241, 1755, -874, -2824},
{ 1140, 12643, 2306, 22263, -25146, -17557},
{ -2609, 3379, 10337, -19730, -15468, -23944},
{ -4040, -12796, -25772, 13096, 3905, 1315},
{ 4624, -23799, 13608, 25317, -1175, 2173},
{ -97, 13747, -5122, 23255, 4214, -22145},
{ 6878, -322, 18264, -854, -11916, -733},
{ 17280, -12669, -9693, 23563, -16240, -1309},
{ 5802, -4968, 19526, -21194, -24622, -183},
{ 5851, -16137, 15229, -9496, -1538, 377},
{ 14096, 25057, 13419, 8290, 23320, 16818},
{ -7261, 118, -15867, 19097, 9781, -277},
{ -4288, 21589, -13288, -16259, 16633, -4862},
{ 4909, -19217, 23411, 14705, -722, 125},
{ 19462, -4732, -1928, -11527, 20770, 5425},
{ -27562, -2881, -4331, 384, -2103, 1367},
{ -266, -9175, 5441, 26333, -1924, 4221},
{ -2970, -20170, -21816, 5450, -7426, 5344},
{ -221, -6696, 603, -9140, 1308, -27506},
{ 9621, -8380, -1967, 9403, -1651, 22817},
{ 7566, -5250, -4165, 1385, -990, 560},
{ -1262, 24738, -19057, 10741, 7585, -7098},
{ 451, 20130, -9949, -6015, -2188, -1458},
{ 22249, 9380, 9096, 10959, -2365, -3724},
{ 18668, -650, -1234, 11092, 7678, 5969},
{ 19207, -1485, -1076, -731, -684, 43},
{ -4973, 13430, 20139, 60, 476, -935},
{ -20029, 8710, 2499, 1016, -1158, 335},
{ -26413, 18598, -2201, -669, 3409, 793},
{ -4726, 8875, -24607, -9646, 3643, -283},
{ 13303, -21404, -3691, -1184, -1970, 1612},
{ 173, 60, 919, 1229, 6942, -665},
{ 16377, 16991, 5341, -14015, -2304, -20390},
{ 25334, -10609, 11947, -7653, -6363, 14058},
{ 23929, -13259, -7226, -937, 234, -187},
{ 6311, -1877, 12506, -1879, 18751, -23341},
{ 621, 6445, 3354, -24274, 8406, 5315},
{ -3297, -5034, -4704, -5080, -25730, 5347},
{ -1275, -13295, -965, -23318, 1214, 26259},
{ -6252, 10035, -20105, 15301, -16073, 5136},
{ 9562, -3911, -19510, 4745, 22270, -4171},
{ 7978, -19600, 14024, -5745, -20855, 8939},
{ 7, -4039, 991, -6065, 52, -19423},
{ 3485, 2969, 7732, 7786, 25312, 6206},
{ -959, -12812, -1840, -22743, 7324, 10830},
{ -4686, 1678, -10172, -5205, 4294, -1271},
{ 3889, 1302, 7450, 638, 20374, -3133},
{ -12496, -9123, 18463, -12343, -7238, 18552},
{ -6185, 8649, -6903, -895, 17109, 16604},
{ -9896, 28579, 2845, 1640, 2925, -298},
{ 14968, -25988, 14878, -24012, 1815, -6474},
{ 26107, 5166, 21225, 15873, 21617, 14825},
{ -21684, 16438, 20504, -14346, -7114, -4162},
{ 28647, 90, -1572, 789, -902, -75},
{ -1479, 2471, -4061, 3612, -2240, 10914},
{ 8616, 17491, 17255, -17456, 17022, -16357},
{ -20722, -18597, 25274, 17720, -3573, 1695},
{ -997, 6129, -6303, 11250, -11359, -19739},
{ -74, -4001, -1584, 13384, 162, -144},
{ -529, 21068, 7923, -11396, 422, -26},
{ 7102, -13531, -20055, 2629, -178, -429},
{ 9201, 1368, -22238, 2623, -20499, 24889},
{ -432, 6675, -266, 8723, 80, 28024},
{ 19493, -3108, -9261, 1910, -21777, 5345},
{ 14079, -11489, 12604, 6079, 19877, 1315},
{ 10947, 9837, -18612, 15742, 4792, 605},
{ -1777, 3758, -4087, 21696, 6024, -576},
{ 3567, -3578, 16379, 2680, -1752, 716},
{ -5049, -1399, -4550, -652, -17721, -3366},
{ -3635, -4372, -6522, -22152, 7382, 1458},
{ 12242, 19190, 5646, -7815, -20289, 21344},
{ -7508, 19952, 23542, -9753, 5669, -1990},
{ -2275, 15438, 10907, -17879, 6497, 13582},
{ -15894, -15646, -4716, 6019, 24250, -6179},
{ -2049, -6856, -1208, 918, 17735, -69},
{ -3721, 9099, -16065, -23621, 5981, -2344},
{ 7862, -8918, 24033, 25508, -11033, -741},
{ -12588, 19468, 14649, 15451, -21226, 1171},
{ 2102, 1147, 2789, 4096, 2179, 8750},
{ -18214, -17758, -10366, -5203, -1066, -3541},
{ -2819, -19958, -11921, 6032, 8315, 10374},
{ -9078, -2100, 19431, -17, 732, -689},
{ -14512, -19224, -7095, 18727, 1870, 22906},
{ 3912, 659, 25597, -4006, 9619, 877},
{ 2616, 22695, -5770, 17920, 3812, 20220},
{ 2561, 26847, -5245, -10908, 2256, -517},
{ -4974, 198, -21983, -3608, 22174, -18924},
{ 21308, -1211, 19144, 16691, -1588, 11390},
{ -1790, 3959, -3488, 7003, -7107, 20877},
{ -6108, -17955, -18722, 24763, 16508, 3211},
{ 20462, -24987, -20361, 4484, -5111, -478},
{ -6378, -1998, -10229, -561, -22039, -22339},
{ 3047, -18850, 7586, 14743, -19862, 6351},
{ -5047, 1405, -9672, 1055, -21881, 11170},
{ 3481, -9699, 6526, -16655, 22813, 21907},
{ -18570, 17501, 14664, 1291, 5026, 19676},
{ 16134, -19810, -16956, -17939, -16933, 5800},
{ -8224, 4908, 8935, 2272, -1140, -23217},
{ 1572, 2753, -1598, 2143, -3346, -21926},
{ -9832, -1060, -27818, 1214, 7289, 150},
{ 98, 1538, 535, 17429, -23198, -901},
{ 21340, -20146, 3297, -1744, -8207, -21462},
{ -4166, -4633, -17902, 5478, 1285, 136},
{ 18713, 21003, 24818, 11421, 1282, -4618},
{ -3535, 7636, -265, 2141, -829, -2035},
{ -3184, 19713, 2775, -2, 1090, 104},
{ -6771, -20185, 2938, -2125, -36, 1268},
{ 9560, 9430, 9586, 22100, 13827, 6296},
{ -535, -20018, 4276, -1868, -448, -17183},
{ -24352, 14244, -13647, -21040, 2271, 11555},
{ -2646, 15437, -4589, 18638, -4299, -622},
{ -20064, 4169, 18115, -1404, 13722, -1825},
{ -16359, 9080, 744, 22021, 125, 10794},
{ 9644, -14607, -18479, -14714, 11174, -20754},
{ -326, -23762, 6144, 7909, 602, 1540},
{ -6650, 6634, -12683, 21396, 20785, -6839},
{ 4252, -21043, 5628, 18687, 23860, 8328},
{ 17986, 5704, -5245, -18093, -555, 3219},
{ 6091, 14232, -5117, -17456, -19452, -11649},
{ -21586, 11302, 15434, 25590, 6777, -26683},
{ 21355, -8244, 5877, -3540, 6079, -2567},
{ 2603, -2455, 5421, -12286, -19100, 5574},
{ -1721, -26393, -23664, 22904, -349, 3787},
{ 2189, -1203, 5340, 3249, -22617, 104},
{ -1664, -11020, -2857, -20723, -24049, 19900},
{ 22873, -7345, -18481, -14616, -8400, -12965},
{ 3777, 3958, 8239, 20494, -6991, -1201},
{ -160, -1613, -793, -8681, 573, 776},
{ 4297, -3786, 20373, 6082, -5321, -18400},
{ 18745, 2463, 12546, -7749, -7734, -2183},
{ 11074, -4720, 22119, 1825, -24351, 4080},
{ 1503, -19178, -1569, 13, -313, 375},
{ 318, -575, 2544, 178, 102, 40},
{ -15996, -26897, 5008, 3320, 686, 1159},
{ 25755, 26886, 574, -5930, -3916, 1407},
{ -9148, -7665, -2875, -8384, -18663, 26400},
{ -7445, -18040, -18396, 8802, -2252, -21886},
{ 7851, 11773, 27485, -12847, -1410, 19590},
{ 2240, 5947, 11247, 15980, -6499, 24280},
{ 21673, -18515, 9771, 6550, -2730, 334},
{ -4149, 1576, -11010, 89, -24429, -5710},
{ 7720, 1478, 21412, -25025, -8385, 9},
{ -2448, 10218, -12756, -16079, 1161, -21284},
{ -8757, -14429, -22918, -14812, 2629, 13844},
{ -7252, 2843, -9639, 2882, -14625, 24497},
{ -674, -6530, 414, -23333, -21343, 454},
{ 2104, -6312, 10887, 18087, -1199, 175},
{ -493, -562, -2739, 118, -1074, 93},
{ -10011, -4075, -28071, 22180, 15077, -636},
{ -4637, -16408, -9003, -20418, -11608, -20932},
{ 4815, 15892, 24238, -13634, -3074, -1059},
{ -6724, 4610, -18772, -15283, -16685, 23988},
{ 15349, -674, -3682, 21679, 4475, -12088},
{ 4756, 2593, 5354, 6001, 15063, 26490},
{ -23815, -17251, 6944, 378, 694, 670},
{ 23392, -8839, -14713, 7544, -876, 11088},
{ 3640, 3336, 22593, -3495, -2328, -113},
{ 284, 6914, 3097, 10171, 6638, -18621},
{ 2472, 5976, 11054, -11936, -603, -663},
{ 16175, 16441, 13164, -4043, 4667, 7431},
{ 19338, 15534, -6533, 1681, -4857, 17048},
{ 17027, 532, -19064, -1441, -5130, 1085},
{ -12617, -17609, 2062, -25332, 19009, -16121},
{ 10056, -21000, -13634, -2949, 15367, 19934},
{ -648, -1605, 10046, -1592, 13296, 19808},
{ -1054, 10744, 538, 24938, 9630, -9052},
{ -10099, 3042, -25076, -24052, 13971, 100},
{ 6547, 6907, 7031, 10348, 23775, -17886},
{ -22793, -1984, -1393, -3330, 9267, 14317},
{ -14346, -3967, 3042, 16254, -17303, 9646},
{ -21393, 23628, 16773, 716, 2663, 114},
{ -19016, -3038, 1574, -245, 1463, -793},
{ 22410, 23441, -14637, -530, 17310, 13617},
{ -11582, 7935, -13954, 23465, -24628, 26550},
{ -1045, 3679, -2218, 10572, 20999, -3702},
{ -15513, 197, 16718, -24603, 4945, 5},
{ 10781, 4335, 26790, -9059, -16152, -2840},
{ 16075, -24100, -3933, -6833, 12645, -7029},
{ 2096, -25572, -8370, 6814, 11, 1178},
{ -11848, -583, -8889, -20543, -10471, -380},
{ -2487, 24777, -21639, -19341, 1660, -732},
{ 2313, 13679, 4085, 24549, 24691, -21179},
{ -2366, -504, -4130, -10570, 23668, 1961},
{ 20379, 17809, -9506, 3733, -18954, -6292},
{ -3856, 16802, -929, -20310, -17739, 6797},
{ 12431, 6078, -11272, -14450, 6913, 23476},
{ 7636, -1655, 23017, 10719, -8292, 838},
{ -8559, -1235, -18096, 3897, 16093, 1490},
{ -3586, 8276, 15165, -3791, -21149, 1741},
{ -4497, 21739, 2366, -278, -4792, 15549},
{ -23122, -13708, 7668, 16232, 24120, 15025},
{ -20043, 12821, -20160, 16691, -11655, -16081},
{ -12601, 20239, 3496, -2549, -6745, -11850},
{ 4441, 7812, 20783, 17080, 11523, -9643},
{ 24766, 8494, -23298, -3262, 11101, -7120},
{ -10107, -7623, -22152, -18303, 26645, 9550},
{ -25549, 477, 7874, -1538, 1123, -168},
{ 470, 9834, -347, 23945, -10381, -9467},
{ -4096, -9702, -6856, -21544, 20845, 7174},
{ 5370, 9748, -23765, -1190, 512, -1538},
{ -1006, -10046, -12649, 19234, -1790, -890},
{ 15108, 23620, -15646, -2522, -1203, -1325},
{ -7406, -2605, 1095, -247, -473, 177},
{ 8089, 4, 12424, -22284, 10405, -7728},
{ 22196, 10775, -5043, 690, 534, -212},
{ -3153, -1418, -16835, 18426, 15821, 22956},
{ 5681, -2229, 3196, -3414, -21817, -14807},
{ 19, 787, 1032, 170, -8295, -645},
{ -882, -2319, -27105, 432, -4392, 1499},
{ -1354, -11819, -76, -20380, -10293, 11328},
{ 211, -4753, -4675, -6933, -13538, 14479},
{ 6043, 5260, -459, -462, 143, -65},
{ -2572, 7256, -3317, 9212, -23184, -9990},
{ -24882, -9532, 18874, 6101, 2429, -14482},
{ 8314, 2277, 14192, 3512, 25881, 22000},
{ 208, 20218, -281, -24778, -63, -1183},
{ 1095, -6034, 2706, -21935, -2655, 563},
{ 23, -5930, 243, -8989, 5345, 20558},
{ -15466, 12699, 4160, 11087, 20621, -10416},
{ 20995, -85, -8468, 194, 1003, -9515},
{ -19637, -3335, -14081, 3574, -23381, -667},
{ -2076, 3489, -3192, -19367, 539, -1530},
{ 7352, -15213, 22596, 19369, 1043, 16627},
{ -1872, -413, 1235, -5276, -3550, 21903},
{ 7931, -2008, 16968, -6799, 29393, -2475},
{ -13589, 8389, -23636, -22091, -14178, -14297},
{ -11575, -20090, 16056, -1848, 15721, 4500},
{ 3849, -16581, 20161, -21155, 7778, 11864},
{ -6547, -1273, -18837, -11218, 11636, 1044},
{ 2528, -6691, -17917, -11362, -4894, -1008},
{ 1241, 4260, 2319, 6111, 3485, 20209},
{ 3014, -3048, 5316, -4539, 20831, 8702},
{ -1790, -14683, 278, 13956, -10065, -10547},
{ -22732, -7957, -1154, 13821, -1484, -1247},
{ -7317, -615, 13094, 18927, 9897, 1452},
{ 2552, -2338, 3424, -4630, 11124, -19584},
{ -11125, -20553, -10855, -10783, -20767, 6833},
{ 984, -15095, 5775, 25125, 5377, -19799},
{ 517, 13272, -7458, -1711, 20612, -6013},
{ -21417, 13251, -20795, 13449, 17281, 13104},
{ -15811, -16248, 23093, -4037, -8195, 871},
{ 582, 12571, -21129, -14766, -9187, 5685},
{ 4318, -1776, 11425, -17763, -9921, 577},
{ 6013, 16830, 17655, -25766, -4400, -3550},
{ -13744, -16541, 3636, -3330, -21091, -15886},
{ 6565, -11147, 8649, -13114, 23345, -13565},
{ -2542, -9046, -7558, 29240, 3701, -383},
{ -10612, 24995, 1893, -8210, 20920, -16210},
{ 5276, 16726, 10659, 19940, -4799, -19324},
{ -532, -9300, 27856, 4965, -241, 536},
{ -765, -20706, -3412, 18870, 2765, 1420},
{ -3059, 2708, -19022, -331, 3537, 116},
};
static const int16_t vq_hebap7[512][6] = {
{ -21173, 21893, 10390, 13646, 10718, -9177},
{ -22519, -8193, 18328, -6629, 25518, -10848},
{ 6800, -13758, -13278, 22418, 14667, -20938},
{ 2347, 10516, 1125, -3455, 5569, 27136},
{ -6617, 11851, -24524, 22937, 20362, -6019},
{ -21768, 10681, -19615, -15021, -8478, -2081},
{ -2745, 8684, -4895, 27739, 7554, -11961},
{ -1020, 2460, -954, 4754, -627, -16368},
{ -19702, 23097, 75, -13684, -2644, 2108},
{ 4049, -2872, 5851, -4459, 22150, 12560},
{ -21304, -17129, -730, 7419, -11658, -10523},
{ 11332, 1792, 26666, 23518, -19561, -491},
{ -17827, -16777, -13606, -14389, -22029, -2464},
{ 1091, -5967, -7975, -16977, -20432, -21931},
{ 18388, -1103, 1933, 13342, -17463, 18114},
{ 22646, 17345, -9966, 17919, 18274, 698},
{ 1484, 20297, -5754, -26515, 4941, -22263},
{ -2603, 4587, -5842, 18464, 8767, -2568},
{ -2797, -1602, 21713, 3099, -25683, 3224},
{ -19027, 4693, -5007, 6060, 1972, -15095},
{ -2189, 9516, -530, 20669, -4662, -8301},
{ -22325, -8887, 2529, -11352, 5476, 998},
{ 22100, -5052, 1651, -2657, 4615, 2319},
{ 20855, -3078, -3330, 4105, 13470, 3069},
{ 85, 17289, 10264, -14752, 214, 90},
{ -26365, -18849, -19352, 19244, -10218, 9909},
{ -9739, 20497, -6579, -6983, 2891, -738},
{ 20575, -15860, -22913, 6870, 76, 327},
{ 8744, -12877, -22945, -2372, -19424, -9771},
{ -12886, 16183, 21084, 3821, 749, -13792},
{ -15995, 18399, 2391, -17661, 19484, -6018},
{ 1423, 11734, 4051, 19290, 6857, -19681},
{ -5200, 9766, 18246, 2463, 18764, -4852},
{ -597, 19498, 1323, -9096, -308, -1104},
{ -3099, -25731, -15665, 25332, 4634, 2635},
{ 19623, -2384, -7913, 11796, -9333, -14084},
{ 2642, 26453, -21091, -10354, -1693, -1711},
{ 22031, 21625, 11580, -22915, -4141, 129},
{ -6122, 3542, 915, -261, -17, -383},
{ 1696, 6704, -1425, 20838, 857, -4416},
{ 1423, -15280, -8550, -9667, 5210, 5687},
{ -4520, -613, -11683, 5618, 4230, 619},
{ 937, -4963, -14102, -17104, -6906, -5952},
{ -15068, -481, -7237, -14894, 18876, 21673},
{ -25658, 2910, 1143, -327, -458, -995},
{ -9656, -819, -24900, 2804, 20225, 1083},
{ -1111, -3682, -1788, -19492, 966, 821},
{ 7293, -21759, 10790, -7059, -23293, -1723},
{ -282, -11093, 170, -20950, -28926, 12615},
{ 17938, 3713, -1563, 885, 5, 564},
{ 6116, 22696, 2242, -6951, 9975, -6132},
{ 4338, 26808, -3705, 1976, -1079, -2570},
{ -661, -7901, -2668, -15194, 17722, 4375},
{ -4174, -11053, 717, -22506, 1562, 12252},
{ -6405, 18334, 6103, 6983, 5956, 18195},
{ 9851, 5370, 23604, -6861, -6569, -62},
{ 21964, 13359, -683, 3785, 2168, 209},
{ -3569, -1127, -19724, -1544, 1308, -803},
{ -3083, 16049, -13791, -3077, 4294, 23713},
{ -9999, 9943, -15872, 12934, -23631, 21699},
{ 9722, 22837, 12192, 15091, 5533, 4837},
{ 2243, 2099, 1243, 4089, 4748, 12956},
{ 4007, -2468, 3353, -3092, 8843, 17024},
{ 4330, 6127, 5549, 9249, 11226, 28592},
{ -9586, -8825, 236, 1009, 455, -964},
{ 6829, 19290, -1018, 200, 1821, 578},
{ 5196, 957, 10372, 3330, -12800, -127},
{ -3022, -8193, -14557, 22061, 5920, 1053},
{ 10982, 25942, -24546, -23278, -11905, -6789},
{ 22667, -11010, 5736, 2567, 23705, -10253},
{ -3343, -4233, -5458, 20667, -10843, -3605},
{ -4131, -3612, 4575, -829, -350, -847},
{ -3303, 3451, -7398, -11604, 3023, 455},
{ 3200, -9547, 3202, -22893, 11184, -26466},
{ -14093, -4117, 15382, 14295, -10915, -20377},
{ 3807, -11016, 22052, 14370, -15328, -7733},
{ -6291, -17719, -1560, 12048, -19805, -443},
{ -6147, -4234, -160, 8363, 22638, 11911},
{ 19197, 1175, 7422, -9875, -4136, 4704},
{ -72, -7652, -112, -11955, -3230, 27175},
{ 3274, 5963, 7501, -17019, 866, -25452},
{ 737, 1861, 1833, 2022, 2384, 4755},
{ -5217, 7512, 3323, 2715, 3065, -1606},
{ 4247, 565, 5629, 2497, 18019, -4920},
{ -2833, -17920, -8062, 15738, -1018, 2136},
{ 3050, -19483, 16930, 29835, -10222, 15153},
{ -11346, 118, -25796, -13761, 15320, -468},
{ -4824, 4960, -4263, 1575, -10593, 19561},
{ -8203, -1409, -763, -1139, -607, 1408},
{ -2203, -11415, 2021, -6388, -2600, 711},
{ -413, -2511, -216, -3519, -28267, 1719},
{ -14446, 17050, 13917, 13499, -25762, -16121},
{ 19228, 7341, -12301, 682, -3791, -199},
{ -4193, 20746, -15651, 11349, 5860, -824},
{ -21490, -3546, -3, -1705, -3959, 9213},
{ 15445, -1876, 2012, -19627, 16228, -4845},
{ -2867, -3733, -7354, -175, -20119, 11174},
{ -3571, -24587, 19700, 6654, 979, -654},
{ 21820, -7430, -6639, -10767, -8362, 15543},
{ 14827, 17977, -7204, -3409, 1906, -17288},
{ 3525, -3947, -1415, -2798, 17648, 2082},
{ -6580, -15255, -17913, 1337, 15338, 21158},
{ 6210, 9698, 15155, -24666, -22507, -3999},
{ -1740, -593, 1095, -7779, 25058, 5601},
{ 21415, -432, -1658, -6898, -1438, -14454},
{ -6943, 700, -12139, -745, -24187, 22466},
{ 6287, 3283, 11006, 3844, 19184, 14781},
{ -22502, 15274, 5443, -2808, -970, -3343},
{ 3257, -3708, 4744, -8301, 22814, -10208},
{ 24346, -20970, 19846, 987, -11958, -6277},
{ 3906, -19701, 13060, -1609, 18641, 7466},
{ -26409, -22549, 16305, 2014, 10975, 18032},
{ -7039, 4655, -14818, 18739, 15789, 1296},
{ 9310, -1681, 14667, -3326, 26535, -11853},
{ 5728, 5917, 13400, 10020, -2236, -24704},
{ 1741, -6727, 12695, -22009, 4080, 5450},
{ -2621, 9393, 21143, -25938, -3162, -2529},
{ 20672, 18894, -13939, 6990, -8260, 15811},
{ -23818, 11183, -13639, 11868, 16045, 2630},
{ 18361, -10220, 829, 856, -1010, 157},
{ 14400, -4678, 5153, -13290, -27434, -11028},
{ 21613, 11256, 17453, 7604, 13130, -484},
{ 7, 1236, 573, 4214, 5576, -3081},
{ 916, -9092, 1285, -8958, 1185, -28699},
{ 21587, 23695, 19116, -2885, -14282, -8438},
{ 23414, -6161, 12978, 3061, -9351, 2236},
{ -3070, -7344, -20140, 5788, 582, -551},
{ -3993, 315, -7773, 8224, -28082, -12465},
{ 13766, -15357, 19205, -20624, 13043, -19247},
{ 3777, -177, 8029, -1001, 17812, 5162},
{ -7308, -4327, -18096, -620, -1350, 14932},
{ 14756, -1221, -12819, -14922, -547, 27125},
{ 2234, 1708, 2764, 5416, 7986, -25163},
{ 2873, 3636, 3992, 5344, 10142, 21259},
{ 1158, 5379, 508, -10514, 290, -1615},
{ 1114, 24789, 16575, -25168, -298, -2832},
{ -1107, -6144, -1918, -7791, -2971, -23276},
{ 4016, 10793, 17317, -4342, -20982, -3383},
{ -4494, -207, -9951, -3575, 7947, 1154},
{ -7576, 8117, -14047, 16982, -26457, -27540},
{ -15164, 16096, -16844, -8886, -23720, 15906},
{ 24922, 5680, -1874, 420, 132, 117},
{ -506, -19310, -198, 412, -311, 752},
{ -1906, 3981, -7688, 16566, -19291, -14722},
{ -399, -729, -3807, -4196, -12395, 7639},
{ 3368, 2330, 9092, 23686, -10290, -1705},
{ -3148, 2596, -7986, 14602, -4807, 16627},
{ 8057, 1481, 49, 17205, 24869, 7474},
{ -19304, -513, 11905, 2346, 5588, 3365},
{ -5063, -21812, 11370, 10896, 4881, 261},
{ 4794, 20577, 5109, -6025, -8049, -1521},
{ 8125, -14756, 20639, -14918, 23941, -3650},
{ 12451, 1381, 3613, 8687, -24002, 4848},
{ 6726, 10643, 10086, 25217, -25159, -1065},
{ 6561, 13977, 2911, 21737, 16465, -26050},
{ -1776, 2575, -19606, -16800, 3032, 6679},
{ 15012, -17910, -8438, -21554, -27111, 11808},
{ 3448, -924, -15913, -1135, 5126, -20613},
{ 7720, 2226, 17463, 5434, 28942, 17552},
{ 1246, 15614, -11743, 24618, -17539, 3272},
{ 3215, 17950, 2783, -722, -22672, 5979},
{ -5678, -3184, -26087, 26034, 6583, 3302},
{ 20310, -3555, -2715, -444, -1487, 1526},
{ -20640, -21970, -12207, -25793, 8863, -1036},
{ 17888, 570, -16102, 8329, -2553, 15275},
{ -2677, 9950, -1879, 16477, -12762, -29007},
{ -120, -2221, 219, 97, 365, 35},
{ 1270, -718, 1480, -2689, 1930, -7527},
{ 1896, 8750, 1906, 18235, -12692, -6174},
{ -3733, 13713, -9882, -15960, -1376, -7146},
{ -10600, 8496, 15967, -8792, 7532, 20439},
{ 3041, -13457, 1032, -26952, 5787, 24984},
{ -4590, -8220, -9322, -6112, -17243, 25745},
{ -17808, 6970, 3752, 626, -114, 2178},
{ 4449, -4862, 7054, -5404, 4738, -2827},
{ 4922, -651, 18939, -9866, 848, 1886},
{ -336, -5410, 7234, 20444, -9583, -600},
{ 781, -19474, -12648, 6634, 1414, 450},
{ -3399, -16770, 11107, 13200, -5498, 21663},
{ -3265, 4859, -5961, 7530, -10837, 28086},
{ 10350, -12901, 25699, 25640, -639, 351},
{ 1163, 18763, -5466, -15087, -145, -1377},
{ -14477, 27229, -31383, -32653, 21439, -2894},
{ 15420, 18823, 22128, 19398, 22583, 13587},
{ -10674, 10710, 5089, -4756, 909, -20760},
{ -12948, -20660, 7410, 2722, 3427, 11585},
{ -1105, 18374, 19731, -9650, 22442, 19634},
{ -296, -6798, -14677, 21603, 19796, 21399},
{ -19350, -7501, 25446, 13144, 8588, -25298},
{ 3092, -10618, 20896, 9249, -3326, 1796},
{ -811, 1449, 3106, 4748, 12073, -14262},
{ -20720, 14275, -4332, -25838, -5781, -21149},
{ -5132, 10554, -14020, -22150, 2840, -554},
{ 25533, 17648, 14886, -21074, 2459, 25142},
{ -9370, -1788, -12862, -5870, -25811, -11023},
{ 6698, 819, 10313, 166, 27581, 523},
{ 101, -19388, 3413, 9638, 64, 806},
{ -2742, -17931, -2576, 22818, 8553, 1126},
{ 2972, 15203, 1792, 25434, -5728, -17265},
{ -1419, 1604, 4398, 11452, 1731, 23787},
{ -5136, 4625, -10653, 27981, 9897, -2510},
{ -10528, -28033, 2999, -1530, -832, -830},
{ -11133, -12511, 22206, -7243, -23578, -21698},
{ 16935, -21892, 1861, -9606, 9432, 19026},
{ 10277, 9516, 26815, 2010, -4943, -9080},
{ 5547, -2210, 14270, -15300, -19316, 1822},
{ -4850, -783, -8959, -3076, -20056, -3197},
{ 8232, -2794, -17752, 13308, 3229, -991},
{ -12237, -6581, 10315, -9552, 2260, -20648},
{ -7000, 5529, -7553, -7490, -10342, -10266},
{ 3641, 19479, -5972, -19097, -18570, 12805},
{ 1283, -4164, 4198, -28473, -2498, 1866},
{ 16047, 26826, -13053, -6316, 985, -1597},
{ -403, 13680, 6457, 25070, 27124, -20710},
{ -18070, -1790, -24986, 5953, -954, 26600},
{ -24224, -15383, 24788, 1953, -1136, 187},
{ -2289, 12505, -20738, -904, 18324, 21258},
{ 2658, -6140, 16179, 22276, -556, 2154},
{ -6087, 13950, -25682, -27713, 4049, -4795},
{ -21452, 26473, 19435, -9124, 895, 303},
{ -22200, -26177, -6026, 24729, -22926, -9030},
{ -14276, -15982, 23732, -22851, 9268, -3841},
{ 29482, 21923, -6213, 1679, -2059, -1120},
{ -435, 9802, -3891, 12359, -4288, -18971},
{ 19768, -86, 2467, 1990, -1021, -5354},
{ 20986, -8783, -5329, -23562, -4730, 2673},
{ -5095, 5605, -4629, 19150, 26037, -12259},
{ 972, 6858, 4551, 27949, -4025, -2272},
{ 6075, -3260, -4989, -373, -1571, -3730},
{ -7256, -12992, -8820, -5109, 23054, 5054},
{ 920, 2615, 7912, -7353, -4905, 20186},
{ -250, 5454, 3140, 6928, -18723, -2051},
{ -10299, -4372, 19608, 4879, -661, -1885},
{ 14816, -8603, -19815, 6135, -21210, 14108},
{ -11945, -2223, 5018, 11892, 22741, 406},
{ -13184, -2613, -13256, -22433, -12482, -8380},
{ 17066, 25267, -2273, 5056, -342, 145},
{ 8401, -17683, 19112, 10615, -19453, 17083},
{ 20821, -5700, 12298, -25598, 10391, 7692},
{ 4550, 15779, 17338, -19379, -4768, 1206},
{ -7723, 10836, -27164, -11439, 6835, -1776},
{ 2542, 3199, 4442, 17513, -3711, -914},
{ 20960, -16774, -5814, 11087, -70, 22961},
{ 3305, 2919, 6256, -4800, -20966, -3230},
{ 5924, -16547, 2183, 2733, 3446, -23306},
{ -6061, -194, -13852, -10971, 19488, 1029},
{ 4467, -5964, -19004, 1519, -359, 855},
{ -1581, -7607, 22070, -11580, -10032, 17102},
{ -12412, 2553, 4324, 22500, 5751, 12170},
{ -25127, 17996, -6384, 1180, 1182, 9622},
{ 23462, -8471, -4392, -2669, 7638, -16835},
{ -5511, -2887, -10757, -20883, 7246, 1053},
{ 2703, -20602, -7554, 7516, -7740, 5868},
{ 20670, 21901, 457, 14969, -17657, -11921},
{ 3603, -1595, -2177, -157, -43, 605},
{ 2513, 8954, 10527, 22559, -16100, -16041},
{ 6002, 4951, 6795, -4862, -22400, 18849},
{ 7590, -1693, -24688, -3404, 14169, 1214},
{ -4398, -6663, -6870, -10083, -24596, 9253},
{ 10468, 17751, -7748, 147, -6314, 4419},
{ 16187, -16557, -4119, 4302, 7625, 5409},
{ 3303, 2735, 7458, -19902, -2254, -3702},
{ -2077, 21609, 14870, 12545, -6081, -1764},
{ 4678, 11740, 2859, 6953, 1919, -3871},
{ 3522, -21853, -2469, -10453, 18893, -10742},
{ 3759, -10191, -4866, -2659, -17831, -1242},
{ 14991, 9351, 11870, -1573, -4848, 22549},
{ 9509, -27152, 10734, 20851, -26185, -17878},
{ -7170, -1392, -19495, 12746, 8198, -1988},
{ 1883, 28158, -846, -7235, 249, 233},
{ -7200, 669, -371, -2948, 23234, -5635},
{ 3141, 288, 3223, -1258, -98, -27607},
{ 17373, -23235, 5110, -11199, -2574, -11487},
{ -4928, 1518, -5456, 670, -18278, 1951},
{ 10334, -19865, -4649, 361, -160, -923},
{ 18732, 14264, -3155, -7485, -3328, 5959},
{ -3614, 21077, 7276, 3536, 8121, -1528},
{ -8422, 500, -19182, 18929, 26392, -1039},
{ 15639, 25668, 8375, 1903, 1945, -11979},
{ -2716, 3389, 26850, -4587, 1803, 22},
{ 1177, -655, 1233, -2128, 7844, 1767},
{ -761, 8209, -19290, -4593, 1923, -343},
{ -689, -3530, -3267, -3804, -2753, 18566},
{ -2110, 1962, -1353, 16643, 2765, -23102},
{ -433, 4905, 302, 13016, 15933, -5905},
{ 3203, 4126, 11181, -5496, -2529, -1160},
{ -1091, -6469, -1415, 5682, -268, 583},
{ -9405, -19572, 6216, 1658, 993, -75},
{ -1695, -4504, -2289, -4088, -6556, -16577},
{ 4760, -892, -10902, 6516, 24199, -6011},
{ -253, 1000, 63, -81, -115, -382},
{ -1333, 24224, -698, -4667, -2801, -19144},
{ -876, -28866, -21873, 12677, -6344, 3235},
{ 16847, 21145, -26172, -3183, -396, 230},
{ 18296, -7790, -12857, -679, -1473, 5},
{ -10488, 11429, 25805, -1122, 1401, -438},
{ 3782, -7429, 26720, 17567, 19257, 12542},
{ 6332, -746, 12789, 9316, -22542, -5354},
{ 3418, -22728, 26978, 18303, 1076, 956},
{ -27315, -2988, 920, 235, 2233, 81},
{ 6199, 5296, 16093, 14768, -8429, -1112},
{ -6432, 19244, 9921, -3253, 1278, -954},
{ 24213, 2049, -22931, 2585, -2410, -4216},
{ 9286, 14282, -19735, -3985, -2344, 1028},
{ -20128, 17993, -9458, 23012, -16983, 8625},
{ -6896, -20730, 3762, 17415, 22341, 19024},
{ 842, 24181, 25062, -5839, -78, 937},
{ -621, 19722, -24204, -1962, -14854, -56},
{ 22766, -5119, 17365, 23868, -19480, -6558},
{ -2158, 17490, -21435, 3340, -12819, -20295},
{ -9621, 17325, 715, 2265, -4123, -492},
{ 9156, 12947, 27303, -21175, -6072, -9457},
{ -13164, -23269, -14006, -4184, 6978, 2},
{ 938, -13381, 3520, -24297, 22902, 19589},
{ -4911, -19774, 19764, -9310, -12650, 3819},
{ -5462, -4249, -6987, -6260, -13943, -25150},
{ 9341, 10369, -13862, -6704, 22556, -519},
{ 6651, 18768, -4855, 12570, 14730, -10209},
{ -823, 18119, 398, -1582, -116, -363},
{ -6935, -12694, -28392, 8552, 6961, -239},
{ -2602, -4704, -1021, 2015, 5129, 23670},
{ -12559, -8190, -25028, 18544, 14179, 1663},
{ 3813, 21036, -9620, -5051, -1800, -1087},
{ -22057, 16675, 14960, 9459, 2786, 16991},
{ -26040, -19318, -6414, 1104, 5798, -18039},
{ -1737, 24825, 10417, -11087, 896, -5273},
{ -1855, 11661, -2803, 24809, -21435, -19792},
{ -23473, -16729, -5782, 5643, 2636, 4940},
{ -1724, 4388, -26673, -13695, 10570, -25895},
{ 15358, -19496, 26242, -18493, 1736, 8054},
{ 5684, 20890, 4091, -19100, -14588, -10468},
{ 17260, -16291, 14859, -17711, -19174, 12435},
{ -27185, -12573, 6743, -562, 976, -257},
{ 12395, -8618, -22248, -19843, 11013, 7762},
{ 3799, 11853, -27622, -8473, 1089, -1495},
{ 4141, -2182, -26720, -735, -774, 1469},
{ 3125, 13762, 4606, 29257, 18771, -9958},
{ -17465, -9445, -17562, -2530, -6435, -3726},
{ -1742, 4351, -6841, -19773, 9627, -10654},
{ 7251, 3525, 10835, 5601, 25198, -23348},
{ -10300, -17830, 631, 11640, 2044, -20878},
{ -873, -8502, -1063, -15674, -10693, 14934},
{ -15957, 28137, 5268, 477, -1053, 1158},
{ -1495, -8814, -5764, -24965, 25988, 7907},
{ -1038, -114, -2308, -1319, -6480, 1472},
{ 4895, -17897, -25850, 5301, -188, 1581},
{ 3200, 17225, 4346, 22101, -18543, 22028},
{ -10250, 545, -10932, 2276, -28070, 8118},
{ 15343, 2329, 9316, 20537, 14908, 21021},
{ 6329, 6130, -24508, 837, -8637, -5844},
{ 7386, -501, 10503, 20131, 11435, -4755},
{ -2745, 24174, -9274, 15273, -8389, -5835},
{ 2992, -2864, 6048, -7473, 11687, -19996},
{ -883, -11954, -9976, -21829, -4436, -27178},
{ 3458, 19626, 1280, 2597, 19849, 5255},
{ -5315, 19133, -14518, -8946, 13749, -1352},
{ 18642, 17655, 11001, 6817, -18418, 6336},
{ -1697, 2244, -4640, 3948, -12890, -5273},
{ 20428, 10542, 4170, -1012, 19439, 21691},
{ -2943, -19735, -4208, 1320, 909, -8897},
{ 9351, -8066, -2618, -12933, 26582, 3507},
{ 9705, -22628, 8311, 8167, -13293, 5608},
{ 3222, 3749, -1508, 165, -52, -196},
{ 102, -22744, -8832, 903, -11421, -14662},
{ -120, 5998, 19765, 13401, 3628, 5197},
{ 8528, 5827, -1066, 774, -39, -166},
{ 9411, -9476, 9581, -13004, 24456, 24900},
{ 17878, 2235, -21639, 20478, 4716, -7190},
{ -2482, 9511, 1611, -21943, 14230, -1289},
{ 9288, -2291, 23215, -3452, -10842, 11},
{ 9496, 3041, 5130, -3890, -21219, -22589},
{ 14262, -9838, 20195, 14019, 91, -17200},
{ -18591, 980, 17, 821, 120, -574},
{ 12285, -19269, 13742, 16373, -161, 6025},
{ -3364, 1530, -4005, 2454, -10872, -23839},
{ 105, 5085, -260, 5790, -588, 19170},
{ 4121, 4169, 13439, 14644, 20899, 7434},
{ -175, 13101, -3704, 23233, 3907, 10106},
{ -6101, 23467, 5204, -1341, 1599, 13174},
{ -3217, -3494, 15117, -8387, -11762, -4750},
{ 1146, 4675, -19378, 14917, -5091, 249},
{ -21506, 10136, -16473, -13305, 18382, -8601},
{ 628, 2447, 3344, 3130, -5115, 119},
{ 17900, -22422, -17633, 21967, -16293, -7676},
{ 16863, 24214, 5612, -3858, -809, 3822},
{ -2291, 10091, -2360, -25109, -1226, 312},
{ 2957, 11256, 26745, -13266, -3455, -1128},
{ -19762, -2708, 4604, 6355, 1638, 25501},
{ -19593, -7753, 3159, -85, -489, -1855},
{ 814, 12510, 19077, -4681, -2610, -1474},
{ -23408, -19027, 8137, 19878, 7912, -282},
{ 839, -19652, 11927, 27278, -3211, 2266},
{ 4020, -1110, 8226, -1274, 20922, 25060},
{ 26576, 325, -8693, -232, -2218, -699},
{ -11293, -4200, 1805, -6673, -22940, -1339},
{ -2005, -15886, -1047, -27687, -13235, 14370},
{ -22073, 1949, 13175, -15656, -1846, 8055},
{ 3039, 12025, 7132, -24632, 413, -2347},
{ -24048, -206, 12459, -6654, -417, -10091},
{ 18179, -23688, -20515, -16396, 7230, 763},
{ 5659, -5085, 13878, -23729, -11077, -19587},
{ 11340, 501, 25040, 7616, -19658, 1605},
{ -26650, 8878, 10544, 417, 1299, 261},
{ 14460, 11369, -3263, 9990, 8194, 18111},
{ 1355, -20838, -9196, -16060, -8559, -730},
{ -1918, -20937, -18293, -2461, -2651, 4316},
{ -2810, 24521, -10996, -25721, 308, -1234},
{ -9075, -17280, -1833, -29342, -24213, -16631},
{ -2843, 10165, -5339, -2888, 21858, -21340},
{ -15832, 14849, -23780, 5184, 10113, -20639},
{ -19535, -11361, 8413, 1486, -23658, -5759},
{ -7512, 1027, -20794, 13732, 19892, -21934},
{ -12132, -7022, -19175, -8840, 22125, -16490},
{ 1937, 5210, -6318, -23788, 13141, 11082},
{ -205, 6036, -380, 8658, -233, 28020},
{ -5523, 7477, 7635, 23595, 9763, -2590},
{ 21658, -28313, -3086, -300, -1032, 1744},
{ -22352, 16646, 208, 6665, -17400, -3028},
{ 18482, 9336, -2737, -19372, 407, -4389},
{ -4913, -17370, 18819, -17654, 13416, 15232},
{ 7749, 6368, 23135, -18174, 7584, -4248},
{ -1489, -6523, 586, -10157, 14964, 25568},
{ 3844, -6156, 4897, -13045, -22526, 5647},
{ -8491, -2105, -24774, 905, -9326, 1456},
{ -3040, -1476, 1166, -4428, 11236, 9204},
{ 3397, -1451, 13598, -15841, 24540, 5819},
{ 8483, -2993, 21547, -16916, 7741, 24018},
{ -14932, -23758, -5332, -6664, -4497, 13267},
{ 19379, 12916, -2142, -737, 21100, -22101},
{ 3393, -4629, 5735, -18913, -6969, 2687},
{ 1148, -16147, -21433, -28095, -630, -14449},
{ 7300, 672, 18530, -17452, -10149, 351},
{ 11356, -10974, 17212, 4624, 145, 17791},
{ -711, -3479, -2238, 15887, 2027, 0},
{ -28048, 1794, -593, -2758, -21852, 11535},
{ -19683, 4937, 22004, 21523, -3148, 1790},
{ 813, 8231, 2633, 11981, -3043, 22201},
{ 8952, -24760, -690, 14873, -2366, -5372},
{ 8406, -5439, -274, -642, -145, 778},
{ -6605, 7258, 20780, -23507, -18625, 22782},
{ -22896, -25488, 10020, -1614, 1508, -1393},
{ 7607, 407, -24678, -16385, -1804, -4699},
{ -10592, -19139, 10462, -3747, 8721, -6919},
{ 13010, 5292, -6230, -4884, -20904, -1797},
{ 16891, -13770, -465, 19343, -10741, -12959},
{ 25193, -14799, -5681, -521, -321, -1211},
{ 6917, -3093, 20183, -26903, -12026, 1295},
{ 305, 1992, 19457, -985, 25, -521},
{ 6707, -3698, 8365, -8687, 21921, -27166},
{ 4668, 5997, 7117, 11696, 24401, -10794},
{ 744, -9416, 19893, 1963, 7922, -9824},
{ 3430, 21282, -1736, 10844, 8821, 27015},
{ -8813, 1521, -24038, 1651, 7838, -1208},
{ 3911, -11221, 3273, -12541, 7168, 18402},
{ 21642, 9117, -11536, -5256, 7077, 2382},
{ 100, 3817, -6713, 1244, 1518, -321},
{ 7946, -18670, 10667, -4866, 727, 776},
{ -15883, -8150, -2087, 22739, 1567, -3482},
{ 4380, -2735, 8469, -7025, -11424, 1317},
{ 26970, 4393, 7665, 17561, -714, 650},
{ -16191, -835, 8365, 1795, -14314, 16297},
{ 4504, -10048, 7662, -26690, -17428, 2580},
{ 48, -3984, 564, -5871, 2658, -18658},
{ 12579, -26016, -15642, 2672, -1347, -887},
{ -4950, 4208, -6811, 2569, -20621, -8658},
{ -1836, -14818, -5571, -23322, -14800, 25867},
{ 5434, -28139, -2357, -2883, -570, 2431},
{ 13096, -2771, 24994, -12496, -24723, -1025},
{ -5676, -4339, 1908, 18628, -21323, 17366},
{ 27660, -27897, -15409, 1436, -7112, -2241},
{ 8019, 3847, 24568, -469, 9674, 10683},
{ -903, -10149, 1801, -21260, 4795, -8751},
{ 1122, -9582, 2625, 22791, 956, 882},
{ 7876, 19075, -9900, -24266, 7496, 9277},
{ 980, -26764, -5386, 5396, 1086, 1648},
{ 28838, -1270, -447, 5, -429, -20},
{ -15283, 6132, 22812, 1252, -9963, 511},
{ 851, 7925, -457, -12210, 4261, 7579},
{ -4530, 8452, -1246, 14501, -24951, -5760},
{ -17814, -10727, 9887, -23929, -13432, 1878},
{ -15049, 10165, 16491, -14603, -11712, -21156},
{ -3317, 840, -5683, 22413, 1994, 586},
{ 23158, -5788, -15043, -10372, -9271, -13523},
{ -773, -9509, -3993, -24264, 8463, 5804},
{ -8545, -703, -12440, -3985, -25122, -28147},
{ -16659, 16001, 2746, 1611, 5097, -1043},
{ 41, -7181, 19903, 31555, -32237, 13927},
{ -5658, 845, -12774, 5705, 16695, -86},
{ 5282, 14875, 27026, 21124, 15776, -10477},
{ 14712, 19648, -11487, -13361, -20196, -15229},
{ 8597, -9138, -626, 10891, -6015, 6346},
{ -1488, -1272, -1479, -1303, -3704, -5485},
{ -3370, 17871, -6604, 24930, 25886, -3127},
{ 8416, 27783, -1385, 5350, -4260, 19993},
{ 5688, 362, 17246, 3809, -3246, 1088},
{ -105, -29607, 2747, 15223, -167, 3722},
{ 3502, -3195, 8602, 7772, -1566, -915},
{ -491, 3257, -2423, 5522, 20606, -100},
{ -13948, -11368, -15375, -21866, -8520, 12221},
{ -616, 2424, -2023, 4398, -3805, 8108},
{ -7204, 21043, 21211, -9395, -19391, 896},
{ -5737, -15160, -21298, 17066, -1006, -366},
{ 6261, 3240, -11937, -16213, -15820, 6581},
{ -3155, 24796, 2733, -1257, -875, -1597},
{ -20469, 11094, 24071, -8987, 14136, 2220},
{ -14106, 11959, -22495, 4135, -1055, -5420},
{ 801, -2655, 60, -5324, -790, 5937},
{ -7372, -1764, -22433, -26060, 21707, 4178},
{ -5715, -6648, -14908, 1325, -24044, 1493},
{ -6024, -12488, 23930, 2950, 1601, 1173},
{ 19067, 17630, 17929, -10654, 10928, -4958},
{ 3231, -3284, 27336, 4174, -1683, 497},
};
const int16_t (* const ff_eac3_mantissa_vq[8])[6] = {
NULL,
vq_hebap1,
vq_hebap2,
vq_hebap3,
vq_hebap4,
vq_hebap5,
vq_hebap6,
vq_hebap7,
};
/**
* Table E2.14 Frame Exponent Strategy Combinations
*/
const uint8_t ff_eac3_frm_expstr[32][6] = {
{ EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_REUSE},
{ EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_D45},
{ EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_D25, EXP_REUSE},
{ EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_D45, EXP_D45},
{ EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_REUSE},
{ EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_D45},
{ EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D45, EXP_D25, EXP_REUSE},
{ EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D45, EXP_D45, EXP_D45},
{ EXP_D25, EXP_REUSE, EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE},
{ EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D45},
{ EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE},
{ EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_D45, EXP_D45},
{ EXP_D25, EXP_REUSE, EXP_D45, EXP_D25, EXP_REUSE, EXP_REUSE},
{ EXP_D25, EXP_REUSE, EXP_D45, EXP_D25, EXP_REUSE, EXP_D45},
{ EXP_D25, EXP_REUSE, EXP_D45, EXP_D45, EXP_D25, EXP_REUSE},
{ EXP_D25, EXP_REUSE, EXP_D45, EXP_D45, EXP_D45, EXP_D45},
{ EXP_D45, EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_REUSE},
{ EXP_D45, EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE, EXP_D45},
{ EXP_D45, EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D25, EXP_REUSE},
{ EXP_D45, EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D45, EXP_D45},
{ EXP_D45, EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_REUSE},
{ EXP_D45, EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE, EXP_D45},
{ EXP_D45, EXP_D25, EXP_REUSE, EXP_D45, EXP_D25, EXP_REUSE},
{ EXP_D45, EXP_D25, EXP_REUSE, EXP_D45, EXP_D45, EXP_D45},
{ EXP_D45, EXP_D45, EXP_D15, EXP_REUSE, EXP_REUSE, EXP_REUSE},
{ EXP_D45, EXP_D45, EXP_D25, EXP_REUSE, EXP_REUSE, EXP_D45},
{ EXP_D45, EXP_D45, EXP_D25, EXP_REUSE, EXP_D25, EXP_REUSE},
{ EXP_D45, EXP_D45, EXP_D25, EXP_REUSE, EXP_D45, EXP_D45},
{ EXP_D45, EXP_D45, EXP_D45, EXP_D25, EXP_REUSE, EXP_REUSE},
{ EXP_D45, EXP_D45, EXP_D45, EXP_D25, EXP_REUSE, EXP_D45},
{ EXP_D45, EXP_D45, EXP_D45, EXP_D45, EXP_D25, EXP_REUSE},
{ EXP_D45, EXP_D45, EXP_D45, EXP_D45, EXP_D45, EXP_D45},
};
/**
* Table E.25: Spectral Extension Attenuation Table
* ff_eac3_spx_atten_tab[code][bin]=pow(2.0,(bin+1)*(code+1)/-15.0);
*/
const float ff_eac3_spx_atten_tab[32][3] = {
{ 0.954841603910416503f, 0.911722488558216804f, 0.870550563296124125f },
{ 0.911722488558216804f, 0.831237896142787758f, 0.757858283255198995f },
{ 0.870550563296124125f, 0.757858283255198995f, 0.659753955386447100f },
{ 0.831237896142787758f, 0.690956439983888004f, 0.574349177498517438f },
{ 0.793700525984099792f, 0.629960524947436595f, 0.500000000000000000f },
{ 0.757858283255198995f, 0.574349177498517438f, 0.435275281648062062f },
{ 0.723634618720189082f, 0.523647061410313364f, 0.378929141627599553f },
{ 0.690956439983888004f, 0.477420801955208307f, 0.329876977693223550f },
{ 0.659753955386447100f, 0.435275281648062062f, 0.287174588749258719f },
{ 0.629960524947436595f, 0.396850262992049896f, 0.250000000000000000f },
{ 0.601512518041058319f, 0.361817309360094541f, 0.217637640824031003f },
{ 0.574349177498517438f, 0.329876977693223550f, 0.189464570813799776f },
{ 0.548412489847312945f, 0.300756259020529160f, 0.164938488846611775f },
{ 0.523647061410313364f, 0.274206244923656473f, 0.143587294374629387f },
{ 0.500000000000000000f, 0.250000000000000000f, 0.125000000000000000f },
{ 0.477420801955208307f, 0.227930622139554201f, 0.108818820412015502f },
{ 0.455861244279108402f, 0.207809474035696939f, 0.094732285406899888f },
{ 0.435275281648062062f, 0.189464570813799776f, 0.082469244423305887f },
{ 0.415618948071393879f, 0.172739109995972029f, 0.071793647187314694f },
{ 0.396850262992049896f, 0.157490131236859149f, 0.062500000000000000f },
{ 0.378929141627599553f, 0.143587294374629387f, 0.054409410206007751f },
{ 0.361817309360094541f, 0.130911765352578369f, 0.047366142703449930f },
{ 0.345478219991944002f, 0.119355200488802049f, 0.041234622211652958f },
{ 0.329876977693223550f, 0.108818820412015502f, 0.035896823593657347f },
{ 0.314980262473718298f, 0.099212565748012460f, 0.031250000000000000f },
{ 0.300756259020529160f, 0.090454327340023621f, 0.027204705103003875f },
{ 0.287174588749258719f, 0.082469244423305887f, 0.023683071351724965f },
{ 0.274206244923656473f, 0.075189064755132290f, 0.020617311105826479f },
{ 0.261823530705156682f, 0.068551561230914118f, 0.017948411796828673f },
{ 0.250000000000000000f, 0.062500000000000000f, 0.015625000000000000f },
{ 0.238710400977604098f, 0.056982655534888536f, 0.013602352551501938f },
{ 0.227930622139554201f, 0.051952368508924235f, 0.011841535675862483f }
};
| mit |
SyllaJay/WinObjC | deps/3rdparty/iculegacy/source/i18n/rbt_rule.cpp | 188 | 19396 | /*
**********************************************************************
* Copyright (C) 1999-2008, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Date Name Description
* 11/17/99 aliu Creation.
**********************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_TRANSLITERATION
#include "unicode/rep.h"
#include "unicode/unifilt.h"
#include "unicode/uniset.h"
#include "rbt_rule.h"
#include "rbt_data.h"
#include "cmemory.h"
#include "strmatch.h"
#include "strrepl.h"
#include "util.h"
#include "putilimp.h"
static const UChar FORWARD_OP[] = {32,62,32,0}; // " > "
U_NAMESPACE_BEGIN
/**
* Construct a new rule with the given input, output text, and other
* attributes. A cursor position may be specified for the output text.
* @param input input string, including key and optional ante and
* post context
* @param anteContextPos offset into input to end of ante context, or -1 if
* none. Must be <= input.length() if not -1.
* @param postContextPos offset into input to start of post context, or -1
* if none. Must be <= input.length() if not -1, and must be >=
* anteContextPos.
* @param output output string
* @param cursorPosition offset into output at which cursor is located, or -1 if
* none. If less than zero, then the cursor is placed after the
* <code>output</code>; that is, -1 is equivalent to
* <code>output.length()</code>. If greater than
* <code>output.length()</code> then an exception is thrown.
* @param segs array of UnicodeFunctors corresponding to input pattern
* segments, or null if there are none. The array itself is adopted,
* but the pointers within it are not.
* @param segsCount number of elements in segs[]
* @param anchorStart TRUE if the the rule is anchored on the left to
* the context start
* @param anchorEnd TRUE if the rule is anchored on the right to the
* context limit
*/
TransliterationRule::TransliterationRule(const UnicodeString& input,
int32_t anteContextPos, int32_t postContextPos,
const UnicodeString& outputStr,
int32_t cursorPosition, int32_t cursorOffset,
UnicodeFunctor** segs,
int32_t segsCount,
UBool anchorStart, UBool anchorEnd,
const TransliterationRuleData* theData,
UErrorCode& status) :
UMemory(),
segments(0),
data(theData) {
if (U_FAILURE(status)) {
return;
}
// Do range checks only when warranted to save time
if (anteContextPos < 0) {
anteContextLength = 0;
} else {
if (anteContextPos > input.length()) {
// throw new IllegalArgumentException("Invalid ante context");
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
anteContextLength = anteContextPos;
}
if (postContextPos < 0) {
keyLength = input.length() - anteContextLength;
} else {
if (postContextPos < anteContextLength ||
postContextPos > input.length()) {
// throw new IllegalArgumentException("Invalid post context");
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
keyLength = postContextPos - anteContextLength;
}
if (cursorPosition < 0) {
cursorPosition = outputStr.length();
} else if (cursorPosition > outputStr.length()) {
// throw new IllegalArgumentException("Invalid cursor position");
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
// We don't validate the segments array. The caller must
// guarantee that the segments are well-formed (that is, that
// all $n references in the output refer to indices of this
// array, and that no array elements are null).
this->segments = segs;
this->segmentsCount = segsCount;
pattern = input;
flags = 0;
if (anchorStart) {
flags |= ANCHOR_START;
}
if (anchorEnd) {
flags |= ANCHOR_END;
}
anteContext = NULL;
if (anteContextLength > 0) {
anteContext = new StringMatcher(pattern, 0, anteContextLength,
FALSE, *data);
/* test for NULL */
if (anteContext == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
key = NULL;
if (keyLength > 0) {
key = new StringMatcher(pattern, anteContextLength, anteContextLength + keyLength,
FALSE, *data);
/* test for NULL */
if (key == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
int32_t postContextLength = pattern.length() - keyLength - anteContextLength;
postContext = NULL;
if (postContextLength > 0) {
postContext = new StringMatcher(pattern, anteContextLength + keyLength, pattern.length(),
FALSE, *data);
/* test for NULL */
if (postContext == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
this->output = new StringReplacer(outputStr, cursorPosition + cursorOffset, data);
/* test for NULL */
if (this->output == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
/**
* Copy constructor.
*/
TransliterationRule::TransliterationRule(TransliterationRule& other) :
UMemory(other),
anteContext(NULL),
key(NULL),
postContext(NULL),
pattern(other.pattern),
anteContextLength(other.anteContextLength),
keyLength(other.keyLength),
flags(other.flags),
data(other.data) {
segments = NULL;
segmentsCount = 0;
if (other.segmentsCount > 0) {
segments = (UnicodeFunctor **)uprv_malloc(other.segmentsCount * sizeof(UnicodeFunctor *));
uprv_memcpy(segments, other.segments, other.segmentsCount*sizeof(segments[0]));
}
if (other.anteContext != NULL) {
anteContext = (StringMatcher*) other.anteContext->clone();
}
if (other.key != NULL) {
key = (StringMatcher*) other.key->clone();
}
if (other.postContext != NULL) {
postContext = (StringMatcher*) other.postContext->clone();
}
output = other.output->clone();
}
TransliterationRule::~TransliterationRule() {
uprv_free(segments);
delete anteContext;
delete key;
delete postContext;
delete output;
}
/**
* Return the preceding context length. This method is needed to
* support the <code>Transliterator</code> method
* <code>getMaximumContextLength()</code>. Internally, this is
* implemented as the anteContextLength, optionally plus one if
* there is a start anchor. The one character anchor gap is
* needed to make repeated incremental transliteration with
* anchors work.
*/
int32_t TransliterationRule::getContextLength(void) const {
return anteContextLength + ((flags & ANCHOR_START) ? 1 : 0);
}
/**
* Internal method. Returns 8-bit index value for this rule.
* This is the low byte of the first character of the key,
* unless the first character of the key is a set. If it's a
* set, or otherwise can match multiple keys, the index value is -1.
*/
int16_t TransliterationRule::getIndexValue() const {
if (anteContextLength == pattern.length()) {
// A pattern with just ante context {such as foo)>bar} can
// match any key.
return -1;
}
UChar32 c = pattern.char32At(anteContextLength);
return (int16_t)(data->lookupMatcher(c) == NULL ? (c & 0xFF) : -1);
}
/**
* Internal method. Returns true if this rule matches the given
* index value. The index value is an 8-bit integer, 0..255,
* representing the low byte of the first character of the key.
* It matches this rule if it matches the first character of the
* key, or if the first character of the key is a set, and the set
* contains any character with a low byte equal to the index
* value. If the rule contains only ante context, as in foo)>bar,
* then it will match any key.
*/
UBool TransliterationRule::matchesIndexValue(uint8_t v) const {
// Delegate to the key, or if there is none, to the postContext.
// If there is neither then we match any key; return true.
UnicodeMatcher *m = (key != NULL) ? key : postContext;
return (m != NULL) ? m->matchesIndexValue(v) : TRUE;
}
/**
* Return true if this rule masks another rule. If r1 masks r2 then
* r1 matches any input string that r2 matches. If r1 masks r2 and r2 masks
* r1 then r1 == r2. Examples: "a>x" masks "ab>y". "a>x" masks "a[b]>y".
* "[c]a>x" masks "[dc]a>y".
*/
UBool TransliterationRule::masks(const TransliterationRule& r2) const {
/* Rule r1 masks rule r2 if the string formed of the
* antecontext, key, and postcontext overlaps in the following
* way:
*
* r1: aakkkpppp
* r2: aaakkkkkpppp
* ^
*
* The strings must be aligned at the first character of the
* key. The length of r1 to the left of the alignment point
* must be <= the length of r2 to the left; ditto for the
* right. The characters of r1 must equal (or be a superset
* of) the corresponding characters of r2. The superset
* operation should be performed to check for UnicodeSet
* masking.
*
* Anchors: Two patterns that differ only in anchors only
* mask one another if they are exactly equal, and r2 has
* all the anchors r1 has (optionally, plus some). Here Y
* means the row masks the column, N means it doesn't.
*
* ab ^ab ab$ ^ab$
* ab Y Y Y Y
* ^ab N Y N Y
* ab$ N N Y Y
* ^ab$ N N N Y
*
* Post context: {a}b masks ab, but not vice versa, since {a}b
* matches everything ab matches, and {a}b matches {|a|}b but ab
* does not. Pre context is different (a{b} does not align with
* ab).
*/
/* LIMITATION of the current mask algorithm: Some rule
* maskings are currently not detected. For example,
* "{Lu}]a>x" masks "A]a>y". This can be added later. TODO
*/
int32_t len = pattern.length();
int32_t left = anteContextLength;
int32_t left2 = r2.anteContextLength;
int32_t right = len - left;
int32_t right2 = r2.pattern.length() - left2;
int32_t cachedCompare = r2.pattern.compare(left2 - left, len, pattern);
// TODO Clean this up -- some logic might be combinable with the
// next statement.
// Test for anchor masking
if (left == left2 && right == right2 &&
keyLength <= r2.keyLength &&
0 == cachedCompare) {
// The following boolean logic implements the table above
return (flags == r2.flags) ||
(!(flags & ANCHOR_START) && !(flags & ANCHOR_END)) ||
((r2.flags & ANCHOR_START) && (r2.flags & ANCHOR_END));
}
return left <= left2 &&
(right < right2 ||
(right == right2 && keyLength <= r2.keyLength)) &&
(0 == cachedCompare);
}
static inline int32_t posBefore(const Replaceable& str, int32_t pos) {
return (pos > 0) ?
pos - UTF_CHAR_LENGTH(str.char32At(pos-1)) :
pos - 1;
}
static inline int32_t posAfter(const Replaceable& str, int32_t pos) {
return (pos >= 0 && pos < str.length()) ?
pos + UTF_CHAR_LENGTH(str.char32At(pos)) :
pos + 1;
}
/**
* Attempt a match and replacement at the given position. Return
* the degree of match between this rule and the given text. The
* degree of match may be mismatch, a partial match, or a full
* match. A mismatch means at least one character of the text
* does not match the context or key. A partial match means some
* context and key characters match, but the text is not long
* enough to match all of them. A full match means all context
* and key characters match.
*
* If a full match is obtained, perform a replacement, update pos,
* and return U_MATCH. Otherwise both text and pos are unchanged.
*
* @param text the text
* @param pos the position indices
* @param incremental if TRUE, test for partial matches that may
* be completed by additional text inserted at pos.limit.
* @return one of <code>U_MISMATCH</code>,
* <code>U_PARTIAL_MATCH</code>, or <code>U_MATCH</code>. If
* incremental is FALSE then U_PARTIAL_MATCH will not be returned.
*/
UMatchDegree TransliterationRule::matchAndReplace(Replaceable& text,
UTransPosition& pos,
UBool incremental) const {
// Matching and replacing are done in one method because the
// replacement operation needs information obtained during the
// match. Another way to do this is to have the match method
// create a match result struct with relevant offsets, and to pass
// this into the replace method.
// ============================ MATCH ===========================
// Reset segment match data
if (segments != NULL) {
for (int32_t i=0; i<segmentsCount; ++i) {
((StringMatcher*) segments[i])->resetMatch();
}
}
// int32_t lenDelta, keyLimit;
int32_t keyLimit;
// ------------------------ Ante Context ------------------------
// A mismatch in the ante context, or with the start anchor,
// is an outright U_MISMATCH regardless of whether we are
// incremental or not.
int32_t oText; // offset into 'text'
// int32_t newStart = 0;
int32_t minOText;
// Note (1): We process text in 16-bit code units, rather than
// 32-bit code points. This works because stand-ins are
// always in the BMP and because we are doing a literal match
// operation, which can be done 16-bits at a time.
int32_t anteLimit = posBefore(text, pos.contextStart);
UMatchDegree match;
// Start reverse match at char before pos.start
oText = posBefore(text, pos.start);
if (anteContext != NULL) {
match = anteContext->matches(text, oText, anteLimit, FALSE);
if (match != U_MATCH) {
return U_MISMATCH;
}
}
minOText = posAfter(text, oText);
// ------------------------ Start Anchor ------------------------
if (((flags & ANCHOR_START) != 0) && oText != anteLimit) {
return U_MISMATCH;
}
// -------------------- Key and Post Context --------------------
oText = pos.start;
if (key != NULL) {
match = key->matches(text, oText, pos.limit, incremental);
if (match != U_MATCH) {
return match;
}
}
keyLimit = oText;
if (postContext != NULL) {
if (incremental && keyLimit == pos.limit) {
// The key matches just before pos.limit, and there is
// a postContext. Since we are in incremental mode,
// we must assume more characters may be inserted at
// pos.limit -- this is a partial match.
return U_PARTIAL_MATCH;
}
match = postContext->matches(text, oText, pos.contextLimit, incremental);
if (match != U_MATCH) {
return match;
}
}
// ------------------------- Stop Anchor ------------------------
if (((flags & ANCHOR_END)) != 0) {
if (oText != pos.contextLimit) {
return U_MISMATCH;
}
if (incremental) {
return U_PARTIAL_MATCH;
}
}
// =========================== REPLACE ==========================
// We have a full match. The key is between pos.start and
// keyLimit.
int32_t newStart;
int32_t newLength = output->toReplacer()->replace(text, pos.start, keyLimit, newStart);
int32_t lenDelta = newLength - (keyLimit - pos.start);
oText += lenDelta;
pos.limit += lenDelta;
pos.contextLimit += lenDelta;
// Restrict new value of start to [minOText, min(oText, pos.limit)].
pos.start = uprv_max(minOText, uprv_min(uprv_min(oText, pos.limit), newStart));
return U_MATCH;
}
/**
* Create a source string that represents this rule. Append it to the
* given string.
*/
UnicodeString& TransliterationRule::toRule(UnicodeString& rule,
UBool escapeUnprintable) const {
// Accumulate special characters (and non-specials following them)
// into quoteBuf. Append quoteBuf, within single quotes, when
// a non-quoted element must be inserted.
UnicodeString str, quoteBuf;
// Do not emit the braces '{' '}' around the pattern if there
// is neither anteContext nor postContext.
UBool emitBraces =
(anteContext != NULL) || (postContext != NULL);
// Emit start anchor
if ((flags & ANCHOR_START) != 0) {
rule.append((UChar)94/*^*/);
}
// Emit the input pattern
ICU_Utility::appendToRule(rule, anteContext, escapeUnprintable, quoteBuf);
if (emitBraces) {
ICU_Utility::appendToRule(rule, (UChar) 0x007B /*{*/, TRUE, escapeUnprintable, quoteBuf);
}
ICU_Utility::appendToRule(rule, key, escapeUnprintable, quoteBuf);
if (emitBraces) {
ICU_Utility::appendToRule(rule, (UChar) 0x007D /*}*/, TRUE, escapeUnprintable, quoteBuf);
}
ICU_Utility::appendToRule(rule, postContext, escapeUnprintable, quoteBuf);
// Emit end anchor
if ((flags & ANCHOR_END) != 0) {
rule.append((UChar)36/*$*/);
}
ICU_Utility::appendToRule(rule, FORWARD_OP, TRUE, escapeUnprintable, quoteBuf);
// Emit the output pattern
ICU_Utility::appendToRule(rule, output->toReplacer()->toReplacerPattern(str, escapeUnprintable),
TRUE, escapeUnprintable, quoteBuf);
ICU_Utility::appendToRule(rule, (UChar) 0x003B /*;*/, TRUE, escapeUnprintable, quoteBuf);
return rule;
}
void TransliterationRule::setData(const TransliterationRuleData* d) {
data = d;
if (anteContext != NULL) anteContext->setData(d);
if (postContext != NULL) postContext->setData(d);
if (key != NULL) key->setData(d);
// assert(output != NULL);
output->setData(d);
// Don't have to do segments since they are in the context or key
}
/**
* Union the set of all characters that may be modified by this rule
* into the given set.
*/
void TransliterationRule::addSourceSetTo(UnicodeSet& toUnionTo) const {
int32_t limit = anteContextLength + keyLength;
for (int32_t i=anteContextLength; i<limit; ) {
UChar32 ch = pattern.char32At(i);
i += UTF_CHAR_LENGTH(ch);
const UnicodeMatcher* matcher = data->lookupMatcher(ch);
if (matcher == NULL) {
toUnionTo.add(ch);
} else {
matcher->addMatchSetTo(toUnionTo);
}
}
}
/**
* Union the set of all characters that may be emitted by this rule
* into the given set.
*/
void TransliterationRule::addTargetSetTo(UnicodeSet& toUnionTo) const {
output->toReplacer()->addReplacementSetTo(toUnionTo);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_TRANSLITERATION */
//eof
| mit |
jjdicharry/godot | drivers/vorbis/lpc.c | 445 | 4547 | /********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: LPC low level routines
last mod: $Id: lpc.c 16227 2009-07-08 06:58:46Z xiphmont $
********************************************************************/
/* Some of these routines (autocorrelator, LPC coefficient estimator)
are derived from code written by Jutta Degener and Carsten Bormann;
thus we include their copyright below. The entirety of this file
is freely redistributable on the condition that both of these
copyright notices are preserved without modification. */
/* Preserved Copyright: *********************************************/
/* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
Technische Universita"t Berlin
Any use of this software is permitted provided that this notice is not
removed and that neither the authors nor the Technische Universita"t
Berlin are deemed to have made any representations as to the
suitability of this software for any purpose nor are held responsible
for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
THIS SOFTWARE.
As a matter of courtesy, the authors request to be informed about uses
this software has found, about bugs in this software, and about any
improvements that may be of general interest.
Berlin, 28.11.1994
Jutta Degener
Carsten Bormann
*********************************************************************/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "os.h"
#include "smallft.h"
#include "lpc.h"
#include "scales.h"
#include "misc.h"
/* Autocorrelation LPC coeff generation algorithm invented by
N. Levinson in 1947, modified by J. Durbin in 1959. */
/* Input : n elements of time doamin data
Output: m lpc coefficients, excitation energy */
float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
double *aut=alloca(sizeof(*aut)*(m+1));
double *lpc=alloca(sizeof(*lpc)*(m));
double error;
double epsilon;
int i,j;
/* autocorrelation, p+1 lag coefficients */
j=m+1;
while(j--){
double d=0; /* double needed for accumulator depth */
for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
aut[j]=d;
}
/* Generate lpc coefficients from autocorr values */
/* set our noise floor to about -100dB */
error=aut[0] * (1. + 1e-10);
epsilon=1e-9*aut[0]+1e-10;
for(i=0;i<m;i++){
double r= -aut[i+1];
if(error<epsilon){
memset(lpc+i,0,(m-i)*sizeof(*lpc));
goto done;
}
/* Sum up this iteration's reflection coefficient; note that in
Vorbis we don't save it. If anyone wants to recycle this code
and needs reflection coefficients, save the results of 'r' from
each iteration. */
for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
r/=error;
/* Update LPC coefficients and total error */
lpc[i]=r;
for(j=0;j<i/2;j++){
double tmp=lpc[j];
lpc[j]+=r*lpc[i-1-j];
lpc[i-1-j]+=r*tmp;
}
if(i&1)lpc[j]+=lpc[j]*r;
error*=1.-r*r;
}
done:
/* slightly damp the filter */
{
double g = .99;
double damp = g;
for(j=0;j<m;j++){
lpc[j]*=damp;
damp*=g;
}
}
for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
/* we need the error value to know how big an impulse to hit the
filter with later */
return error;
}
void vorbis_lpc_predict(float *coeff,float *prime,int m,
float *data,long n){
/* in: coeff[0...m-1] LPC coefficients
prime[0...m-1] initial values (allocated size of n+m-1)
out: data[0...n-1] data samples */
long i,j,o,p;
float y;
float *work=alloca(sizeof(*work)*(m+n));
if(!prime)
for(i=0;i<m;i++)
work[i]=0.f;
else
for(i=0;i<m;i++)
work[i]=prime[i];
for(i=0;i<n;i++){
y=0;
o=i;
p=m;
for(j=0;j<m;j++)
y-=work[o++]*coeff[--p];
data[i]=work[o]=y;
}
}
| mit |
greenfire27/Torque2D | engine/lib/freetype/android/freetype-2.4.12/src/psaux/t1decode.c | 196 | 51012 | /***************************************************************************/
/* */
/* t1decode.c */
/* */
/* PostScript Type 1 decoding routines (body). */
/* */
/* Copyright 2000-2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_CALC_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_POSTSCRIPT_HINTS_H
#include FT_OUTLINE_H
#include "t1decode.h"
#include "psobjs.h"
#include "psauxerr.h"
/* ensure proper sign extension */
#define Fix2Int( f ) ( (FT_Int)(FT_Short)( (f) >> 16 ) )
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1decode
typedef enum T1_Operator_
{
op_none = 0,
op_endchar,
op_hsbw,
op_seac,
op_sbw,
op_closepath,
op_hlineto,
op_hmoveto,
op_hvcurveto,
op_rlineto,
op_rmoveto,
op_rrcurveto,
op_vhcurveto,
op_vlineto,
op_vmoveto,
op_dotsection,
op_hstem,
op_hstem3,
op_vstem,
op_vstem3,
op_div,
op_callothersubr,
op_callsubr,
op_pop,
op_return,
op_setcurrentpoint,
op_unknown15,
op_max /* never remove this one */
} T1_Operator;
static
const FT_Int t1_args_count[op_max] =
{
0, /* none */
0, /* endchar */
2, /* hsbw */
5, /* seac */
4, /* sbw */
0, /* closepath */
1, /* hlineto */
1, /* hmoveto */
4, /* hvcurveto */
2, /* rlineto */
2, /* rmoveto */
6, /* rrcurveto */
4, /* vhcurveto */
1, /* vlineto */
1, /* vmoveto */
0, /* dotsection */
2, /* hstem */
6, /* hstem3 */
2, /* vstem */
6, /* vstem3 */
2, /* div */
-1, /* callothersubr */
1, /* callsubr */
0, /* pop */
0, /* return */
2, /* setcurrentpoint */
2 /* opcode 15 (undocumented and obsolete) */
};
/*************************************************************************/
/* */
/* <Function> */
/* t1_lookup_glyph_by_stdcharcode */
/* */
/* <Description> */
/* Looks up a given glyph by its StandardEncoding charcode. Used to */
/* implement the SEAC Type 1 operator. */
/* */
/* <Input> */
/* face :: The current face object. */
/* */
/* charcode :: The character code to look for. */
/* */
/* <Return> */
/* A glyph index in the font face. Returns -1 if the corresponding */
/* glyph wasn't found. */
/* */
static FT_Int
t1_lookup_glyph_by_stdcharcode( T1_Decoder decoder,
FT_Int charcode )
{
FT_UInt n;
const FT_String* glyph_name;
FT_Service_PsCMaps psnames = decoder->psnames;
/* check range of standard char code */
if ( charcode < 0 || charcode > 255 )
return -1;
glyph_name = psnames->adobe_std_strings(
psnames->adobe_std_encoding[charcode]);
for ( n = 0; n < decoder->num_glyphs; n++ )
{
FT_String* name = (FT_String*)decoder->glyph_names[n];
if ( name &&
name[0] == glyph_name[0] &&
ft_strcmp( name, glyph_name ) == 0 )
return n;
}
return -1;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1operator_seac */
/* */
/* <Description> */
/* Implements the `seac' Type 1 operator for a Type 1 decoder. */
/* */
/* <Input> */
/* decoder :: The current CID decoder. */
/* */
/* asb :: The accent's side bearing. */
/* */
/* adx :: The horizontal offset of the accent. */
/* */
/* ady :: The vertical offset of the accent. */
/* */
/* bchar :: The base character's StandardEncoding charcode. */
/* */
/* achar :: The accent character's StandardEncoding charcode. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
static FT_Error
t1operator_seac( T1_Decoder decoder,
FT_Pos asb,
FT_Pos adx,
FT_Pos ady,
FT_Int bchar,
FT_Int achar )
{
FT_Error error;
FT_Int bchar_index, achar_index;
#if 0
FT_Int n_base_points;
FT_Outline* base = decoder->builder.base;
#endif
FT_Vector left_bearing, advance;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
T1_Face face = (T1_Face)decoder->builder.face;
#endif
if ( decoder->seac )
{
FT_ERROR(( "t1operator_seac: invalid nested seac\n" ));
return FT_THROW( Syntax_Error );
}
if ( decoder->builder.metrics_only )
{
FT_ERROR(( "t1operator_seac: unexpected seac\n" ));
return FT_THROW( Syntax_Error );
}
/* seac weirdness */
adx += decoder->builder.left_bearing.x;
/* `glyph_names' is set to 0 for CID fonts which do not */
/* include an encoding. How can we deal with these? */
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( decoder->glyph_names == 0 &&
!face->root.internal->incremental_interface )
#else
if ( decoder->glyph_names == 0 )
#endif /* FT_CONFIG_OPTION_INCREMENTAL */
{
FT_ERROR(( "t1operator_seac:"
" glyph names table not available in this font\n" ));
return FT_THROW( Syntax_Error );
}
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( face->root.internal->incremental_interface )
{
/* the caller must handle the font encoding also */
bchar_index = bchar;
achar_index = achar;
}
else
#endif
{
bchar_index = t1_lookup_glyph_by_stdcharcode( decoder, bchar );
achar_index = t1_lookup_glyph_by_stdcharcode( decoder, achar );
}
if ( bchar_index < 0 || achar_index < 0 )
{
FT_ERROR(( "t1operator_seac:"
" invalid seac character code arguments\n" ));
return FT_THROW( Syntax_Error );
}
/* if we are trying to load a composite glyph, do not load the */
/* accent character and return the array of subglyphs. */
if ( decoder->builder.no_recurse )
{
FT_GlyphSlot glyph = (FT_GlyphSlot)decoder->builder.glyph;
FT_GlyphLoader loader = glyph->internal->loader;
FT_SubGlyph subg;
/* reallocate subglyph array if necessary */
error = FT_GlyphLoader_CheckSubGlyphs( loader, 2 );
if ( error )
goto Exit;
subg = loader->current.subglyphs;
/* subglyph 0 = base character */
subg->index = bchar_index;
subg->flags = FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES |
FT_SUBGLYPH_FLAG_USE_MY_METRICS;
subg->arg1 = 0;
subg->arg2 = 0;
subg++;
/* subglyph 1 = accent character */
subg->index = achar_index;
subg->flags = FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES;
subg->arg1 = (FT_Int)FIXED_TO_INT( adx - asb );
subg->arg2 = (FT_Int)FIXED_TO_INT( ady );
/* set up remaining glyph fields */
glyph->num_subglyphs = 2;
glyph->subglyphs = loader->base.subglyphs;
glyph->format = FT_GLYPH_FORMAT_COMPOSITE;
loader->current.num_subglyphs = 2;
goto Exit;
}
/* First load `bchar' in builder */
/* now load the unscaled outline */
FT_GlyphLoader_Prepare( decoder->builder.loader ); /* prepare loader */
/* the seac operator must not be nested */
decoder->seac = TRUE;
error = t1_decoder_parse_glyph( decoder, bchar_index );
decoder->seac = FALSE;
if ( error )
goto Exit;
/* save the left bearing and width of the base character */
/* as they will be erased by the next load. */
left_bearing = decoder->builder.left_bearing;
advance = decoder->builder.advance;
decoder->builder.left_bearing.x = 0;
decoder->builder.left_bearing.y = 0;
decoder->builder.pos_x = adx - asb;
decoder->builder.pos_y = ady;
/* Now load `achar' on top of */
/* the base outline */
/* the seac operator must not be nested */
decoder->seac = TRUE;
error = t1_decoder_parse_glyph( decoder, achar_index );
decoder->seac = FALSE;
if ( error )
goto Exit;
/* restore the left side bearing and */
/* advance width of the base character */
decoder->builder.left_bearing = left_bearing;
decoder->builder.advance = advance;
decoder->builder.pos_x = 0;
decoder->builder.pos_y = 0;
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1_decoder_parse_charstrings */
/* */
/* <Description> */
/* Parses a given Type 1 charstrings program. */
/* */
/* <Input> */
/* decoder :: The current Type 1 decoder. */
/* */
/* charstring_base :: The base address of the charstring stream. */
/* */
/* charstring_len :: The length in bytes of the charstring stream. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^
(FT_PtrDist)(char*)&decoder ^
(FT_PtrDist)(char*)&charstring_base ) &
FT_ULONG_MAX ) ;
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
ft_memset( &decoder->buildchar[0],
0,
sizeof ( decoder->buildchar[0] ) * decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %ld", value ));
else
FT_TRACE4(( " %ld", Fix2Int( value ) ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( decoder->flex_state == 0 ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 6 ) )
!= FT_Err_Ok )
goto Fail;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( decoder->flex_state == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
break;
case 3: /* change hints */
if ( arg_cnt != 1 )
goto Unexpected_OtherSubr;
known_othersubr_result_cnt = 1;
if ( hinter )
hinter->reset( hinter->hints, builder->current->n_points );
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || blend == NULL )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || blend == NULL )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || blend == NULL )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints, builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; ++i )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 3 ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( ( error = t1_builder_add_point1( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 3 ) )
!= FT_Err_Ok )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok ||
( error = t1_builder_check_points( builder, 3 ) )
!= FT_Err_Ok )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( ( error = t1_builder_start_point( builder, x, y ) )
!= FT_Err_Ok )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
++top;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( idx < 0 || idx >= (FT_Int)decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
/* parse a single Type 1 glyph */
FT_LOCAL_DEF( FT_Error )
t1_decoder_parse_glyph( T1_Decoder decoder,
FT_UInt glyph )
{
return decoder->parse_callback( decoder, glyph );
}
/* initialize T1 decoder */
FT_LOCAL_DEF( FT_Error )
t1_decoder_init( T1_Decoder decoder,
FT_Face face,
FT_Size size,
FT_GlyphSlot slot,
FT_Byte** glyph_names,
PS_Blend blend,
FT_Bool hinting,
FT_Render_Mode hint_mode,
T1_Decoder_Callback parse_callback )
{
FT_MEM_ZERO( decoder, sizeof ( *decoder ) );
/* retrieve PSNames interface from list of current modules */
{
FT_Service_PsCMaps psnames = 0;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
if ( !psnames )
{
FT_ERROR(( "t1_decoder_init:"
" the `psnames' module is not available\n" ));
return FT_THROW( Unimplemented_Feature );
}
decoder->psnames = psnames;
}
t1_builder_init( &decoder->builder, face, size, slot, hinting );
/* decoder->buildchar and decoder->len_buildchar have to be */
/* initialized by the caller since we cannot know the length */
/* of the BuildCharArray */
decoder->num_glyphs = (FT_UInt)face->num_glyphs;
decoder->glyph_names = glyph_names;
decoder->hint_mode = hint_mode;
decoder->blend = blend;
decoder->parse_callback = parse_callback;
decoder->funcs = t1_decoder_funcs;
return FT_Err_Ok;
}
/* finalize T1 decoder */
FT_LOCAL_DEF( void )
t1_decoder_done( T1_Decoder decoder )
{
t1_builder_done( &decoder->builder );
}
/* END */
| mit |
globaltoken/globaltoken | src/leveldb/db/c_test.c | 4294 | 11634 | /* Copyright (c) 2011 The LevelDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. See the AUTHORS file for names of contributors. */
#include "leveldb/c.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
const char* phase = "";
static char dbname[200];
static void StartPhase(const char* name) {
fprintf(stderr, "=== Test %s\n", name);
phase = name;
}
static const char* GetTempDir(void) {
const char* ret = getenv("TEST_TMPDIR");
if (ret == NULL || ret[0] == '\0')
ret = "/tmp";
return ret;
}
#define CheckNoError(err) \
if ((err) != NULL) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, phase, (err)); \
abort(); \
}
#define CheckCondition(cond) \
if (!(cond)) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, phase, #cond); \
abort(); \
}
static void CheckEqual(const char* expected, const char* v, size_t n) {
if (expected == NULL && v == NULL) {
// ok
} else if (expected != NULL && v != NULL && n == strlen(expected) &&
memcmp(expected, v, n) == 0) {
// ok
return;
} else {
fprintf(stderr, "%s: expected '%s', got '%s'\n",
phase,
(expected ? expected : "(null)"),
(v ? v : "(null"));
abort();
}
}
static void Free(char** ptr) {
if (*ptr) {
free(*ptr);
*ptr = NULL;
}
}
static void CheckGet(
leveldb_t* db,
const leveldb_readoptions_t* options,
const char* key,
const char* expected) {
char* err = NULL;
size_t val_len;
char* val;
val = leveldb_get(db, options, key, strlen(key), &val_len, &err);
CheckNoError(err);
CheckEqual(expected, val, val_len);
Free(&val);
}
static void CheckIter(leveldb_iterator_t* iter,
const char* key, const char* val) {
size_t len;
const char* str;
str = leveldb_iter_key(iter, &len);
CheckEqual(key, str, len);
str = leveldb_iter_value(iter, &len);
CheckEqual(val, str, len);
}
// Callback from leveldb_writebatch_iterate()
static void CheckPut(void* ptr,
const char* k, size_t klen,
const char* v, size_t vlen) {
int* state = (int*) ptr;
CheckCondition(*state < 2);
switch (*state) {
case 0:
CheckEqual("bar", k, klen);
CheckEqual("b", v, vlen);
break;
case 1:
CheckEqual("box", k, klen);
CheckEqual("c", v, vlen);
break;
}
(*state)++;
}
// Callback from leveldb_writebatch_iterate()
static void CheckDel(void* ptr, const char* k, size_t klen) {
int* state = (int*) ptr;
CheckCondition(*state == 2);
CheckEqual("bar", k, klen);
(*state)++;
}
static void CmpDestroy(void* arg) { }
static int CmpCompare(void* arg, const char* a, size_t alen,
const char* b, size_t blen) {
int n = (alen < blen) ? alen : blen;
int r = memcmp(a, b, n);
if (r == 0) {
if (alen < blen) r = -1;
else if (alen > blen) r = +1;
}
return r;
}
static const char* CmpName(void* arg) {
return "foo";
}
// Custom filter policy
static unsigned char fake_filter_result = 1;
static void FilterDestroy(void* arg) { }
static const char* FilterName(void* arg) {
return "TestFilter";
}
static char* FilterCreate(
void* arg,
const char* const* key_array, const size_t* key_length_array,
int num_keys,
size_t* filter_length) {
*filter_length = 4;
char* result = malloc(4);
memcpy(result, "fake", 4);
return result;
}
unsigned char FilterKeyMatch(
void* arg,
const char* key, size_t length,
const char* filter, size_t filter_length) {
CheckCondition(filter_length == 4);
CheckCondition(memcmp(filter, "fake", 4) == 0);
return fake_filter_result;
}
int main(int argc, char** argv) {
leveldb_t* db;
leveldb_comparator_t* cmp;
leveldb_cache_t* cache;
leveldb_env_t* env;
leveldb_options_t* options;
leveldb_readoptions_t* roptions;
leveldb_writeoptions_t* woptions;
char* err = NULL;
int run = -1;
CheckCondition(leveldb_major_version() >= 1);
CheckCondition(leveldb_minor_version() >= 1);
snprintf(dbname, sizeof(dbname),
"%s/leveldb_c_test-%d",
GetTempDir(),
((int) geteuid()));
StartPhase("create_objects");
cmp = leveldb_comparator_create(NULL, CmpDestroy, CmpCompare, CmpName);
env = leveldb_create_default_env();
cache = leveldb_cache_create_lru(100000);
options = leveldb_options_create();
leveldb_options_set_comparator(options, cmp);
leveldb_options_set_error_if_exists(options, 1);
leveldb_options_set_cache(options, cache);
leveldb_options_set_env(options, env);
leveldb_options_set_info_log(options, NULL);
leveldb_options_set_write_buffer_size(options, 100000);
leveldb_options_set_paranoid_checks(options, 1);
leveldb_options_set_max_open_files(options, 10);
leveldb_options_set_block_size(options, 1024);
leveldb_options_set_block_restart_interval(options, 8);
leveldb_options_set_compression(options, leveldb_no_compression);
roptions = leveldb_readoptions_create();
leveldb_readoptions_set_verify_checksums(roptions, 1);
leveldb_readoptions_set_fill_cache(roptions, 0);
woptions = leveldb_writeoptions_create();
leveldb_writeoptions_set_sync(woptions, 1);
StartPhase("destroy");
leveldb_destroy_db(options, dbname, &err);
Free(&err);
StartPhase("open_error");
db = leveldb_open(options, dbname, &err);
CheckCondition(err != NULL);
Free(&err);
StartPhase("leveldb_free");
db = leveldb_open(options, dbname, &err);
CheckCondition(err != NULL);
leveldb_free(err);
err = NULL;
StartPhase("open");
leveldb_options_set_create_if_missing(options, 1);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", NULL);
StartPhase("put");
leveldb_put(db, woptions, "foo", 3, "hello", 5, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", "hello");
StartPhase("compactall");
leveldb_compact_range(db, NULL, 0, NULL, 0);
CheckGet(db, roptions, "foo", "hello");
StartPhase("compactrange");
leveldb_compact_range(db, "a", 1, "z", 1);
CheckGet(db, roptions, "foo", "hello");
StartPhase("writebatch");
{
leveldb_writebatch_t* wb = leveldb_writebatch_create();
leveldb_writebatch_put(wb, "foo", 3, "a", 1);
leveldb_writebatch_clear(wb);
leveldb_writebatch_put(wb, "bar", 3, "b", 1);
leveldb_writebatch_put(wb, "box", 3, "c", 1);
leveldb_writebatch_delete(wb, "bar", 3);
leveldb_write(db, woptions, wb, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", "hello");
CheckGet(db, roptions, "bar", NULL);
CheckGet(db, roptions, "box", "c");
int pos = 0;
leveldb_writebatch_iterate(wb, &pos, CheckPut, CheckDel);
CheckCondition(pos == 3);
leveldb_writebatch_destroy(wb);
}
StartPhase("iter");
{
leveldb_iterator_t* iter = leveldb_create_iterator(db, roptions);
CheckCondition(!leveldb_iter_valid(iter));
leveldb_iter_seek_to_first(iter);
CheckCondition(leveldb_iter_valid(iter));
CheckIter(iter, "box", "c");
leveldb_iter_next(iter);
CheckIter(iter, "foo", "hello");
leveldb_iter_prev(iter);
CheckIter(iter, "box", "c");
leveldb_iter_prev(iter);
CheckCondition(!leveldb_iter_valid(iter));
leveldb_iter_seek_to_last(iter);
CheckIter(iter, "foo", "hello");
leveldb_iter_seek(iter, "b", 1);
CheckIter(iter, "box", "c");
leveldb_iter_get_error(iter, &err);
CheckNoError(err);
leveldb_iter_destroy(iter);
}
StartPhase("approximate_sizes");
{
int i;
int n = 20000;
char keybuf[100];
char valbuf[100];
uint64_t sizes[2];
const char* start[2] = { "a", "k00000000000000010000" };
size_t start_len[2] = { 1, 21 };
const char* limit[2] = { "k00000000000000010000", "z" };
size_t limit_len[2] = { 21, 1 };
leveldb_writeoptions_set_sync(woptions, 0);
for (i = 0; i < n; i++) {
snprintf(keybuf, sizeof(keybuf), "k%020d", i);
snprintf(valbuf, sizeof(valbuf), "v%020d", i);
leveldb_put(db, woptions, keybuf, strlen(keybuf), valbuf, strlen(valbuf),
&err);
CheckNoError(err);
}
leveldb_approximate_sizes(db, 2, start, start_len, limit, limit_len, sizes);
CheckCondition(sizes[0] > 0);
CheckCondition(sizes[1] > 0);
}
StartPhase("property");
{
char* prop = leveldb_property_value(db, "nosuchprop");
CheckCondition(prop == NULL);
prop = leveldb_property_value(db, "leveldb.stats");
CheckCondition(prop != NULL);
Free(&prop);
}
StartPhase("snapshot");
{
const leveldb_snapshot_t* snap;
snap = leveldb_create_snapshot(db);
leveldb_delete(db, woptions, "foo", 3, &err);
CheckNoError(err);
leveldb_readoptions_set_snapshot(roptions, snap);
CheckGet(db, roptions, "foo", "hello");
leveldb_readoptions_set_snapshot(roptions, NULL);
CheckGet(db, roptions, "foo", NULL);
leveldb_release_snapshot(db, snap);
}
StartPhase("repair");
{
leveldb_close(db);
leveldb_options_set_create_if_missing(options, 0);
leveldb_options_set_error_if_exists(options, 0);
leveldb_repair_db(options, dbname, &err);
CheckNoError(err);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", NULL);
CheckGet(db, roptions, "bar", NULL);
CheckGet(db, roptions, "box", "c");
leveldb_options_set_create_if_missing(options, 1);
leveldb_options_set_error_if_exists(options, 1);
}
StartPhase("filter");
for (run = 0; run < 2; run++) {
// First run uses custom filter, second run uses bloom filter
CheckNoError(err);
leveldb_filterpolicy_t* policy;
if (run == 0) {
policy = leveldb_filterpolicy_create(
NULL, FilterDestroy, FilterCreate, FilterKeyMatch, FilterName);
} else {
policy = leveldb_filterpolicy_create_bloom(10);
}
// Create new database
leveldb_close(db);
leveldb_destroy_db(options, dbname, &err);
leveldb_options_set_filter_policy(options, policy);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
leveldb_put(db, woptions, "foo", 3, "foovalue", 8, &err);
CheckNoError(err);
leveldb_put(db, woptions, "bar", 3, "barvalue", 8, &err);
CheckNoError(err);
leveldb_compact_range(db, NULL, 0, NULL, 0);
fake_filter_result = 1;
CheckGet(db, roptions, "foo", "foovalue");
CheckGet(db, roptions, "bar", "barvalue");
if (phase == 0) {
// Must not find value when custom filter returns false
fake_filter_result = 0;
CheckGet(db, roptions, "foo", NULL);
CheckGet(db, roptions, "bar", NULL);
fake_filter_result = 1;
CheckGet(db, roptions, "foo", "foovalue");
CheckGet(db, roptions, "bar", "barvalue");
}
leveldb_options_set_filter_policy(options, NULL);
leveldb_filterpolicy_destroy(policy);
}
StartPhase("cleanup");
leveldb_close(db);
leveldb_options_destroy(options);
leveldb_readoptions_destroy(roptions);
leveldb_writeoptions_destroy(woptions);
leveldb_cache_destroy(cache);
leveldb_comparator_destroy(cmp);
leveldb_env_destroy(env);
fprintf(stderr, "PASS\n");
return 0;
}
| mit |
foric/lk-lollipop | lib/openssl/crypto/asn1/a_bitstr.c | 712 | 7281 | /* crypto/asn1/a_bitstr.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/asn1.h>
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
{ return M_ASN1_BIT_STRING_set(x, d, len); }
int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp)
{
int ret,j,bits,len;
unsigned char *p,*d;
if (a == NULL) return(0);
len=a->length;
if (len > 0)
{
if (a->flags & ASN1_STRING_FLAG_BITS_LEFT)
{
bits=(int)a->flags&0x07;
}
else
{
for ( ; len > 0; len--)
{
if (a->data[len-1]) break;
}
j=a->data[len-1];
if (j & 0x01) bits=0;
else if (j & 0x02) bits=1;
else if (j & 0x04) bits=2;
else if (j & 0x08) bits=3;
else if (j & 0x10) bits=4;
else if (j & 0x20) bits=5;
else if (j & 0x40) bits=6;
else if (j & 0x80) bits=7;
else bits=0; /* should not happen */
}
}
else
bits=0;
ret=1+len;
if (pp == NULL) return(ret);
p= *pp;
*(p++)=(unsigned char)bits;
d=a->data;
memcpy(p,d,len);
p+=len;
if (len > 0) p[-1]&=(0xff<<bits);
*pp=p;
return(ret);
}
ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long len)
{
ASN1_BIT_STRING *ret=NULL;
const unsigned char *p;
unsigned char *s;
int i;
if (len < 1)
{
i=ASN1_R_STRING_TOO_SHORT;
goto err;
}
if ((a == NULL) || ((*a) == NULL))
{
if ((ret=M_ASN1_BIT_STRING_new()) == NULL) return(NULL);
}
else
ret=(*a);
p= *pp;
i= *(p++);
/* We do this to preserve the settings. If we modify
* the settings, via the _set_bit function, we will recalculate
* on output */
ret->flags&= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07); /* clear */
ret->flags|=(ASN1_STRING_FLAG_BITS_LEFT|(i&0x07)); /* set */
if (len-- > 1) /* using one because of the bits left byte */
{
s=(unsigned char *)OPENSSL_malloc((int)len);
if (s == NULL)
{
i=ERR_R_MALLOC_FAILURE;
goto err;
}
memcpy(s,p,(int)len);
s[len-1]&=(0xff<<i);
p+=len;
}
else
s=NULL;
ret->length=(int)len;
if (ret->data != NULL) OPENSSL_free(ret->data);
ret->data=s;
ret->type=V_ASN1_BIT_STRING;
if (a != NULL) (*a)=ret;
*pp=p;
return(ret);
err:
ASN1err(ASN1_F_C2I_ASN1_BIT_STRING,i);
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_BIT_STRING_free(ret);
return(NULL);
}
/* These next 2 functions from Goetz Babin-Ebell <babinebell@trustcenter.de>
*/
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value)
{
int w,v,iv;
unsigned char *c;
w=n/8;
v=1<<(7-(n&0x07));
iv= ~v;
if (!value) v=0;
if (a == NULL)
return 0;
a->flags&= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07); /* clear, set on write */
if ((a->length < (w+1)) || (a->data == NULL))
{
if (!value) return(1); /* Don't need to set */
if (a->data == NULL)
c=(unsigned char *)OPENSSL_malloc(w+1);
else
c=(unsigned char *)OPENSSL_realloc_clean(a->data,
a->length,
w+1);
if (c == NULL)
{
ASN1err(ASN1_F_ASN1_BIT_STRING_SET_BIT,ERR_R_MALLOC_FAILURE);
return 0;
}
if (w+1-a->length > 0) memset(c+a->length, 0, w+1-a->length);
a->data=c;
a->length=w+1;
}
a->data[w]=((a->data[w])&iv)|v;
while ((a->length > 0) && (a->data[a->length-1] == 0))
a->length--;
return(1);
}
int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n)
{
int w,v;
w=n/8;
v=1<<(7-(n&0x07));
if ((a == NULL) || (a->length < (w+1)) || (a->data == NULL))
return(0);
return((a->data[w]&v) != 0);
}
/*
* Checks if the given bit string contains only bits specified by
* the flags vector. Returns 0 if there is at least one bit set in 'a'
* which is not specified in 'flags', 1 otherwise.
* 'len' is the length of 'flags'.
*/
int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a,
unsigned char *flags, int flags_len)
{
int i, ok;
/* Check if there is one bit set at all. */
if (!a || !a->data) return 1;
/* Check each byte of the internal representation of the bit string. */
ok = 1;
for (i = 0; i < a->length && ok; ++i)
{
unsigned char mask = i < flags_len ? ~flags[i] : 0xff;
/* We are done if there is an unneeded bit set. */
ok = (a->data[i] & mask) == 0;
}
return ok;
}
| mit |
aguadev/aguadev | apps/node/node-v0.10.15/deps/openssl/openssl/crypto/ec/ec_pmeth.c | 204 | 8138 | /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 2006.
*/
/* ====================================================================
* Copyright (c) 2006 The OpenSSL Project. 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/evp.h>
#include "evp_locl.h"
/* EC pkey context structure */
typedef struct
{
/* Key and paramgen group */
EC_GROUP *gen_group;
/* message digest */
const EVP_MD *md;
} EC_PKEY_CTX;
static int pkey_ec_init(EVP_PKEY_CTX *ctx)
{
EC_PKEY_CTX *dctx;
dctx = OPENSSL_malloc(sizeof(EC_PKEY_CTX));
if (!dctx)
return 0;
dctx->gen_group = NULL;
dctx->md = NULL;
ctx->data = dctx;
return 1;
}
static int pkey_ec_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)
{
EC_PKEY_CTX *dctx, *sctx;
if (!pkey_ec_init(dst))
return 0;
sctx = src->data;
dctx = dst->data;
if (sctx->gen_group)
{
dctx->gen_group = EC_GROUP_dup(sctx->gen_group);
if (!dctx->gen_group)
return 0;
}
dctx->md = sctx->md;
return 1;
}
static void pkey_ec_cleanup(EVP_PKEY_CTX *ctx)
{
EC_PKEY_CTX *dctx = ctx->data;
if (dctx)
{
if (dctx->gen_group)
EC_GROUP_free(dctx->gen_group);
OPENSSL_free(dctx);
}
}
static int pkey_ec_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen)
{
int ret, type;
unsigned int sltmp;
EC_PKEY_CTX *dctx = ctx->data;
EC_KEY *ec = ctx->pkey->pkey.ec;
if (!sig)
{
*siglen = ECDSA_size(ec);
return 1;
}
else if(*siglen < (size_t)ECDSA_size(ec))
{
ECerr(EC_F_PKEY_EC_SIGN, EC_R_BUFFER_TOO_SMALL);
return 0;
}
if (dctx->md)
type = EVP_MD_type(dctx->md);
else
type = NID_sha1;
ret = ECDSA_sign(type, tbs, tbslen, sig, &sltmp, ec);
if (ret <= 0)
return ret;
*siglen = (size_t)sltmp;
return 1;
}
static int pkey_ec_verify(EVP_PKEY_CTX *ctx,
const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen)
{
int ret, type;
EC_PKEY_CTX *dctx = ctx->data;
EC_KEY *ec = ctx->pkey->pkey.ec;
if (dctx->md)
type = EVP_MD_type(dctx->md);
else
type = NID_sha1;
ret = ECDSA_verify(type, tbs, tbslen, sig, siglen, ec);
return ret;
}
static int pkey_ec_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)
{
int ret;
size_t outlen;
const EC_POINT *pubkey = NULL;
if (!ctx->pkey || !ctx->peerkey)
{
ECerr(EC_F_PKEY_EC_DERIVE, EC_R_KEYS_NOT_SET);
return 0;
}
if (!key)
{
const EC_GROUP *group;
group = EC_KEY_get0_group(ctx->pkey->pkey.ec);
*keylen = (EC_GROUP_get_degree(group) + 7)/8;
return 1;
}
pubkey = EC_KEY_get0_public_key(ctx->peerkey->pkey.ec);
/* NB: unlike PKCS#3 DH, if *outlen is less than maximum size this is
* not an error, the result is truncated.
*/
outlen = *keylen;
ret = ECDH_compute_key(key, outlen, pubkey, ctx->pkey->pkey.ec, 0);
if (ret < 0)
return ret;
*keylen = ret;
return 1;
}
static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
EC_PKEY_CTX *dctx = ctx->data;
EC_GROUP *group;
switch (type)
{
case EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID:
group = EC_GROUP_new_by_curve_name(p1);
if (group == NULL)
{
ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_CURVE);
return 0;
}
if (dctx->gen_group)
EC_GROUP_free(dctx->gen_group);
dctx->gen_group = group;
return 1;
case EVP_PKEY_CTRL_MD:
if (EVP_MD_type((const EVP_MD *)p2) != NID_sha1 &&
EVP_MD_type((const EVP_MD *)p2) != NID_ecdsa_with_SHA1 &&
EVP_MD_type((const EVP_MD *)p2) != NID_sha224 &&
EVP_MD_type((const EVP_MD *)p2) != NID_sha256 &&
EVP_MD_type((const EVP_MD *)p2) != NID_sha384 &&
EVP_MD_type((const EVP_MD *)p2) != NID_sha512)
{
ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_DIGEST_TYPE);
return 0;
}
dctx->md = p2;
return 1;
case EVP_PKEY_CTRL_PEER_KEY:
/* Default behaviour is OK */
case EVP_PKEY_CTRL_DIGESTINIT:
case EVP_PKEY_CTRL_PKCS7_SIGN:
case EVP_PKEY_CTRL_CMS_SIGN:
return 1;
default:
return -2;
}
}
static int pkey_ec_ctrl_str(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
if (!strcmp(type, "ec_paramgen_curve"))
{
int nid;
nid = OBJ_sn2nid(value);
if (nid == NID_undef)
nid = OBJ_ln2nid(value);
if (nid == NID_undef)
{
ECerr(EC_F_PKEY_EC_CTRL_STR, EC_R_INVALID_CURVE);
return 0;
}
return EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid);
}
return -2;
}
static int pkey_ec_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
EC_KEY *ec = NULL;
EC_PKEY_CTX *dctx = ctx->data;
int ret = 0;
if (dctx->gen_group == NULL)
{
ECerr(EC_F_PKEY_EC_PARAMGEN, EC_R_NO_PARAMETERS_SET);
return 0;
}
ec = EC_KEY_new();
if (!ec)
return 0;
ret = EC_KEY_set_group(ec, dctx->gen_group);
if (ret)
EVP_PKEY_assign_EC_KEY(pkey, ec);
else
EC_KEY_free(ec);
return ret;
}
static int pkey_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
EC_KEY *ec = NULL;
if (ctx->pkey == NULL)
{
ECerr(EC_F_PKEY_EC_KEYGEN, EC_R_NO_PARAMETERS_SET);
return 0;
}
ec = EC_KEY_new();
if (!ec)
return 0;
EVP_PKEY_assign_EC_KEY(pkey, ec);
/* Note: if error return, pkey is freed by parent routine */
if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey))
return 0;
return EC_KEY_generate_key(pkey->pkey.ec);
}
const EVP_PKEY_METHOD ec_pkey_meth =
{
EVP_PKEY_EC,
0,
pkey_ec_init,
pkey_ec_copy,
pkey_ec_cleanup,
0,
pkey_ec_paramgen,
0,
pkey_ec_keygen,
0,
pkey_ec_sign,
0,
pkey_ec_verify,
0,0,
0,0,0,0,
0,0,
0,0,
0,
pkey_ec_derive,
pkey_ec_ctrl,
pkey_ec_ctrl_str
};
| mit |
JeeLiu/WinObjC | deps/3rdparty/icu/icu/source/tools/ctestfw/uperf.cpp | 220 | 17132 | /********************************************************************
* COPYRIGHT:
* Copyright (c) 2002-2012, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
// Defines _XOPEN_SOURCE for access to POSIX functions.
// Must be before any other #includes.
#include "uposixdefs.h"
#include "unicode/uperf.h"
#include "uoptions.h"
#include "cmemory.h"
#include <stdio.h>
#include <stdlib.h>
#if !UCONFIG_NO_CONVERSION
UPerfFunction::~UPerfFunction() {}
static const char delim = '/';
static int32_t execCount = 0;
UPerfTest* UPerfTest::gTest = NULL;
static const int MAXLINES = 40000;
const char UPerfTest::gUsageString[] =
"Usage: %s [OPTIONS] [FILES]\n"
"\tReads the input file and prints out time taken in seconds\n"
"Options:\n"
"\t-h or -? or --help this usage text\n"
"\t-v or --verbose print extra information when processing files\n"
"\t-s or --sourcedir source directory for files followed by path\n"
"\t followed by path\n"
"\t-e or --encoding encoding of source files\n"
"\t-u or --uselen perform timing analysis on non-null terminated buffer using length\n"
"\t-f or --file-name file to be used as input data\n"
"\t-p or --passes Number of passes to be performed. Requires Numeric argument.\n"
"\t Cannot be used with --time\n"
"\t-i or --iterations Number of iterations to be performed. Requires Numeric argument\n"
"\t-t or --time Threshold time for looping until in seconds. Requires Numeric argument.\n"
"\t Cannot be used with --iterations\n"
"\t-l or --line-mode The data file should be processed in line mode\n"
"\t-b or --bulk-mode The data file should be processed in file based.\n"
"\t Cannot be used with --line-mode\n"
"\t-L or --locale Locale for the test\n";
enum
{
HELP1,
HELP2,
VERBOSE,
SOURCEDIR,
ENCODING,
USELEN,
FILE_NAME,
PASSES,
ITERATIONS,
TIME,
LINE_MODE,
BULK_MODE,
LOCALE,
OPTIONS_COUNT
};
static UOption options[OPTIONS_COUNT+20]={
UOPTION_HELP_H,
UOPTION_HELP_QUESTION_MARK,
UOPTION_VERBOSE,
UOPTION_SOURCEDIR,
UOPTION_ENCODING,
UOPTION_DEF( "uselen", 'u', UOPT_NO_ARG),
UOPTION_DEF( "file-name", 'f', UOPT_REQUIRES_ARG),
UOPTION_DEF( "passes", 'p', UOPT_REQUIRES_ARG),
UOPTION_DEF( "iterations", 'i', UOPT_REQUIRES_ARG),
UOPTION_DEF( "time", 't', UOPT_REQUIRES_ARG),
UOPTION_DEF( "line-mode", 'l', UOPT_NO_ARG),
UOPTION_DEF( "bulk-mode", 'b', UOPT_NO_ARG),
UOPTION_DEF( "locale", 'L', UOPT_REQUIRES_ARG)
};
UPerfTest::UPerfTest(int32_t argc, const char* argv[], UErrorCode& status)
: _argc(argc), _argv(argv), _addUsage(NULL),
ucharBuf(NULL), encoding(""),
uselen(FALSE),
fileName(NULL), sourceDir("."),
lines(NULL), numLines(0), line_mode(TRUE),
buffer(NULL), bufferLen(0),
verbose(FALSE), bulk_mode(FALSE),
passes(1), iterations(0), time(0),
locale(NULL) {
init(NULL, 0, status);
}
UPerfTest::UPerfTest(int32_t argc, const char* argv[],
UOption addOptions[], int32_t addOptionsCount,
const char *addUsage,
UErrorCode& status)
: _argc(argc), _argv(argv), _addUsage(addUsage),
ucharBuf(NULL), encoding(""),
uselen(FALSE),
fileName(NULL), sourceDir("."),
lines(NULL), numLines(0), line_mode(TRUE),
buffer(NULL), bufferLen(0),
verbose(FALSE), bulk_mode(FALSE),
passes(1), iterations(0), time(0),
locale(NULL) {
init(addOptions, addOptionsCount, status);
}
void UPerfTest::init(UOption addOptions[], int32_t addOptionsCount,
UErrorCode& status) {
//initialize the argument list
U_MAIN_INIT_ARGS(_argc, _argv);
resolvedFileName = NULL;
// add specific options
int32_t optionsCount = OPTIONS_COUNT;
if (addOptionsCount > 0) {
memcpy(options+optionsCount, addOptions, addOptionsCount*sizeof(UOption));
optionsCount += addOptionsCount;
}
//parse the arguments
_remainingArgc = u_parseArgs(_argc, (char**)_argv, optionsCount, options);
// copy back values for additional options
if (addOptionsCount > 0) {
memcpy(addOptions, options+OPTIONS_COUNT, addOptionsCount*sizeof(UOption));
}
// Now setup the arguments
if(_argc==1 || options[HELP1].doesOccur || options[HELP2].doesOccur) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if(options[VERBOSE].doesOccur) {
verbose = TRUE;
}
if(options[SOURCEDIR].doesOccur) {
sourceDir = options[SOURCEDIR].value;
}
if(options[ENCODING].doesOccur) {
encoding = options[ENCODING].value;
}
if(options[USELEN].doesOccur) {
uselen = TRUE;
}
if(options[FILE_NAME].doesOccur){
fileName = options[FILE_NAME].value;
}
if(options[PASSES].doesOccur) {
passes = atoi(options[PASSES].value);
}
if(options[ITERATIONS].doesOccur) {
iterations = atoi(options[ITERATIONS].value);
if(options[TIME].doesOccur) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
} else if(options[TIME].doesOccur) {
time = atoi(options[TIME].value);
} else {
iterations = 1000; // some default
}
if(options[LINE_MODE].doesOccur) {
line_mode = TRUE;
bulk_mode = FALSE;
}
if(options[BULK_MODE].doesOccur) {
bulk_mode = TRUE;
line_mode = FALSE;
}
if(options[LOCALE].doesOccur) {
locale = options[LOCALE].value;
}
int32_t len = 0;
if(fileName!=NULL){
//pre-flight
ucbuf_resolveFileName(sourceDir, fileName, NULL, &len, &status);
resolvedFileName = (char*) uprv_malloc(len);
if(resolvedFileName==NULL){
status= U_MEMORY_ALLOCATION_ERROR;
return;
}
if(status == U_BUFFER_OVERFLOW_ERROR){
status = U_ZERO_ERROR;
}
ucbuf_resolveFileName(sourceDir, fileName, resolvedFileName, &len, &status);
ucharBuf = ucbuf_open(resolvedFileName,&encoding,TRUE,FALSE,&status);
if(U_FAILURE(status)){
printf("Could not open the input file %s. Error: %s\n", fileName, u_errorName(status));
return;
}
}
}
ULine* UPerfTest::getLines(UErrorCode& status){
if (U_FAILURE(status)) {
return NULL;
}
if (lines != NULL) {
return lines; // don't do it again
}
lines = new ULine[MAXLINES];
int maxLines = MAXLINES;
numLines=0;
const UChar* line=NULL;
int32_t len =0;
for (;;) {
line = ucbuf_readline(ucharBuf,&len,&status);
if(line == NULL || U_FAILURE(status)){
break;
}
lines[numLines].name = new UChar[len];
lines[numLines].len = len;
memcpy(lines[numLines].name, line, len * U_SIZEOF_UCHAR);
numLines++;
len = 0;
if (numLines >= maxLines) {
maxLines += MAXLINES;
ULine *newLines = new ULine[maxLines];
if(newLines == NULL) {
fprintf(stderr, "Out of memory reading line %d.\n", (int)numLines);
status= U_MEMORY_ALLOCATION_ERROR;
delete []lines;
return NULL;
}
memcpy(newLines, lines, numLines*sizeof(ULine));
delete []lines;
lines = newLines;
}
}
return lines;
}
const UChar* UPerfTest::getBuffer(int32_t& len, UErrorCode& status){
if (U_FAILURE(status)) {
return NULL;
}
len = ucbuf_size(ucharBuf);
buffer = (UChar*) uprv_malloc(U_SIZEOF_UCHAR * (len+1));
u_strncpy(buffer,ucbuf_getBuffer(ucharBuf,&bufferLen,&status),len);
buffer[len]=0;
len = bufferLen;
return buffer;
}
UBool UPerfTest::run(){
if(_remainingArgc==1){
// Testing all methods
return runTest();
}
UBool res=FALSE;
// Test only the specified fucntion
for (int i = 1; i < _remainingArgc; ++i) {
if (_argv[i][0] != '-') {
char* name = (char*) _argv[i];
if(verbose==TRUE){
//fprintf(stdout, "\n=== Handling test: %s: ===\n", name);
//fprintf(stdout, "\n%s:\n", name);
}
char* parameter = strchr( name, '@' );
if (parameter) {
*parameter = 0;
parameter += 1;
}
execCount = 0;
res = runTest( name, parameter );
if (!res || (execCount <= 0)) {
fprintf(stdout, "\n---ERROR: Test doesn't exist: %s!\n", name);
return FALSE;
}
}
}
return res;
}
UBool UPerfTest::runTest(char* name, char* par ){
UBool rval;
char* pos = NULL;
if (name)
pos = strchr( name, delim ); // check if name contains path (by looking for '/')
if (pos) {
path = pos+1; // store subpath for calling subtest
*pos = 0; // split into two strings
}else{
path = NULL;
}
if (!name || (name[0] == 0) || (strcmp(name, "*") == 0)) {
rval = runTestLoop( NULL, NULL );
}else if (strcmp( name, "LIST" ) == 0) {
this->usage();
rval = TRUE;
}else{
rval = runTestLoop( name, par );
}
if (pos)
*pos = delim; // restore original value at pos
return rval;
}
void UPerfTest::setPath( char* pathVal )
{
this->path = pathVal;
}
// call individual tests, to be overriden to call implementations
UPerfFunction* UPerfTest::runIndexedTest( int32_t /*index*/, UBool /*exec*/, const char* & /*name*/, char* /*par*/ )
{
// to be overriden by a method like:
/*
switch (index) {
case 0: name = "First Test"; if (exec) FirstTest( par ); break;
case 1: name = "Second Test"; if (exec) SecondTest( par ); break;
default: name = ""; break;
}
*/
fprintf(stderr,"*** runIndexedTest needs to be overriden! ***");
return NULL;
}
UBool UPerfTest::runTestLoop( char* testname, char* par )
{
int32_t index = 0;
const char* name;
UBool run_this_test;
UBool rval = FALSE;
UErrorCode status = U_ZERO_ERROR;
UPerfTest* saveTest = gTest;
gTest = this;
int32_t loops = 0;
double t=0;
int32_t n = 1;
long ops;
do {
this->runIndexedTest( index, FALSE, name );
if (!name || (name[0] == 0))
break;
if (!testname) {
run_this_test = TRUE;
}else{
run_this_test = (UBool) (strcmp( name, testname ) == 0);
}
if (run_this_test) {
UPerfFunction* testFunction = this->runIndexedTest( index, TRUE, name, par );
execCount++;
rval=TRUE;
if(testFunction==NULL){
fprintf(stderr,"%s function returned NULL", name);
return FALSE;
}
ops = testFunction->getOperationsPerIteration();
if (ops < 1) {
fprintf(stderr, "%s returned an illegal operations/iteration()\n", name);
return FALSE;
}
if(iterations == 0) {
n = time;
// Run for specified duration in seconds
if(verbose==TRUE){
fprintf(stdout,"= %s calibrating %i seconds \n", name, (int)n);
}
//n *= 1000; // s => ms
//System.out.println("# " + meth.getName() + " " + n + " sec");
int32_t failsafe = 1; // last resort for very fast methods
t = 0;
while (t < (int)(n * 0.9)) { // 90% is close enough
if (loops == 0 || t == 0) {
loops = failsafe;
failsafe *= 10;
} else {
//System.out.println("# " + meth.getName() + " x " + loops + " = " + t);
loops = (int)((double)n / t * loops + 0.5);
if (loops == 0) {
fprintf(stderr,"Unable to converge on desired duration");
return FALSE;
}
}
//System.out.println("# " + meth.getName() + " x " + loops);
t = testFunction->time(loops,&status);
if(U_FAILURE(status)){
printf("Performance test failed with error: %s \n", u_errorName(status));
break;
}
}
} else {
loops = iterations;
}
double min_t=1000000.0, sum_t=0.0;
long events = -1;
for(int32_t ps =0; ps < passes; ps++){
fprintf(stdout,"= %s begin " ,name);
if(verbose==TRUE){
if(iterations > 0) {
fprintf(stdout, "%i\n", (int)loops);
} else {
fprintf(stdout, "%i\n", (int)n);
}
} else {
fprintf(stdout, "\n");
}
t = testFunction->time(loops, &status);
if(U_FAILURE(status)){
printf("Performance test failed with error: %s \n", u_errorName(status));
break;
}
sum_t+=t;
if(t<min_t) {
min_t=t;
}
events = testFunction->getEventsPerIteration();
//print info only in verbose mode
if(verbose==TRUE){
if(events == -1){
fprintf(stdout, "= %s end: %f loops: %i operations: %li \n", name, t, (int)loops, ops);
}else{
fprintf(stdout, "= %s end: %f loops: %i operations: %li events: %li\n", name, t, (int)loops, ops, events);
}
}else{
if(events == -1){
fprintf(stdout,"= %s end %f %i %li\n", name, t, (int)loops, ops);
}else{
fprintf(stdout,"= %s end %f %i %li %li\n", name, t, (int)loops, ops, events);
}
}
}
if(verbose && U_SUCCESS(status)) {
double avg_t = sum_t/passes;
if (loops == 0 || ops == 0) {
fprintf(stderr, "%s did not run\n", name);
}
else if(events == -1) {
fprintf(stdout, "%%= %s avg: %.4g loops: %i avg/op: %.4g ns\n",
name, avg_t, (int)loops, (avg_t*1E9)/(loops*ops));
fprintf(stdout, "_= %s min: %.4g loops: %i min/op: %.4g ns\n",
name, min_t, (int)loops, (min_t*1E9)/(loops*ops));
}
else {
fprintf(stdout, "%%= %s avg: %.4g loops: %i avg/op: %.4g ns avg/event: %.4g ns\n",
name, avg_t, (int)loops, (avg_t*1E9)/(loops*ops), (avg_t*1E9)/(loops*events));
fprintf(stdout, "_= %s min: %.4g loops: %i min/op: %.4g ns min/event: %.4g ns\n",
name, min_t, (int)loops, (min_t*1E9)/(loops*ops), (min_t*1E9)/(loops*events));
}
}
delete testFunction;
}
index++;
}while(name);
gTest = saveTest;
return rval;
}
/**
* Print a usage message for this test class.
*/
void UPerfTest::usage( void )
{
puts(gUsageString);
if (_addUsage != NULL) {
puts(_addUsage);
}
UBool save_verbose = verbose;
verbose = TRUE;
fprintf(stdout,"Test names:\n");
fprintf(stdout,"-----------\n");
int32_t index = 0;
const char* name = NULL;
do{
this->runIndexedTest( index, FALSE, name );
if (!name)
break;
fprintf(stdout, "%s\n", name);
index++;
}while (name && (name[0] != 0));
verbose = save_verbose;
}
void UPerfTest::setCaller( UPerfTest* callingTest )
{
caller = callingTest;
if (caller) {
verbose = caller->verbose;
}
}
UBool UPerfTest::callTest( UPerfTest& testToBeCalled, char* par )
{
execCount--; // correct a previously assumed test-exec, as this only calls a subtest
testToBeCalled.setCaller( this );
return testToBeCalled.runTest( path, par );
}
UPerfTest::~UPerfTest(){
if(lines!=NULL){
delete[] lines;
}
if(buffer!=NULL){
uprv_free(buffer);
}
if(resolvedFileName!=NULL){
uprv_free(resolvedFileName);
}
ucbuf_close(ucharBuf);
}
#endif
| mit |
Louiefigz/flatiron-store-project-v-000 | vendor/cache/ruby/2.2.0/gems/ffi-1.9.10/ext/ffi_c/libffi/src/x86/ffi64.c | 221 | 17583 | /* -----------------------------------------------------------------------
ffi64.c - Copyright (c) 20011 Anthony Green
Copyright (c) 2008, 2010 Red Hat, Inc.
Copyright (c) 2002, 2007 Bo Thorsen <bo@suse.de>
x86-64 Foreign Function Interface
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#include <ffi.h>
#include <ffi_common.h>
#include <stdlib.h>
#include <stdarg.h>
#ifdef __x86_64__
#define MAX_GPR_REGS 6
#define MAX_SSE_REGS 8
struct register_args
{
/* Registers for argument passing. */
UINT64 gpr[MAX_GPR_REGS];
__int128_t sse[MAX_SSE_REGS];
};
extern void ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags,
void *raddr, void (*fnaddr)(void), unsigned ssecount);
/* All reference to register classes here is identical to the code in
gcc/config/i386/i386.c. Do *not* change one without the other. */
/* Register class used for passing given 64bit part of the argument.
These represent classes as documented by the PS ABI, with the
exception of SSESF, SSEDF classes, that are basically SSE class,
just gcc will use SF or DFmode move instead of DImode to avoid
reformatting penalties.
Similary we play games with INTEGERSI_CLASS to use cheaper SImode moves
whenever possible (upper half does contain padding). */
enum x86_64_reg_class
{
X86_64_NO_CLASS,
X86_64_INTEGER_CLASS,
X86_64_INTEGERSI_CLASS,
X86_64_SSE_CLASS,
X86_64_SSESF_CLASS,
X86_64_SSEDF_CLASS,
X86_64_SSEUP_CLASS,
X86_64_X87_CLASS,
X86_64_X87UP_CLASS,
X86_64_COMPLEX_X87_CLASS,
X86_64_MEMORY_CLASS
};
#define MAX_CLASSES 4
#define SSE_CLASS_P(X) ((X) >= X86_64_SSE_CLASS && X <= X86_64_SSEUP_CLASS)
/* x86-64 register passing implementation. See x86-64 ABI for details. Goal
of this code is to classify each 8bytes of incoming argument by the register
class and assign registers accordingly. */
/* Return the union class of CLASS1 and CLASS2.
See the x86-64 PS ABI for details. */
static enum x86_64_reg_class
merge_classes (enum x86_64_reg_class class1, enum x86_64_reg_class class2)
{
/* Rule #1: If both classes are equal, this is the resulting class. */
if (class1 == class2)
return class1;
/* Rule #2: If one of the classes is NO_CLASS, the resulting class is
the other class. */
if (class1 == X86_64_NO_CLASS)
return class2;
if (class2 == X86_64_NO_CLASS)
return class1;
/* Rule #3: If one of the classes is MEMORY, the result is MEMORY. */
if (class1 == X86_64_MEMORY_CLASS || class2 == X86_64_MEMORY_CLASS)
return X86_64_MEMORY_CLASS;
/* Rule #4: If one of the classes is INTEGER, the result is INTEGER. */
if ((class1 == X86_64_INTEGERSI_CLASS && class2 == X86_64_SSESF_CLASS)
|| (class2 == X86_64_INTEGERSI_CLASS && class1 == X86_64_SSESF_CLASS))
return X86_64_INTEGERSI_CLASS;
if (class1 == X86_64_INTEGER_CLASS || class1 == X86_64_INTEGERSI_CLASS
|| class2 == X86_64_INTEGER_CLASS || class2 == X86_64_INTEGERSI_CLASS)
return X86_64_INTEGER_CLASS;
/* Rule #5: If one of the classes is X87, X87UP, or COMPLEX_X87 class,
MEMORY is used. */
if (class1 == X86_64_X87_CLASS
|| class1 == X86_64_X87UP_CLASS
|| class1 == X86_64_COMPLEX_X87_CLASS
|| class2 == X86_64_X87_CLASS
|| class2 == X86_64_X87UP_CLASS
|| class2 == X86_64_COMPLEX_X87_CLASS)
return X86_64_MEMORY_CLASS;
/* Rule #6: Otherwise class SSE is used. */
return X86_64_SSE_CLASS;
}
/* Classify the argument of type TYPE and mode MODE.
CLASSES will be filled by the register class used to pass each word
of the operand. The number of words is returned. In case the parameter
should be passed in memory, 0 is returned. As a special case for zero
sized containers, classes[0] will be NO_CLASS and 1 is returned.
See the x86-64 PS ABI for details.
*/
static int
classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
size_t byte_offset)
{
switch (type->type)
{
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_POINTER:
{
int size = byte_offset + type->size;
if (size <= 4)
{
classes[0] = X86_64_INTEGERSI_CLASS;
return 1;
}
else if (size <= 8)
{
classes[0] = X86_64_INTEGER_CLASS;
return 1;
}
else if (size <= 12)
{
classes[0] = X86_64_INTEGER_CLASS;
classes[1] = X86_64_INTEGERSI_CLASS;
return 2;
}
else if (size <= 16)
{
classes[0] = classes[1] = X86_64_INTEGERSI_CLASS;
return 2;
}
else
FFI_ASSERT (0);
}
case FFI_TYPE_FLOAT:
if (!(byte_offset % 8))
classes[0] = X86_64_SSESF_CLASS;
else
classes[0] = X86_64_SSE_CLASS;
return 1;
case FFI_TYPE_DOUBLE:
classes[0] = X86_64_SSEDF_CLASS;
return 1;
case FFI_TYPE_LONGDOUBLE:
classes[0] = X86_64_X87_CLASS;
classes[1] = X86_64_X87UP_CLASS;
return 2;
case FFI_TYPE_STRUCT:
{
const int UNITS_PER_WORD = 8;
int words = (type->size + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
ffi_type **ptr;
int i;
enum x86_64_reg_class subclasses[MAX_CLASSES];
/* If the struct is larger than 32 bytes, pass it on the stack. */
if (type->size > 32)
return 0;
for (i = 0; i < words; i++)
classes[i] = X86_64_NO_CLASS;
/* Zero sized arrays or structures are NO_CLASS. We return 0 to
signalize memory class, so handle it as special case. */
if (!words)
{
classes[0] = X86_64_NO_CLASS;
return 1;
}
/* Merge the fields of structure. */
for (ptr = type->elements; *ptr != NULL; ptr++)
{
int num;
byte_offset = ALIGN (byte_offset, (*ptr)->alignment);
num = classify_argument (*ptr, subclasses, byte_offset % 8);
if (num == 0)
return 0;
for (i = 0; i < num; i++)
{
int pos = byte_offset / 8;
classes[i + pos] =
merge_classes (subclasses[i], classes[i + pos]);
}
byte_offset += (*ptr)->size;
}
if (words > 2)
{
/* When size > 16 bytes, if the first one isn't
X86_64_SSE_CLASS or any other ones aren't
X86_64_SSEUP_CLASS, everything should be passed in
memory. */
if (classes[0] != X86_64_SSE_CLASS)
return 0;
for (i = 1; i < words; i++)
if (classes[i] != X86_64_SSEUP_CLASS)
return 0;
}
/* Final merger cleanup. */
for (i = 0; i < words; i++)
{
/* If one class is MEMORY, everything should be passed in
memory. */
if (classes[i] == X86_64_MEMORY_CLASS)
return 0;
/* The X86_64_SSEUP_CLASS should be always preceded by
X86_64_SSE_CLASS or X86_64_SSEUP_CLASS. */
if (classes[i] == X86_64_SSEUP_CLASS
&& classes[i - 1] != X86_64_SSE_CLASS
&& classes[i - 1] != X86_64_SSEUP_CLASS)
{
/* The first one should never be X86_64_SSEUP_CLASS. */
FFI_ASSERT (i != 0);
classes[i] = X86_64_SSE_CLASS;
}
/* If X86_64_X87UP_CLASS isn't preceded by X86_64_X87_CLASS,
everything should be passed in memory. */
if (classes[i] == X86_64_X87UP_CLASS
&& (classes[i - 1] != X86_64_X87_CLASS))
{
/* The first one should never be X86_64_X87UP_CLASS. */
FFI_ASSERT (i != 0);
return 0;
}
}
return words;
}
default:
FFI_ASSERT(0);
}
return 0; /* Never reached. */
}
/* Examine the argument and return set number of register required in each
class. Return zero iff parameter should be passed in memory, otherwise
the number of registers. */
static int
examine_argument (ffi_type *type, enum x86_64_reg_class classes[MAX_CLASSES],
_Bool in_return, int *pngpr, int *pnsse)
{
int i, n, ngpr, nsse;
n = classify_argument (type, classes, 0);
if (n == 0)
return 0;
ngpr = nsse = 0;
for (i = 0; i < n; ++i)
switch (classes[i])
{
case X86_64_INTEGER_CLASS:
case X86_64_INTEGERSI_CLASS:
ngpr++;
break;
case X86_64_SSE_CLASS:
case X86_64_SSESF_CLASS:
case X86_64_SSEDF_CLASS:
nsse++;
break;
case X86_64_NO_CLASS:
case X86_64_SSEUP_CLASS:
break;
case X86_64_X87_CLASS:
case X86_64_X87UP_CLASS:
case X86_64_COMPLEX_X87_CLASS:
return in_return != 0;
default:
abort ();
}
*pngpr = ngpr;
*pnsse = nsse;
return n;
}
/* Perform machine dependent cif processing. */
ffi_status
ffi_prep_cif_machdep (ffi_cif *cif)
{
int gprcount, ssecount, i, avn, n, ngpr, nsse, flags;
enum x86_64_reg_class classes[MAX_CLASSES];
size_t bytes;
gprcount = ssecount = 0;
flags = cif->rtype->type;
if (flags != FFI_TYPE_VOID)
{
n = examine_argument (cif->rtype, classes, 1, &ngpr, &nsse);
if (n == 0)
{
/* The return value is passed in memory. A pointer to that
memory is the first argument. Allocate a register for it. */
gprcount++;
/* We don't have to do anything in asm for the return. */
flags = FFI_TYPE_VOID;
}
else if (flags == FFI_TYPE_STRUCT)
{
/* Mark which registers the result appears in. */
_Bool sse0 = SSE_CLASS_P (classes[0]);
_Bool sse1 = n == 2 && SSE_CLASS_P (classes[1]);
if (sse0 && !sse1)
flags |= 1 << 8;
else if (!sse0 && sse1)
flags |= 1 << 9;
else if (sse0 && sse1)
flags |= 1 << 10;
/* Mark the true size of the structure. */
flags |= cif->rtype->size << 12;
}
}
/* Go over all arguments and determine the way they should be passed.
If it's in a register and there is space for it, let that be so. If
not, add it's size to the stack byte count. */
for (bytes = 0, i = 0, avn = cif->nargs; i < avn; i++)
{
if (examine_argument (cif->arg_types[i], classes, 0, &ngpr, &nsse) == 0
|| gprcount + ngpr > MAX_GPR_REGS
|| ssecount + nsse > MAX_SSE_REGS)
{
long align = cif->arg_types[i]->alignment;
if (align < 8)
align = 8;
bytes = ALIGN (bytes, align);
bytes += cif->arg_types[i]->size;
}
else
{
gprcount += ngpr;
ssecount += nsse;
}
}
if (ssecount)
flags |= 1 << 11;
cif->flags = flags;
cif->bytes = ALIGN (bytes, 8);
return FFI_OK;
}
void
ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
{
enum x86_64_reg_class classes[MAX_CLASSES];
char *stack, *argp;
ffi_type **arg_types;
int gprcount, ssecount, ngpr, nsse, i, avn;
_Bool ret_in_memory;
struct register_args *reg_args;
/* Can't call 32-bit mode from 64-bit mode. */
FFI_ASSERT (cif->abi == FFI_UNIX64);
/* If the return value is a struct and we don't have a return value
address then we need to make one. Note the setting of flags to
VOID above in ffi_prep_cif_machdep. */
ret_in_memory = (cif->rtype->type == FFI_TYPE_STRUCT
&& (cif->flags & 0xff) == FFI_TYPE_VOID);
if (rvalue == NULL && ret_in_memory)
rvalue = alloca (cif->rtype->size);
/* Allocate the space for the arguments, plus 4 words of temp space. */
stack = alloca (sizeof (struct register_args) + cif->bytes + 4*8);
reg_args = (struct register_args *) stack;
argp = stack + sizeof (struct register_args);
gprcount = ssecount = 0;
/* If the return value is passed in memory, add the pointer as the
first integer argument. */
if (ret_in_memory)
reg_args->gpr[gprcount++] = (long) rvalue;
avn = cif->nargs;
arg_types = cif->arg_types;
for (i = 0; i < avn; ++i)
{
size_t size = arg_types[i]->size;
int n;
n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse);
if (n == 0
|| gprcount + ngpr > MAX_GPR_REGS
|| ssecount + nsse > MAX_SSE_REGS)
{
long align = arg_types[i]->alignment;
/* Stack arguments are *always* at least 8 byte aligned. */
if (align < 8)
align = 8;
/* Pass this argument in memory. */
argp = (void *) ALIGN (argp, align);
memcpy (argp, avalue[i], size);
argp += size;
}
else
{
/* The argument is passed entirely in registers. */
char *a = (char *) avalue[i];
int j;
for (j = 0; j < n; j++, a += 8, size -= 8)
{
switch (classes[j])
{
case X86_64_INTEGER_CLASS:
case X86_64_INTEGERSI_CLASS:
reg_args->gpr[gprcount] = 0;
memcpy (®_args->gpr[gprcount], a, size < 8 ? size : 8);
gprcount++;
break;
case X86_64_SSE_CLASS:
case X86_64_SSEDF_CLASS:
reg_args->sse[ssecount++] = *(UINT64 *) a;
break;
case X86_64_SSESF_CLASS:
reg_args->sse[ssecount++] = *(UINT32 *) a;
break;
default:
abort();
}
}
}
}
ffi_call_unix64 (stack, cif->bytes + sizeof (struct register_args),
cif->flags, rvalue, fn, ssecount);
}
extern void ffi_closure_unix64(void);
ffi_status
ffi_prep_closure_loc (ffi_closure* closure,
ffi_cif* cif,
void (*fun)(ffi_cif*, void*, void**, void*),
void *user_data,
void *codeloc)
{
volatile unsigned short *tramp;
/* Sanity check on the cif ABI. */
{
int abi = cif->abi;
if (UNLIKELY (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)))
return FFI_BAD_ABI;
}
tramp = (volatile unsigned short *) &closure->tramp[0];
tramp[0] = 0xbb49; /* mov <code>, %r11 */
*(void * volatile *) &tramp[1] = ffi_closure_unix64;
tramp[5] = 0xba49; /* mov <data>, %r10 */
*(void * volatile *) &tramp[6] = codeloc;
/* Set the carry bit iff the function uses any sse registers.
This is clc or stc, together with the first byte of the jmp. */
tramp[10] = cif->flags & (1 << 11) ? 0x49f9 : 0x49f8;
tramp[11] = 0xe3ff; /* jmp *%r11 */
closure->cif = cif;
closure->fun = fun;
closure->user_data = user_data;
return FFI_OK;
}
int
ffi_closure_unix64_inner(ffi_closure *closure, void *rvalue,
struct register_args *reg_args, char *argp)
{
ffi_cif *cif;
void **avalue;
ffi_type **arg_types;
long i, avn;
int gprcount, ssecount, ngpr, nsse;
int ret;
cif = closure->cif;
avalue = alloca(cif->nargs * sizeof(void *));
gprcount = ssecount = 0;
ret = cif->rtype->type;
if (ret != FFI_TYPE_VOID)
{
enum x86_64_reg_class classes[MAX_CLASSES];
int n = examine_argument (cif->rtype, classes, 1, &ngpr, &nsse);
if (n == 0)
{
/* The return value goes in memory. Arrange for the closure
return value to go directly back to the original caller. */
rvalue = (void *) reg_args->gpr[gprcount++];
/* We don't have to do anything in asm for the return. */
ret = FFI_TYPE_VOID;
}
else if (ret == FFI_TYPE_STRUCT && n == 2)
{
/* Mark which register the second word of the structure goes in. */
_Bool sse0 = SSE_CLASS_P (classes[0]);
_Bool sse1 = SSE_CLASS_P (classes[1]);
if (!sse0 && sse1)
ret |= 1 << 8;
else if (sse0 && !sse1)
ret |= 1 << 9;
}
}
avn = cif->nargs;
arg_types = cif->arg_types;
for (i = 0; i < avn; ++i)
{
enum x86_64_reg_class classes[MAX_CLASSES];
int n;
n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse);
if (n == 0
|| gprcount + ngpr > MAX_GPR_REGS
|| ssecount + nsse > MAX_SSE_REGS)
{
long align = arg_types[i]->alignment;
/* Stack arguments are *always* at least 8 byte aligned. */
if (align < 8)
align = 8;
/* Pass this argument in memory. */
argp = (void *) ALIGN (argp, align);
avalue[i] = argp;
argp += arg_types[i]->size;
}
/* If the argument is in a single register, or two consecutive
integer registers, then we can use that address directly. */
else if (n == 1
|| (n == 2 && !(SSE_CLASS_P (classes[0])
|| SSE_CLASS_P (classes[1]))))
{
/* The argument is in a single register. */
if (SSE_CLASS_P (classes[0]))
{
avalue[i] = ®_args->sse[ssecount];
ssecount += n;
}
else
{
avalue[i] = ®_args->gpr[gprcount];
gprcount += n;
}
}
/* Otherwise, allocate space to make them consecutive. */
else
{
char *a = alloca (16);
int j;
avalue[i] = a;
for (j = 0; j < n; j++, a += 8)
{
if (SSE_CLASS_P (classes[j]))
memcpy (a, ®_args->sse[ssecount++], 8);
else
memcpy (a, ®_args->gpr[gprcount++], 8);
}
}
}
/* Invoke the closure. */
closure->fun (cif, rvalue, avalue, closure->user_data);
/* Tell assembly how to perform return type promotions. */
return ret;
}
#endif /* __x86_64__ */
| mit |
supriyantomaftuh/Windows-universal-samples | Samples/XamlCloudFontIntegration/cpp/Scenario_SampleOverview.xaml.cpp | 222 | 1033 | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario_SampleOverview.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
Scenario_SampleOverview::Scenario_SampleOverview()
{
InitializeComponent();
}
| mit |
Viktorminator/coinvscoin | node_modules/node-sass/src/libsass/src/extend.cpp | 226 | 74695 | #ifdef _MSC_VER
#pragma warning(disable : 4503)
#endif
#include "extend.hpp"
#include "context.hpp"
#include "to_string.hpp"
#include "backtrace.hpp"
#include "paths.hpp"
#include "parser.hpp"
#include "node.hpp"
#include "sass_util.hpp"
#include "debug.hpp"
#include <iostream>
#include <deque>
#include <set>
/*
NOTES:
- The print* functions print to cerr. This allows our testing frameworks (like sass-spec) to ignore the output, which
is very helpful when debugging. The format of the output is mainly to wrap things in square brackets to match what
ruby already outputs (to make comparisons easier).
- For the direct porting effort, we're trying to port method-for-method until we get all the tests passing.
Where applicable, I've tried to include the ruby code above the function for reference until all our tests pass.
The ruby code isn't always directly portable, so I've tried to include any modified ruby code that was actually
used for the porting.
- DO NOT try to optimize yet. We get a tremendous benefit out of comparing the output of each stage of the extend to the ruby
output at the same stage. This makes it much easier to determine where problems are. Try to keep as close to
the ruby code as you can until we have all the sass-spec tests passing. Then, we should optimize. However, if you see
something that could probably be optimized, let's not forget it. Add a // TODO: or // IMPROVEMENT: comment.
- Coding conventions in this file (these may need to be changed before merging back into master)
- Very basic hungarian notation:
p prefix for pointers (pSelector)
no prefix for value types and references (selector)
- Use STL iterators where possible
- prefer verbose naming over terse naming
- use typedefs for STL container types for make maintenance easier
- You may see a lot of comments that say "// TODO: is this the correct combinator?". See the comment referring to combinators
in extendCompoundSelector for a more extensive explanation of my confusion. I think our divergence in data model from ruby
sass causes this to be necessary.
GLOBAL TODOS:
- wrap the contents of the print functions in DEBUG preprocesser conditionals so they will be optimized away in non-debug mode.
- consider making the extend* functions member functions to avoid passing around ctx and subset_map map around. This has the
drawback that the implementation details of the operator are then exposed to the outside world, which is not ideal and
can cause additional compile time dependencies.
- mark the helper methods in this file static to given them compilation unit linkage.
- implement parent directive matching
- fix compilation warnings for unused Extend members if we really don't need those references anymore.
*/
namespace Sass {
typedef std::pair<Complex_Selector*, Compound_Selector*> ExtensionPair;
typedef std::vector<ExtensionPair> SubsetMapEntries;
#ifdef DEBUG
// TODO: move the ast specific ostream operators into ast.hpp/ast.cpp
std::ostream& operator<<(std::ostream& os, const Complex_Selector::Combinator combinator) {
switch (combinator) {
case Complex_Selector::ANCESTOR_OF: os << "\" \""; break;
case Complex_Selector::PARENT_OF: os << "\">\""; break;
case Complex_Selector::PRECEDES: os << "\"~\""; break;
case Complex_Selector::ADJACENT_TO: os << "\"+\""; break;
case Complex_Selector::REFERENCE: os << "\"/\""; break;
}
return os;
}
std::ostream& operator<<(std::ostream& os, Compound_Selector& compoundSelector) {
To_String to_string;
for (size_t i = 0, L = compoundSelector.length(); i < L; ++i) {
if (i > 0) os << ", ";
os << compoundSelector[i]->perform(&to_string);
}
return os;
}
std::ostream& operator<<(std::ostream& os, Simple_Selector& simpleSelector) {
To_String to_string;
os << simpleSelector.perform(&to_string);
return os;
}
// Print a string representation of a Compound_Selector
static void printSimpleSelector(Simple_Selector* pSimpleSelector, const char* message=NULL, bool newline=true) {
To_String to_string;
if (message) {
std::cerr << message;
}
if (pSimpleSelector) {
std::cerr << "[" << *pSimpleSelector << "]";
} else {
std::cerr << "NULL";
}
if (newline) {
std::cerr << std::endl;
}
}
// Print a string representation of a Compound_Selector
typedef std::pair<Compound_Selector*, Complex_Selector*> SelsNewSeqPair;
typedef std::vector<SelsNewSeqPair> SelsNewSeqPairCollection;
// Print a string representation of a Compound_Selector
static void printCompoundSelector(Compound_Selector* pCompoundSelector, const char* message=NULL, bool newline=true) {
To_String to_string;
if (message) {
std::cerr << message;
}
if (pCompoundSelector) {
std::cerr << "[" << *pCompoundSelector << "]";
} else {
std::cerr << "NULL";
}
if (newline) {
std::cerr << std::endl;
}
}
std::ostream& operator<<(std::ostream& os, Complex_Selector& complexSelector) {
To_String to_string;
os << "[";
Complex_Selector* pIter = &complexSelector;
bool first = true;
while (pIter) {
if (pIter->combinator() != Complex_Selector::ANCESTOR_OF) {
if (!first) {
os << ", ";
}
first = false;
os << pIter->combinator();
}
if (!first) {
os << ", ";
}
first = false;
if (pIter->head()) {
os << pIter->head()->perform(&to_string);
} else {
os << "NULL_HEAD";
}
pIter = pIter->tail();
}
os << "]";
return os;
}
// Print a string representation of a Complex_Selector
static void printComplexSelector(Complex_Selector* pComplexSelector, const char* message=NULL, bool newline=true) {
To_String to_string;
if (message) {
std::cerr << message;
}
if (pComplexSelector) {
std::cerr << *pComplexSelector;
} else {
std::cerr << "NULL";
}
if (newline) {
std::cerr << std::endl;
}
}
static void printSelsNewSeqPairCollection(SelsNewSeqPairCollection& collection, const char* message=NULL, bool newline=true) {
To_String to_string;
if (message) {
std::cerr << message;
}
bool first = true;
std::cerr << "[";
for(SelsNewSeqPair& pair : collection) {
if (first) {
first = false;
} else {
std::cerr << ", ";
}
std::cerr << "[";
Compound_Selector* pSels = pair.first;
Complex_Selector* pNewSelector = pair.second;
std::cerr << "[" << *pSels << "], ";
printComplexSelector(pNewSelector, NULL, false);
}
std::cerr << "]";
if (newline) {
std::cerr << std::endl;
}
}
// Print a string representation of a SourcesSet
static void printSourcesSet(SourcesSet& sources, Context& ctx, const char* message=NULL, bool newline=true) {
To_String to_string;
if (message) {
std::cerr << message;
}
// Convert to a deque of strings so we can sort since order doesn't matter in a set. This should cut down on
// the differences we see when debug printing.
typedef std::deque<std::string> SourceStrings;
SourceStrings sourceStrings;
for (SourcesSet::iterator iterator = sources.begin(), iteratorEnd = sources.end(); iterator != iteratorEnd; ++iterator) {
Complex_Selector* pSource = *iterator;
std::stringstream sstream;
sstream << complexSelectorToNode(pSource, ctx);
sourceStrings.push_back(sstream.str());
}
// Sort to get consistent output
std::sort(sourceStrings.begin(), sourceStrings.end());
std::cerr << "SourcesSet[";
for (SourceStrings::iterator iterator = sourceStrings.begin(), iteratorEnd = sourceStrings.end(); iterator != iteratorEnd; ++iterator) {
std::string source = *iterator;
if (iterator != sourceStrings.begin()) {
std::cerr << ", ";
}
std::cerr << source;
}
std::cerr << "]";
if (newline) {
std::cerr << std::endl;
}
}
std::ostream& operator<<(std::ostream& os, SubsetMapEntries& entries) {
os << "SUBSET_MAP_ENTRIES[";
for (SubsetMapEntries::iterator iterator = entries.begin(), endIterator = entries.end(); iterator != endIterator; ++iterator) {
Complex_Selector* pExtComplexSelector = iterator->first; // The selector up to where the @extend is (ie, the thing to merge)
Compound_Selector* pExtCompoundSelector = iterator->second; // The stuff after the @extend
if (iterator != entries.begin()) {
os << ", ";
}
os << "(";
if (pExtComplexSelector) {
std::cerr << *pExtComplexSelector;
} else {
std::cerr << "NULL";
}
os << " -> ";
if (pExtCompoundSelector) {
std::cerr << *pExtCompoundSelector;
} else {
std::cerr << "NULL";
}
os << ")";
}
os << "]";
return os;
}
#endif
static bool parentSuperselector(Complex_Selector* pOne, Complex_Selector* pTwo, Context& ctx) {
// TODO: figure out a better way to create a Complex_Selector from scratch
// TODO: There's got to be a better way. This got ugly quick...
Position noPosition(-1, -1, -1);
Type_Selector fakeParent(ParserState("[FAKE]"), "temp");
Compound_Selector fakeHead(ParserState("[FAKE]"), 1 /*size*/);
fakeHead.elements().push_back(&fakeParent);
Complex_Selector fakeParentContainer(ParserState("[FAKE]"), Complex_Selector::ANCESTOR_OF, &fakeHead /*head*/, NULL /*tail*/);
pOne->set_innermost(&fakeParentContainer, Complex_Selector::ANCESTOR_OF);
pTwo->set_innermost(&fakeParentContainer, Complex_Selector::ANCESTOR_OF);
bool isSuperselector = pOne->is_superselector_of(pTwo);
pOne->clear_innermost();
pTwo->clear_innermost();
return isSuperselector;
}
void nodeToComplexSelectorDeque(const Node& node, ComplexSelectorDeque& out, Context& ctx) {
for (NodeDeque::iterator iter = node.collection()->begin(), iterEnd = node.collection()->end(); iter != iterEnd; iter++) {
Node& child = *iter;
out.push_back(nodeToComplexSelector(child, ctx));
}
}
Node complexSelectorDequeToNode(const ComplexSelectorDeque& deque, Context& ctx) {
Node result = Node::createCollection();
for (ComplexSelectorDeque::const_iterator iter = deque.begin(), iterEnd = deque.end(); iter != iterEnd; iter++) {
Complex_Selector* pChild = *iter;
result.collection()->push_back(complexSelectorToNode(pChild, ctx));
}
return result;
}
class LcsCollectionComparator {
public:
LcsCollectionComparator(Context& ctx) : mCtx(ctx) {}
Context& mCtx;
bool operator()(Complex_Selector* pOne, Complex_Selector* pTwo, Complex_Selector*& pOut) const {
/*
This code is based on the following block from ruby sass' subweave
do |s1, s2|
next s1 if s1 == s2
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
next s2 if parent_superselector?(s1, s2)
next s1 if parent_superselector?(s2, s1)
end
*/
if (selectors_equal(*pOne, *pTwo, true /*simpleSelectorOrderDependent*/)) {
pOut = pOne;
return true;
}
if (pOne->combinator() != Complex_Selector::ANCESTOR_OF || pTwo->combinator() != Complex_Selector::ANCESTOR_OF) {
return false;
}
if (parentSuperselector(pOne, pTwo, mCtx)) {
pOut = pTwo;
return true;
}
if (parentSuperselector(pTwo, pOne, mCtx)) {
pOut = pOne;
return true;
}
return false;
}
};
/*
This is the equivalent of ruby's Sass::Util.lcs_backtrace.
# Computes a single longest common subsequence for arrays x and y.
# Algorithm from http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS
*/
void lcs_backtrace(const LCSTable& c, ComplexSelectorDeque& x, ComplexSelectorDeque& y, int i, int j, const LcsCollectionComparator& comparator, ComplexSelectorDeque& out) {
//DEBUG_PRINTLN(LCS, "LCSBACK: X=" << x << " Y=" << y << " I=" << i << " J=" << j)
// TODO: make printComplexSelectorDeque and use DEBUG_EXEC AND DEBUG_PRINTLN HERE to get equivalent output
if (i == 0 || j == 0) {
DEBUG_PRINTLN(LCS, "RETURNING EMPTY")
return;
}
Complex_Selector* pCompareOut = NULL;
if (comparator(x[i], y[j], pCompareOut)) {
DEBUG_PRINTLN(LCS, "RETURNING AFTER ELEM COMPARE")
lcs_backtrace(c, x, y, i - 1, j - 1, comparator, out);
out.push_back(pCompareOut);
return;
}
if (c[i][j - 1] > c[i - 1][j]) {
DEBUG_PRINTLN(LCS, "RETURNING AFTER TABLE COMPARE")
lcs_backtrace(c, x, y, i, j - 1, comparator, out);
return;
}
DEBUG_PRINTLN(LCS, "FINAL RETURN")
lcs_backtrace(c, x, y, i - 1, j, comparator, out);
return;
}
/*
This is the equivalent of ruby's Sass::Util.lcs_table.
# Calculates the memoization table for the Least Common Subsequence algorithm.
# Algorithm from http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS
*/
void lcs_table(const ComplexSelectorDeque& x, const ComplexSelectorDeque& y, const LcsCollectionComparator& comparator, LCSTable& out) {
//DEBUG_PRINTLN(LCS, "LCSTABLE: X=" << x << " Y=" << y)
// TODO: make printComplexSelectorDeque and use DEBUG_EXEC AND DEBUG_PRINTLN HERE to get equivalent output
LCSTable c(x.size(), std::vector<int>(y.size()));
// These shouldn't be necessary since the vector will be initialized to 0 already.
// x.size.times {|i| c[i][0] = 0}
// y.size.times {|j| c[0][j] = 0}
for (size_t i = 1; i < x.size(); i++) {
for (size_t j = 1; j < y.size(); j++) {
Complex_Selector* pCompareOut = NULL;
if (comparator(x[i], y[j], pCompareOut)) {
c[i][j] = c[i - 1][j - 1] + 1;
} else {
c[i][j] = std::max(c[i][j - 1], c[i - 1][j]);
}
}
}
out = c;
}
/*
This is the equivalent of ruby's Sass::Util.lcs.
# Computes a single longest common subsequence for `x` and `y`.
# If there are more than one longest common subsequences,
# the one returned is that which starts first in `x`.
# @param x [NodeCollection]
# @param y [NodeCollection]
# @comparator An equality check between elements of `x` and `y`.
# @return [NodeCollection] The LCS
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
*/
void lcs(ComplexSelectorDeque& x, ComplexSelectorDeque& y, const LcsCollectionComparator& comparator, Context& ctx, ComplexSelectorDeque& out) {
//DEBUG_PRINTLN(LCS, "LCS: X=" << x << " Y=" << y)
// TODO: make printComplexSelectorDeque and use DEBUG_EXEC AND DEBUG_PRINTLN HERE to get equivalent output
x.push_front(NULL);
y.push_front(NULL);
LCSTable table;
lcs_table(x, y, comparator, table);
return lcs_backtrace(table, x, y, static_cast<int>(x.size()) - 1, static_cast<int>(y.size()) - 1, comparator, out);
}
/*
This is the equivalent of ruby's Sequence.trim.
The following is the modified version of the ruby code that was more portable to C++. You
should be able to drop it into ruby 3.2.19 and get the same results from ruby sass.
# Avoid truly horrific quadratic behavior. TODO: I think there
# may be a way to get perfect trimming without going quadratic.
return seqses if seqses.size > 100
# Keep the results in a separate array so we can be sure we aren't
# comparing against an already-trimmed selector. This ensures that two
# identical selectors don't mutually trim one another.
result = seqses.dup
# This is n^2 on the sequences, but only comparing between
# separate sequences should limit the quadratic behavior.
seqses.each_with_index do |seqs1, i|
tempResult = []
for seq1 in seqs1 do
max_spec = 0
for seq in _sources(seq1) do
max_spec = [max_spec, seq.specificity].max
end
isMoreSpecificOuter = false
for seqs2 in result do
if seqs1.equal?(seqs2) then
next
end
# Second Law of Extend: the specificity of a generated selector
# should never be less than the specificity of the extending
# selector.
#
# See https://github.com/nex3/sass/issues/324.
isMoreSpecificInner = false
for seq2 in seqs2 do
isMoreSpecificInner = _specificity(seq2) >= max_spec && _superselector?(seq2, seq1)
if isMoreSpecificInner then
break
end
end
if isMoreSpecificInner then
isMoreSpecificOuter = true
break
end
end
if !isMoreSpecificOuter then
tempResult.push(seq1)
end
end
result[i] = tempResult
end
result
*/
/*
- IMPROVEMENT: We could probably work directly in the output trimmed deque.
*/
static Node trim(Node& seqses, Context& ctx, bool isReplace) {
// See the comments in the above ruby code before embarking on understanding this function.
// Avoid poor performance in extreme cases.
if (seqses.collection()->size() > 100) {
return seqses;
}
DEBUG_PRINTLN(TRIM, "TRIM: " << seqses)
Node result = Node::createCollection();
result.plus(seqses);
DEBUG_PRINTLN(TRIM, "RESULT INITIAL: " << result)
// Normally we use the standard STL iterators, but in this case, we need to access the result collection by index since we're
// iterating the input collection, computing a value, and then setting the result in the output collection. We have to keep track
// of the index manually.
int toTrimIndex = 0;
for (NodeDeque::iterator seqsesIter = seqses.collection()->begin(), seqsesIterEnd = seqses.collection()->end(); seqsesIter != seqsesIterEnd; ++seqsesIter) {
Node& seqs1 = *seqsesIter;
DEBUG_PRINTLN(TRIM, "SEQS1: " << seqs1 << " " << toTrimIndex)
Node tempResult = Node::createCollection();
tempResult.got_line_feed = seqs1.got_line_feed;
for (NodeDeque::iterator seqs1Iter = seqs1.collection()->begin(), seqs1EndIter = seqs1.collection()->end(); seqs1Iter != seqs1EndIter; ++seqs1Iter) {
Node& seq1 = *seqs1Iter;
Complex_Selector* pSeq1 = nodeToComplexSelector(seq1, ctx);
// Compute the maximum specificity. This requires looking at the "sources" of the sequence. See SimpleSequence.sources in the ruby code
// for a good description of sources.
//
// TODO: I'm pretty sure there's a bug in the sources code. It was implemented for sass-spec's 182_test_nested_extend_loop test.
// While the test passes, I compared the state of each trim call to verify correctness. The last trim call had incorrect sources. We
// had an extra source that the ruby version did not have. Without a failing test case, this is going to be extra hard to find. My
// best guess at this point is that we're cloning an object somewhere and maintaining the sources when we shouldn't be. This is purely
// a guess though.
unsigned long maxSpecificity = isReplace ? pSeq1->specificity() : 0;
SourcesSet sources = pSeq1->sources();
DEBUG_PRINTLN(TRIM, "TRIM SEQ1: " << seq1)
DEBUG_EXEC(TRIM, printSourcesSet(sources, ctx, "TRIM SOURCES: "))
for (SourcesSet::iterator sourcesSetIterator = sources.begin(), sourcesSetIteratorEnd = sources.end(); sourcesSetIterator != sourcesSetIteratorEnd; ++sourcesSetIterator) {
const Complex_Selector* const pCurrentSelector = *sourcesSetIterator;
maxSpecificity = std::max(maxSpecificity, pCurrentSelector->specificity());
}
DEBUG_PRINTLN(TRIM, "MAX SPECIFICITY: " << maxSpecificity)
bool isMoreSpecificOuter = false;
int resultIndex = 0;
for (NodeDeque::iterator resultIter = result.collection()->begin(), resultIterEnd = result.collection()->end(); resultIter != resultIterEnd; ++resultIter) {
Node& seqs2 = *resultIter;
DEBUG_PRINTLN(TRIM, "SEQS1: " << seqs1)
DEBUG_PRINTLN(TRIM, "SEQS2: " << seqs2)
// Do not compare the same sequence to itself. The ruby call we're trying to
// emulate is: seqs1.equal?(seqs2). equal? is an object comparison, not an equivalency comparision.
// Since we have the same pointers in seqes and results, we can do a pointer comparision. seqs1 is
// derived from seqses and seqs2 is derived from result.
if (seqs1.collection() == seqs2.collection()) {
DEBUG_PRINTLN(TRIM, "CONTINUE")
continue;
}
bool isMoreSpecificInner = false;
for (NodeDeque::iterator seqs2Iter = seqs2.collection()->begin(), seqs2IterEnd = seqs2.collection()->end(); seqs2Iter != seqs2IterEnd; ++seqs2Iter) {
Node& seq2 = *seqs2Iter;
Complex_Selector* pSeq2 = nodeToComplexSelector(seq2, ctx);
DEBUG_PRINTLN(TRIM, "SEQ2 SPEC: " << pSeq2->specificity())
DEBUG_PRINTLN(TRIM, "IS SPEC: " << pSeq2->specificity() << " >= " << maxSpecificity << " " << (pSeq2->specificity() >= maxSpecificity ? "true" : "false"))
DEBUG_PRINTLN(TRIM, "IS SUPER: " << (pSeq2->is_superselector_of(pSeq1) ? "true" : "false"))
isMoreSpecificInner = pSeq2->specificity() >= maxSpecificity && pSeq2->is_superselector_of(pSeq1);
if (isMoreSpecificInner) {
DEBUG_PRINTLN(TRIM, "FOUND MORE SPECIFIC")
break;
}
}
// If we found something more specific, we're done. Let the outer loop know and stop iterating.
if (isMoreSpecificInner) {
isMoreSpecificOuter = true;
break;
}
resultIndex++;
}
if (!isMoreSpecificOuter) {
DEBUG_PRINTLN(TRIM, "PUSHING: " << seq1)
tempResult.collection()->push_back(seq1);
}
}
DEBUG_PRINTLN(TRIM, "RESULT BEFORE ASSIGN: " << result)
DEBUG_PRINTLN(TRIM, "TEMP RESULT: " << toTrimIndex << " " << tempResult)
(*result.collection())[toTrimIndex] = tempResult;
toTrimIndex++;
DEBUG_PRINTLN(TRIM, "RESULT: " << result)
}
return result;
}
static bool parentSuperselector(const Node& one, const Node& two, Context& ctx) {
// TODO: figure out a better way to create a Complex_Selector from scratch
// TODO: There's got to be a better way. This got ugly quick...
Position noPosition(-1, -1, -1);
Type_Selector fakeParent(ParserState("[FAKE]"), "temp");
Compound_Selector fakeHead(ParserState("[FAKE]"), 1 /*size*/);
fakeHead.elements().push_back(&fakeParent);
Complex_Selector fakeParentContainer(ParserState("[FAKE]"), Complex_Selector::ANCESTOR_OF, &fakeHead /*head*/, NULL /*tail*/);
Complex_Selector* pOneWithFakeParent = nodeToComplexSelector(one, ctx);
pOneWithFakeParent->set_innermost(&fakeParentContainer, Complex_Selector::ANCESTOR_OF);
Complex_Selector* pTwoWithFakeParent = nodeToComplexSelector(two, ctx);
pTwoWithFakeParent->set_innermost(&fakeParentContainer, Complex_Selector::ANCESTOR_OF);
return pOneWithFakeParent->is_superselector_of(pTwoWithFakeParent);
}
class ParentSuperselectorChunker {
public:
ParentSuperselectorChunker(Node& lcs, Context& ctx) : mLcs(lcs), mCtx(ctx) {}
Node& mLcs;
Context& mCtx;
bool operator()(const Node& seq) const {
// {|s| parent_superselector?(s.first, lcs.first)}
if (seq.collection()->size() == 0) return false;
return parentSuperselector(seq.collection()->front(), mLcs.collection()->front(), mCtx);
}
};
class SubweaveEmptyChunker {
public:
bool operator()(const Node& seq) const {
// {|s| s.empty?}
return seq.collection()->empty();
}
};
/*
# Takes initial subsequences of `seq1` and `seq2` and returns all
# orderings of those subsequences. The initial subsequences are determined
# by a block.
#
# Destructively removes the initial subsequences of `seq1` and `seq2`.
#
# For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|`
# denoting the boundary of the initial subsequence), this would return
# `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and
# `(3 4 5)`.
#
# @param seq1 [Array]
# @param seq2 [Array]
# @yield [a] Used to determine when to cut off the initial subsequences.
# Called repeatedly for each sequence until it returns true.
# @yieldparam a [Array] A final subsequence of one input sequence after
# cutting off some initial subsequence.
# @yieldreturn [Boolean] Whether or not to cut off the initial subsequence
# here.
# @return [Array<Array>] All possible orderings of the initial subsequences.
def chunks(seq1, seq2)
chunk1 = []
chunk1 << seq1.shift until yield seq1
chunk2 = []
chunk2 << seq2.shift until yield seq2
return [] if chunk1.empty? && chunk2.empty?
return [chunk2] if chunk1.empty?
return [chunk1] if chunk2.empty?
[chunk1 + chunk2, chunk2 + chunk1]
end
*/
template<typename ChunkerType>
static Node chunks(Node& seq1, Node& seq2, const ChunkerType& chunker) {
Node chunk1 = Node::createCollection();
while (seq1.collection()->size() && !chunker(seq1)) {
chunk1.collection()->push_back(seq1.collection()->front());
seq1.collection()->pop_front();
}
Node chunk2 = Node::createCollection();
while (!chunker(seq2)) {
chunk2.collection()->push_back(seq2.collection()->front());
seq2.collection()->pop_front();
}
if (chunk1.collection()->empty() && chunk2.collection()->empty()) {
DEBUG_PRINTLN(CHUNKS, "RETURNING BOTH EMPTY")
return Node::createCollection();
}
if (chunk1.collection()->empty()) {
Node chunk2Wrapper = Node::createCollection();
chunk2Wrapper.collection()->push_back(chunk2);
DEBUG_PRINTLN(CHUNKS, "RETURNING ONE EMPTY")
return chunk2Wrapper;
}
if (chunk2.collection()->empty()) {
Node chunk1Wrapper = Node::createCollection();
chunk1Wrapper.collection()->push_back(chunk1);
DEBUG_PRINTLN(CHUNKS, "RETURNING TWO EMPTY")
return chunk1Wrapper;
}
Node perms = Node::createCollection();
Node firstPermutation = Node::createCollection();
firstPermutation.collection()->insert(firstPermutation.collection()->end(), chunk1.collection()->begin(), chunk1.collection()->end());
firstPermutation.collection()->insert(firstPermutation.collection()->end(), chunk2.collection()->begin(), chunk2.collection()->end());
perms.collection()->push_back(firstPermutation);
Node secondPermutation = Node::createCollection();
secondPermutation.collection()->insert(secondPermutation.collection()->end(), chunk2.collection()->begin(), chunk2.collection()->end());
secondPermutation.collection()->insert(secondPermutation.collection()->end(), chunk1.collection()->begin(), chunk1.collection()->end());
perms.collection()->push_back(secondPermutation);
DEBUG_PRINTLN(CHUNKS, "RETURNING PERM")
return perms;
}
static Node groupSelectors(Node& seq, Context& ctx) {
Node newSeq = Node::createCollection();
Node tail = Node::createCollection();
tail.plus(seq);
while (!tail.collection()->empty()) {
Node head = Node::createCollection();
do {
head.collection()->push_back(tail.collection()->front());
tail.collection()->pop_front();
} while (!tail.collection()->empty() && (head.collection()->back().isCombinator() || tail.collection()->front().isCombinator()));
newSeq.collection()->push_back(head);
}
return newSeq;
}
static void getAndRemoveInitialOps(Node& seq, Node& ops) {
NodeDeque& seqCollection = *(seq.collection());
NodeDeque& opsCollection = *(ops.collection());
while (seqCollection.size() > 0 && seqCollection.front().isCombinator()) {
opsCollection.push_back(seqCollection.front());
seqCollection.pop_front();
}
}
static void getAndRemoveFinalOps(Node& seq, Node& ops) {
NodeDeque& seqCollection = *(seq.collection());
NodeDeque& opsCollection = *(ops.collection());
while (seqCollection.size() > 0 && seqCollection.back().isCombinator()) {
opsCollection.push_back(seqCollection.back()); // Purposefully reversed to match ruby code
seqCollection.pop_back();
}
}
/*
def merge_initial_ops(seq1, seq2)
ops1, ops2 = [], []
ops1 << seq1.shift while seq1.first.is_a?(String)
ops2 << seq2.shift while seq2.first.is_a?(String)
newline = false
newline ||= !!ops1.shift if ops1.first == "\n"
newline ||= !!ops2.shift if ops2.first == "\n"
# If neither sequence is a subsequence of the other, they cannot be
# merged successfully
lcs = Sass::Util.lcs(ops1, ops2)
return unless lcs == ops1 || lcs == ops2
return (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
end
*/
static Node mergeInitialOps(Node& seq1, Node& seq2, Context& ctx) {
Node ops1 = Node::createCollection();
Node ops2 = Node::createCollection();
getAndRemoveInitialOps(seq1, ops1);
getAndRemoveInitialOps(seq2, ops2);
// TODO: Do we have this information available to us?
// newline = false
// newline ||= !!ops1.shift if ops1.first == "\n"
// newline ||= !!ops2.shift if ops2.first == "\n"
// If neither sequence is a subsequence of the other, they cannot be merged successfully
DefaultLcsComparator lcsDefaultComparator;
Node opsLcs = lcs(ops1, ops2, lcsDefaultComparator, ctx);
if (!(opsLcs == ops1 || opsLcs == ops2)) {
return Node::createNil();
}
// TODO: more newline logic
// return (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
return (ops1.collection()->size() > ops2.collection()->size() ? ops1 : ops2);
}
/*
def merge_final_ops(seq1, seq2, res = [])
# This code looks complicated, but it's actually just a bunch of special
# cases for interactions between different combinators.
op1, op2 = ops1.first, ops2.first
if op1 && op2
sel1 = seq1.pop
sel2 = seq2.pop
if op1 == '~' && op2 == '~'
if sel1.superselector?(sel2)
res.unshift sel2, '~'
elsif sel2.superselector?(sel1)
res.unshift sel1, '~'
else
merged = sel1.unify(sel2.members, sel2.subject?)
res.unshift [
[sel1, '~', sel2, '~'],
[sel2, '~', sel1, '~'],
([merged, '~'] if merged)
].compact
end
elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~')
if op1 == '~'
tilde_sel, plus_sel = sel1, sel2
else
tilde_sel, plus_sel = sel2, sel1
end
if tilde_sel.superselector?(plus_sel)
res.unshift plus_sel, '+'
else
merged = plus_sel.unify(tilde_sel.members, tilde_sel.subject?)
res.unshift [
[tilde_sel, '~', plus_sel, '+'],
([merged, '+'] if merged)
].compact
end
elsif op1 == '>' && %w[~ +].include?(op2)
res.unshift sel2, op2
seq1.push sel1, op1
elsif op2 == '>' && %w[~ +].include?(op1)
res.unshift sel1, op1
seq2.push sel2, op2
elsif op1 == op2
return unless merged = sel1.unify(sel2.members, sel2.subject?)
res.unshift merged, op1
else
# Unknown selector combinators can't be unified
return
end
return merge_final_ops(seq1, seq2, res)
elsif op1
seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last)
res.unshift seq1.pop, op1
return merge_final_ops(seq1, seq2, res)
else # op2
seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last)
res.unshift seq2.pop, op2
return merge_final_ops(seq1, seq2, res)
end
end
*/
static Node mergeFinalOps(Node& seq1, Node& seq2, Context& ctx, Node& res) {
Node ops1 = Node::createCollection();
Node ops2 = Node::createCollection();
getAndRemoveFinalOps(seq1, ops1);
getAndRemoveFinalOps(seq2, ops2);
// TODO: do we have newlines to remove?
// ops1.reject! {|o| o == "\n"}
// ops2.reject! {|o| o == "\n"}
if (ops1.collection()->empty() && ops2.collection()->empty()) {
return res;
}
if (ops1.collection()->size() > 1 || ops2.collection()->size() > 1) {
DefaultLcsComparator lcsDefaultComparator;
Node opsLcs = lcs(ops1, ops2, lcsDefaultComparator, ctx);
// If there are multiple operators, something hacky's going on. If one is a supersequence of the other, use that, otherwise give up.
if (!(opsLcs == ops1 || opsLcs == ops2)) {
return Node::createNil();
}
if (ops1.collection()->size() > ops2.collection()->size()) {
res.collection()->insert(res.collection()->begin(), ops1.collection()->rbegin(), ops1.collection()->rend());
} else {
res.collection()->insert(res.collection()->begin(), ops2.collection()->rbegin(), ops2.collection()->rend());
}
return res;
}
if (!ops1.collection()->empty() && !ops2.collection()->empty()) {
Node op1 = ops1.collection()->front();
Node op2 = ops2.collection()->front();
Node sel1 = seq1.collection()->back();
seq1.collection()->pop_back();
Node sel2 = seq2.collection()->back();
seq2.collection()->pop_back();
if (op1.combinator() == Complex_Selector::PRECEDES && op2.combinator() == Complex_Selector::PRECEDES) {
if (sel1.selector()->is_superselector_of(sel2.selector())) {
res.collection()->push_front(op1 /*PRECEDES - could have been op2 as well*/);
res.collection()->push_front(sel2);
} else if (sel2.selector()->is_superselector_of(sel1.selector())) {
res.collection()->push_front(op1 /*PRECEDES - could have been op2 as well*/);
res.collection()->push_front(sel1);
} else {
DEBUG_PRINTLN(ALL, "sel1: " << sel1)
DEBUG_PRINTLN(ALL, "sel2: " << sel2)
Complex_Selector* pMergedWrapper = sel1.selector()->clone(ctx); // Clone the Complex_Selector to get back to something we can transform to a node once we replace the head with the unification result
// TODO: does subject matter? Ruby: return unless merged = sel1.unify(sel2.members, sel2.subject?)
Compound_Selector* pMerged = sel1.selector()->head()->unify_with(sel2.selector()->head(), ctx);
pMergedWrapper->head(pMerged);
DEBUG_EXEC(ALL, printCompoundSelector(pMerged, "MERGED: "))
Node newRes = Node::createCollection();
Node firstPerm = Node::createCollection();
firstPerm.collection()->push_back(sel1);
firstPerm.collection()->push_back(Node::createCombinator(Complex_Selector::PRECEDES));
firstPerm.collection()->push_back(sel2);
firstPerm.collection()->push_back(Node::createCombinator(Complex_Selector::PRECEDES));
newRes.collection()->push_back(firstPerm);
Node secondPerm = Node::createCollection();
secondPerm.collection()->push_back(sel2);
secondPerm.collection()->push_back(Node::createCombinator(Complex_Selector::PRECEDES));
secondPerm.collection()->push_back(sel1);
secondPerm.collection()->push_back(Node::createCombinator(Complex_Selector::PRECEDES));
newRes.collection()->push_back(secondPerm);
if (pMerged) {
Node mergedPerm = Node::createCollection();
mergedPerm.collection()->push_back(Node::createSelector(pMergedWrapper, ctx));
mergedPerm.collection()->push_back(Node::createCombinator(Complex_Selector::PRECEDES));
newRes.collection()->push_back(mergedPerm);
}
res.collection()->push_front(newRes);
DEBUG_PRINTLN(ALL, "RESULT: " << res)
}
} else if (((op1.combinator() == Complex_Selector::PRECEDES && op2.combinator() == Complex_Selector::ADJACENT_TO)) || ((op1.combinator() == Complex_Selector::ADJACENT_TO && op2.combinator() == Complex_Selector::PRECEDES))) {
Node tildeSel = sel1;
Node tildeOp = op1;
Node plusSel = sel2;
Node plusOp = op2;
if (op1.combinator() != Complex_Selector::PRECEDES) {
tildeSel = sel2;
tildeOp = op2;
plusSel = sel1;
plusOp = op1;
}
if (tildeSel.selector()->is_superselector_of(plusSel.selector())) {
res.collection()->push_front(plusOp);
res.collection()->push_front(plusSel);
} else {
DEBUG_PRINTLN(ALL, "PLUS SEL: " << plusSel)
DEBUG_PRINTLN(ALL, "TILDE SEL: " << tildeSel)
Complex_Selector* pMergedWrapper = plusSel.selector()->clone(ctx); // Clone the Complex_Selector to get back to something we can transform to a node once we replace the head with the unification result
// TODO: does subject matter? Ruby: merged = plus_sel.unify(tilde_sel.members, tilde_sel.subject?)
Compound_Selector* pMerged = plusSel.selector()->head()->unify_with(tildeSel.selector()->head(), ctx);
pMergedWrapper->head(pMerged);
DEBUG_EXEC(ALL, printCompoundSelector(pMerged, "MERGED: "))
Node newRes = Node::createCollection();
Node firstPerm = Node::createCollection();
firstPerm.collection()->push_back(tildeSel);
firstPerm.collection()->push_back(Node::createCombinator(Complex_Selector::PRECEDES));
firstPerm.collection()->push_back(plusSel);
firstPerm.collection()->push_back(Node::createCombinator(Complex_Selector::ADJACENT_TO));
newRes.collection()->push_back(firstPerm);
if (pMerged) {
Node mergedPerm = Node::createCollection();
mergedPerm.collection()->push_back(Node::createSelector(pMergedWrapper, ctx));
mergedPerm.collection()->push_back(Node::createCombinator(Complex_Selector::ADJACENT_TO));
newRes.collection()->push_back(mergedPerm);
}
res.collection()->push_front(newRes);
DEBUG_PRINTLN(ALL, "RESULT: " << res)
}
} else if (op1.combinator() == Complex_Selector::PARENT_OF && (op2.combinator() == Complex_Selector::PRECEDES || op2.combinator() == Complex_Selector::ADJACENT_TO)) {
res.collection()->push_front(op2);
res.collection()->push_front(sel2);
seq1.collection()->push_back(sel1);
seq1.collection()->push_back(op1);
} else if (op2.combinator() == Complex_Selector::PARENT_OF && (op1.combinator() == Complex_Selector::PRECEDES || op1.combinator() == Complex_Selector::ADJACENT_TO)) {
res.collection()->push_front(op1);
res.collection()->push_front(sel1);
seq2.collection()->push_back(sel2);
seq2.collection()->push_back(op2);
} else if (op1.combinator() == op2.combinator()) {
DEBUG_PRINTLN(ALL, "sel1: " << sel1)
DEBUG_PRINTLN(ALL, "sel2: " << sel2)
Complex_Selector* pMergedWrapper = sel1.selector()->clone(ctx); // Clone the Complex_Selector to get back to something we can transform to a node once we replace the head with the unification result
// TODO: does subject matter? Ruby: return unless merged = sel1.unify(sel2.members, sel2.subject?)
Compound_Selector* pMerged = sel1.selector()->head()->unify_with(sel2.selector()->head(), ctx);
pMergedWrapper->head(pMerged);
DEBUG_EXEC(ALL, printCompoundSelector(pMerged, "MERGED: "))
if (!pMerged) {
return Node::createNil();
}
res.collection()->push_front(op1);
res.collection()->push_front(Node::createSelector(pMergedWrapper, ctx));
DEBUG_PRINTLN(ALL, "RESULT: " << res)
} else {
return Node::createNil();
}
return mergeFinalOps(seq1, seq2, ctx, res);
} else if (!ops1.collection()->empty()) {
Node op1 = ops1.collection()->front();
if (op1.combinator() == Complex_Selector::PARENT_OF && !seq2.collection()->empty() && seq2.collection()->back().selector()->is_superselector_of(seq1.collection()->back().selector())) {
seq2.collection()->pop_back();
}
// TODO: consider unshift(NodeCollection, Node)
res.collection()->push_front(op1);
res.collection()->push_front(seq1.collection()->back());
seq1.collection()->pop_back();
return mergeFinalOps(seq1, seq2, ctx, res);
} else { // !ops2.collection()->empty()
Node op2 = ops2.collection()->front();
if (op2.combinator() == Complex_Selector::PARENT_OF && !seq1.collection()->empty() && seq1.collection()->back().selector()->is_superselector_of(seq2.collection()->back().selector())) {
seq1.collection()->pop_back();
}
res.collection()->push_front(op2);
res.collection()->push_front(seq2.collection()->back());
seq2.collection()->pop_back();
return mergeFinalOps(seq1, seq2, ctx, res);
}
}
/*
This is the equivalent of ruby's Sequence.subweave.
Here is the original subweave code for reference during porting.
def subweave(seq1, seq2)
return [seq2] if seq1.empty?
return [seq1] if seq2.empty?
seq1, seq2 = seq1.dup, seq2.dup
return unless init = merge_initial_ops(seq1, seq2)
return unless fin = merge_final_ops(seq1, seq2)
seq1 = group_selectors(seq1)
seq2 = group_selectors(seq2)
lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2|
next s1 if s1 == s2
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
next s2 if parent_superselector?(s1, s2)
next s1 if parent_superselector?(s2, s1)
end
diff = [[init]]
until lcs.empty?
diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift]
seq1.shift
seq2.shift
end
diff << chunks(seq1, seq2) {|s| s.empty?}
diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
diff.reject! {|c| c.empty?}
result = Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)}
result
end
*/
Node Extend::subweave(Node& one, Node& two, Context& ctx) {
// Check for the simple cases
if (one.collection()->size() == 0) {
Node out = Node::createCollection();
out.collection()->push_back(two);
return out;
}
if (two.collection()->size() == 0) {
Node out = Node::createCollection();
out.collection()->push_back(one);
return out;
}
Node seq1 = Node::createCollection();
seq1.plus(one);
Node seq2 = Node::createCollection();
seq2.plus(two);
DEBUG_PRINTLN(SUBWEAVE, "SUBWEAVE ONE: " << seq1)
DEBUG_PRINTLN(SUBWEAVE, "SUBWEAVE TWO: " << seq2)
Node init = mergeInitialOps(seq1, seq2, ctx);
if (init.isNil()) {
return Node::createNil();
}
DEBUG_PRINTLN(SUBWEAVE, "INIT: " << init)
Node res = Node::createCollection();
Node fin = mergeFinalOps(seq1, seq2, ctx, res);
if (fin.isNil()) {
return Node::createNil();
}
DEBUG_PRINTLN(SUBWEAVE, "FIN: " << fin)
// Moving this line up since fin isn't modified between now and when it happened before
// fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
for (NodeDeque::iterator finIter = fin.collection()->begin(), finEndIter = fin.collection()->end();
finIter != finEndIter; ++finIter) {
Node& childNode = *finIter;
if (!childNode.isCollection()) {
Node wrapper = Node::createCollection();
wrapper.collection()->push_back(childNode);
childNode = wrapper;
}
}
DEBUG_PRINTLN(SUBWEAVE, "FIN MAPPED: " << fin)
Node groupSeq1 = groupSelectors(seq1, ctx);
DEBUG_PRINTLN(SUBWEAVE, "SEQ1: " << groupSeq1)
Node groupSeq2 = groupSelectors(seq2, ctx);
DEBUG_PRINTLN(SUBWEAVE, "SEQ2: " << groupSeq2)
ComplexSelectorDeque groupSeq1Converted;
nodeToComplexSelectorDeque(groupSeq1, groupSeq1Converted, ctx);
ComplexSelectorDeque groupSeq2Converted;
nodeToComplexSelectorDeque(groupSeq2, groupSeq2Converted, ctx);
ComplexSelectorDeque out;
LcsCollectionComparator collectionComparator(ctx);
lcs(groupSeq2Converted, groupSeq1Converted, collectionComparator, ctx, out);
Node seqLcs = complexSelectorDequeToNode(out, ctx);
DEBUG_PRINTLN(SUBWEAVE, "SEQLCS: " << seqLcs)
Node initWrapper = Node::createCollection();
initWrapper.collection()->push_back(init);
Node diff = Node::createCollection();
diff.collection()->push_back(initWrapper);
DEBUG_PRINTLN(SUBWEAVE, "DIFF INIT: " << diff)
while (!seqLcs.collection()->empty()) {
ParentSuperselectorChunker superselectorChunker(seqLcs, ctx);
Node chunksResult = chunks(groupSeq1, groupSeq2, superselectorChunker);
diff.collection()->push_back(chunksResult);
Node lcsWrapper = Node::createCollection();
lcsWrapper.collection()->push_back(seqLcs.collection()->front());
seqLcs.collection()->pop_front();
diff.collection()->push_back(lcsWrapper);
if (groupSeq1.collection()->size()) groupSeq1.collection()->pop_front();
if (groupSeq2.collection()->size()) groupSeq2.collection()->pop_front();
}
DEBUG_PRINTLN(SUBWEAVE, "DIFF POST LCS: " << diff)
DEBUG_PRINTLN(SUBWEAVE, "CHUNKS: ONE=" << groupSeq1 << " TWO=" << groupSeq2)
SubweaveEmptyChunker emptyChunker;
Node chunksResult = chunks(groupSeq1, groupSeq2, emptyChunker);
diff.collection()->push_back(chunksResult);
DEBUG_PRINTLN(SUBWEAVE, "DIFF POST CHUNKS: " << diff)
diff.collection()->insert(diff.collection()->end(), fin.collection()->begin(), fin.collection()->end());
DEBUG_PRINTLN(SUBWEAVE, "DIFF POST FIN MAPPED: " << diff)
// JMA - filter out the empty nodes (use a new collection, since iterator erase() invalidates the old collection)
Node diffFiltered = Node::createCollection();
for (NodeDeque::iterator diffIter = diff.collection()->begin(), diffEndIter = diff.collection()->end();
diffIter != diffEndIter; ++diffIter) {
Node& node = *diffIter;
if (node.collection() && !node.collection()->empty()) {
diffFiltered.collection()->push_back(node);
}
}
diff = diffFiltered;
DEBUG_PRINTLN(SUBWEAVE, "DIFF POST REJECT: " << diff)
Node pathsResult = paths(diff, ctx);
DEBUG_PRINTLN(SUBWEAVE, "PATHS: " << pathsResult)
// We're flattening in place
for (NodeDeque::iterator pathsIter = pathsResult.collection()->begin(), pathsEndIter = pathsResult.collection()->end();
pathsIter != pathsEndIter; ++pathsIter) {
Node& child = *pathsIter;
child = flatten(child, ctx);
}
DEBUG_PRINTLN(SUBWEAVE, "FLATTENED: " << pathsResult)
/*
TODO: implement
rejected = mapped.reject {|p| path_has_two_subjects?(p)}
$stderr.puts "REJECTED: #{rejected}"
*/
return pathsResult;
}
/*
// disabled to avoid clang warning [-Wunused-function]
static Node subweaveNaive(const Node& one, const Node& two, Context& ctx) {
Node out = Node::createCollection();
// Check for the simple cases
if (one.isNil()) {
out.collection()->push_back(two.clone(ctx));
} else if (two.isNil()) {
out.collection()->push_back(one.clone(ctx));
} else {
// Do the naive implementation. pOne = A B and pTwo = C D ...yields... A B C D and C D A B
// See https://gist.github.com/nex3/7609394 for details.
Node firstPerm = one.clone(ctx);
Node twoCloned = two.clone(ctx);
firstPerm.plus(twoCloned);
out.collection()->push_back(firstPerm);
Node secondPerm = two.clone(ctx);
Node oneCloned = one.clone(ctx);
secondPerm.plus(oneCloned );
out.collection()->push_back(secondPerm);
}
return out;
}
*/
/*
This is the equivalent of ruby's Sequence.weave.
The following is the modified version of the ruby code that was more portable to C++. You
should be able to drop it into ruby 3.2.19 and get the same results from ruby sass.
def weave(path)
# This function works by moving through the selector path left-to-right,
# building all possible prefixes simultaneously. These prefixes are
# `befores`, while the remaining parenthesized suffixes is `afters`.
befores = [[]]
afters = path.dup
until afters.empty?
current = afters.shift.dup
last_current = [current.pop]
tempResult = []
for before in befores do
sub = subweave(before, current)
if sub.nil?
next
end
for seqs in sub do
tempResult.push(seqs + last_current)
end
end
befores = tempResult
end
return befores
end
*/
/*
def weave(path)
befores = [[]]
afters = path.dup
until afters.empty?
current = afters.shift.dup
last_current = [current.pop]
tempResult = []
for before in befores do
sub = subweave(before, current)
if sub.nil?
next []
end
for seqs in sub do
toPush = seqs + last_current
tempResult.push(seqs + last_current)
end
end
befores = tempResult
end
return befores
end
*/
static Node weave(Node& path, Context& ctx) {
DEBUG_PRINTLN(WEAVE, "WEAVE: " << path)
Node befores = Node::createCollection();
befores.collection()->push_back(Node::createCollection());
Node afters = Node::createCollection();
afters.plus(path);
while (!afters.collection()->empty()) {
Node current = afters.collection()->front().clone(ctx);
afters.collection()->pop_front();
DEBUG_PRINTLN(WEAVE, "CURRENT: " << current)
Node last_current = Node::createCollection();
last_current.collection()->push_back(current.collection()->back());
current.collection()->pop_back();
DEBUG_PRINTLN(WEAVE, "CURRENT POST POP: " << current)
DEBUG_PRINTLN(WEAVE, "LAST CURRENT: " << last_current)
Node tempResult = Node::createCollection();
for (NodeDeque::iterator beforesIter = befores.collection()->begin(), beforesEndIter = befores.collection()->end(); beforesIter != beforesEndIter; beforesIter++) {
Node& before = *beforesIter;
Node sub = Extend::subweave(before, current, ctx);
DEBUG_PRINTLN(WEAVE, "SUB: " << sub)
if (sub.isNil()) {
return Node::createCollection();
}
for (NodeDeque::iterator subIter = sub.collection()->begin(), subEndIter = sub.collection()->end(); subIter != subEndIter; subIter++) {
Node& seqs = *subIter;
Node toPush = Node::createCollection();
toPush.plus(seqs);
toPush.plus(last_current);
tempResult.collection()->push_back(toPush);
}
}
befores = tempResult;
}
return befores;
}
// This forward declaration is needed since extendComplexSelector calls extendCompoundSelector, which may recursively
// call extendComplexSelector again.
static Node extendComplexSelector(
Complex_Selector* pComplexSelector,
Context& ctx,
ExtensionSubsetMap& subset_map,
std::set<Compound_Selector> seen, bool isReplace, bool isOriginal);
/*
This is the equivalent of ruby's SimpleSequence.do_extend.
// TODO: I think I have some modified ruby code to put here. Check.
*/
/*
ISSUES:
- Previous TODO: Do we need to group the results by extender?
- What does subject do in?: next unless unified = seq.members.last.unify(self_without_sel, subject?)
- IMPROVEMENT: The search for uniqueness at the end is not ideal since it's has to loop over everything...
- IMPROVEMENT: Check if the final search for uniqueness is doing anything that extendComplexSelector isn't already doing...
*/
template<typename KeyType>
class GroupByToAFunctor {
public:
KeyType operator()(ExtensionPair& extPair) const {
Complex_Selector* pSelector = extPair.first;
return *pSelector;
}
};
static Node extendCompoundSelector(
Compound_Selector* pSelector,
Context& ctx,
ExtensionSubsetMap& subset_map,
std::set<Compound_Selector> seen, bool isReplace) {
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pSelector, "EXTEND COMPOUND: "))
// TODO: Ruby has another loop here to skip certain members?
Node extendedSelectors = Node::createCollection();
// extendedSelectors.got_line_feed = true;
To_String to_string;
SubsetMapEntries entries = subset_map.get_v(pSelector->to_str_vec());
typedef std::vector<std::pair<Complex_Selector, std::vector<ExtensionPair> > > GroupedByToAResult;
GroupByToAFunctor<Complex_Selector> extPairKeyFunctor;
GroupedByToAResult arr;
group_by_to_a(entries, extPairKeyFunctor, arr);
typedef std::pair<Compound_Selector*, Complex_Selector*> SelsNewSeqPair;
typedef std::vector<SelsNewSeqPair> SelsNewSeqPairCollection;
SelsNewSeqPairCollection holder;
for (GroupedByToAResult::iterator groupedIter = arr.begin(), groupedIterEnd = arr.end(); groupedIter != groupedIterEnd; groupedIter++) {
std::pair<Complex_Selector, std::vector<ExtensionPair> >& groupedPair = *groupedIter;
Complex_Selector& seq = groupedPair.first;
std::vector<ExtensionPair>& group = groupedPair.second;
DEBUG_EXEC(EXTEND_COMPOUND, printComplexSelector(&seq, "SEQ: "))
Compound_Selector* pSels = SASS_MEMORY_NEW(ctx.mem, Compound_Selector, pSelector->pstate());
for (std::vector<ExtensionPair>::iterator groupIter = group.begin(), groupIterEnd = group.end(); groupIter != groupIterEnd; groupIter++) {
ExtensionPair& pair = *groupIter;
Compound_Selector* pCompound = pair.second;
for (size_t index = 0; index < pCompound->length(); index++) {
Simple_Selector* pSimpleSelector = (*pCompound)[index];
(*pSels) << pSimpleSelector;
}
}
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pSels, "SELS: "))
Complex_Selector* pExtComplexSelector = &seq; // The selector up to where the @extend is (ie, the thing to merge)
Compound_Selector* pExtCompoundSelector = pSels; // All the simple selectors to be replaced from the current compound selector from all extensions
// TODO: This can return a Compound_Selector with no elements. Should that just be returning NULL?
// RUBY: self_without_sel = Sass::Util.array_minus(members, sels)
Compound_Selector* pSelectorWithoutExtendSelectors = pSelector->minus(pExtCompoundSelector, ctx);
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pSelector, "MEMBERS: "))
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pSelectorWithoutExtendSelectors, "SELF_WO_SEL: "))
Compound_Selector* pInnermostCompoundSelector = pExtComplexSelector->last()->head();
Compound_Selector* pUnifiedSelector = NULL;
if (!pInnermostCompoundSelector) {
pInnermostCompoundSelector = SASS_MEMORY_NEW(ctx.mem, Compound_Selector, pSelector->pstate());
}
pUnifiedSelector = pInnermostCompoundSelector->unify_with(pSelectorWithoutExtendSelectors, ctx);
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pInnermostCompoundSelector, "LHS: "))
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pSelectorWithoutExtendSelectors, "RHS: "))
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pUnifiedSelector, "UNIFIED: "))
// RUBY: next unless unified
if (!pUnifiedSelector || pUnifiedSelector->length() == 0) {
continue;
}
// TODO: implement the parent directive match (if necessary based on test failures)
// next if group.map {|e, _| check_directives_match!(e, parent_directives)}.none?
// TODO: This seems a little fishy to me. See if it causes any problems. From the ruby, we should be able to just
// get rid of the last Compound_Selector and replace it with this one. I think the reason this code is more
// complex is that Complex_Selector contains a combinator, but in ruby combinators have already been filtered
// out and aren't operated on.
Complex_Selector* pNewSelector = pExtComplexSelector->cloneFully(ctx); // ->first();
Complex_Selector* pNewInnerMost = SASS_MEMORY_NEW(ctx.mem, Complex_Selector, pSelector->pstate(), Complex_Selector::ANCESTOR_OF, pUnifiedSelector, NULL);
Complex_Selector::Combinator combinator = pNewSelector->clear_innermost();
pNewSelector->set_innermost(pNewInnerMost, combinator);
#ifdef DEBUG
SourcesSet debugSet;
debugSet = pNewSelector->sources();
if (debugSet.size() > 0) {
throw "The new selector should start with no sources. Something needs to be cloned to fix this.";
}
debugSet = pExtComplexSelector->sources();
if (debugSet.size() > 0) {
throw "The extension selector from our subset map should not have sources. These will bleed to the new selector. Something needs to be cloned to fix this.";
}
#endif
// if (pSelector && pSelector->has_line_feed()) pNewInnerMost->has_line_feed(true);
// Set the sources on our new Complex_Selector to the sources of this simple sequence plus the thing we're extending.
DEBUG_PRINTLN(EXTEND_COMPOUND, "SOURCES SETTING ON NEW SEQ: " << complexSelectorToNode(pNewSelector, ctx))
DEBUG_EXEC(EXTEND_COMPOUND, SourcesSet oldSet = pNewSelector->sources(); printSourcesSet(oldSet, ctx, "SOURCES NEW SEQ BEGIN: "))
SourcesSet newSourcesSet = pSelector->sources();
DEBUG_EXEC(EXTEND_COMPOUND, printSourcesSet(newSourcesSet, ctx, "SOURCES THIS EXTEND: "))
newSourcesSet.insert(pExtComplexSelector);
DEBUG_EXEC(EXTEND_COMPOUND, printSourcesSet(newSourcesSet, ctx, "SOURCES WITH NEW SOURCE: "))
// RUBY: new_seq.add_sources!(sources + [seq])
pNewSelector->addSources(newSourcesSet, ctx);
DEBUG_EXEC(EXTEND_COMPOUND, SourcesSet newSet = pNewSelector->sources(); printSourcesSet(newSet, ctx, "SOURCES ON NEW SELECTOR AFTER ADD: "))
DEBUG_EXEC(EXTEND_COMPOUND, printSourcesSet(pSelector->sources(), ctx, "SOURCES THIS EXTEND WHICH SHOULD BE SAME STILL: "))
if (pSels->has_line_feed()) pNewSelector->has_line_feed(true);;
holder.push_back(std::make_pair(pSels, pNewSelector));
}
for (SelsNewSeqPairCollection::iterator holderIter = holder.begin(), holderIterEnd = holder.end(); holderIter != holderIterEnd; holderIter++) {
SelsNewSeqPair& pair = *holderIter;
Compound_Selector* pSels = pair.first;
Complex_Selector* pNewSelector = pair.second;
// RUBY??: next [] if seen.include?(sels)
if (seen.find(*pSels) != seen.end()) {
continue;
}
std::set<Compound_Selector> recurseSeen(seen);
recurseSeen.insert(*pSels);
DEBUG_PRINTLN(EXTEND_COMPOUND, "RECURSING DO EXTEND: " << complexSelectorToNode(pNewSelector, ctx))
Node recurseExtendedSelectors = extendComplexSelector(pNewSelector, ctx, subset_map, recurseSeen, isReplace, false); // !:isOriginal
DEBUG_PRINTLN(EXTEND_COMPOUND, "RECURSING DO EXTEND RETURN: " << recurseExtendedSelectors)
for (NodeDeque::iterator iterator = recurseExtendedSelectors.collection()->begin(), endIterator = recurseExtendedSelectors.collection()->end();
iterator != endIterator; ++iterator) {
Node& newSelector = *iterator;
// DEBUG_PRINTLN(EXTEND_COMPOUND, "EXTENDED AT THIS POINT: " << extendedSelectors)
// DEBUG_PRINTLN(EXTEND_COMPOUND, "SELECTOR EXISTS ALREADY: " << newSelector << " " << extendedSelectors.contains(newSelector, false /*simpleSelectorOrderDependent*/));
if (!extendedSelectors.contains(newSelector, false /*simpleSelectorOrderDependent*/)) {
// DEBUG_PRINTLN(EXTEND_COMPOUND, "ADDING NEW SELECTOR")
extendedSelectors.collection()->push_back(newSelector);
}
}
}
DEBUG_EXEC(EXTEND_COMPOUND, printCompoundSelector(pSelector, "EXTEND COMPOUND END: "))
return extendedSelectors;
}
static bool complexSelectorHasExtension(
Complex_Selector* pComplexSelector,
Context& ctx,
ExtensionSubsetMap& subset_map) {
bool hasExtension = false;
Complex_Selector* pIter = pComplexSelector;
while (!hasExtension && pIter) {
Compound_Selector* pHead = pIter->head();
if (pHead) {
SubsetMapEntries entries = subset_map.get_v(pHead->to_str_vec());
for (ExtensionPair ext : entries) {
// check if both selectors have the same media block parent
if (ext.first->media_block() == pComplexSelector->media_block()) continue;
To_String to_string(&ctx);
if (ext.second->media_block() == 0) continue;
if (pComplexSelector->media_block() &&
ext.second->media_block()->media_queries() &&
pComplexSelector->media_block()->media_queries()
) {
std::string query_left(ext.second->media_block()->media_queries()->perform(&to_string));
std::string query_right(pComplexSelector->media_block()->media_queries()->perform(&to_string));
if (query_left == query_right) continue;
}
// fail if one goes across media block boundaries
std::stringstream err;
std::string cwd(Sass::File::get_cwd());
ParserState pstate(ext.second->pstate());
std::string rel_path(Sass::File::abs2rel(pstate.path, cwd, cwd));
err << "You may not @extend an outer selector from within @media.\n";
err << "You may only @extend selectors within the same directive.\n";
err << "From \"@extend " << ext.second->perform(&to_string) << "\"";
err << " on line " << pstate.line+1 << " of " << rel_path << "\n";
error(err.str(), pComplexSelector->pstate());
}
if (entries.size() > 0) hasExtension = true;
}
pIter = pIter->tail();
}
if (!hasExtension) {
/* ToDo: don't break stuff
std::stringstream err;
To_String to_string(&ctx);
std::string cwd(Sass::File::get_cwd());
std::string sel1(pComplexSelector->perform(&to_string));
Compound_Selector* pExtendSelector = 0;
for (auto i : subset_map.values()) {
if (i.first == pComplexSelector) {
pExtendSelector = i.second;
break;
}
}
if (!pExtendSelector || !pExtendSelector->is_optional()) {
std::string sel2(pExtendSelector ? pExtendSelector->perform(&to_string) : "[unknown]");
err << "\"" << sel1 << "\" failed to @extend \"" << sel2 << "\"\n";
err << "The selector \"" << sel2 << "\" was not found.\n";
err << "Use \"@extend " << sel2 << " !optional\" if the extend should be able to fail.";
error(err.str(), pExtendSelector ? pExtendSelector->pstate() : pComplexSelector->pstate());
}
*/
}
return hasExtension;
}
/*
This is the equivalent of ruby's Sequence.do_extend.
// TODO: I think I have some modified ruby code to put here. Check.
*/
/*
ISSUES:
- check to automatically include combinators doesn't transfer over to libsass' data model where
the combinator and compound selector are one unit
next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
*/
static Node extendComplexSelector(
Complex_Selector* pComplexSelector,
Context& ctx,
ExtensionSubsetMap& subset_map,
std::set<Compound_Selector> seen, bool isReplace, bool isOriginal) {
Node complexSelector = complexSelectorToNode(pComplexSelector, ctx);
DEBUG_PRINTLN(EXTEND_COMPLEX, "EXTEND COMPLEX: " << complexSelector)
Node extendedNotExpanded = Node::createCollection();
for (NodeDeque::iterator complexSelIter = complexSelector.collection()->begin(),
complexSelIterEnd = complexSelector.collection()->end();
complexSelIter != complexSelIterEnd; ++complexSelIter)
{
Node& sseqOrOp = *complexSelIter;
DEBUG_PRINTLN(EXTEND_COMPLEX, "LOOP: " << sseqOrOp)
// If it's not a selector (meaning it's a combinator), just include it automatically
// RUBY: next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
if (!sseqOrOp.isSelector()) {
// Wrap our Combinator in two collections to match ruby. This is essentially making a collection Node
// with one collection child. The collection child represents a Complex_Selector that is only a combinator.
Node outer = Node::createCollection();
Node inner = Node::createCollection();
outer.collection()->push_back(inner);
inner.collection()->push_back(sseqOrOp);
extendedNotExpanded.collection()->push_back(outer);
continue;
}
Compound_Selector* pCompoundSelector = sseqOrOp.selector()->head();
// RUBY: extended = sseq_or_op.do_extend(extends, parent_directives, replace, seen)
Node extended = extendCompoundSelector(pCompoundSelector, ctx, subset_map, seen, isReplace);
if (sseqOrOp.got_line_feed) extended.got_line_feed = true;
DEBUG_PRINTLN(EXTEND_COMPLEX, "EXTENDED: " << extended)
// Prepend the Compound_Selector based on the choices logic; choices seems to be extend but with an ruby Array instead of a Sequence
// due to the member mapping: choices = extended.map {|seq| seq.members}
Complex_Selector* pJustCurrentCompoundSelector = sseqOrOp.selector();
// RUBY: extended.first.add_sources!([self]) if original && !has_placeholder?
if (isOriginal && !pComplexSelector->has_placeholder()) {
SourcesSet srcset;
srcset.insert(pComplexSelector);
pJustCurrentCompoundSelector->addSources(srcset, ctx);
DEBUG_PRINTLN(EXTEND_COMPLEX, "ADD SOURCES: " << *pComplexSelector)
}
bool isSuperselector = false;
for (NodeDeque::iterator iterator = extended.collection()->begin(), endIterator = extended.collection()->end();
iterator != endIterator; ++iterator) {
Node& childNode = *iterator;
Complex_Selector* pExtensionSelector = nodeToComplexSelector(childNode, ctx);
if (pExtensionSelector->is_superselector_of(pJustCurrentCompoundSelector)) {
isSuperselector = true;
break;
}
}
if (!isSuperselector) {
if (sseqOrOp.got_line_feed) pJustCurrentCompoundSelector->has_line_feed(sseqOrOp.got_line_feed);
extended.collection()->push_front(complexSelectorToNode(pJustCurrentCompoundSelector, ctx));
}
DEBUG_PRINTLN(EXTEND_COMPLEX, "CHOICES UNSHIFTED: " << extended)
// Aggregate our current extensions
extendedNotExpanded.collection()->push_back(extended);
}
DEBUG_PRINTLN(EXTEND_COMPLEX, "EXTENDED NOT EXPANDED: " << extendedNotExpanded)
// Ruby Equivalent: paths
Node paths = Sass::paths(extendedNotExpanded, ctx);
DEBUG_PRINTLN(EXTEND_COMPLEX, "PATHS: " << paths)
// Ruby Equivalent: weave
Node weaves = Node::createCollection();
for (NodeDeque::iterator pathsIter = paths.collection()->begin(), pathsEndIter = paths.collection()->end(); pathsIter != pathsEndIter; ++pathsIter) {
Node& path = *pathsIter;
Node weaved = weave(path, ctx);
weaved.got_line_feed = path.got_line_feed;
weaves.collection()->push_back(weaved);
}
DEBUG_PRINTLN(EXTEND_COMPLEX, "WEAVES: " << weaves)
// Ruby Equivalent: trim
Node trimmed = trim(weaves, ctx, isReplace);
DEBUG_PRINTLN(EXTEND_COMPLEX, "TRIMMED: " << trimmed)
// Ruby Equivalent: flatten
Node extendedSelectors = flatten(trimmed, ctx, 1);
DEBUG_PRINTLN(EXTEND_COMPLEX, ">>>>> EXTENDED: " << extendedSelectors)
DEBUG_PRINTLN(EXTEND_COMPLEX, "EXTEND COMPLEX END: " << complexSelector)
return extendedSelectors;
}
/*
This is the equivalent of ruby's CommaSequence.do_extend.
*/
Selector_List* Extend::extendSelectorList(Selector_List* pSelectorList, Context& ctx, ExtensionSubsetMap& subset_map, bool isReplace, bool& extendedSomething) {
To_String to_string(&ctx);
Selector_List* pNewSelectors = SASS_MEMORY_NEW(ctx.mem, Selector_List, pSelectorList->pstate(), pSelectorList->length());
extendedSomething = false;
for (size_t index = 0, length = pSelectorList->length(); index < length; index++) {
Complex_Selector* pSelector = (*pSelectorList)[index];
// ruby sass seems to keep a list of things that have extensions and then only extend those. We don't currently do that.
// Since it's not that expensive to check if an extension exists in the subset map and since it can be relatively expensive to
// run through the extend code (which does a data model transformation), check if there is anything to extend before doing
// the extend. We might be able to optimize extendComplexSelector, but this approach keeps us closer to ruby sass (which helps
// when debugging).
if (!complexSelectorHasExtension(pSelector, ctx, subset_map)) {
*pNewSelectors << pSelector;
continue;
}
extendedSomething = true;
std::set<Compound_Selector> seen;
Node extendedSelectors = extendComplexSelector(pSelector, ctx, subset_map, seen, isReplace, true);
if (!pSelector->has_placeholder()) {
if (!extendedSelectors.contains(complexSelectorToNode(pSelector, ctx), true /*simpleSelectorOrderDependent*/)) {
*pNewSelectors << pSelector;
}
}
for (NodeDeque::iterator iterator = extendedSelectors.collection()->begin(), iteratorBegin = extendedSelectors.collection()->begin(), iteratorEnd = extendedSelectors.collection()->end(); iterator != iteratorEnd; ++iterator) {
// When it is a replace, skip the first one, unless there is only one
if(isReplace && iterator == iteratorBegin && extendedSelectors.collection()->size() > 1 ) continue;
Node& childNode = *iterator;
*pNewSelectors << nodeToComplexSelector(childNode, ctx);
}
}
return pNewSelectors;
}
bool shouldExtendBlock(Block* b) {
// If a block is empty, there's no reason to extend it since any rules placed on this block
// won't have any output. The main benefit of this is for structures like:
//
// .a {
// .b {
// x: y;
// }
// }
//
// We end up visiting two rulesets (one with the selector .a and the other with the selector .a .b).
// In this case, we don't want to try to pull rules onto .a since they won't get output anyway since
// there are no child statements. However .a .b should have extensions applied.
for (size_t i = 0, L = b->length(); i < L; ++i) {
Statement* stm = (*b)[i];
if (typeid(*stm) == typeid(Ruleset)) {
// Do nothing. This doesn't count as a statement that causes extension since we'll iterate over this rule set in a future visit and try to extend it.
}
else {
return true;
}
}
return false;
}
// Extend a ruleset by extending the selectors and updating them on the ruleset. The block's rules don't need to change.
template <typename ObjectType>
static void extendObjectWithSelectorAndBlock(ObjectType* pObject, Context& ctx, ExtensionSubsetMap& subset_map) {
To_String to_string(&ctx);
DEBUG_PRINTLN(EXTEND_OBJECT, "FOUND SELECTOR: " << static_cast<Selector_List*>(pObject->selector())->perform(&to_string))
// Ruby sass seems to filter nodes that don't have any content well before we get here. I'm not sure the repercussions
// of doing so, so for now, let's just not extend things that won't be output later.
if (!shouldExtendBlock(pObject->block())) {
DEBUG_PRINTLN(EXTEND_OBJECT, "RETURNING WITHOUT EXTEND ATTEMPT")
return;
}
bool extendedSomething = false;
Selector_List* pNewSelectorList = Extend::extendSelectorList(static_cast<Selector_List*>(pObject->selector()), ctx, subset_map, false, extendedSomething);
if (extendedSomething && pNewSelectorList) {
DEBUG_PRINTLN(EXTEND_OBJECT, "EXTEND ORIGINAL SELECTORS: " << static_cast<Selector_List*>(pObject->selector())->perform(&to_string))
DEBUG_PRINTLN(EXTEND_OBJECT, "EXTEND SETTING NEW SELECTORS: " << pNewSelectorList->perform(&to_string))
pNewSelectorList->remove_parent_selectors();
pObject->selector(pNewSelectorList);
} else {
DEBUG_PRINTLN(EXTEND_OBJECT, "EXTEND DID NOT TRY TO EXTEND ANYTHING")
}
}
Extend::Extend(Context& ctx, ExtensionSubsetMap& ssm)
: ctx(ctx), subset_map(ssm)
{ }
void Extend::operator()(Block* b)
{
for (size_t i = 0, L = b->length(); i < L; ++i) {
(*b)[i]->perform(this);
}
}
void Extend::operator()(Ruleset* pRuleset)
{
extendObjectWithSelectorAndBlock(pRuleset, ctx, subset_map);
pRuleset->block()->perform(this);
}
void Extend::operator()(Supports_Block* pFeatureBlock)
{
pFeatureBlock->block()->perform(this);
}
void Extend::operator()(Media_Block* pMediaBlock)
{
pMediaBlock->block()->perform(this);
}
void Extend::operator()(At_Rule* a)
{
// Selector_List* ls = dynamic_cast<Selector_List*>(a->selector());
// selector_stack.push_back(ls);
if (a->block()) a->block()->perform(this);
// exp.selector_stack.pop_back();
}
}
| mit |
PC-ai/WinObjC | deps/3rdparty/icu/icu/source/common/utrie2.cpp | 226 | 24036 | /*
******************************************************************************
*
* Copyright (C) 2001-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
* file name: utrie2.cpp
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2008aug16 (starting from a copy of utrie.c)
* created by: Markus W. Scherer
*
* This is a common implementation of a Unicode trie.
* It is a kind of compressed, serializable table of 16- or 32-bit values associated with
* Unicode code points (0..0x10ffff).
* This is the second common version of a Unicode trie (hence the name UTrie2).
* See utrie2.h for a comparison.
*
* This file contains only the runtime and enumeration code, for read-only access.
* See utrie2_builder.c for the builder code.
*/
#ifdef UTRIE2_DEBUG
# include <stdio.h>
#endif
#include "unicode/utypes.h"
#include "unicode/utf.h"
#include "unicode/utf8.h"
#include "unicode/utf16.h"
#include "cmemory.h"
#include "utrie2.h"
#include "utrie2_impl.h"
#include "uassert.h"
/* Public UTrie2 API implementation ----------------------------------------- */
static uint32_t
get32(const UNewTrie2 *trie, UChar32 c, UBool fromLSCP) {
int32_t i2, block;
if(c>=trie->highStart && (!U_IS_LEAD(c) || fromLSCP)) {
return trie->data[trie->dataLength-UTRIE2_DATA_GRANULARITY];
}
if(U_IS_LEAD(c) && fromLSCP) {
i2=(UTRIE2_LSCP_INDEX_2_OFFSET-(0xd800>>UTRIE2_SHIFT_2))+
(c>>UTRIE2_SHIFT_2);
} else {
i2=trie->index1[c>>UTRIE2_SHIFT_1]+
((c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK);
}
block=trie->index2[i2];
return trie->data[block+(c&UTRIE2_DATA_MASK)];
}
U_CAPI uint32_t U_EXPORT2
utrie2_get32(const UTrie2 *trie, UChar32 c) {
if(trie->data16!=NULL) {
return UTRIE2_GET16(trie, c);
} else if(trie->data32!=NULL) {
return UTRIE2_GET32(trie, c);
} else if((uint32_t)c>0x10ffff) {
return trie->errorValue;
} else {
return get32(trie->newTrie, c, TRUE);
}
}
U_CAPI uint32_t U_EXPORT2
utrie2_get32FromLeadSurrogateCodeUnit(const UTrie2 *trie, UChar32 c) {
if(!U_IS_LEAD(c)) {
return trie->errorValue;
}
if(trie->data16!=NULL) {
return UTRIE2_GET16_FROM_U16_SINGLE_LEAD(trie, c);
} else if(trie->data32!=NULL) {
return UTRIE2_GET32_FROM_U16_SINGLE_LEAD(trie, c);
} else {
return get32(trie->newTrie, c, FALSE);
}
}
static inline int32_t
u8Index(const UTrie2 *trie, UChar32 c, int32_t i) {
int32_t idx=
_UTRIE2_INDEX_FROM_CP(
trie,
trie->data32==NULL ? trie->indexLength : 0,
c);
return (idx<<3)|i;
}
U_CAPI int32_t U_EXPORT2
utrie2_internalU8NextIndex(const UTrie2 *trie, UChar32 c,
const uint8_t *src, const uint8_t *limit) {
int32_t i, length;
i=0;
/* support 64-bit pointers by avoiding cast of arbitrary difference */
if((limit-src)<=7) {
length=(int32_t)(limit-src);
} else {
length=7;
}
c=utf8_nextCharSafeBody(src, &i, length, c, -1);
return u8Index(trie, c, i);
}
U_CAPI int32_t U_EXPORT2
utrie2_internalU8PrevIndex(const UTrie2 *trie, UChar32 c,
const uint8_t *start, const uint8_t *src) {
int32_t i, length;
/* support 64-bit pointers by avoiding cast of arbitrary difference */
if((src-start)<=7) {
i=length=(int32_t)(src-start);
} else {
i=length=7;
start=src-7;
}
c=utf8_prevCharSafeBody(start, 0, &i, c, -1);
i=length-i; /* number of bytes read backward from src */
return u8Index(trie, c, i);
}
U_CAPI UTrie2 * U_EXPORT2
utrie2_openFromSerialized(UTrie2ValueBits valueBits,
const void *data, int32_t length, int32_t *pActualLength,
UErrorCode *pErrorCode) {
const UTrie2Header *header;
const uint16_t *p16;
int32_t actualLength;
UTrie2 tempTrie;
UTrie2 *trie;
if(U_FAILURE(*pErrorCode)) {
return 0;
}
if( length<=0 || (U_POINTER_MASK_LSB(data, 3)!=0) ||
valueBits<0 || UTRIE2_COUNT_VALUE_BITS<=valueBits
) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
/* enough data for a trie header? */
if(length<(int32_t)sizeof(UTrie2Header)) {
*pErrorCode=U_INVALID_FORMAT_ERROR;
return 0;
}
/* check the signature */
header=(const UTrie2Header *)data;
if(header->signature!=UTRIE2_SIG) {
*pErrorCode=U_INVALID_FORMAT_ERROR;
return 0;
}
/* get the options */
if(valueBits!=(UTrie2ValueBits)(header->options&UTRIE2_OPTIONS_VALUE_BITS_MASK)) {
*pErrorCode=U_INVALID_FORMAT_ERROR;
return 0;
}
/* get the length values and offsets */
uprv_memset(&tempTrie, 0, sizeof(tempTrie));
tempTrie.indexLength=header->indexLength;
tempTrie.dataLength=header->shiftedDataLength<<UTRIE2_INDEX_SHIFT;
tempTrie.index2NullOffset=header->index2NullOffset;
tempTrie.dataNullOffset=header->dataNullOffset;
tempTrie.highStart=header->shiftedHighStart<<UTRIE2_SHIFT_1;
tempTrie.highValueIndex=tempTrie.dataLength-UTRIE2_DATA_GRANULARITY;
if(valueBits==UTRIE2_16_VALUE_BITS) {
tempTrie.highValueIndex+=tempTrie.indexLength;
}
/* calculate the actual length */
actualLength=(int32_t)sizeof(UTrie2Header)+tempTrie.indexLength*2;
if(valueBits==UTRIE2_16_VALUE_BITS) {
actualLength+=tempTrie.dataLength*2;
} else {
actualLength+=tempTrie.dataLength*4;
}
if(length<actualLength) {
*pErrorCode=U_INVALID_FORMAT_ERROR; /* not enough bytes */
return 0;
}
/* allocate the trie */
trie=(UTrie2 *)uprv_malloc(sizeof(UTrie2));
if(trie==NULL) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return 0;
}
uprv_memcpy(trie, &tempTrie, sizeof(tempTrie));
trie->memory=(uint32_t *)data;
trie->length=actualLength;
trie->isMemoryOwned=FALSE;
/* set the pointers to its index and data arrays */
p16=(const uint16_t *)(header+1);
trie->index=p16;
p16+=trie->indexLength;
/* get the data */
switch(valueBits) {
case UTRIE2_16_VALUE_BITS:
trie->data16=p16;
trie->data32=NULL;
trie->initialValue=trie->index[trie->dataNullOffset];
trie->errorValue=trie->data16[UTRIE2_BAD_UTF8_DATA_OFFSET];
break;
case UTRIE2_32_VALUE_BITS:
trie->data16=NULL;
trie->data32=(const uint32_t *)p16;
trie->initialValue=trie->data32[trie->dataNullOffset];
trie->errorValue=trie->data32[UTRIE2_BAD_UTF8_DATA_OFFSET];
break;
default:
*pErrorCode=U_INVALID_FORMAT_ERROR;
return 0;
}
if(pActualLength!=NULL) {
*pActualLength=actualLength;
}
return trie;
}
U_CAPI UTrie2 * U_EXPORT2
utrie2_openDummy(UTrie2ValueBits valueBits,
uint32_t initialValue, uint32_t errorValue,
UErrorCode *pErrorCode) {
UTrie2 *trie;
UTrie2Header *header;
uint32_t *p;
uint16_t *dest16;
int32_t indexLength, dataLength, length, i;
int32_t dataMove; /* >0 if the data is moved to the end of the index array */
if(U_FAILURE(*pErrorCode)) {
return 0;
}
if(valueBits<0 || UTRIE2_COUNT_VALUE_BITS<=valueBits) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
/* calculate the total length of the dummy trie data */
indexLength=UTRIE2_INDEX_1_OFFSET;
dataLength=UTRIE2_DATA_START_OFFSET+UTRIE2_DATA_GRANULARITY;
length=(int32_t)sizeof(UTrie2Header)+indexLength*2;
if(valueBits==UTRIE2_16_VALUE_BITS) {
length+=dataLength*2;
} else {
length+=dataLength*4;
}
/* allocate the trie */
trie=(UTrie2 *)uprv_malloc(sizeof(UTrie2));
if(trie==NULL) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return 0;
}
uprv_memset(trie, 0, sizeof(UTrie2));
trie->memory=uprv_malloc(length);
if(trie->memory==NULL) {
uprv_free(trie);
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return 0;
}
trie->length=length;
trie->isMemoryOwned=TRUE;
/* set the UTrie2 fields */
if(valueBits==UTRIE2_16_VALUE_BITS) {
dataMove=indexLength;
} else {
dataMove=0;
}
trie->indexLength=indexLength;
trie->dataLength=dataLength;
trie->index2NullOffset=UTRIE2_INDEX_2_OFFSET;
trie->dataNullOffset=(uint16_t)dataMove;
trie->initialValue=initialValue;
trie->errorValue=errorValue;
trie->highStart=0;
trie->highValueIndex=dataMove+UTRIE2_DATA_START_OFFSET;
/* set the header fields */
header=(UTrie2Header *)trie->memory;
header->signature=UTRIE2_SIG; /* "Tri2" */
header->options=(uint16_t)valueBits;
header->indexLength=(uint16_t)indexLength;
header->shiftedDataLength=(uint16_t)(dataLength>>UTRIE2_INDEX_SHIFT);
header->index2NullOffset=(uint16_t)UTRIE2_INDEX_2_OFFSET;
header->dataNullOffset=(uint16_t)dataMove;
header->shiftedHighStart=0;
/* fill the index and data arrays */
dest16=(uint16_t *)(header+1);
trie->index=dest16;
/* write the index-2 array values shifted right by UTRIE2_INDEX_SHIFT */
for(i=0; i<UTRIE2_INDEX_2_BMP_LENGTH; ++i) {
*dest16++=(uint16_t)(dataMove>>UTRIE2_INDEX_SHIFT); /* null data block */
}
/* write UTF-8 2-byte index-2 values, not right-shifted */
for(i=0; i<(0xc2-0xc0); ++i) { /* C0..C1 */
*dest16++=(uint16_t)(dataMove+UTRIE2_BAD_UTF8_DATA_OFFSET);
}
for(; i<(0xe0-0xc0); ++i) { /* C2..DF */
*dest16++=(uint16_t)dataMove;
}
/* write the 16/32-bit data array */
switch(valueBits) {
case UTRIE2_16_VALUE_BITS:
/* write 16-bit data values */
trie->data16=dest16;
trie->data32=NULL;
for(i=0; i<0x80; ++i) {
*dest16++=(uint16_t)initialValue;
}
for(; i<0xc0; ++i) {
*dest16++=(uint16_t)errorValue;
}
/* highValue and reserved values */
for(i=0; i<UTRIE2_DATA_GRANULARITY; ++i) {
*dest16++=(uint16_t)initialValue;
}
break;
case UTRIE2_32_VALUE_BITS:
/* write 32-bit data values */
p=(uint32_t *)dest16;
trie->data16=NULL;
trie->data32=p;
for(i=0; i<0x80; ++i) {
*p++=initialValue;
}
for(; i<0xc0; ++i) {
*p++=errorValue;
}
/* highValue and reserved values */
for(i=0; i<UTRIE2_DATA_GRANULARITY; ++i) {
*p++=initialValue;
}
break;
default:
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
return trie;
}
U_CAPI void U_EXPORT2
utrie2_close(UTrie2 *trie) {
if(trie!=NULL) {
if(trie->isMemoryOwned) {
uprv_free(trie->memory);
}
if(trie->newTrie!=NULL) {
uprv_free(trie->newTrie->data);
uprv_free(trie->newTrie);
}
uprv_free(trie);
}
}
U_CAPI int32_t U_EXPORT2
utrie2_getVersion(const void *data, int32_t length, UBool anyEndianOk) {
uint32_t signature;
if(length<16 || data==NULL || (U_POINTER_MASK_LSB(data, 3)!=0)) {
return 0;
}
signature=*(const uint32_t *)data;
if(signature==UTRIE2_SIG) {
return 2;
}
if(anyEndianOk && signature==UTRIE2_OE_SIG) {
return 2;
}
if(signature==UTRIE_SIG) {
return 1;
}
if(anyEndianOk && signature==UTRIE_OE_SIG) {
return 1;
}
return 0;
}
U_CAPI UBool U_EXPORT2
utrie2_isFrozen(const UTrie2 *trie) {
return (UBool)(trie->newTrie==NULL);
}
U_CAPI int32_t U_EXPORT2
utrie2_serialize(const UTrie2 *trie,
void *data, int32_t capacity,
UErrorCode *pErrorCode) {
/* argument check */
if(U_FAILURE(*pErrorCode)) {
return 0;
}
if( trie==NULL || trie->memory==NULL || trie->newTrie!=NULL ||
capacity<0 || (capacity>0 && (data==NULL || (U_POINTER_MASK_LSB(data, 3)!=0)))
) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
if(capacity>=trie->length) {
uprv_memcpy(data, trie->memory, trie->length);
} else {
*pErrorCode=U_BUFFER_OVERFLOW_ERROR;
}
return trie->length;
}
U_CAPI int32_t U_EXPORT2
utrie2_swap(const UDataSwapper *ds,
const void *inData, int32_t length, void *outData,
UErrorCode *pErrorCode) {
const UTrie2Header *inTrie;
UTrie2Header trie;
int32_t dataLength, size;
UTrie2ValueBits valueBits;
if(U_FAILURE(*pErrorCode)) {
return 0;
}
if(ds==NULL || inData==NULL || (length>=0 && outData==NULL)) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
/* setup and swapping */
if(length>=0 && length<(int32_t)sizeof(UTrie2Header)) {
*pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
return 0;
}
inTrie=(const UTrie2Header *)inData;
trie.signature=ds->readUInt32(inTrie->signature);
trie.options=ds->readUInt16(inTrie->options);
trie.indexLength=ds->readUInt16(inTrie->indexLength);
trie.shiftedDataLength=ds->readUInt16(inTrie->shiftedDataLength);
valueBits=(UTrie2ValueBits)(trie.options&UTRIE2_OPTIONS_VALUE_BITS_MASK);
dataLength=(int32_t)trie.shiftedDataLength<<UTRIE2_INDEX_SHIFT;
if( trie.signature!=UTRIE2_SIG ||
valueBits<0 || UTRIE2_COUNT_VALUE_BITS<=valueBits ||
trie.indexLength<UTRIE2_INDEX_1_OFFSET ||
dataLength<UTRIE2_DATA_START_OFFSET
) {
*pErrorCode=U_INVALID_FORMAT_ERROR; /* not a UTrie */
return 0;
}
size=sizeof(UTrie2Header)+trie.indexLength*2;
switch(valueBits) {
case UTRIE2_16_VALUE_BITS:
size+=dataLength*2;
break;
case UTRIE2_32_VALUE_BITS:
size+=dataLength*4;
break;
default:
*pErrorCode=U_INVALID_FORMAT_ERROR;
return 0;
}
if(length>=0) {
UTrie2Header *outTrie;
if(length<size) {
*pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
return 0;
}
outTrie=(UTrie2Header *)outData;
/* swap the header */
ds->swapArray32(ds, &inTrie->signature, 4, &outTrie->signature, pErrorCode);
ds->swapArray16(ds, &inTrie->options, 12, &outTrie->options, pErrorCode);
/* swap the index and the data */
switch(valueBits) {
case UTRIE2_16_VALUE_BITS:
ds->swapArray16(ds, inTrie+1, (trie.indexLength+dataLength)*2, outTrie+1, pErrorCode);
break;
case UTRIE2_32_VALUE_BITS:
ds->swapArray16(ds, inTrie+1, trie.indexLength*2, outTrie+1, pErrorCode);
ds->swapArray32(ds, (const uint16_t *)(inTrie+1)+trie.indexLength, dataLength*4,
(uint16_t *)(outTrie+1)+trie.indexLength, pErrorCode);
break;
default:
*pErrorCode=U_INVALID_FORMAT_ERROR;
return 0;
}
}
return size;
}
// utrie2_swapAnyVersion() should be defined here but lives in utrie2_builder.c
// to avoid a dependency from utrie2.cpp on utrie.c.
/* enumeration -------------------------------------------------------------- */
#define MIN_VALUE(a, b) ((a)<(b) ? (a) : (b))
/* default UTrie2EnumValue() returns the input value itself */
static uint32_t U_CALLCONV
enumSameValue(const void * /*context*/, uint32_t value) {
return value;
}
/**
* Enumerate all ranges of code points with the same relevant values.
* The values are transformed from the raw trie entries by the enumValue function.
*
* Currently requires start<limit and both start and limit must be multiples
* of UTRIE2_DATA_BLOCK_LENGTH.
*
* Optimizations:
* - Skip a whole block if we know that it is filled with a single value,
* and it is the same as we visited just before.
* - Handle the null block specially because we know a priori that it is filled
* with a single value.
*/
static void
enumEitherTrie(const UTrie2 *trie,
UChar32 start, UChar32 limit,
UTrie2EnumValue *enumValue, UTrie2EnumRange *enumRange, const void *context) {
const uint32_t *data32;
const uint16_t *idx;
uint32_t value, prevValue, initialValue;
UChar32 c, prev, highStart;
int32_t j, i2Block, prevI2Block, index2NullOffset, block, prevBlock, nullBlock;
if(enumRange==NULL) {
return;
}
if(enumValue==NULL) {
enumValue=enumSameValue;
}
if(trie->newTrie==NULL) {
/* frozen trie */
idx=trie->index;
U_ASSERT(idx!=NULL); /* the following code assumes trie->newTrie is not NULL when idx is NULL */
data32=trie->data32;
index2NullOffset=trie->index2NullOffset;
nullBlock=trie->dataNullOffset;
} else {
/* unfrozen, mutable trie */
idx=NULL;
data32=trie->newTrie->data;
U_ASSERT(data32!=NULL); /* the following code assumes idx is not NULL when data32 is NULL */
index2NullOffset=trie->newTrie->index2NullOffset;
nullBlock=trie->newTrie->dataNullOffset;
}
highStart=trie->highStart;
/* get the enumeration value that corresponds to an initial-value trie data entry */
initialValue=enumValue(context, trie->initialValue);
/* set variables for previous range */
prevI2Block=-1;
prevBlock=-1;
prev=start;
prevValue=0;
/* enumerate index-2 blocks */
for(c=start; c<limit && c<highStart;) {
/* Code point limit for iterating inside this i2Block. */
UChar32 tempLimit=c+UTRIE2_CP_PER_INDEX_1_ENTRY;
if(limit<tempLimit) {
tempLimit=limit;
}
if(c<=0xffff) {
if(!U_IS_SURROGATE(c)) {
i2Block=c>>UTRIE2_SHIFT_2;
} else if(U_IS_SURROGATE_LEAD(c)) {
/*
* Enumerate values for lead surrogate code points, not code units:
* This special block has half the normal length.
*/
i2Block=UTRIE2_LSCP_INDEX_2_OFFSET;
tempLimit=MIN_VALUE(0xdc00, limit);
} else {
/*
* Switch back to the normal part of the index-2 table.
* Enumerate the second half of the surrogates block.
*/
i2Block=0xd800>>UTRIE2_SHIFT_2;
tempLimit=MIN_VALUE(0xe000, limit);
}
} else {
/* supplementary code points */
if(idx!=NULL) {
i2Block=idx[(UTRIE2_INDEX_1_OFFSET-UTRIE2_OMITTED_BMP_INDEX_1_LENGTH)+
(c>>UTRIE2_SHIFT_1)];
} else {
i2Block=trie->newTrie->index1[c>>UTRIE2_SHIFT_1];
}
if(i2Block==prevI2Block && (c-prev)>=UTRIE2_CP_PER_INDEX_1_ENTRY) {
/*
* The index-2 block is the same as the previous one, and filled with prevValue.
* Only possible for supplementary code points because the linear-BMP index-2
* table creates unique i2Block values.
*/
c+=UTRIE2_CP_PER_INDEX_1_ENTRY;
continue;
}
}
prevI2Block=i2Block;
if(i2Block==index2NullOffset) {
/* this is the null index-2 block */
if(prevValue!=initialValue) {
if(prev<c && !enumRange(context, prev, c-1, prevValue)) {
return;
}
prevBlock=nullBlock;
prev=c;
prevValue=initialValue;
}
c+=UTRIE2_CP_PER_INDEX_1_ENTRY;
} else {
/* enumerate data blocks for one index-2 block */
int32_t i2, i2Limit;
i2=(c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK;
if((c>>UTRIE2_SHIFT_1)==(tempLimit>>UTRIE2_SHIFT_1)) {
i2Limit=(tempLimit>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK;
} else {
i2Limit=UTRIE2_INDEX_2_BLOCK_LENGTH;
}
for(; i2<i2Limit; ++i2) {
if(idx!=NULL) {
block=(int32_t)idx[i2Block+i2]<<UTRIE2_INDEX_SHIFT;
} else {
block=trie->newTrie->index2[i2Block+i2];
}
if(block==prevBlock && (c-prev)>=UTRIE2_DATA_BLOCK_LENGTH) {
/* the block is the same as the previous one, and filled with prevValue */
c+=UTRIE2_DATA_BLOCK_LENGTH;
continue;
}
prevBlock=block;
if(block==nullBlock) {
/* this is the null data block */
if(prevValue!=initialValue) {
if(prev<c && !enumRange(context, prev, c-1, prevValue)) {
return;
}
prev=c;
prevValue=initialValue;
}
c+=UTRIE2_DATA_BLOCK_LENGTH;
} else {
for(j=0; j<UTRIE2_DATA_BLOCK_LENGTH; ++j) {
value=enumValue(context, data32!=NULL ? data32[block+j] : idx[block+j]);
if(value!=prevValue) {
if(prev<c && !enumRange(context, prev, c-1, prevValue)) {
return;
}
prev=c;
prevValue=value;
}
++c;
}
}
}
}
}
if(c>limit) {
c=limit; /* could be higher if in the index2NullOffset */
} else if(c<limit) {
/* c==highStart<limit */
uint32_t highValue;
if(idx!=NULL) {
highValue=
data32!=NULL ?
data32[trie->highValueIndex] :
idx[trie->highValueIndex];
} else {
highValue=trie->newTrie->data[trie->newTrie->dataLength-UTRIE2_DATA_GRANULARITY];
}
value=enumValue(context, highValue);
if(value!=prevValue) {
if(prev<c && !enumRange(context, prev, c-1, prevValue)) {
return;
}
prev=c;
prevValue=value;
}
c=limit;
}
/* deliver last range */
enumRange(context, prev, c-1, prevValue);
}
U_CAPI void U_EXPORT2
utrie2_enum(const UTrie2 *trie,
UTrie2EnumValue *enumValue, UTrie2EnumRange *enumRange, const void *context) {
enumEitherTrie(trie, 0, 0x110000, enumValue, enumRange, context);
}
U_CAPI void U_EXPORT2
utrie2_enumForLeadSurrogate(const UTrie2 *trie, UChar32 lead,
UTrie2EnumValue *enumValue, UTrie2EnumRange *enumRange,
const void *context) {
if(!U16_IS_LEAD(lead)) {
return;
}
lead=(lead-0xd7c0)<<10; /* start code point */
enumEitherTrie(trie, lead, lead+0x400, enumValue, enumRange, context);
}
/* C++ convenience wrappers ------------------------------------------------- */
U_NAMESPACE_BEGIN
uint16_t BackwardUTrie2StringIterator::previous16() {
codePointLimit=codePointStart;
if(start>=codePointStart) {
codePoint=U_SENTINEL;
return 0;
}
uint16_t result;
UTRIE2_U16_PREV16(trie, start, codePointStart, codePoint, result);
return result;
}
uint16_t ForwardUTrie2StringIterator::next16() {
codePointStart=codePointLimit;
if(codePointLimit==limit) {
codePoint=U_SENTINEL;
return 0;
}
uint16_t result;
UTRIE2_U16_NEXT16(trie, codePointLimit, limit, codePoint, result);
return result;
}
U_NAMESPACE_END
| mit |
KellyChan/python-examples | cpp/eigen/eigen/test/householder.cpp | 246 | 5984 | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/QR>
template<typename MatrixType> void householder(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
static bool even = true;
even = !even;
/* this test covers the following files:
Householder.h
*/
Index rows = m.rows();
Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, internal::decrement_size<MatrixType::RowsAtCompileTime>::ret, 1> EssentialVectorType;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
typedef Matrix<Scalar, Dynamic, MatrixType::ColsAtCompileTime> HBlockMatrixType;
typedef Matrix<Scalar, Dynamic, 1> HCoeffsVectorType;
typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, MatrixType::RowsAtCompileTime> TMatrixType;
Matrix<Scalar, EIGEN_SIZE_MAX(MatrixType::RowsAtCompileTime,MatrixType::ColsAtCompileTime), 1> _tmp((std::max)(rows,cols));
Scalar* tmp = &_tmp.coeffRef(0,0);
Scalar beta;
RealScalar alpha;
EssentialVectorType essential;
VectorType v1 = VectorType::Random(rows), v2;
v2 = v1;
v1.makeHouseholder(essential, beta, alpha);
v1.applyHouseholderOnTheLeft(essential,beta,tmp);
VERIFY_IS_APPROX(v1.norm(), v2.norm());
if(rows>=2) VERIFY_IS_MUCH_SMALLER_THAN(v1.tail(rows-1).norm(), v1.norm());
v1 = VectorType::Random(rows);
v2 = v1;
v1.applyHouseholderOnTheLeft(essential,beta,tmp);
VERIFY_IS_APPROX(v1.norm(), v2.norm());
MatrixType m1(rows, cols),
m2(rows, cols);
v1 = VectorType::Random(rows);
if(even) v1.tail(rows-1).setZero();
m1.colwise() = v1;
m2 = m1;
m1.col(0).makeHouseholder(essential, beta, alpha);
m1.applyHouseholderOnTheLeft(essential,beta,tmp);
VERIFY_IS_APPROX(m1.norm(), m2.norm());
if(rows>=2) VERIFY_IS_MUCH_SMALLER_THAN(m1.block(1,0,rows-1,cols).norm(), m1.norm());
VERIFY_IS_MUCH_SMALLER_THAN(numext::imag(m1(0,0)), numext::real(m1(0,0)));
VERIFY_IS_APPROX(numext::real(m1(0,0)), alpha);
v1 = VectorType::Random(rows);
if(even) v1.tail(rows-1).setZero();
SquareMatrixType m3(rows,rows), m4(rows,rows);
m3.rowwise() = v1.transpose();
m4 = m3;
m3.row(0).makeHouseholder(essential, beta, alpha);
m3.applyHouseholderOnTheRight(essential,beta,tmp);
VERIFY_IS_APPROX(m3.norm(), m4.norm());
if(rows>=2) VERIFY_IS_MUCH_SMALLER_THAN(m3.block(0,1,rows,rows-1).norm(), m3.norm());
VERIFY_IS_MUCH_SMALLER_THAN(numext::imag(m3(0,0)), numext::real(m3(0,0)));
VERIFY_IS_APPROX(numext::real(m3(0,0)), alpha);
// test householder sequence on the left with a shift
Index shift = internal::random<Index>(0, std::max<Index>(rows-2,0));
Index brows = rows - shift;
m1.setRandom(rows, cols);
HBlockMatrixType hbm = m1.block(shift,0,brows,cols);
HouseholderQR<HBlockMatrixType> qr(hbm);
m2 = m1;
m2.block(shift,0,brows,cols) = qr.matrixQR();
HCoeffsVectorType hc = qr.hCoeffs().conjugate();
HouseholderSequence<MatrixType, HCoeffsVectorType> hseq(m2, hc);
hseq.setLength(hc.size()).setShift(shift);
VERIFY(hseq.length() == hc.size());
VERIFY(hseq.shift() == shift);
MatrixType m5 = m2;
m5.block(shift,0,brows,cols).template triangularView<StrictlyLower>().setZero();
VERIFY_IS_APPROX(hseq * m5, m1); // test applying hseq directly
m3 = hseq;
VERIFY_IS_APPROX(m3 * m5, m1); // test evaluating hseq to a dense matrix, then applying
SquareMatrixType hseq_mat = hseq;
SquareMatrixType hseq_mat_conj = hseq.conjugate();
SquareMatrixType hseq_mat_adj = hseq.adjoint();
SquareMatrixType hseq_mat_trans = hseq.transpose();
SquareMatrixType m6 = SquareMatrixType::Random(rows, rows);
VERIFY_IS_APPROX(hseq_mat.adjoint(), hseq_mat_adj);
VERIFY_IS_APPROX(hseq_mat.conjugate(), hseq_mat_conj);
VERIFY_IS_APPROX(hseq_mat.transpose(), hseq_mat_trans);
VERIFY_IS_APPROX(hseq_mat * m6, hseq_mat * m6);
VERIFY_IS_APPROX(hseq_mat.adjoint() * m6, hseq_mat_adj * m6);
VERIFY_IS_APPROX(hseq_mat.conjugate() * m6, hseq_mat_conj * m6);
VERIFY_IS_APPROX(hseq_mat.transpose() * m6, hseq_mat_trans * m6);
VERIFY_IS_APPROX(m6 * hseq_mat, m6 * hseq_mat);
VERIFY_IS_APPROX(m6 * hseq_mat.adjoint(), m6 * hseq_mat_adj);
VERIFY_IS_APPROX(m6 * hseq_mat.conjugate(), m6 * hseq_mat_conj);
VERIFY_IS_APPROX(m6 * hseq_mat.transpose(), m6 * hseq_mat_trans);
// test householder sequence on the right with a shift
TMatrixType tm2 = m2.transpose();
HouseholderSequence<TMatrixType, HCoeffsVectorType, OnTheRight> rhseq(tm2, hc);
rhseq.setLength(hc.size()).setShift(shift);
VERIFY_IS_APPROX(rhseq * m5, m1); // test applying rhseq directly
m3 = rhseq;
VERIFY_IS_APPROX(m3 * m5, m1); // test evaluating rhseq to a dense matrix, then applying
}
void test_householder()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( householder(Matrix<double,2,2>()) );
CALL_SUBTEST_2( householder(Matrix<float,2,3>()) );
CALL_SUBTEST_3( householder(Matrix<double,3,5>()) );
CALL_SUBTEST_4( householder(Matrix<float,4,4>()) );
CALL_SUBTEST_5( householder(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( householder(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_7( householder(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_8( householder(Matrix<double,1,1>()) );
}
}
| mit |
madscient/FITOM | FITOMApp/TimerWin.cpp | 1 | 1480 | #include "stdafx.h"
#include "timer.h"
static UINT_PTR timerID;
static unsigned long lTimCnt;
static void ( *TimIntr)();
static unsigned long uSecPeriod;
static long long previous;
void CALLBACK TimerProc(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dummy1, DWORD dummy2)
{
if (uTimerID == timerID) {
#if 0
LONGLONG freq;
LONGLONG end;
LONGLONG begin = previous;
::QueryPerformanceFrequency( (LARGE_INTEGER*)&freq );
do {
::QueryPerformanceCounter( (LARGE_INTEGER*)&end );
} while ( ((end - begin) / freq) < uSecPeriod );
#endif
lTimCnt++;
if ( TimIntr != NULL ) {
(*TimIntr)();
}
#if 0
::QueryPerformanceCounter( (LARGE_INTEGER*)&previous );
#endif
}
}
unsigned long CTimer::GetPeriod()
{
return( uSecPeriod );
}
unsigned long CTimer::GetClock()
{
return( lTimCnt );
}
int CTimer::ResetClock()
{
lTimCnt = 0;
return( NOERR );
}
void *CTimer::SetIntr( void ( *timer)() )
{
void ( *Intr)();
Intr = TimIntr;
TimIntr = timer;
return( Intr );
}
int CTimer::Init( unsigned msec )
{
MSG msg;
PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
::timeBeginPeriod( 1 );
::QueryPerformanceFrequency( (LARGE_INTEGER*)&previous );
timerID = timeSetEvent(msec-1, 0, TimerProc, (DWORD)this, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
uSecPeriod = msec * 1000;
lTimCnt = 0;
return 0;
}
int CTimer::Stop()
{
KillTimer(NULL, timerID);
Sleep(20);
return( NOERR );
}
| cc0-1.0 |
giovannimanzoni/volcano | linux/projects/sumo/scanAndPush/testScanPush.c | 2 | 1265 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define SCAN 0
#define CHECK 1
#define STOP 2
#define NEW 1
#define CURRENT 0
int dir;
int line;
int speed;
int mm;
void printBanner(){
printf("\n\n\rPROGRAM for detect robot within 55cm\n\n\r");
}
void init(){
line=NEW;
speed = SCAN;
initPwm();
stop();
sleep(2);
}
void scanFast(){
if (line == CURRENT ) {
printf("\n\r");
line = NEW;
}
if ( speed == STOP ) speed = SCAN;
if ( speed == SCAN) turnMax();
else turnMin(); // CHECK
}
void scanSlow(){
printf("Seeking better the robot \r");
turnMin();
speed= CHECK;
}
void push(){
// robot found
forward();
speed= STOP; // as soon as the object moves, the robot must rotate faster
printf("\n\rRobot found \n\r");
}
int objInRange(){
if ( (mm > 55) || ( mm < 1 ) ) return 0;
else return 1;
}
void run(){
init();
for(;;){
mm=getmm();
if ( objInRange() ) scanFast();
// the robot could not stand still in front, so reverse the direction.
else {
if (line == NEW ) {
printf("\n\r");
line = CURRENT;
}
if (speed == SCAN) scanSlow();
else if( speed==CHECK ) push();
// STOP -> nothing
}
}
closePwm();
}
int main(){
printBanner();
run();
return 0;
}
| cc0-1.0 |
supriyasingh01/github_basics | Internetworking Distributed Project/Kernal/linux-3.6.3/samples/kfifo/bytestream-example.c | 10729 | 4083 | /*
* Sample kfifo byte stream implementation
*
* Copyright (C) 2010 Stefani Seibold <stefani@seibold.net>
*
* Released under the GPL version 2 only.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include <linux/kfifo.h>
/*
* This module shows how to create a byte stream fifo.
*/
/* fifo size in elements (bytes) */
#define FIFO_SIZE 32
/* name of the proc entry */
#define PROC_FIFO "bytestream-fifo"
/* lock for procfs read access */
static DEFINE_MUTEX(read_lock);
/* lock for procfs write access */
static DEFINE_MUTEX(write_lock);
/*
* define DYNAMIC in this example for a dynamically allocated fifo.
*
* Otherwise the fifo storage will be a part of the fifo structure.
*/
#if 0
#define DYNAMIC
#endif
#ifdef DYNAMIC
static struct kfifo test;
#else
static DECLARE_KFIFO(test, unsigned char, FIFO_SIZE);
#endif
static const unsigned char expected_result[FIFO_SIZE] = {
3, 4, 5, 6, 7, 8, 9, 0,
1, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42,
};
static int __init testfunc(void)
{
unsigned char buf[6];
unsigned char i, j;
unsigned int ret;
printk(KERN_INFO "byte stream fifo test start\n");
/* put string into the fifo */
kfifo_in(&test, "hello", 5);
/* put values into the fifo */
for (i = 0; i != 10; i++)
kfifo_put(&test, &i);
/* show the number of used elements */
printk(KERN_INFO "fifo len: %u\n", kfifo_len(&test));
/* get max of 5 bytes from the fifo */
i = kfifo_out(&test, buf, 5);
printk(KERN_INFO "buf: %.*s\n", i, buf);
/* get max of 2 elements from the fifo */
ret = kfifo_out(&test, buf, 2);
printk(KERN_INFO "ret: %d\n", ret);
/* and put it back to the end of the fifo */
ret = kfifo_in(&test, buf, ret);
printk(KERN_INFO "ret: %d\n", ret);
/* skip first element of the fifo */
printk(KERN_INFO "skip 1st element\n");
kfifo_skip(&test);
/* put values into the fifo until is full */
for (i = 20; kfifo_put(&test, &i); i++)
;
printk(KERN_INFO "queue len: %u\n", kfifo_len(&test));
/* show the first value without removing from the fifo */
if (kfifo_peek(&test, &i))
printk(KERN_INFO "%d\n", i);
/* check the correctness of all values in the fifo */
j = 0;
while (kfifo_get(&test, &i)) {
printk(KERN_INFO "item = %d\n", i);
if (i != expected_result[j++]) {
printk(KERN_WARNING "value mismatch: test failed\n");
return -EIO;
}
}
if (j != ARRAY_SIZE(expected_result)) {
printk(KERN_WARNING "size mismatch: test failed\n");
return -EIO;
}
printk(KERN_INFO "test passed\n");
return 0;
}
static ssize_t fifo_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int ret;
unsigned int copied;
if (mutex_lock_interruptible(&write_lock))
return -ERESTARTSYS;
ret = kfifo_from_user(&test, buf, count, &copied);
mutex_unlock(&write_lock);
return ret ? ret : copied;
}
static ssize_t fifo_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int ret;
unsigned int copied;
if (mutex_lock_interruptible(&read_lock))
return -ERESTARTSYS;
ret = kfifo_to_user(&test, buf, count, &copied);
mutex_unlock(&read_lock);
return ret ? ret : copied;
}
static const struct file_operations fifo_fops = {
.owner = THIS_MODULE,
.read = fifo_read,
.write = fifo_write,
.llseek = noop_llseek,
};
static int __init example_init(void)
{
#ifdef DYNAMIC
int ret;
ret = kfifo_alloc(&test, FIFO_SIZE, GFP_KERNEL);
if (ret) {
printk(KERN_ERR "error kfifo_alloc\n");
return ret;
}
#else
INIT_KFIFO(test);
#endif
if (testfunc() < 0) {
#ifdef DYNAMIC
kfifo_free(&test);
#endif
return -EIO;
}
if (proc_create(PROC_FIFO, 0, NULL, &fifo_fops) == NULL) {
#ifdef DYNAMIC
kfifo_free(&test);
#endif
return -ENOMEM;
}
return 0;
}
static void __exit example_exit(void)
{
remove_proc_entry(PROC_FIFO, NULL);
#ifdef DYNAMIC
kfifo_free(&test);
#endif
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Stefani Seibold <stefani@seibold.net>");
| cc0-1.0 |
tomgr/graphviz-cmake | tclpkg/tclpathplan/tclpathplan.c | 1 | 23995 | /* $Id: tclpathplan.c,v 1.6 2011/01/25 16:30:52 ellson Exp $ $Revision: 1.6 $ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
/*
* Tcl binding to drive Stephen North's and
* Emden Gansner's shortest path code.
*
* ellson@graphviz.org October 2nd, 1996
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* avoid compiler warnings with template changes in Tcl8.4 */
/* specifically just the change to Tcl_CmdProc */
#define USE_NON_CONST
/* for sincos */
#define _GNU_SOURCE 1
#ifdef HAVE_AST
#include <ast.h>
#include <vmalloc.h>
#else
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#endif
#include <assert.h>
#include <math.h>
#include <pathutil.h>
#include <vispath.h>
#include <tri.h>
#include <tcl.h>
#include "tclhandle.h"
#ifndef CONST84
#define CONST84
#endif
#if ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 6)) || ( TCL_MAJOR_VERSION > 8)
#else
#ifndef Tcl_GetStringResult
#define Tcl_GetStringResult(interp) interp->result
#endif
#endif
typedef Ppoint_t point;
typedef struct poly_s {
int id;
Ppoly_t boundary;
} poly;
typedef struct vgpane_s {
int Npoly; /* number of polygons */
poly *poly; /* set of polygons */
int N_poly_alloc; /* for allocation */
vconfig_t *vc; /* visibility graph handle */
Tcl_Interp *interp; /* interpreter that owns the binding */
char *triangle_cmd; /* why is this here any more */
} vgpane_t;
#ifdef HAVE_SINCOS
extern void sincos(double x, double *s, double *c);
#else
# define sincos(x,s,c) *s = sin(x); *c = cos(x)
#endif
tblHeader_pt vgpaneTable;
extern void make_CW(Ppoly_t * poly);
extern int Plegal_arrangement(Ppoly_t ** polys, int n_polys);
static int polyid = 0; /* unique and unchanging id for each poly */
static poly *allocpoly(vgpane_t * vgp, int id, int npts)
{
poly *rv;
if (vgp->Npoly >= vgp->N_poly_alloc) {
vgp->N_poly_alloc *= 2;
vgp->poly = realloc(vgp->poly, vgp->N_poly_alloc * sizeof(poly));
}
rv = &(vgp->poly[vgp->Npoly++]);
rv->id = id;
rv->boundary.pn = 0;
rv->boundary.ps = malloc(npts * sizeof(point));
return rv;
}
static void vc_stale(vgpane_t * vgp)
{
if (vgp->vc) {
Pobsclose(vgp->vc);
vgp->vc = (vconfig_t *) 0;
}
}
static int vc_refresh(vgpane_t * vgp)
{
int i;
Ppoly_t **obs;
if (vgp->vc == (vconfig_t *) 0) {
obs = malloc(vgp->Npoly * sizeof(Ppoly_t));
for (i = 0; i < vgp->Npoly; i++)
obs[i] = &(vgp->poly[i].boundary);
if (NOT(Plegal_arrangement(obs, vgp->Npoly)))
fprintf(stderr, "bad arrangement\n");
else
vgp->vc = Pobsopen(obs, vgp->Npoly);
free(obs);
}
return (vgp->vc != 0);
}
static void dgsprintxy(Tcl_DString * result, int npts, point p[])
{
int i;
char buf[20];
if (npts != 1)
Tcl_DStringStartSublist(result);
for (i = 0; i < npts; i++) {
sprintf(buf, "%g", p[i].x);
Tcl_DStringAppendElement(result, buf);
sprintf(buf, "%g", p[i].y);
Tcl_DStringAppendElement(result, buf);
}
if (npts != 1)
Tcl_DStringEndSublist(result);
}
static void expandPercentsEval(Tcl_Interp * interp, /* interpreter context */
register char *before, /* Command with percent expressions */
char *r, /* vgpaneHandle string to substitute for "%r" */
int npts, /* number of coordinates */
point * ppos /* Cordinates to substitute for %t */
)
{
register char *string;
Tcl_DString scripts;
Tcl_DStringInit(&scripts);
while (1) {
/*
* Find everything up to the next % character and append it to the
* result string.
*/
for (string = before; (*string != 0) && (*string != '%'); string++) {
/* Empty loop body. */
}
if (string != before) {
Tcl_DStringAppend(&scripts, before, string - before);
before = string;
}
if (*before == 0) {
break;
}
/*
* There's a percent sequence here. Process it.
*/
switch (before[1]) {
case 'r':
Tcl_DStringAppend(&scripts, r, strlen(r)); /* vgcanvasHandle */
break;
case 't':
dgsprintxy(&scripts, npts, ppos);
break;
default:
Tcl_DStringAppend(&scripts, before + 1, 1);
break;
}
before += 2;
}
if (Tcl_GlobalEval(interp, Tcl_DStringValue(&scripts)) != TCL_OK)
fprintf(stderr, "%s while in binding: %s\n\n",
Tcl_GetStringResult(interp), Tcl_DStringValue(&scripts));
Tcl_DStringFree(&scripts);
}
void triangle_callback(void *vgparg, point pqr[])
{
char vbuf[20];
vgpane_t *vgp;
vgp = vgparg;
/* TBL_ENTRY((tblHeader_pt)vgpaneTable, (ubyte_pt)vgp));*/
if (vgp->triangle_cmd) {
sprintf(vbuf, "vgpane%lu",
(unsigned long) (((ubyte_pt) vgp - (vgpaneTable->bodyPtr))
/ (vgpaneTable->entrySize)));
expandPercentsEval(vgp->interp, vgp->triangle_cmd, vbuf, 3, pqr);
}
}
static char *buildBindings(char *s1, char *s2)
/*
* previous binding in s1 binding to be added in s2 result in s3
*
* if s2 begins with + then append (separated by \n) else s2 replaces if
* resultant string is null then bindings are deleted
*/
{
char *s3;
int l;
if (s2[0] == '+') {
if (s1) {
l = strlen(s2) - 1;
if (l) {
s3 = malloc(strlen(s1) + l + 2);
strcpy(s3, s1);
strcat(s3, "\n");
strcat(s3, s2 + 1);
free(s1);
} else {
s3 = s1;
}
} else {
l = strlen(s2) - 1;
if (l) {
s3 = malloc(l + 2);
strcpy(s3, s2 + 1);
} else {
s3 = (char *) NULL;
}
}
} else {
if (s1)
free(s1);
l = strlen(s2);
if (l) {
s3 = malloc(l + 2);
strcpy(s3, s2);
} else {
s3 = (char *) NULL;
}
}
return s3;
}
/* convert x and y string args to point */
static int scanpoint(Tcl_Interp * interp, char *argv[], point * p)
{
if (sscanf(argv[0], "%lg", &(p->x)) != 1) {
Tcl_AppendResult(interp, "invalid x coordinate: \"", argv[0],
"\"", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[1], "%lg", &(p->y)) != 1) {
Tcl_AppendResult(interp, "invalid y coordinate: \"", argv[1],
"\"", (char *) NULL);
return TCL_ERROR;
}
return TCL_OK;
}
static point center(point vertex[], int n)
{
int i;
point c;
c.x = c.y = 0;
for (i = 0; i < n; i++) {
c.x += vertex[i].x;
c.y += vertex[i].y;
}
c.x /= n;
c.y /= n;
return c;
}
static double distance(point p, point q)
{
double dx, dy;
dx = p.x - q.x;
dy = p.y - q.y;
return sqrt(dx * dx + dy * dy);
}
static point rotate(point c, point p, double alpha)
{
point q;
double beta, r, sina, cosa;
r = distance(c, p);
beta = atan2(p.x - c.x, p.y - c.y);
sincos(beta + alpha, &sina, &cosa);
q.x = c.x + r * sina;
q.y = c.y - r * cosa; /* adjust for tk y-down */
return q;
}
static point scale(point c, point p, double gain)
{
point q;
q.x = c.x + gain * (p.x - c.x);
q.y = c.y + gain * (p.y - c.y);
return q;
}
static int remove_poly(vgpane_t * vgp, int polyid)
{
int i, j;
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
free(vgp->poly[i].boundary.ps);
for (j = i++; i < vgp->Npoly; i++, j++) {
vgp->poly[j] = vgp->poly[i];
}
vgp->Npoly -= 1;
vc_stale(vgp);
return TRUE;
}
}
return FALSE;
}
static int
insert_poly(Tcl_Interp * interp, vgpane_t * vgp, int polyid, char *vargv[],
int vargc)
{
poly *np;
int i, result;
np = allocpoly(vgp, polyid, vargc);
for (i = 0; i < vargc; i += 2) {
result =
scanpoint(interp, &vargv[i],
&(np->boundary.ps[np->boundary.pn]));
if (result != TCL_OK)
return result;
np->boundary.pn++;
}
make_CW(&(np->boundary));
vc_stale(vgp);
return TCL_OK;
}
static void
make_barriers(vgpane_t * vgp, int pp, int qp, Pedge_t ** barriers,
int *n_barriers)
{
int i, j, k, n, b;
Pedge_t *bar;
n = 0;
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == pp)
continue;
if (vgp->poly[i].id == qp)
continue;
n = n + vgp->poly[i].boundary.pn;
}
bar = malloc(n * sizeof(Pedge_t));
b = 0;
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == pp)
continue;
if (vgp->poly[i].id == qp)
continue;
for (j = 0; j < vgp->poly[i].boundary.pn; j++) {
k = j + 1;
if (k >= vgp->poly[i].boundary.pn)
k = 0;
bar[b].a = vgp->poly[i].boundary.ps[j];
bar[b].b = vgp->poly[i].boundary.ps[k];
b++;
}
}
assert(b == n);
*barriers = bar;
*n_barriers = n;
}
/* append the x and y coordinates of a point to the Tcl result */
static void appendpoint(Tcl_Interp * interp, point p)
{
char buf[30];
sprintf(buf, "%g", p.x);
Tcl_AppendElement(interp, buf);
sprintf(buf, "%g", p.y);
Tcl_AppendElement(interp, buf);
}
/* process vgpane methods */
static int
vgpanecmd(ClientData clientData, Tcl_Interp * interp, int argc,
char *argv[])
{
int vargc, length, i, j, n, result;
char c, *s, **vargv, vbuf[30];
vgpane_t *vgp, **vgpp;
point p, q, *ps;
poly *tpp;
double alpha, gain;
Pvector_t slopes[2];
Ppolyline_t line, spline;
int pp, qp; /* polygon indices for p, q */
Pedge_t *barriers;
int n_barriers;
if (argc < 2) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
" ", argv[0], " method ?arg arg ...?\"",
(char *) NULL);
return TCL_ERROR;
}
if (!(vgpp = (vgpane_t **) tclhandleXlate(vgpaneTable, argv[0]))) {
Tcl_AppendResult(interp, "Invalid handle: \"", argv[0],
"\"", (char *) NULL);
return TCL_ERROR;
}
vgp = *vgpp;
c = argv[1][0];
length = strlen(argv[1]);
if ((c == 'c') && (strncmp(argv[1], "coords", length) == 0)) {
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " id ?x1 y1 x2 y2...?\"",
(char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
if (argc == 3) {
/* find poly and return its coordinates */
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
n = vgp->poly[i].boundary.pn;
for (j = 0; j < n; j++) {
appendpoint(interp, vgp->poly[i].boundary.ps[j]);
}
return TCL_OK;
}
}
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
/* accept either inline or delimited list */
if ((argc == 4)) {
result =
Tcl_SplitList(interp, argv[3], &vargc,
(CONST84 char ***) &vargv);
if (result != TCL_OK) {
return result;
}
} else {
vargc = argc - 3;
vargv = &argv[3];
}
if (!vargc || vargc % 2) {
Tcl_AppendResult(interp,
"There must be a multiple of two terms in the list.",
(char *) NULL);
return TCL_ERROR;
}
/* remove old poly, add modified polygon to the end with
the same id as the original */
if (!(remove_poly(vgp, polyid))) {
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
return (insert_poly(interp, vgp, polyid, vargv, vargc));
} else if ((c == 'd') && (strncmp(argv[1], "debug", length) == 0)) {
/* debug only */
printf("debug output goes here\n");
return TCL_OK;
} else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0)) {
/* delete a vgpane and all memory associated with it */
if (vgp->vc)
Pobsclose(vgp->vc);
free(vgp->poly); /* ### */
Tcl_DeleteCommand(interp, argv[0]);
free((char *) tclhandleFree(vgpaneTable, argv[0]));
return TCL_OK;
} else if ((c == 'f') && (strncmp(argv[1], "find", length) == 0)) {
/* find the polygon that the point is inside and return it
id, or null */
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " x y\"", (char *) NULL);
return TCL_ERROR;
}
if (argc == 3) {
result =
Tcl_SplitList(interp, argv[2], &vargc,
(CONST84 char ***) &vargv);
if (result != TCL_OK) {
return result;
}
} else {
vargc = argc - 2;
vargv = &argv[2];
}
result = scanpoint(interp, &vargv[0], &p);
if (result != TCL_OK)
return result;
/* determine the polygons (if any) that contain the point */
for (i = 0; i < vgp->Npoly; i++) {
if (in_poly(vgp->poly[i].boundary, p)) {
sprintf(vbuf, "%d", vgp->poly[i].id);
Tcl_AppendElement(interp, vbuf);
}
}
return TCL_OK;
} else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0)) {
/* add poly to end poly list, and it coordinates to the end of
the point list */
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " x1 y1 x2 y2 ...\"",
(char *) NULL);
return TCL_ERROR;
}
/* accept either inline or delimited list */
if ((argc == 3)) {
result =
Tcl_SplitList(interp, argv[2], &vargc,
(CONST84 char ***) &vargv);
if (result != TCL_OK) {
return result;
}
} else {
vargc = argc - 2;
vargv = &argv[2];
}
if (!vargc || vargc % 2) {
Tcl_AppendResult(interp,
"There must be a multiple of two terms in the list.",
(char *) NULL);
return TCL_ERROR;
}
polyid++;
result = insert_poly(interp, vgp, polyid, vargv, vargc);
if (result != TCL_OK)
return result;
sprintf(vbuf, "%d", polyid);
Tcl_AppendResult(interp, vbuf, (char *) NULL);
return TCL_OK;
} else if ((c == 'l') && (strncmp(argv[1], "list", length) == 0)) {
/* return list of polygon ids */
for (i = 0; i < vgp->Npoly; i++) {
sprintf(vbuf, "%d", vgp->poly[i].id);
Tcl_AppendElement(interp, vbuf);
}
return TCL_OK;
} else if ((c == 'p') && (strncmp(argv[1], "path", length) == 0)) {
/* return a list of points corresponding to the shortest path
that does not cross the remaining "visible" polygons. */
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " x1 y1 x2 y2\"",
(char *) NULL);
return TCL_ERROR;
}
if (argc == 3) {
result =
Tcl_SplitList(interp, argv[2], &vargc,
(CONST84 char ***) &vargv);
if (result != TCL_OK) {
return result;
}
} else {
vargc = argc - 2;
vargv = &argv[2];
}
if ((vargc < 4)) {
Tcl_AppendResult(interp,
"invalid points: should be: \"x1 y1 x2 y2\"",
(char *) NULL);
return TCL_ERROR;
}
result = scanpoint(interp, &vargv[0], &p);
if (result != TCL_OK)
return result;
result = scanpoint(interp, &vargv[2], &q);
if (result != TCL_OK)
return result;
/* only recompute the visibility graph if we have to */
if ((vc_refresh(vgp))) {
Pobspath(vgp->vc, p, POLYID_UNKNOWN, q, POLYID_UNKNOWN, &line);
for (i = 0; i < line.pn; i++) {
appendpoint(interp, line.ps[i]);
}
}
return TCL_OK;
} else if ((c == 'b') && (strncmp(argv[1], "bind", length) == 0)) {
if ((argc < 2) || (argc > 4)) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " bind triangle ?command?\"",
(char *) NULL);
return TCL_ERROR;
}
if (argc == 2) {
Tcl_AppendElement(interp, "triangle");
return TCL_OK;
}
length = strlen(argv[2]);
if (strncmp(argv[2], "triangle", length) == 0) {
s = vgp->triangle_cmd;
if (argc == 4)
vgp->triangle_cmd = s = buildBindings(s, argv[3]);
} else {
Tcl_AppendResult(interp, "unknown event \"", argv[2],
"\": must be one of:\n\ttriangle.",
(char *) NULL);
return TCL_ERROR;
}
if (argc == 3)
Tcl_AppendResult(interp, s, (char *) NULL);
return TCL_OK;
} else if ((c == 'b') && (strncmp(argv[1], "bpath", length) == 0)) {
/* return a list of points corresponding to the shortest path
that does not cross the remaining "visible" polygons. */
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " x1 y1 x2 y2\"",
(char *) NULL);
return TCL_ERROR;
}
if (argc == 3) {
result =
Tcl_SplitList(interp, argv[2], &vargc,
(CONST84 char ***) &vargv);
if (result != TCL_OK) {
return result;
}
} else {
vargc = argc - 2;
vargv = &argv[2];
}
if ((vargc < 4)) {
Tcl_AppendResult(interp,
"invalid points: should be: \"x1 y1 x2 y2\"",
(char *) NULL);
return TCL_ERROR;
}
result = scanpoint(interp, &vargv[0], &p);
if (result != TCL_OK)
return result;
result = scanpoint(interp, &vargv[2], &q);
if (result != TCL_OK)
return result;
/* determine the polygons (if any) that contain the endpoints */
pp = qp = POLYID_NONE;
for (i = 0; i < vgp->Npoly; i++) {
tpp = &(vgp->poly[i]);
if ((pp == POLYID_NONE) && in_poly(tpp->boundary, p))
pp = i;
if ((qp == POLYID_NONE) && in_poly(tpp->boundary, q))
qp = i;
}
if (vc_refresh(vgp)) {
/*Pobspath(vgp->vc, p, pp, q, qp, &line); */
Pobspath(vgp->vc, p, POLYID_UNKNOWN, q, POLYID_UNKNOWN, &line);
make_barriers(vgp, pp, qp, &barriers, &n_barriers);
slopes[0].x = slopes[0].y = 0.0;
slopes[1].x = slopes[1].y = 0.0;
Proutespline(barriers, n_barriers, line, slopes, &spline);
for (i = 0; i < spline.pn; i++) {
appendpoint(interp, spline.ps[i]);
}
}
return TCL_OK;
} else if ((c == 'b') && (strncmp(argv[1], "bbox", length) == 0)) {
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " id\"", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
Ppoly_t pp = vgp->poly[i].boundary;
point LL, UR;
LL = UR = pp.ps[0];
for (j = 1; j < pp.pn; j++) {
p = pp.ps[j];
if (p.x > UR.x)
UR.x = p.x;
if (p.y > UR.y)
UR.y = p.y;
if (p.x < LL.x)
LL.x = p.x;
if (p.y < LL.y)
LL.y = p.y;
}
appendpoint(interp, LL);
appendpoint(interp, UR);
return TCL_OK;
}
}
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
} else if ((c == 'c') && (strncmp(argv[1], "center", length) == 0)) {
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " id\"", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
appendpoint(interp, center(vgp->poly[i].boundary.ps,
vgp->poly[i].boundary.pn));
return TCL_OK;
}
}
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
} else if ((c == 't')
&& (strncmp(argv[1], "triangulate", length) == 0)) {
if ((argc < 2)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" id ", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
Ptriangulate(&(vgp->poly[i].boundary), triangle_callback,
vgp);
return TCL_OK;
}
}
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
} else if ((c == 'r') && (strncmp(argv[1], "rotate", length) == 0)) {
if ((argc < 4)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " id alpha\"", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[3], "%lg", &alpha) != 1) {
Tcl_AppendResult(interp, "not an angle in radians: ", argv[3],
(char *) NULL);
return TCL_ERROR;
}
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
n = vgp->poly[i].boundary.pn;
ps = vgp->poly[i].boundary.ps;
p = center(ps, n);
for (j = 0; j < n; j++) {
appendpoint(interp, rotate(p, ps[j], alpha));
}
return TCL_OK;
}
}
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
} else if ((c == 's') && (strncmp(argv[1], "scale", length) == 0)) {
if ((argc < 4)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " id gain\"", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[3], "%lg", &gain) != 1) {
Tcl_AppendResult(interp, "not a number: ", argv[3],
(char *) NULL);
return TCL_ERROR;
}
for (i = 0; i < vgp->Npoly; i++) {
if (vgp->poly[i].id == polyid) {
n = vgp->poly[i].boundary.pn;
ps = vgp->poly[i].boundary.ps;
for (j = 0; j < n; j++) {
appendpoint(interp, scale(p, ps[j], gain));
}
return TCL_OK;
}
}
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
} else if ((c == 'r') && (strncmp(argv[1], "remove", length) == 0)) {
if ((argc < 3)) {
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ", argv[1], " id\"", (char *) NULL);
return TCL_ERROR;
}
if (sscanf(argv[2], "%d", &polyid) != 1) {
Tcl_AppendResult(interp, "not an integer: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
if (remove_poly(vgp, polyid))
return TCL_OK;
Tcl_AppendResult(interp, " no such polygon: ", argv[2],
(char *) NULL);
return TCL_ERROR;
}
Tcl_AppendResult(interp, "bad method \"", argv[1],
"\" must be one of:",
"\n\tbbox, bind, bpath, center, coords, delete, find,",
"\n\tinsert, list, path, remove, rotate, scale, triangulate.",
(char *) NULL);
return TCL_ERROR;
}
static int
vgpane(ClientData clientData, Tcl_Interp * interp, int argc, char *argv[])
{
char vbuf[30];
vgpane_t *vgp;
vgp = (vgpane_t *) malloc(sizeof(vgpane_t));
*(vgpane_t **) tclhandleAlloc(vgpaneTable, vbuf, NULL) = vgp;
vgp->vc = (vconfig_t *) 0;
vgp->Npoly = 0;
vgp->N_poly_alloc = 250;
vgp->poly = malloc(vgp->N_poly_alloc * sizeof(poly));
vgp->interp = interp;
vgp->triangle_cmd = (char *) NULL;
Tcl_CreateCommand(interp, vbuf, vgpanecmd,
(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
Tcl_AppendResult(interp, vbuf, (char *) NULL);
return TCL_OK;
}
int Tclpathplan_Init(Tcl_Interp * interp)
{
#ifdef USE_TCL_STUBS
if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) {
return TCL_ERROR;
}
#else
if (Tcl_PkgRequire(interp, "Tcl", TCL_VERSION, 0) == NULL) {
return TCL_ERROR;
}
#endif
if (Tcl_PkgProvide(interp, "Tclpathplan", VERSION) != TCL_OK) {
return TCL_ERROR;
}
Tcl_CreateCommand(interp, "vgpane", vgpane,
(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
vgpaneTable = tclhandleInit("vgpane", sizeof(vgpane_t), 10);
return TCL_OK;
}
int Tclpathplan_SafeInit(Tcl_Interp * interp)
{
return Tclpathplan_Init(interp);
}
| epl-1.0 |
dupuisa/i-CodeCNES | fortran77-rules/src/test/resources/f77_2/dlafts.f | 32 | 5956 | *> \brief \b DLAFTS
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
* Definition:
* ===========
*
* SUBROUTINE DLAFTS( TYPE, M, N, IMAT, NTESTS, RESULT, ISEED,
* THRESH, IOUNIT, IE )
*
* .. Scalar Arguments ..
* CHARACTER*3 TYPE
* INTEGER IE, IMAT, IOUNIT, M, N, NTESTS
* DOUBLE PRECISION THRESH
* ..
* .. Array Arguments ..
* INTEGER ISEED( 4 )
* DOUBLE PRECISION RESULT( * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> DLAFTS tests the result vector against the threshold value to
*> see which tests for this matrix type failed to pass the threshold.
*> Output is to the file given by unit IOUNIT.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \verbatim
*> TYPE - CHARACTER*3
*> On entry, TYPE specifies the matrix type to be used in the
*> printed messages.
*> Not modified.
*>
*> N - INTEGER
*> On entry, N specifies the order of the test matrix.
*> Not modified.
*>
*> IMAT - INTEGER
*> On entry, IMAT specifies the type of the test matrix.
*> A listing of the different types is printed by DLAHD2
*> to the output file if a test fails to pass the threshold.
*> Not modified.
*>
*> NTESTS - INTEGER
*> On entry, NTESTS is the number of tests performed on the
*> subroutines in the path given by TYPE.
*> Not modified.
*>
*> RESULT - DOUBLE PRECISION array of dimension( NTESTS )
*> On entry, RESULT contains the test ratios from the tests
*> performed in the calling program.
*> Not modified.
*>
*> ISEED - INTEGER array of dimension( 4 )
*> Contains the random seed that generated the matrix used
*> for the tests whose ratios are in RESULT.
*> Not modified.
*>
*> THRESH - DOUBLE PRECISION
*> On entry, THRESH specifies the acceptable threshold of the
*> test ratios. If RESULT( K ) > THRESH, then the K-th test
*> did not pass the threshold and a message will be printed.
*> Not modified.
*>
*> IOUNIT - INTEGER
*> On entry, IOUNIT specifies the unit number of the file
*> to which the messages are printed.
*> Not modified.
*>
*> IE - INTEGER
*> On entry, IE contains the number of tests which have
*> failed to pass the threshold so far.
*> Updated on exit if any of the ratios in RESULT also fail.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup double_eig
*
* =====================================================================
SUBROUTINE DLAFTS( TYPE, M, N, IMAT, NTESTS, RESULT, ISEED,
$ THRESH, IOUNIT, IE )
*
* -- LAPACK test routine (version 3.4.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2011
*
* .. Scalar Arguments ..
CHARACTER*3 TYPE
INTEGER IE, IMAT, IOUNIT, M, N, NTESTS
DOUBLE PRECISION THRESH
* ..
* .. Array Arguments ..
INTEGER ISEED( 4 )
DOUBLE PRECISION RESULT( * )
* ..
*
* =====================================================================
*
* .. Local Scalars ..
INTEGER K
* ..
* .. External Subroutines ..
EXTERNAL DLAHD2
* ..
* .. Executable Statements ..
*
IF( M.EQ.N ) THEN
*
* Output for square matrices:
*
DO 10 K = 1, NTESTS
IF( RESULT( K ).GE.THRESH ) THEN
*
* If this is the first test to fail, call DLAHD2
* to print a header to the data file.
*
IF( IE.EQ.0 )
$ CALL DLAHD2( IOUNIT, TYPE )
IE = IE + 1
IF( RESULT( K ).LT.10000.0D0 ) THEN
WRITE( IOUNIT, FMT = 9999 )N, IMAT, ISEED, K,
$ RESULT( K )
9999 FORMAT( ' Matrix order=', I5, ', type=', I2,
$ ', seed=', 4( I4, ',' ), ' result ', I3, ' is',
$ 0P, F8.2 )
ELSE
WRITE( IOUNIT, FMT = 9998 )N, IMAT, ISEED, K,
$ RESULT( K )
9998 FORMAT( ' Matrix order=', I5, ', type=', I2,
$ ', seed=', 4( I4, ',' ), ' result ', I3, ' is',
$ 1P, D10.3 )
END IF
END IF
10 CONTINUE
ELSE
*
* Output for rectangular matrices
*
DO 20 K = 1, NTESTS
IF( RESULT( K ).GE.THRESH ) THEN
*
* If this is the first test to fail, call DLAHD2
* to print a header to the data file.
*
IF( IE.EQ.0 )
$ CALL DLAHD2( IOUNIT, TYPE )
IE = IE + 1
IF( RESULT( K ).LT.10000.0D0 ) THEN
WRITE( IOUNIT, FMT = 9997 )M, N, IMAT, ISEED, K,
$ RESULT( K )
9997 FORMAT( 1X, I5, ' x', I5, ' matrix, type=', I2, ', s',
$ 'eed=', 3( I4, ',' ), I4, ': result ', I3,
$ ' is', 0P, F8.2 )
ELSE
WRITE( IOUNIT, FMT = 9996 )M, N, IMAT, ISEED, K,
$ RESULT( K )
9996 FORMAT( 1X, I5, ' x', I5, ' matrix, type=', I2, ', s',
$ 'eed=', 3( I4, ',' ), I4, ': result ', I3,
$ ' is', 1P, D10.3 )
END IF
END IF
20 CONTINUE
*
END IF
RETURN
*
* End of DLAFTS
*
END
| epl-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.