text stringlengths 1 1.05M |
|---|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 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 "interpreter.h"
#include "primitives/transaction.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "pubkey.h"
#include "script/script.h"
#include "uint256.h"
using namespace std;
typedef vector<unsigned char> valtype;
namespace {
inline bool set_success(ScriptError* ret)
{
if (ret)
*ret = SCRIPT_ERR_OK;
return true;
}
inline bool set_error(ScriptError* ret, const ScriptError serror)
{
if (ret)
*ret = serror;
return false;
}
} // anon namespace
bool CastToBool(const valtype& vch)
{
for (unsigned int i = 0; i < vch.size(); i++)
{
if (vch[i] != 0)
{
// Can be negative zero
if (i == vch.size()-1 && vch[i] == 0x80)
return false;
return true;
}
}
return false;
}
/**
* Script is a stack machine (like Forth) that evaluates a predicate
* returning a bool indicating valid or not. There are no loops.
*/
#define stacktop(i) (stack.at(stack.size()+(i)))
#define altstacktop(i) (altstack.at(altstack.size()+(i)))
static inline void popstack(vector<valtype>& stack)
{
if (stack.empty())
throw runtime_error("popstack(): stack empty");
stack.pop_back();
}
bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
if (vchPubKey.size() < 33) {
// Non-canonical public key: too short
return false;
}
if (vchPubKey[0] == 0x04) {
if (vchPubKey.size() != 65) {
// Non-canonical public key: invalid length for uncompressed key
return false;
}
} else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
if (vchPubKey.size() != 33) {
// Non-canonical public key: invalid length for compressed key
return false;
}
} else {
// Non-canonical public key: neither compressed nor uncompressed
return false;
}
return true;
}
/**
* A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
* Where R and S are not negative (their first byte has its highest bit not set), and not
* excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
* in which case a single 0 byte is necessary and even required).
*
* See https://koobittalk.org/index.php?topic=8392.msg127623#msg127623
*
* This function is consensus-critical since BIP66.
*/
bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
// * total-length: 1-byte length descriptor of everything that follows,
// excluding the sighash byte.
// * R-length: 1-byte length descriptor of the R value that follows.
// * R: arbitrary-length big-endian encoded R value. It must use the shortest
// possible encoding for a positive integers (which means no null bytes at
// the start, except a single one when the next byte has its highest bit set).
// * S-length: 1-byte length descriptor of the S value that follows.
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
// * sighash: 1-byte value indicating what data is hashed (not part of the DER
// signature)
// Minimum and maximum size constraints.
if (sig.size() < 9) return false;
if (sig.size() > 73) return false;
// A signature is of type 0x30 (compound).
if (sig[0] != 0x30) return false;
// Make sure the length covers the entire signature.
if (sig[1] != sig.size() - 3) return false;
// Extract the length of the R element.
unsigned int lenR = sig[3];
// Make sure the length of the S element is still inside the signature.
if (5 + lenR >= sig.size()) return false;
// Extract the length of the S element.
unsigned int lenS = sig[5 + lenR];
// Verify that the length of the signature matches the sum of the length
// of the elements.
if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
// Check whether the R element is an integer.
if (sig[2] != 0x02) return false;
// Zero-length integers are not allowed for R.
if (lenR == 0) return false;
// Negative numbers are not allowed for R.
if (sig[4] & 0x80) return false;
// Null bytes at the start of R are not allowed, unless R would
// otherwise be interpreted as a negative number.
if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
// Check whether the S element is an integer.
if (sig[lenR + 4] != 0x02) return false;
// Zero-length integers are not allowed for S.
if (lenS == 0) return false;
// Negative numbers are not allowed for S.
if (sig[lenR + 6] & 0x80) return false;
// Null bytes at the start of S are not allowed, unless S would otherwise be
// interpreted as a negative number.
if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
return true;
}
bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
if (!IsValidSignatureEncoding(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_DER);
}
std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
if (!CPubKey::CheckLowS(vchSigCopy)) {
return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
}
return true;
}
bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
if (vchSig.size() == 0) {
return false;
}
unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
return false;
return true;
}
bool CheckSignatureEncoding(const vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
// Empty signature. Not strictly DER encoded, but allowed to provide a
// compact way to provide an invalid signature for use with CHECK(MULTI)SIG
if (vchSig.size() == 0) {
return true;
}
if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_DER);
} else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
// serror is set
return false;
} else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
}
return true;
}
bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) {
if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) {
return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
}
return true;
}
bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
if (data.size() == 0) {
// Could have used OP_0.
return opcode == OP_0;
} else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
// Could have used OP_1 .. OP_16.
return opcode == OP_1 + (data[0] - 1);
} else if (data.size() == 1 && data[0] == 0x81) {
// Could have used OP_1NEGATE.
return opcode == OP_1NEGATE;
} else if (data.size() <= 75) {
// Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
return opcode == data.size();
} else if (data.size() <= 255) {
// Could have used OP_PUSHDATA.
return opcode == OP_PUSHDATA1;
} else if (data.size() <= 65535) {
// Could have used OP_PUSHDATA2.
return opcode == OP_PUSHDATA2;
}
return true;
}
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
{
static const CScriptNum bnZero(0);
static const CScriptNum bnOne(1);
static const CScriptNum bnFalse(0);
static const CScriptNum bnTrue(1);
static const valtype vchFalse(0);
static const valtype vchZero(0);
static const valtype vchTrue(1, 1);
CScript::const_iterator pc = script.begin();
CScript::const_iterator pend = script.end();
CScript::const_iterator pbegincodehash = script.begin();
opcodetype opcode;
valtype vchPushValue;
vector<bool> vfExec;
vector<valtype> altstack;
set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
if (script.size() > 10000)
return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
int nOpCount = 0;
bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
try
{
while (pc < pend)
{
bool fExec = !count(vfExec.begin(), vfExec.end(), false);
//
// Read instruction
//
if (!script.GetOp(pc, opcode, vchPushValue))
return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
// Note how OP_RESERVED does not count towards the opcode limit.
if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
return set_error(serror, SCRIPT_ERR_OP_COUNT);
if (opcode == OP_CAT ||
opcode == OP_SUBSTR ||
opcode == OP_LEFT ||
opcode == OP_RIGHT ||
opcode == OP_INVERT ||
opcode == OP_AND ||
opcode == OP_OR ||
opcode == OP_XOR ||
opcode == OP_2MUL ||
opcode == OP_2DIV ||
opcode == OP_MUL ||
opcode == OP_DIV ||
opcode == OP_MOD ||
opcode == OP_LSHIFT ||
opcode == OP_RSHIFT)
return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
return set_error(serror, SCRIPT_ERR_MINIMALDATA);
}
stack.push_back(vchPushValue);
} else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
switch (opcode)
{
//
// Push value
//
case OP_1NEGATE:
case OP_1:
case OP_2:
case OP_3:
case OP_4:
case OP_5:
case OP_6:
case OP_7:
case OP_8:
case OP_9:
case OP_10:
case OP_11:
case OP_12:
case OP_13:
case OP_14:
case OP_15:
case OP_16:
{
// ( -- value)
CScriptNum bn((int)opcode - (int)(OP_1 - 1));
stack.push_back(bn.getvch());
// The result of these opcodes should always be the minimal way to push the data
// they push, so no need for a CheckMinimalPush here.
}
break;
//
// Control
//
case OP_NOP:
break;
case OP_CHECKLOCKTIMEVERIFY:
{
if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
// not enabled; treat as a NOP2
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// Note that elsewhere numeric opcodes are limited to
// operands in the range -2**31+1 to 2**31-1, however it is
// legal for opcodes to produce results exceeding that
// range. This limitation is implemented by CScriptNum's
// default 4-byte limit.
//
// If we kept to that limit we'd have a year 2038 problem,
// even though the nLockTime field in transactions
// themselves is uint32 which only becomes meaningless
// after the year 2106.
//
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums, which are good until 2**39-1, well
// beyond the 2**32-1 limit of the nLockTime field itself.
const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKLOCKTIMEVERIFY.
if (nLockTime < 0)
return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
// Actually compare the specified lock time with the transaction.
if (!checker.CheckLockTime(nLockTime))
return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
break;
}
case OP_CHECKSEQUENCEVERIFY:
{
if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
// not enabled; treat as a NOP3
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// nSequence, like nLockTime, is a 32-bit unsigned integer
// field. See the comment in CHECKLOCKTIMEVERIFY regarding
// 5-byte numeric operands.
const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKSEQUENCEVERIFY.
if (nSequence < 0)
return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
// To provide for future soft-fork extensibility, if the
// operand has the disabled lock-time flag set,
// CHECKSEQUENCEVERIFY behaves as a NOP.
if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
break;
// Compare the specified sequence number with the input.
if (!checker.CheckSequence(nSequence))
return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
break;
}
case OP_NOP1: case OP_NOP4: case OP_NOP5:
case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
{
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
case OP_IF:
case OP_NOTIF:
{
// <expression> if [statements] [else [statements]] endif
bool fValue = false;
if (fExec)
{
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
valtype& vch = stacktop(-1);
fValue = CastToBool(vch);
if (opcode == OP_NOTIF)
fValue = !fValue;
popstack(stack);
}
vfExec.push_back(fValue);
}
break;
case OP_ELSE:
{
if (vfExec.empty())
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
vfExec.back() = !vfExec.back();
}
break;
case OP_ENDIF:
{
if (vfExec.empty())
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
vfExec.pop_back();
}
break;
case OP_VERIFY:
{
// (true -- ) or
// (false -- false) and return
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
bool fValue = CastToBool(stacktop(-1));
if (fValue)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_VERIFY);
}
break;
case OP_RETURN:
{
return set_error(serror, SCRIPT_ERR_OP_RETURN);
}
break;
//
// Stack ops
//
case OP_TOALTSTACK:
{
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
altstack.push_back(stacktop(-1));
popstack(stack);
}
break;
case OP_FROMALTSTACK:
{
if (altstack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
stack.push_back(altstacktop(-1));
popstack(altstack);
}
break;
case OP_2DROP:
{
// (x1 x2 -- )
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
popstack(stack);
popstack(stack);
}
break;
case OP_2DUP:
{
// (x1 x2 -- x1 x2 x1 x2)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-2);
valtype vch2 = stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_3DUP:
{
// (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
if (stack.size() < 3)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-3);
valtype vch2 = stacktop(-2);
valtype vch3 = stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
stack.push_back(vch3);
}
break;
case OP_2OVER:
{
// (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
if (stack.size() < 4)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-4);
valtype vch2 = stacktop(-3);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_2ROT:
{
// (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
if (stack.size() < 6)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch1 = stacktop(-6);
valtype vch2 = stacktop(-5);
stack.erase(stack.end()-6, stack.end()-4);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_2SWAP:
{
// (x1 x2 x3 x4 -- x3 x4 x1 x2)
if (stack.size() < 4)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
swap(stacktop(-4), stacktop(-2));
swap(stacktop(-3), stacktop(-1));
}
break;
case OP_IFDUP:
{
// (x - 0 | x x)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-1);
if (CastToBool(vch))
stack.push_back(vch);
}
break;
case OP_DEPTH:
{
// -- stacksize
CScriptNum bn(stack.size());
stack.push_back(bn.getvch());
}
break;
case OP_DROP:
{
// (x -- )
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
popstack(stack);
}
break;
case OP_DUP:
{
// (x -- x x)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-1);
stack.push_back(vch);
}
break;
case OP_NIP:
{
// (x1 x2 -- x2)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
stack.erase(stack.end() - 2);
}
break;
case OP_OVER:
{
// (x1 x2 -- x1 x2 x1)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-2);
stack.push_back(vch);
}
break;
case OP_PICK:
case OP_ROLL:
{
// (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
// (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
popstack(stack);
if (n < 0 || n >= (int)stack.size())
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-n-1);
if (opcode == OP_ROLL)
stack.erase(stack.end()-n-1);
stack.push_back(vch);
}
break;
case OP_ROT:
{
// (x1 x2 x3 -- x2 x3 x1)
// x2 x1 x3 after first swap
// x2 x3 x1 after second swap
if (stack.size() < 3)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
swap(stacktop(-3), stacktop(-2));
swap(stacktop(-2), stacktop(-1));
}
break;
case OP_SWAP:
{
// (x1 x2 -- x2 x1)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
swap(stacktop(-2), stacktop(-1));
}
break;
case OP_TUCK:
{
// (x1 x2 -- x2 x1 x2)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype vch = stacktop(-1);
stack.insert(stack.end()-2, vch);
}
break;
case OP_SIZE:
{
// (in -- in size)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn(stacktop(-1).size());
stack.push_back(bn.getvch());
}
break;
//
// Bitwise logic
//
case OP_EQUAL:
case OP_EQUALVERIFY:
//case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
{
// (x1 x2 - bool)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype& vch1 = stacktop(-2);
valtype& vch2 = stacktop(-1);
bool fEqual = (vch1 == vch2);
// OP_NOTEQUAL is disabled because it would be too easy to say
// something like n != 1 and have some wiseguy pass in 1 with extra
// zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
//if (opcode == OP_NOTEQUAL)
// fEqual = !fEqual;
popstack(stack);
popstack(stack);
stack.push_back(fEqual ? vchTrue : vchFalse);
if (opcode == OP_EQUALVERIFY)
{
if (fEqual)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
}
}
break;
//
// Numeric
//
case OP_1ADD:
case OP_1SUB:
case OP_NEGATE:
case OP_ABS:
case OP_NOT:
case OP_0NOTEQUAL:
{
// (in -- out)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn(stacktop(-1), fRequireMinimal);
switch (opcode)
{
case OP_1ADD: bn += bnOne; break;
case OP_1SUB: bn -= bnOne; break;
case OP_NEGATE: bn = -bn; break;
case OP_ABS: if (bn < bnZero) bn = -bn; break;
case OP_NOT: bn = (bn == bnZero); break;
case OP_0NOTEQUAL: bn = (bn != bnZero); break;
default: assert(!"invalid opcode"); break;
}
popstack(stack);
stack.push_back(bn.getvch());
}
break;
case OP_ADD:
case OP_SUB:
case OP_BOOLAND:
case OP_BOOLOR:
case OP_NUMEQUAL:
case OP_NUMEQUALVERIFY:
case OP_NUMNOTEQUAL:
case OP_LESSTHAN:
case OP_GREATERTHAN:
case OP_LESSTHANOREQUAL:
case OP_GREATERTHANOREQUAL:
case OP_MIN:
case OP_MAX:
{
// (x1 x2 -- out)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn1(stacktop(-2), fRequireMinimal);
CScriptNum bn2(stacktop(-1), fRequireMinimal);
CScriptNum bn(0);
switch (opcode)
{
case OP_ADD:
bn = bn1 + bn2;
break;
case OP_SUB:
bn = bn1 - bn2;
break;
case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
case OP_NUMEQUAL: bn = (bn1 == bn2); break;
case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
case OP_LESSTHAN: bn = (bn1 < bn2); break;
case OP_GREATERTHAN: bn = (bn1 > bn2); break;
case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
default: assert(!"invalid opcode"); break;
}
popstack(stack);
popstack(stack);
stack.push_back(bn.getvch());
if (opcode == OP_NUMEQUALVERIFY)
{
if (CastToBool(stacktop(-1)))
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
}
}
break;
case OP_WITHIN:
{
// (x min max -- out)
if (stack.size() < 3)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
CScriptNum bn1(stacktop(-3), fRequireMinimal);
CScriptNum bn2(stacktop(-2), fRequireMinimal);
CScriptNum bn3(stacktop(-1), fRequireMinimal);
bool fValue = (bn2 <= bn1 && bn1 < bn3);
popstack(stack);
popstack(stack);
popstack(stack);
stack.push_back(fValue ? vchTrue : vchFalse);
}
break;
//
// Crypto
//
case OP_RIPEMD160:
case OP_SHA1:
case OP_SHA256:
case OP_HASH160:
case OP_HASH256:
{
// (in -- hash)
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype& vch = stacktop(-1);
valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
if (opcode == OP_RIPEMD160)
CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_SHA1)
CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_SHA256)
CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_HASH160)
CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
else if (opcode == OP_HASH256)
CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
popstack(stack);
stack.push_back(vchHash);
}
break;
case OP_CODESEPARATOR:
{
// Hash starts after the code separator
pbegincodehash = pc;
}
break;
case OP_CHECKSIG:
case OP_CHECKSIGVERIFY:
{
// (sig pubkey -- bool)
if (stack.size() < 2)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
valtype& vchSig = stacktop(-2);
valtype& vchPubKey = stacktop(-1);
// Subset of script starting at the most recent codeseparator
CScript scriptCode(pbegincodehash, pend);
// Drop the signature, since there's no way for a signature to sign itself
scriptCode.FindAndDelete(CScript(vchSig));
if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
//serror is set
return false;
}
bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode);
popstack(stack);
popstack(stack);
stack.push_back(fSuccess ? vchTrue : vchFalse);
if (opcode == OP_CHECKSIGVERIFY)
{
if (fSuccess)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
}
}
break;
case OP_CHECKMULTISIG:
case OP_CHECKMULTISIGVERIFY:
{
// ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
int i = 1;
if ((int)stack.size() < i)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
nOpCount += nKeysCount;
if (nOpCount > MAX_OPS_PER_SCRIPT)
return set_error(serror, SCRIPT_ERR_OP_COUNT);
int ikey = ++i;
i += nKeysCount;
if ((int)stack.size() < i)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
if (nSigsCount < 0 || nSigsCount > nKeysCount)
return set_error(serror, SCRIPT_ERR_SIG_COUNT);
int isig = ++i;
i += nSigsCount;
if ((int)stack.size() < i)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// Subset of script starting at the most recent codeseparator
CScript scriptCode(pbegincodehash, pend);
// Drop the signatures, since there's no way for a signature to sign itself
for (int k = 0; k < nSigsCount; k++)
{
valtype& vchSig = stacktop(-isig-k);
scriptCode.FindAndDelete(CScript(vchSig));
}
bool fSuccess = true;
while (fSuccess && nSigsCount > 0)
{
valtype& vchSig = stacktop(-isig);
valtype& vchPubKey = stacktop(-ikey);
// Note how this makes the exact order of pubkey/signature evaluation
// distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
// See the script_(in)valid tests for details.
if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
// serror is set
return false;
}
// Check signature
bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode);
if (fOk) {
isig++;
nSigsCount--;
}
ikey++;
nKeysCount--;
// If there are more signatures left than keys left,
// then too many signatures have failed. Exit early,
// without checking any further signatures.
if (nSigsCount > nKeysCount)
fSuccess = false;
}
// Clean up stack of actual arguments
while (i-- > 1)
popstack(stack);
// A bug causes CHECKMULTISIG to consume one extra argument
// whose contents were not checked in any way.
//
// Unfortunately this is a potential source of mutability,
// so optionally verify it is exactly equal to zero prior
// to removing it from the stack.
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
popstack(stack);
stack.push_back(fSuccess ? vchTrue : vchFalse);
if (opcode == OP_CHECKMULTISIGVERIFY)
{
if (fSuccess)
popstack(stack);
else
return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
}
}
break;
default:
return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
}
// Size limits
if (stack.size() + altstack.size() > 1000)
return set_error(serror, SCRIPT_ERR_STACK_SIZE);
}
}
catch (...)
{
return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
}
if (!vfExec.empty())
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
return set_success(serror);
}
namespace {
/**
* Wrapper that serializes like CTransaction, but with the modifications
* required for the signature hash done in-place
*/
class CTransactionSignatureSerializer {
private:
const CTransaction &txTo; //! reference to the spending transaction (the one being serialized)
const CScript &scriptCode; //! output script being consumed
const unsigned int nIn; //! input index of txTo being signed
const bool fAnyoneCanPay; //! whether the hashtype has the SIGHASH_ANYONECANPAY flag set
const bool fHashSingle; //! whether the hashtype is SIGHASH_SINGLE
const bool fHashNone; //! whether the hashtype is SIGHASH_NONE
public:
CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
/** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
template<typename S>
void SerializeScriptCode(S &s, int nType, int nVersion) const {
CScript::const_iterator it = scriptCode.begin();
CScript::const_iterator itBegin = it;
opcodetype opcode;
unsigned int nCodeSeparators = 0;
while (scriptCode.GetOp(it, opcode)) {
if (opcode == OP_CODESEPARATOR)
nCodeSeparators++;
}
::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
it = itBegin;
while (scriptCode.GetOp(it, opcode)) {
if (opcode == OP_CODESEPARATOR) {
s.write((char*)&itBegin[0], it-itBegin-1);
itBegin = it;
}
}
if (itBegin != scriptCode.end())
s.write((char*)&itBegin[0], it-itBegin);
}
/** Serialize an input of txTo */
template<typename S>
void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
// In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
if (fAnyoneCanPay)
nInput = nIn;
// Serialize the prevout
::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
// Serialize the script
if (nInput != nIn)
// Blank out other inputs' signatures
::Serialize(s, CScriptBase(), nType, nVersion);
else
SerializeScriptCode(s, nType, nVersion);
// Serialize the nSequence
if (nInput != nIn && (fHashSingle || fHashNone))
// let the others update at will
::Serialize(s, (int)0, nType, nVersion);
else
::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
}
/** Serialize an output of txTo */
template<typename S>
void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
if (fHashSingle && nOutput != nIn)
// Do not lock-in the txout payee at other indices as txin
::Serialize(s, CTxOut(), nType, nVersion);
else
::Serialize(s, txTo.vout[nOutput], nType, nVersion);
}
/** Serialize txTo */
template<typename S>
void Serialize(S &s, int nType, int nVersion) const {
// Serialize nVersion
::Serialize(s, txTo.nVersion, nType, nVersion);
// Serialize vin
unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
::WriteCompactSize(s, nInputs);
for (unsigned int nInput = 0; nInput < nInputs; nInput++)
SerializeInput(s, nInput, nType, nVersion);
// Serialize vout
unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
::WriteCompactSize(s, nOutputs);
for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
SerializeOutput(s, nOutput, nType, nVersion);
// Serialize nLockTime
::Serialize(s, txTo.nLockTime, nType, nVersion);
}
};
} // anon namespace
uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
if (nIn >= txTo.vin.size()) {
// nIn out of range
return one;
}
// Check for invalid use of SIGHASH_SINGLE
if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
if (nIn >= txTo.vout.size()) {
// nOut out of range
return one;
}
}
// Wrapper to serialize only the necessary parts of the transaction being signed
CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
{
return pubkey.Verify(sighash, vchSig);
}
bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode) const
{
CPubKey pubkey(vchPubKey);
if (!pubkey.IsValid())
return false;
// Hash type is one byte tacked on to the end of the signature
vector<unsigned char> vchSig(vchSigIn);
if (vchSig.empty())
return false;
int nHashType = vchSig.back();
vchSig.pop_back();
uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType);
if (!VerifySignature(vchSig, pubkey, sighash))
return false;
return true;
}
bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
{
// There are two kinds of nLockTime: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nLockTime < LOCKTIME_THRESHOLD.
//
// We want to compare apples to apples, so fail the script
// unless the type of nLockTime being tested is the same as
// the nLockTime in the transaction.
if (!(
(txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
(txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
))
return false;
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nLockTime > (int64_t)txTo->nLockTime)
return false;
// Finally the nLockTime feature can be disabled and thus
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
// finalized by setting nSequence to maxint. The
// transaction would be allowed into the blockchain, making
// the opcode ineffective.
//
// Testing if this vin is not final is sufficient to
// prevent this condition. Alternatively we could test all
// inputs, but testing just this input minimizes the data
// required to prove correct CHECKLOCKTIMEVERIFY execution.
if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
return false;
return true;
}
bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
{
// Relative lock times are supported by comparing the passed
// in operand to the sequence number of the input.
const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
// Fail if the transaction's version number is not set high
// enough to trigger BIP 68 rules.
if (static_cast<uint32_t>(txTo->nVersion) < 2)
return false;
// Sequence numbers with their most significant bit set are not
// consensus constrained. Testing that the transaction's sequence
// number do not have this bit set prevents using this property
// to get around a CHECKSEQUENCEVERIFY check.
if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
return false;
// Mask off any bits that do not have consensus-enforced meaning
// before doing the integer comparisons
const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
// There are two kinds of nSequence: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
//
// We want to compare apples to apples, so fail the script
// unless the type of nSequenceMasked being tested is the same as
// the nSequenceMasked in the transaction.
if (!(
(txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
(txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
)) {
return false;
}
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nSequenceMasked > txToSequenceMasked)
return false;
return true;
}
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
{
set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
}
vector<vector<unsigned char> > stack, stackCopy;
if (!EvalScript(stack, scriptSig, flags, checker, serror))
// serror is set
return false;
if (flags & SCRIPT_VERIFY_P2SH)
stackCopy = stack;
if (!EvalScript(stack, scriptPubKey, flags, checker, serror))
// serror is set
return false;
if (stack.empty())
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
if (CastToBool(stack.back()) == false)
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
// Additional validation for spend-to-script-hash transactions:
if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
{
// scriptSig must be literals-only or validation fails
if (!scriptSig.IsPushOnly())
return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
// Restore stack.
swap(stack, stackCopy);
// stack cannot be empty here, because if it was the
// P2SH HASH <> EQUAL scriptPubKey would be evaluated with
// an empty stack and the EvalScript above would return false.
assert(!stack.empty());
const valtype& pubKeySerialized = stack.back();
CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
popstack(stack);
if (!EvalScript(stack, pubKey2, flags, checker, serror))
// serror is set
return false;
if (stack.empty())
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
if (!CastToBool(stack.back()))
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
}
// The CLEANSTACK check is only performed after potential P2SH evaluation,
// as the non-P2SH evaluation of a P2SH script will obviously not result in
// a clean stack (the P2SH inputs remain).
if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
// Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
// would be possible, which is not a softfork (and P2SH should be one).
assert((flags & SCRIPT_VERIFY_P2SH) != 0);
if (stack.size() != 1) {
return set_error(serror, SCRIPT_ERR_CLEANSTACK);
}
}
return set_success(serror);
}
|
; A142376: Primes congruent to 25 mod 47.
; Submitted by Jon Maiga
; 307,401,683,1153,1811,1999,2281,2657,2939,3221,3691,4349,5101,5477,6229,6323,6793,7451,7639,8297,8861,9049,9613,10177,10271,10459,11117,11399,11587,11681,12433,12527,12809,14407,14783,15629,15817,16193,16381,17321,17509,17791,18637,18731,18919,19013,19483,19577,20047,20611,21269,21739,22303,22397,22679,22961,23431,24371,24841,25969,26251,26627,27191,27943,28319,28789,29917,30011,30293,30763,31139,31327,31891,32173,32831,33113,33301,34147,34429,35839,35933,36497,36779,37061,37813,37907,38189
mov $2,$0
add $2,6
pow $2,2
lpb $2
mov $3,$4
add $3,24
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
mov $1,$0
max $1,0
cmp $1,$0
mul $2,$1
sub $2,1
add $4,47
lpe
mov $0,$4
add $0,25
|
; A121929: a(n) = ceiling(n*(e^Pi + Pi^e)).
; 0,46,92,137,183,228,274,320,365,411,456,502,548,593,639,684,730,776,821,867,912,958,1004,1049,1095,1140,1186,1232,1277,1323,1368,1414,1460,1505,1551,1596,1642,1688,1733,1779,1824,1870,1916,1961,2007,2052,2098,2144,2189,2235,2280,2326,2372,2417,2463,2508,2554,2600,2645,2691,2736,2782,2828,2873,2919,2964,3010,3056,3101,3147,3192,3238,3284,3329,3375,3420,3466,3512,3557,3603,3648,3694,3740,3785,3831,3876,3922,3968,4013,4059,4104,4150,4196,4241,4287,4332,4378,4424,4469,4515,4560,4606,4652,4697,4743,4788,4834,4880,4925,4971,5016,5062,5108,5153,5199,5244,5290,5336,5381,5427,5472,5518,5564,5609,5655,5700,5746,5792,5837,5883,5928,5974,6020,6065,6111,6156,6202,6248,6293,6339,6384,6430,6476,6521,6567,6612,6658,6704,6749,6795,6840,6886,6932,6977,7023,7068,7114,7160,7205,7251,7296,7342,7388,7433,7479,7524,7570,7616,7661,7707,7752,7798,7844,7889,7935,7980,8026,8072,8117,8163,8208,8254,8300,8345,8391,8436,8482,8528,8573,8619,8664,8710,8756,8801,8847,8892,8938,8984,9029,9075,9120,9166,9212,9257,9303,9348,9394,9440,9485,9531,9576,9622,9668,9713,9759,9804,9850,9896,9941,9987,10032,10078,10124,10169,10215,10260,10306,10352,10397,10443,10488,10534,10580,10625,10671,10716,10762,10808,10853,10899,10944,10990,11036,11081,11127,11172,11218,11264,11309,11355
mov $2,$0
mul $0,8
mov $1,4
add $1,$0
div $1,5
mov $3,$2
mul $3,44
add $1,$3
|
/*
* Copyright 2013 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkColorPriv.h"
#include "SkBlurImage_opts.h"
#include "SkRect.h"
#include <arm_neon.h>
namespace {
enum BlurDirection {
kX, kY
};
/**
* Helper function to load 2 pixels from diffent rows to a 8x8 NEON register
* and also pre-load pixels for future read
*/
template<BlurDirection srcDirection>
inline uint8x8_t load_2_pixels(const SkPMColor* src, int srcStride) {
if (srcDirection == kX) {
uint32x2_t temp = vdup_n_u32(0);
// 10% faster by adding these 2 prefetches
SK_PREFETCH(src + 16);
SK_PREFETCH(src + srcStride + 16);
return vreinterpret_u8_u32(vld1_lane_u32(src + srcStride, vld1_lane_u32(src, temp, 0), 1));
} else {
return vld1_u8((uint8_t*)src);
}
}
/**
* Helper function to store the low 8-bits from a 16x8 NEON register to 2 rows
*/
template<BlurDirection dstDirection>
inline void store_2_pixels(uint16x8_t result16x8, SkPMColor* dst, int dstStride) {
if (dstDirection == kX) {
uint32x2_t temp = vreinterpret_u32_u8(vmovn_u16(result16x8));
vst1_lane_u32(dst, temp, 0);
vst1_lane_u32(dst + dstStride, temp, 1);
} else {
uint8x8_t temp = vmovn_u16(result16x8);
vst1_u8((uint8_t*)dst, temp);
}
}
/**
* fast path for kernel size less than 128
*/
template<BlurDirection srcDirection, BlurDirection dstDirection>
void SkDoubleRowBoxBlur_NEON(const SkPMColor** src, int srcStride, SkPMColor** dst, int kernelSize,
int leftOffset, int rightOffset, int width, int* height)
{
const int rightBorder = SkMin32(rightOffset + 1, width);
const int srcStrideX = srcDirection == kX ? 1 : srcStride;
const int dstStrideX = dstDirection == kX ? 1 : *height;
const int srcStrideY = srcDirection == kX ? srcStride : 1;
const int dstStrideY = dstDirection == kX ? width : 1;
const uint16x8_t scale = vdupq_n_u16((1 << 15) / kernelSize);
for (; *height >= 2; *height -= 2) {
uint16x8_t sum = vdupq_n_u16(0);
const SkPMColor* p = *src;
for (int i = 0; i < rightBorder; i++) {
sum = vaddw_u8(sum,
load_2_pixels<srcDirection>(p, srcStride));
p += srcStrideX;
}
const SkPMColor* sptr = *src;
SkPMColor* dptr = *dst;
for (int x = 0; x < width; x++) {
// val = (sum * scale * 2 + 0x8000) >> 16
uint16x8_t resultPixels = vreinterpretq_u16_s16(vqrdmulhq_s16(
vreinterpretq_s16_u16(sum), vreinterpretq_s16_u16(scale)));
store_2_pixels<dstDirection>(resultPixels, dptr, width);
if (x >= leftOffset) {
sum = vsubw_u8(sum,
load_2_pixels<srcDirection>(sptr - leftOffset * srcStrideX, srcStride));
}
if (x + rightOffset + 1 < width) {
sum = vaddw_u8(sum,
load_2_pixels<srcDirection>(sptr + (rightOffset + 1) * srcStrideX, srcStride));
}
sptr += srcStrideX;
dptr += dstStrideX;
}
*src += srcStrideY * 2;
*dst += dstStrideY * 2;
}
}
/**
* Helper function to spread the components of a 32-bit integer into the
* lower 8 bits of each 16-bit element of a NEON register.
*/
static inline uint16x4_t expand(uint32_t a) {
// ( ARGB ) -> ( ARGB ARGB ) -> ( A R G B A R G B )
uint8x8_t v8 = vreinterpret_u8_u32(vdup_n_u32(a));
// ( A R G B A R G B ) -> ( 0A 0R 0G 0B 0A 0R 0G 0B ) -> ( 0A 0R 0G 0B )
return vget_low_u16(vmovl_u8(v8));
}
template<BlurDirection srcDirection, BlurDirection dstDirection>
void SkBoxBlur_NEON(const SkPMColor* src, int srcStride, SkPMColor* dst, int kernelSize,
int leftOffset, int rightOffset, int width, int height)
{
const int rightBorder = SkMin32(rightOffset + 1, width);
const int srcStrideX = srcDirection == kX ? 1 : srcStride;
const int dstStrideX = dstDirection == kX ? 1 : height;
const int srcStrideY = srcDirection == kX ? srcStride : 1;
const int dstStrideY = dstDirection == kX ? width : 1;
const uint32x4_t scale = vdupq_n_u32((1 << 24) / kernelSize);
const uint32x4_t half = vdupq_n_u32(1 << 23);
if (kernelSize < 128)
{
SkDoubleRowBoxBlur_NEON<srcDirection, dstDirection>(&src, srcStride, &dst, kernelSize,
leftOffset, rightOffset, width, &height);
}
for (; height > 0; height--) {
uint32x4_t sum = vdupq_n_u32(0);
const SkPMColor* p = src;
for (int i = 0; i < rightBorder; ++i) {
sum = vaddw_u16(sum, expand(*p));
p += srcStrideX;
}
const SkPMColor* sptr = src;
SkPMColor* dptr = dst;
for (int x = 0; x < width; ++x) {
// ( half+sumA*scale half+sumR*scale half+sumG*scale half+sumB*scale )
uint32x4_t result = vmlaq_u32(half, sum, scale);
// Saturated conversion to 16-bit.
// ( AAAA RRRR GGGG BBBB ) -> ( 0A 0R 0G 0B )
uint16x4_t result16 = vqshrn_n_u32(result, 16);
// Saturated conversion to 8-bit.
// ( 0A 0R 0G 0B ) -> ( 0A 0R 0G 0B 0A 0R 0G 0B ) -> ( A R G B A R G B )
uint8x8_t result8 = vqshrn_n_u16(vcombine_u16(result16, result16), 8);
// ( A R G B A R G B ) -> ( ARGB ARGB ) -> ( ARGB )
// Store low 32 bits to destination.
vst1_lane_u32(dptr, vreinterpret_u32_u8(result8), 0);
if (x >= leftOffset) {
const SkPMColor* l = sptr - leftOffset * srcStrideX;
sum = vsubw_u16(sum, expand(*l));
}
if (x + rightOffset + 1 < width) {
const SkPMColor* r = sptr + (rightOffset + 1) * srcStrideX;
sum = vaddw_u16(sum, expand(*r));
}
sptr += srcStrideX;
if (srcDirection == kX) {
SK_PREFETCH(sptr + (rightOffset + 16) * srcStrideX);
}
dptr += dstStrideX;
}
src += srcStrideY;
dst += dstStrideY;
}
}
} // namespace
bool SkBoxBlurGetPlatformProcs_NEON(SkBoxBlurProc* boxBlurX,
SkBoxBlurProc* boxBlurY,
SkBoxBlurProc* boxBlurXY,
SkBoxBlurProc* boxBlurYX) {
*boxBlurX = SkBoxBlur_NEON<kX, kX>;
*boxBlurY = SkBoxBlur_NEON<kY, kY>;
*boxBlurXY = SkBoxBlur_NEON<kX, kY>;
*boxBlurYX = SkBoxBlur_NEON<kY, kX>;
return true;
}
|
CALL LABEL3 ; LABEL3 - yes
LD A,(LABEL1) ; LABEL1 - yes
jr 1B ;; error
jr 1F
jr 4F
1
jr 1B
jr 1F ;; error
IFUSED LABEL1
LABEL1:
DB '1'
ENDIF
jr 2F
jr 4F
2
jr 1B
jr 2B
IFUSED LABEL2
LABEL2:
DB '2'
ENDIF
jr 3F
jr 4F
3
jr 1B
jr 3B
IFUSED LABEL3
LABEL3:
DB '3'
ENDIF
jr 4B ;; error
jr 4F
4
jr 1B
jr 4B
jr 4F
IFUSED LABEL4
LABEL4:
DB '4'
ENDIF
jr 4B
jr 4F
4 ;; double "4" local label (according to docs this should work)
jr 1B
jr 4B
jr 4F ;; error
LD A,LABEL2 ; LABEL2 - yes
call LABEL1
call LABEL2
call LABEL3
; call LABEL4 - stay unused
RET
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright(c) 2011-2015 Intel Corporation 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 Intel Corporation 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; gf_vect_mad_sse(len, vec, vec_i, mul_array, src, dest);
;;;
%include "reg_sizes.asm"
%ifidn __OUTPUT_FORMAT__, win64
%define arg0 rcx
%define arg0.w ecx
%define arg1 rdx
%define arg2 r8
%define arg3 r9
%define arg4 r12
%define arg5 r15
%define tmp r11
%define return rax
%define return.w eax
%define PS 8
%define stack_size 16*3 + 3*8
%define arg(x) [rsp + stack_size + PS + PS*x]
%define func(x) proc_frame x
%macro FUNC_SAVE 0
sub rsp, stack_size
movdqa [rsp+16*0],xmm6
movdqa [rsp+16*1],xmm7
movdqa [rsp+16*2],xmm8
save_reg r12, 3*16 + 0*8
save_reg r15, 3*16 + 1*8
end_prolog
mov arg4, arg(4)
mov arg5, arg(5)
%endmacro
%macro FUNC_RESTORE 0
movdqa xmm6, [rsp+16*0]
movdqa xmm7, [rsp+16*1]
movdqa xmm8, [rsp+16*2]
mov r12, [rsp + 3*16 + 0*8]
mov r15, [rsp + 3*16 + 1*8]
add rsp, stack_size
%endmacro
%elifidn __OUTPUT_FORMAT__, elf64
%define arg0 rdi
%define arg0.w edi
%define arg1 rsi
%define arg2 rdx
%define arg3 rcx
%define arg4 r8
%define arg5 r9
%define tmp r11
%define return rax
%define return.w eax
%define func(x) x:
%define FUNC_SAVE
%define FUNC_RESTORE
%endif
;;; gf_vect_mad_sse(len, vec, vec_i, mul_array, src, dest)
%define len arg0
%define len.w arg0.w
%define vec arg1
%define vec_i arg2
%define mul_array arg3
%define src arg4
%define dest arg5
%define pos return
%define pos.w return.w
%ifndef EC_ALIGNED_ADDR
;;; Use Un-aligned load/store
%define XLDR movdqu
%define XSTR movdqu
%else
;;; Use Non-temporal load/stor
%ifdef NO_NT_LDST
%define XLDR movdqa
%define XSTR movdqa
%else
%define XLDR movntdqa
%define XSTR movntdq
%endif
%endif
default rel
[bits 64]
section .text
%define xmask0f xmm8
%define xgft_lo xmm7
%define xgft_hi xmm6
%define x0 xmm0
%define xtmpa xmm1
%define xtmph xmm2
%define xtmpl xmm3
%define xd xmm4
%define xtmpd xmm5
align 16
global gf_vect_mad_sse:ISAL_SYM_TYPE_FUNCTION
func(gf_vect_mad_sse)
FUNC_SAVE
sub len, 16
jl .return_fail
xor pos, pos
movdqa xmask0f, [mask0f] ;Load mask of lower nibble in each byte
sal vec_i, 5 ;Multiply by 32
movdqu xgft_lo, [vec_i+mul_array] ;Load array Cx{00}, Cx{01}, Cx{02}, ...
movdqu xgft_hi, [vec_i+mul_array+16] ; " Cx{00}, Cx{10}, Cx{20}, ... , Cx{f0}
XLDR xtmpd, [dest+len] ;backup the last 16 bytes in dest
.loop16:
XLDR xd, [dest+pos] ;Get next dest vector
.loop16_overlap:
XLDR x0, [src+pos] ;Get next source vector
movdqa xtmph, xgft_hi ;Reload const array registers
movdqa xtmpl, xgft_lo
movdqa xtmpa, x0 ;Keep unshifted copy of src
psraw x0, 4 ;Shift to put high nibble into bits 4-0
pand x0, xmask0f ;Mask high src nibble in bits 4-0
pand xtmpa, xmask0f ;Mask low src nibble in bits 4-0
pshufb xtmph, x0 ;Lookup mul table of high nibble
pshufb xtmpl, xtmpa ;Lookup mul table of low nibble
pxor xtmph, xtmpl ;GF add high and low partials
pxor xd, xtmph
XSTR [dest+pos], xd ;Store result
add pos, 16 ;Loop on 16 bytes at a time
cmp pos, len
jle .loop16
lea tmp, [len + 16]
cmp pos, tmp
je .return_pass
;; Tail len
mov pos, len ;Overlapped offset length-16
movdqa xd, xtmpd ;Restore xd
jmp .loop16_overlap ;Do one more overlap pass
.return_pass:
mov return, 0
FUNC_RESTORE
ret
.return_fail:
mov return, 1
FUNC_RESTORE
ret
endproc_frame
section .data
align 16
mask0f: dq 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f
;;; func core, ver, snum
slversion gf_vect_mad_sse, 00, 01, 0200
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Number Guessing Game ;;;
;;; -------------------- ;;;
;;; ;;;
;;; Members: ;;;
;;; - Jonathan Trousdale ;;;
;;; - Tyler Wray ;;;
;;; - Bekah Williams ;;;
;;; - Justin Ward ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
;
; This is a number guessing game that uses a binary search.
; The user thinks of a number in their head, and then
; our program tries to guess their number in the least amount
; of steps.
;
; ****** Register Map ******
; note that this is just a general key to use, variables are stored
; R0 = Input/Output
; R1 = High (100, Can't ever change)
; R2 = Low (0, Can't ever change)
; R3 = Guess
; R4 = Decide
; R5 = High + Low
; R6 = 2
; counter placed in R3
;
.ORIG x3000
;
; Clear all registers
;
CLEAR AND R0,R0,#0
AND R1,R1,#0
AND R2,R2,#0
AND R3,R3,#0
AND R4,R4,#0
AND R5,R5,#0
AND R6,R6,#0
AND R7,R7,#0
;
; tell user about the game
;
LEA R0,EXPLANATION ; load string
PUTS ; output string
; Entry point for the program, Sets R1 = 100 and R2 = 0
;
LD R1,HUNDRED ; set R1 to 100 for first run through
ST R1,HIGH ; store 100 into variable high
LD R2,ZERO ; set R2 to 0 for first run through
ST R2,LOW ; store 0 into variable low
LD R4,NEGONE ; load -1 into R4
ST R4,DECIDE ; store -1 into variable decide
;
; Implementation of the binary search algorithm
;
START LD R6,TWO ; load 2 into R6 - for division puposes
LD R1,HIGH ; load high into R1
LD R2,LOW ; load low into R2
ADD R5,R1,R2 ; add the high and low and save to R5
;
DIVISION ADD R5,R5,R6 ; subtract 2 from the sum of high and low
ADD R3,R3,#1 ; increment R7 (new guess) each implementation
ST R3,GUESS ; store the new number for guess into variable GUESS
ADD R5,R5,#0 ; test for Branch
BRp DIVISION ; if positive repeat subtraction
;
; User Question: Ask the user if the new guess is correct and take input
;
USERQUESTION LEA R0,QUESTIONPRE ; Load 'Pre' Question into R0
PUTS ; Output 'Pre' Question
JSR OUTPUT
LEA R0,QUESTIONPOST ; Load the 'Post' Question
PUTS ; Output the 'Post' Question
GETC ; Get response from console
OUT ; Show the user the number they entered
LD R1,ASCII
ADD R0,R0,R1 ; change from ascii to binary
ST R0,USERINPUT ; save input in variable userinput
;
; check to make sure user entered valid input
;
VALIDINPUT LD R0,USERINPUT
LD R1,TESTLOWER
ADD R0,R0,R1 ; check if less than 0
BRn BADINPUT
LD R0,USERINPUT
LD R1,TESTUPPER
ADD R0,R0,R1 ; check to see if greater than 2
BRp BADINPUT
LD R0,USERINPUT ; load userinput to test
LD R4,DECIDE ; load -1 to R4
ADD R4,R4,R0 ; test R4 by addition to -1 to see if they answered (0,1,2) or (low,correct,high)
BRn TOOLOW ; test for too low
BRp TOOHIGH ; test for too high
BRz CORRECT ; test for correct answer
;
; if too low, change low to guess or R2 = R3
;
TOOLOW LD R3,GUESS ; load GUESS into R3
AND R0, R0, #0 ; Clear R0
LD R1,HIGH ; Load High into R1
NOT R1, R1 ; Negate HIGH
ADD R1, R1, #1 ; Negate HIGH
ADD R0, R1, R2 ; Get difference between HIGH and LOW
ADD R0, R0, #1 ; Add 1 to test
BRz CHEATED ; Branch to Cheated
LD R2,LOW ; load LOW into R2
ADD R2,R3,#0 ; change low value to the previous guess
ST R2,LOW ; store number in R2 in variable LOW
AND R3,R3,#0 ; clear R3 for iteration
AND R5,R5,#0 ; clear R5 for iteration
BRnzp START ; go to start
;
; if too high, change high to guess or R1 = R3
;
TOOHIGH LD R3,GUESS ; load GUESS into R3
AND R0, R0, #0 ; Clear R0
LD R1, HIGH ; Load High into R1
NOT R1, R1 ; Negate HIGH
ADD R1, R1, #1 ; Negate HIGH
ADD R0, R1, R2 ; Get difference between HIGH and LOW
ADD R0, R0, #1 ; Add two to check for cheating
BRz CHEATED ; Branch to Cheated
LD R1,HIGH ; load HIGH into R1
ADD R1,R3,#0 ; change high value to the previous guess
ST R1,HIGH ; store number in R1 in variable HIGH
AND R3,R3,#0 ; clear R3 for iteration
AND R5,R5,#0 ; clear R5 for iteration
BRnzp START ; go to start
;
; Branch here if input is incorrect
;
BADINPUT LEA R0,WRONGINPUT ; Load R0 with wrong input string
PUTS ; Output the Incorrect String
BRnzp USERQUESTION ; loop back to START routine
;
; Outputing an int between 0 & 999
;
; store registries for reloading at end of routine
OUTPUT ST R0,REG0 ; store r0 into reg0 .blkw
ST R1,REG1
ST R2,REG2
ST R3,REG3
ST R4,REG4
ST R5,REG5
ST R6,REG6
ST R7,REG7 ; PC counter to return to
; Set up registries for use
LD R0,GUESS ; Put number into r0
AND R3,R3,#0 ; hundreds
AND R4,R4,#0 ; tens
AND R5,R5,#0 ; ones
AND R6,R6,#0 ; hundreds flag
; Figure out how many 100's and 10's there are, with 1's left over
HUNDS LD R2,NHNDRD ; load #-100 for use (to big)
ADD R0,R0,R2 ; sub 100 to number for test (if there was 100 there)
BRn DONE1 ; branch to done because there is no 100
ADD R3,R3,#1 ; increment r3 (meaning there was 100 there)
BRnzp HUNDS ; hard branch until other branch gets us out
DONE1 LD R2,HNDRD ; load #100 for use
ADD R0,R0,R2 ; add 100 back on (because it turns out there was no hundred there)
TENS LD R2,NTEN ; load #-10 for use (consistancy)
ADD R0,R0,R2 ; sub #10 for test
BRn DONE2 ; branch to done because there is no 10
ADD R4,R4,#1 ; increment tens
BRnzp TENS ; hard branch until other branch gets us out
DONE2 LD R2,TEN ; load #10 for use
ADD R0,R0,R2 ; add 10 back on
ONES ADD R5,R0,#0 ; put whats left in r0 into r5, so we can use r0 for output
; Outputing to the console
LD R1,ASCII2 ; load ascii value for 0 to be used to outputl,m
; hundreds
H AND R0,R0,#0 ; clear r0 for output
ADD R0,R3,#0 ; place hundreds in r0
BRz T ; dont display if it was 0
ADD R0,R0,R1 ; load ascii offeset
OUT ; output to console
ADD R6,R6,#1 ; set flag for use of significant digit
; tens
T AND R0,R0,#0 ; clear r0 for output
ADD R0,R4,#0 ; place tens in r0
BRnp chck
ADD R6,R6,#0 ; update the flag
BRnz O ; if signficant digit flag is not set (meaning no hundreds) then check for zero in tens place
chck ADD R0,R0,R1 ; ascii offset
OUT ; output to console
; ones
O AND R0,R0,#0 ; clear r0 for output
ADD R0,R5,R1 ; place ones in r0, also adding ascii here
OUT ; output to console
LD R0,REG0 ; load registries back in before leaving
LD R1,REG1
LD R2,REG2
LD R3,REG3
LD R4,REG4
LD R5,REG5
LD R6,REG6
LD R7,REG7 ; load back to PC counter to return to if ever changed
RET ; use if used as a function in a program
;
; if correct, output a correct message and end
;
CORRECT LEA R0, FINISH ; load finish string for output
PUTS ; output finish string
JSR OUTPUT
PERIOD .STRINGZ "."
LEA R0,PERIOD
PUTS
HALT
;
CHEATED LEA R0, USERCHEATED ; Output the user cheated string
PUTS
HALT
;
;;;;;;;;;;;;;;;;
; Constants ;
;;;;;;;;;;;;;;;;
;
ANSWER .BLKW 1
USERINPUT .BLKW 1
HIGH .BLKW 1
LOW .BLKW 1
GUESS .BLKW 1
DECIDE .BLKW 1
TWO .FILL #-2
ZERO .FILL #0
HUNDRED .FILL #100
NEGONE .FILL #-1
ASCII .FILL #-48
TESTLOWER .FILL #0
TESTUPPER .FILL #-2
;
ASCII2 .FILL #48 ; Zero in ascii
NUMBER .FILL #999 ; test number
;
NHNDRD .FILL #-100 ; neg one hundred for test
HNDRD .FILL #100 ; one hundred for test
NTEN .FILL #-10
TEN .FILL #10
;
REG0 .BLKW 1 ; To restore the registers
REG1 .BLKW 1
REG2 .BLKW 1
REG3 .BLKW 1
REG4 .BLKW 1
REG5 .BLKW 1
REG6 .BLKW 1
REG7 .BLKW 1
;
FINISH .STRINGZ "\nYay, we guessed your number!\nYour number was "
QUESTIONPRE .STRINGZ "\nIs "
QUESTIONPOST .STRINGZ " your number? (0 = low, 1 = correct, 2 = high): "
WRONGINPUT .STRINGZ "ERROR: That is not a valid input.\nPlease try again.\n"
USERCHEATED .STRINGZ "\nYou cheated!\n"
EXPLANATION .STRINGZ "------- Number Guessing Game -------\nThink of a number between 1-100\n"
;
.END
;
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 91
call lwaitly_b
ld hl, fe00
ld d, 10
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 01
ldff(45), a
ld c, 41
ld b, 03
ld a, b3
ldff(40), a
ld a, 09
ldff(4b), a
ld a, 00
ldff(43), a
.text@1000
lstatint:
nop
.text@1094
ldff a, (c)
and a, b
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
dnl AMD64 mpn_hamdist -- hamming distance.
dnl Copyright 2008, 2010-2012, 2017 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C AMD K8,K9 -
C AMD K10 2.0 =
C AMD bd1 ~4.4 =
C AMD bd2 ~4.4 =
C AMD bd3
C AMD bd4
C AMD bobcat 7.55 =
C AMD jaguar 2.52 -
C Intel P4 -
C Intel core2 -
C Intel NHM 2.03 +
C Intel SBR 2.01 +
C Intel IBR 1.96 +
C Intel HWL 1.64 =
C Intel BWL 1.56 -
C Intel SKL 1.52 =
C Intel atom
C Intel SLM 3.0 -
C VIA nano
define(`ap', `%rdi')
define(`bp', `%rsi')
define(`n', `%rdx')
ABI_SUPPORT(DOS64)
ABI_SUPPORT(STD64)
ASM_START()
TEXT
ALIGN(32)
PROLOGUE(mpn_hamdist)
FUNC_ENTRY(3)
mov (ap), %r8
xor (bp), %r8
lea (ap,n,8), ap C point at A operand end
lea (bp,n,8), bp C point at B operand end
neg n
test $1, R8(n)
jz L(2)
L(1): .byte 0xf3,0x49,0x0f,0xb8,0xc0 C popcnt %r8, %rax
xor R32(%r10), R32(%r10)
inc n
js L(top)
FUNC_EXIT()
ret
ALIGN(16)
L(2): mov 8(ap,n,8), %r9
.byte 0xf3,0x49,0x0f,0xb8,0xc0 C popcnt %r8, %rax
xor 8(bp,n,8), %r9
.byte 0xf3,0x4d,0x0f,0xb8,0xd1 C popcnt %r9, %r10
add $2, n
js L(top)
lea (%r10, %rax), %rax
FUNC_EXIT()
ret
ALIGN(16)
L(top): mov (ap,n,8), %r8
lea (%r10, %rax), %rax
mov 8(ap,n,8), %r9
xor (bp,n,8), %r8
xor 8(bp,n,8), %r9
.byte 0xf3,0x49,0x0f,0xb8,0xc8 C popcnt %r8, %rcx
lea (%rcx, %rax), %rax
.byte 0xf3,0x4d,0x0f,0xb8,0xd1 C popcnt %r9, %r10
add $2, n
js L(top)
lea (%r10, %rax), %rax
FUNC_EXIT()
ret
EPILOGUE()
|
; A157759: a(n) = 15780962*n^2 - 25943924*n + 10662963.
; 500001,21898963,74859849,159382659,275467393,423114051,602322633,813093139,1055425569,1329319923,1634776201,1971794403,2340374529,2740516579,3172220553,3635486451,4130314273,4656704019,5214655689,5804169283,6425244801,7077882243,7762081609,8477842899,9225166113,10004051251,10814498313,11656507299,12530078209,13435211043,14371905801,15340162483,16339981089,17371361619,18434304073,19528808451,20654874753,21812502979,23001693129,24222445203,25474759201,26758635123,28074072969,29421072739
seq $0,157758 ; a(n) = 297754*n - 244754.
pow $0,2
sub $0,2809000000
div $0,5618
add $0,500001
|
; A008123: Coordination sequence T1 for Zeolite Code KFI.
; 1,4,9,17,29,45,64,86,112,141,173,209,249,292,338,388,441,497,557,621,688,758,832,909,989,1073,1161,1252,1346,1444,1545,1649,1757,1869,1984,2102,2224,2349,2477,2609,2745,2884,3026,3172,3321,3473,3629,3789,3952,4118,4288,4461,4637,4817,5001,5188,5378,5572,5769,5969,6173,6381,6592,6806,7024,7245,7469,7697,7929,8164,8402,8644,8889,9137,9389,9645,9904,10166,10432,10701,10973,11249,11529,11812,12098,12388,12681,12977,13277,13581,13888,14198,14512,14829,15149,15473,15801,16132,16466,16804
pow $0,2
lpb $0
sub $0,1
add $2,$0
add $0,$2
mov $2,$0
mov $0,0
mov $1,3
trn $2,1
add $1,$2
div $2,7
sub $1,$2
lpe
add $1,1
mov $0,$1
|
; A263511: Total number of ON (black) cells after n iterations of the "Rule 155" elementary cellular automaton starting with a single ON (black) cell.
; 1,3,6,12,19,29,40,54,69,87,106,128,151,177,204,234,265,299,334,372,411,453,496,542,589,639,690,744,799,857,916,978,1041,1107,1174,1244,1315,1389,1464,1542,1621,1703,1786,1872,1959,2049,2140,2234,2329,2427,2526,2628,2731,2837,2944,3054,3165,3279,3394,3512,3631,3753,3876,4002,4129,4259,4390,4524,4659,4797,4936,5078,5221,5367,5514,5664,5815,5969,6124,6282,6441,6603,6766,6932,7099,7269,7440,7614,7789,7967,8146,8328,8511,8697,8884,9074,9265,9459,9654,9852
mov $1,$0
add $0,3
div $0,2
pow $1,2
add $0,$1
|
#include "ShoppingCart.h"
void addItemQuantity(const Product& product, double quantity);
std::vector<ProductQuantity> ShoppingCart::getItems() const {
return items;
}
std::map<Product, double> ShoppingCart::getProductQuantities() const {
return productQuantities;
}
void ShoppingCart::addItem(const Product& product) {
addItemQuantity(product, 1.0);
}
void ShoppingCart::addItemQuantity(const Product& product, double quantity) {
items.emplace_back(product, quantity);
if (productQuantities.find(product) != productQuantities.end()) {
productQuantities[product] += quantity;
} else {
productQuantities[product] = quantity;
}
}
void ShoppingCart::handleOffers(Receipt& receipt, std::map<Product, Offer> offers, SupermarketCatalog* catalog) {
for (const auto& productQuantity : productQuantities) {
Product product = productQuantity.first;
double quantity = productQuantity.second;
if (offers.find(product) != offers.end()) {
auto offer = offers[product];
double unitPrice = catalog->getUnitPrice(product);
int quantityAsInt = (int) quantity;
Discount* discount = nullptr;
int offerCount = 1;
if (offer.getOfferType() == SpecialOfferType::Bundles){ // product is included in bundle offer
bool isBundle = true; // flag to indentify bundles
std::vector<int> localCountOffer; // keep track of the local offer counts
for(const auto& p : offer.getProducts()){ // for every product in the bundle offer
if(productQuantities.find(product) != productQuantities.end()){ // product found in quantities
double limit = offers.getArguments()[offer.getProducts().find(product) - offer.getProducts().begin() + offers.getArguments().begin()]; // argument of the product
if(productQuantities[product] >= limit){
localCountOffer.push_back(int(productQuantities[product] / limit));
}
else{
isBundle = false;
break; // amount not reached the minimum limit
}
}
else{
isBundle = false;
break; // element not found
}
}
if(isBundle == true){ // a suitable bundle found
int offerWhole = std::min_element(localCountOffer.begin(), localCountOffer.end()); // number of wholes in bundle
double limit = offers.getArguments()[offer.getProducts().find(product) - offer.getProducts().begin() + offers.getArguments().begin()]; // argument of the product
double percentage = offers.getArguments().back(); // get the discount percentage
double discountAmount = quantity - (percentage*offerWhole*limit + quantityAsInt % (offerWhole*limit)); // difference
discount = new Discount("Bundles", -1 * unitPrice *discountAmount, product); // create discount
}
}
if (offer.getOfferType() == SpecialOfferType::ThreeForTwo) {
offerCount = 3;
} else if (offer.getOfferType() == SpecialOfferType::TwoForAmount) {
offerCount = 2;
if (quantityAsInt >= 2) {
double total = offer.getArguments().front() * (quantityAsInt / offerCount) + quantityAsInt % 2 * unitPrice;
double discountN = unitPrice * quantity - total;
discount = new Discount("2 for " + std::to_string(offer.getArguments().front()), -discountN, product);
}
} if (offer.getOfferType() == SpecialOfferType::FiveForAmount) {
offerCount = 5;
}
int offerWhole = quantityAsInt / offerCount;
if (offer.getOfferType() == SpecialOfferType::ThreeForTwo && quantityAsInt > 2) {
double discountAmount = quantity * unitPrice - ((offerWhole * 2 * unitPrice) + quantityAsInt % 3 * unitPrice);
discount = new Discount("3 for 2", -discountAmount, product);
}
if (offer.getOfferType() == SpecialOfferType::TenPercentDiscount) {
discount = new Discount(std::to_string(offer.getArguments().front()) + "% off", -quantity * unitPrice * offer.getArguments().front() / 100.0, product);
}
if (offer.getOfferType() == SpecialOfferType::FiveForAmount && quantityAsInt >= 5) {
double discountTotal = unitPrice * quantity - (offer.getArguments().front() * offerWhole + quantityAsInt % 5 * unitPrice);
discount = new Discount(std::to_string(offerCount) + " for " + std::to_string(offer.getArguments().front()), -discountTotal, product);
}
if (discount != nullptr)
receipt.addDiscount(*discount);
}
}
} |
; A004449: Nimsum n + 8.
; 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31,16,17,18,19,20,21,22,23,40,41,42,43,44,45,46,47,32,33,34,35,36,37,38,39,56,57,58,59,60,61,62,63,48,49,50,51,52,53,54,55,72,73,74,75,76,77,78,79,64,65,66,67,68,69,70,71,88,89,90,91,92,93,94,95,80,81,82,83,84,85,86,87,104,105,106,107,108,109,110,111,96,97,98,99,100,101,102,103,120,121,122,123,124,125,126,127,112,113,114,115,116,117,118,119,136,137,138,139,140,141,142,143,128,129,130,131,132,133,134,135,152,153,154,155,156,157,158,159,144,145,146,147,148,149,150,151,168,169,170,171,172,173,174,175,160,161,162,163,164,165,166,167,184,185,186,187,188,189,190,191,176,177,178,179,180,181,182,183,200,201,202,203,204,205,206,207,192,193,194,195,196,197,198,199,216,217,218,219,220,221,222,223,208,209,210,211,212,213,214,215,232,233,234,235,236,237,238,239,224,225,226,227,228,229,230,231,248,249,250,251,252,253,254,255,240,241
mov $1,$0
mov $4,$0
mov $5,32
lpb $1,1
mov $1,0
lpb $5,1
mov $2,$0
div $2,8
mov $5,7
lpe
sub $1,1
lpe
add $3,$2
pow $1,$3
mul $1,8
add $1,$4
|
dnl ARM mpn_invert_limb -- Invert a normalized limb.
dnl Copyright 2001, 2009, 2011, 2012 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
ASM_START()
PROLOGUE(mpn_invert_limb)
LEA( r2, approx_tab-512)
mov r3, r0, lsr #23
mov r3, r3, asl #1
ldrh r3, [r3, r2]
mov r1, r3, asl #17
mul r12, r3, r3
umull r3, r2, r12, r0
sub r1, r1, r2, asl #1
umull r3, r2, r1, r1
umull r12, r3, r0, r3
umull r2, r12, r0, r2
adds r2, r2, r3
adc r12, r12, #0
rsb r1, r12, r1
mvn r2, r2, lsr #30
add r2, r2, r1, asl #2
umull r12, r3, r0, r2
adds r1, r12, r0
adc r3, r3, r0
rsb r0, r3, r2
return lr
EPILOGUE()
RODATA
ALIGN(2)
approx_tab:
.short 0xffc0,0xfec0,0xfdc0,0xfcc0,0xfbc0,0xfac0,0xfa00,0xf900
.short 0xf800,0xf700,0xf640,0xf540,0xf440,0xf380,0xf280,0xf180
.short 0xf0c0,0xefc0,0xef00,0xee00,0xed40,0xec40,0xeb80,0xeac0
.short 0xe9c0,0xe900,0xe840,0xe740,0xe680,0xe5c0,0xe500,0xe400
.short 0xe340,0xe280,0xe1c0,0xe100,0xe040,0xdf80,0xdec0,0xde00
.short 0xdd40,0xdc80,0xdbc0,0xdb00,0xda40,0xd980,0xd8c0,0xd800
.short 0xd740,0xd680,0xd600,0xd540,0xd480,0xd3c0,0xd340,0xd280
.short 0xd1c0,0xd140,0xd080,0xcfc0,0xcf40,0xce80,0xcdc0,0xcd40
.short 0xcc80,0xcc00,0xcb40,0xcac0,0xca00,0xc980,0xc8c0,0xc840
.short 0xc780,0xc700,0xc640,0xc5c0,0xc540,0xc480,0xc400,0xc380
.short 0xc2c0,0xc240,0xc1c0,0xc100,0xc080,0xc000,0xbf80,0xbec0
.short 0xbe40,0xbdc0,0xbd40,0xbc80,0xbc00,0xbb80,0xbb00,0xba80
.short 0xba00,0xb980,0xb900,0xb840,0xb7c0,0xb740,0xb6c0,0xb640
.short 0xb5c0,0xb540,0xb4c0,0xb440,0xb3c0,0xb340,0xb2c0,0xb240
.short 0xb1c0,0xb140,0xb0c0,0xb080,0xb000,0xaf80,0xaf00,0xae80
.short 0xae00,0xad80,0xad40,0xacc0,0xac40,0xabc0,0xab40,0xaac0
.short 0xaa80,0xaa00,0xa980,0xa900,0xa8c0,0xa840,0xa7c0,0xa740
.short 0xa700,0xa680,0xa600,0xa5c0,0xa540,0xa4c0,0xa480,0xa400
.short 0xa380,0xa340,0xa2c0,0xa240,0xa200,0xa180,0xa140,0xa0c0
.short 0xa080,0xa000,0x9f80,0x9f40,0x9ec0,0x9e80,0x9e00,0x9dc0
.short 0x9d40,0x9d00,0x9c80,0x9c40,0x9bc0,0x9b80,0x9b00,0x9ac0
.short 0x9a40,0x9a00,0x9980,0x9940,0x98c0,0x9880,0x9840,0x97c0
.short 0x9780,0x9700,0x96c0,0x9680,0x9600,0x95c0,0x9580,0x9500
.short 0x94c0,0x9440,0x9400,0x93c0,0x9340,0x9300,0x92c0,0x9240
.short 0x9200,0x91c0,0x9180,0x9100,0x90c0,0x9080,0x9000,0x8fc0
.short 0x8f80,0x8f40,0x8ec0,0x8e80,0x8e40,0x8e00,0x8d80,0x8d40
.short 0x8d00,0x8cc0,0x8c80,0x8c00,0x8bc0,0x8b80,0x8b40,0x8b00
.short 0x8a80,0x8a40,0x8a00,0x89c0,0x8980,0x8940,0x88c0,0x8880
.short 0x8840,0x8800,0x87c0,0x8780,0x8740,0x8700,0x8680,0x8640
.short 0x8600,0x85c0,0x8580,0x8540,0x8500,0x84c0,0x8480,0x8440
.short 0x8400,0x8380,0x8340,0x8300,0x82c0,0x8280,0x8240,0x8200
.short 0x81c0,0x8180,0x8140,0x8100,0x80c0,0x8080,0x8040,0x8000
ASM_END()
|
/* Copyright 2003-2013 Joaquin M Lopez Munoz.
* 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/multi_index for library home page.
*/
#pragma once
#include <brigand/functions/logical/or.hpp>
#include <brigand/types/bool.hpp>
#include <type_traits>
namespace multi_index{
namespace detail{
/* determines whether an index type has a given tag in its tag list */
template <typename Tag, typename... Ts>
struct has_tag_impl;
template <typename Tag>
struct has_tag_impl<Tag> : brigand::false_type {};
template <typename Tag, typename T, typename... Ts>
struct has_tag_impl<Tag, T, Ts...> : brigand::or_<std::is_same<Tag, T>, has_tag_impl<Tag, Ts...>> {};
template <typename Tag, typename... Ts>
struct has_tag;
template <typename Tag, typename... Ts, template <typename...> class C>
struct has_tag<Tag, C<Ts...>>
{
using type = has_tag_impl<Tag, Ts...>;
};
} /* namespace multi_index::detail */
} /* namespace multi_index */
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r15
push %r8
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x96f4, %rsi
lea addresses_WC_ht+0xdef4, %rdi
nop
nop
dec %r12
mov $6, %rcx
rep movsb
nop
nop
nop
sub %r8, %r8
lea addresses_normal_ht+0x1e100, %r15
nop
nop
dec %rbp
mov $0x6162636465666768, %rsi
movq %rsi, (%r15)
and %r15, %r15
lea addresses_normal_ht+0xd6f4, %rsi
lea addresses_UC_ht+0x1b7d4, %rdi
clflush (%rsi)
nop
and %r10, %r10
mov $34, %rcx
rep movsq
nop
nop
nop
nop
nop
and $22907, %r15
lea addresses_UC_ht+0x165f4, %rsi
lea addresses_WC_ht+0xa6f4, %rdi
clflush (%rsi)
nop
nop
nop
nop
and $46064, %rbp
mov $39, %rcx
rep movsl
nop
nop
nop
xor %r8, %r8
lea addresses_WC_ht+0x14df4, %rsi
lea addresses_normal_ht+0x52a4, %rdi
nop
nop
nop
nop
nop
sub $47692, %r8
mov $106, %rcx
rep movsw
nop
nop
nop
nop
nop
sub $13230, %r10
lea addresses_UC_ht+0x1b034, %r10
nop
nop
nop
nop
sub %r12, %r12
mov $0x6162636465666768, %rcx
movq %rcx, (%r10)
nop
nop
nop
add $48021, %r8
lea addresses_WT_ht+0x15ef4, %r10
nop
and %rbp, %rbp
mov (%r10), %r15w
nop
nop
nop
nop
nop
add %r15, %r15
lea addresses_normal_ht+0x1cb74, %rsi
nop
nop
nop
nop
cmp $54325, %rdi
mov $0x6162636465666768, %r15
movq %r15, (%rsi)
nop
nop
nop
nop
nop
dec %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r8
pop %r15
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %rax
push %rbp
push %rbx
push %rcx
// Store
lea addresses_normal+0x4ef4, %r11
nop
nop
nop
nop
nop
inc %r10
movw $0x5152, (%r11)
nop
nop
nop
nop
cmp $2597, %r10
// Store
lea addresses_RW+0x11524, %r11
nop
nop
nop
nop
sub $43559, %rbp
mov $0x5152535455565758, %rcx
movq %rcx, %xmm3
movups %xmm3, (%r11)
nop
nop
nop
add %rbp, %rbp
// Faulty Load
lea addresses_WT+0x96f4, %rax
nop
sub $48228, %rbp
vmovntdqa (%rax), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $1, %xmm3, %r11
lea oracles, %rbp
and $0xff, %r11
shlq $12, %r11
mov (%rbp,%r11,1), %r11
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WT', 'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}, 'dst': {'same': True, 'congruent': 5, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}}
{'00': 624, '48': 7, '44': 21198}
00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 00 44 44 44 44 00 00 44 44 44 44 00 44 44 44 44 44 44 44 00 44 44 44 44 44 44 00 44 44 00 44 44 44 44 44 44 44 44 44 44 00 44 44 44 00 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 00 44 44 44 00 00 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 00 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 00 44 44 44 44 44 44 00 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 00 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 00 44 00 44 44 44 44 44 44 44 44 44 44
*/
|
; A092364: a(n) = n^2*binomial(n,2).
; 0,4,27,96,250,540,1029,1792,2916,4500,6655,9504,13182,17836,23625,30720,39304,49572,61731,76000,92610,111804,133837,158976,187500,219700,255879,296352,341446,391500,446865,507904,574992,648516,728875,816480
mov $1,$0
add $0,1
pow $0,3
mul $1,$0
div $1,2
|
; A335648: Partial sums of A006010.
; 0,1,6,26,78,195,420,820,1476,2501,4026,6222,9282,13447,18984,26216,35496,47241,61902,80002,102102,128843,160908,199068,244140,297037,358722,430262,512778,607503,715728,838864,978384,1135889,1313046,1511658,1733598,1980883,2255604
mov $12,$0
mov $14,$0
lpb $14,1
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
lpb $11,1
mov $0,$9
sub $11,1
sub $0,$11
mov $1,$0
mov $2,$0
mul $2,$0
mov $8,1
add $8,$2
div $8,2
mul $1,$8
add $10,$1
lpe
add $13,$10
lpe
mov $1,$13
|
; void wherex()
; 09.2017 stefano
SECTION code_clib
PUBLIC wherex
PUBLIC _wherex
EXTERN __console_x
.wherex
._wherex
ld a,(__console_x)
ld l,a
ld h,0
IF __CPU_GBZ80__
ld d,h
ld e,l
ENDIF
ret
|
// This file is part of DM-HEOM (https://github.com/noma/dm-heom)
//
// Copyright (c) 2015-2019 Matthias Noack, Zuse Institute Berlin
//
// Licensed under the 3-clause BSD License, see accompanying LICENSE,
// CONTRIBUTORS.md, and README.md for further information.
#include "heom/static_fluorescence_config.hpp"
namespace heom {
namespace bpo = ::boost::program_options;
static_fluorescence_config::static_fluorescence_config(const std::string& config_file_name, bool parse_config)
: thermal_state_search_config(config_file_name, false),
dipole_config_entries(desc_)
{
// NOTE: no additional entries needed
if (parse_config)
parse(config_file_name);
}
void static_fluorescence_config::check()
{
thermal_state_search_config::check(); // call direct super-class' check()
// call generic checks from entry classes
dipole_config_entries::check(system_sites());
}
void static_fluorescence_config::check_final()
{
// check program_task_
if (program_task() != program_task_t::STATIC_FLUORESCENCE)
throw config_error("wrong program_task for this application");
// check observations specification, static_fluorescence is a special case
// as it averages multiple observations
if (observations().get().size() > 1)
throw config_error("static_fluorescence only supports a single observation of type matrix_trace_static_fluorescence");
for (auto& obs : observations().get())
{
if (obs.get().first != heom::observation_type_t::matrix_trace_static_fluorescence)
throw config_error("invalid observation type found in observations, only matrix_trace_static_fluorescence is allowed");
}
}
void static_fluorescence_config::post_process()
{
thermal_state_search_config::post_process(); // call direct super-class' post_process()
// call post_process from entry classes
dipole_config_entries::post_process();
}
} // namespace heom
|
#ifndef _MTOOL_ASM_
#define _MTOOL_ASM_
;.INCLUDE "RESOURCE\RESOURCE.INC"
.MACRO CBRS
SEZ
SBRS @0,@1
CLZ
.ENDMACRO
;STACK = X
//-------------------------------------------STACK ERROR COMPATE LATER-----------------------
/*LDI R27,0
LDI R26,0
.MACRO MPUSH
MOV ARG1,@0
CALL MYPUSH
.ENDMACRO
.MACRO MPOP
MOV ARG1,@0
CALL MYPOP
.ENDMACRO
MYPOP:
CPI R26,0
IF(MYPOPIF,BRNE)
LD ARG1,-X
END(MYPOPIF)
RET
MYPUSH:
CPI R26,0X0F
IF(MYPUSHIF,BRNE)
ST X+,ARG1
END(MYPUSHIF)
RET*/
//-------------------------------------------STACK ERROR COMPATE LATER-----------------------
/*LDI R28,low(GETARR(@1,@2))
LDI R29,high(GETARR(@1,@2))*/
.MACRO MLARR
;LDS RD,K
LDS @0,GETARR(@1,@2)
.ENDMACRO
.MACRO MSARR
;STS K,RD
STS GETARR(@1,@2),@0
.ENDMACRO
INT2CHAR:
PUSH TMP
LDI TMP,'0'
ADD ARG1,TMP
;MPUSH ARG1
MOV RES,ARG1
POP TMP
RET
.MACRO MINT2CHAR
MOV ARG1,@0
CALL INT2CHAR
.ENDMACRO
#endif
;1<<BU|1<<BD
/*.MACRO MITA1
;INIT TMP ARG
MOV TMPARG1,ARG1
.ENDMACRO
.MACRO MIA1
MOV ARG1,TMPARG1
.ENDMACRO
.MACRO MITA2
;INIT TMP ARG
MOV TMPARG2,ARG2
.ENDMACRO
.MACRO MIA2
MOV ARG2,TMPARG2
.ENDMACRO
.MACRO MITA
;INIT TMP ARG
MOV TMPARG1,ARG1
MOV TMPARG2,ARG2
.ENDMACRO
.MACRO MIA
MOV ARG1,TMPARG1
MOV ARG2,TMPARG2
.ENDMACRO*/
|
; Static display list which is modified every scanline to render graphics.
; This takes seven seconds to assemble, and including rdp.inc would paralyze
; compilation of the rest of the program, so this is in a file of its own.
thecolors equne $80009520
org 0x430
#include macros.inc
#include rdp.inc
#include defs.inc
displaylist
fillstart
dw $FF100000|($118-1) ; SetCimg
SetCimg dw screenbuffer
scissor
dw $ED000000|(8<14)|(8<2) ; SetScissor
dw ($118<14)|(232<2)
; dw $ED000000|(8<14)|(0<2) ; SetScissor PAL
; dw ($118<14)|(240<2)
dw $EFB92CBF ; RDPSetOtherMode (magic number from Destop)
dw $0F0A4000
dw $F7000000 ; set fill color
bgcolor dw $00010001
fillrect dw $F65003C0 ; fill rectangle (completely overwritten)
dw 0
fillend
loadpalstart
gsDPLoadTLUT_pal256(_bgpal)
loadpalend
bgsprstart
; set other mode
dw $EF800CBF|G_TT_RGBA16|G_TF_POINT|G_CYC_1CYCLE
dw $0F0A7008
dw $fc11fe23 ; setcombine (magic number from Destop)
dw $fffff3f9
dw $FA000000 ;SetPrimColor
primcolor dw $ffffffff ; (used for color deemphasis)
_gsDPLoadTextureBlock(bgsprbuffer,0,G_IM_FMT_CI,G_IM_SIZ_8b,256,1,0,2,2,0,0,0,0)
bg_spr_rect
gsDPDrawTexturedRectangle(8,100,256,1,$400,$400)
gsDPTileSync
gsDPPipeSync
bgsprend
bgstart
_gsDPLoadTextureBlock((bgbuffer+8),0,G_IM_FMT_CI,G_IM_SIZ_8b,256,1,0,2,2,0,0,0,0)
;_gsDPLoadTextureBlock((thecolors),0,G_IM_FMT_CI,G_IM_SIZ_8b,256,1,0,2,2,0,0,0,0)
bg_rect
gsDPDrawTexturedRectangle(8,100,256,1,$400,$400)
gsDPTileSync
gsDPPipeSync
bgend
fgsprstart
_gsDPLoadTextureBlock(fgsprbuffer,0,G_IM_FMT_CI,G_IM_SIZ_8b,256,1,0,2,2,0,0,0,0)
fg_spr_rect
gsDPDrawTexturedRectangle(8,100,256,1,$400,$400)
gsDPTileSync
gsDPPipeSync
fgsprend
end_dl
|
#include "noise.hpp"
#include "third_party/src/simplexnoise/simplexnoise1234.hpp"
#include "vcl/base/base.hpp"
namespace vcl
{
float noise_perlin(float x, int octave, float persistency, float frequency_gain)
{
float value = 0.0f;
float a = 1.0f; // current magnitude
float f = 1.0f; // current frequency
for(int k=0;k<octave;k++)
{
const float n = static_cast<float>(snoise1(x*f));
value += a*(0.5f+0.5f*n);
f *= frequency_gain;
a *= persistency;
}
return value;
}
float noise_perlin(vec2 const& p, int octave, float persistency, float frequency_gain)
{
float value = 0.0f;
float a = 1.0f; // current magnitude
float f = 1.0f; // current frequency
for(int k=0;k<octave;k++)
{
const float n = static_cast<float>(snoise2(p.x*f, p.y*f));
value += a*(0.5f+0.5f*n );
f *= frequency_gain;
a *= persistency;
}
return value;
}
float noise_perlin(vec3 const& p, int octave, float persistency, float frequency_gain)
{
float value = 0.0f;
float a = 1.0f; // current magnitude
float f = 1.0f; // current frequency
for(int k=0;k<octave;k++)
{
const float n = static_cast<float>(snoise3(p.x*f, p.y*f, p.z*f));
value += a*(0.5f+0.5f*n);
f *= frequency_gain;
a *= persistency;
}
return value;
}
} |
/* Programa que lee una matriz simétrica y construye una matriz
suavizada, cuya diagonal principal son iguales a la original, es
simétrica y en cada posición (i,j) incluye el valor medio de los
valores que ocupan las posiciones de las columnas j,j+1,...,n-1 en
la fila i de la original. */
#include<iostream>
using namespace std;
int main() {
const int MAX_FILAS = 50;
double original[MAX_FILAS][MAX_FILAS];
double suavizada[MAX_FILAS][MAX_FILAS];
int n, i, j, columnas;
double elemento, suma;
do {
cout <<"Número de filas: ";
cin >> n;
} while(n < 0 || n>= MAX_FILAS);
for(i = 0; i < n; i++) { // Lectura de la matriz original
for(j = i; j < n; j++) {
cout << "Fila: " << i+1 << " , columna " << j+1 << ": ";
cin >> elemento;
original[i][j] = elemento;
}
}
for(i = 0; i < n; i++) // Copia de la diagonal principal
suavizada[i][i] = original[i][i];
for(i = 0; i < n; i++) { // Recorro la matriz original
suma = 0;
columnas = 0;
for(j = n-1; j > i; j--) {
suma += original[i][j]; // Sumo los distinos elementos
suavizada[i][j] = suma / ++columnas; // Asigno a cada posición el valor medio correspondiente
suavizada[j][i] = suavizada[i][j]; // Para que la matriz sea simétrica
}
}
cout <<"Matriz suavizada:\n\n";
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++)
cout << "\t" << suavizada[i][j];
cout << "\n";
}
}
|
; void p_stack_push(p_stack_t *s, void *item)
SECTION code_clib
SECTION code_adt_p_stack
PUBLIC p_stack_push
EXTERN p_forward_list_insert_after
defc p_stack_push = p_forward_list_insert_after
|
li $v0,1
add $a0,$t0,$0
syscall |
#include "blockexplorer.h"
#include "bitcoinunits.h"
#include "chainparams.h"
#include "clientmodel.h"
#include "core_io.h"
#include "guiutil.h"
#include "main.h"
#include "net.h"
#include "txdb.h"
#include "ui_blockexplorer.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include <QDateTime>
#include <QKeyEvent>
#include <QMessageBox>
#include <set>
extern double GetDifficulty(const CBlockIndex* blockindex = NULL);
inline std::string utostr(unsigned int n)
{
return strprintf("%u", n);
}
static std::string makeHRef(const std::string& Str)
{
return "<a href=\"" + Str + "\">" + Str + "</a>";
}
static CAmount getTxIn(const CTransaction& tx)
{
if (tx.IsCoinBase())
return 0;
CAmount Sum = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
Sum += getPrevOut(tx.vin[i].prevout).nValue;
return Sum;
}
static std::string ValueToString(CAmount nValue, bool AllowNegative = false)
{
if (nValue < 0 && !AllowNegative)
return "<span>" + _("unknown") + "</span>";
QString Str = BitcoinUnits::formatWithUnit(BitcoinUnits::DCO, nValue);
if (AllowNegative && nValue > 0)
Str = '+' + Str;
return std::string("<span>") + Str.toUtf8().data() + "</span>";
}
static std::string ScriptToString(const CScript& Script, bool Long = false, bool Highlight = false)
{
if (Script.empty())
return "unknown";
CTxDestination Dest;
CBitcoinAddress Address;
if (ExtractDestination(Script, Dest) && Address.Set(Dest)) {
if (Highlight)
return "<span class=\"addr\">" + Address.ToString() + "</span>";
else
return makeHRef(Address.ToString());
} else
return Long ? "<pre>" + FormatScript(Script) + "</pre>" : _("Non-standard script");
}
static std::string TimeToString(uint64_t Time)
{
QDateTime timestamp;
timestamp.setTime_t(Time);
return timestamp.toString("yyyy-MM-dd hh:mm:ss").toUtf8().data();
}
static std::string makeHTMLTableRow(const std::string* pCells, int n)
{
std::string Result = "<tr>";
for (int i = 0; i < n; i++) {
Result += "<td class=\"d" + utostr(i) + "\">";
Result += pCells[i];
Result += "</td>";
}
Result += "</tr>";
return Result;
}
static const char* table = "<table>";
static std::string makeHTMLTable(const std::string* pCells, int nRows, int nColumns)
{
std::string Table = table;
for (int i = 0; i < nRows; i++)
Table += makeHTMLTableRow(pCells + i * nColumns, nColumns);
Table += "</table>";
return Table;
}
static std::string TxToRow(const CTransaction& tx, const CScript& Highlight = CScript(), const std::string& Prepend = std::string(), int64_t* pSum = NULL)
{
std::string InAmounts, InAddresses, OutAmounts, OutAddresses;
int64_t Delta = 0;
for (unsigned int j = 0; j < tx.vin.size(); j++) {
if (tx.IsCoinBase()) {
InAmounts += ValueToString(tx.GetValueOut());
InAddresses += "coinbase";
} else {
CTxOut PrevOut = getPrevOut(tx.vin[j].prevout);
InAmounts += ValueToString(PrevOut.nValue);
InAddresses += ScriptToString(PrevOut.scriptPubKey, false, PrevOut.scriptPubKey == Highlight).c_str();
if (PrevOut.scriptPubKey == Highlight)
Delta -= PrevOut.nValue;
}
if (j + 1 != tx.vin.size()) {
InAmounts += "<br/>";
InAddresses += "<br/>";
}
}
for (unsigned int j = 0; j < tx.vout.size(); j++) {
CTxOut Out = tx.vout[j];
OutAmounts += ValueToString(Out.nValue);
OutAddresses += ScriptToString(Out.scriptPubKey, false, Out.scriptPubKey == Highlight);
if (Out.scriptPubKey == Highlight)
Delta += Out.nValue;
if (j + 1 != tx.vout.size()) {
OutAmounts += "<br/>";
OutAddresses += "<br/>";
}
}
std::string List[8] =
{
Prepend,
makeHRef(tx.GetHash().GetHex()),
InAddresses,
InAmounts,
OutAddresses,
OutAmounts,
"",
""};
int n = sizeof(List) / sizeof(std::string) - 2;
if (!Highlight.empty()) {
List[n++] = std::string("<font color=\"") + ((Delta > 0) ? "green" : "red") + "\">" + ValueToString(Delta, true) + "</font>";
*pSum += Delta;
List[n++] = ValueToString(*pSum);
return makeHTMLTableRow(List, n);
}
return makeHTMLTableRow(List + 1, n - 1);
}
CTxOut getPrevOut(const COutPoint& out)
{
CTransaction tx;
uint256 hashBlock;
if (GetTransaction(out.hash, tx, hashBlock, true))
return tx.vout[out.n];
return CTxOut();
}
void getNextIn(const COutPoint& Out, uint256& Hash, unsigned int& n)
{
// Hash = 0;
// n = 0;
// if (paddressmap)
// paddressmap->ReadNextIn(Out, Hash, n);
}
const CBlockIndex* getexplorerBlockIndex(int64_t height)
{
std::string hex = getexplorerBlockHash(height);
uint256 hash = uint256S(hex);
return mapBlockIndex[hash];
}
std::string getexplorerBlockHash(int64_t Height)
{
std::string genesisblockhash = "0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818";
CBlockIndex* pindexBest = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
if ((Height < 0) || (Height > pindexBest->nHeight)) {
return genesisblockhash;
}
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
while (pblockindex->nHeight > Height)
pblockindex = pblockindex->pprev;
return pblockindex->GetBlockHash().GetHex(); // pblockindex->phashBlock->GetHex();
}
std::string BlockToString(CBlockIndex* pBlock)
{
if (!pBlock)
return "";
CBlock block;
ReadBlockFromDisk(block, pBlock);
CAmount Fees = 0;
CAmount OutVolume = 0;
CAmount Reward = 0;
std::string TxLabels[] = {_("Hash"), _("From"), _("Amount"), _("To"), _("Amount")};
std::string TxContent = table + makeHTMLTableRow(TxLabels, sizeof(TxLabels) / sizeof(std::string));
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const CTransaction& tx = block.vtx[i];
TxContent += TxToRow(tx);
CAmount In = getTxIn(tx);
CAmount Out = tx.GetValueOut();
if (tx.IsCoinBase())
Reward += Out;
else if (In < 0)
Fees = -Params().MaxMoneyOut();
else {
Fees += In - Out;
OutVolume += Out;
}
}
TxContent += "</table>";
CAmount Generated;
if (pBlock->nHeight == 0)
Generated = OutVolume;
else
Generated = GetBlockValue(pBlock->nHeight - 1);
std::string BlockContentCells[] =
{
_("Height"), itostr(pBlock->nHeight),
_("Size"), itostr(GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)),
_("Number of Transactions"), itostr(block.vtx.size()),
_("Value Out"), ValueToString(OutVolume),
_("Fees"), ValueToString(Fees),
_("Generated"), ValueToString(Generated),
_("Timestamp"), TimeToString(block.nTime),
_("Difficulty"), strprintf("%.4f", GetDifficulty(pBlock)),
_("Bits"), utostr(block.nBits),
_("Nonce"), utostr(block.nNonce),
_("Version"), itostr(block.nVersion),
_("Hash"), "<pre>" + block.GetHash().GetHex() + "</pre>",
_("Merkle Root"), "<pre>" + block.hashMerkleRoot.GetHex() + "</pre>",
// _("Hash Whole Block"), "<pre>" + block.hashWholeBlock.GetHex() + "</pre>"
// _("Miner Signature"), "<pre>" + block.MinerSignature.ToString() + "</pre>"
};
std::string BlockContent = makeHTMLTable(BlockContentCells, sizeof(BlockContentCells) / (2 * sizeof(std::string)), 2);
std::string Content;
Content += "<h2><a class=\"nav\" href=";
Content += itostr(pBlock->nHeight - 1);
Content += ">◄ </a>";
Content += _("Block");
Content += " ";
Content += itostr(pBlock->nHeight);
Content += "<a class=\"nav\" href=";
Content += itostr(pBlock->nHeight + 1);
Content += "> ►</a></h2>";
Content += BlockContent;
Content += "</br>";
/*
if (block.nHeight > getThirdHardforkBlock())
{
std::vector<std::string> votes[2];
for (int i = 0; i < 2; i++)
{
for (unsigned int j = 0; j < block.vvotes[i].size(); j++)
{
votes[i].push_back(block.vvotes[i][j].hash.ToString() + ':' + itostr(block.vvotes[i][j].n));
}
}
Content += "<h3>" + _("Votes +") + "</h3>";
Content += makeHTMLTable(&votes[1][0], votes[1].size(), 1);
Content += "</br>";
Content += "<h3>" + _("Votes -") + "</h3>";
Content += makeHTMLTable(&votes[0][0], votes[0].size(), 1);
Content += "</br>";
}
*/
Content += "<h2>" + _("Transactions") + "</h2>";
Content += TxContent;
return Content;
}
std::string TxToString(uint256 BlockHash, const CTransaction& tx)
{
CAmount Input = 0;
CAmount Output = tx.GetValueOut();
std::string InputsContentCells[] = {_("#"), _("Taken from"), _("Address"), _("Amount")};
std::string InputsContent = makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string));
std::string OutputsContentCells[] = {_("#"), _("Redeemed in"), _("Address"), _("Amount")};
std::string OutputsContent = makeHTMLTableRow(OutputsContentCells, sizeof(OutputsContentCells) / sizeof(std::string));
if (tx.IsCoinBase()) {
std::string InputsContentCells[] =
{
"0",
"coinbase",
"-",
ValueToString(Output)};
InputsContent += makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string));
} else
for (unsigned int i = 0; i < tx.vin.size(); i++) {
COutPoint Out = tx.vin[i].prevout;
CTxOut PrevOut = getPrevOut(tx.vin[i].prevout);
if (PrevOut.nValue < 0)
Input = -Params().MaxMoneyOut();
else
Input += PrevOut.nValue;
std::string InputsContentCells[] =
{
itostr(i),
"<span>" + makeHRef(Out.hash.GetHex()) + ":" + itostr(Out.n) + "</span>",
ScriptToString(PrevOut.scriptPubKey, true),
ValueToString(PrevOut.nValue)};
InputsContent += makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string));
}
uint256 TxHash = tx.GetHash();
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& Out = tx.vout[i];
uint256 HashNext = uint256S("0");
unsigned int nNext = 0;
bool fAddrIndex = false;
getNextIn(COutPoint(TxHash, i), HashNext, nNext);
std::string OutputsContentCells[] =
{
itostr(i),
(HashNext == uint256S("0")) ? (fAddrIndex ? _("no") : _("unknown")) : "<span>" + makeHRef(HashNext.GetHex()) + ":" + itostr(nNext) + "</span>",
ScriptToString(Out.scriptPubKey, true),
ValueToString(Out.nValue)};
OutputsContent += makeHTMLTableRow(OutputsContentCells, sizeof(OutputsContentCells) / sizeof(std::string));
}
InputsContent = table + InputsContent + "</table>";
OutputsContent = table + OutputsContent + "</table>";
std::string Hash = TxHash.GetHex();
std::string Labels[] =
{
_("In Block"), "",
_("Size"), itostr(GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)),
_("Input"), tx.IsCoinBase() ? "-" : ValueToString(Input),
_("Output"), ValueToString(Output),
_("Fees"), tx.IsCoinBase() ? "-" : ValueToString(Input - Output),
_("Timestamp"), "",
_("Hash"), "<pre>" + Hash + "</pre>",
};
// std::map<uint256, CBlockIndex*>::iterator iter = mapBlockIndex.find(BlockHash);
BlockMap::iterator iter = mapBlockIndex.find(BlockHash);
if (iter != mapBlockIndex.end()) {
CBlockIndex* pIndex = iter->second;
Labels[0 * 2 + 1] = makeHRef(itostr(pIndex->nHeight));
Labels[5 * 2 + 1] = TimeToString(pIndex->nTime);
}
std::string Content;
Content += "<h2>" + _("Transaction") + " <span>" + Hash + "</span></h2>";
Content += makeHTMLTable(Labels, sizeof(Labels) / (2 * sizeof(std::string)), 2);
Content += "</br>";
Content += "<h3>" + _("Inputs") + "</h3>";
Content += InputsContent;
Content += "</br>";
Content += "<h3>" + _("Outputs") + "</h3>";
Content += OutputsContent;
return Content;
}
std::string AddressToString(const CBitcoinAddress& Address)
{
std::string TxLabels[] =
{
_("Date"),
_("Hash"),
_("From"),
_("Amount"),
_("To"),
_("Amount"),
_("Delta"),
_("Balance")};
std::string TxContent = table + makeHTMLTableRow(TxLabels, sizeof(TxLabels) / sizeof(std::string));
std::set<COutPoint> PrevOuts;
/*
CScript AddressScript;
AddressScript.SetDestination(Address.Get());
CAmount Sum = 0;
bool fAddrIndex = false;
if (!fAddrIndex)
return ""; // it will take too long to find transactions by address
else
{
std::vector<CDiskTxPos> Txs;
paddressmap->GetTxs(Txs, AddressScript.GetID());
BOOST_FOREACH (const CDiskTxPos& pos, Txs)
{
CTransaction tx;
CBlock block;
uint256 bhash = block.GetHash();
GetTransaction(pos.nTxOffset, tx, bhash);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
continue;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
continue;
std::string Prepend = "<a href=\"" + itostr(pindex->nHeight) + "\">" + TimeToString(pindex->nTime) + "</a>";
TxContent += TxToRow(tx, AddressScript, Prepend, &Sum);
}
}
*/
TxContent += "</table>";
std::string Content;
Content += "<h1 style='color:#ffffff;'>" + _("Transactions to/from") + " <span>" + Address.ToString() + "</span></h1>";
Content += TxContent;
return Content;
}
BlockExplorer::BlockExplorer(QWidget* parent) : QMainWindow(parent),
ui(new Ui::BlockExplorer),
m_NeverShown(true),
m_HistoryIndex(0)
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
connect(ui->pushSearch, SIGNAL(released()), this, SLOT(onSearch()));
connect(ui->content, SIGNAL(linkActivated(const QString&)), this, SLOT(goTo(const QString&)));
connect(ui->back, SIGNAL(released()), this, SLOT(back()));
connect(ui->forward, SIGNAL(released()), this, SLOT(forward()));
}
BlockExplorer::~BlockExplorer()
{
delete ui;
}
void BlockExplorer::keyPressEvent(QKeyEvent* event)
{
switch ((Qt::Key)event->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
onSearch();
return;
default:
return QMainWindow::keyPressEvent(event);
}
}
void BlockExplorer::showEvent(QShowEvent*)
{
if (m_NeverShown) {
m_NeverShown = false;
CBlockIndex* pindexBest = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
setBlock(pindexBest);
QString text = QString("%1").arg(pindexBest->nHeight);
ui->searchBox->setText(text);
m_History.push_back(text);
updateNavButtons();
if (!GetBoolArg("-txindex", false)) {
QString Warning = tr("Not all transactions will be shown. To view all transactions you need to set txindex=1 in the configuration file (dcoins.conf).");
QMessageBox::warning(this, "Dcoins Core Blockchain Explorer", Warning, QMessageBox::Ok);
}
}
}
bool BlockExplorer::switchTo(const QString& query)
{
bool IsOk;
int64_t AsInt = query.toInt(&IsOk);
// If query is integer, get hash from height
if (IsOk && AsInt >= 0 && AsInt <= chainActive.Tip()->nHeight) {
std::string hex = getexplorerBlockHash(AsInt);
uint256 hash = uint256S(hex);
CBlockIndex* pIndex = mapBlockIndex[hash];
if (pIndex) {
setBlock(pIndex);
return true;
}
}
// If the query is not an integer, assume it is a block hash
uint256 hash = uint256S(query.toUtf8().constData());
// std::map<uint256, CBlockIndex*>::iterator iter = mapBlockIndex.find(hash);
BlockMap::iterator iter = mapBlockIndex.find(hash);
if (iter != mapBlockIndex.end()) {
setBlock(iter->second);
return true;
}
// If the query is neither an integer nor a block hash, assume a transaction hash
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock, true)) {
setContent(TxToString(hashBlock, tx));
return true;
}
// If the query is not an integer, nor a block hash, nor a transaction hash, assume an address
CBitcoinAddress Address;
Address.SetString(query.toUtf8().constData());
if (Address.IsValid()) {
std::string Content = AddressToString(Address);
if (Content.empty())
return false;
setContent(Content);
return true;
}
return false;
}
void BlockExplorer::goTo(const QString& query)
{
if (switchTo(query)) {
ui->searchBox->setText(query);
while (m_History.size() > m_HistoryIndex + 1)
m_History.pop_back();
m_History.push_back(query);
m_HistoryIndex = m_History.size() - 1;
updateNavButtons();
}
}
void BlockExplorer::onSearch()
{
goTo(ui->searchBox->text());
}
void BlockExplorer::setBlock(CBlockIndex* pBlock)
{
setContent(BlockToString(pBlock));
}
void BlockExplorer::setContent(const std::string& Content)
{
QString CSS = "body {font-size:12px; color:#f8f6f6; bgcolor:#fafafa;}\n a, span { font-family: monospace; }\n span.addr {color:#fafafa; font-weight: bold;}\n table tr td {padding: 3px; border: 1px solid black; background-color: #fafafa;}\n td.d0 {font-weight: bold; color:#f8f6f6;}\n h2, h3 { white-space:nowrap; color:#fafafa;}\n a { color:#88f6f6; text-decoration:none; }\n a.nav {color:#fafafa;}\n";
QString FullContent = "<html><head><style type=\"text/css\">" + CSS + "</style></head>" + "<body>" + Content.c_str() + "</body></html>";
// printf(FullContent.toUtf8());
ui->content->setText(FullContent);
}
void BlockExplorer::back()
{
int NewIndex = m_HistoryIndex - 1;
if (0 <= NewIndex && NewIndex < m_History.size()) {
m_HistoryIndex = NewIndex;
ui->searchBox->setText(m_History[NewIndex]);
switchTo(m_History[NewIndex]);
updateNavButtons();
}
}
void BlockExplorer::forward()
{
int NewIndex = m_HistoryIndex + 1;
if (0 <= NewIndex && NewIndex < m_History.size()) {
m_HistoryIndex = NewIndex;
ui->searchBox->setText(m_History[NewIndex]);
switchTo(m_History[NewIndex]);
updateNavButtons();
}
}
void BlockExplorer::updateNavButtons()
{
ui->back->setEnabled(m_HistoryIndex - 1 >= 0);
ui->forward->setEnabled(m_HistoryIndex + 1 < m_History.size());
}
|
#include "serialization.h"
#include "table.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"
#include "zlib/zlib.h"
struct __table_json
{
rapidjson::Value root;
};
#define _TABLE_ROOT_NAME "root"
#define _FLOAT2_PREFIX "<float2>"
#define _FLOAT3_PREFIX "<float3>"
#define _FLOAT4_PREFIX "<float4>"
#define _FLOAT4X4_PREFIX "<float4x4>"
#define _USERDATA_PREFIX "<userdata>"
void _set_float2(rapidjson::Value& val, const Schema::float2& f2, MemoryIncrement& strpool)
{
char buff[128];
sprintf_s(buff, _countof(buff), "%s%.6f,%.6f", _FLOAT2_PREFIX, f2.x, f2.y);
unsigned len = (unsigned)strlen(buff);
char* addr = (char*)strpool.alloc(len);
if (addr)
{
memcpy(addr, buff, len);
val.SetString(addr, (rapidjson::SizeType)len);
}
}
void _set_float3(rapidjson::Value& val, const Schema::float3& f3, MemoryIncrement& strpool)
{
char buff[128];
sprintf_s(buff, _countof(buff), "%s%.6f,%.6f,%.6f", _FLOAT3_PREFIX, f3.x, f3.y, f3.z);
unsigned len = (unsigned)strlen(buff);
char* addr = (char*)strpool.alloc(len);
if (addr)
{
memcpy(addr, buff, len);
val.SetString(addr, (rapidjson::SizeType)len);
}
}
void _set_float4(rapidjson::Value& val, const Schema::float4& f4, MemoryIncrement& strpool)
{
char buff[128];
sprintf_s(buff, _countof(buff), "%s%.6f,%.6f,%.6f,%.6f", _FLOAT4_PREFIX, f4.x, f4.y, f4.z, f4.w);
unsigned len = (unsigned)strlen(buff);
char* addr = (char*)strpool.alloc(len);
if (addr)
{
memcpy(addr, buff, len);
val.SetString(addr, (rapidjson::SizeType)len);
}
}
void _set_float4x4(rapidjson::Value& val, const Schema::float4x4& f4x4, MemoryIncrement& strpool)
{
char buff[512];
sprintf_s(buff, _countof(buff)
, "%s%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f", _FLOAT4X4_PREFIX
, f4x4.m00, f4x4.m01, f4x4.m02, f4x4.m03
, f4x4.m10, f4x4.m11, f4x4.m12, f4x4.m13
, f4x4.m20, f4x4.m21, f4x4.m22, f4x4.m23
, f4x4.m30, f4x4.m31, f4x4.m32, f4x4.m33);
unsigned len = (unsigned)strlen(buff);
char* addr = (char*)strpool.alloc(len);
if (addr)
{
memcpy(addr, buff, len);
val.SetString(addr, (rapidjson::SizeType)len);
}
}
void _set_userdata(rapidjson::Value& val, void* ud, unsigned len, MemoryIncrement& strpool)
{
unsigned size = BASE64_ENCODE_OUT_SIZE(len);
size += (unsigned)strlen(_USERDATA_PREFIX) + 1;
char* buff = (char*)malloc(size);
if (buff)
{
memset(buff, 0, size);
strcpy_s(buff, size, _USERDATA_PREFIX);
base64_encode((const char*)ud, len, buff + strlen(_USERDATA_PREFIX));
len = (unsigned)strlen(buff);
char* addr = (char*)strpool.alloc(len);
if (addr)
{
memcpy(addr, buff, len);
val.SetString(addr, (rapidjson::SizeType)len);
}
free(buff);
}
}
int _tab2val(__table* ptab, rapidjson::Value& val, rapidjson::Document& doc, MemoryIncrement& strpool)
{
for (unsigned i = 0; i < ptab->_count; ++i)
{
__pair* pair = ptab->_elements[i];
assert(pair);
etvaltype vt = (etvaltype)pair->_cm.vt;
rapidjson::Value key;
key.SetString(pair->_key, cstr_len(pair->_key));
rapidjson::Value nval;
switch (vt)
{
case etvt_reserved:
case etvt_ptr:
case etvt_reference:
nval.SetNull();
break;
case etvt_int:
nval.SetInt(pair->_int);
break;
case etvt_uint:
nval.SetUint(pair->_uint);
break;
case etvt_int64:
nval.SetInt64(pair->_i64);
break;
case etvt_uint64:
nval.SetUint64(pair->_u64);
break;
case etvt_float:
nval.SetFloat(pair->_flt);
break;
case etvt_double:
nval.SetDouble(pair->_dbl);
break;
case etvt_float2:
_set_float2(nval, pair->_f2, strpool);
break;
case etvt_float3:
_set_float3(nval, pair->_f3, strpool);
break;
case etvt_float4:
_set_float4(nval, pair->_f4, strpool);
break;
case etvt_cstr:
nval.SetString(pair->_str, cstr_len(pair->_str));
break;
case etvt_table:
nval.SetObject();
_tab2val((__table*)pair->_ptr, nval, doc, strpool);
break;
case etvt_string:
{
const char* str = (const char*)pair->_ptr;
unsigned len = (unsigned)strlen(str);
char* addr = (char*)strpool.alloc(len);
if (!addr) continue;
memcpy(addr, str, len);
nval.SetString(addr, (rapidjson::SizeType)len);
}
break;
case etvt_float4x4:
_set_float4x4(nval, *(Schema::float4x4*)pair->_ptr, strpool);
break;
case etvt_userdata:
_set_userdata(nval, pair->_userdata.ptr, pair->_userdata.size, strpool);
break;
default:
break;
}
val.AddMember(key, nval, doc.GetAllocator());
}
return true;
}
int _parse_string(__table* ptab, c_str key, const char* val)
{
if (val[0] != '<')
{
c_str str = cstr_string(val);
table_set_cstr(ptab, key, str, 0);
return true;
}
static size_t _float2_length = strlen(_FLOAT2_PREFIX);
static size_t _float3_length = strlen(_FLOAT3_PREFIX);
static size_t _float4_length = strlen(_FLOAT4_PREFIX);
static size_t _float4x4_length = strlen(_FLOAT4X4_PREFIX);
static size_t _userdata_length = strlen(_USERDATA_PREFIX);
if (strncmp(val, _FLOAT2_PREFIX, _float2_length) == 0)
{
const char* buff = val + _float2_length;
Schema::float2 f2;
sscanf_s(buff, "%f,%f", &f2.x, &f2.y);
table_set_float2(ptab, key, (float*)f2.ptr(), 0);
}
else if (strncmp(val, _FLOAT3_PREFIX, _float3_length) == 0)
{
const char* buff = val + _float3_length;
Schema::float3 f3;
sscanf_s(buff, "%f,%f,%f", &f3.x, &f3.y, &f3.z);
table_set_float3(ptab, key, (float*)f3.ptr(), 0);
}
else if (strncmp(val, _FLOAT4_PREFIX, _float4_length) == 0)
{
const char* buff = val + _float4_length;
Schema::float4 f4;
sscanf_s(buff, "%f,%f,%f,%f", &f4.x, &f4.y, &f4.z, &f4.w);
table_set_float4(ptab, key, (float*)f4.ptr(), 0);
}
else if (strncmp(val, _FLOAT4X4_PREFIX, _float4x4_length) == 0)
{
const char* buff = val + _float4x4_length;
Schema::float4x4 f4x4;
sscanf_s(buff
, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f"
, &f4x4.m00, &f4x4.m01, &f4x4.m02, &f4x4.m03
, &f4x4.m10, &f4x4.m11, &f4x4.m12, &f4x4.m13
, &f4x4.m20, &f4x4.m21, &f4x4.m22, &f4x4.m23
, &f4x4.m30, &f4x4.m31, &f4x4.m32, &f4x4.m33);
table_set_float4x4(ptab, key, (float*)f4x4.ptr(), 0);
}
else if (strncmp(val, _USERDATA_PREFIX, _userdata_length) == 0)
{
const char* buff = val + _userdata_length;
unsigned len = (unsigned)strlen(buff);
unsigned size = BASE64_DECODE_OUT_SIZE(len);
char* out = (char*)malloc(size + 1);
if (out)
{
len = (unsigned)base64_decode(buff, len, out);
if (len > 0)
{
table_set_userdata(ptab, key, out, len, 0);
}
}
}
else
{
c_str str = cstr_string(val);
table_set_cstr(ptab, key, str, 0);
}
return true;
}
int _val2tab(const rapidjson::Value& val, __table* ptab)
{
for (rapidjson::Value::ConstMemberIterator it = val.MemberBegin(); it != val.MemberEnd(); ++it)
{
rapidjson::Type typ = it->value.GetType();
c_str key = cstr_string(it->name.GetString());
if (!key || key[0] == 0) continue;
switch (typ)
{
case rapidjson::kNullType:
table_reserve(ptab, key);
break;
case rapidjson::kFalseType:
table_set_integer(ptab, key, 0, 0);
break;
case rapidjson::kTrueType:
table_set_integer(ptab, key, 1, 0);
break;
case rapidjson::kObjectType:
{
__table* psubtab = (__table*)table_set(ptab, key, 0);
if (psubtab) _val2tab(it->value, psubtab);
}
break;
case rapidjson::kArrayType:
break;
case rapidjson::kStringType:
_parse_string(ptab, key, it->value.GetString());
break;
case rapidjson::kNumberType:
{
const rapidjson::Value& nval = it->value;
if (nval.IsInt()) table_set_integer(ptab, key, nval.GetInt(), 0);
else if (nval.IsUint()) table_set_uint(ptab, key, nval.GetUint(), 0);
else if (nval.IsInt64()) table_set_int64(ptab, key, nval.GetInt64(), 0);
else if (nval.IsUint64()) table_set_uint64(ptab, key, nval.GetUint64(), 0);
else if (nval.IsFloat()) table_set_float(ptab, key, nval.GetFloat(), 0);
else if (nval.IsDouble()) table_set_double(ptab, key, nval.GetDouble(), 0);
}
break;
default:
break;
}
}
return true;
}
htabj tabj_from(__table* ptab)
{
__table_json* ptabj = new(std::nothrow) __table_json();
if (!ptabj) return 0;
MemoryIncrement strpool;
rapidjson::Document doc;
rapidjson::Value& val = ptabj->root;
val.SetObject();
if (!_tab2val(ptab, val, doc, strpool))
{
delete ptabj;
ptabj = 0;
}
return ptabj;
}
void tabj_free(htabj htj)
{
__table_json* ptabj = (__table_json*)htj;
if (ptabj)
{
delete ptabj;
ptabj = nullptr;
}
}
__table* tabj_to(htabj htj)
{
__table_json* ptabj = (__table_json*)htj;
if (!ptabj) return nullptr;
rapidjson::Value& val = ptabj->root;
__table* ptab = (__table*)table_create();
if (!ptab) return nullptr;
if (!_val2tab(val, ptab))
{
table_destroy(ptab);
ptab = nullptr;
}
return ptab;
}
htabj tabj_read(const char* filename)
{
__table_json* ptabj = nullptr;
Schema::hfile hf = _fopenread(filename);
char* buff = nullptr;
if (!hf) return 0;
int flag = false;
do
{
unsigned len = _flength(hf);
if (len == 0) break;
len += 1;
buff = (char*)malloc(len);
if (!buff) break;
_fread(hf, buff, len);
buff[len] = 0;
ptabj = new(std::nothrow) __table_json();
if (!ptabj) break;
try
{
rapidjson::StringStream ss(buff);
rapidjson::Document doc;
doc.ParseStream<rapidjson::kParseCommentsFlag>(ss);
//ptabj->root = doc.GetObjectA();
/*if (doc.FindMember(_TABLE_ROOT_NAME) == doc.MemberEnd()) break;
ptabj->root = doc[_TABLE_ROOT_NAME];*/
}
catch (const std::exception&) { break; }
flag = true;
} while (0);
if (!flag)
{
if (ptabj)
{
delete ptabj;
ptabj = nullptr;
}
}
if (buff) { free(buff); buff = nullptr; }
if (hf) { _fclose(hf); hf = 0; }
return (htabj)ptabj;
}
int tabj_save(htabj htj, const char* filename)
{
__table_json* ptabj = (__table_json*)htj;
Schema::hfile hf = 0;
int flag = false;
do
{
if (!ptabj) break;
rapidjson::StringBuffer buff;
try
{
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buff);
ptabj->root.Accept(writer);
}
catch (const std::exception&) { break; }
const char* pbuf = buff.GetString();
unsigned len = (unsigned)buff.GetSize();
hf = _fopenwrite(filename);
if (!hf) break;
_fwrite(hf, (void*)pbuf, len);
flag = true;
} while (0);
if (hf) { _fclose(hf); hf = 0; }
return flag;
}
#define _ttObjectBegin "{"
#define _ttObjectBeginLen 1
#define _ttObjectEnd "}"
#define _ttObjectEndLen 1
#define _ttPrettyObjectBegin "{\n"
#define _ttPrettyObjectBeginLen 2
#define _ttPrettyObjectEnd "}\n"
#define _ttPrettyObjectEndLen 2
#define _ttIndent "\t"
#define _ttIndentLen 1
#define _ttSeparator "="
#define _ttSeparatorLen 1
#define _ttPrettySeparator " = "
#define _ttPrettySeparatorLen 3
#define _ttStringBegin "\""
#define _ttStringBeginLen 1
#define _ttStringEnd "\""
#define _ttStringEndLen 1
#define _ttNull "null"
#define _ttNullLen 4
#define _ttLineEnd "\n"
#define _ttLineEndLen 1
#include <set>
struct __table_txt
{
MemoryIncrement _strpool;
std::set<void*> _refs;
int _pretty;
};
typedef __table_txt tabt;
inline int _ttAppend(tabt* ptabt, const char* str, unsigned len) { return ptabt->_strpool.set(str, len) ? true : false; }
inline int _ttAppendIndent(tabt* ptabt, int layer) { for (int i = 0; i < layer; ++i) if (!ptabt->_strpool.set(_ttIndent, _ttIndentLen)) return false; return true; }
inline int _ttAddObjectBegin(tabt* ptabt, int layer)
{
if (ptabt->_pretty)
{
return _ttAppend(ptabt, _ttPrettyObjectBegin, _ttPrettyObjectBeginLen);
}
return _ttAppend(ptabt, _ttObjectBegin, _ttObjectBeginLen);
}
inline int _ttAddObjectEnd(tabt* ptabt, int layer)
{
if (ptabt->_pretty)
{
if (!_ttAppendIndent(ptabt, layer)) return false;
return _ttAppend(ptabt, _ttPrettyObjectEnd, _ttPrettyObjectEndLen);
}
return _ttAppend(ptabt, _ttObjectEnd, _ttObjectEndLen);
}
inline int _ttAddKey(tabt* ptabt, const char* key, unsigned len, int layer)
{
int rst = false;
do {
register int pretty = ptabt->_pretty;
if (pretty && !_ttAppendIndent(ptabt, layer)) break;
if (!_ttAppend(ptabt, _ttStringBegin, _ttStringBeginLen)) break;
if (!_ttAppend(ptabt, key, len)) break;
if (!_ttAppend(ptabt, _ttStringEnd, _ttStringEndLen)) break;
if (pretty) { if (!_ttAppend(ptabt, _ttPrettySeparator, _ttPrettySeparatorLen)) break; }
else { if (!_ttAppend(ptabt, _ttSeparator, _ttSeparatorLen)) break; }
rst = true;
} while (0);
return rst;
}
inline int _ttAddNull(tabt* ptabt) { if (!_ttAppend(ptabt, _ttNull, _ttNullLen)) return false; if (ptabt->_pretty) return _ttAppend(ptabt, _ttLineEnd, _ttLineEndLen); return true; }
inline int _ttAddValue(tabt* ptabt, const char* buff) { if (!_ttAppend(ptabt, buff, (unsigned)strlen(buff))) return false; if (ptabt->_pretty) return _ttAppend(ptabt, _ttLineEnd, _ttLineEndLen); return true; }
inline int _ttAddPtr(tabt* ptabt, void* ptr) { char buff[64]; sprintf_s(buff, _countof(buff), "P%llx", uint64(ULONG_PTR(ptr))); return _ttAddValue(ptabt, buff); }
inline int _ttAddInt(tabt* ptabt, int n) { char buff[32]; sprintf_s(buff, _countof(buff), "I%d", n); return _ttAddValue(ptabt, buff); }
inline int _ttAddUint(tabt* ptabt, unsigned u) { char buff[32]; sprintf_s(buff, _countof(buff), "U%u", u); return _ttAddValue(ptabt, buff); }
inline int _ttAddInt64(tabt* ptabt, int64 ll) { char buff[32]; sprintf_s(buff, _countof(buff), "L%lld", ll); return _ttAddValue(ptabt, buff); }
inline int _ttAddUint64(tabt* ptabt, uint64 ull) { char buff[32]; sprintf_s(buff, _countof(buff), "UL%llu", ull); return _ttAddValue(ptabt, buff); }
inline int _ttAddFloat(tabt* ptabt, float f) { char buff[64]; sprintf_s(buff, _countof(buff), "F%f", f); return _ttAddValue(ptabt, buff); }
inline int _ttAddDouble(tabt* ptabt, double d) { char buff[128]; sprintf_s(buff, _countof(buff), "D%.12lf", d); return _ttAddValue(ptabt, buff); }
inline int _ttAddFloat2(tabt* ptabt, Schema::float2& f2) { char buff[128]; sprintf_s(buff, _countof(buff), "<float2>%f,%f", f2.x, f2.y); return _ttAddValue(ptabt, buff); }
inline int _ttAddFloat3(tabt* ptabt, Schema::float3& f3) { char buff[256]; sprintf_s(buff, _countof(buff), "<float3>%f,%f,%f", f3.x, f3.y, f3.z); return _ttAddValue(ptabt, buff); }
inline int _ttAddFloat4(tabt* ptabt, Schema::float4& f4) { char buff[256]; sprintf_s(buff, _countof(buff), "<float4>%f,%f,%f,%f", f4.x, f4.y, f4.z, f4.w); return _ttAddValue(ptabt, buff); }
inline int _ttAddBool(tabt* ptabt, bool b) { if (b) return _ttAddValue(ptabt, "true"); return _ttAddValue(ptabt, "false"); }
inline int _ttAddFloat4x4(tabt* ptabt, Schema::float4x4& f4x4)
{
char buff[1024];
sprintf_s(buff, _countof(buff)
, "<float4x4>%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f"
, f4x4.m00, f4x4.m01, f4x4.m02, f4x4.m03
, f4x4.m10, f4x4.m11, f4x4.m12, f4x4.m13
, f4x4.m20, f4x4.m21, f4x4.m22, f4x4.m23
, f4x4.m30, f4x4.m31, f4x4.m32, f4x4.m33);
return _ttAddValue(ptabt, buff);
}
inline int _ttAddString(tabt* ptabt, const char* str, unsigned len)
{
int rst = false;
do {
if (!_ttAppend(ptabt, _ttStringBegin, _ttStringBeginLen)) break;
void* ptr = ptabt->_strpool.alloc(len);
if (!ptr) break;
memcpy(ptr, str, len);
if (!_ttAppend(ptabt, _ttStringEnd, _ttStringEndLen)) break;
if (ptabt->_pretty) { if (!_ttAppend(ptabt, _ttLineEnd, _ttLineEndLen)) break; }
rst = true;
} while (0);
return rst;
}
inline int _ttAddUserdata(tabt* ptabt, void* ud, unsigned len)
{
int rst = false;
char* buff = nullptr;
do {
unsigned size = BASE64_ENCODE_OUT_SIZE(len);
size += (unsigned)strlen(_USERDATA_PREFIX) + 1;
buff = (char*)malloc(size);
if (!buff) break;
memset(buff, 0, size);
strcpy_s(buff, size, _USERDATA_PREFIX);
len = base64_encode((const char*)ud, len, buff + strlen(_USERDATA_PREFIX));
len += (unsigned)strlen(_USERDATA_PREFIX);
if (!_ttAppend(ptabt, buff, len)) break;
if (ptabt->_pretty) { if (!_ttAppend(ptabt, _ttLineEnd, _ttLineEndLen)) break; }
rst = true;
} while (0);
if (buff) free(buff);
return true;
}
int _tab2tabt(__table* ptab, tabt* ptabt, int layer)
{
for (unsigned i = 0; i < ptab->_count; ++i)
{
__pair* pair = ptab->_elements[i];
assert(pair);
if (!_ttAddKey(ptabt, pair->_key, cstr_len(pair->_key), layer)) return false;
etvaltype vt = (etvaltype)pair->_cm.vt;
switch (vt)
{
case etvt_reserved:
if (!_ttAddNull(ptabt)) return false;
break;
case etvt_ptr:
if (!_ttAddPtr(ptabt, pair->_ptr)) return false;
break;
case etvt_int:
if (!_ttAddInt(ptabt, pair->_int)) return false;
break;
case etvt_uint:
if (!_ttAddUint(ptabt, pair->_uint)) return false;
break;
case etvt_int64:
if (!_ttAddInt64(ptabt, pair->_i64)) return false;
break;
case etvt_uint64:
if (!_ttAddUint64(ptabt, pair->_u64)) return false;
break;
case etvt_float:
if (!_ttAddFloat(ptabt, pair->_flt)) return false;
break;
case etvt_double:
if (!_ttAddDouble(ptabt, pair->_dbl)) return false;
break;
case etvt_float2:
if (!_ttAddFloat2(ptabt, pair->_f2)) return false;
break;
case etvt_float3:
if (!_ttAddFloat3(ptabt, pair->_f3)) return false;
break;
case etvt_float4:
if (!_ttAddFloat4(ptabt, pair->_f4)) return false;
break;
case etvt_bool:
if (!_ttAddBool(ptabt, pair->_bl)) return false;
break;
case etvt_cstr:
if (!_ttAddString(ptabt, pair->_str, cstr_len(pair->_str))) return false;
break;
case etvt_reference:
if (ptabt->_refs.find(pair->_ptr) != ptabt->_refs.end()) break;
case etvt_table:
ptabt->_refs.insert(pair->_ptr);
if (!_ttAddObjectBegin(ptabt, layer)) return false;
if (!_tab2tabt((__table*)pair->_ptr, ptabt, layer + 1)) return false;
if (!_ttAddObjectEnd(ptabt, layer)) return false;
break;
case etvt_string:
{
const char* str = (const char*)pair->_ptr;
unsigned len = (unsigned)strlen(str);
if (!_ttAddString(ptabt, str, len)) return false;
}
break;
case etvt_float4x4:
if (!_ttAddFloat4x4(ptabt, *(Schema::float4x4*)pair->_ptr)) return false;
break;
case etvt_userdata:
if (!_ttAddUserdata(ptabt, pair->_userdata.ptr, pair->_userdata.size)) return false;
break;
default:
break;
}
}
return true;
}
#include "_g.h"
#define _ttRead(v, c) { c = 0; ch = *buff; while (ch != v && ch != EOF) ch = *(++buff), ++c; if (ch == EOF) return nullptr; }
#define _ttTrim() { ch = *buff; while (char_blank(ch) && ch != EOF) ch = *(++buff); if (ch == EOF) return nullptr; }
#define _ttIsNumeric(c) (c >= '0' && c <= '9')
#define _ttIsNumericX(c) (_ttIsNumeric(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
#define _ttIsNumericI(c) (_ttIsNumeric(c) || (c == '-'))
#define _ttIsNumericF(c) (_ttIsNumericI(c) || (c == '.'))
#define _ttIsNumericV(c) (_ttIsNumericF(c) || (c == ','))
inline int _ttParseString(const char* str, unsigned len, __table* ptab, c_str key)
{
if (len < 2) return false;
register char ch0 = str[0];
register char ch1 = str[1];
register char ch = 0;
char buff[1024];
if (len >= 4 && ch0 == 'n' && ch1 == 'u' && str[2] == 'l' && str[3] == 'l')
{
table_reserve(ptab, key);
}
else if (len >= 4 && ch0 == 't' && ch1 == 'r' && str[2] == 'u' && str[3] == 'e')
{
table_set_bool(ptab, key, true, 0);
}
else if (len >= 5 && ch0 == 'f' && ch1 == 'a' && str[2] == 'l' && str[3] == 's' && str[4] == 'e')
{
table_set_bool(ptab, key, false, 0);
}
else if (ch0 == 'P')
{
unsigned cnt = 0;
for (unsigned i = 1; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericX(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 16) return false;
memcpy(buff, str + 1, cnt);
buff[cnt] = 0;
void* ptr = 0;
if (1 != sscanf_s(buff, "%llx", (uint64*)&ptr)) return false;
table_set_ptr(ptab, key, ptr, 0);
}
else if (ch0 == 'I')
{
unsigned cnt = 0;
for (unsigned i = 1; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericI(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 11) return false;
memcpy(buff, str + 1, cnt);
buff[cnt] = 0;
int val = 0;
if (1 != sscanf_s(buff, "%d", &val)) return false;
table_set_integer(ptab, key, val, 0);
}
else if (ch0 == 'U' && ch1 != 'L')
{
unsigned cnt = 0;
for (unsigned i = 1; i < len; ++i)
{
ch = str[i];
if (_ttIsNumeric(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 10) return false;
memcpy(buff, str + 1, cnt);
buff[cnt] = 0;
unsigned val = 0;
if (1 != sscanf_s(buff, "%u", &val)) return false;
table_set_uint(ptab, key, val, 0);
}
else if (ch0 == 'L')
{
unsigned cnt = 0;
for (unsigned i = 1; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericI(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 20) return false;
memcpy(buff, str + 1, cnt);
buff[cnt] = 0;
int64 val = 0;
if (1 != sscanf_s(buff, "%lld", &val)) return false;
table_set_int64(ptab, key, val, 0);
}
else if (ch0 == 'U' && ch1 == 'L')
{
unsigned cnt = 0;
for (unsigned i = 2; i < len; ++i)
{
ch = str[i];
if (_ttIsNumeric(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 20) return false;
memcpy(buff, str + 2, cnt);
buff[cnt] = 0;
uint64 val = 0;
if (1 != sscanf_s(buff, "%llu", &val)) return false;
table_set_uint64(ptab, key, val, 0);
}
else if (ch0 == 'F')
{
unsigned cnt = 0;
for (unsigned i = 1; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericF(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 1023) return false;
memcpy(buff, str + 1, cnt);
buff[cnt] = 0;
float val = 0;
if (1 != sscanf_s(buff, "%f", &val)) return false;
table_set_float(ptab, key, val, 0);
}
else if (ch0 == 'D')
{
unsigned cnt = 0;
for (unsigned i = 1; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericF(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 1023) return false;
memcpy(buff, str + 1, cnt);
buff[cnt] = 0;
double val = 0;
if (1 != sscanf_s(buff, "%lf", &val)) return false;
table_set_double(ptab, key, val, 0);
}
else if (len > 8 && ch0 == '<' && ch1 == 'f' && str[2] == 'l' && str[3] == 'o' && str[4] == 'a' && str[5] == 't')
{
if (str[6] == '2' && str[7] == '>')
{
unsigned cnt = 0;
for (unsigned i = 8; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericV(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 1023) return false;
memcpy(buff, str + 8, cnt);
buff[cnt] = 0;
Schema::float2 f2;
if (2 != sscanf_s(buff, "%f,%f", &f2.x, &f2.y)) return false;
table_set_float2(ptab, key, (float*)f2.ptr(), 0);
}
else if (str[6] == '3' && str[7] == '>')
{
unsigned cnt = 0;
for (unsigned i = 8; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericV(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 1023) return false;
memcpy(buff, str + 8, cnt);
buff[cnt] = 0;
Schema::float3 f3;
if (3 != sscanf_s(buff, "%f,%f,%f", &f3.x, &f3.y, &f3.z)) return false;
table_set_float3(ptab, key, (float*)f3.ptr(), 0);
}
else if (str[6] == '4' && str[7] == '>')
{
unsigned cnt = 0;
for (unsigned i = 8; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericV(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 1023) return false;
memcpy(buff, str + 8, cnt);
buff[cnt] = 0;
Schema::float4 f4;
if (4 != sscanf_s(buff, "%f,%f,%f,%f", &f4.x, &f4.y, &f4.z, &f4.w)) return false;
table_set_float4(ptab, key, (float*)f4.ptr(), 0);
}
else if (len > 10 && str[6] == '4' && str[7] == 'x' && str[8] == '4' && str[9] == '>')
{
unsigned cnt = 0;
for (unsigned i = 10; i < len; ++i)
{
ch = str[i];
if (_ttIsNumericV(ch)) cnt++;
else break;
}
if (cnt == 0 || cnt > 1023) return false;
memcpy(buff, str + 10, cnt);
buff[cnt] = 0;
Schema::float4x4 f4x4;
if (16 != sscanf_s(buff
, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f"
, &f4x4.m00, &f4x4.m01, &f4x4.m02, &f4x4.m03
, &f4x4.m10, &f4x4.m11, &f4x4.m12, &f4x4.m13
, &f4x4.m20, &f4x4.m21, &f4x4.m22, &f4x4.m23
, &f4x4.m30, &f4x4.m31, &f4x4.m32, &f4x4.m33)) return false;
table_set_float4x4(ptab, key, (float*)f4x4.ptr(), 0);
}
else return false;
}
else if (len > 10 && strncmp(str, _USERDATA_PREFIX, strlen(_USERDATA_PREFIX)) == 0)
{
unsigned cnt = 0;
for (unsigned i = 10; i < len; ++i)
{
ch = str[i];
if (base64_validate(ch)) cnt++;
else break;
}
if (cnt == 0) return false;
//unsigned size = BASE64_DECODE_OUT_SIZE(cnt);
unsigned size = cnt;
char* ud = (char*)malloc(size);
if (!ud) return false;
size = base64_decode(str + 10, cnt, ud);
if (size == 0)
{
free(ud);
return false;
}
table_set_userdata(ptab, key, ud, size, 0);
free(ud);
}
else return false;
return true;
}
const char* _ttParse(const char* buff, __table* ptab)
{
char ch = *buff;
while (ch != '}' && ch != EOF)
{
unsigned len = 0;
ch = *buff;
while (ch != EOF && ch != '\"' && ch != '}') ch = *(++buff);
if (ch == EOF) return nullptr;
if (ch == '}') break;
++buff;
const char* str = buff;
_ttRead('\"', len); ++buff;
if (len == 0) return nullptr;
c_str skey = cstr_stringl(str, len);
_ttRead('=', len); ++buff;
_ttTrim();
if (ch == '{')
{
ch = *(++buff);
__table* psubtab = (__table*)table_set(ptab, skey, 0);
if (!psubtab) return nullptr;
buff = _ttParse(buff, psubtab);
if (!buff) return nullptr;
}
else if (ch == '\"')
{
ch = *(++buff);
str = buff;
_ttRead('\"', len); ++buff;
ptab->set(skey, str, len, 0);
}
else
{
str = buff;
len = 0;
while (ch != EOF && ch != '}' && ch != '\"') ch = *(++buff), ++len;
if (ch == EOF) return nullptr;
if (!_ttParseString(str, len, ptab, skey)) return nullptr;
}
}
if (ch == EOF) return nullptr;
++buff;
return buff;
}
htabtxt tabtxt_from(__table* ptab, int pretty)
{
tabt* ptabt = new(std::nothrow) tabt();
if (!ptabt) return 0;
ptabt->_pretty = pretty;
ptabt->_refs.insert(ptab);
_ttAddObjectBegin(ptabt, 0);
if (!_tab2tabt(ptab, ptabt, 1)) { delete ptabt; return 0; }
_ttAddObjectEnd(ptabt, 0);
return (htabtxt)ptabt;
}
ttrd tabtxt_read(const char* filename)
{
ttrd td = { 0 };
Schema::hfile hf = _fopenread(filename);
char* buff = nullptr;
if (!hf) return td;
int flag = false;
do
{
unsigned len = _flength(hf);
if (len == 0) break;
buff = (char*)malloc(len + 1);
if (!buff) break;
_fread(hf, buff, len);
buff[len] = EOF;
td._addr = buff;
td._size = len + 1;
flag = true;
} while (0);
if (!flag)
{
if (buff) { free(buff); buff = 0; }
td._addr = 0;
td._size = 0;
}
if (hf) { _fclose(hf); hf = 0; }
return td;
}
void tabtxt_free_ttrd(ttrd dt)
{
if (dt._addr)
{
free(dt._addr);
dt._addr = 0;
dt._size = 0;
}
}
void tabtxt_free(htabtxt htt)
{
tabt* ptabt = (tabt*)htt;
if (ptabt) { delete ptabt; ptabt = nullptr; }
}
int tabtxt_save(htabtxt htt, const char* filename)
{
__table_txt* ptabt = (__table_txt*)htt;
Schema::hfile hf = 0;
int flag = false;
do
{
if (!ptabt) break;
hf = _fopenwrite(filename);
if (!hf) break;
FArray<ttrd> arr;
for (void* ptr = ptabt->_strpool.travel(0); ptr != nullptr; ptr = ptabt->_strpool.travel(ptr))
{
const char* buff = ptabt->_strpool.getPtr(ptr);
unsigned size = ptabt->_strpool.getSize(ptr);
ttrd td = { (void*)buff, size };
arr.Push(td);
}
if (arr.Count() == 0) break;
for (unsigned i = arr.Count(); i > 0; --i)
{
ttrd td = arr[i - 1];
if (td._addr)
{
_fwrite(hf, td._addr, td._size);
}
}
flag = true;
} while (0);
if (hf) { _fclose(hf); hf = 0; }
return flag;
}
__table*tabtxt_to(ttrd dt)
{
__table* ptab = (__table*)table_create();
if (!ptab) return nullptr;
if (!_ttParse((const char*)dt._addr, ptab))
{
table_destroy(ptab);
ptab = nullptr;
}
return ptab;
}
struct __table_bin
{
MemoryIncrement _buffpool;
std::set<void*> _refs;
};
struct __table_bin_header
{
fourcc fcc;
fourcc version;
unsigned length;
unsigned compress_length;
};
#define _tbAppend(p, l) if (!ptabb->_buffpool.set((void*)p, l)) return -1; size += l
unsigned _tab2tabb(__table* ptab, __table_bin* ptabb)
{
unsigned size = 0;
for (unsigned i = 0; i < ptab->_count; ++i)
{
__pair* pair = ptab->_elements[i];
assert(pair);
c_str key = pair->_key;
unsigned len = cstr_len(key) + 1;
_tbAppend(key, len);
etvaltype vt = (etvaltype)pair->_cm.vt;
_tbAppend(&vt, sizeof(uint8));
switch (vt)
{
case etvt_reserved: break;
case etvt_ptr: _tbAppend(&pair->_ptr, sizeof(void*)); break;
case etvt_int: _tbAppend(&pair->_int, sizeof(int)); break;
case etvt_uint: _tbAppend(&pair->_uint, sizeof(uint)); break;
case etvt_int64: _tbAppend(&pair->_i64, sizeof(int64)); break;
case etvt_uint64: _tbAppend(&pair->_u64, sizeof(uint64)); break;
case etvt_float: _tbAppend(&pair->_flt, sizeof(float)); break;
case etvt_double: _tbAppend(&pair->_dbl, sizeof(double)); break;
case etvt_float2: _tbAppend(pair->_f2.ptr(), sizeof(Schema::float2)); break;
case etvt_float3: _tbAppend(pair->_f3.ptr(), sizeof(Schema::float3)); break;
case etvt_float4: _tbAppend(pair->_f4.ptr(), sizeof(Schema::float4)); break;
case etvt_cstr: _tbAppend(pair->_str, cstr_len(pair->_str) + 1); break;
case etvt_bool: _tbAppend(&pair->_bl, sizeof(bool)); break;
case etvt_reference:
if (ptabb->_refs.find(pair->_ptr) != ptabb->_refs.end())
{
unsigned val = -1;
_tbAppend(&val, sizeof(unsigned));
break;
}
case etvt_table:
{
unsigned* psize = (unsigned*)ptabb->_buffpool.alloc(sizeof(unsigned));
if (!psize) return -1;
unsigned u = _tab2tabb((__table*)pair->_ptr, ptabb);
if (u == -1) return -1;
*psize = u;
size += u;
}
break;
case etvt_string:
{
const char* str = (const char*)pair->_ptr;
len = (unsigned)strlen(str) + 1;
_tbAppend(str, len);
}
break;
case etvt_float4x4:
{
Schema::float4x4* f4x4 = (Schema::float4x4*)pair->_ptr;
_tbAppend(f4x4->ptr(), sizeof(Schema::float4x4));
}
break;
case etvt_userdata:
_tbAppend(&pair->_userdata.size, sizeof(unsigned));
_tbAppend(pair->_userdata.ptr, pair->_userdata.size);
break;
}
}
return size;
}
#define _tbParseValue(t, fn) { t val = *(t*)(buff + offset); offset += sizeof(t); fn(ptab, skey, val, 0); }
#define _tbParseVector(t, fn) { float* arr = (float*)(buff + offset); offset += sizeof(t); fn(ptab, skey, arr, 0); }
int _tbParse(__table* ptab, byte* buff, unsigned len)
{
unsigned offset = 0;
while (offset < len)
{
const char* key = (const char*)(buff + offset);
unsigned size = 0;
while (size + offset < len && key[size]) size++;
if (size + offset == len || size == 0) return false;
c_str skey = cstr_string(key);
offset += size + 1;
size = *(uint8*)(buff + offset);
offset += sizeof(uint8);
etvaltype vt = (etvaltype)size;
switch (vt)
{
case etvt_reserved: table_reserve(ptab, skey); break;
case etvt_ptr: _tbParseValue(void*, table_set_ptr); break;
case etvt_int: _tbParseValue(int, table_set_integer); break;
case etvt_uint: _tbParseValue(uint, table_set_uint); break;
case etvt_int64: _tbParseValue(int64, table_set_int64); break;
case etvt_uint64: _tbParseValue(uint64, table_set_uint64); break;
case etvt_float: _tbParseValue(float, table_set_float); break;
case etvt_double: _tbParseValue(double, table_set_double); break;
case etvt_float2: _tbParseVector(Schema::float2, table_set_float2); break;
case etvt_float3: _tbParseVector(Schema::float3, table_set_float3); break;
case etvt_float4: _tbParseVector(Schema::float4, table_set_float4); break;
case etvt_bool: _tbParseValue(bool, table_set_bool); break;
case etvt_cstr:
{
size = 0;
const char* val = (const char*)(buff + offset);
while (size + offset < len && val[size]) size++;
if (size + offset == len) return false;
offset += size + 1;
c_str sval = cstr_string(val);
table_set_cstr(ptab, skey, sval, 0);
}
break;
case etvt_reference:
case etvt_table:
{
size = *(unsigned*)(buff + offset);
offset += sizeof(unsigned);
if (size == -1) break;
__table* psub = (__table*)table_set(ptab, skey, 0);
if (!psub) return false;
if (!_tbParse(psub, buff + offset, size)) return false;
offset += size;
}
break;
case etvt_string:
{
size = 0;
const char* val = (const char*)(buff + offset);
while (size + offset < len && val[size]) size++;
if (size + offset == len) return false;
offset += size + 1;
table_set_string(ptab, skey, val, 0);
}
break;
case etvt_float4x4: _tbParseVector(Schema::float4x4, table_set_float4x4); break;
case etvt_userdata:
{
size = *(unsigned*)(buff + offset);
offset += sizeof(unsigned);
table_set_userdata(ptab, skey, buff + offset, size, 0);
offset += size;
}
break;
}
}
return true;
}
htabbin tabbin_from(__table* ptab)
{
__table_bin* ptabb = new(std::nothrow) __table_bin();
if (!ptabb) return 0;
ptabb->_refs.insert(ptab);
unsigned* psize = (unsigned*)ptabb->_buffpool.alloc(sizeof(unsigned));
if (psize)
{
unsigned size = _tab2tabb(ptab, ptabb);
if (size != -1)
{
*psize = size;
return ptabb;
}
}
delete ptabb;
return 0;
}
void tabbin_free(htabbin htb)
{
__table_bin* ptabb = (__table_bin*)htb;
if (ptabb)
{
delete ptabb;
ptabb = nullptr;
}
}
int tabbin_save(htabbin htb, const char* filename)
{
__table_bin* ptabb = (__table_bin*)htb;
Schema::hfile hf = 0;
byte* buff = nullptr;
byte* cmprs = nullptr;
int flag = false;
do
{
if (!ptabb) break;
hf = _fopenwrite(filename);
if (!hf) break;
unsigned len = 0;
__table_bin_header header = { 0 };
header.fcc = 'tabb';
header.version = 'V000';
FArray<ttrd> arr;
for (void* ptr = ptabb->_buffpool.travel(0); ptr != nullptr; ptr = ptabb->_buffpool.travel(ptr))
{
const char* buff = ptabb->_buffpool.getPtr(ptr);
unsigned size = ptabb->_buffpool.getSize(ptr);
len += size;
ttrd td = { (void*)buff, size };
arr.Push(td);
}
header.length = len;
buff = (byte*)malloc(len);
cmprs = (byte*)malloc(len);
if (!buff || !cmprs) break;
if (arr.Count() == 0) break;
len = 0;
for (unsigned i = arr.Count(); i > 0; --i)
{
ttrd td = arr[i - 1];
memcpy(buff + len, td._addr, td._size);
len += td._size;
}
if (Z_OK != compress((Bytef*)cmprs, (uLongf*)&len, (Bytef*)buff, len)) break;
header.compress_length = len;
_fwrite(hf, &header, sizeof(__table_bin_header));
_fwrite(hf, cmprs, len);
flag = true;
} while (0);
if (cmprs) { free(cmprs); cmprs = nullptr; }
if (buff) { free(buff); buff = nullptr; }
if (hf) { _fclose(hf); hf = 0; }
return flag;
}
ttrd tabbin_read(const char* filename)
{
ttrd td = { 0 };
Schema::hfile hf = _fopenread(filename);
char* buff = nullptr;
char* unbuff = nullptr;
if (!hf) return td;
int flag = false;
do
{
unsigned len = _flength(hf);
if (len == 0 || len < sizeof(__table_bin_header)) break;
buff = (char*)malloc(len);
if (!buff) break;
_fread(hf, buff, len);
__table_bin_header* pheader = (__table_bin_header*)buff;
if (pheader->compress_length != len - sizeof(__table_bin_header)) break;
if (pheader->length < pheader->compress_length) break;
if (pheader->fcc != 'tabb') break;
unbuff = (char*)malloc(pheader->length);
if (!unbuff) break;
unsigned dstlen = pheader->length;
unsigned srclen = pheader->compress_length;
if (Z_OK != uncompress((Bytef*)unbuff, (uLongf*)&dstlen, (Bytef*)(buff + sizeof(__table_bin_header)), (uLong)srclen)) break;
td._addr = unbuff;
td._size = dstlen;
flag = true;
} while (0);
if (!flag)
{
if (unbuff) { free(unbuff); unbuff = 0; }
td._addr = 0;
td._size = 0;
}
if (buff) { free(buff); buff = 0; }
if (hf) { _fclose(hf); hf = 0; }
return td;
}
void tabbin_free_ttrd(ttrd td)
{
if (td._addr)
{
free(td._addr);
td._addr = 0;
td._size = 0;
}
}
__table*tabbin_to(ttrd td)
{
if (!td._addr) return nullptr;
__table* ptab = (__table*)table_create();
if (!ptab) return nullptr;
unsigned len = *(unsigned*)td._addr;
if (len > td._size) { table_destroy(ptab); return nullptr; }
if (!_tbParse(ptab, (byte*)td._addr + sizeof(unsigned), len))
{
table_destroy(ptab);
return nullptr;
}
return ptab;
}
int tab_peek_type(const char* filename)
{
etfiletype ftyp = etft_unknown;
Schema::hfile hf = _fopenread(filename);
if (hf)
{
unsigned len = _flength(hf);
if (len > 0)
{
ftyp = etft_text;
if (len > sizeof(__table_bin_header))
{
__table_bin_header header = { 0 };
_fread(hf, &header, sizeof(__table_bin_header));
if (header.fcc == 'tabb') ftyp = etft_binary;
}
}
_fclose(hf);
}
return (int)ftyp;
}
|
; A033999: a(n) = (-1)^n.
; 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,-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,1,-1,1
mov $1,-1
bin $1,$0
mov $0,$1
|
; A097064: Expansion of (1-4x+6x^2)/(1-2x)^2.
; 1,0,2,8,24,64,160,384,896,2048,4608,10240,22528,49152,106496,229376,491520,1048576,2228224,4718592,9961472,20971520,44040192,92274688,192937984,402653184,838860800,1744830464,3623878656,7516192768
sub $0,1
mov $2,$0
lpb $0
sub $0,1
mul $2,2
mov $1,$2
lpe
add $1,1
sub $1,$0
sub $1,1
mov $0,$1
|
; FILE *fdopen(int fd, const char *mode)
SECTION code_stdio
PUBLIC fdopen
EXTERN asm_fdopen
fdopen:
pop af
pop de
pop hl
push hl
push de
push af
jp asm_fdopen
|
; *****************************************************************************
; *****************************************************************************
;
; Name : files.asm
; Purpose : RPL-C Includes
; Author : Paul Robson (paul@robsons.org.uk)
; Date : 17th January 2020
;
; *****************************************************************************
; *****************************************************************************
;
; This is the first thing after the JMP at the start. Keep it as
; stable as possible.
;
.include "code/core.src"
.include "words/arithmetic/binary.src"
.include "words/arithmetic/compare.src"
.include "words/arithmetic/divide.src"
.include "words/arithmetic/multiply.src"
.include "words/arithmetic/unary.src"
.include "words/data/literals.src"
.include "words/data/stack.src"
.include "words/data/memory.src"
.include "words/structures/fornext.src"
.include "words/structures/ifelseendif.src"
.include "words/structures/repeatuntil.src"
.include "words/system/branch.src"
.include "words/system/callhandler.src"
.include "words/system/clrnew.src"
.include "words/system/debug.src"
.include "words/system/decode.src"
.include "words/system/edit.src"
.include "words/system/fastsearch.src"
.include "words/system/list.src"
.include "words/system/miscellany.src"
.include "words/system/old.src"
.include "words/system/saveload.src"
.include "words/system/skipper.src"
.include "words/system/toint.src"
.include "words/system/tostr.src"
.include "words/system/varhandlers.src"
.include "words/encode/encode.src"
.include "words/encode/comstr.src"
.include "words/encode/encdef.src"
.include "words/encode/encutils.src"
.include "words/encode/encsearch.src"
.include "words/encode/encvar.src"
|
#include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <climits>
#include <stack>
using namespace std;
class Solution {
public:
int n;
int target;
vector<int> searchRange(vector<int>& nums, int _target) {
n = nums.size();
target = _target;
int left = 0;
int right = n - 1;
int left_pos = -1;
while ( left <= right ) {
int mid = (left + right) / 2;
if (nums[mid] < target) {
left = mid + 1;
}
else {
right = mid;
}
if (right - left < 2) {
if (nums[left] == target)
left_pos = left;
else if (nums[right] == target)
left_pos = right;
break;
}
}
//cout << "left position = " << left_pos << endl << endl;
left = 0;
right = n - 1;
int right_pos = -1;
while (left <= right) {
int mid = (left + right) / 2;
//cout << "left = " << left << " mid = " << mid << " right = " << right << endl;
//cout << "midele value = " << nums[mid] << " " << target << endl << endl;
if (nums[mid] > target) {
right = mid - 1;
}
else {
left = mid;
}
if (right - left < 2) {
if (nums[right] == target)
right_pos = right;
else if (nums[left] == target)
right_pos = left;
break;
}
}
//cout << "right position = " << right_pos << endl << endl;
vector<int> ans;
ans.push_back(left_pos);
ans.push_back(right_pos);
return ans;
}
};
int main() {
vector<int> nums = {4};
vector<int> ans = Solution().searchRange(nums, 5);
//for (int i = 0; i < ans.size(); ++ i)
// cout << ans[i] << endl;
return 0;
} |
; A010969: a(n) = binomial(n,16).
; 1,17,153,969,4845,20349,74613,245157,735471,2042975,5311735,13037895,30421755,67863915,145422675,300540195,601080390,1166803110,2203961430,4059928950,7307872110,12875774670,22239974430,37711260990,62852101650,103077446706,166509721602,265182149218,416714805914,646626422970,991493848554,1503232609098,2254848913647,3348108992991,4923689695575,7174519270695,10363194502115,14844575908435,21094923659355,29749251314475,41648951840265,57902201338905,79960182801345,109712808959985,149608375854525,202802465047245,273342452889765,366395202809685,488526937079580,648045936942300,855420636763836,1123787895356412,1469568786235308,1913212193400684,2480089880334220,3201570572795084,4116305022165108,5271759063474612,6726037425812436,8550047575185300,10830060261901380,13670731806006660,17198662594653540,21566576904406820,26958221130508525,33594090947249085,41738112995067045,51705423561053205,63871405575418665,78682166288559225,96666661440229905,118450697821126785,144773075114710515,176504160071359395,214667221708410075,260462895672870891,315297189498738447,380813488615359423,458929076023638279,551876736990451095,662252084388541314,793067310934426018,947812152092362802,1130522928399324306,1345860629046814650,1599199100396803290,1896724514424115530,2245547413628550570,2653828761561014310,3130921572628162950,3687529852206503030,4335886749297756310,5089954010045192190,5965645022526085470,6981073962530525550,8156833787798824590,9516306085765295355,11086006058675034795,12895966231519938435,14980162794189827475
add $0,16
bin $0,16
|
; A025993: Expansion of 1/((1-2x)(1-5x)(1-7x)(1-9x)).
; Submitted by Jon Maiga
; 1,23,344,4258,47487,496725,4981918,48547136,463544213,4361492707,40596873252,374857310334,3440520848779,31434357529169,286207079508746,2598999610410652,23553202070626785,213115529239825311
mov $1,1
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
seq $0,16312 ; Expansion of 1/((1-2x)*(1-7x)*(1-9x)).
mul $1,5
add $1,$0
lpe
mov $0,$1
|
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main(int argc, char **argv) {
std::string line;
std::string direction;
int value;
int forward = 0;
int depth = 0;
int aim = 0;
std::ifstream inputFile("input.txt");
while (getline(inputFile, line)) {
std::string temp;
std::istringstream iss(line);
iss >> direction;
iss >> temp;
value = atoi(temp.c_str());
if (direction == "forward") {
forward += value;
depth += aim * value;
} else if (direction == "down") {
aim += value;
} else {
aim -= value;
}
}
inputFile.close();
std::cout << "Depth: " << depth << std::endl;
std::cout << "Horizontal: " << forward << std::endl;
std::cout << "Multiplied: " << depth * forward << std::endl;
return 0;
}
|
//
// Copyright 2019 Google LLC
//
// 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 "zetasql/public/types/extended_type.h"
#include "zetasql/public/language_options.h"
namespace zetasql {
bool ExtendedType::IsSupportedType(
const LanguageOptions& language_options) const {
return language_options.LanguageFeatureEnabled(FEATURE_EXTENDED_TYPES);
}
zetasql_base::StatusOr<std::string> ExtendedType::TypeNameWithParameters(
const TypeParameters& type_params, ProductMode mode) const {
ZETASQL_DCHECK(type_params.IsEmpty());
return TypeName(mode);
}
} // namespace zetasql
|
; A062956: a(n) = h(n^2) - h(n), where h(n) is the half-totient function (A023022).
; 2,3,8,5,18,14,24,18,50,22,72,39,56,60,128,51,162,76,120,105,242,92,240,150,234,162,392,116,450,248,320,264,408,210,648,333,456,312,800,246,882,430,528,495,1058,376,1008,490,800,612,1352,477,1080,660,1008
add $0,2
mov $1,$0
seq $0,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
mul $0,$1
div $0,2
|
/** --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose" file="DeleteFormFieldRequest.cpp">
* Copyright (c) 2020 Aspose.Words for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
-------------------------------------------------------------------------------------------------------------------- **/
#include "DeleteFormFieldRequest.h"
namespace aspose {
namespace words {
namespace cloud {
namespace api {
namespace models {
DeleteFormFieldRequest::DeleteFormFieldRequest(
utility::string_t name,
int32_t index,
boost::optional< utility::string_t > nodePath,
boost::optional< utility::string_t > folder,
boost::optional< utility::string_t > storage,
boost::optional< utility::string_t > loadEncoding,
boost::optional< utility::string_t > password,
boost::optional< utility::string_t > destFileName,
boost::optional< utility::string_t > revisionAuthor,
boost::optional< utility::string_t > revisionDateTime
) : m_Name(std::move(name)),
m_Index(std::move(index)),
m_NodePath(std::move(nodePath)),
m_Folder(std::move(folder)),
m_Storage(std::move(storage)),
m_LoadEncoding(std::move(loadEncoding)),
m_Password(std::move(password)),
m_DestFileName(std::move(destFileName)),
m_RevisionAuthor(std::move(revisionAuthor)),
m_RevisionDateTime(std::move(revisionDateTime))
{
}
utility::string_t DeleteFormFieldRequest::getName() const
{
return m_Name;
}
void DeleteFormFieldRequest::setName(utility::string_t name)
{
m_Name = std::move(name);
}
int32_t DeleteFormFieldRequest::getIndex() const
{
return m_Index;
}
void DeleteFormFieldRequest::setIndex(int32_t index)
{
m_Index = std::move(index);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getNodePath() const
{
return m_NodePath;
}
void DeleteFormFieldRequest::setNodePath(boost::optional< utility::string_t > nodePath)
{
m_NodePath = std::move(nodePath);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getFolder() const
{
return m_Folder;
}
void DeleteFormFieldRequest::setFolder(boost::optional< utility::string_t > folder)
{
m_Folder = std::move(folder);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getStorage() const
{
return m_Storage;
}
void DeleteFormFieldRequest::setStorage(boost::optional< utility::string_t > storage)
{
m_Storage = std::move(storage);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getLoadEncoding() const
{
return m_LoadEncoding;
}
void DeleteFormFieldRequest::setLoadEncoding(boost::optional< utility::string_t > loadEncoding)
{
m_LoadEncoding = std::move(loadEncoding);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getPassword() const
{
return m_Password;
}
void DeleteFormFieldRequest::setPassword(boost::optional< utility::string_t > password)
{
m_Password = std::move(password);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getDestFileName() const
{
return m_DestFileName;
}
void DeleteFormFieldRequest::setDestFileName(boost::optional< utility::string_t > destFileName)
{
m_DestFileName = std::move(destFileName);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getRevisionAuthor() const
{
return m_RevisionAuthor;
}
void DeleteFormFieldRequest::setRevisionAuthor(boost::optional< utility::string_t > revisionAuthor)
{
m_RevisionAuthor = std::move(revisionAuthor);
}
boost::optional< utility::string_t > DeleteFormFieldRequest::getRevisionDateTime() const
{
return m_RevisionDateTime;
}
void DeleteFormFieldRequest::setRevisionDateTime(boost::optional< utility::string_t > revisionDateTime)
{
m_RevisionDateTime = std::move(revisionDateTime);
}
}
}
}
}
}
|
; A184334: Period 6 sequence [0, 2, 2, 0, -2, -2, ...] except a(0) = 1.
; 1,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0,-2,-2,0,2,2,0
mov $2,$0
mov $3,$0
add $0,8
sub $0,$3
mov $1,3
lpb $2,1
sub $0,$1
add $4,$0
mov $1,$4
sub $2,1
lpe
div $1,2
|
; ***************************************************************************************************************************************
; ***************************************************************************************************************************************
;
; BERZERK - For the RCA Studio 2 (1802 Assembler)
; ===============================================
;
; Author : Paul Robson (paul@robsons.org.uk)
; Tools : Assembles with asmx cross assembler http://xi6.com/projects/asmx/
;
; ***************************************************************************************************************************************
; ***************************************************************************************************************************************
;
; Reserved for Studio 2 BIOS : R0,R1,R2,R8,R9,RB.0
;
; Other usage
; ===========
; R2 Used for Stack, therefore R2.1 always points to RAM Page.
; R3 PC (lowest level)
; R4 PC (level 1 subroutine)
; R5 PC (level 2 subroutine)
;
; ***************************************************************************************************************************************
; ***************************************************************************************************************************************
RamPage = 8 ; 256 byte RAM page used for Data ($800 on S2)
VideoPage = 9 ; 256 byte RAM page used for Video ($900 on S2)
Studio2BeepTimer = $CD ; Studio 2 Beep Counter
Studio2SyncTimer = $CE ; Studio 2 Syncro timer.
XRoom = $E0 ; Horizontal Room Number
YRoom = $E1 ; Vertical Room Number
Seed1 = $E2 ; Random Number Seed #1
Seed2 = $E3 ; Random Number Seed #2
NorthDoor = $E4 ; door present flags. If non-zero can exit in that direction.
SouthDoor = $E5
EastDoor = $E6
WestDoor = $E7
LivesLost = $E8 ; Number of lives lost
Score = $E9 ; Score (LS Digit first, 6 digits)
FrameCounter = $F0 ; Frame counter
KeyboardState = $F1 ; Current Keyboard State (0-9 + bit 7 for fire)
XAdjustStart = 125
YAdjustStart = 227
; ------------------------------------------------------------------------------------------------------------------------------------
;
; +0 bit 7 : Not in use, bit 6 : To be Deleted, Bit 5 : not drawn Bits 3-0 : ObjectID
; (0 = Player, 1 = Missile, 2-4 = Robots)
; +1 Speed Mask (and with Frame counter, move if zero)
; +2 bits 3..0 direction as per Studio 2 Keypad, 0 = no movement
; +3 X position (0-63)
; +4 Y position (0-31)
; +5 0 if graphic not drawn, or LSB of address of 3 bit right justified graphic terminated with $00
;
; It is a convention that an objects missile immediately follows it's own object. Object 0 is the Player, Object 1 is the Player Missile
;
; ------------------------------------------------------------------------------------------------------------------------------------
ObjectStart = $00
ObjectRecordSize = 6
ObjectCount = 2+8
ObjectEnd = ObjectStart+ObjectRecordSize * ObjectCount
PlayerObject = ObjectStart+0*ObjectRecordSize
PlayerMissileObject = ObjectStart+1*ObjectRecordSize
; ***************************************************************************************************************************************
;
; Studio 2 Boot Code
;
; ***************************************************************************************************************************************
.include "1802.inc"
.org 400h ; ROM code in S2 starts at $400.
StartCode:
.db >(StartGame),<(StartGame) ; This is required for the Studio 2, which runs from StartGame with P = 3
; ***************************************************************************************************************************************
;
; Draw Room according to current specification.
;
; Runs in R4, Returns to R3
; ***************************************************************************************************************************************
DrawRoom:
; ---------------------------------------------------------------------------------------------------------------------------------------
; Clear the whole screen, draw the basic frame.
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi VideoPage ; point RF to video page
phi rf
ldi 0
plo rf
DRM_ClearScreen:
glo rf
ani $F8 ; top and bottom lines
bz DRM_WriteFF
xri $F0
bz DRM_WriteFF
xri $08
bz DRM_Write00
glo rf ; check left and right sides
ani $07
bz DRM_Write80
xri $07
bz DRM_Write08
DRM_Write00: ; erase
ldi $00
br DRM_Write
DRM_Write08: ; right wall
ldi $08
br DRM_Write
DRM_Write80: ; left wall
ldi $80
br DRM_Write
DRM_WriteF8: ; top/bottom right
ldi $F8
br DRM_Write
DRM_WriteFF: ; write top/bottom
glo rf ; check RHS
ani 7
xri 7
bz DRM_WriteF8
ldi $FF
DRM_Write: ; write and fill whole screen
str rf
inc rf
glo rf
bnz DRM_ClearScreen
; ---------------------------------------------------------------------------------------------------------------------------------------
; Get West Door from room to the left's east door
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi WestDoor ; point RF to West door, RE to XRoom.
plo rf
ldi XRoom
plo re
ghi r2
phi rf
phi re
ldn re ; read XRoom
plo rd ; save it in RD.
smi 1
str re ; go to the room to the left.
ldi >ResetSeed ; reset the seed according to room to the immediate left.
phi r5
ldi <ResetSeed
plo r5
sep r5 ; reset the seed, get the first Random Number
ani $01 ; bit 0 (east door) becomes our west door.
str rf
glo rd ; restore old XRoom
str re
; ---------------------------------------------------------------------------------------------------------------------------------------
; Get North door from rom to the north's south door.
; ---------------------------------------------------------------------------------------------------------------------------------------
inc re ; RE points to Y Room
ldi NorthDoor ; RF to North Door.
plo rf
ldn re ; Read Y Room
plo rd ; save in RD.0
smi 1
str re ; go to room above
ldi <ResetSeed
plo r5
sep r5 ; reset the seed, get the first Random Number
ani $02 ; bit 1 (south door) becomes our north door.
str rf
glo rd ; restore old Y Room
str re
ldi SouthDoor ; point RF to south door.
plo rf
; ---------------------------------------------------------------------------------------------------------------------------------------
; Get South and East doors from our current room, initialise RNG for walls
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi <ResetSeed ; reset the seed, our actual room now.
plo r5
sep r5 ; reset the seed, get the first Random Number
shr ; shift bit 0 (east door) into DF
ani $01 ; bit 0 (was bit 1) is the south door
str rf
inc rf ; point RF to east door
ldi $00
shrc ; get the old bit 7 out.
str rf ; save in east door.
; ---------------------------------------------------------------------------------------------------------------------------------------
; Draw the 8 walls from the 8 centre point in directions chosen from the RNG
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi VideoPage ; set RF to point to the first of the eight 'wall' centre points
phi rf
ldi 10*8+1 ; row 8, byte 1
plo rf
ldi $08 ; set RE.1 to point to the current bit mask for Oring in.
phi re
ldi $0F ; set RE.0 to the current byte #1 for Oring in.
plo re
ldi $FF ; set RD.1 to currentbyte #2 for Oring in.
phi rd
; ---------------------------------------------------------------------------------------------------------------------------------------
; Inner Wall Loop
; ---------------------------------------------------------------------------------------------------------------------------------------
DRM_Loop1:
glo rf ; save start position in RC.1s
phi rc
ghi re ; set the pixel on the wall corner
sex rf
or
str rf
sep r5 ; get the second seeded number that defines the room layout.
shl ; put bit 7 in DF
bnf DRM_WallHorizontal ; if clear the wall is horizontal.
; ---------------------------------------------------------------------------------------------------------------------------------------
; Vertical wall, either direction
; ---------------------------------------------------------------------------------------------------------------------------------------
shl ; put bit 6 in DF.
ldi 8 ; use that to decide up or down ?
bnf DRM_VerticalOpposite
ldi -8
DRM_VerticalOpposite:
dec r2 ; save offset position on stack.
str r2
ldi 10 ; set RC.0 (counter) to 10
plo rc
DRM_VerticalLoop:
sex rf ; video memory = index
ghi re ; or bit mask in.
or
str rf
sex r2 ; offset = index
glo rf ; add to screen position
add
plo rf
dec rc ; do it 10 times.
glo rc
bnz DRM_VerticalLoop
inc r2 ; fix stack up.
br DRM_Next
; ---------------------------------------------------------------------------------------------------------------------------------------
; Horizontal walls, seperate code for left and right
; ---------------------------------------------------------------------------------------------------------------------------------------
DRM_WallHorizontal:
shl ; bit 6 determines direction
bnf DRM_WallLeft
sex rf ; index = vram - right wall
glo re
or
str rf
inc rf
ghi rd
or
str rf
br DRM_Next
DRM_WallLeft: ; left wall.
sex rf
ghi re ; check the wall pixel
shl
bnf DRMWL_NotLHB
dec rf ; back one if the wall is not on the MS Bit.
DRMWL_NotLHB:
ghi rd
xri $0F
or
str rf
dec rf
glo re
xri $F0
or
str rf
; ---------------------------------------------------------------------------------------------------------------------------------------
; Advance to next wall position
; ---------------------------------------------------------------------------------------------------------------------------------------
DRM_Next:
ghi rc ; reset start position saved in RC.1
plo rf
glo re ; change the ORing byte from $0F to $FF
xri $F0
plo re
ghi rd ; change the other one from $FF to $F0
xri $0F
phi rd
ghi re ; change the ORing bitmask from $08 to $80
xri $88
phi re
shl ; if gone from 08 to 80 add 1 to rf
bnf DRM_NoBump
inc rf
DRM_NoBump:
inc rf ; add one further to RF anyway.
glo rf ; reached the end of row 2 ?
xri 20*8+7
bz DRM_Frame
glo rf
xri 10*8+7 ; reached the end of row 1 ?
bnz DRM_Loop1 ; no keep going
ldi 20*8+1 ; yes, move to the second row
plo rf
br DRM_Loop1
; ---------------------------------------------------------------------------------------------------------------------------------------
; Open top and bottom doors
; ---------------------------------------------------------------------------------------------------------------------------------------
DRM_Frame:
ldi 3 ; point RF to upper door space
plo rf
ghi r2 ; point RE to NorthDoor
phi re
ldi NorthDoor
plo re
br DRM_TBDoor-1 ; sorts the page out.
.org StartCode+$FF
glo re ; nop but not 3 cycles.
DRM_TBDoor:
ldn re ; read north door
bz DRM_TBClosed ; if zero, it is closed.
ldi $80 ; open door on display
str rf
inc rf
ldi $0F
str rf
dec rf
DRM_TBClosed:
ldi 30*8+3 ; point to bottom door always
plo rf
glo re ; switch NorthDoor pointer to South Door
xri NorthDoor ^ SouthDoor
plo re
xri NorthDoor ; do it twice, till it returns to its original value.
bnz DRM_TBDoor
; ---------------------------------------------------------------------------------------------------------------------------------------
; Open left and right doors
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi 11*8 ; point RF to west door space
plo rf
ldi WestDoor ; point RE to west door pointer
plo re
DRM_LRDoor:
ldn re ; read west door, if zero it's closed
bz DRM_LRClosed
DRM_OpenLRDoor:
ldi $00 ; open it
str rf
glo rf ; down one line
adi 8
plo rf
smi 20*8 ; until reached the bottom
bnf DRM_OpenLRDoor
DRM_LRClosed:
ldi 11*8+7 ; point RF to east door space
plo rf
glo re ; switch west door pointer to east door pointer
xri EastDoor ^ WestDoor
plo re
xri WestDoor ; do it twice, till it returns to original value.
bnz DRM_LRDoor
; ---------------------------------------------------------------------------------------------------------------------------------------
; Draw number of lives lost
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi 7+8 ; point RF to lives draw area
plo rf
ldi LivesLost ; point RE to lives lost
plo re
ldn re ; calculate 3-lost
sdi 3
plo rd ; save in RD.0
DRM_Lives:
ldn rf ; set lives marker
ori 3
str rf
glo rf ; two rows down
adi 16
plo rf
dec rd
glo rd ; for however many lives.
bnz DRM_Lives
sep r3
; ***************************************************************************************************************************************
;
; Reset Seed according to Room positions, breaks R7, returns first Random Number
;
; Runs in R5, returns to R4, drops through to "Random" subroutine below. Need to be in same page.
; ***************************************************************************************************************************************
ResetSeed:
ldi XRoom ; point R7 to XRoom
plo r7
ghi r2
phi r7
lda r7 ; read X Room, bump it
inc r7 ; bump again to Seed1
adi XAdjustStart
str r7 ; store (modified) in Seed1
dec r7 ; repeat with Y Room and Seed2
lda r7
inc r7
adi YAdjustStart
str r7
; ***************************************************************************************************************************************
;
; Random Number Generator, breaks R7.
;
; Runs in R5, return to R4.
; ***************************************************************************************************************************************
Random: ghi r2 ; point R7 to the Seed Data (2nd byte)
phi r7
ldi Seed2
plo r7
sex r7 ; use R7 as index register
ldn r7 ; load the 2nd byte
shr ; shift right into DF
stxd ; store and point to first byte
ldn r7 ; rotate DF into it and out
shrc
str r7
bnf RN_NoXor
inc r7 ; if LSB was set then xor high byte with $B4
ldn r7
xri $B4
stxd ; store it back and fix up RF again.
RN_NoXor:
ldn r7 ; re-read the LSB
inc r7
add ; add the high byte.
sep r4 ; and exit.
br Random
; ***************************************************************************************************************************************
;
; Erase the object structure. Initialise the Player, flipping position horizontally or vertically accordingly.
;
; Runs in R4, return to R3
; ***************************************************************************************************************************************
InitialiseRoomAndPlayer:
ghi r2 ; set RF to the last object structure byte
phi rf
ldi ObjectEnd-1
plo rf
IRM_Clear: ; fill everything with $FF
sex rf
ldi $FF
stxd
glo rf
xri PlayerObject+ObjectRecordSize-1 ; keep going until reached last byte of player record
bnz IRM_Clear
stxd ; +5 graphic drawn zero
ldn rf ; +4 copy Y
stxd
ldn rf ; +3 copy X
stxd
ldi 0 ; +2 direction no movement
stxd
ldi 3 ; +1 speed mask
stxd
ldi 0+32 ; object ID = 0 (Player object) and not drawn flag set.
stxd
sep r3
; ***************************************************************************************************************************************
; Partial line plotter - xors one row of 3 pixels
;
; On entry, D contains pattern, RF points to the Video RAM to alter.
; On exit, RF is up one (e.g. -8) we draw sprites upwards.
;
; Runs in R6. Returns to R5. Breaks RE, Set [R2] to Non-Zero on collision.
;
; ***************************************************************************************************************************************
PartialXORPlot:
br PX_Shift0 ; shift right x 0
br PX_Shift1 ; shift right x 1
br PX_Shift2 ; shift right x 2
br PX_Shift3 ; shift right x 3
br PX_Shift4 ; shift right x 4
br PX_Shift5 ; shift right x 5
br PX_Shift6 ; shift right 8, shift left 2.
PX_Shift7: ; shift right 8, shift left 1.
shl ; shift left, store in right half
phi re
ldi 0 ; D = DF, store in left half.
shlc
plo re
PX_XorRE: ; XOR with RE, check collision.
sex rf
glo re ; check collision.
and
bz PX_NoCollideLeftPart
str r2 ; set TOS non zero on collision
PX_NoCollideLeftPart:
glo re ; XOR [RF] with RE.0
xor
str rf
inc rf ; XOR [RF+1] with RE.1
ghi re ; check collision.
and
bz PX_NoCollideRightPart
str r2 ; set TOS non zero on collision
PX_NoCollideRightPart:
ghi re
xor
str rf
glo rf ; go down one row
adi 7
plo rf
sep r5 ; and exit
PX_Shift6:
shl ; RE.10 = D >> 8 left 1.
phi re
ldi 0
shlc
plo re
ghi re ; shift it left once again
shl
phi re
glo re
shlc
plo re
br PX_XorRE ; and exclusive OR into video memory.
PX_Shift5: ; shift right 6 and xor
shr
PX_Shift4: ; shift right 4 and xor
shr
PX_Shift3: ; shift right 3 and xor
shr
PX_Shift2: ; shift right 2 and xor
shr
PX_Shift1: ; shift right 1 and xor
shr
PX_Shift0: ; shift right 0 and xor
sex rf ; XOR into RF
plo re ; save pattern in RE.0
and ; and with screen
bz PX_NoCollideSingle ; skip if zero e.g. no collision
str r2 ; set TOS non zero on collision
PX_NoCollideSingle:
glo re ; restore pattern from RE.0
xor
str rf
glo rf ; go down one row
adi 8
plo rf
sep r5 ; and exit
; ***************************************************************************************************************************************
; Plot Character in RC
;
; Runs in R5, Returns to R4. D set to non-zero on collision with .... something.
;
; Subroutine breaks RB.1,RD,RE, uses RF as VideoRAM pointer.
; ***************************************************************************************************************************************
PlotCharacter:
inc rc ; advance to RC[3] which is the X position.
inc rc
inc rc
ldi >PartialXORPlot ; R6.1 set to PartialXOR Plot (MSB) throughout.
phi r6
ldn rc ; read X position
ani 7 ; get the lower 3 bits - the shifting bits.
shl ; double and add to PartialXORPlot LSB
adi <PartialXORPlot ; this is the LSB of the routine address
phi rb ; save in RB.1
lda rc ; get X, bump to point to Y RC[4], divide by 8.
shr
shr
shr
dec r2 ; save X/8 on stack.
str r2
lda rc ; get Y, bump to point to character data pointer RC[5]
shl
shl
shl ; multiply by 8
sex r2 ; add to X/8
add ; D now = Y*8 + X/8 e.g. the byte position in the screen
plo rf ; store in RF (points to video RAM)
ldi VideoPage
phi rf
ldn rc ; read character data pointer RC[5]
plo rd ; put in RD, RD is the pixel data source.
ldi >Graphics ; Make RD a full 16 bit pointer to graphics.
phi rd
ldi 0
str r2 ; clear top of stack which is the collision flag.
PCLoop:
ghi rb ; set R6 to the drawer routine.
plo r6
lda rd ; read a graphic byte
bz PCComplete ; complete if zero
sep r6 ; draw that pixel out.
br PCLoop ; keep going till more data.
PCComplete:
glo rc ; fix up RC so it points back to the start
smi 5
plo rc
lda r2 ; read collision flag off top of stack and fix the stack.
sep r4 ; and return to R4.
; ***************************************************************************************************************************************
;
; Object Mover (object pointed to by RC)
;
; ***************************************************************************************************************************************
MoveObject:
; ---------------------------------------------------------------------------------------------------------------------------------------
; Check bit 7 of the ID/Flags is clear, e.g. it is in use
; ---------------------------------------------------------------------------------------------------------------------------------------
ldn rc ; read RC[0] - ID and Flags
shl ; put bit 7 (not in use) into DF
bnf MO_InUse
sep r3
MO_InUse:
; ---------------------------------------------------------------------------------------------------------------------------------------
; if to be deleted (bit 6), erase and delete, if not drawn yet (bit 5), draw it and exit
; ---------------------------------------------------------------------------------------------------------------------------------------
shl ; put bit 6 (deleted) flag into DF.
bdf MO_Erase ; if set, go to erase because you want to delete it.
shl ; put bit 5 (not drawn) into DF.
bdf MO_Redraw
; ---------------------------------------------------------------------------------------------------------------------------------------
; And the Frame Counter with the speed mask, to see if it is move time
; ---------------------------------------------------------------------------------------------------------------------------------------
inc rc ; move to RC[1]
ghi r2 ; point RF at the Frame Counter
phi rf
ldi FrameCounter
plo rf
ldn rf ; read the Frame Counter
sex rc ; and with the speed mask - controls how fast it goes.
and
dec rc ; fix RC up before carrying on.
bz MO_TimeToMove
sep r3
MO_TimeToMove:
; ---------------------------------------------------------------------------------------------------------------------------------------
; Figure out what direction is required, update it if $FF not returned. If direction = 0 (no move) collision only
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi >CallVector ; call the code to get the new direction.
phi r6
ldi <CallVector
plo r6
ldi <VTBL_GetDirection
sep r6
plo re ; save it in RE.0
ghi rc ; point RF to RC[2], the direction.
phi rf
glo rc
plo rf
inc rf
inc rf
glo re ; look at the returned direction.
xri $FF ; returned $FF, no change.
bz MO_NoUpdateDirection
glo re ; copy the returned direction in.
str rf
MO_NoUpdateDirection:
ldn rf ; if movement is zero, do nothing other than collision check.
bz MO_CheckCollision
; ---------------------------------------------------------------------------------------------------------------------------------------
; Erase the old drawn character
; ---------------------------------------------------------------------------------------------------------------------------------------
MO_Erase:
ldi >PlotCharacter ; erase the character.
phi r5
ldi <PlotCharacter
plo r5
sep r5
; ---------------------------------------------------------------------------------------------------------------------------------------
; if character marked to be deleted, then set ID/Flags to all '1' and return
; ---------------------------------------------------------------------------------------------------------------------------------------
ldn rc ; read the ID + Flags
ani $40 ; is the delete flag set ?
bz MO_DontDelete ; skip if not deleting.
ldi $FF ; set the flags to $FF e.g. deleted object
str rc
sep r3 ; and return to caller.
MO_DontDelete:
; ---------------------------------------------------------------------------------------------------------------------------------------
; Move in the requested direction
; ---------------------------------------------------------------------------------------------------------------------------------------
ldi >MoveObjectPosition ; set R5 to point to the object moving code
phi r5
ldi <MoveObjectPosition
plo r5
inc rc ; read the current direction from RC[2]
inc rc
ldn rc
dec rc
dec rc
sep r5 ; and move it.
; ---------------------------------------------------------------------------------------------------------------------------------------
; Get the graphic we want to use for drawing, and save that, then draw it in the new place
; ---------------------------------------------------------------------------------------------------------------------------------------
MO_Redraw: ; redraw in its new/old position.
ldi >CallVector ; call the code to get the graphic character
phi r6
ldi <CallVector
plo r6
ldi <VTBL_GetGraphicCharacter
sep r6
plo re ; save in RE.0
ghi rc ; set RF = RC[5], the graphic pointer
phi rf
glo rc
adi 5
plo rf
glo re ; restore from RE.0
str rf ; save in RF.0 table.
ldi >PlotCharacter ; now redraw it in the new position.
phi r5
ldi <PlotCharacter
plo r5
sep r5
bz MO_ClearNotDrawn ; if no collision clear the 'not drawn' flag.
; ---------------------------------------------------------------------------------------------------------------------------------------
; if Player collided, must've died. if Missile collided, delete. if robot collided, undo move.
; ---------------------------------------------------------------------------------------------------------------------------------------
MO_Collide:
ldn rc ; get the ID number
ani 15
bz MO_PlayerHitFrame ; if zero then the player has hit something, life over.
xri 1 ; if it is ID #1 (bullet) then delete it but keep data for collision.
bz MO_DeleteMissile ; otherwise move it back.
MO_MoveBackwards:
ldi >PlotCharacter ; now erase it in the new position
phi r5
ldi <PlotCharacter
plo r5
sep r5
ldi >MoveObjectPosition ; set R5 to point to the object moving code
phi r5
ldi <MoveObjectPosition
plo r5
inc rc ; read the current direction from RC[2]
inc rc
ldn rc
sdi 10 ; move it backwards i.e. to where it was.
dec rc
dec rc
sep r5 ; and move it.
ldi >PlotCharacter ; now redraw it in the original position.
phi r5
ldi <PlotCharacter
plo r5
sep r5
br MO_ClearNotDrawn ; go on to the next phase.
MO_DeleteMissile:
ldn rc
ori $40
str rc
br MO_ClearNotDrawn
; ---------------------------------------------------------------------------------------------------------------------------------------
; Player died
; ---------------------------------------------------------------------------------------------------------------------------------------
MO_PlayerHitFrame: ; player hit something, die now.
ldi >LifeLost
phi r3
ldi <LifeLost
plo r3
sep r3
; ---------------------------------------------------------------------------------------------------------------------------------------
; Collision okay, clear not drawn bit.
; ---------------------------------------------------------------------------------------------------------------------------------------
MO_ClearNotDrawn:
ldn rc ; clear the 'not drawn' flag as it now will be until deleted.
ani $FF-$20
str rc
; ---------------------------------------------------------------------------------------------------------------------------------------
; Call the collision testing code (missiles vs players/robots) or firing code (player/robot)
; ---------------------------------------------------------------------------------------------------------------------------------------
MO_CheckCollision:
ldi >CallVector ; call collision testing code.
phi r6
ldi <CallVector
plo r6
ldi <VTBL_CollisionCheckOrFire
sep r6
sep r3 ; and finally exit.
; ***************************************************************************************************************************************
;
; Adjust object at RC in direction D
;
; ***************************************************************************************************************************************
MoveObjectPosition:
ani 15 ; lower 4 bits only.
shl ; RF to point to the offset table + D x 2
adi <XYOffsetTable
plo rf
ldi >XYOffsetTable
phi rf
sex rc ; RC as index
inc rc ; point to RC[3] , x position
inc rc
inc rc
lda rf ; read X offset
add ; add to RC[3]
str rc
inc rc ; point to RC[4], y position
ldn rf ; read Y offset
add ; add to RC[4]
str rc
glo rc ; set RC[4] back to RC[0]
smi 4
plo rc
sep r4
br MoveObjectPosition ; make reentrant
XYOffsetTable:
.db 0,0 ; 0
.db -1,-1, 0,-1, 1,-1 ; 1 2 3
.db -1,0, 0,0, 1,0 ; 4 5 6
.db -1,1, 0,1, 1,1 ; 7 8 9
.db 0,0 ; 10
; ***************************************************************************************************************************************
;
; On entry, P = 6 and D points to a table. Load the vector into R5, and set P = 5 - vectored code run in P5, return to P4
;
; ***************************************************************************************************************************************
CallVector:
dec r2 ; save the table LSB on the stack
str r2
ldn rc ; get ID bits
ani 15
shl ; double
sex r2 ; add to table LSB
add
plo rf ; put in RF.0
ldi >VTBL_GetDirection ; point to tables, all in same page
phi rf
inc r2 ; fix up stack
lda rf ; read MSB into R5.1
phi r5
ldn rf ; read LSB into R5.0
plo r5
sep r5 ; and jump.
Continue: ; continue is a no-op e.g. don't change direction.
ldi $FF
sep r4
GetMissileGraphic:
ldi <Graphics_Missile
sep r4
GetRobotGraphic:
ldi <Graphics_Robot
sep r4
VTBL_GetDirection:
.dw GetPlayerDirection,Continue,ChasePlayer, ChasePlayer, ChasePlayer
VTBL_GetGraphicCharacter:
.dw GetPlayerGraphic,GetMissileGraphic,GetRobotGraphic,GetRobotGraphic,GetRobotGraphic
VTBL_CollisionCheckOrFire:
.dw CheckPlayerFire,CollideMissile,Continue,LaunchMissile,LaunchMissile
; ***************************************************************************************************************************************
;
; Update Keyboard State, also returned in D
;
; ***************************************************************************************************************************************
UpdateKeyboardState:
ldi 9 ; set RF.0 to 9
plo rf
UKSScan:
dec r2 ; put RF.0 on TOS.
glo rf
str r2
sex r2 ; put into keyboard latch.
out 2
b3 UKSFound ; if EF3 set then found a key pressed.
dec rf
glo rf
bnz UKSScan ; try all of them
UKSFound: ; at this point RF.0 is 0 if no key pressed, 1 if pressed.
ldi 0 ; set keyboard latch to zero.
dec r2
str r2
out 2
bn4 UKSNoFire ; skip if Keypad 2 key 0 not pressed
glo rf ; set bit 7 (the fire bit)
ori $80
plo rf
UKSNoFire:
ghi r2 ; point RE to the keyboard state variable
phi re
ldi KeyboardState
plo re
glo rf ; save the result there
str re
sep r3
; ***************************************************************************************************************************************
;
; Get Player Direction Move
;
; ***************************************************************************************************************************************
GetPlayerDirection:
ghi r2 ; point RF to KeyboardState
phi rf
ldi KeyboardState
plo rf
ldn rf ; read Keyboard State
ani 15 ; only interested in bits 0-3
sep r4
; ***************************************************************************************************************************************
; Get Player Graphic
; ***************************************************************************************************************************************
GetPlayerGraphic:
ghi r2 ; read keyboard state
phi rf
ldi <KeyboardState
plo rf
ldn rf
ani 15 ; bits 0-3
shl ; x 2, add XYOffsetTable
adi <XYOffsetTable
plo rf
ldi >XYOffsetTable
phi rf
ldn rf ; read X offset
shl ; sign bit in DF
ldi <Graphics_Left1 ; pick graphic based on sign bit
bdf GPG_Left
ldi <Graphics_Right1
GPG_Left:
plo rf
glo r9 ; use S2 BIOS Clock to pick which animation to use.
ani 4
bz GPG_NotAlternate
glo rf
adi 5
plo rf
GPG_NotAlternate:
glo rf
sep r4
; ***************************************************************************************************************************************
;
; Check Player Fire
;
; ***************************************************************************************************************************************
CheckPlayerFire:
ghi r2 ; point RF to keyboard state
phi rf
ldi <KeyboardState
plo rf
ldn rf ; read keyboard
shl ; fire button into DF
bdf LaunchMissile
sep r4
; ***************************************************************************************************************************************
;
; Launch Missile from RC
;
; ***************************************************************************************************************************************
LaunchMissile:
ghi rc ; point RD to Missile that's being launched
phi rd
glo rc
adi ObjectRecordSize
plo rd
ldn rd ; check if already in use, if so exit.
shl
bnf LM_Exit
ldi 1+$20 ; object ID #1, not drawn in RD[0]
str rd
inc rd
ldi 0 ; speed mask RD[1]
str rd
inc rd
inc rc ; point RC to direction RC[2]
inc rc
lda rc ; read it and bump it.
bz LM_Cancel ; if zero cancel missile launch.
str rd ; save in RD[2]
inc rd
shl ; double direction, add XYOffsetTable
adi <XYOffsetTable
plo rf ; make RF point to offset data
ldi >XYOffsetTable
phi rf
ldn rc ; read RC[3] (X Position)
sex rf
add ; add 2 x direction to it
add
adi 1
str rd ; save in RD[3]
inc rc ; point to RC[4],RD[4] and Y offset
inc rd
inc rf
ldn rc ; RD[4] = RC[4] + 3 x dy
add
add
add
adi 2
str rd
glo rc ; fix RC back
smi 4
plo rc
LM_Exit:
sep r4
LM_Cancel: ; missile launch cancelled
dec rd
dec rd
ldi $FF ; write $FF to RD[0] no object
str rd
dec rc ; fix up RC
dec rc
dec rc
sep r4 ; and exit.
; ***************************************************************************************************************************************
;
; Missile collision check
;
; ***************************************************************************************************************************************
CollideMissile:
ghi rc ; RF = RC + 3
phi rf
glo rc
adi 3
plo rf ; RF points to X
lda rf
ani $C0
bnz CM_Delete
ldn rf
ani $E0
bnz CM_Delete
ldi >CheckHitPlayerRobotObjects ; check for collisions with player or robots.
phi r6
ldi <CheckHitPlayerRobotObjects
plo r6
sep r6
sep r4
CM_Delete:
ldn rc
ori $40
str rc
sep r4
; ***************************************************************************************************************************************
;
; Berzerk Graphics
;
; ***************************************************************************************************************************************
Graphics:
Graphics_Left1:
.db $40,$C0,$40,$40,0
Graphics_Left2:
.db $40,$C0,$40,$A0,0
Graphics_Right1:
.db $40,$60,$40,$40,0
Graphics_Right2:
.db $40,$60,$40,$A0,0
Graphics_Missile:
.db $80,0
Graphics_Robot:
.db $40,$A0,$E0,$A0,0
; ***************************************************************************************************************************************
;
; Write byte D to RE. Add 8 to RE
;
; ***************************************************************************************************************************************
WriteDisplayByte:
str re ; save result
glo re ; down one row
adi 8
plo re
sep r3
br WriteDisplayByte
; ***************************************************************************************************************************************
;
; SECOND ROM SECTION
;
; ***************************************************************************************************************************************
.org 0C00h
; ***************************************************************************************************************************************
;
; Game starts here
;
; ***************************************************************************************************************************************
StartGame:
; --------------------------------------------------------------------------------------------------------------------------------------
; Come back here when life lost
; --------------------------------------------------------------------------------------------------------------------------------------
ghi r2 ; reset the player object position to something sensible
phi rf
ldi PlayerObject+3
plo rf
ldi 13
str rf
inc rf
str rf
ldi XRoom ; reset the start room
plo rf
ldi 0
str rf
inc rf
str rf
WaitKey5:
ldi >UpdateKeyboardState ; update keyboard state.
phi r4
ldi <UpdateKeyboardState
plo r4
sep r4
xri 5 ; keep going till key 5 pressed.
bnz WaitKey5
; --------------------------------------------------------------------------------------------------------------------------------------
; Come back here when re-entering a new rooom - initialise and draw
; --------------------------------------------------------------------------------------------------------------------------------------
NewRoom:
ldi RamPage ; reset the stack.
phi r2
ldi $FF
plo r2
ldi >InitialiseRoomAndPlayer ; re-initialise a room
phi r4
ldi <InitialiseRoomAndPlayer
plo r4
sep r4
ldi >DrawRoom ; draw the room.
phi r4
ldi <DrawRoom
plo r4
sep r4
; --------------------------------------------------------------------------------------------------------------------------------------
; Create Robots
; --------------------------------------------------------------------------------------------------------------------------------------
ghi r2 ; point RF to objects where can create robots
phi rf
ldi ObjectStart+ObjectRecordSize*2
plo rf
ldi >CreateRobot ; point R4 to create robot code.
phi r4
ldi <CreateRobot
plo r4
ldi 2 ; create various robot types 2,3 and 4.
sep r4
ldi 3
sep r4
ldi 4
sep r4
; --------------------------------------------------------------------------------------------------------------------------------------
; MAIN LOOP
; --------------------------------------------------------------------------------------------------------------------------------------
MainLoop:
ldi >UpdateKeyboardState ; update keyboard state.
phi r4
ldi <UpdateKeyboardState
plo r4
sep r4
; --------------------------------------------------------------------------------------------------------------------------------------
; Move/Check all objects
; --------------------------------------------------------------------------------------------------------------------------------------
ldi ObjectStart ; point RC to object start
plo rc
ghi r2
phi rc
ObjectLoop:
ldi >MoveObject ; move object
phi r4
ldi <MoveObject
plo r4
sep r4
glo rc ; go to next object.
adi ObjectRecordSize
plo rc
xri ObjectEnd ; loop back if not at end.
bnz ObjectLoop
; --------------------------------------------------------------------------------------------------------------------------------------
; Increment the frame counter (used for speed)
; --------------------------------------------------------------------------------------------------------------------------------------
ldi FrameCounter ; bump the frame counter
plo rc
ldn rc
adi 1
str rc
; --------------------------------------------------------------------------------------------------------------------------------------
; Check to see if exited through doors
; --------------------------------------------------------------------------------------------------------------------------------------
ldi PlayerObject+3 ; point RC to Player.X
plo rc
ghi r2 ; point RD to XRoom
phi rd
ldi XRoom
plo rd
ldn rc ; read RC (Player X)
bz MoveLeftRoom
xri $3A
bz MoveRightRoom
inc rc ; point RC to Player Y
inc rd ; point RD to YRoom
ldn rc ; read RC (Player Y)
bz MoveUpRoom
xri $1B
bz MoveDownRoom
; --------------------------------------------------------------------------------------------------------------------------------------
; Synchronise with RCAS2 Timer Counter
; --------------------------------------------------------------------------------------------------------------------------------------
Synchronise:
ldi Studio2SyncTimer ; synchronise and reset
plo rc
ldn rc
bnz Synchronise
ldi 3*1
str rc
br MainLoop
; --------------------------------------------------------------------------------------------------------------------------------------
; Handle vertical moves (room->room)
; --------------------------------------------------------------------------------------------------------------------------------------
MoveDownRoom:
ldi 1
br MoveVRoom
MoveUpRoom:
ldi $FF
MoveVRoom: ; add offset to RD (points to YRoom)
plo re
sex rd
add
str rd
glo re
shl
ldi 1
bnf MoveVRoom2
ldi 26
MoveVRoom2:
str rc
br NewRoom
; --------------------------------------------------------------------------------------------------------------------------------------
; Handle horizontal moves (room->room)
; --------------------------------------------------------------------------------------------------------------------------------------
MoveRightRoom:
ldi 1
br MoveHRoom
MoveLeftRoom:
ldi $FF
MoveHRoom: ; add offset to RD (points to XRoom)
plo re
sex rd
add
str rd
glo re
shl
ldi 2
bnf MoveHRoom2
ldi $38
MoveHRoom2:
str rc
br NewRoom
; ***************************************************************************************************************************************
;
; Dead if reached here.
;
; ***************************************************************************************************************************************
LifeLost:
ghi r2 ; point RF to lives lost
phi rf
ldi LivesLost
plo rf
ldn rf ; bump lives lost
adi 1
str rf
xri 3 ; lost 3 lives, if not, try again
bnz StartGame
; ***************************************************************************************************************************************
;
; Display Score
;
; ***************************************************************************************************************************************
ghi r2 ; point RD to the score.
phi rd
ldi Score
plo rd
ldi 6 ; make 3 LSBs of E 110 (screen position)
plo re
ldi >WriteDisplayByte ; point RA to the byte-writer
phi ra
ldi <WriteDisplayByte
plo ra
ScoreWriteLoop:
glo re ; convert 3 LSBs of RE to screen address
ani 7
adi 128-40
plo re
ldi VideoPage ; put in video page
phi re
ldi $00
sep ra
lda rd ; read next score digit
adi $10 ; score table offset in BIOS
plo r4
ldi $02 ; read from $210+n
phi r4
ldn r4 ; into D, the new offset
plo r4 ; put into R4, R4 now contains 5 rows graphic data
ldi 5 ; set R5.0 to 6
plo r5
OutputChar:
lda r4 ; read character and advance
shr ; centre in byte
shr
sep ra ; output it
dec r5 ; decrement counter
glo r5
bnz OutputChar ; loop back if nonzero
ldi $00
sep ra
dec re ; previous value of 3 LSBs.
glo re
ani 7
bnz ScoreWriteLoop
Halt: br Halt ; game over, stop forever.
; ***************************************************************************************************************************************
;
; Make object @RC chase the player
;
; ***************************************************************************************************************************************
ChasePlayer:
ghi rc ; point RF to RC+3 X Position.
phi rf ; point RE to PlayerObject+3
phi re
glo rc
adi 3
plo rf
ldi PlayerObject+3
plo re
sex rf
glo r9 ; check bit 4 of the sync counter
ani $10
bz CP_Horizontal
inc re ; point to Y coordinates
inc rf
ldn re
sm
ldi 2
bnf CP_1
ldi 8
sep r4
CP_Horizontal:
ldn re ; calculate Player Object Coord - Object Coord
sm
ldi 4
bnf CP_1 ; if >= return 4 (left) else return 6 (right)
ldi 6
CP_1: sep r4
; ***************************************************************************************************************************************
;
; Check to see if missile object at RC has collided with a Player or a Robot. If it has delete both (set delete flags)
; Jump to lost-life code if required, add score if required.
;
; Runs in R6, Returns to R5, must preserve RC. May crash out if player dies.
; ***************************************************************************************************************************************
CheckHitPlayerRobotObjects:
ghi rc ; RD <- RC+3 e.g. x position of missile
phi rd
glo rc
adi 3
plo rd
ghi r2 ; RE points to the Object List
phi re
ldi ObjectStart
plo re
CHPRO_Loop:
ldn re ; get ID/Flags for Object being tested
shl ; check in use flag.
bdf CHPRO_Next ; skip if not in use.
ldn re ; get ID
ani 15
xri 1 ; if missile don't check.
bz CHPRO_Next
ghi re ; point RF to x position.
phi rf
glo re
adi 3
plo rf
sex rf
ldn rd ; check |missile.X - object.X|
smi 1
sm
bdf CHPRO_1
sdi 0
CHPRO_1:smi 2 ; check that value is < 2
bdf CHPRO_Next
inc rd ; calculate |missile.Y - object.Y|
inc rf
ldn rd
smi 2
sm
dec rd
bdf CHPRO_2
sdi 0
CHPRO_2:smi 3
bnf CHPRO_Hit
CHPRO_Next:
glo re ; go to next one
adi ObjectRecordSize
plo re
xri ObjectEnd ; loop back if not reached the end.
bnz CHPRO_Loop
sep r5
CHPRO_Hit:
ldn rc ; set delete on missile
ori $40
str rc
ldn re ; set delete on object
ori $40
str re
glo re ; did we hit the player object
xri PlayerObject
bnz CHPRO_HitRobot
ldi >LifeLost ; lost a life.
phi r3
ldi <LifeLost
plo r3
sep r3
CHPRO_HitRobot:
ldi Score+1 ; RF points to score+1
plo rf
ldn re ; Get object ID 2-4
ani 15
smi 1 ; now 1,2 or 3 representing 10,20,30 points
CHPRO_BumpScore:
sex rf ; add to the current digit.
add
str rf
smi 10 ; if < 10 then no carry out to next digit
bnf CHPRO_Exit
str rf ; save modulo 10 value
ldi 1 ; carry 1 forward.
inc rf
br CHPRO_BumpScore
CHPRO_Exit:
sep r5
; ***************************************************************************************************************************************
;
; Create Robots of type D at position RF.
;
; ***************************************************************************************************************************************
CreateRobot:
phi re ; save type in RE.1
ldi >Random ; random in R5
phi r5
ldi <Random
plo r5
sep r5 ; random number
ani 3 ; from 0-3 robots
adi 1 ; from 1-4 robots
plo re ; save in RE.0
CRBT_Loop:
glo rf ; reached end of storage space
smi ObjectEnd-ObjectRecordSize*2
bdf CRBT_Exit ; if not enough space for two objects then exit.
ghi re ; get type
ori $20 ; set not-drawn-yet flag
str rf ; write to ID/Flags[0] and bump
inc rf
ghi re ; type 2,3,4
adi 252 ; set DF if 4.
ldi 15 ; slow speed.
bnf CRBT_0
ldi 7 ; fast speed.
CRBT_0:
str rf ; write to speed[1] and bump
inc rf
ldi 0 ; write 0 to direction[2] and bump
str rf
inc rf
dec r2 ; space on stack.
CRBT_XPosition:
sep r5 ; random number 0-255
ani 7 ; 0-7
smi 5
bdf CRBT_XPosition
adi 5 ; 0-5
shl ; x2
shl ; x4
str r2
shl ; x8
sex r2
add ; x12
adi 1
str r2
glo rf
shr
ani 7
add
str rf ; write to xPosition[3]
str r2
ghi r2 ; RD ^ PlayerX
phi rd
ldi PlayerObject+3
plo rd
ldn rd ; read PlayerX
sm ; PlayerX - RobotX
bdf CRBT_NotAbs
sdi 0
CRBT_NotAbs: ; |PlayerX-RobotX|
smi 8
bnf CRBT_XPosition
inc rf ; bump to yPosition[4]
CRBT_YPosition:
sep r5 ; random number 0-255
ani 3 ; 0-3
bz CRBT_YPosition ; 1-3
smi 1 ; 0-2
shl ; x2
str r2
shl ; x4
shl ; x8
sex r2
add ; x10
adi 2 ; spacing
str rf ; write to yPosition[4]
inc rf ; move to next free slot
inc rf
ghi re ; type 2,3,4
xri 2 ; if 2 skip
bz CRBT_NotFire
glo rf ; 3 and 4 allow space for missile firer.
adi ObjectRecordSize
plo rf
CRBT_NotFire:
inc r2 ; fix stack back.
dec re ; decrement the counter
glo re
bnz CRBT_Loop ; keep going till zero.
CRBT_Exit:
sep r3
br CreateRobot ; re-entrant subroutine.
.org $DFF
|
; A165749: a(n) = (9/5)*(1+4*(-9)^(n-1)).
; Submitted by Jamie Morken(s4)
; 1,9,-63,585,-5247,47241,-425151,3826377,-34437375,309936393,-2789427519,25104847689,-225943629183,2033492662665,-18301433963967,164712905675721,-1482416151081471,13341745359733257,-120075708237599295,1080681374138393673,-9726132367245543039,87535191305209887369,-787816721746888986303,7090350495722000876745,-63813154461498007890687,574318390153482071016201,-5168865511381338639145791,46519789602432047752312137,-418678106421888429770809215,3768102957796995867937282953
mov $2,$0
bin $2,$0
lpb $0
sub $0,1
sub $2,2
mov $1,$2
mul $1,9
mov $2,0
sub $2,$1
lpe
mov $0,$2
|
;
; Generic pseudo graphics routines for text-only platforms
;
; Written by Stefano Bodrato 30/01/2002
;
;
; Erases pixel at (x,y) coordinate.
;
;
; $Id: respixl.asm,v 1.5 2015/01/19 01:32:51 pauloscustodio Exp $
;
INCLUDE "graphics/text/textgfx.inc"
PUBLIC respixel
EXTERN textpixl
EXTERN coords
EXTERN base_graphics
.respixel
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
ld (coords),hl
push bc
ld c,a
ld b,h
push bc
srl b
srl c
ld hl,(base_graphics)
ld a,c
ld c,b ; !!
and a
jr z,r_zero
ld b,a
ld de,maxx/2
.r_loop
add hl,de
djnz r_loop
.r_zero ; hl = char address
ld e,c
add hl,de
ld a,(hl) ; get current symbol
ld e,a
push hl
ld hl,textpixl
ld e,0
ld b,16
.ckmap cp (hl)
jr z,chfound
inc hl
inc e
djnz ckmap
ld e,0
.chfound ld a,e
pop hl
ex (sp),hl ; save char address <=> restore x,y
ld b,a
ld a,1 ; the bit we want to draw
bit 0,h
jr z,iseven
add a,a ; move right the bit
.iseven
bit 0,l
jr z,evenrow
add a,a
add a,a ; move down the bit
.evenrow
cpl
and b
ld hl,textpixl
ld d,0
ld e,a
add hl,de
ld a,(hl)
pop hl
ld (hl),a
pop bc
ret
|
; A249827: Row 3 of A246278: replace in 2n each prime factor p(k) with prime p(k+2).
; 5,25,35,125,55,175,65,625,245,275,85,875,95,325,385,3125,115,1225,145,1375,455,425,155,4375,605,475,1715,1625,185,1925,205,15625,595,575,715,6125,215,725,665,6875,235,2275,265,2125,2695,775,295,21875,845,3025,805,2375,305,8575,935,8125,1015,925,335,9625,355,1025,3185,78125,1045,2975,365,2875,1085,3575,395,30625,415,1075,4235,3625,1105,3325,445,34375,12005,1175,485,11375,1265,1325,1295,10625,505,13475,1235,3875,1435,1475,1595,109375,515,4225,4165,15125
seq $0,253885 ; Permutation of even numbers: a(n) = A003961(n+1) - 1.
seq $0,3961 ; Completely multiplicative with a(prime(k)) = prime(k+1).
mul $0,5
|
SFX_Snare6_4_Ch7:
unknownnoise0x20 0, 129, 16
endchannel
|
; A166660: Totally multiplicative sequence with a(p) = 2p+1 for prime p.
; Submitted by Jamie Morken(s4)
; 1,5,7,25,11,35,15,125,49,55,23,175,27,75,77,625,35,245,39,275,105,115,47,875,121,135,343,375,59,385,63,3125,161,175,165,1225,75,195,189,1375,83,525,87,575,539,235,95,4375,225,605,245,675,107,1715,253,1875,273,295,119,1925,123,315,735,15625,297,805,135,875,329,825,143,6125,147,375,847,975,345,945,159,6875,2401,415,167,2625,385,435,413,2875,179,2695,405,1175,441,475,429,21875,195,1125,1127,3025
add $0,1
mov $1,1
mov $2,2
mov $4,1
lpb $0
mul $1,$4
mov $3,$0
lpb $3
mov $4,$0
mod $4,$2
add $2,1
cmp $4,0
cmp $4,0
sub $3,$4
lpe
div $0,$2
mov $4,$2
add $5,$2
lpb $5
mul $4,2
add $4,1
mov $5,1
lpe
lpe
mov $0,$1
|
#include <link/i_link_manager.hpp>
|
; $Id: 32BitTo32Bit.asm 69221 2017-10-24 15:07:46Z vboxsync $
;; @file
; VMM - World Switchers, 32-Bit to 32-Bit.
;
;
; Copyright (C) 2006-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
;*******************************************************************************
;* Defined Constants And Macros *
;*******************************************************************************
%define SWITCHER_TYPE VMMSWITCHER_32_TO_32
%define SWITCHER_DESCRIPTION "32-bit to/from 32-bit"
%define NAME_OVERLOAD(name) vmmR3Switcher32BitTo32Bit_ %+ name
%define SWITCHER_FIX_INTER_CR3_HC FIX_INTER_32BIT_CR3
%define SWITCHER_FIX_INTER_CR3_GC FIX_INTER_32BIT_CR3
;*******************************************************************************
;* Header Files *
;*******************************************************************************
%include "VBox/asmdefs.mac"
%include "VMMSwitcher/PAEand32Bit.mac"
|
/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file ir_constant_expression.cpp
* Evaluate and process constant valued expressions
*
* In GLSL, constant valued expressions are used in several places. These
* must be processed and evaluated very early in the compilation process.
*
* * Sizes of arrays
* * Initializers for uniforms
* * Initializers for \c const variables
*/
#include <math.h>
#include "main/core.h" /* for MAX2, MIN2, CLAMP */
#include "ir.h"
#include "ir_visitor.h"
#include "glsl_types.h"
#include "program/hash_table.h"
#if defined(_MSC_VER) && (_MSC_VER < 1800)
static int isnormal(double x)
{
return _fpclass(x) == _FPCLASS_NN || _fpclass(x) == _FPCLASS_PN;
}
#elif defined(__SUNPRO_CC)
#include <ieeefp.h>
static int isnormal(double x)
{
return fpclass(x) == FP_NORMAL;
}
#endif
#if defined(_MSC_VER)
static double copysign(double x, double y)
{
return _copysign(x, y);
}
#endif
static float
dot(ir_constant *op0, ir_constant *op1)
{
assert(op0->type->is_float() && op1->type->is_float());
float result = 0;
for (unsigned c = 0; c < op0->type->components(); c++)
result += op0->value.f[c] * op1->value.f[c];
return result;
}
/* This method is the only one supported by gcc. Unions in particular
* are iffy, and read-through-converted-pointer is killed by strict
* aliasing. OTOH, the compiler sees through the memcpy, so the
* resulting asm is reasonable.
*/
static float
bitcast_u2f(unsigned int u)
{
assert(sizeof(float) == sizeof(unsigned int));
float f;
memcpy(&f, &u, sizeof(f));
return f;
}
static unsigned int
bitcast_f2u(float f)
{
assert(sizeof(float) == sizeof(unsigned int));
unsigned int u;
memcpy(&u, &f, sizeof(f));
return u;
}
/**
* Evaluate one component of a floating-point 4x8 unpacking function.
*/
typedef uint8_t
(*pack_1x8_func_t)(float);
/**
* Evaluate one component of a floating-point 2x16 unpacking function.
*/
typedef uint16_t
(*pack_1x16_func_t)(float);
/**
* Evaluate one component of a floating-point 4x8 unpacking function.
*/
typedef float
(*unpack_1x8_func_t)(uint8_t);
/**
* Evaluate one component of a floating-point 2x16 unpacking function.
*/
typedef float
(*unpack_1x16_func_t)(uint16_t);
/**
* Evaluate a 2x16 floating-point packing function.
*/
static uint32_t
pack_2x16(pack_1x16_func_t pack_1x16,
float x, float y)
{
/* From section 8.4 of the GLSL ES 3.00 spec:
*
* packSnorm2x16
* -------------
* The first component of the vector will be written to the least
* significant bits of the output; the last component will be written to
* the most significant bits.
*
* The specifications for the other packing functions contain similar
* language.
*/
uint32_t u = 0;
u |= ((uint32_t) pack_1x16(x) << 0);
u |= ((uint32_t) pack_1x16(y) << 16);
return u;
}
/**
* Evaluate a 4x8 floating-point packing function.
*/
static uint32_t
pack_4x8(pack_1x8_func_t pack_1x8,
float x, float y, float z, float w)
{
/* From section 8.4 of the GLSL 4.30 spec:
*
* packSnorm4x8
* ------------
* The first component of the vector will be written to the least
* significant bits of the output; the last component will be written to
* the most significant bits.
*
* The specifications for the other packing functions contain similar
* language.
*/
uint32_t u = 0;
u |= ((uint32_t) pack_1x8(x) << 0);
u |= ((uint32_t) pack_1x8(y) << 8);
u |= ((uint32_t) pack_1x8(z) << 16);
u |= ((uint32_t) pack_1x8(w) << 24);
return u;
}
/**
* Evaluate a 2x16 floating-point unpacking function.
*/
static void
unpack_2x16(unpack_1x16_func_t unpack_1x16,
uint32_t u,
float *x, float *y)
{
/* From section 8.4 of the GLSL ES 3.00 spec:
*
* unpackSnorm2x16
* ---------------
* The first component of the returned vector will be extracted from
* the least significant bits of the input; the last component will be
* extracted from the most significant bits.
*
* The specifications for the other unpacking functions contain similar
* language.
*/
*x = unpack_1x16((uint16_t) (u & 0xffff));
*y = unpack_1x16((uint16_t) (u >> 16));
}
/**
* Evaluate a 4x8 floating-point unpacking function.
*/
static void
unpack_4x8(unpack_1x8_func_t unpack_1x8, uint32_t u,
float *x, float *y, float *z, float *w)
{
/* From section 8.4 of the GLSL 4.30 spec:
*
* unpackSnorm4x8
* --------------
* The first component of the returned vector will be extracted from
* the least significant bits of the input; the last component will be
* extracted from the most significant bits.
*
* The specifications for the other unpacking functions contain similar
* language.
*/
*x = unpack_1x8((uint8_t) (u & 0xff));
*y = unpack_1x8((uint8_t) (u >> 8));
*z = unpack_1x8((uint8_t) (u >> 16));
*w = unpack_1x8((uint8_t) (u >> 24));
}
/**
* Evaluate one component of packSnorm4x8.
*/
static uint8_t
pack_snorm_1x8(float x)
{
/* From section 8.4 of the GLSL 4.30 spec:
*
* packSnorm4x8
* ------------
* The conversion for component c of v to fixed point is done as
* follows:
*
* packSnorm4x8: round(clamp(c, -1, +1) * 127.0)
*
* We must first cast the float to an int, because casting a negative
* float to a uint is undefined.
*/
return (uint8_t) (int8_t)
_mesa_round_to_even(CLAMP(x, -1.0f, +1.0f) * 127.0f);
}
/**
* Evaluate one component of packSnorm2x16.
*/
static uint16_t
pack_snorm_1x16(float x)
{
/* From section 8.4 of the GLSL ES 3.00 spec:
*
* packSnorm2x16
* -------------
* The conversion for component c of v to fixed point is done as
* follows:
*
* packSnorm2x16: round(clamp(c, -1, +1) * 32767.0)
*
* We must first cast the float to an int, because casting a negative
* float to a uint is undefined.
*/
return (uint16_t) (int16_t)
_mesa_round_to_even(CLAMP(x, -1.0f, +1.0f) * 32767.0f);
}
/**
* Evaluate one component of unpackSnorm4x8.
*/
static float
unpack_snorm_1x8(uint8_t u)
{
/* From section 8.4 of the GLSL 4.30 spec:
*
* unpackSnorm4x8
* --------------
* The conversion for unpacked fixed-point value f to floating point is
* done as follows:
*
* unpackSnorm4x8: clamp(f / 127.0, -1, +1)
*/
return CLAMP((int8_t) u / 127.0f, -1.0f, +1.0f);
}
/**
* Evaluate one component of unpackSnorm2x16.
*/
static float
unpack_snorm_1x16(uint16_t u)
{
/* From section 8.4 of the GLSL ES 3.00 spec:
*
* unpackSnorm2x16
* ---------------
* The conversion for unpacked fixed-point value f to floating point is
* done as follows:
*
* unpackSnorm2x16: clamp(f / 32767.0, -1, +1)
*/
return CLAMP((int16_t) u / 32767.0f, -1.0f, +1.0f);
}
/**
* Evaluate one component packUnorm4x8.
*/
static uint8_t
pack_unorm_1x8(float x)
{
/* From section 8.4 of the GLSL 4.30 spec:
*
* packUnorm4x8
* ------------
* The conversion for component c of v to fixed point is done as
* follows:
*
* packUnorm4x8: round(clamp(c, 0, +1) * 255.0)
*/
return (uint8_t) _mesa_round_to_even(CLAMP(x, 0.0f, 1.0f) * 255.0f);
}
/**
* Evaluate one component packUnorm2x16.
*/
static uint16_t
pack_unorm_1x16(float x)
{
/* From section 8.4 of the GLSL ES 3.00 spec:
*
* packUnorm2x16
* -------------
* The conversion for component c of v to fixed point is done as
* follows:
*
* packUnorm2x16: round(clamp(c, 0, +1) * 65535.0)
*/
return (uint16_t) _mesa_round_to_even(CLAMP(x, 0.0f, 1.0f) * 65535.0f);
}
/**
* Evaluate one component of unpackUnorm4x8.
*/
static float
unpack_unorm_1x8(uint8_t u)
{
/* From section 8.4 of the GLSL 4.30 spec:
*
* unpackUnorm4x8
* --------------
* The conversion for unpacked fixed-point value f to floating point is
* done as follows:
*
* unpackUnorm4x8: f / 255.0
*/
return (float) u / 255.0f;
}
/**
* Evaluate one component of unpackUnorm2x16.
*/
static float
unpack_unorm_1x16(uint16_t u)
{
/* From section 8.4 of the GLSL ES 3.00 spec:
*
* unpackUnorm2x16
* ---------------
* The conversion for unpacked fixed-point value f to floating point is
* done as follows:
*
* unpackUnorm2x16: f / 65535.0
*/
return (float) u / 65535.0f;
}
/**
* Evaluate one component of packHalf2x16.
*/
static uint16_t
pack_half_1x16(float x)
{
return _mesa_float_to_half(x);
}
/**
* Evaluate one component of unpackHalf2x16.
*/
static float
unpack_half_1x16(uint16_t u)
{
return _mesa_half_to_float(u);
}
ir_constant *
ir_rvalue::constant_expression_value(struct hash_table *variable_context)
{
assert(this->type->is_error());
return NULL;
}
ir_constant *
ir_expression::constant_expression_value(struct hash_table *variable_context)
{
if (this->type->is_error())
return NULL;
ir_constant *op[Elements(this->operands)] = { NULL, };
ir_constant_data data;
memset(&data, 0, sizeof(data));
for (unsigned operand = 0; operand < this->get_num_operands(); operand++) {
op[operand] = this->operands[operand]->constant_expression_value(variable_context);
if (!op[operand])
return NULL;
}
if (op[1] != NULL)
switch (this->operation) {
case ir_binop_lshift:
case ir_binop_rshift:
case ir_binop_ldexp:
case ir_binop_vector_extract:
case ir_triop_csel:
case ir_triop_bitfield_extract:
break;
default:
assert(op[0]->type->base_type == op[1]->type->base_type);
break;
}
bool op0_scalar = op[0]->type->is_scalar();
bool op1_scalar = op[1] != NULL && op[1]->type->is_scalar();
/* When iterating over a vector or matrix's components, we want to increase
* the loop counter. However, for scalars, we want to stay at 0.
*/
unsigned c0_inc = op0_scalar ? 0 : 1;
unsigned c1_inc = op1_scalar ? 0 : 1;
unsigned components;
if (op1_scalar || !op[1]) {
components = op[0]->type->components();
} else {
components = op[1]->type->components();
}
void *ctx = ralloc_parent(this);
/* Handle array operations here, rather than below. */
if (op[0]->type->is_array()) {
assert(op[1] != NULL && op[1]->type->is_array());
switch (this->operation) {
case ir_binop_all_equal:
return new(ctx) ir_constant(op[0]->has_value(op[1]));
case ir_binop_any_nequal:
return new(ctx) ir_constant(!op[0]->has_value(op[1]));
default:
break;
}
return NULL;
}
switch (this->operation) {
case ir_unop_bit_not:
switch (op[0]->type->base_type) {
case GLSL_TYPE_INT:
for (unsigned c = 0; c < components; c++)
data.i[c] = ~ op[0]->value.i[c];
break;
case GLSL_TYPE_UINT:
for (unsigned c = 0; c < components; c++)
data.u[c] = ~ op[0]->value.u[c];
break;
default:
assert(0);
}
break;
case ir_unop_logic_not:
assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
for (unsigned c = 0; c < op[0]->type->components(); c++)
data.b[c] = !op[0]->value.b[c];
break;
case ir_unop_f2i:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.i[c] = (int) op[0]->value.f[c];
}
break;
case ir_unop_f2u:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.i[c] = (unsigned) op[0]->value.f[c];
}
break;
case ir_unop_i2f:
assert(op[0]->type->base_type == GLSL_TYPE_INT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = (float) op[0]->value.i[c];
}
break;
case ir_unop_u2f:
assert(op[0]->type->base_type == GLSL_TYPE_UINT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = (float) op[0]->value.u[c];
}
break;
case ir_unop_b2f:
assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = op[0]->value.b[c] ? 1.0F : 0.0F;
}
break;
case ir_unop_f2b:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.b[c] = op[0]->value.f[c] != 0.0F ? true : false;
}
break;
case ir_unop_b2i:
assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.u[c] = op[0]->value.b[c] ? 1 : 0;
}
break;
case ir_unop_i2b:
assert(op[0]->type->is_integer());
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.b[c] = op[0]->value.u[c] ? true : false;
}
break;
case ir_unop_u2i:
assert(op[0]->type->base_type == GLSL_TYPE_UINT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.i[c] = op[0]->value.u[c];
}
break;
case ir_unop_i2u:
assert(op[0]->type->base_type == GLSL_TYPE_INT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.u[c] = op[0]->value.i[c];
}
break;
case ir_unop_bitcast_i2f:
assert(op[0]->type->base_type == GLSL_TYPE_INT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = bitcast_u2f(op[0]->value.i[c]);
}
break;
case ir_unop_bitcast_f2i:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.i[c] = bitcast_f2u(op[0]->value.f[c]);
}
break;
case ir_unop_bitcast_u2f:
assert(op[0]->type->base_type == GLSL_TYPE_UINT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = bitcast_u2f(op[0]->value.u[c]);
}
break;
case ir_unop_bitcast_f2u:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.u[c] = bitcast_f2u(op[0]->value.f[c]);
}
break;
case ir_unop_any:
assert(op[0]->type->is_boolean());
data.b[0] = false;
for (unsigned c = 0; c < op[0]->type->components(); c++) {
if (op[0]->value.b[c])
data.b[0] = true;
}
break;
case ir_unop_trunc:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = truncf(op[0]->value.f[c]);
}
break;
case ir_unop_round_even:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = _mesa_round_to_even(op[0]->value.f[c]);
}
break;
case ir_unop_ceil:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = ceilf(op[0]->value.f[c]);
}
break;
case ir_unop_floor:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = floorf(op[0]->value.f[c]);
}
break;
case ir_unop_fract:
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (this->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = 0;
break;
case GLSL_TYPE_INT:
data.i[c] = 0;
break;
case GLSL_TYPE_FLOAT:
data.f[c] = op[0]->value.f[c] - floor(op[0]->value.f[c]);
break;
default:
assert(0);
}
}
break;
case ir_unop_sin:
case ir_unop_sin_reduced:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = sinf(op[0]->value.f[c]);
}
break;
case ir_unop_cos:
case ir_unop_cos_reduced:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = cosf(op[0]->value.f[c]);
}
break;
case ir_unop_neg:
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (this->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = -((int) op[0]->value.u[c]);
break;
case GLSL_TYPE_INT:
data.i[c] = -op[0]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.f[c] = -op[0]->value.f[c];
break;
default:
assert(0);
}
}
break;
case ir_unop_abs:
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (this->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c];
break;
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c];
if (data.i[c] < 0)
data.i[c] = -data.i[c];
break;
case GLSL_TYPE_FLOAT:
data.f[c] = fabs(op[0]->value.f[c]);
break;
default:
assert(0);
}
}
break;
case ir_unop_sign:
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (this->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.i[c] > 0;
break;
case GLSL_TYPE_INT:
data.i[c] = (op[0]->value.i[c] > 0) - (op[0]->value.i[c] < 0);
break;
case GLSL_TYPE_FLOAT:
data.f[c] = float((op[0]->value.f[c] > 0)-(op[0]->value.f[c] < 0));
break;
default:
assert(0);
}
}
break;
case ir_unop_rcp:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (this->type->base_type) {
case GLSL_TYPE_UINT:
if (op[0]->value.u[c] != 0.0)
data.u[c] = 1 / op[0]->value.u[c];
break;
case GLSL_TYPE_INT:
if (op[0]->value.i[c] != 0.0)
data.i[c] = 1 / op[0]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
if (op[0]->value.f[c] != 0.0)
data.f[c] = 1.0F / op[0]->value.f[c];
break;
default:
assert(0);
}
}
break;
case ir_unop_rsq:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = 1.0F / sqrtf(op[0]->value.f[c]);
}
break;
case ir_unop_sqrt:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = sqrtf(op[0]->value.f[c]);
}
break;
case ir_unop_exp:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = expf(op[0]->value.f[c]);
}
break;
case ir_unop_exp2:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = exp2f(op[0]->value.f[c]);
}
break;
case ir_unop_log:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = logf(op[0]->value.f[c]);
}
break;
case ir_unop_log2:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = log2f(op[0]->value.f[c]);
}
break;
case ir_unop_dFdx:
case ir_unop_dFdy:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = 0.0;
}
break;
case ir_unop_pack_snorm_2x16:
assert(op[0]->type == glsl_type::vec2_type);
data.u[0] = pack_2x16(pack_snorm_1x16,
op[0]->value.f[0],
op[0]->value.f[1]);
break;
case ir_unop_pack_snorm_4x8:
assert(op[0]->type == glsl_type::vec4_type);
data.u[0] = pack_4x8(pack_snorm_1x8,
op[0]->value.f[0],
op[0]->value.f[1],
op[0]->value.f[2],
op[0]->value.f[3]);
break;
case ir_unop_unpack_snorm_2x16:
assert(op[0]->type == glsl_type::uint_type);
unpack_2x16(unpack_snorm_1x16,
op[0]->value.u[0],
&data.f[0], &data.f[1]);
break;
case ir_unop_unpack_snorm_4x8:
assert(op[0]->type == glsl_type::uint_type);
unpack_4x8(unpack_snorm_1x8,
op[0]->value.u[0],
&data.f[0], &data.f[1], &data.f[2], &data.f[3]);
break;
case ir_unop_pack_unorm_2x16:
assert(op[0]->type == glsl_type::vec2_type);
data.u[0] = pack_2x16(pack_unorm_1x16,
op[0]->value.f[0],
op[0]->value.f[1]);
break;
case ir_unop_pack_unorm_4x8:
assert(op[0]->type == glsl_type::vec4_type);
data.u[0] = pack_4x8(pack_unorm_1x8,
op[0]->value.f[0],
op[0]->value.f[1],
op[0]->value.f[2],
op[0]->value.f[3]);
break;
case ir_unop_unpack_unorm_2x16:
assert(op[0]->type == glsl_type::uint_type);
unpack_2x16(unpack_unorm_1x16,
op[0]->value.u[0],
&data.f[0], &data.f[1]);
break;
case ir_unop_unpack_unorm_4x8:
assert(op[0]->type == glsl_type::uint_type);
unpack_4x8(unpack_unorm_1x8,
op[0]->value.u[0],
&data.f[0], &data.f[1], &data.f[2], &data.f[3]);
break;
case ir_unop_pack_half_2x16:
assert(op[0]->type == glsl_type::vec2_type);
data.u[0] = pack_2x16(pack_half_1x16,
op[0]->value.f[0],
op[0]->value.f[1]);
break;
case ir_unop_unpack_half_2x16:
assert(op[0]->type == glsl_type::uint_type);
unpack_2x16(unpack_half_1x16,
op[0]->value.u[0],
&data.f[0], &data.f[1]);
break;
case ir_binop_pow:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
data.f[c] = powf(op[0]->value.f[c], op[1]->value.f[c]);
}
break;
case ir_binop_dot:
data.f[0] = dot(op[0], op[1]);
break;
case ir_binop_min:
assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = MIN2(op[0]->value.u[c0], op[1]->value.u[c1]);
break;
case GLSL_TYPE_INT:
data.i[c] = MIN2(op[0]->value.i[c0], op[1]->value.i[c1]);
break;
case GLSL_TYPE_FLOAT:
data.f[c] = MIN2(op[0]->value.f[c0], op[1]->value.f[c1]);
break;
default:
assert(0);
}
}
break;
case ir_binop_max:
assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = MAX2(op[0]->value.u[c0], op[1]->value.u[c1]);
break;
case GLSL_TYPE_INT:
data.i[c] = MAX2(op[0]->value.i[c0], op[1]->value.i[c1]);
break;
case GLSL_TYPE_FLOAT:
data.f[c] = MAX2(op[0]->value.f[c0], op[1]->value.f[c1]);
break;
default:
assert(0);
}
}
break;
case ir_binop_add:
assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c0] + op[1]->value.u[c1];
break;
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c0] + op[1]->value.i[c1];
break;
case GLSL_TYPE_FLOAT:
data.f[c] = op[0]->value.f[c0] + op[1]->value.f[c1];
break;
default:
assert(0);
}
}
break;
case ir_binop_sub:
assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c0] - op[1]->value.u[c1];
break;
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c0] - op[1]->value.i[c1];
break;
case GLSL_TYPE_FLOAT:
data.f[c] = op[0]->value.f[c0] - op[1]->value.f[c1];
break;
default:
assert(0);
}
}
break;
case ir_binop_mul:
/* Check for equal types, or unequal types involving scalars */
if ((op[0]->type == op[1]->type && !op[0]->type->is_matrix())
|| op0_scalar || op1_scalar) {
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c0] * op[1]->value.u[c1];
break;
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c0] * op[1]->value.i[c1];
break;
case GLSL_TYPE_FLOAT:
data.f[c] = op[0]->value.f[c0] * op[1]->value.f[c1];
break;
default:
assert(0);
}
}
} else {
assert(op[0]->type->is_matrix() || op[1]->type->is_matrix());
/* Multiply an N-by-M matrix with an M-by-P matrix. Since either
* matrix can be a GLSL vector, either N or P can be 1.
*
* For vec*mat, the vector is treated as a row vector. This
* means the vector is a 1-row x M-column matrix.
*
* For mat*vec, the vector is treated as a column vector. Since
* matrix_columns is 1 for vectors, this just works.
*/
const unsigned n = op[0]->type->is_vector()
? 1 : op[0]->type->vector_elements;
const unsigned m = op[1]->type->vector_elements;
const unsigned p = op[1]->type->matrix_columns;
for (unsigned j = 0; j < p; j++) {
for (unsigned i = 0; i < n; i++) {
for (unsigned k = 0; k < m; k++) {
data.f[i+n*j] += op[0]->value.f[i+n*k]*op[1]->value.f[k+m*j];
}
}
}
}
break;
case ir_binop_div:
/* FINISHME: Emit warning when division-by-zero is detected. */
assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
if (op[1]->value.u[c1] == 0) {
data.u[c] = 0;
} else {
data.u[c] = op[0]->value.u[c0] / op[1]->value.u[c1];
}
break;
case GLSL_TYPE_INT:
if (op[1]->value.i[c1] == 0) {
data.i[c] = 0;
} else {
data.i[c] = op[0]->value.i[c0] / op[1]->value.i[c1];
}
break;
case GLSL_TYPE_FLOAT:
data.f[c] = op[0]->value.f[c0] / op[1]->value.f[c1];
break;
default:
assert(0);
}
}
break;
case ir_binop_mod:
/* FINISHME: Emit warning when division-by-zero is detected. */
assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
if (op[1]->value.u[c1] == 0) {
data.u[c] = 0;
} else {
data.u[c] = op[0]->value.u[c0] % op[1]->value.u[c1];
}
break;
case GLSL_TYPE_INT:
if (op[1]->value.i[c1] == 0) {
data.i[c] = 0;
} else {
data.i[c] = op[0]->value.i[c0] % op[1]->value.i[c1];
}
break;
case GLSL_TYPE_FLOAT:
/* We don't use fmod because it rounds toward zero; GLSL specifies
* the use of floor.
*/
data.f[c] = op[0]->value.f[c0] - op[1]->value.f[c1]
* floorf(op[0]->value.f[c0] / op[1]->value.f[c1]);
break;
default:
assert(0);
}
}
break;
case ir_binop_logic_and:
assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
for (unsigned c = 0; c < op[0]->type->components(); c++)
data.b[c] = op[0]->value.b[c] && op[1]->value.b[c];
break;
case ir_binop_logic_xor:
assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
for (unsigned c = 0; c < op[0]->type->components(); c++)
data.b[c] = op[0]->value.b[c] ^ op[1]->value.b[c];
break;
case ir_binop_logic_or:
assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
for (unsigned c = 0; c < op[0]->type->components(); c++)
data.b[c] = op[0]->value.b[c] || op[1]->value.b[c];
break;
case ir_binop_less:
assert(op[0]->type == op[1]->type);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.b[c] = op[0]->value.u[c] < op[1]->value.u[c];
break;
case GLSL_TYPE_INT:
data.b[c] = op[0]->value.i[c] < op[1]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.b[c] = op[0]->value.f[c] < op[1]->value.f[c];
break;
default:
assert(0);
}
}
break;
case ir_binop_greater:
assert(op[0]->type == op[1]->type);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.b[c] = op[0]->value.u[c] > op[1]->value.u[c];
break;
case GLSL_TYPE_INT:
data.b[c] = op[0]->value.i[c] > op[1]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.b[c] = op[0]->value.f[c] > op[1]->value.f[c];
break;
default:
assert(0);
}
}
break;
case ir_binop_lequal:
assert(op[0]->type == op[1]->type);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.b[c] = op[0]->value.u[c] <= op[1]->value.u[c];
break;
case GLSL_TYPE_INT:
data.b[c] = op[0]->value.i[c] <= op[1]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.b[c] = op[0]->value.f[c] <= op[1]->value.f[c];
break;
default:
assert(0);
}
}
break;
case ir_binop_gequal:
assert(op[0]->type == op[1]->type);
for (unsigned c = 0; c < op[0]->type->components(); c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.b[c] = op[0]->value.u[c] >= op[1]->value.u[c];
break;
case GLSL_TYPE_INT:
data.b[c] = op[0]->value.i[c] >= op[1]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.b[c] = op[0]->value.f[c] >= op[1]->value.f[c];
break;
default:
assert(0);
}
}
break;
case ir_binop_equal:
assert(op[0]->type == op[1]->type);
for (unsigned c = 0; c < components; c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.b[c] = op[0]->value.u[c] == op[1]->value.u[c];
break;
case GLSL_TYPE_INT:
data.b[c] = op[0]->value.i[c] == op[1]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.b[c] = op[0]->value.f[c] == op[1]->value.f[c];
break;
case GLSL_TYPE_BOOL:
data.b[c] = op[0]->value.b[c] == op[1]->value.b[c];
break;
default:
assert(0);
}
}
break;
case ir_binop_nequal:
assert(op[0]->type == op[1]->type);
for (unsigned c = 0; c < components; c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.b[c] = op[0]->value.u[c] != op[1]->value.u[c];
break;
case GLSL_TYPE_INT:
data.b[c] = op[0]->value.i[c] != op[1]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.b[c] = op[0]->value.f[c] != op[1]->value.f[c];
break;
case GLSL_TYPE_BOOL:
data.b[c] = op[0]->value.b[c] != op[1]->value.b[c];
break;
default:
assert(0);
}
}
break;
case ir_binop_all_equal:
data.b[0] = op[0]->has_value(op[1]);
break;
case ir_binop_any_nequal:
data.b[0] = !op[0]->has_value(op[1]);
break;
case ir_binop_lshift:
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
if (op[0]->type->base_type == GLSL_TYPE_INT &&
op[1]->type->base_type == GLSL_TYPE_INT) {
data.i[c] = op[0]->value.i[c0] << op[1]->value.i[c1];
} else if (op[0]->type->base_type == GLSL_TYPE_INT &&
op[1]->type->base_type == GLSL_TYPE_UINT) {
data.i[c] = op[0]->value.i[c0] << op[1]->value.u[c1];
} else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
op[1]->type->base_type == GLSL_TYPE_INT) {
data.u[c] = op[0]->value.u[c0] << op[1]->value.i[c1];
} else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
op[1]->type->base_type == GLSL_TYPE_UINT) {
data.u[c] = op[0]->value.u[c0] << op[1]->value.u[c1];
}
}
break;
case ir_binop_rshift:
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
if (op[0]->type->base_type == GLSL_TYPE_INT &&
op[1]->type->base_type == GLSL_TYPE_INT) {
data.i[c] = op[0]->value.i[c0] >> op[1]->value.i[c1];
} else if (op[0]->type->base_type == GLSL_TYPE_INT &&
op[1]->type->base_type == GLSL_TYPE_UINT) {
data.i[c] = op[0]->value.i[c0] >> op[1]->value.u[c1];
} else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
op[1]->type->base_type == GLSL_TYPE_INT) {
data.u[c] = op[0]->value.u[c0] >> op[1]->value.i[c1];
} else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
op[1]->type->base_type == GLSL_TYPE_UINT) {
data.u[c] = op[0]->value.u[c0] >> op[1]->value.u[c1];
}
}
break;
case ir_binop_bit_and:
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c0] & op[1]->value.i[c1];
break;
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c0] & op[1]->value.u[c1];
break;
default:
assert(0);
}
}
break;
case ir_binop_bit_or:
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c0] | op[1]->value.i[c1];
break;
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c0] | op[1]->value.u[c1];
break;
default:
assert(0);
}
}
break;
case ir_binop_vector_extract: {
const int c = CLAMP(op[1]->value.i[0], 0,
(int) op[0]->type->vector_elements - 1);
switch (op[0]->type->base_type) {
case GLSL_TYPE_UINT:
data.u[0] = op[0]->value.u[c];
break;
case GLSL_TYPE_INT:
data.i[0] = op[0]->value.i[c];
break;
case GLSL_TYPE_FLOAT:
data.f[0] = op[0]->value.f[c];
break;
case GLSL_TYPE_BOOL:
data.b[0] = op[0]->value.b[c];
break;
default:
assert(0);
}
break;
}
case ir_binop_bit_xor:
for (unsigned c = 0, c0 = 0, c1 = 0;
c < components;
c0 += c0_inc, c1 += c1_inc, c++) {
switch (op[0]->type->base_type) {
case GLSL_TYPE_INT:
data.i[c] = op[0]->value.i[c0] ^ op[1]->value.i[c1];
break;
case GLSL_TYPE_UINT:
data.u[c] = op[0]->value.u[c0] ^ op[1]->value.u[c1];
break;
default:
assert(0);
}
}
break;
case ir_unop_bitfield_reverse:
/* http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious */
for (unsigned c = 0; c < components; c++) {
unsigned int v = op[0]->value.u[c]; // input bits to be reversed
unsigned int r = v; // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1) {
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
data.u[c] = r;
}
break;
case ir_unop_bit_count:
for (unsigned c = 0; c < components; c++) {
unsigned count = 0;
unsigned v = op[0]->value.u[c];
for (; v; count++) {
v &= v - 1;
}
data.u[c] = count;
}
break;
case ir_unop_find_msb:
for (unsigned c = 0; c < components; c++) {
int v = op[0]->value.i[c];
if (v == 0 || (op[0]->type->base_type == GLSL_TYPE_INT && v == -1))
data.i[c] = -1;
else {
int count = 0;
int top_bit = op[0]->type->base_type == GLSL_TYPE_UINT
? 0 : v & (1 << 31);
while (((v & (1 << 31)) == top_bit) && count != 32) {
count++;
v <<= 1;
}
data.i[c] = 31 - count;
}
}
break;
case ir_unop_find_lsb:
for (unsigned c = 0; c < components; c++) {
if (op[0]->value.i[c] == 0)
data.i[c] = -1;
else {
unsigned pos = 0;
unsigned v = op[0]->value.u[c];
for (; !(v & 1); v >>= 1) {
pos++;
}
data.u[c] = pos;
}
}
break;
case ir_triop_bitfield_extract: {
int offset = op[1]->value.i[0];
int bits = op[2]->value.i[0];
for (unsigned c = 0; c < components; c++) {
if (bits == 0)
data.u[c] = 0;
else if (offset < 0 || bits < 0)
data.u[c] = 0; /* Undefined, per spec. */
else if (offset + bits > 32)
data.u[c] = 0; /* Undefined, per spec. */
else {
if (op[0]->type->base_type == GLSL_TYPE_INT) {
/* int so that the right shift will sign-extend. */
int value = op[0]->value.i[c];
value <<= 32 - bits - offset;
value >>= 32 - bits;
data.i[c] = value;
} else {
unsigned value = op[0]->value.u[c];
value <<= 32 - bits - offset;
value >>= 32 - bits;
data.u[c] = value;
}
}
}
break;
}
case ir_binop_bfm: {
int bits = op[0]->value.i[0];
int offset = op[1]->value.i[0];
for (unsigned c = 0; c < components; c++) {
if (bits == 0)
data.u[c] = op[0]->value.u[c];
else if (offset < 0 || bits < 0)
data.u[c] = 0; /* Undefined for bitfieldInsert, per spec. */
else if (offset + bits > 32)
data.u[c] = 0; /* Undefined for bitfieldInsert, per spec. */
else
data.u[c] = ((1 << bits) - 1) << offset;
}
break;
}
case ir_binop_ldexp:
for (unsigned c = 0; c < components; c++) {
data.f[c] = ldexp(op[0]->value.f[c], op[1]->value.i[c]);
/* Flush subnormal values to zero. */
if (!isnormal(data.f[c]))
data.f[c] = copysign(0.0f, op[0]->value.f[c]);
}
break;
case ir_triop_fma:
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
assert(op[1]->type->base_type == GLSL_TYPE_FLOAT);
assert(op[2]->type->base_type == GLSL_TYPE_FLOAT);
for (unsigned c = 0; c < components; c++) {
data.f[c] = op[0]->value.f[c] * op[1]->value.f[c]
+ op[2]->value.f[c];
}
break;
case ir_triop_lrp: {
assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
assert(op[1]->type->base_type == GLSL_TYPE_FLOAT);
assert(op[2]->type->base_type == GLSL_TYPE_FLOAT);
unsigned c2_inc = op[2]->type->is_scalar() ? 0 : 1;
for (unsigned c = 0, c2 = 0; c < components; c2 += c2_inc, c++) {
data.f[c] = op[0]->value.f[c] * (1.0f - op[2]->value.f[c2]) +
(op[1]->value.f[c] * op[2]->value.f[c2]);
}
break;
}
case ir_triop_csel:
for (unsigned c = 0; c < components; c++) {
data.u[c] = op[0]->value.b[c] ? op[1]->value.u[c]
: op[2]->value.u[c];
}
break;
case ir_triop_vector_insert: {
const unsigned idx = op[2]->value.u[0];
memcpy(&data, &op[0]->value, sizeof(data));
switch (this->type->base_type) {
case GLSL_TYPE_INT:
data.i[idx] = op[1]->value.i[0];
break;
case GLSL_TYPE_UINT:
data.u[idx] = op[1]->value.u[0];
break;
case GLSL_TYPE_FLOAT:
data.f[idx] = op[1]->value.f[0];
break;
case GLSL_TYPE_BOOL:
data.b[idx] = op[1]->value.b[0];
break;
default:
assert(!"Should not get here.");
break;
}
break;
}
case ir_quadop_bitfield_insert: {
int offset = op[2]->value.i[0];
int bits = op[3]->value.i[0];
for (unsigned c = 0; c < components; c++) {
if (bits == 0)
data.u[c] = op[0]->value.u[c];
else if (offset < 0 || bits < 0)
data.u[c] = 0; /* Undefined, per spec. */
else if (offset + bits > 32)
data.u[c] = 0; /* Undefined, per spec. */
else {
unsigned insert_mask = ((1 << bits) - 1) << offset;
unsigned insert = op[1]->value.u[c];
insert <<= offset;
insert &= insert_mask;
unsigned base = op[0]->value.u[c];
base &= ~insert_mask;
data.u[c] = base | insert;
}
}
break;
}
case ir_quadop_vector:
for (unsigned c = 0; c < this->type->vector_elements; c++) {
switch (this->type->base_type) {
case GLSL_TYPE_INT:
data.i[c] = op[c]->value.i[0];
break;
case GLSL_TYPE_UINT:
data.u[c] = op[c]->value.u[0];
break;
case GLSL_TYPE_FLOAT:
data.f[c] = op[c]->value.f[0];
break;
case GLSL_TYPE_BOOL:
data.b[c] = op[c]->value.b[0];
break;
default:
assert(0);
}
}
break;
default:
/* FINISHME: Should handle all expression types. */
return NULL;
}
return new(ctx) ir_constant(this->type, &data);
}
ir_constant *
ir_texture::constant_expression_value(struct hash_table *variable_context)
{
/* texture lookups aren't constant expressions */
return NULL;
}
ir_constant *
ir_swizzle::constant_expression_value(struct hash_table *variable_context)
{
ir_constant *v = this->val->constant_expression_value(variable_context);
if (v != NULL) {
ir_constant_data data = { { 0 } };
const unsigned swiz_idx[4] = {
this->mask.x, this->mask.y, this->mask.z, this->mask.w
};
for (unsigned i = 0; i < this->mask.num_components; i++) {
switch (v->type->base_type) {
case GLSL_TYPE_UINT:
case GLSL_TYPE_INT: data.u[i] = v->value.u[swiz_idx[i]]; break;
case GLSL_TYPE_FLOAT: data.f[i] = v->value.f[swiz_idx[i]]; break;
case GLSL_TYPE_BOOL: data.b[i] = v->value.b[swiz_idx[i]]; break;
default: assert(!"Should not get here."); break;
}
}
void *ctx = ralloc_parent(this);
return new(ctx) ir_constant(this->type, &data);
}
return NULL;
}
void
ir_dereference_variable::constant_referenced(struct hash_table *variable_context,
ir_constant *&store, int &offset) const
{
if (variable_context) {
store = (ir_constant *)hash_table_find(variable_context, var);
offset = 0;
} else {
store = NULL;
offset = 0;
}
}
ir_constant *
ir_dereference_variable::constant_expression_value(struct hash_table *variable_context)
{
/* This may occur during compile and var->type is glsl_type::error_type */
if (!var)
return NULL;
/* Give priority to the context hashtable, if it exists */
if (variable_context) {
ir_constant *value = (ir_constant *)hash_table_find(variable_context, var);
if(value)
return value;
}
/* The constant_value of a uniform variable is its initializer,
* not the lifetime constant value of the uniform.
*/
if (var->data.mode == ir_var_uniform)
return NULL;
if (!var->constant_value)
return NULL;
return var->constant_value->clone(ralloc_parent(var), NULL);
}
void
ir_dereference_array::constant_referenced(struct hash_table *variable_context,
ir_constant *&store, int &offset) const
{
ir_constant *index_c = array_index->constant_expression_value(variable_context);
if (!index_c || !index_c->type->is_scalar() || !index_c->type->is_integer()) {
store = 0;
offset = 0;
return;
}
int index = index_c->type->base_type == GLSL_TYPE_INT ?
index_c->get_int_component(0) :
index_c->get_uint_component(0);
ir_constant *substore;
int suboffset;
const ir_dereference *deref = array->as_dereference();
if (!deref) {
store = 0;
offset = 0;
return;
}
deref->constant_referenced(variable_context, substore, suboffset);
if (!substore) {
store = 0;
offset = 0;
return;
}
const glsl_type *vt = array->type;
if (vt->is_array()) {
store = substore->get_array_element(index);
offset = 0;
return;
}
if (vt->is_matrix()) {
store = substore;
offset = index * vt->vector_elements;
return;
}
if (vt->is_vector()) {
store = substore;
offset = suboffset + index;
return;
}
store = 0;
offset = 0;
}
ir_constant *
ir_dereference_array::constant_expression_value(struct hash_table *variable_context)
{
ir_constant *array = this->array->constant_expression_value(variable_context);
ir_constant *idx = this->array_index->constant_expression_value(variable_context);
if ((array != NULL) && (idx != NULL)) {
void *ctx = ralloc_parent(this);
if (array->type->is_matrix()) {
/* Array access of a matrix results in a vector.
*/
const unsigned column = idx->value.u[0];
const glsl_type *const column_type = array->type->column_type();
/* Offset in the constant matrix to the first element of the column
* to be extracted.
*/
const unsigned mat_idx = column * column_type->vector_elements;
ir_constant_data data = { { 0 } };
switch (column_type->base_type) {
case GLSL_TYPE_UINT:
case GLSL_TYPE_INT:
for (unsigned i = 0; i < column_type->vector_elements; i++)
data.u[i] = array->value.u[mat_idx + i];
break;
case GLSL_TYPE_FLOAT:
for (unsigned i = 0; i < column_type->vector_elements; i++)
data.f[i] = array->value.f[mat_idx + i];
break;
default:
assert(!"Should not get here.");
break;
}
return new(ctx) ir_constant(column_type, &data);
} else if (array->type->is_vector()) {
const unsigned component = idx->value.u[0];
return new(ctx) ir_constant(array, component);
} else {
const unsigned index = idx->value.u[0];
return array->get_array_element(index)->clone(ctx, NULL);
}
}
return NULL;
}
void
ir_dereference_record::constant_referenced(struct hash_table *variable_context,
ir_constant *&store, int &offset) const
{
ir_constant *substore;
int suboffset;
const ir_dereference *deref = record->as_dereference();
if (!deref) {
store = 0;
offset = 0;
return;
}
deref->constant_referenced(variable_context, substore, suboffset);
if (!substore) {
store = 0;
offset = 0;
return;
}
store = substore->get_record_field(field);
offset = 0;
}
ir_constant *
ir_dereference_record::constant_expression_value(struct hash_table *variable_context)
{
ir_constant *v = this->record->constant_expression_value();
return (v != NULL) ? v->get_record_field(this->field) : NULL;
}
ir_constant *
ir_assignment::constant_expression_value(struct hash_table *variable_context)
{
/* FINISHME: Handle CEs involving assignment (return RHS) */
return NULL;
}
ir_constant *
ir_constant::constant_expression_value(struct hash_table *variable_context)
{
return this;
}
ir_constant *
ir_call::constant_expression_value(struct hash_table *variable_context)
{
return this->callee->constant_expression_value(&this->actual_parameters, variable_context);
}
bool ir_function_signature::constant_expression_evaluate_expression_list(const struct exec_list &body,
struct hash_table *variable_context,
ir_constant **result)
{
foreach_list(n, &body) {
ir_instruction *inst = (ir_instruction *)n;
switch(inst->ir_type) {
/* (declare () type symbol) */
case ir_type_variable: {
ir_variable *var = inst->as_variable();
hash_table_insert(variable_context, ir_constant::zero(this, var->type), var);
break;
}
/* (assign [condition] (write-mask) (ref) (value)) */
case ir_type_assignment: {
ir_assignment *asg = inst->as_assignment();
if (asg->condition) {
ir_constant *cond = asg->condition->constant_expression_value(variable_context);
if (!cond)
return false;
if (!cond->get_bool_component(0))
break;
}
ir_constant *store = NULL;
int offset = 0;
asg->lhs->constant_referenced(variable_context, store, offset);
if (!store)
return false;
ir_constant *value = asg->rhs->constant_expression_value(variable_context);
if (!value)
return false;
store->copy_masked_offset(value, offset, asg->write_mask);
break;
}
/* (return (expression)) */
case ir_type_return:
assert (result);
*result = inst->as_return()->value->constant_expression_value(variable_context);
return *result != NULL;
/* (call name (ref) (params))*/
case ir_type_call: {
ir_call *call = inst->as_call();
/* Just say no to void functions in constant expressions. We
* don't need them at that point.
*/
if (!call->return_deref)
return false;
ir_constant *store = NULL;
int offset = 0;
call->return_deref->constant_referenced(variable_context, store, offset);
if (!store)
return false;
ir_constant *value = call->constant_expression_value(variable_context);
if(!value)
return false;
store->copy_offset(value, offset);
break;
}
/* (if condition (then-instructions) (else-instructions)) */
case ir_type_if: {
ir_if *iif = inst->as_if();
ir_constant *cond = iif->condition->constant_expression_value(variable_context);
if (!cond || !cond->type->is_boolean())
return false;
exec_list &branch = cond->get_bool_component(0) ? iif->then_instructions : iif->else_instructions;
*result = NULL;
if (!constant_expression_evaluate_expression_list(branch, variable_context, result))
return false;
/* If there was a return in the branch chosen, drop out now. */
if (*result)
return true;
break;
}
/* Every other expression type, we drop out. */
default:
return false;
}
}
/* Reaching the end of the block is not an error condition */
if (result)
*result = NULL;
return true;
}
ir_constant *
ir_function_signature::constant_expression_value(exec_list *actual_parameters, struct hash_table *variable_context)
{
const glsl_type *type = this->return_type;
if (type == glsl_type::void_type)
return NULL;
/* From the GLSL 1.20 spec, page 23:
* "Function calls to user-defined functions (non-built-in functions)
* cannot be used to form constant expressions."
*/
if (!this->is_builtin())
return NULL;
/*
* Of the builtin functions, only the texture lookups and the noise
* ones must not be used in constant expressions. They all include
* specific opcodes so they don't need to be special-cased at this
* point.
*/
/* Initialize the table of dereferencable names with the function
* parameters. Verify their const-ness on the way.
*
* We expect the correctness of the number of parameters to have
* been checked earlier.
*/
hash_table *deref_hash = hash_table_ctor(8, hash_table_pointer_hash,
hash_table_pointer_compare);
/* If "origin" is non-NULL, then the function body is there. So we
* have to use the variable objects from the object with the body,
* but the parameter instanciation on the current object.
*/
const exec_node *parameter_info = origin ? origin->parameters.head : parameters.head;
foreach_list(n, actual_parameters) {
ir_constant *constant = ((ir_rvalue *) n)->constant_expression_value(variable_context);
if (constant == NULL) {
hash_table_dtor(deref_hash);
return NULL;
}
ir_variable *var = (ir_variable *)parameter_info;
hash_table_insert(deref_hash, constant, var);
parameter_info = parameter_info->next;
}
ir_constant *result = NULL;
/* Now run the builtin function until something non-constant
* happens or we get the result.
*/
if (constant_expression_evaluate_expression_list(origin ? origin->body : body, deref_hash, &result) && result)
result = result->clone(ralloc_parent(this), NULL);
hash_table_dtor(deref_hash);
return result;
}
|
; A023950: Expansion of 1/((1-x)(1-6x)(1-7x)(1-9x)).
; Submitted by Jon Maiga
; 1,23,348,4378,49679,528381,5380306,53132816,513181317,4875626899,45752166824,425305531014,3925114125115,36023250380777,329183853207102,2998041099306172,27233460168740273,246879085434889215,2234479248275592340,20199016821699469490,182416463895957269991,1646151686909018195413,14846347711143593837738,133834954779297019416168,1206045056724311884821469,10865152872838913849566571,97861812089864788343162496,881285590637427933931005406,7935282657668022635055445907,71443574527314346469905373889
add $0,2
lpb $0
sub $0,1
add $2,2
mul $2,6
sub $2,11
mul $3,9
add $3,$1
mul $1,7
add $1,$2
lpe
mov $0,$3
|
Name: zel_rmdt09.asm
Type: file
Size: 172147
Last-Modified: '2016-05-13T04:22:15Z'
SHA-1: 8D4C35677AC1F9EAABEEDDCE8B9DF9C00AF150E9
Description: null
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r14
push %r15
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0xc833, %rdi
nop
nop
cmp %r15, %r15
mov $0x6162636465666768, %r10
movq %r10, %xmm7
vmovups %ymm7, (%rdi)
cmp %r12, %r12
lea addresses_A_ht+0x2ae3, %r14
nop
nop
nop
nop
add %rcx, %rcx
mov (%r14), %dx
cmp %r15, %r15
lea addresses_A_ht+0x5a33, %r15
nop
nop
inc %rcx
mov (%r15), %rdx
nop
nop
nop
nop
nop
sub $8350, %r15
lea addresses_D_ht+0x46c3, %rsi
lea addresses_WC_ht+0xc973, %rdi
sub %r15, %r15
mov $73, %rcx
rep movsl
nop
nop
nop
nop
cmp %rdi, %rdi
lea addresses_A_ht+0x81f3, %r15
nop
dec %r14
mov $0x6162636465666768, %r10
movq %r10, %xmm0
movups %xmm0, (%r15)
nop
nop
nop
and $24935, %r15
lea addresses_WT_ht+0x158f3, %rsi
lea addresses_D_ht+0xeebf, %rdi
add %r15, %r15
mov $110, %rcx
rep movsb
nop
nop
nop
cmp $40667, %rdx
lea addresses_UC_ht+0x107b3, %r12
nop
add $29366, %rdi
movw $0x6162, (%r12)
nop
nop
nop
nop
nop
and %r10, %r10
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r15
pop %r14
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r13
push %rax
push %rdx
push %rsi
// Load
lea addresses_PSE+0x17f73, %rdx
nop
nop
nop
sub %r11, %r11
mov (%rdx), %r12
nop
nop
nop
cmp $57978, %r13
// Store
lea addresses_WT+0x18173, %rdx
nop
nop
nop
nop
and $5418, %rax
movb $0x51, (%rdx)
nop
dec %rdx
// Store
lea addresses_A+0x10973, %r11
nop
nop
nop
add %rsi, %rsi
mov $0x5152535455565758, %rax
movq %rax, %xmm6
movups %xmm6, (%r11)
nop
dec %r11
// Store
lea addresses_WT+0xc473, %r12
nop
nop
add $59955, %r10
movw $0x5152, (%r12)
nop
xor %r11, %r11
// Store
lea addresses_UC+0x1ab73, %r12
nop
nop
add $54706, %rsi
movl $0x51525354, (%r12)
nop
nop
inc %rax
// Store
lea addresses_UC+0x1e87b, %r13
clflush (%r13)
add $21043, %r12
movb $0x51, (%r13)
nop
nop
xor $55122, %rax
// Store
lea addresses_UC+0x1b633, %rax
nop
nop
nop
nop
and $31308, %r11
mov $0x5152535455565758, %r12
movq %r12, (%rax)
nop
nop
nop
nop
nop
dec %r11
// Faulty Load
lea addresses_A+0x10973, %rax
cmp $35943, %rdx
vmovups (%rax), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %r11
lea oracles, %r12
and $0xff, %r11
shlq $12, %r11
mov (%r12,%r11,1), %r11
pop %rsi
pop %rdx
pop %rax
pop %r13
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'}
{'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT'}}
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_A'}}
{'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT'}}
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_UC'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_UC'}}
{'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_UC'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_UC_ht'}}
{'00': 52}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_IFNOT_PLUS_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_IFNOT_PLUS_HPP_INCLUDED
#include <boost/simd/function/is_nez.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/config.hpp>
namespace boost { namespace simd { namespace ext
{
BOOST_DISPATCH_OVERLOAD ( ifnot_plus_
, (typename A0, typename A1)
, bd::cpu_
, bd::scalar_< bd::unspecified_<A0> >
, bd::scalar_< bd::fundamental_<A1> >
, bd::scalar_< bd::fundamental_<A1> >
)
{
BOOST_FORCEINLINE A1 operator() (const A0 & a0,const A1 & a1,const A1 & a2) const BOOST_NOEXCEPT
{
return is_nez(a0) ? a1 :(a1+a2);
}
};
} } }
#endif
|
; A211441: Number of ordered triples (w,x,y) with all terms in {-n,...,0,...,n} and w + x + y = 2.
; 0,3,15,33,57,87,123,165,213,267,327,393,465,543,627,717,813,915,1023,1137,1257,1383,1515,1653,1797,1947,2103,2265,2433,2607,2787,2973,3165,3363,3567,3777,3993,4215,4443,4677,4917,5163,5415,5673,5937,6207,6483,6765,7053,7347,7647,7953,8265,8583,8907,9237,9573,9915,10263,10617,10977,11343,11715,12093,12477,12867,13263,13665,14073,14487,14907,15333,15765,16203,16647,17097,17553,18015,18483,18957,19437,19923,20415,20913,21417,21927,22443,22965,23493,24027,24567,25113,25665,26223,26787,27357,27933,28515,29103,29697,30297,30903,31515,32133,32757,33387,34023,34665,35313,35967,36627,37293,37965,38643,39327,40017,40713,41415,42123,42837,43557,44283,45015,45753,46497,47247,48003,48765,49533,50307,51087,51873,52665,53463,54267,55077,55893,56715,57543,58377,59217,60063,60915,61773,62637,63507,64383,65265,66153,67047,67947,68853,69765,70683,71607,72537,73473,74415,75363,76317,77277,78243,79215,80193,81177,82167,83163,84165,85173,86187,87207,88233,89265,90303,91347,92397,93453,94515,95583,96657,97737,98823,99915,101013,102117,103227,104343,105465,106593,107727,108867,110013,111165,112323,113487,114657,115833,117015,118203,119397,120597,121803,123015,124233,125457,126687,127923,129165,130413,131667,132927,134193,135465,136743,138027,139317,140613,141915,143223,144537,145857,147183,148515,149853,151197,152547,153903,155265,156633,158007,159387,160773,162165,163563,164967,166377,167793,169215,170643,172077,173517,174963,176415,177873,179337,180807,182283,183765,185253,186747
mov $1,$0
pow $0,2
add $1,$0
trn $1,1
mul $1,3
|
//
// Created by LongXiaJun on 2018/12/29 0029.
//
#include "day23_binary_search_and_equal_range.h"
#include <vector>
#include <iostream>
#include <algorithm>
namespace demo_binary_search_and_equal_range {
namespace definition {
// Possible definition
template<typename ForwardIt, typename T>
bool binary_search(ForwardIt first, ForwardIt last, const T &value) {
first = std::lower_bound(first, last, value);
return (!(first == last) && !(value < *first));
}
template<typename ForwardIt, typename T, typename Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T &value, Compare comp) {
first = std::lower_bound(first, last, value, comp);
return (!(first == last) && !(comp(value, *first)));
}
template<typename ForwardIt, typename T>
std::pair<ForwardIt, ForwardIt>
equal_range(ForwardIt first, ForwardIt last,
const T &value) {
return std::make_pair(std::lower_bound(first, last, value),
std::upper_bound(first, last, value));
}
template<typename ForwardIt, typename T, typename Compare>
std::pair<ForwardIt, ForwardIt>
equal_range(ForwardIt first, ForwardIt last,
const T &value, Compare comp) {
return
std::make_pair(std::lower_bound(first, last, value, comp),
std::upper_bound(first, last, value, comp)
);
}
}
struct S {
int number;
char name;
// 注意:此比较运算符忽略 name
bool operator<(const S &s) const { return number < s.number; }
};
void stl_binary_search_and_equal_range() {
std::cout << "STL binary_search usage demo:\n";
std::vector<int> haystack{1, 3, 4, 5, 9};
std::vector<int> needles{1, 2, 3};
for (auto needle : needles) {
std::cout << "Searching for " << needle << '\n';
if (std::binary_search(haystack.begin(), haystack.end(), needle)) {
std::cout << "Found " << needle << '\n';
} else {
std::cout << "no dice!\n";
}
}
std::cout << "STL equal_range usage demo: \n";
// 注意:非有序,仅相对于定义于下的 S 划分
std::vector<S> vec = {{1, 'A'},
{2, 'B'},
{2, 'C'},
{2, 'D'},
{4, 'G'},
{3, 'F'}};
S value = {2, '?'};
auto p = std::equal_range(vec.begin(), vec.end(), value);
for (auto i = p.first; i != p.second; ++i)
std::cout << i->name << ' ';
// 异相比较:
struct Comp {
bool operator()(const S &s, int i) const { return s.number < i; }
bool operator()(int i, const S &s) const { return i < s.number; }
};
auto p2 = std::equal_range(vec.begin(), vec.end(), 2, Comp{});
for (auto i = p2.first; i != p2.second; ++i)
std::cout << i->name << ' ';
}
} |
//
// Bundle.cpp
//
// Library: OSP
// Package: Bundle
// Module: Bundle
//
// Copyright (c) 2007-2014, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/OSP/Bundle.h"
#include "Poco/OSP/BundleLoader.h"
#include "Poco/OSP/OSPException.h"
#include "Poco/Util/PropertyFileConfiguration.h"
#include "Poco/Format.h"
#include "Poco/Path.h"
#include <memory>
using namespace std::string_literals;
using Poco::Util::PropertyFileConfiguration;
using Poco::Path;
namespace Poco {
namespace OSP {
namespace
{
class StateChange
{
public:
StateChange(Bundle::State& state, Bundle::State newState):
_state(state),
_oldState(state)
{
_state = newState;
}
~StateChange()
{
_state = _oldState;
}
void set(Bundle::State state)
{
_state = state;
}
void commit(Bundle::State state)
{
_state = _oldState = state;
}
void commit()
{
_oldState = _state;
}
private:
Bundle::State& _state;
Bundle::State _oldState;
};
}
const std::string Bundle::MANIFEST_FILE("META-INF/manifest.mf");
const std::string Bundle::PROPERTIES_FILE("bundle.properties");
const std::string Bundle::BUNDLE_INSTALLED_STRING("installed");
const std::string Bundle::BUNDLE_UNINSTALLED_STRING("uninstalled");
const std::string Bundle::BUNDLE_RESOLVED_STRING("resolved");
const std::string Bundle::BUNDLE_STARTING_STRING("starting");
const std::string Bundle::BUNDLE_ACTIVE_STRING("active");
const std::string Bundle::BUNDLE_STOPPING_STRING("stopping");
const std::string Bundle::BUNDLE_INVALID_STRING("INVALID");
Bundle::Bundle(int id, BundleLoader& loader, BundleStorage::Ptr pStorage, const LanguageTag& language):
_id(id),
_state(BUNDLE_INSTALLED),
_loader(loader),
_pStorage(pStorage),
_language(language),
_pProperties(new BundleProperties),
_pActivator(0)
{
poco_check_ptr (_pStorage);
loadManifest();
loadProperties();
_name = _pProperties->expand(_pManifest->name());
_vendor = _pProperties->expand(_pManifest->vendor());
_copyright = _pProperties->expand(_pManifest->copyright());
}
Bundle::~Bundle()
{
}
const std::string& Bundle::stateString() const
{
switch (_state)
{
case BUNDLE_INSTALLED:
return BUNDLE_INSTALLED_STRING;
case BUNDLE_UNINSTALLED:
return BUNDLE_UNINSTALLED_STRING;
case BUNDLE_RESOLVED:
return BUNDLE_RESOLVED_STRING;
case BUNDLE_STARTING:
return BUNDLE_STARTING_STRING;
case BUNDLE_ACTIVE:
return BUNDLE_ACTIVE_STRING;
case BUNDLE_STOPPING:
return BUNDLE_STOPPING_STRING;
default:
poco_bugcheck();
return BUNDLE_INVALID_STRING;
}
}
std::istream* Bundle::getResource(const std::string& name) const
{
std::istream* pStream = _pStorage->getResource(name);
if (!pStream)
{
Poco::FastMutex::ScopedLock lock(_extensionBundlesMutex);
std::set<Bundle::Ptr>::const_iterator it = _extensionBundles.begin();
std::set<Bundle::Ptr>::const_iterator end = _extensionBundles.end();
while (!pStream && it != end)
{
pStream = (*it)->getResource(name);
++it;
}
}
return pStream;
}
std::istream* Bundle::getLocalizedResource(const std::string& name) const
{
return getLocalizedResource(name, _language);
}
std::istream* Bundle::getLocalizedResource(const std::string& name, const LanguageTag& language) const
{
Path localPath(false);
localPath.pushDirectory(language.primaryTag());
localPath.pushDirectory(language.subTags());
Path resPath(localPath, name);
std::istream* pStream = getResource(resPath.toString(Path::PATH_UNIX));
while (!pStream && localPath.depth() > 0)
{
localPath.popDirectory();
resPath = Path(localPath, name);
pStream = getResource(resPath.toString(Path::PATH_UNIX));
}
return pStream;
}
inline BundleEvents& Bundle::events()
{
return _loader.events();
}
void Bundle::resolve()
{
if (_state != BUNDLE_INSTALLED) throw BundleStateException("resolve() requires INSTALLED state");
BundleEvent resolvingEvent(this, BundleEvent::EV_BUNDLE_RESOLVING);
events().bundleResolving(this, resolvingEvent);
_resolvedDependencies.clear();
_loader.resolveBundle(this);
_state = BUNDLE_RESOLVED;
BundleEvent resolvedEvent(this, BundleEvent::EV_BUNDLE_RESOLVED);
events().bundleResolved(this, resolvedEvent);
}
void Bundle::start()
{
if (_state != BUNDLE_RESOLVED) throw BundleStateException("start() requires RESOLVED state");
StateChange stateChange(_state, BUNDLE_STARTING);
BundleEvent startingEvent(this, BundleEvent::EV_BUNDLE_STARTING);
events().bundleStarting(this, startingEvent);
try
{
_loader.startBundle(this);
}
catch (Poco::Exception& exc)
{
BundleEvent failedEvent(this, exc);
events().bundleFailed(this, failedEvent);
throw;
}
catch (std::exception& exc)
{
BundleEvent failedEvent(this, Poco::SystemException(exc.what()));
events().bundleFailed(this, failedEvent);
throw;
}
catch (...)
{
BundleEvent failedEvent(this, Poco::UnhandledException("unknown exception"));
events().bundleFailed(this, failedEvent);
throw;
}
stateChange.commit(BUNDLE_ACTIVE);
BundleEvent startedEvent(this, BundleEvent::EV_BUNDLE_STARTED);
events().bundleStarted(this, startedEvent);
}
void Bundle::stop()
{
if (_state != BUNDLE_ACTIVE) throw BundleStateException("stop() requires ACTIVE state");
StateChange stateChange(_state, BUNDLE_STOPPING);
BundleEvent stoppingEvent(this, BundleEvent::EV_BUNDLE_STOPPING);
events().bundleStopping(this, stoppingEvent);
_loader.stopBundle(this);
stateChange.commit(BUNDLE_RESOLVED);
BundleEvent stoppedEvent(this, BundleEvent::EV_BUNDLE_STOPPED);
events().bundleStopped(this, stoppedEvent);
}
void Bundle::uninstall()
{
if (_state != BUNDLE_INSTALLED && _state != BUNDLE_RESOLVED) throw BundleStateException("uninstall() requires INSTALLED or RESOLVED state");
if (_pManifest->preventUninstall()) throw BundleUninstallException("bundle manifest prevents uninstall");
BundleEvent uninstallingEvent(this, BundleEvent::EV_BUNDLE_UNINSTALLING);
events().bundleUninstalling(this, uninstallingEvent);
_loader.uninstallBundle(this);
_state = BUNDLE_UNINSTALLED;
BundleEvent uninstalledEvent(this, BundleEvent::EV_BUNDLE_UNINSTALLED);
events().bundleUninstalled(this, uninstalledEvent);
}
bool Bundle::isExtensionBundle() const
{
return !_pManifest->extendedBundle().empty();
}
Bundle::Ptr Bundle::extendedBundle() const
{
Bundle::Ptr pExtendedBundle;
const std::string& bundleId = _pManifest->extendedBundle();
if (!bundleId.empty())
{
pExtendedBundle = _loader.findBundle(bundleId);
}
return pExtendedBundle;
}
void Bundle::loadManifest()
{
std::unique_ptr<std::istream> pStream(_pStorage->getResource(MANIFEST_FILE));
if (pStream.get())
_pManifest = new BundleManifest(*pStream);
else
throw BundleLoadException("No manifest found", _pStorage->path());
}
void Bundle::loadProperties()
{
Path localPath(false);
localPath.pushDirectory(_language.primaryTag());
localPath.pushDirectory(_language.subTags());
while (localPath.depth() > 0)
{
Path resPath(localPath, PROPERTIES_FILE);
addProperties(resPath.toString(Path::PATH_UNIX));
localPath.popDirectory();
}
addProperties(PROPERTIES_FILE);
}
void Bundle::addProperties(const std::string& path)
{
std::unique_ptr<std::istream> pStream(getResource(path));
if (pStream.get())
{
PropertyFileConfiguration::Ptr pConfig = new PropertyFileConfiguration(*pStream);
_pProperties->addProperties(pConfig);
}
}
void Bundle::setActivator(BundleActivator* pActivator)
{
_pActivator = pActivator;
}
void Bundle::addExtensionBundle(Bundle* pExtensionBundle)
{
if (!_pManifest->sealed())
{
if (isResolved())
{
{
Poco::FastMutex::ScopedLock lock(_extensionBundlesMutex);
_extensionBundles.insert(Bundle::Ptr(pExtensionBundle, true));
}
_pProperties->addProperties(pExtensionBundle->_pProperties, -static_cast<int>(_extensionBundles.size()));
}
else throw BundleStateException("addExtensionBundle() requires at least RESOLVED state");
}
else throw BundleSealedException(Poco::format("%s cannot extend %s"s, pExtensionBundle->symbolicName(), symbolicName()));
}
void Bundle::removeExtensionBundle(Bundle* pExtensionBundle)
{
Poco::FastMutex::ScopedLock lock(_extensionBundlesMutex);
_extensionBundles.erase(Bundle::Ptr(pExtensionBundle, true));
_pProperties->removeProperties(pExtensionBundle->_pProperties);
}
void Bundle::addResolvedDependency(const ResolvedDependency& dependency)
{
for (ResolvedDependencies::const_iterator it = _resolvedDependencies.begin(); it != _resolvedDependencies.end(); ++it)
{
if (it->symbolicName == dependency.symbolicName)
return;
}
_resolvedDependencies.push_back(dependency);
}
void Bundle::clearResolvedDependencies()
{
_resolvedDependencies.clear();
}
} } // namespace Poco::OSP
|
; A027266: a(n) = Sum_{k=0..2n} (k+1) * A026519(n, k).
; 1,6,18,72,180,648,1512,5184,11664,38880,85536,279936,606528,1959552,4199040,13436928,28553472,90699264,191476224,604661760,1269789696,3990767616,8344332288,26121388032,54419558400,169789022208
mov $2,5
mov $3,$0
add $0,2
mov $1,$3
mov $3,$0
add $3,5
mov $0,$3
add $1,1
add $2,$3
add $2,$3
lpb $0
sub $0,1
gcd $2,2
add $2,1
mul $1,$2
lpe
sub $1,432
div $1,432
add $1,1
|
include io.h
cr equ 10
lf equ 13
.model small
.Stack 200h
.Data
newline db cr, lf, 0
number_prompt1 db cr, lf, 'Enter number z: ', 0
number_one db 10 dup(?)
sum1 dw 0
sum2 dw 0
sum3 dw 0
total dw 0
sum_prompt db 'F = ', 0
.Code
main proc
mov ax, @Data
mov ds, ax
;-------------------------------------------------------------
clrscr
output number_prompt1
inputs number_one, 4
atoi number_one
mov sum1, ax
mov bx, 18
mul bx
mov bx, 10
div bx
add ax,32
itoa total, ax
output newline
output total
;-------------------------------------------------------------
mov ax, 4c00h
int 21h
main endp
end main |
je label1
times 4 nop
je label1
align 8
times 118 nop
je label2
label1:
times 128 nop
label2:
|
; A137951: Redundant binary representation (A089591) of n interpreted as ternary number.
; 0,1,3,4,6,10,12,13,15,19,21,31,33,37,39,40,42,46,48,58,60,64,66,94,96,100,102,112,114,118,120,121,123,127,129,139,141,145,147,175,177,181,183,193,195,199,201,283,285,289,291,301,303,307,309,337,339,343,345,355,357,361,363,364,366,370,372,382,384,388,390,418,420,424,426,436,438,442,444,526,528,532,534,544,546,550,552,580,582,586,588,598,600,604,606,850,852,856,858,868
mov $2,$0
add $2,1
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
seq $0,80940 ; Smallest proper divisor of n which is a suffix of n in binary representation; a(n) = 0 if no such divisor exists.
seq $0,191106 ; Increasing sequence generated by these rules: a(1)=1, and if x is in a then 3x-2 and 3x are in a.
mov $3,$0
div $3,2
add $3,1
add $1,$3
lpe
sub $1,1
mov $0,$1
|
; A054966: Numbers that are congruent to {0, 1, 8} mod 9.
; 0,1,8,9,10,17,18,19,26,27,28,35,36,37,44,45,46,53,54,55,62,63,64,71,72,73,80,81,82,89,90,91,98,99,100,107,108,109,116,117,118,125,126,127,134,135,136,143,144,145,152,153,154,161,162,163,170,171,172,179,180,181,188,189,190,197,198,199,206,207,208,215,216,217,224,225,226,233,234,235,242,243,244,251,252,253,260,261,262,269,270,271,278,279,280,287,288,289,296,297
mov $1,$0
add $0,1
div $0,3
mul $0,6
add $0,$1
|
/*
Copyright (c) 2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#include "libtorrent/rss.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/bencode.hpp"
#include <signal.h>
#include <stdio.h>
using namespace libtorrent;
int load_file(std::string const& filename, std::vector<char>& v, libtorrent::error_code& ec, int limit = 8000000)
{
ec.clear();
FILE* f = fopen(filename.c_str(), "rb");
if (f == NULL)
{
ec.assign(errno, boost::system::get_generic_category());
return -1;
}
int r = fseek(f, 0, SEEK_END);
if (r != 0)
{
ec.assign(errno, boost::system::get_generic_category());
fclose(f);
return -1;
}
long s = ftell(f);
if (s < 0)
{
ec.assign(errno, boost::system::get_generic_category());
fclose(f);
return -1;
}
if (s > limit)
{
fclose(f);
return -2;
}
r = fseek(f, 0, SEEK_SET);
if (r != 0)
{
ec.assign(errno, boost::system::get_generic_category());
fclose(f);
return -1;
}
v.resize(s);
if (s == 0)
{
fclose(f);
return 0;
}
r = fread(&v[0], 1, v.size(), f);
if (r < 0)
{
ec.assign(errno, boost::system::get_generic_category());
fclose(f);
return -1;
}
fclose(f);
if (r != s) return -3;
return 0;
}
void print_feed(feed_status const& f)
{
printf("FEED: %s\n",f.url.c_str());
if (f.error)
printf("ERROR: %s\n", f.error.message().c_str());
printf(" %s\n %s\n", f.title.c_str(), f.description.c_str());
printf(" ttl: %d minutes\n", f.ttl);
for (std::vector<feed_item>::const_iterator i = f.items.begin()
, end(f.items.end()); i != end; ++i)
{
printf("\033[32m%s\033[0m\n------------------------------------------------------\n"
" url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n"
" comment: %s\n category: %s\n"
, i->title.c_str(), i->url.c_str(), i->size
, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
}
}
std::string const& progress_bar(int progress, int width)
{
static std::string bar;
bar.clear();
bar.reserve(width + 10);
int progress_chars = (progress * width + 500) / 1000;
std::fill_n(std::back_inserter(bar), progress_chars, '#');
std::fill_n(std::back_inserter(bar), width - progress_chars, '-');
return bar;
}
int save_file(std::string const& filename, std::vector<char>& v)
{
using namespace libtorrent;
file f;
error_code ec;
if (!f.open(filename, file::write_only, ec)) return -1;
if (ec) return -1;
file::iovec_t b = {&v[0], v.size()};
size_type written = f.writev(0, &b, 1, ec);
if (written != int(v.size())) return -3;
if (ec) return -3;
return 0;
}
volatile bool quit = false;
void sig(int num)
{
quit = true;
}
int main(int argc, char* argv[])
{
if ((argc == 2 && strcmp(argv[1], "--help") == 0) || argc > 2)
{
fprintf(stderr, "usage: rss_reader [rss-url]\n");
return 0;
}
session ses;
session_settings sett;
sett.active_downloads = 2;
sett.active_seeds = 1;
sett.active_limit = 3;
ses.set_settings(sett);
std::vector<char> in;
error_code ec;
if (load_file(".ses_state", in, ec) == 0)
{
lazy_entry e;
if (lazy_bdecode(&in[0], &in[0] + in.size(), e, ec) == 0)
ses.load_state(e);
}
feed_handle fh;
if (argc == 2)
{
feed_settings feed;
feed.url = argv[1];
feed.add_args.save_path = ".";
fh = ses.add_feed(feed);
fh.update_feed();
}
else
{
std::vector<feed_handle> handles;
ses.get_feeds(handles);
if (handles.empty())
{
printf("usage: rss_reader rss-url\n");
return 1;
}
fh = handles[0];
}
feed_status fs = fh.get_feed_status();
int i = 0;
char spinner[] = {'|', '/', '-', '\\'};
fprintf(stderr, "fetching feed ... %c", spinner[i]);
while (fs.updating)
{
sleep(100);
i = (i + 1) % 4;
fprintf(stderr, "\b%c", spinner[i]);
fs = fh.get_feed_status();
}
fprintf(stderr, "\bDONE\n");
print_feed(fs);
signal(SIGTERM, &sig);
signal(SIGINT, &sig);
while (!quit)
{
std::vector<torrent_handle> t = ses.get_torrents();
for (std::vector<torrent_handle>::iterator i = t.begin()
, end(t.end()); i != end; ++i)
{
torrent_status st = i->status();
std::string const& progress = progress_bar(st.progress_ppm / 1000, 40);
std::string name = st.name;
if (name.size() > 70) name.resize(70);
std::string error = st.error;
if (error.size() > 40) error.resize(40);
static char const* state_str[] =
{"checking (q)", "checking", "dl metadata"
, "downloading", "finished", "seeding", "allocating", "checking (r)"};
std::string status = st.paused ? "queued" : state_str[st.state];
int attribute = 0;
if (st.paused) attribute = 33;
else if (st.state == torrent_status::downloading) attribute = 1;
printf("\033[%dm%2d %-70s d:%-4d u:%-4d %-40s %4d(%4d) %-12s\033[0m\n"
, attribute, st.queue_position
, name.c_str(), st.download_rate / 1000
, st.upload_rate / 1000, !error.empty() ? error.c_str() : progress.c_str()
, st.num_peers, st.num_seeds, status.c_str());
}
sleep(500);
if (quit) break;
printf("\033[%dA", int(t.size()));
}
printf("saving session state\n");
{
entry session_state;
ses.save_state(session_state);
std::vector<char> out;
bencode(std::back_inserter(out), session_state);
save_file(".ses_state", out);
}
printf("closing session");
return 0;
}
|
.text
.align 2
.global main
main:
;Bitfield instructions
MOV R6, #0A12Fh; R6 = 0xA12F
BFC R6, #8, #12; R6 = 0x2F
SBFX R7, R6, #4, #8; R7 = 0x2
;Packing and unpacking instructions
MOV R8, #0AABBh; R8 = 0xAABB
MOV R9, #0CCDh; R9 = 0xCCDD
PKHBT R10, R8, R9, LSL #16; R9 = 0xCCDDAABB
SXTH R11, R10, ROR #16; R10 = 0xFFFFCCDD
;Misc instructions
NOP
DMB
DSB
MRS R12, APSR
NOP
.end
|
#include "coinunits.h"
#include <QStringList>
CoinUnits::CoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<CoinUnits::Unit> CoinUnits::availableUnits()
{
QList<CoinUnits::Unit> unitlist;
unitlist.append(BASEUNIT);
unitlist.append(mBASEUNIT);
unitlist.append(uBASEUNIT);
return unitlist;
}
bool CoinUnits::valid(int unit)
{
switch(unit)
{
case BASEUNIT:
case mBASEUNIT:
case uBASEUNIT:
return true;
default:
return false;
}
}
QString CoinUnits::name(int unit)
{
switch(unit)
{
case BASEUNIT: return QString("SHOT");
case mBASEUNIT: return QString("mINCP");
case uBASEUNIT: return QString::fromUtf8("μINCP");
default: return QString("???");
}
}
QString CoinUnits::description(int unit)
{
switch(unit)
{
case BASEUNIT: return QString("Moonshot coins");
case mBASEUNIT: return QString("Milli Moonshot coins (1 / 1,000)");
case uBASEUNIT: return QString("Micro Moonshot coins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 CoinUnits::factor(int unit)
{
switch(unit)
{
case BASEUNIT: return 100000000;
case mBASEUNIT: return 100000;
case uBASEUNIT: return 100;
default: return 100000000;
}
}
int CoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BASEUNIT: return 8; // ex. 1,000,000 (# digits, without commas)
case mBASEUNIT: return 11; // ex. 1,000,000,000
case uBASEUNIT: return 14; // ex. 1,000,000,000,000
default: return 0;
}
}
int CoinUnits::decimals(int unit)
{
switch(unit)
{
case BASEUNIT: return 8;
case mBASEUNIT: return 5;
case uBASEUNIT: return 2;
default: return 0;
}
}
QString CoinUnits::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 CoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool CoinUnits::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 CoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant CoinUnits::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();
}
|
; A172475: a(n) = floor(n*sqrt(3)/2).
; 0,0,1,2,3,4,5,6,6,7,8,9,10,11,12,12,13,14,15,16,17,18,19,19,20,21,22,23,24,25,25,26,27,28,29,30,31,32,32,33,34,35,36,37,38,38,39,40,41,42,43,44,45,45,46,47,48,49,50,51,51,52,53,54,55,56,57,58,58,59,60,61,62,63,64,64,65,66,67,68,69,70,71,71,72,73,74,75,76,77,77,78,79,80,81,82,83,84,84,85,86,87,88,89,90,90,91,92,93,94,95,96,96,97,98,99,100,101,102,103,103,104,105,106,107,108,109,109,110,111,112,113,114,115,116,116,117,118,119,120,121,122,122,123,124,125,126,127,128,129,129,130,131,132,133,134,135,135,136,137,138,139,140,141,142,142,143,144,145,146,147,148,148,149,150,151,152,153,154,155,155,156,157,158,159,160,161,161,162,163,164,165,166,167,168,168,169,170,171,172,173,174,174,175,176,177,178,179,180,180,181,182,183,184,185,186,187,187,188,189,190,191,192,193,193,194,195,196,197,198,199,200,200,201,202,203,204,205,206,206,207,208,209,210,211,212,213,213,214,215
pow $0,2
mov $2,$0
add $2,$0
add $0,$2
mov $2,1
lpb $0,1
sub $0,1
mov $1,$2
mul $1,2
sub $0,$1
trn $0,1
add $2,4
lpe
div $1,8
|
; A191012: a(n) = n^5 - n^4 + n^3 - n^2 + n.
; 0,1,22,183,820,2605,6666,14707,29128,53145,90910,147631,229692,344773,501970,711915,986896,1340977,1790118,2352295,3047620,3898461,4929562,6168163,7644120,9390025,11441326,13836447,16616908,19827445,23516130,27734491,32537632,37984353,44137270,51062935,58831956,67519117,77203498,87968595,99902440,113097721,127651902,143667343,161251420,180516645,201580786,224566987,249603888,276825745,306372550,338390151,373030372,410451133,450816570,494297155,541069816,591318057,645232078,703008895,764852460,830973781,901591042,976929723,1057222720,1142710465,1233641046,1330270327,1432862068,1541688045,1657028170,1779170611,1908411912,2045057113,2189419870,2341822575,2502596476,2672081797,2850627858,3038593195,3236345680,3444262641,3662730982,3892147303,4132918020,4385459485,4650198106,4927570467,5218023448,5522014345,5840010990,6172491871,6519946252,6882874293,7261787170,7657207195,8069667936,8499714337,8947902838,9414801495,9900990100,10407060301,10933615722,11481272083,12050657320,12642411705,13257187966,13895651407,14558480028,15246364645,15960009010,16700129931,17467457392,18262734673,19086718470,19940179015,20823900196,21738679677,22685329018,23664673795,24677553720,25724822761,26807349262,27926016063,29081720620,30275375125,31507906626,32780257147,34093383808,35448258945,36845870230,38287220791,39773329332,41305230253,42883973770,44510626035,46186269256,47912001817,49688938398,51518210095,53400964540,55338366021,57331595602,59381851243,61490347920,63658317745,65887010086,68177691687,70531646788,72950177245,75434602650,77986260451,80606506072,83296713033,86058273070,88892596255,91801111116,94785264757,97846522978,100986370395,104206310560,107507866081,110892578742,114362009623,117917739220,121561367565,125294514346,129118819027,133035940968,137047559545,141155374270,145361104911,149666491612,154073295013,158583296370,163198297675,167920121776,172750612497,177691634758,182745074695,187912839780,193196858941,198599082682,204121483203,209766054520,215534812585,221429795406,227453063167,233606698348,239892805845,246313513090,252870970171,259567349952,266404848193,273385683670,280512098295,287786357236,295210749037,302787585738,310519202995,318407960200,326456240601,334666451422,343041023983,351582413820,360293100805,369175589266,378232408107,387466110928,396879276145,406474507110,416254432231,426221705092,436379004573,446729034970,457274526115,468018233496,478962938377,490111447918,501466595295,513031239820,524808267061,536800588962,549011143963,561442897120,574098840225,586981991926,600095397847,613442130708,627025290445,640848004330,654913427091,669224741032,683785156153,698597910270,713666269135,728993526556,744583004517,760438053298,776562051595,792958406640,809630554321,826581959302,843816115143,861336544420,879146798845,897250459386,915651136387,934352469688,953358128745
mov $1,$0
pow $1,6
lpb $0,1
add $0,1
add $1,$0
div $1,$0
div $0,$0
lpe
|
SECTION code_fp_math48
PUBLIC _tanh_fastcall
EXTERN cm48_sdccix_tanh_fastcall
defc _tanh_fastcall = cm48_sdccix_tanh_fastcall
|
// This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/be/test/olap/delete_handler_test.cpp
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "storage/delete_handler.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <string>
#include <vector>
#include "runtime/exec_env.h"
#include "storage/olap_define.h"
#include "storage/options.h"
#include "storage/storage_engine.h"
#include "util/file_utils.h"
#include "util/logging.h"
#include "util/mem_info.h"
using namespace std;
using namespace starrocks;
using google::protobuf::RepeatedPtrField;
namespace starrocks {
static StorageEngine* k_engine = nullptr;
static MemTracker* k_tablet_meta_mem_tracker = nullptr;
static MemTracker* k_schema_change_mem_tracker = nullptr;
void set_up() {
ExecEnv::GetInstance()->init_mem_tracker();
config::storage_root_path = std::filesystem::current_path().string() + "/data_test";
FileUtils::remove_all(config::storage_root_path);
FileUtils::remove_all(string(getenv("STARROCKS_HOME")) + UNUSED_PREFIX);
FileUtils::create_dir(config::storage_root_path);
std::vector<StorePath> paths;
paths.emplace_back(config::storage_root_path);
config::min_file_descriptor_number = 1000;
config::tablet_map_shard_size = 1;
config::txn_map_shard_size = 1;
config::txn_shard_size = 1;
config::storage_format_version = 2;
k_tablet_meta_mem_tracker = new MemTracker();
k_schema_change_mem_tracker = new MemTracker();
starrocks::EngineOptions options;
options.store_paths = paths;
options.tablet_meta_mem_tracker = k_tablet_meta_mem_tracker;
options.schema_change_mem_tracker = k_schema_change_mem_tracker;
Status s = starrocks::StorageEngine::open(options, &k_engine);
ASSERT_TRUE(s.ok()) << s.to_string();
}
void tear_down() {
config::storage_root_path = std::filesystem::current_path().string() + "/data_test";
FileUtils::remove_all(config::storage_root_path);
FileUtils::remove_all(string(getenv("STARROCKS_HOME")) + UNUSED_PREFIX);
k_tablet_meta_mem_tracker->release(k_tablet_meta_mem_tracker->consumption());
k_schema_change_mem_tracker->release(k_schema_change_mem_tracker->consumption());
delete k_tablet_meta_mem_tracker;
delete k_schema_change_mem_tracker;
}
void set_default_create_tablet_request(TCreateTabletReq* request) {
request->tablet_id = random();
request->__set_version(1);
request->__set_version_hash(0);
request->tablet_schema.schema_hash = 270068375;
request->tablet_schema.short_key_column_count = 2;
request->tablet_schema.keys_type = TKeysType::AGG_KEYS;
request->tablet_schema.storage_type = TStorageType::COLUMN;
TColumn k1;
k1.column_name = "k1";
k1.__set_is_key(true);
k1.column_type.type = TPrimitiveType::TINYINT;
request->tablet_schema.columns.push_back(k1);
TColumn k2;
k2.column_name = "k2";
k2.__set_is_key(true);
k2.column_type.type = TPrimitiveType::SMALLINT;
request->tablet_schema.columns.push_back(k2);
TColumn k3;
k3.column_name = "k3";
k3.__set_is_key(true);
k3.column_type.type = TPrimitiveType::INT;
request->tablet_schema.columns.push_back(k3);
TColumn k4;
k4.column_name = "k4";
k4.__set_is_key(true);
k4.column_type.type = TPrimitiveType::BIGINT;
request->tablet_schema.columns.push_back(k4);
TColumn k5;
k5.column_name = "k5";
k5.__set_is_key(true);
k5.column_type.type = TPrimitiveType::LARGEINT;
request->tablet_schema.columns.push_back(k5);
TColumn k9;
k9.column_name = "k9";
k9.__set_is_key(true);
k9.column_type.type = TPrimitiveType::DECIMAL;
k9.column_type.__set_precision(6);
k9.column_type.__set_scale(3);
request->tablet_schema.columns.push_back(k9);
TColumn k10;
k10.column_name = "k10";
k10.__set_is_key(true);
k10.column_type.type = TPrimitiveType::DATE;
request->tablet_schema.columns.push_back(k10);
TColumn k11;
k11.column_name = "k11";
k11.__set_is_key(true);
k11.column_type.type = TPrimitiveType::DATETIME;
request->tablet_schema.columns.push_back(k11);
TColumn k12;
k12.column_name = "k12";
k12.__set_is_key(true);
k12.column_type.__set_len(64);
k12.column_type.type = TPrimitiveType::CHAR;
request->tablet_schema.columns.push_back(k12);
TColumn k13;
k13.column_name = "k13";
k13.__set_is_key(true);
k13.column_type.__set_len(64);
k13.column_type.type = TPrimitiveType::VARCHAR;
request->tablet_schema.columns.push_back(k13);
TColumn v;
v.column_name = "v";
v.__set_is_key(false);
v.column_type.type = TPrimitiveType::BIGINT;
v.__set_aggregation_type(TAggregationType::SUM);
request->tablet_schema.columns.push_back(v);
}
void set_create_duplicate_tablet_request(TCreateTabletReq* request) {
request->tablet_id = random();
request->__set_version(1);
request->__set_version_hash(0);
request->tablet_schema.schema_hash = 270068376;
request->tablet_schema.short_key_column_count = 2;
request->tablet_schema.keys_type = TKeysType::DUP_KEYS;
request->tablet_schema.storage_type = TStorageType::COLUMN;
TColumn k1;
k1.column_name = "k1";
k1.__set_is_key(true);
k1.column_type.type = TPrimitiveType::TINYINT;
request->tablet_schema.columns.push_back(k1);
TColumn k2;
k2.column_name = "k2";
k2.__set_is_key(true);
k2.column_type.type = TPrimitiveType::SMALLINT;
request->tablet_schema.columns.push_back(k2);
TColumn k3;
k3.column_name = "k3";
k3.__set_is_key(true);
k3.column_type.type = TPrimitiveType::INT;
request->tablet_schema.columns.push_back(k3);
TColumn k4;
k4.column_name = "k4";
k4.__set_is_key(true);
k4.column_type.type = TPrimitiveType::BIGINT;
request->tablet_schema.columns.push_back(k4);
TColumn k5;
k5.column_name = "k5";
k5.__set_is_key(true);
k5.column_type.type = TPrimitiveType::LARGEINT;
request->tablet_schema.columns.push_back(k5);
TColumn k9;
k9.column_name = "k9";
k9.__set_is_key(true);
k9.column_type.type = TPrimitiveType::DECIMAL;
k9.column_type.__set_precision(6);
k9.column_type.__set_scale(3);
request->tablet_schema.columns.push_back(k9);
TColumn k10;
k10.column_name = "k10";
k10.__set_is_key(true);
k10.column_type.type = TPrimitiveType::DATE;
request->tablet_schema.columns.push_back(k10);
TColumn k11;
k11.column_name = "k11";
k11.__set_is_key(true);
k11.column_type.type = TPrimitiveType::DATETIME;
request->tablet_schema.columns.push_back(k11);
TColumn k12;
k12.column_name = "k12";
k12.__set_is_key(true);
k12.column_type.__set_len(64);
k12.column_type.type = TPrimitiveType::CHAR;
request->tablet_schema.columns.push_back(k12);
TColumn k13;
k13.column_name = "k13";
k13.__set_is_key(true);
k13.column_type.__set_len(64);
k13.column_type.type = TPrimitiveType::VARCHAR;
request->tablet_schema.columns.push_back(k13);
TColumn v;
v.column_name = "v";
v.__set_is_key(false);
v.column_type.type = TPrimitiveType::BIGINT;
request->tablet_schema.columns.push_back(v);
}
class TestDeleteConditionHandler : public testing::Test {
protected:
void SetUp() {
config::storage_root_path = std::filesystem::current_path().string() + "/data_delete_condition";
FileUtils::remove_all(config::storage_root_path);
ASSERT_TRUE(FileUtils::create_dir(config::storage_root_path).ok());
// 1. Prepare for query split key.
// create base tablet
set_default_create_tablet_request(&_create_tablet);
auto res = k_engine->create_tablet(_create_tablet);
ASSERT_TRUE(res.ok()) << res.to_string();
tablet = k_engine->tablet_manager()->get_tablet(_create_tablet.tablet_id);
ASSERT_TRUE(tablet.get() != nullptr);
_schema_hash_path = tablet->schema_hash_path();
set_create_duplicate_tablet_request(&_create_dup_tablet);
res = k_engine->create_tablet(_create_dup_tablet);
ASSERT_TRUE(res.ok()) << res.to_string();
dup_tablet = k_engine->tablet_manager()->get_tablet(_create_dup_tablet.tablet_id);
ASSERT_TRUE(dup_tablet.get() != nullptr);
_dup_tablet_path = tablet->schema_hash_path();
}
void TearDown() {
tablet.reset();
dup_tablet.reset();
(void)StorageEngine::instance()->tablet_manager()->drop_tablet(_create_tablet.tablet_id);
ASSERT_TRUE(FileUtils::remove_all(config::storage_root_path).ok());
}
std::string _schema_hash_path;
std::string _dup_tablet_path;
TabletSharedPtr tablet;
TabletSharedPtr dup_tablet;
TCreateTabletReq _create_tablet;
TCreateTabletReq _create_dup_tablet;
DeleteConditionHandler _delete_condition_handler;
};
TEST_F(TestDeleteConditionHandler, StoreCondSucceed) {
Status success_res;
std::vector<TCondition> conditions;
TCondition condition;
condition.column_name = "k1";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("1");
conditions.push_back(condition);
condition.column_name = "k2";
condition.condition_op = ">";
condition.condition_values.clear();
condition.condition_values.emplace_back("3");
conditions.push_back(condition);
condition.column_name = "k3";
condition.condition_op = "<=";
condition.condition_values.clear();
condition.condition_values.emplace_back("5");
conditions.push_back(condition);
condition.column_name = "k4";
condition.condition_op = "IS";
condition.condition_values.clear();
condition.condition_values.push_back("NULL");
conditions.push_back(condition);
condition.column_name = "k5";
condition.condition_op = "*=";
condition.condition_values.clear();
condition.condition_values.push_back("7");
conditions.push_back(condition);
condition.column_name = "k12";
condition.condition_op = "!*=";
condition.condition_values.clear();
condition.condition_values.push_back("9");
conditions.push_back(condition);
condition.column_name = "k13";
condition.condition_op = "*=";
condition.condition_values.clear();
condition.condition_values.push_back("1");
condition.condition_values.push_back("3");
conditions.push_back(condition);
DeletePredicatePB del_pred;
success_res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred);
ASSERT_EQ(true, success_res.ok());
// Verify that the filter criteria stored in the header are correct
ASSERT_EQ(size_t(6), del_pred.sub_predicates_size());
EXPECT_STREQ("k1=1", del_pred.sub_predicates(0).c_str());
EXPECT_STREQ("k2>>3", del_pred.sub_predicates(1).c_str());
EXPECT_STREQ("k3<=5", del_pred.sub_predicates(2).c_str());
EXPECT_STREQ("k4 IS NULL", del_pred.sub_predicates(3).c_str());
EXPECT_STREQ("k5=7", del_pred.sub_predicates(4).c_str());
EXPECT_STREQ("k12!=9", del_pred.sub_predicates(5).c_str());
ASSERT_EQ(size_t(1), del_pred.in_predicates_size());
ASSERT_FALSE(del_pred.in_predicates(0).is_not_in());
EXPECT_STREQ("k13", del_pred.in_predicates(0).column_name().c_str());
ASSERT_EQ(std::size_t(2), del_pred.in_predicates(0).values().size());
}
// empty string
TEST_F(TestDeleteConditionHandler, StoreCondInvalidParameters) {
std::vector<TCondition> conditions;
DeletePredicatePB del_pred;
Status failed_res =
_delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred);
ASSERT_EQ(true, failed_res.is_invalid_argument());
}
TEST_F(TestDeleteConditionHandler, StoreCondNonexistentColumn) {
// 'k100' is an invalid column
std::vector<TCondition> conditions;
TCondition condition;
condition.column_name = "k100";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("2");
conditions.push_back(condition);
DeletePredicatePB del_pred;
Status failed_res =
_delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred);
ASSERT_TRUE(failed_res.is_invalid_argument());
// 'v' is a value column
conditions.clear();
condition.column_name = "v";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("5");
conditions.push_back(condition);
failed_res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred);
ASSERT_TRUE(failed_res.is_invalid_argument());
// value column in duplicate model can be deleted;
conditions.clear();
condition.column_name = "v";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("5");
conditions.push_back(condition);
Status success_res =
_delete_condition_handler.generate_delete_predicate(dup_tablet->tablet_schema(), conditions, &del_pred);
ASSERT_EQ(true, success_res.ok());
}
// delete condition does not match
class TestDeleteConditionHandler2 : public testing::Test {
protected:
void SetUp() {
config::storage_root_path = std::filesystem::current_path().string() + "/data_delete_condition";
FileUtils::remove_all(config::storage_root_path);
ASSERT_TRUE(FileUtils::create_dir(config::storage_root_path).ok());
// 1. Prepare for query split key.
// create base tablet
set_default_create_tablet_request(&_create_tablet);
auto res = k_engine->create_tablet(_create_tablet);
ASSERT_TRUE(res.ok()) << res.to_string();
tablet = k_engine->tablet_manager()->get_tablet(_create_tablet.tablet_id);
ASSERT_TRUE(tablet.get() != nullptr);
_schema_hash_path = tablet->schema_hash_path();
}
void TearDown() {
tablet.reset();
(void)StorageEngine::instance()->tablet_manager()->drop_tablet(_create_tablet.tablet_id);
ASSERT_TRUE(FileUtils::remove_all(config::storage_root_path).ok());
}
std::string _schema_hash_path;
TabletSharedPtr tablet;
TCreateTabletReq _create_tablet;
DeleteConditionHandler _delete_condition_handler;
};
TEST_F(TestDeleteConditionHandler2, ValidConditionValue) {
Status res;
std::vector<TCondition> conditions;
// k1,k2,k3,k4 type is int8, int16, int32, int64
TCondition condition;
condition.column_name = "k1";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("-1");
conditions.push_back(condition);
condition.column_name = "k2";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("-1");
conditions.push_back(condition);
condition.column_name = "k3";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("-1");
conditions.push_back(condition);
condition.column_name = "k4";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("-1");
conditions.push_back(condition);
DeletePredicatePB del_pred;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred);
ASSERT_TRUE(res.ok());
// k5 type is int128
conditions.clear();
condition.column_name = "k5";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("1");
conditions.push_back(condition);
DeletePredicatePB del_pred_2;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_2);
ASSERT_TRUE(res.ok());
// k9 type is decimal, precision=6, frac=3
conditions.clear();
condition.column_name = "k9";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("2.3");
conditions.push_back(condition);
DeletePredicatePB del_pred_3;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_3);
ASSERT_EQ(true, res.ok());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2");
DeletePredicatePB del_pred_4;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_4);
ASSERT_TRUE(res.ok());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-2");
DeletePredicatePB del_pred_5;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_5);
ASSERT_TRUE(res.ok());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-2.3");
DeletePredicatePB del_pred_6;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_6);
ASSERT_TRUE(res.ok());
// k10,k11 type is date, datetime
conditions.clear();
condition.column_name = "k10";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("2014-01-01");
conditions.push_back(condition);
condition.column_name = "k10";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("2014-01-01 00:00:00");
conditions.push_back(condition);
DeletePredicatePB del_pred_7;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_7);
ASSERT_TRUE(res.ok());
// k12,k13 type is string(64), varchar(64)
conditions.clear();
condition.column_name = "k12";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("YWFh");
conditions.push_back(condition);
condition.column_name = "k13";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("YWFhYQ==");
conditions.push_back(condition);
DeletePredicatePB del_pred_8;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_8);
ASSERT_TRUE(res.ok());
}
TEST_F(TestDeleteConditionHandler2, InvalidConditionValue) {
Status res;
std::vector<TCondition> conditions;
// Test k1 max, k1 type is int8
TCondition condition;
condition.column_name = "k1";
condition.condition_op = "=";
condition.condition_values.clear();
condition.condition_values.emplace_back("1000");
conditions.push_back(condition);
DeletePredicatePB del_pred_1;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_1);
ASSERT_TRUE(res.is_invalid_argument());
// test k1 min, k1 type is int8
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-1000");
DeletePredicatePB del_pred_2;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_2);
ASSERT_TRUE(res.is_invalid_argument());
// k2(int16) max value
conditions[0].condition_values.clear();
conditions[0].column_name = "k2";
conditions[0].condition_values.emplace_back("32768");
DeletePredicatePB del_pred_3;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_3);
ASSERT_TRUE(res.is_invalid_argument());
// k2(int16) min value
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-32769");
DeletePredicatePB del_pred_4;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_4);
ASSERT_TRUE(res.is_invalid_argument());
// k3(int32) max
conditions[0].condition_values.clear();
conditions[0].column_name = "k3";
conditions[0].condition_values.emplace_back("2147483648");
DeletePredicatePB del_pred_5;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_5);
ASSERT_TRUE(res.is_invalid_argument());
// k3(int32) min value
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-2147483649");
DeletePredicatePB del_pred_6;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_6);
ASSERT_TRUE(res.is_invalid_argument());
// k4(int64) max
conditions[0].condition_values.clear();
conditions[0].column_name = "k4";
conditions[0].condition_values.emplace_back("9223372036854775808");
DeletePredicatePB del_pred_7;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_7);
ASSERT_TRUE(res.is_invalid_argument());
// k4(int64) min
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-9223372036854775809");
DeletePredicatePB del_pred_8;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_8);
ASSERT_TRUE(res.is_invalid_argument());
// k5(int128) max
conditions[0].condition_values.clear();
conditions[0].column_name = "k5";
conditions[0].condition_values.emplace_back("170141183460469231731687303715884105728");
DeletePredicatePB del_pred_9;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_9);
ASSERT_TRUE(res.is_invalid_argument());
// k5(int128) min
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("-170141183460469231731687303715884105729");
DeletePredicatePB del_pred_10;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_10);
ASSERT_TRUE(res.is_invalid_argument());
// k9 integer overflow, type is decimal, precision=6, frac=3
conditions[0].condition_values.clear();
conditions[0].column_name = "k9";
conditions[0].condition_values.emplace_back("12347876.5");
DeletePredicatePB del_pred_11;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_11);
ASSERT_TRUE(res.is_invalid_argument());
// k9 scale overflow, type is decimal, precision=6, frac=3
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("1.2345678");
DeletePredicatePB del_pred_12;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_12);
ASSERT_TRUE(res.is_invalid_argument());
// k9 has point
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("1.");
DeletePredicatePB del_pred_13;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_13);
ASSERT_TRUE(res.is_invalid_argument());
// invalid date
conditions[0].condition_values.clear();
conditions[0].column_name = "k10";
conditions[0].condition_values.emplace_back("20130101");
DeletePredicatePB del_pred_14;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_14);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-64-01");
DeletePredicatePB del_pred_15;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_15);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-01-40");
DeletePredicatePB del_pred_16;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_16);
ASSERT_TRUE(res.is_invalid_argument());
// invalid datetime
conditions[0].condition_values.clear();
conditions[0].column_name = "k11";
conditions[0].condition_values.emplace_back("20130101 00:00:00");
DeletePredicatePB del_pred_17;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_17);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-64-01 00:00:00");
DeletePredicatePB del_pred_18;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_18);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-01-40 00:00:00");
DeletePredicatePB del_pred_19;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_19);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-01-01 24:00:00");
DeletePredicatePB del_pred_20;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_20);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-01-01 00:60:00");
DeletePredicatePB del_pred_21;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_21);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].condition_values.emplace_back("2013-01-01 00:00:60");
DeletePredicatePB del_pred_22;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_22);
ASSERT_TRUE(res.is_invalid_argument());
// too long varchar
conditions[0].condition_values.clear();
conditions[0].column_name = "k12";
conditions[0].condition_values.emplace_back(
"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW"
"FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW"
"FhYWFhYWFhYWFhYWFhYWFhYWFhYWE=;k13=YWFhYQ==");
DeletePredicatePB del_pred_23;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_23);
ASSERT_TRUE(res.is_invalid_argument());
conditions[0].condition_values.clear();
conditions[0].column_name = "k13";
conditions[0].condition_values.emplace_back(
"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW"
"FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW"
"FhYWFhYWFhYWFhYWFhYWFhYWFhYWE=;k13=YWFhYQ==");
DeletePredicatePB del_pred_24;
res = _delete_condition_handler.generate_delete_predicate(tablet->tablet_schema(), conditions, &del_pred_24);
ASSERT_TRUE(res.is_invalid_argument());
}
} // namespace starrocks
int main(int argc, char** argv) {
starrocks::init_glog("be-test");
starrocks::MemInfo::init();
int ret = 0;
testing::InitGoogleTest(&argc, argv);
config::mem_limit = "10g";
starrocks::set_up();
ret = RUN_ALL_TESTS();
starrocks::tear_down();
google::protobuf::ShutdownProtobufLibrary();
return ret;
}
|
; A275015: Number of neighbors of each new term in an isosceles triangle read by rows.
; 0,1,2,1,3,2,1,3,3,2,1,3,3,3,2,1,3,3,3,3,2,1,3,3,3,3,3,2,1,3,3,3,3,3,3,2,1,3,3,3,3,3,3,3,2,1,3,3,3,3,3,3,3,3,2,1,3,3,3,3,3,3,3,3,3,2,1,3,3,3,3,3,3,3,3,3,3,2,1,3,3,3,3,3,3,3,3,3,3,3,2,1,3,3,3,3,3,3,3,3
lpb $0
add $0,4
mov $1,3
trn $2,2
add $2,3
trn $0,$2
sub $1,$0
trn $0,2
lpe
mov $0,$1
|
; stars.asm
AnimateStars proc
ld a, (ColourFlip)
xor 3
ld (ColourFlip), a
ld hl, StarField.Table ; Starting point of ROM "psuedo-random" table (2 bytes per star). Try $03F3!
ld a, StarField.StarCount ; Loop through this many times, once for each star.
ld c, 0
ResetLoop:
ex af, af' ; Save number of stars (loop counter).
//ld a, (hl) ; Read the byte represnting the star pixel,
//or %10000111 ; turn it into a "res n, a" instruction ($80 10nnn111) by setting
//and %10111111 ; and clearing bits,
//ld (ResetBit1), a ; SMC> then write this into the pixel-drawing code.
//ld (ResetBit2), a ; SMC> then write this into the pixel-drawing code.
//ld (ResetBit3), a ; SMC> then write this into the pixel-drawing code.
inc l ; Read two
ld e, (hl) ; coordinate bytes,
inc l ; for this star,
ld a, (hl) ; into de.
and %00000111 ; Constrain de between 0..2047
ld d, a ; (size of top screen third).
ex de, hl ; Sawp the reading addr into de, and the writing addr into hl.
ld b, high(PixelAddress) ; c stays 0, so this is a fast way of doing ld bc, $4000.
add hl, bc ; Calculate a pixel address in the top screen third.
push hl
ld h, %01011000
ld a, (hl)
pop hl
and %0100 0000
jp nz, Unset2
xor a ; Undraw a single pixel star,
//ResetBit1 equ $+1: res SMC, a ; <SMC by resetting that pseudo-random
ld (hl), a ; bit (0..7) from earlier.
Unset2:
ld b, 8 ; Fast way of doing ld bc, $0800 (size of a screen third).
add hl, bc ; hl is now a pixel address in the middle screen third.
push hl
ld h, %01011001
ld a, (hl)
pop hl
and %0100 0000
jp nz, Unset3
xor a
//ResetBit2 equ $+1: res SMC, a
ld (hl), a ; Draw the same single pixel star here, too.
Unset3:
add hl, bc ; hl is now a pixel address in the bottom screen third.
push hl
ld h, %01011010
ld a, (hl)
pop hl
and %0100 0000
jp nz, Unset4
xor a
//ResetBit3 equ $+1: res SMC, a
ld (hl), a ; Draw the same single pixel star here, too.
Unset4:
ex de, hl ; Swap the writing addr back into de, and reading addr into hl.
inc l
ex af, af' ; Retrieve the number of stars (loop counter),
dec a ; decrease it,
jp nz, ResetLoop ; and do all over again if there are any stars left.
ld hl, StarField.Table ; Starting point of ROM "psuedo-random" table (2 bytes per star). Try $03F3!
ld a, StarField.StarCount ; Loop through this many times, once for each star.
SetLoop:
ex af, af' ; Save number of stars (loop counter).
ld a, (hl) ; Read the byte represnting the star pixel,
or %11000111 ; turn it into a "set n, a" instruction ($CB 11nnn111),
ld (SetBit1), a ; SMC> then write this into the pixel-drawing code.
ld (SetBit2), a ; SMC> then write this into the pixel-drawing code.
ld (SetBit3), a ; SMC> then write this into the pixel-drawing code.
inc l ; Read two
ld e, (hl) ; coordinate bytes,
inc l ; for this star,
ld a, (hl) ; into de.
and %00000111 ; Constrain de between 0..2047
ld d, a ; (size of top screen third).
ScrollStar() ; Macro to manipulate the Y coordinate.
ex de, hl ; Sawp the reading addr into de, and the writing addr into hl.
ld b, high(PixelAddress) ; c stays 0, so this is a fast way of doing ld bc, $4000.
add hl, bc ; Calculate a pixel address in the top screen third.
push hl
ld h, %01011000
ld a, (hl)
pop hl
and %0100 0000
jp nz, Set2
xor a ; Draw a single pixel star,
SetBit1 equ $+1: set SMC, a ; <SMC by setting that pseudo-random
ld (hl), a ; bit (0..7) from earlier.
Set2:
ld b, 8 ; Fast way of doing ld bc, $0800 (size of a screen third).
add hl, bc ; hl is now a pixel address in the middle screen third.
push hl
ld h, %01011001
ld a, (hl)
pop hl
and %0100 0000
jp nz, Set3
xor a ; Draw a single pixel star,
SetBit2 equ $+1: set SMC, a ; <SMC by setting that pseudo-random
ld (hl), a ; Draw the same single pixel star here, too.
Set3:
add hl, bc ; hl is now a pixel address in the bottom screen third.
push hl
ld h, %01011010
ld a, (hl)
pop hl
and %0100 0000
jp nz, Set4
xor a ; Draw a single pixel star,
SetBit3 equ $+1: set SMC, a ; <SMC by setting that pseudo-random
ld (hl), a ; Draw the same single pixel star here, too.
Set4:
ld h, %01011000
Colour equ $+1: ld a, SMC
ColourFlip equ $+1: jr SameColour
dec a
and %111
SameColour:
push bc
ld c, a
ld a, (hl)
and %01000000
ld a, c
pop bc
jp nz, SetCol2
ld (hl), a
SetCol2:
ld h, %01011001
push bc
ld c, a
ld a, (hl)
and %01000000
ld a, c
pop bc
jp nz, SetCol3
ld (hl), a
SetCol3:
ld h, %01011010
push bc
ld c, a
ld a, (hl)
and %01000000
ld a, c
pop bc
jp nz, SetCol4
ld (hl), a
SetCol4:
ld c, 0
ex de, hl ; Swap the writing addr back into de, and reading addr into hl.
inc l
ex af, af' ; Retrieve the number of stars (loop counter),
dec a ; decrease it,
jp nz, SetLoop ; and do all over again if there are any stars left.
jp SetupMenu.AnimateStarsRet
pend
align 256
StarField proc
StarCount equ 32
Table: ds StarCount*3
Length equ $-StarField
pend
; 8-bit Complementary-Multiply-With-Carry (CMWC) random number generator.
; Created by Patrik Rak in 2012, and revised in 2014/2015,
; with optimization contribution from Einar Saukas and Alan Albrecht.
; See http://www.worldofspectrum.org/forums/showthread.php?t=39632
; and https://gist.github.com/raxoft/2275716fea577b48f7f0
RndCMWC proc
ld hl, Seed
ld a, (hl) ; i = ( i & 7 ) + 1
and 7
inc a
ld (hl), a
inc l ; hl = &cy
ld b, h ; bc = &q[i]
add a, l
ld c, a
ld a, (bc) ; y = q[i]
ld d, a
ld e, a
ld a, (hl) ; da = 256 * y + cy
sub e ; da = 255 * y + cy
jr nc, $+3
dec d
sub e ; da = 254 * y + cy
jr nc, $+3
dec d
sub e ; da = 253 * y + cy
jr nc ,$+3
dec d
ld (hl), d ; cy = da >> 8, x = da & 255
cpl ; x = (b-1) - x = -x - 1 = ~x + 1 - 1 = ~x
ld (bc), a ; q[i] = x
ret
ds 12
Seed: db 0,0,82,97,120,111,102,116,20,15
if (Seed/256)-((Seed+17)/256)
zeuserror "Seed table must be within single 256 byte block";
endif
pend
|
; simple2
include "subdir/insubdir2.asm"
|
#include <iostream>
#include <string>
#include <cstdint>
#include <cassert>
const int8_t HexDigitTable[256] = { -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, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, -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, 0xa, 0xb, 0xc, 0xd, 0xe,
0xf, -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, -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, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, };
const int8_t HexTable[] = "0123456789abcdef";
std::string Str2Hex(std::string src)
{
std::string dst;
dst.reserve(src.size() * 2);
for (auto itor : src)
{
dst.push_back(HexTable[itor >> 4]);
dst.push_back(HexTable[itor & 0x0f]);
}
return dst;
}
std::string Hex2Str(std::string src)
{
assert(src.size() % 2 == 0);
std::string dst;
int8_t c;
dst.reserve(src.size() / 2);
for (auto itor = src.begin(); itor != src.end(); ++ itor)
{
c = (HexDigitTable[*itor++] << 4) | HexDigitTable[*itor];
dst.push_back(c);
}
return dst;
}
int main()
{
std::string src = "hello world";
std::string dst = Str2Hex(src);
std::cout << dst << std::endl;
std::cout << Hex2Str(dst) << std::endl;
return 0;
} |
; A055142: E.g.f.: exp(x)*sqrt(1-2x).
; 1,0,-2,-8,-36,-224,-1880,-19872,-251888,-3712256,-62286624,-1171487360,-24402416192,-557542291968,-13861636770176,-372514645389824,-10759590258589440,-332386419622387712,-10935312198369141248,-381705328034883127296,-14089260601787531469824,-548302210950105933701120,-22436943914629372893714432,-963100234961887746240585728,-43270511388173885173956079616,-2030755735354175876530343706624,-99374261198300099567819381350400,-5061862284073188031947029957476352,-267974353235243948348477371110801408
mul $0,2
mov $1,1
lpb $0
sub $0,2
sub $2,$1
add $1,$2
mul $2,$0
lpe
mov $0,$1
|
;** Standard device IO for MSDOS (first 12 function calls)
;
TITLE IBMCPMIO - device IO for MSDOS
NAME IBMCPMIO
;** CPMIO.ASM - Standard device IO for MSDOS (first 12 function calls)
;
;
; Old style CP/M 1-12 system calls to talk to reserved devices
;
; $Std_Con_Input_No_Echo
; $Std_Con_String_Output
; $Std_Con_String_Input
; $RawConIO
; $RawConInput
; RAWOUT
; RAWOUT2
;
; Revision history:
;
; A000 version 4.00 - Jan 1988
; A002 PTM -- dir >lpt3 hangs
.xlist
.xcref
include version.inc
include dosseg.inc
INCLUDE DOSSYM.INC
include sf.inc
include vector.inc
INCLUDE DEVSYM.INC
include doscntry.inc
.list
.cref
; The following routines form the console I/O group (funcs 1,2,6,7,8,9,10,11).
; They assume ES and DS NOTHING, while not strictly correct, this forces data
; references to be SS or CS relative which is desired.
i_need CARPOS,BYTE
i_need STARTPOS,BYTE
i_need INBUF,128
i_need INSMODE,BYTE
i_need user_SP,WORD
EXTRN OUTCHA:NEAR ;AN000 char out with status check 2/11/KK
i_need Printer_Flag,BYTE
i_need SCAN_FLAG,BYTE
i_need DATE_FLAG,WORD
i_need Packet_Temp,WORD ; temporary packet used by readtime
i_need DEVCALL,DWORD
i_need InterChar,BYTE ;AN000;interim char flag ( 0 = regular char)
i_need InterCon,BYTE ;AN000;console flag ( 1 = in interim mode )
i_need SaveCurFlg,BYTE ;AN000;console out ( 1 = print and do not advance)
i_need COUNTRY_CDPG,byte ;AN000; 2/12/KK
i_need TEMP_VAR,WORD ;AN000; 2/12/KK
i_need DOS34_FLAG,WORD ;AN000; 2/12/KK
ifdef DBCS
i_need LOOKSIZ,BYTE
endif
NT_WAIT_BOP equ 5Ah
bop MACRO callid
db 0c4h,0c4h,callid
endm
DOSCODE SEGMENT
ASSUME SS:DOSDATA,CS:DOSCODE
EXTRN Get_IO_SFT:Near
EXTRN IOFunc:near
EXTRN EscChar:BYTE ; lead byte for function keys
EXTRN CanChar:BYTE ; Cancel character
Break
IFDEF DBCS ;AN000;
;
;----------------------------------------------------------------------------
;
; Procedure : $Std_Con_Input_No_Echo
;
;----------------------------------------------------------------------------
;
;--- Start of Korean Support 2/11/KK
procedure $STD_CON_INPUT_NO_ECHO,NEAR ;System call 8 ;AN000;
StdCILop: ;AN000;
invoke INTER_CON_INPUT_NO_ECHO ;AN000;
jmp InterApRet ; go to return fuction ;AN000;
EndProc $STD_CON_INPUT_NO_ECHO ;AN000;
;
;----------------------------------------------------------------------------
;
; Procedure : Inter_Con_Input_No_Echo
;
;
;----------------------------------------------------------------------------
;
procedure INTER_CON_INPUT_NO_ECHO,NEAR ;AN000;
;--- End of Korean Support 2/11/KK
; Inputs:
; None
; Function:
; Same as $STD_CON_INPUT_NO_ECHO but uses interim character read from
; the device.
; Returns:
; AL = character
; Zero flag SET if interim character, RESET otherwise
ELSE ;AN000;
;
; Inputs:
; None
; Function:
; Input character from console, no echo
; Returns:
; AL = character
procedure $STD_CON_INPUT_NO_ECHO,NEAR ;System call 8
ENDIF
PUSH DS
PUSH SI
push cx
INTEST:
mov cx, 10h
InTest1:
push cx
invoke STATCHK
pop cx
JNZ Get
loop InTest1
; extra idling for full screen
xor ax,ax ; with AX = 0 for WaitIfIdle
bop NT_WAIT_BOP
;;; 7/15/86 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
JMP Intest
Get:
XOR AH,AH
call IOFUNC
pop cx
POP SI
POP DS
;;; 7/15/86
;hkn; SS override
MOV BYTE PTR [SCAN_FLAG],0
CMP AL,0 ; extended code ( AL )
JNZ noscan
;hkn; SS override
MOV BYTE PTR [SCAN_FLAG],1 ; set this flag for ALT_Q key
noscan:
;;; 7/15/86
IFDEF DBCS ;AN000;
;hkn; InterChar is in DOSDATA. use SS override.
cmp [InterChar],1 ;AN000; set the zero flag if the character3/31/KK ;AN000;
ENDIF ;AN000;
return
IFDEF DBCS ;AN000;
EndProc INTER_CON_INPUT_NO_ECHO ;AN000; ;2/11/KK ;AN000;
ELSE ;AN000;
EndProc $STD_CON_INPUT_NO_ECHO
ENDIF ;AN000;
BREAK <$STD_CON_STRING_OUTPUT - Console String Output>
;
;----------------------------------------------------------------------------
;
;** $STD_CON_STRING_OUTPUT - Console String Output
;
;
; ENTRY (DS:DX) Point to output string '$' terminated
; EXIT none
; USES ALL
;
;----------------------------------------------------------------------------
;
procedure $STD_CON_STRING_OUTPUT,NEAR ;System call 9
MOV SI,DX
STRING_OUT1:
LODSB
; IFDEF DBCS ;AN000;
; invoke TESTKANJ ;AN000; 2/11/KK ;AN000;
; jz SBCS00 ;AN000; 2/11/KK ;AN000;
; invoke OUTT ;AN000; 2/11/KK ;AN000;
; LODSB ;AN000; 2/11/KK ;AN000;
; JMP NEXT_STR1 ;AN000; 2/11/KK ;AN000;
;SBCS00: ;AN000; 2/11/KK ;AN000;
; ENDIF ;AN000;
CMP AL,'$'
retz
NEXT_STR1:
invoke OUTT
JMP STRING_OUT1
EndProc $STD_CON_STRING_OUTPUT
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
IFDEF DBCS
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
include kstrin.asm
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
ELSE ; Not double byte characters
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
; SCCSID = @(#)strin.asm 1.2 85/04/18
BREAK <$STD_CON_STRING_INPUT - Input Line from Console>
;** $STD_CON_STRING_INPUT - Input Line from Console
;
; $STD_CON_STRING_INPUT Fills a buffer from console input until CR
;
; ENTRY (ds:dx) = input buffer
; EXIT none
; USES ALL
ASSUME DS:NOTHING,ES:NOTHING
procedure $STD_CON_STRING_INPUT,NEAR ;System call 10
MOV AX,SS
MOV ES,AX
MOV SI,DX
XOR CH,CH
LODSW
; (AL) = the buffer length
; (AH) = the template length
OR AL,AL
retz ;Buffer is 0 length!!?
MOV BL,AH ;Init template counter
MOV BH,CH ;Init template counter
; (BL) = the number of bytes in the template
CMP AL,BL
JBE NOEDIT ;If length of buffer inconsistent with contents
CMP BYTE PTR [BX+SI],c_CR
JZ EDITON ;If CR correctly placed EDIT is OK
; The number of chars in the template is >= the number of chars in buffer or
; there is no CR at the end of the template. This is an inconsistant state
; of affairs. Pretend that the template was empty:
;
noedit: MOV BL,CH ;Reset buffer
editon: MOV DL,AL
DEC DX ;DL is # of bytes we can put in the buffer
; Top level. We begin to read a line in.
;hkn; SS override
newlin: MOV AL,[CARPOS]
MOV [STARTPOS],AL ;Remember position in raw buffer
PUSH SI
;hkn; INBUF is in DOSDATA
MOV DI,OFFSET DOSDATA:INBUF ;Build the new line here
;hkn; SS override
MOV [INSMODE],CH ;Insert mode off
MOV BH,CH ;No chars from template yet
MOV DH,CH ;No chars to new line yet
invoke $STD_CON_INPUT_NO_ECHO ;Get first char
CMP AL,c_LF ;Linefeed
JNZ GOTCH ;Filter out LF so < works
; This is the main loop of reading in a character and processing it.
;
; (BH) = the index of the next byte in the template
; (BL) = the length of the template
; (DH) = the number of bytes in the buffer
; (DL) = the length of the buffer
entry GETCH
invoke $STD_CON_INPUT_NO_ECHO
GOTCH:
;
; Tim Patterson ignored ^F in case his BIOS did not flush the
; input queue.
;
CMP AL,"F"-"@"
JZ GETCH
; If the leading char is the function-key lead byte
;hkn; ESCCHAR is in TABLE seg (DOSCODE)
CMP AL,[ESCCHAR]
JZ ESCape ;change reserved keyword DBM 5-7-87
; Rubout and ^H are both destructive backspaces.
CMP AL,c_DEL
JZ BACKSPJ
CMP AL,c_BS
JZ BACKSPJ
; ^W deletes backward once and then backs up until a letter is before the
; cursor
CMP AL,"W" - "@"
; The removal of the comment characters before the jump statement will
; cause ^W to backup a word.
;*** JZ WordDel
NOP
NOP
CMP AL,"U" - "@"
; The removal of the comment characters before the jump statement will
; cause ^U to clear a line.
;*** JZ LineDel
NOP
NOP
; CR terminates the line.
CMP AL,c_CR
JZ ENDLIN
; LF goes to a new line and keeps on reading.
CMP AL,c_LF
JZ PHYCRLF
; ^X (or ESC) deletes the line and starts over
;hkn; CANCHAR is in TABLE seg (DOSCODE), so CS override
CMP AL,[CANCHAR]
JZ KILNEW
; Otherwise, we save the input character.
savch: CMP DH,DL
JAE BUFFUL ; buffer is full.
STOSB
INC DH ; increment count in buffer.
invoke BUFOUT ;Print control chars nicely
;hkn; SS override
CMP BYTE PTR [INSMODE],0
JNZ GETCH ; insertmode => don't advance template
CMP BH,BL
JAE GETCH ; no more characters in template
INC SI ; Skip to next char in template
INC BH ; remember position in template
JMP SHORT GETCH
BACKSPJ: JMP SHORT BACKSP
bufful: MOV AL,7 ; Bell to signal full buffer
invoke OUTT
JMP SHORT GETCH
ESCape: transfer OEMFunctionKey ; let the OEM's handle the key dispatch
ENDLIN:
STOSB ; Put the CR in the buffer
invoke OUTT ; Echo it
POP DI ; Get start of user buffer
MOV [DI-1],DH ; Tell user how many bytes
INC DH ; DH is length including CR
COPYNEW:
SAVE <DS,ES>
RESTORE <DS,ES> ; XCHG ES,DS
;hkn; INBUF is in DOSDATA
MOV SI,OFFSET DOSDATA:INBUF
MOV CL,DH ; set up count
REP MOVSB ; Copy final line to user buffer
return
; Output a CRLF to the user screen and do NOT store it into the buffer
PHYCRLF:
invoke CRLF
JMP GETCH
;
; Delete the previous line
;
LineDel:
OR DH,DH
JZ GetCh
Call BackSpace
JMP LineDel
;
; delete the previous word.
;
WordDel:
WordLoop:
Call BackSpace ; backspace the one spot
OR DH,DH
JZ GetChJ
MOV AL,ES:[DI-1]
cmp al,'0'
jb GetChj
cmp al,'9'
jbe WordLoop
OR AL,20h
CMP AL,'a'
JB GetChJ
CMP AL,'z'
JBE WordLoop
getchj: JMP GetCh
; The user wants to throw away what he's typed in and wants to start over. We
; print the backslash and then go to the next line and tab to the correct spot
; to begin the buffered input.
entry KILNEW
MOV AL,"\"
invoke OUTT ;Print the CANCEL indicator
POP SI ;Remember start of edit buffer
PUTNEW:
invoke CRLF ;Go to next line on screen
;hkn; SS override
MOV AL,[STARTPOS]
invoke TAB ;Tab over
JMP NEWLIN ;Start over again
; Destructively back up one character position
entry BackSp
Call BackSpace
JMP GetCh
BackSpace:
OR DH,DH
JZ OLDBAK ;No chars in line, do nothing to line
CALL BACKUP ;Do the backup
MOV AL,ES:[DI] ;Get the deleted char
CMP AL," "
JAE OLDBAK ;Was a normal char
CMP AL,c_HT
JZ BAKTAB ;Was a tab, fix up users display
;; 9/27/86 fix for ctrl-U backspace
CMP AL,"U"-"@" ; ctrl-U is a section symbol not ^U
JZ OLDBAK
CMP AL,"T"-"@" ; ctrl-T is a paragraphs symbol not ^T
JZ OLDBAK
;; 9/27/86 fix for ctrl-U backspace
CALL BACKMES ;Was a control char, zap the '^'
OLDBAK:
;hkn; SS override
CMP BYTE PTR [INSMODE],0
retnz ;In insert mode, done
OR BH,BH
retz ;Not advanced in template, stay where we are
DEC BH ;Go back in template
DEC SI
return
BAKTAB:
PUSH DI
DEC DI ;Back up one char
STD ;Go backward
MOV CL,DH ;Number of chars currently in line
MOV AL," "
PUSH BX
MOV BL,7 ;Max
JCXZ FIGTAB ;At start, do nothing
FNDPOS:
SCASB ;Look back
JNA CHKCNT
CMP BYTE PTR ES:[DI+1],9
JZ HAVTAB ;Found a tab
DEC BL ;Back one char if non tab control char
CHKCNT:
LOOP FNDPOS
FIGTAB:
;hkn; SS override
SUB BL,[STARTPOS]
HAVTAB:
SUB BL,DH
ADD CL,BL
AND CL,7 ;CX has correct number to erase
CLD ;Back to normal
POP BX
POP DI
JZ OLDBAK ;Nothing to erase
TABBAK:
invoke BACKMES
LOOP TABBAK ;Erase correct number of chars
JMP SHORT OLDBAK
BACKUP:
DEC DH ;Back up in line
DEC DI
BACKMES:
MOV AL,c_BS ;Backspace
invoke OUTT
MOV AL," " ;Erase
invoke OUTT
MOV AL,c_BS ;Backspace
JMP OUTT ;Done
;User really wants an ESC character in his line
entry TwoEsc
;hkn; ESCCHAR is in TABLE seg (DOSCODE), so CS override
MOV AL,[ESCCHAR]
JMP SAVCH
;Copy the rest of the template
entry COPYLIN
MOV CL,BL ;Total size of template
SUB CL,BH ;Minus position in template, is number to move
JMP SHORT COPYEACH
entry CopyStr
invoke FINDOLD ;Find the char
JMP SHORT COPYEACH ;Copy up to it
;Copy one char from template to line
entry COPYONE
MOV CL,1
;Copy CX chars from template to line
COPYEACH:
;hkn; SS override
MOV BYTE PTR [INSMODE],0 ;All copies turn off insert mode
CMP DH,DL
JZ GETCH2 ;At end of line, can't do anything
CMP BH,BL
JZ GETCH2 ;At end of template, can't do anything
LODSB
STOSB
invoke BUFOUT
INC BH ;Ahead in template
INC DH ;Ahead in line
LOOP COPYEACH
GETCH2:
JMP GETCH
;Skip one char in template
entry SKIPONE
CMP BH,BL
JZ GETCH2 ;At end of template
INC BH ;Ahead in template
INC SI
JMP GETCH
entry SKIPSTR
invoke FINDOLD ;Find out how far to go
ADD SI,CX ;Go there
ADD BH,CL
JMP GETCH
;Get the next user char, and look ahead in template for a match
;CX indicates how many chars to skip to get there on output
;NOTE: WARNING: If the operation cannot be done, the return
; address is popped off and a jump to GETCH is taken.
; Make sure nothing extra on stack when this routine
; is called!!! (no PUSHes before calling it).
FINDOLD:
invoke $STD_CON_INPUT_NO_ECHO
;hkn; ESCCHAR is in TABLE seg (DOSCODE), so CS override
CMP AL,[ESCCHAR] ; did he type a function key?
JNZ FindSetup ; no, set up for scan
invoke $STD_CON_INPUT_NO_ECHO ; eat next char
JMP short NotFnd ; go try again
FindSetup:
MOV CL,BL
SUB CL,BH ;CX is number of chars to end of template
JZ NOTFND ;At end of template
DEC CX ;Cannot point past end, limit search
JZ NOTFND ;If only one char in template, forget it
PUSH ES
PUSH DS
POP ES
PUSH DI
MOV DI,SI ;Template to ES:DI
INC DI
REPNE SCASB ;Look
POP DI
POP ES
JNZ NOTFND ;Didn't find the char
NOT CL ;Turn how far to go into how far we went
ADD CL,BL ;Add size of template
SUB CL,BH ;Subtract current pos, result distance to skip
return
NOTFND:
POP BP ;Chuck return address
JMP GETCH
entry REEDIT
MOV AL,"@" ;Output re-edit character
invoke OUTT
POP DI
PUSH DI
PUSH ES
PUSH DS
invoke COPYNEW ;Copy current line into template
POP DS
POP ES
POP SI
MOV BL,DH ;Size of line is new size template
JMP PUTNEW ;Start over again
entry EXITINS
entry ENTERINS
;hkn; SS override
NOT BYTE PTR [INSMODE]
JMP GETCH
;Put a real live ^Z in the buffer (embedded)
entry CTRLZ
MOV AL,"Z"-"@"
JMP SAVCH
;Output a CRLF
entry CRLF
MOV AL,c_CR
invoke OUTT
MOV AL,c_LF
JMP OUTT
EndProc $STD_CON_STRING_INPUT
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
ENDIF
;----------------------------------------------------------------------------
;----------------------------------------------------------------------------
BREAK <$RAW_CON_IO - Do Raw Console I/O>
;
;----------------------------------------------------------------------------
;
;** $RAW_CON_IO - Do Raw Console I/O
;
; Input or output raw character from console, no echo
;
; ENTRY DL = -1 if input
; = output character if output
; EXIT (AL) = input character if input
; USES all
;
;----------------------------------------------------------------------------
;
procedure $RAW_CON_IO,NEAR ; System call 6
MOV AL,DL
CMP AL,-1
LJNE RAWOUT ; is output
;hkn; SS override
LES DI,DWORD PTR [user_SP] ; Get pointer to register save area
XOR BX,BX
call GET_IO_SFT
retc
IFDEF DBCS ;AN000;
;hkn; SS override
push word ptr [Intercon] ;AN000;
mov [Intercon],0 ;AN000; disable interim characters
ENDIF ;AN000;
MOV AH,1
call IOFUNC
JNZ RESFLG
IFDEF DBCS ;AN000;
;hkn; SS override
pop word ptr [InterCon] ;AN000; restore interim flag
ENDIF ;AN000;
invoke SPOOLINT
OR BYTE PTR ES:[DI.user_F],40H ; Set user's zero flag
XOR AL,AL
return
RESFLG:
AND BYTE PTR ES:[DI.user_F],0FFH-40H ; Reset user's zero flag
IFDEF DBCS ;AN000;
XOR AH,AH ;AN000;
call IOFUNC ;AN000; get the character
;hkn; SS override
pop word ptr [InterCon] ;AN000;
return ;AN000;
ENDIF ;AN000; ;AN000;
;
;----------------------------------------------------------------------------
;
;** $Raw_CON_INPUT - Raw Console Input
;
; Input raw character from console, no echo
;
; ENTRY none
; EXIT (al) = character
; USES all
;
;----------------------------------------------------------------------------
;
rci0: invoke SPOOLINT
entry $RAW_CON_INPUT ; System call 7
PUSH BX
XOR BX,BX
call GET_IO_SFT
POP BX
retc
MOV AH,1
call IOFUNC
JNZ rci5
; We don't do idling here for NTVDM because softpc's
; idle detection requires a hi num polls/ tic to be
; activated
;
; 04-Aug-1992 Jonle
;
; MOV AH,84h
; INT int_IBM
JMP rci0
rci5: XOR AH,AH
call IOFUNC
IFDEF DBCS ;AN000;
;hkn; SS override
cmp [InterChar],1 ;AN000; 2/11/KK
; 2/11/KK
; Sets the application zero flag depending on the 2/11/KK
; zero flag upon entry to this routine. Then returns 2/11/KK
; from system call. 2/11/KK
; 2/11/KK
entry InterApRet ;AN000; 2/11/KK ;AN000;
pushf ;AN000; 3/16/KK
;hkn; push ds ;AN000; 3/16/KK
push bx ;AN000; 3/16/KK
;hkn; SS is DOSDATA
;hkn; Context DS ;AN000; 3/16/KK
;hkn; COUNTRY_CDPG is in DOSCODE;smr;NO in DOSDATA
MOV BX,offset DOSDATA:COUNTRY_CDPG.ccDosCodePage
cmp word ptr ss:[bx],934 ;AN000; 3/16/KK korean code page ?; bug fix. use SS
pop bx ;AN000; 3/16/KK
;hkn; pop ds ;AN000; 3/16/KK
je do_koren ;AN000; 3/16/KK
popf ;AN000; 3/16/KK
return ;AN000; 3/16/KK
do_koren: ;AN000; 3/16/KK
popf ;AN000;
;hkn; SS override
LES DI,DWORD PTR [user_SP] ;AN000; Get pointer to register save area KK
jnz sj0 ;AN000; 2/11/KK
OR BYTE PTR ES:[DI.user_F],40H ;AN000; Set user's zero flag 2/11/KK
return ;AN000; 2/11/KK
sj0: ;AN000; 2/11/KK
AND BYTE PTR ES:[DI.user_F],0FFH-40H ;AN000; Reset user's zero flag 2/KK
ENDIF ;AN000;
return ;AN000;
;
; Output the character in AL to stdout
;
entry RAWOUT
PUSH BX
MOV BX,1
call GET_IO_SFT
JC RAWRET1
MOV BX,[SI.sf_flags] ;hkn; DS set up by get_io_sft
;
; If we are a network handle OR if we are not a local device then go do the
; output the hard way.
;
AND BX,sf_isNet + devid_device
CMP BX,devid_device
JNZ RawNorm
IFDEF DBCS ;AN000;
;hkn; SS override
TEST [SaveCurFlg],01H ;AN000; print but no cursor adv?
JNZ RAWNORM ;AN000; 2/11/KK
ENDIF ;AN000;
; TEST BX,sf_isnet ; output to NET?
; JNZ RAWNORM ; if so, do normally
; TEST BX,devid_device ; output to file?
; JZ RAWNORM ; if so, do normally
PUSH DS
LDS BX,[SI.sf_devptr] ; output to special?
TEST BYTE PTR [BX+SDEVATT],ISSPEC
POP DS
ifndef NEC_98
JZ RAWNORM ; if not, do normally
INT int_fastcon ; quickly output the char
else ;NEC_98
;93/03/25 MVDM DOS5.0A---------------------------- NEC 93/01/07 ---------------
;<patch>
extrn patch_fastcon:near
public RAWRET,RAWNORM
jmp patch_fastcon
db 90h
;------------------------------------------------------------------------------
endif ;NEC_98
RAWRET:
CLC
RAWRET1:
POP BX
return
RAWNORM:
CALL RAWOUT3
JMP RAWRET
;
; Output the character in AL to handle in BX
;
entry RAWOUT2
call GET_IO_SFT
retc
RAWOUT3:
PUSH AX
JMP SHORT RAWOSTRT
ROLP:
invoke SPOOLINT
;hkn; SS override
OR [DOS34_FLAG],CTRL_BREAK_FLAG ;AN002; set control break
invoke DSKSTATCHK ;AN002; check control break
RAWOSTRT:
MOV AH,3
call IOFUNC
JZ ROLP
;SR;
; IOFUNC now returns ax = 0ffffh if there was an I24 on a status call and
;the user failed. We do not send a char if this happens. We however return
;to the caller with carry clear because this DOS call does not return any
;status.
;
inc ax ;fail on I24 if ax = -1
POP AX
jz nosend ;yes, do not send char
MOV AH,2
call IOFUNC
nosend:
CLC ; Clear carry indicating successful
return
EndProc $RAW_CON_IO
;
;----------------------------------------------------------------------------
;
; Inputs:
; AX=0 save the DEVCALL request packet
; =1 restore the DEVCALL request packet
; Function:
; save or restore the DEVCALL packet
; Returns:
; none
;
;----------------------------------------------------------------------------
;
procedure Save_Restore_Packet,NEAR
PUSH DS
PUSH ES
PUSH SI
PUSH DI
CMP AX,0 ; save packet
JZ save_packet
restore_packet:
MOV SI,OFFSET DOSDATA:Packet_Temp ;sourec
MOV DI,OFFSET DOSDATA:DEVCALL ;destination
JMP short set_seg
save_packet:
MOV DI,OFFSET DOSDATA:Packet_Temp ;destination
MOV SI,OFFSET DOSDATA:DEVCALL ;source
set_seg:
MOV AX,SS ; set DS,ES to DOSDATA
MOV DS,AX
MOV ES,AX
MOV CX,11 ; 11 words to move
REP MOVSW
POP DI
POP SI
POP ES
POP DS
return
EndProc Save_Restore_Packet
DOSCODE ENDS
END
|
; A096978: Sum of the areas of the first n Jacobsthal rectangles.
; 0,1,4,19,74,305,1208,4863,19398,77709,310612,1242907,4970722,19884713,79535216,318148151,1272578046,5090341317,20361307020,81445344595,325781145370,1303125047521,5212499258024,20849998896239,83399991856694,333599974883325,1334399884620228,5337599568307083
mov $2,$0
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
mov $3,2
pow $3,$0
mov $0,1
mul $3,2
div $3,3
mul $0,$3
add $0,1
mov $3,$0
bin $3,2
add $1,$3
lpe
|
; A226737: 11^n + n.
; 1,12,123,1334,14645,161056,1771567,19487178,214358889,2357947700,25937424611,285311670622,3138428376733,34522712143944,379749833583255,4177248169415666,45949729863572177,505447028499293788,5559917313492231499,61159090448414546310,672749994932560009221,7400249944258160101232,81402749386839761113343,895430243255237372246554,9849732675807611094711865,108347059433883722041830276,1191817653772720942460132787,13109994191499930367061460398,144209936106499234037676064109,1586309297171491574414436704920,17449402268886407318558803753831,191943424957750480504146841291842,2111377674535255285545615254209953,23225154419887808141001767796309164,255476698618765889551019445759400475
mov $1,11
pow $1,$0
add $0,$1
|
; b = 0
MOV 0, A
SWP A, B
; a = 1
MOV 1, A
; RET = A == B
EQL A, B, RET
; Show RET
MOV RET, A
SHW A
; Halt the machine.
HLT
|
.byte 0x02,0x00,0x09,0x00
.word 0x08095838
.byte 0x09,0x00,0x0F,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x00,0x01,0x00,0x00
.byte 0x00,0x1E,0x00,0x03
.byte 0x09,0x00,0x00,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x7C,0xDA,0x09,0x00
.byte 0x9E,0x33,0x00,0x00
.byte 0x09,0x00,0x01,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x1C,0x0E,0x0A,0x00
.byte 0xB0,0x04,0x00,0x00
.byte 0x09,0x00,0x02,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0xCC,0x12,0x0A,0x00
.byte 0xF0,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x09,0x00,0x0E,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x09,0x00,0x08,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x1E,0x00,0x00,0x00
.byte 0x14,0x00,0x00,0x00
.byte 0x09,0x00,0x03,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x09,0x00,0x09,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x09,0x00,0x11,0x00
.byte 0x02,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x08,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x03,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x2B,0x00,0x00,0x00
.byte 0x01,0x00,0x01,0x00
.byte 0x0C,0x00,0x00,0x00
.byte 0x42,0x00,0x00,0x00
.byte 0xF0,0x00,0x00,0x00
.byte 0x0C,0x00,0x00,0x00
.byte 0x46,0x00,0x00,0x00
.byte 0x14,0x00,0x00,0x00
.byte 0x0C,0x00,0x02,0x00
.byte 0x48,0x00,0x00,0x00
.byte 0x3F,0x00,0x00,0x00
.byte 0x0C,0x00,0x01,0x00
.byte 0x48,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0C,0x00,0x00,0x00
.byte 0x4A,0x00,0x00,0x00
.byte 0x3F,0x00,0x00,0x00
.byte 0x0C,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x00,0x40,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x03,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x2B,0x00,0x00,0x00
loadCharsAndSfx s_kappado2win1
.byte 0x02,0x00,0x09,0x00
.word 0x08095F94
.byte 0x05,0x00,0x02,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x5A,0x00,0x00,0x00
loadCharsAndSfx s_kappado2win2
.byte 0x02,0x00,0x09,0x00
.word 0x08095F3C
.byte 0x05,0x00,0x02,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x03,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x5B,0x00,0x00,0x00
loadCharsAndSfx s_kappado2win3
.byte 0x02,0x00,0x09,0x00
.word 0x08095F94
.byte 0x05,0x00,0x02,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x04,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x5C,0x00,0x00,0x00
loadCharsAndSfx s_kappado2win4
.byte 0x02,0x00,0x09,0x00
.word 0x08095F3C
.byte 0x05,0x00,0x02,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x03,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x5D,0x00,0x00,0x00
loadCharsAndSfx s_kappado2win5
.byte 0x02,0x00,0x09,0x00
.word 0x08095F94
.byte 0x05,0x00,0x02,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0F,0x00,0x02,0x00
.byte 0x07,0xFF,0xFF,0x7F
.byte 0x02,0x00,0x09,0x00
.word MinigameUnlock
.byte 0x0F,0x00,0x03,0x00
.byte 0x07,0xFF,0xFF,0x7F
.byte 0x02,0x00,0x09,0x00
.word MagicUnlock
.byte 0x02,0x00,0x00,0x00
.word 0x080A4350
.byte 0x02,0x00,0x09,0x00
.word 0x080A33D4
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x27,0x00,0x00,0x00
.byte 0x02,0x00,0x09,0x00
.word 0x080A388C
.byte 0x03,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x01,0x00,0x00,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x0A,0x00,0x01,0x00
.byte 0x00,0x00,0x00,0x00
.byte 0x27,0x00,0x00,0x00
.byte 0x02,0x00,0x09,0x00
.word 0x080A38B0
.byte 0x03,0x00,0x00,0x00 |
; A048693: Generalized Pellian with 2nd term equal to 6.
; 1,6,13,32,77,186,449,1084,2617,6318,15253,36824,88901,214626,518153,1250932,3020017,7290966,17601949,42494864,102591677,247678218,597948113,1443574444,3485097001,8413768446
mov $1,1
mov $3,4
lpb $0,1
sub $0,1
mov $2,$3
add $2,$1
mov $3,$1
add $1,$2
lpe
|
/*
;********************************************************************************************************
; uC/CPU
; CPU CONFIGURATION & PORT LAYER
;
; Copyright 2004-2020 Silicon Laboratories Inc. www.silabs.com
;
; SPDX-License-Identifier: APACHE-2.0
;
; This software is subject to an open source license and is distributed by
; Silicon Laboratories Inc. pursuant to the terms of the Apache License,
; Version 2.0 available at www.apache.org/licenses/LICENSE-2.0.
;
;********************************************************************************************************
*/
/*
;********************************************************************************************************
;
; CPU PORT FILE
;
; ColdFire
; IAR C Compiler
;
; Filename : cpu_a.asm
; Version : v1.32.00
;********************************************************************************************************
*/
/*
;********************************************************************************************************
; PUBLIC DECLARATIONS
;********************************************************************************************************
*/
PUBLIC CPU_VectInit
PUBLIC CPU_SR_Save
PUBLIC CPU_SR_Restore
/*
;********************************************************************************************************
; EXTERNAL DECLARATIONS
;********************************************************************************************************
*/
EXTERN CPU_VBR_Ptr
RSEG CODE:CODE:NOROOT(2) /* Align to power 2, 4 bytes. */
/*
;********************************************************************************************************
; VECTOR BASE REGISTER INITIALIZATION
;
; Description : This function is called to set the Vector Base Register to the value specified in
; the function argument.
;
; Argument(s) : VBR Desired vector base address.
;
; Return(s) : none.
;
; Note(s) : (1) 'CPU_VBR_Ptr' keeps the current vector base address.
;
; (2) 'VBR' parameter is assumed to be passed on D0 by the compiler.
;********************************************************************************************************
*/
CPU_VectInit:
MOVE.L D0, (CPU_VBR_Ptr) /* Save 'vbr' into CPU_VBR_Ptr */
MOVEC D0, VBR
RTS
/*
;********************************************************************************************************
; CPU_SR_Save() for OS_CRITICAL_METHOD #3
;
; Description : This functions implements the OS_CRITICAL_METHOD #3 function to preserve the state of the
; interrupt disable flag in order to be able to restore it later.
;
; Argument(s) : none.
;
; Return(s) : It is assumed that the return value is placed in the D0 register as expected by the
; compiler.
;
; Note(s) : none.
;********************************************************************************************************
*/
CPU_SR_Save:
MOVE.W SR, D0 /* Copy SR into D0 */
MOVE.W D0, D1
ORI.L #0x0700, D1 /* Disable interrupts */
MOVE.W D1, SR /* Restore SR state with interrupts disabled */
RTS
/*
;********************************************************************************************************
; CPU_SR_Restore() for OS_CRITICAL_METHOD #3
;
; Description : This functions implements the OS_CRITICAL_METHOD #function to restore the state of the
; interrupt flag.
;
; Argument(s) : cpu_sr Contents of the SR to restore. It is assumed that 'cpu_sr' is passed in D0.
;
; Return(s) : none.
;
; Note(s) : none.
;********************************************************************************************************
*/
CPU_SR_Restore:
MOVE.W D0, SR /* Restore SR previous state */
RTS
/*
;********************************************************************************************************
; CPU ASSEMBLY PORT FILE END
;********************************************************************************************************
*/
END
|
;;
;; Copyright (c) Microsoft. All rights reserved.
;; Licensed under the MIT license. See LICENSE file in the project root for full license information.
;;
#include "AsmMacros.h"
TEXTAREA
SETALIAS GetLoopIndirCells, ?GetLoopIndirCells@ModuleHeader@@QAAPAEXZ
SETALIAS g_fGcStressStarted, ?g_GCShadow@@3PAEA
SETALIAS g_pTheRuntimeInstance, ?g_pTheRuntimeInstance@@3PAVRuntimeInstance@@A
SETALIAS RuntimeInstance__ShouldHijackLoopForGcStress, ?ShouldHijackLoopForGcStress@RuntimeInstance@@QAA_NI@Z
EXTERN $g_fGcStressStarted
EXTERN $g_pTheRuntimeInstance
EXTERN $RuntimeInstance__ShouldHijackLoopForGcStress
EXTERN $GetLoopIndirCells
EXTERN RecoverLoopHijackTarget
PROBE_SAVE_FLAGS_EVERYTHING equ DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_ALL_SCRATCH
PROBE_SAVE_FLAGS_R0_IS_GCREF equ DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_R0 + PTFF_R0_IS_GCREF
;; Build a map of symbols representing offsets into a transition frame (see PInvokeTransitionFrame in
;; rhbinder.h and keep these two in sync.
map 0
m_ChainPointer field 4 ; r11 - OS frame chain used for quick stackwalks
m_RIP field 4 ; lr
m_FramePointer field 4 ; r7
m_pThread field 4
m_dwFlags field 4 ; bitmask of saved registers
m_PreservedRegs field (4 * 6) ; r4-r6,r8-r10
m_CallersSP field 4 ; sp at routine entry
m_SavedR0 field 4 ; r0
m_VolatileRegs field (4 * 4) ; r1-r3,lr
m_ReturnVfpRegs field (8 * 4) ; d0-d3, not really part of the struct
m_SavedAPSR field 4 ; saved condition codes
PROBE_FRAME_SIZE field 0
;; Support for setting up a transition frame when performing a GC probe. In many respects this is very
;; similar to the logic in COOP_PINVOKE_FRAME_PROLOG in AsmMacros.h. In most cases setting up the
;; transition frame comprises the entirety of the caller's prolog (and initial non-prolog code) and
;; similarly for the epilog. Those cases can be dealt with using PROLOG_PROBE_FRAME and EPILOG_PROBE_FRAME
;; defined below. For the special cases where additional work has to be done in the prolog we also provide
;; the lower level macros ALLOC_PROBE_FRAME, FREE_PROBE_FRAME and INIT_PROBE_FRAME that allow more control
;; to be asserted.
;;
;; Note that we currently employ a significant simplification of frame setup: we always allocate a
;; maximally-sized PInvokeTransitionFrame and save all of the registers. Depending on the caller this can
;; lead to upto five additional register saves (r0-r3,r12) or 20 bytes of stack space. I have done no
;; analysis to see whether any of the worst cases occur on performance sensitive paths and whether the
;; additional saves will show any measurable degradation.
;; Perform the parts of setting up a probe frame that can occur during the prolog (and indeed this macro
;; can only be called from within the prolog).
MACRO
ALLOC_PROBE_FRAME
PROLOG_STACK_ALLOC 4 ; Space for saved APSR
PROLOG_VPUSH {d0-d3} ; Save floating point return registers
PROLOG_PUSH {r0-r3,lr} ; Save volatile registers
PROLOG_STACK_ALLOC 4 ; Space for caller's SP
PROLOG_PUSH {r4-r6,r8-r10} ; Save non-volatile registers
PROLOG_STACK_ALLOC 8 ; Space for flags and Thread*
PROLOG_PUSH {r7} ; Save caller's frame pointer
PROLOG_PUSH {r11,lr} ; Save frame-chain pointer and return address
MEND
;; Undo the effects of an ALLOC_PROBE_FRAME. This may only be called within an epilog. Note that all
;; registers are restored (apart for sp and pc), even volatiles.
MACRO
FREE_PROBE_FRAME
EPILOG_POP {r11,lr} ; Restore frame-chain pointer and return address
EPILOG_POP {r7} ; Restore caller's frame pointer
EPILOG_STACK_FREE 8 ; Discard flags and Thread*
EPILOG_POP {r4-r6,r8-r10} ; Restore non-volatile registers
EPILOG_STACK_FREE 4 ; Discard caller's SP
EPILOG_POP {r0-r3,lr} ; Restore volatile registers
EPILOG_VPOP {d0-d3} ; Restore floating point return registers
EPILOG_STACK_FREE 4 ; Space for saved APSR
MEND
;; Complete the setup of a probe frame allocated with ALLOC_PROBE_FRAME with the initialization that can
;; occur only outside the prolog (includes linking the frame to the current Thread). This macro assumes SP
;; is invariant outside of the prolog.
;;
;; $threadReg : register containing the Thread* (this will be preserved)
;; $trashReg : register that can be trashed by this macro
;; $BITMASK : value to initialize m_dwFlags field with (register or #constant)
;; $frameSize : total size of the method's stack frame (including probe frame size)
MACRO
INIT_PROBE_FRAME $threadReg, $trashReg, $BITMASK, $frameSize
str $threadReg, [sp, #m_pThread] ; Thread *
mov $trashReg, $BITMASK ; Bitmask of preserved registers
str $trashReg, [sp, #m_dwFlags]
add $trashReg, sp, #$frameSize
str $trashReg, [sp, #m_CallersSP]
; Link the frame into the Thread.
str sp, [$threadReg, #OFFSETOF__Thread__m_pHackPInvokeTunnel]
MEND
;; Simple macro to use when setting up the probe frame can comprise the entire prolog. Call this macro
;; first in the method (no further prolog instructions can be added after this).
;;
;; $threadReg : register containing the Thread* (this will be preserved). If defaulted (specify |) then
;; the current thread will be calculated inline into r2 ($trashReg must not equal r2 in
;; this case)
;; $trashReg : register that can be trashed by this macro
;; $BITMASK : value to initialize m_dwFlags field with (register or #constant)
MACRO
PROLOG_PROBE_FRAME $threadReg, $trashReg, $BITMASK
; Local string tracking the name of the register in which the Thread* is kept. Defaults to the value
; of $threadReg.
LCLS __PPF_ThreadReg
__PPF_ThreadReg SETS "$threadReg"
; Define the method prolog, allocating enough stack space for the PInvokeTransitionFrame and saving
; incoming register values into it.
ALLOC_PROBE_FRAME
; If the caller didn't provide a value for $threadReg then generate code to fetch the Thread* into r2.
; Record that r2 holds the Thread* in our local variable.
IF "$threadReg" == ""
ASSERT "$trashReg" != "r2"
__PPF_ThreadReg SETS "r2"
INLINE_GETTHREAD $__PPF_ThreadReg, $trashReg
ENDIF
; Perform the rest of the PInvokeTransitionFrame initialization.
INIT_PROBE_FRAME $__PPF_ThreadReg, $trashReg, $BITMASK, PROBE_FRAME_SIZE
MEND
; Simple macro to use when PROLOG_PROBE_FRAME was used to set up and initialize the prolog and
; PInvokeTransitionFrame. This will define the epilog including a return via the restored LR.
MACRO
EPILOG_PROBE_FRAME
FREE_PROBE_FRAME
EPILOG_RETURN
MEND
;;
;; Macro to clear the hijack state. This is safe to do because the suspension code will not Unhijack this
;; thread if it finds it at an IP that isn't managed code.
;;
;; Register state on entry:
;; r2: thread pointer
;;
;; Register state on exit:
;; r12: trashed
;;
MACRO
ClearHijackState
mov r12, #0
str r12, [r2, #OFFSETOF__Thread__m_ppvHijackedReturnAddressLocation]
str r12, [r2, #OFFSETOF__Thread__m_pvHijackedReturnAddress]
MEND
;;
;; The prolog for all GC suspension hijacks (normal and stress). Fixes up the hijacked return address, and
;; clears the hijack state.
;;
;; Register state on entry:
;; All registers correct for return to the original return address.
;;
;; Register state on exit:
;; r2: thread pointer
;; r3: trashed
;; r12: trashed
;;
MACRO
FixupHijackedCallstack
;; r2 <- GetThread(), TRASHES r3
INLINE_GETTHREAD r2, r3
;;
;; Fix the stack by restoring the original return address
;;
ldr lr, [r2, #OFFSETOF__Thread__m_pvHijackedReturnAddress]
ClearHijackState
MEND
;;
;; Set the Thread state and wait for a GC to complete.
;;
;; Register state on entry:
;; r4: thread pointer
;;
;; Register state on exit:
;; r4: thread pointer
;; All other registers trashed
;;
EXTERN RhpWaitForGC
MACRO
WaitForGCCompletion
ldr r2, [r4, #OFFSETOF__Thread__m_ThreadStateFlags]
tst r2, #TSF_SuppressGcStress__OR__TSF_DoNotTriggerGC
bne %ft0
ldr r2, [r4, #OFFSETOF__Thread__m_pHackPInvokeTunnel]
bl RhpWaitForGC
0
MEND
MACRO
HijackTargetFakeProlog
;; This is a fake entrypoint for the method that 'tricks' the OS into calling our personality routine.
;; The code here should never be executed, and the unwind info is bogus, but we don't mind since the
;; stack is broken by the hijack anyway until after we fix it below.
PROLOG_PUSH {lr}
nop ; We also need a nop here to simulate the implied bl instruction. Without
; this, an OS-applied -2 will back up into the method prolog and the unwind
; will not be applied as desired.
MEND
;;
;;
;;
;; GC Probe Hijack targets
;;
;;
EXTERN RhpPInvokeExceptionGuard
NESTED_ENTRY RhpGcProbeHijackScalarWrapper, .text, RhpPInvokeExceptionGuard
HijackTargetFakeProlog
LABELED_RETURN_ADDRESS RhpGcProbeHijackScalar
FixupHijackedCallstack
mov r12, #DEFAULT_FRAME_SAVE_FLAGS
b RhpGcProbe
NESTED_END RhpGcProbeHijackScalarWrapper
NESTED_ENTRY RhpGcProbeHijackObjectWrapper, .text, RhpPInvokeExceptionGuard
HijackTargetFakeProlog
LABELED_RETURN_ADDRESS RhpGcProbeHijackObject
FixupHijackedCallstack
mov r12, #(DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_R0 + PTFF_R0_IS_GCREF)
b RhpGcProbe
NESTED_END RhpGcProbeHijackObjectWrapper
NESTED_ENTRY RhpGcProbeHijackByrefWrapper, .text, RhpPInvokeExceptionGuard
HijackTargetFakeProlog
LABELED_RETURN_ADDRESS RhpGcProbeHijackByref
FixupHijackedCallstack
mov r12, #(DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_R0 + PTFF_R0_IS_BYREF)
b RhpGcProbe
NESTED_END RhpGcProbeHijackByrefWrapper
#ifdef FEATURE_GC_STRESS
;;
;;
;; GC Stress Hijack targets
;;
;;
LEAF_ENTRY RhpGcStressHijackScalar
FixupHijackedCallstack
mov r12, #DEFAULT_FRAME_SAVE_FLAGS
b RhpGcStressProbe
LEAF_END RhpGcStressHijackScalar
LEAF_ENTRY RhpGcStressHijackObject
FixupHijackedCallstack
mov r12, #(DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_R0 + PTFF_R0_IS_GCREF)
b RhpGcStressProbe
LEAF_END RhpGcStressHijackObject
LEAF_ENTRY RhpGcStressHijackByref
FixupHijackedCallstack
mov r12, #(DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_R0 + PTFF_R0_IS_BYREF)
b RhpGcStressProbe
LEAF_END RhpGcStressHijackByref
;;
;; Worker for our GC stress probes. Do not call directly!!
;; Instead, go through RhpGcStressHijack{Scalar|Object|Byref}.
;; This worker performs the GC Stress work and returns to the original return address.
;;
;; Register state on entry:
;; r0: hijacked function return value
;; r1: hijacked function return value
;; r2: thread pointer
;; r12: register bitmask
;;
;; Register state on exit:
;; Scratch registers, except for r0, have been trashed
;; All other registers restored as they were when the hijack was first reached.
;;
NESTED_ENTRY RhpGcStressProbe
PROLOG_PROBE_FRAME r2, r3, r12
bl $REDHAWKGCINTERFACE__STRESSGC
EPILOG_PROBE_FRAME
NESTED_END RhpGcStressProbe
#endif ;; FEATURE_GC_STRESS
LEAF_ENTRY RhpGcProbe
ldr r3, =RhpTrapThreads
ldr r3, [r3]
cbnz r3, %0
bx lr
0
b RhpGcProbeRare
LEAF_END RhpGcProbe
NESTED_ENTRY RhpGcProbeRare
PROLOG_PROBE_FRAME r2, r3, r12
mov r4, r2
WaitForGCCompletion
EPILOG_PROBE_FRAME
NESTED_END RhpGcProbe
LEAF_ENTRY RhpGcPoll
; @todo: I'm assuming it's not OK to trash any register here. If that's not true we can optimize the
; push/pops out of this fast path.
push {r0}
ldr r0, =RhpTrapThreads
ldr r0, [r0]
cbnz r0, %0
pop {r0}
bx lr
0
pop {r0}
b RhpGcPollRare
LEAF_END RhpGcPoll
NESTED_ENTRY RhpGcPollRare
PROLOG_PROBE_FRAME |, r3, #PROBE_SAVE_FLAGS_EVERYTHING
; Unhijack this thread, if necessary.
INLINE_THREAD_UNHIJACK r2, r0, r1 ;; trashes r0, r1
mov r4, r2
WaitForGCCompletion
EPILOG_PROBE_FRAME
NESTED_END RhpGcPoll
LEAF_ENTRY RhpGcPollStress
;
; loop hijacking is used instead
;
__debugbreak
LEAF_END RhpGcPollStress
#ifdef FEATURE_GC_STRESS
NESTED_ENTRY RhpHijackForGcStress
PROLOG_PUSH {r0,r1} ; Save return value
PROLOG_VPUSH {d0-d3} ; Save VFP return value
;;
;; Setup a PAL_LIMITED_CONTEXT that looks like what you'd get if you had suspended this thread at the
;; IP after the call to this helper.
;;
;; This is very likely overkill since the calculation of the return address should only need SP and
;; LR, but this is test code, so I'm not too worried about efficiency.
;;
;; Setup a PAL_LIMITED_CONTEXT on the stack {
;; we'll need to reserve the size of the D registers in the context
;; compute in the funny way below to include any padding between LR and D
DREG_SZ equ (SIZEOF__PAL_LIMITED_CONTEXT - (OFFSETOF__PAL_LIMITED_CONTEXT__LR + 4))
PROLOG_STACK_ALLOC DREG_SZ ;; Reserve space for d8-d15
PROLOG_PUSH {r0,lr} ;; Reserve space for SP and store LR
PROLOG_PUSH {r0,r4-r11,lr}
;; } end PAL_LIMITED_CONTEXT
;; Compute and save SP at callsite.
add r0, sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20 + 8) ;; +0x20 for vpush {d0-d3}, +8 for push {r0,r1}
str r0, [sp, #OFFSETOF__PAL_LIMITED_CONTEXT__SP]
mov r0, sp ; Address of PAL_LIMITED_CONTEXT
bl $THREAD__HIJACKFORGCSTRESS
;; epilog
EPILOG_POP {r0,r4-r11,lr}
EPILOG_STACK_FREE DREG_SZ + 8 ; Discard saved SP and LR and space for d8-d15
EPILOG_VPOP {d0-d3} ; Restore VFP return value
EPILOG_POP {r0,r1} ; Restore return value
bx lr
NESTED_END RhpHijackForGcStress
#endif ;; FEATURE_GC_STRESS
;;
;; The following functions are _jumped_ to when we need to transfer control from one method to another for EH
;; dispatch. These are needed to properly coordinate with the GC hijacking logic. We are essentially replacing
;; the return from the throwing method with a jump to the handler in the caller, but we need to be aware of
;; any return address hijack that may be in place for GC suspension. These routines use a quick test of the
;; return address against a specific GC hijack routine, and then fixup the stack pointer to what it would be
;; after a real return from the throwing method. Then, if we are not hijacked we can simply jump to the
;; handler in the caller.
;;
;; If we are hijacked, then we jump to a routine that will unhijack appropriatley and wait for the GC to
;; complete. There are also variants for GC stress.
;;
;; Note that at this point we are eiher hijacked or we are not, and this will not change until we return to
;; managed code. It is an invariant of the system that a thread will only attempt to hijack or unhijack
;; another thread while the target thread is suspended in managed code, and this is _not_ managed code.
;;
;; Register state on entry:
;; r0: pointer to this function (i.e., trash)
;; r1: reference to the exception object.
;; r2: handler address we want to jump to.
;; Non-volatile registers are all already correct for return to the caller.
;; LR still contains the return address.
;;
;; Register state on exit:
;; All registers except r0 and lr unchanged
;;
MACRO
RTU_EH_JUMP_HELPER $funcName, $hijackFuncName, $isStress, $stressFuncName
LEAF_ENTRY $funcName
; Currently the EH epilog won't pop the return address back into LR,
; so we have to have a funny load from [sp-4] here to retrieve it.
ldr r0, =$hijackFuncName
cmp r0, lr
beq RhpGCProbeForEHJump
IF $isStress
ldr r0, =$stressFuncName
cmp r0, lr
beq RhpGCStressProbeForEHJump
ENDIF
;; We are not hijacked, so we can return to the handler.
;; We return to keep the call/return prediction balanced.
mov lr, r2 ; Update the return address
bx lr
LEAF_END $funcName
MEND
;; We need an instance of the helper for each possible hijack function. The binder has enough
;; information to determine which one we need to use for any function.
RTU_EH_JUMP_HELPER RhpEHJumpScalar, RhpGcProbeHijackScalar, {false}, 0
RTU_EH_JUMP_HELPER RhpEHJumpObject, RhpGcProbeHijackObject, {false}, 0
RTU_EH_JUMP_HELPER RhpEHJumpByref, RhpGcProbeHijackByref, {false}, 0
#ifdef FEATURE_GC_STRESS
RTU_EH_JUMP_HELPER RhpEHJumpScalarGCStress, RhpGcProbeHijackScalar, {true}, RhpGcStressHijackScalar
RTU_EH_JUMP_HELPER RhpEHJumpObjectGCStress, RhpGcProbeHijackObject, {true}, RhpGcStressHijackObject
RTU_EH_JUMP_HELPER RhpEHJumpByrefGCStress, RhpGcProbeHijackByref, {true}, RhpGcStressHijackByref
#endif
;;
;; Macro to setup our frame and adjust the location of the EH object reference for EH jump probe funcs.
;;
;; Register state on entry:
;; r0: scratch
;; r1: reference to the exception object.
;; r2: handler address we want to jump to.
;; Non-volatile registers are all already correct for return to the caller.
;; The stack is as if we are just about to returned from the call
;;
;; Register state on exit:
;; r0: reference to the exception object
;; r2: thread pointer
;;
MACRO
EHJumpProbeProlog
PROLOG_PUSH {r1,r2} ; save the handler address so we can jump to it later (save r1 just for alignment)
PROLOG_NOP mov r0, r1 ; move the ex object reference into r0 so we can report it
ALLOC_PROBE_FRAME
;; r2 <- GetThread(), TRASHES r1
INLINE_GETTHREAD r2, r1
;; Recover the original return address and update the frame
ldr lr, [r2, #OFFSETOF__Thread__m_pvHijackedReturnAddress]
str lr, [sp, #OFFSETOF__PInvokeTransitionFrame__m_RIP]
;; ClearHijackState expects thread in r2 (trashes r12).
ClearHijackState
; TRASHES r1
INIT_PROBE_FRAME r2, r1, #PROBE_SAVE_FLAGS_R0_IS_GCREF, (PROBE_FRAME_SIZE + 8)
MEND
;;
;; Macro to re-adjust the location of the EH object reference, cleanup the frame, and make the
;; final jump to the handler for EH jump probe funcs.
;;
;; Register state on entry:
;; r0: reference to the exception object
;; r1-r3: scratch
;;
;; Register state on exit:
;; sp: correct for return to the caller
;; r1: reference to the exception object
;;
MACRO
EHJumpProbeEpilog
FREE_PROBE_FRAME ; This restores exception object back into r0
EPILOG_NOP mov r1, r0 ; Move the Exception object back into r1 where the catch handler expects it
EPILOG_POP {r0,pc} ; Recover the handler address and jump to it
MEND
;;
;; We are hijacked for a normal GC (not GC stress), so we need to unhijack and wait for the GC to complete.
;;
;; Register state on entry:
;; r0: reference to the exception object.
;; r2: thread
;; Non-volatile registers are all already correct for return to the caller.
;; The stack is as if we have tail called to this function (lr points to return address).
;;
;; Register state on exit:
;; r7: previous frame pointer
;; r0: reference to the exception object
;;
NESTED_ENTRY RhpGCProbeForEHJump
EHJumpProbeProlog
#ifdef _DEBUG
;;
;; If we get here, then we have been hijacked for a real GC, and our SyncState must
;; reflect that we've been requested to synchronize.
ldr r1, =RhpTrapThreads
ldr r1, [r1]
cbnz r1, %0
bl $PALDEBUGBREAK
0
#endif ;; _DEBUG
mov r4, r2
WaitForGCCompletion
EHJumpProbeEpilog
NESTED_END RhpGCProbeForEHJump
#ifdef FEATURE_GC_STRESS
;;
;; We are hijacked for GC Stress (not a normal GC) so we need to invoke the GC stress helper.
;;
;; Register state on entry:
;; r1: reference to the exception object.
;; r2: thread
;; Non-volatile registers are all already correct for return to the caller.
;; The stack is as if we have tail called to this function (lr points to return address).
;;
;; Register state on exit:
;; r7: previous frame pointer
;; r0: reference to the exception object
;;
NESTED_ENTRY RhpGCStressProbeForEHJump
EHJumpProbeProlog
bl $REDHAWKGCINTERFACE__STRESSGC
EHJumpProbeEpilog
NESTED_END RhpGCStressProbeForEHJump
;;
;; INVARIANT: Don't trash the argument registers, the binder codegen depends on this.
;;
LEAF_ENTRY RhpSuppressGcStress
push {r0-r2}
INLINE_GETTHREAD r0, r1
Retry
ldrex r1, [r0, #OFFSETOF__Thread__m_ThreadStateFlags]
orr r1, #TSF_SuppressGcStress
strex r2, r1, [r0, #OFFSETOF__Thread__m_ThreadStateFlags]
cbz r2, Success
b Retry
Success
pop {r0-r2}
bx lr
LEAF_END RhpSuppressGcStress
#endif ;; FEATURE_GC_STRESS
;; Helper called from hijacked loops
LEAF_ENTRY RhpLoopHijack
;; we arrive here with essentially all registers containing useful content
;; except r12, which we trashed
;; on the stack, we have two arguments:
;; - [sp+0] has the module header
;; - [sp+4] has the address of the indirection cell we jumped through
;;
;;
;; save registers
ALLOC_PROBE_FRAME
; save condition codes
mrs r12, apsr
str r12, [sp, #m_SavedAPSR]
INLINE_GETTHREAD r4, r1
INIT_PROBE_FRAME r4, r1, #PROBE_SAVE_FLAGS_EVERYTHING, (PROBE_FRAME_SIZE + 8)
;;
;; compute the index of the indirection cell
;;
ldr r0, [sp,#(PROBE_FRAME_SIZE+0)]
bl $GetLoopIndirCells
; r0 now has address of the first loop indir cell
; subtract that from the address of our cell
; and divide by 4 to give the index of our cell
ldr r1, [sp,#(PROBE_FRAME_SIZE+4)]
sub r1, r0
lsr r0, r1, #2
; r0 now has the index
; recover the loop hijack target, passing the module header as an additional argument
ldr r1, [sp,#(PROBE_FRAME_SIZE+0)]
bl RecoverLoopHijackTarget
; store the result as our pinvoke return address
str r0, [sp, #OFFSETOF__PInvokeTransitionFrame__m_RIP]
; also save it in the incoming parameter space for the actual return below
str r0, [sp,#(PROBE_FRAME_SIZE+4)]
; Early out if GC stress is currently suppressed. Do this after we have computed the real address to
; return to but before we link the transition frame onto m_pHackPInvokeTunnel (because hitting this
; condition implies we're running restricted callouts during a GC itself and we could end up
; overwriting a co-op frame set by the code that caused the GC in the first place, e.g. a GC.Collect
; call).
ldr r1, [r4, #OFFSETOF__Thread__m_ThreadStateFlags]
tst r1, #TSF_SuppressGcStress__OR__TSF_DoNotTriggerGC
bne DoneWaitingForGc
; link the frame into the Thread
str sp,[r4, #OFFSETOF__Thread__m_pHackPInvokeTunnel]
;;
;; Unhijack this thread, if necessary.
;;
INLINE_THREAD_UNHIJACK r4, r1, r2 ;; trashes r1, r2
#ifdef FEATURE_GC_STRESS
ldr r1, =$g_fGcStressStarted
ldr r1, [r1]
cmp r1, #0
bne NoGcStress
mov r1, r0
ldr r0, =$g_pTheRuntimeInstance
ldr r0, [r0]
bl $RuntimeInstance__ShouldHijackLoopForGcStress
cmp r0, #0
beq NoGcStress
bl $REDHAWKGCINTERFACE__STRESSGC
NoGcStress
#endif ;; FEATURE_GC_STRESS
ldr r2, [r4, #OFFSETOF__Thread__m_pHackPInvokeTunnel]
bl RhpWaitForGC
DoneWaitingForGc
; restore condition codes
ldr r12, [sp, #m_SavedAPSR]
msr apsr_nzcvqg, r12
FREE_PROBE_FRAME
EPILOG_POP {r12,pc} ; recover the hijack target and jump to it
LEAF_END RhpLoopHijack
end
|
; A112460: Absolute value of coefficient of term [x^(n-4)] in characteristic polynomial of maximum matrix A of size n X n, where n >= 4. Maximum matrix A(i,j) is MAX(i,j), where indices i and j run from 1 to n.
; 4,39,207,795,2475,6633,15873,34749,70785,135850,247962,433602,730626,1191870,1889550,2920566,4412826,6532713,9493825,13567125,19092645,26492895,36288135,49113675,65739375,87091524,114277284,148611892,191648820,245213100,311438028
lpb $0
mov $2,$0
sub $0,1
seq $2,27791 ; a(n) = 5*(n+1)*C(n+3,6).
add $1,$2
lpe
div $1,5
add $1,4
mov $0,$1
|
; $Id: ASMXSave.asm $
;; @file
; IPRT - ASMXSave().
;
;
; Copyright (C) 2006-2015 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
;*******************************************************************************
;* Header Files *
;*******************************************************************************
%define RT_ASM_WITH_SEH64
%include "iprt/asmdefs.mac"
BEGINCODE
;;
; Saves extended CPU state.
; @param pXStateArea Pointer to the XSAVE state area.
; msc=rcx, gcc=rdi, x86=[esp+4]
; @param fComponents The 64-bit state component mask.
; msc=rdx, gcc=rsi, x86=[esp+8]
;
BEGINPROC_EXPORTED ASMXSave
SEH64_END_PROLOGUE
%ifdef ASM_CALL64_MSC
mov eax, edx
shr rdx, 32
xsave [rcx]
%elifdef ASM_CALL64_GCC
mov rdx, rsi
shr rdx, 32
mov eax, esi
xsave [rdi]
%elifdef RT_ARCH_X86
mov ecx, [esp + 4]
mov eax, [esp + 8]
mov edx, [esp + 12]
xsave [ecx]
%else
%error "Undefined arch?"
%endif
ret
ENDPROC ASMXSave
|
arch snes.cpu
lorom
org $83ADA0
db $FD, $92, $00, $05, $3E, $26, $03, $02, $00, $80, $A2, $B9 //door to parlor
db $2B, $B6, $40, $04, $01, $06, $00, $00, $00, $80, $00, $00 //door to metal pirates
db $79, $98, $40, $05, $2E, $06, $02, $00, $00, $80, $00, $00 //to pre-bt
org $8F98DC
db $06, $F0 //setup asm pointer for pre-bt room
org $8FF000
db $A0, $AD, $AC, $AD //door out pointer for pre-bt
org $8FF006
LDA #$F000 //load door pointer
STA $7E07B5 //change door out pointer
JML $8F91BB //run original code
org $8FB650
db $18, $F0 //setup asm pointer for metal pirates
org $8FEFF0
db $B8, $AD, $AC, $AD //door out pointer for metal pirates room
org $8FF018
LDA $7ED820 //loads event flags
BIT #$4000 //checks for escape flag set
BEQ quit
LDA #$0000
STA $7ED8BC //resets grey door for metal pirates
LDA #$EFF0 //load door pointer
STA $7E07B5 //change door out pointer
JML $8F91F7 //run original code for ridley
quit:
RTS |
;
; $Id: led_mt2.asm,v 1.0 2016/10/30 13:00:00 srajesh Exp $
;
; This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
;
; Copyright 2007-2020 Broadcom Inc. All rights reserved.
;
;
; This is to be used on the BCM56960 SDKs with MOntreal2.
; To start it, use the following commands from BCM:
;
; led 0 load sdk56960_mt2.hex
; led 0 auto on
; led 0 start
;
; The are 2 LEDs per port one for Link(Top) and one for activity(Bottom).
;
; Each chip drives only its own LEDs and needs to write them in the order:
; L01/A01, L02/A02, ..., L64/A64
;
; There are two bits per Ethernet LED for activity with the following colors:
; ZERO, ZERO Black
; ZERO, ONE Amber
; ONE, ZERO Green
;
; Link up/down info cannot be derived from LINKEN or LINKUP, as the LED
; processor does not always have access to link status. This program
; assumes link status is kept current in bit 0 of RAM byte (0xA0 + portnum).
; Generally, a program running on the main CPU must update these
; locations on link change; see linkscan callback in
; $SDK/src/appl/diag/ledproc.c.
;
; When Montreal2 inband stats collection is running, the activity is not
; derived from TX and RX. The Software-calculated activity is kept in the
; RAM byte (0xA0 + portnum) in bits 1 & 2
;
; Current implementation:
;
; L01 reflects port 1 link status:
; Black: no link
; Green: Link
;
; A01 reflects port 1 activity status:
; Black: no link
; Green: Link
; Amber: Activity
;
;
TICKS EQU 1
SECOND_TICKS EQU (30*TICKS)
TXRX_ALT_TICKS EQU (SECOND_TICKS/6)
MIN_PORT EQU 0
MAX_PORT EQU 63
NUM_PORT EQU 64
; Assumptions
; LED status [TX/RX Activity] is organized to map 1:1 for indexing with
; link status data thru' CMIC_LEDUP*_PORT_ORDER_REMAP_* registers.
; Link status is injected by SDK from Linkscan task at PORTDATA offset
;
; Main Update Routine
;
; This routine is called once per tick.
;
update:
ld A,MIN_PORT
port_loop:
port A
ld (PORT_NUM),A
call link_status ; Top LED for this port
call chk_activity ; Bottom LED for this port
; Debug
;call led_green
;call led_amber
; Debug
ld a,(PORT_NUM)
inc a
cmp a,NUM_PORT
jnz port_loop
; Update various timers
inc (TXRX_ALT_COUNT)
send 252 ; 2 * 2 * 63
;
;
;
; This routine calculates the activity LED for the current port.
; It extends the activity lights using timers (new activity overrides
; and resets the timers).
;
; Inputs: (PORT_NUM)
; Outputs: two bit sent to LED stream
;
; Activity status LED update
chk_activity:
ld b,PORTDATA
add b,a
ld b,(b)
tst b,1
push CY ; TX
tst b,2
push CY ; RX
tor
pop
jnc led_black ; Always black, No Activity
;jmp led_green ;DEBUG ONLY
ld b, (TXRX_ALT_COUNT)
and b, TXRX_ALT_TICKS
jnz led_amber
jmp led_black ; Fast alternation of black/amber
; Link status LED update
link_status:
call get_link
jnc led_black
jmp led_green
;
; get_link
;
; This routine finds the link status LED for a port.
; Link info is in bit 0 of the byte read from PORTDATA[port]
;
; Inputs: Port number in a
; Outputs: Carry flag set if link is up, clear if link is down.
; Destroys: a, b
;
get_link:
ld b,PORTDATA
add b,a
ld b,(b)
tst b,0
ret
get_link_hw:
port a
pushst LINKUP
pop
ret
;
; led_black, led_amber, led_green
;
; Inputs: None
; Outputs: Two bits to the LED stream indicating color
; Destroys: None
;
led_black:
pushst ZERO
pack
pushst ZERO
pack
ret
led_amber:
pushst ONE
pack
pushst ZERO
pack
ret
led_green:
pushst ZERO
pack
pushst ONE
pack
ret
;
; Variables (SDK software initializes LED memory from 0xa0-0xff to 0)
;
TXRX_ALT_COUNT equ 0xe0
PORT_NUM equ 0xe1
;
; Port data, which must be updated continually by main CPU's
; linkscan task. See $SDK/src/appl/diag/ledproc.c for examples.
; In this program, bit 0 is assumed to contain the link up/down status.
;
;Offset 0x1e00 - 0x80
;LED scan chain assembly area
;Offset 0x1e80 - 0xa0
PORTDATA equ 0xa0 ; Size 48 + 1 + 4 bytes
;
; Symbolic names for the bits of the port status fields
;
RX equ 0x0 ; received packet
TX equ 0x1 ; transmitted packet
COLL equ 0x2 ; collision indicator
SPEED_C equ 0x3 ; 100 Mbps
SPEED_M equ 0x4 ; 1000 Mbps
DUPLEX equ 0x5 ; half/full duplex
FLOW equ 0x6 ; flow control capable
LINKUP equ 0x7 ; link down/up status
LINKEN equ 0x8 ; link disabled/enabled status
ZERO equ 0xE ; always 0
ONE equ 0xF ; always 1
|
map_header UndergroundPathRoute5, UNDERGROUND_PATH_ROUTE_5, GATE, 0
end_map_header
|
; A092460: Numbers that are not Bell numbers (A000110).
; 0,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,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,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79
mov $1,2
mov $2,$0
mov $3,$0
mov $4,2
lpb $2
div $2,3
add $4,$1
mul $2,$4
add $1,$2
log $1,4
add $1,4
sub $2,$2
lpe
sub $1,2
add $1,$3
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r14
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xe306, %rsi
lea addresses_D_ht+0x1d406, %rdi
nop
nop
sub $62734, %r14
mov $43, %rcx
rep movsq
nop
and %rax, %rax
lea addresses_normal_ht+0x1df3f, %r8
nop
add %r14, %r14
movl $0x61626364, (%r8)
nop
nop
nop
nop
dec %rax
lea addresses_A_ht+0xde06, %rsi
lea addresses_WT_ht+0x4406, %rdi
nop
nop
nop
dec %rax
mov $32, %rcx
rep movsb
nop
nop
nop
nop
dec %rax
lea addresses_D_ht+0x15106, %rcx
nop
nop
inc %r11
mov $0x6162636465666768, %r8
movq %r8, (%rcx)
nop
nop
nop
nop
nop
xor %r8, %r8
lea addresses_WT_ht+0x3a06, %rsi
lea addresses_A_ht+0x1a1e6, %rdi
clflush (%rsi)
nop
inc %rbx
mov $18, %rcx
rep movsl
nop
nop
cmp $26236, %r14
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r14
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r14
push %r15
push %r8
push %rax
push %rbx
push %rcx
// Load
lea addresses_WT+0x189ee, %rbx
nop
and %r8, %r8
movb (%rbx), %r13b
nop
nop
nop
cmp %rbx, %rbx
// Store
mov $0x81a, %rax
nop
nop
nop
nop
nop
add $29870, %rcx
mov $0x5152535455565758, %r13
movq %r13, %xmm1
vmovups %ymm1, (%rax)
nop
nop
add %rbx, %rbx
// Store
lea addresses_RW+0x2106, %r8
nop
nop
nop
xor $47482, %rcx
movb $0x51, (%r8)
nop
nop
sub %r14, %r14
// Faulty Load
lea addresses_D+0x1a406, %rbx
sub %rax, %rax
mov (%rbx), %r15w
lea oracles, %rax
and $0xff, %r15
shlq $12, %r15
mov (%rax,%r15,1), %r15
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r15
pop %r14
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'src': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_P'}}
{'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_RW'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 5, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': True, 'type': 'addresses_A_ht'}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// archive_serializer_map.ipp:
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// 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 for updates, documentation, and revision history.
//////////////////////////////////////////////////////////////////////
// implementation of basic_text_iprimitive overrides for the combination
// of template parameters used to implement a text_iprimitive
#include <autoboost/config.hpp>
#include <autoboost/archive/detail/archive_serializer_map.hpp>
#include <autoboost/archive/detail/basic_serializer_map.hpp>
#include <autoboost/serialization/singleton.hpp>
namespace autoboost {
namespace archive {
namespace detail {
#ifdef AUTOBOOST_MSVC
# pragma warning(push)
# pragma warning(disable : 4511 4512)
#endif
namespace extra_detail { // anon
template<class Archive>
class map : public basic_serializer_map
{};
}
#ifdef AUTOBOOST_MSVC
# pragma warning(pop)
#endif
template<class Archive>
AUTOBOOST_ARCHIVE_OR_WARCHIVE_DECL(bool)
archive_serializer_map<Archive>::insert(const basic_serializer * bs){
return autoboost::serialization::singleton<
extra_detail::map<Archive>
>::get_mutable_instance().insert(bs);
}
template<class Archive>
AUTOBOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
archive_serializer_map<Archive>::erase(const basic_serializer * bs){
if(autoboost::serialization::singleton<
extra_detail::map<Archive>
>::is_destroyed())
return;
autoboost::serialization::singleton<
extra_detail::map<Archive>
>::get_mutable_instance().erase(bs);
}
template<class Archive>
AUTOBOOST_ARCHIVE_OR_WARCHIVE_DECL(const basic_serializer *)
archive_serializer_map<Archive>::find(
const autoboost::serialization::extended_type_info & eti
) {
return autoboost::serialization::singleton<
extra_detail::map<Archive>
>::get_const_instance().find(eti);
}
} // namespace detail
} // namespace archive
} // namespace autoboost
|
; A278818: a(n) is the least k > n such that k + n is square.
; 1,3,7,6,5,11,10,9,17,16,15,14,13,23,22,21,20,19,31,30,29,28,27,26,25,39,38,37,36,35,34,33,49,48,47,46,45,44,43,42,41,59,58,57,56,55,54,53,52,51,71,70,69,68,67,66,65,64,63,62,61,83,82,81,80,79,78,77,76,75,74,73,97,96,95,94,93,92,91,90,89,88,87,86,85,111,110,109,108,107,106,105,104,103,102,101,100,99,127,126,125,124,123,122,121,120,119,118,117,116,115,114,113,143,142,141,140,139,138,137,136,135,134,133,132,131,130,129,161,160,159,158,157,156,155,154,153,152,151,150,149,148,147,146,145,179,178,177,176,175,174,173,172,171,170,169,168,167,166,165,164,163,199,198,197,196,195,194,193,192,191,190,189,188,187,186,185,184,183,182,181,219,218,217,216,215,214,213,212,211,210,209,208,207,206,205,204,203,202,201,241,240,239,238,237,236,235,234,233,232,231,230,229,228,227,226,225,224,223,222,221,263,262,261,260,259,258,257,256,255,254,253,252,251,250,249,248,247,246,245,244,243,287,286,285,284,283,282,281,280
mov $1,$0
mul $1,2
cal $1,80883 ; Distance of n to next square.
add $1,$0
|
#include <math.h>
#include "mex.h"
#include "graph.h"
#include <vector>
void
mexFunction(int nout, mxArray *out[],
int nin, const mxArray *in[])
{
if (nin != 3)
mexErrMsgTxt("Three arguments are required (nNodes,TerminalWeights,EdgeWeights)") ;
if (nout > 2)
mexErrMsgTxt("Too many output arguments.");
int nNodes = (int) *mxGetPr(in[0]);
const int* twDim = mxGetDimensions(in[1]) ;
int twRows = twDim[0] ;
int twCols = twDim[1] ;
double* twPt = mxGetPr(in[1]) ;
if(twCols!=3)
mexErrMsgTxt("The Terminal Weight matix should have 3 columns, (Node,sink,source).");
const int* ewDim = mxGetDimensions(in[2]) ;
int ewRows = ewDim[0] ;
int ewCols = ewDim[1] ;
double* ewPt = mxGetPr(in[2]) ;
if(ewCols!=4)
mexErrMsgTxt("The Terminal Weight matix should have 4 columns, (From,To,Capacity,Rev_Capacity).");
typedef Graph<double,double,double> GraphType;
GraphType G(static_cast<int>(nNodes), static_cast<int>(ewRows+twRows));
G.add_node(nNodes);
for(int cTw=0;cTw<twRows;cTw++)
{
//Test for nodes in range
int node=(int)twPt[cTw]-1;
if(node<0 || node>=nNodes)
mexErrMsgTxt("index out of bounds in TerminalWeight Matrix.");
G.add_tweights(node,twPt[cTw+twRows],twPt[cTw+2*twRows]);
}
for(int cEw=0;cEw<ewRows;cEw++)
{
//Test for nodes in range
int From=(int)ewPt[cEw]-1;
int To=(int)ewPt[cEw+ewRows]-1;
if(From<0 || From>=nNodes)
mexErrMsgTxt("From index out of bounds in Edge Weight Matrix.");
if(To<0 || To>=nNodes)
mexErrMsgTxt("To index out of bounds in Edge Weight Matrix.");
G.add_edge(From,To,ewPt[cEw+2*ewRows],ewPt[cEw+3*ewRows]);
}
double flow=G.maxflow();
std::vector<int> SourceCut;
for(int cNode=0;cNode<nNodes;cNode++)
{
if(G.what_segment(cNode)== GraphType::SOURCE)
SourceCut.push_back(cNode+1);
}
out[0] = mxCreateDoubleMatrix(SourceCut.size(), 1, mxREAL) ;
double* pOut=mxGetPr(out[0]);
std::vector<int>::const_iterator Itt(SourceCut.begin());
for(;Itt!=SourceCut.end();++Itt)
{
*pOut=*Itt;
++pOut;
}
if(nout==2)
{
out[1] = mxCreateDoubleMatrix(1, 1, mxREAL) ;
*mxGetPr(out[1])=flow;
}
} |
#include <jni.h>
#include <string>
#include <sys/select.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <ifaddrs.h>
#include <netdb.h>
#include <netinet/in.h>
#include "ifaddrs.h"
#include "android/log.h"
extern "C"
JNIEXPORT jstring JNICALL
Java_com_yx_netprobe_ShowIPActivity_cpp_1get_1ip(JNIEnv *env, jobject thiz) {
std::string respstr = "Get JNI local IP!\n";
int family, s;
char host[NI_MAXHOST];
struct ifaddrs *ifap;
getifaddrs(&ifap);
for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
if (family == AF_INET || family == AF_INET6) {
// s = getnameinfo(ifa->ifa_addr,
// (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
// host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
// if (s != 0) {
// __android_log_print(ANDROID_LOG_INFO, "getifaddrs", "getnameinfo() failed: %s", gai_strerror(s));
// continue;
// }
if (family == AF_INET) {
inet_ntop(AF_INET, &((struct sockaddr_in*)(ifa->ifa_addr))->sin_addr, host, sizeof(host));
} else {
inet_ntop(AF_INET6, &((struct sockaddr_in6*)(ifa->ifa_addr))->sin6_addr, host, sizeof(host));
}
__android_log_print(ANDROID_LOG_INFO, "getifaddrs", "address: <%s>", host);
respstr += "address: [";
respstr += ifa->ifa_name;
respstr += " ";
respstr += host;
respstr += "]\n";
}
}
freeifaddrs(ifap);
return env->NewStringUTF(respstr.c_str());
} |
; 32-bit print function
;
; Parameters:
; EBX - address of string to be printed
;
; Print is performed using direct video memory addressing
[bits 32]
VIDEO_MEM equ 0xB8000
print_no_bios:
pusha
mov edx, VIDEO_MEM
print_no_bios_loop:
mov al, [ebx] ; AL holds the character value (pointed to by EBX)
mov ah, 0x0F ; VGA attribute for white foreground, black background
cmp al, 0 ; Exit condition (null terminator found)
je print_no_bios_done
mov [edx], ax ; Store character + attribute in video memory
add ebx, 1 ; Move to next character in string
add edx, 2 ; Jump 2 bytes in video memory for each character
; 1 byte is used for the character and 1 for the attributes
jmp print_no_bios_loop
print_no_bios_done:
popa
ret
|
; A155966: a(n) = 2*n^2 + 8.
; 8,10,16,26,40,58,80,106,136,170,208,250,296,346,400,458,520,586,656,730,808,890,976,1066,1160,1258,1360,1466,1576,1690,1808,1930,2056,2186,2320,2458,2600,2746,2896,3050,3208,3370,3536,3706,3880,4058,4240,4426,4616,4810,5008,5210,5416,5626,5840,6058,6280,6506,6736,6970,7208,7450,7696,7946,8200,8458,8720,8986,9256,9530,9808,10090,10376,10666,10960,11258,11560,11866,12176,12490,12808,13130,13456,13786,14120,14458,14800,15146,15496,15850,16208,16570,16936,17306,17680,18058,18440,18826,19216,19610
pow $0,2
mul $0,2
add $0,8
|
_grep: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
}
}
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 57 push %edi
e: 56 push %esi
f: 53 push %ebx
10: 51 push %ecx
11: 83 ec 18 sub $0x18,%esp
14: 8b 39 mov (%ecx),%edi
16: 8b 59 04 mov 0x4(%ecx),%ebx
int fd, i;
char *pattern;
if(argc <= 1){
19: 83 ff 01 cmp $0x1,%edi
1c: 7e 7c jle 9a <main+0x9a>
printf(2, "usage: grep pattern [file ...]\n");
exit();
}
pattern = argv[1];
1e: 8b 43 04 mov 0x4(%ebx),%eax
21: 83 c3 08 add $0x8,%ebx
if(argc <= 2){
24: 83 ff 02 cmp $0x2,%edi
grep(pattern, 0);
exit();
}
for(i = 2; i < argc; i++){
27: be 02 00 00 00 mov $0x2,%esi
pattern = argv[1];
2c: 89 45 e0 mov %eax,-0x20(%ebp)
if(argc <= 2){
2f: 74 46 je 77 <main+0x77>
31: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if((fd = open(argv[i], 0)) < 0){
38: 83 ec 08 sub $0x8,%esp
3b: 6a 00 push $0x0
3d: ff 33 pushl (%ebx)
3f: e8 7e 05 00 00 call 5c2 <open>
44: 83 c4 10 add $0x10,%esp
47: 85 c0 test %eax,%eax
49: 78 3b js 86 <main+0x86>
printf(1, "grep: cannot open %s\n", argv[i]);
exit();
}
grep(pattern, fd);
4b: 83 ec 08 sub $0x8,%esp
4e: 89 45 e4 mov %eax,-0x1c(%ebp)
for(i = 2; i < argc; i++){
51: 83 c6 01 add $0x1,%esi
grep(pattern, fd);
54: 50 push %eax
55: ff 75 e0 pushl -0x20(%ebp)
58: 83 c3 04 add $0x4,%ebx
5b: e8 d0 01 00 00 call 230 <grep>
close(fd);
60: 8b 45 e4 mov -0x1c(%ebp),%eax
63: 89 04 24 mov %eax,(%esp)
66: e8 3f 05 00 00 call 5aa <close>
for(i = 2; i < argc; i++){
6b: 83 c4 10 add $0x10,%esp
6e: 39 f7 cmp %esi,%edi
70: 7f c6 jg 38 <main+0x38>
}
exit();
72: e8 0b 05 00 00 call 582 <exit>
grep(pattern, 0);
77: 52 push %edx
78: 52 push %edx
79: 6a 00 push $0x0
7b: 50 push %eax
7c: e8 af 01 00 00 call 230 <grep>
exit();
81: e8 fc 04 00 00 call 582 <exit>
printf(1, "grep: cannot open %s\n", argv[i]);
86: 50 push %eax
87: ff 33 pushl (%ebx)
89: 68 58 0a 00 00 push $0xa58
8e: 6a 01 push $0x1
90: e8 4b 06 00 00 call 6e0 <printf>
exit();
95: e8 e8 04 00 00 call 582 <exit>
printf(2, "usage: grep pattern [file ...]\n");
9a: 51 push %ecx
9b: 51 push %ecx
9c: 68 38 0a 00 00 push $0xa38
a1: 6a 02 push $0x2
a3: e8 38 06 00 00 call 6e0 <printf>
exit();
a8: e8 d5 04 00 00 call 582 <exit>
ad: 66 90 xchg %ax,%ax
af: 90 nop
000000b0 <matchstar>:
return 0;
}
// matchstar: search for c*re at beginning of text
int matchstar(int c, char *re, char *text)
{
b0: 55 push %ebp
b1: 89 e5 mov %esp,%ebp
b3: 57 push %edi
b4: 56 push %esi
b5: 53 push %ebx
b6: 83 ec 0c sub $0xc,%esp
b9: 8b 5d 08 mov 0x8(%ebp),%ebx
bc: 8b 75 0c mov 0xc(%ebp),%esi
bf: 8b 7d 10 mov 0x10(%ebp),%edi
c2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
do{ // a * matches zero or more instances
if(matchhere(re, text))
c8: 83 ec 08 sub $0x8,%esp
cb: 57 push %edi
cc: 56 push %esi
cd: e8 3e 00 00 00 call 110 <matchhere>
d2: 83 c4 10 add $0x10,%esp
d5: 85 c0 test %eax,%eax
d7: 75 1f jne f8 <matchstar+0x48>
return 1;
}while(*text!='\0' && (*text++==c || c=='.'));
d9: 0f be 17 movsbl (%edi),%edx
dc: 84 d2 test %dl,%dl
de: 74 0c je ec <matchstar+0x3c>
e0: 83 c7 01 add $0x1,%edi
e3: 39 da cmp %ebx,%edx
e5: 74 e1 je c8 <matchstar+0x18>
e7: 83 fb 2e cmp $0x2e,%ebx
ea: 74 dc je c8 <matchstar+0x18>
return 0;
}
ec: 8d 65 f4 lea -0xc(%ebp),%esp
ef: 5b pop %ebx
f0: 5e pop %esi
f1: 5f pop %edi
f2: 5d pop %ebp
f3: c3 ret
f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
f8: 8d 65 f4 lea -0xc(%ebp),%esp
return 1;
fb: b8 01 00 00 00 mov $0x1,%eax
}
100: 5b pop %ebx
101: 5e pop %esi
102: 5f pop %edi
103: 5d pop %ebp
104: c3 ret
105: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
109: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000110 <matchhere>:
{
110: 55 push %ebp
111: 89 e5 mov %esp,%ebp
113: 57 push %edi
114: 56 push %esi
115: 53 push %ebx
116: 83 ec 0c sub $0xc,%esp
if(re[0] == '\0')
119: 8b 45 08 mov 0x8(%ebp),%eax
{
11c: 8b 7d 0c mov 0xc(%ebp),%edi
if(re[0] == '\0')
11f: 0f b6 08 movzbl (%eax),%ecx
122: 84 c9 test %cl,%cl
124: 74 67 je 18d <matchhere+0x7d>
if(re[1] == '*')
126: 0f be 40 01 movsbl 0x1(%eax),%eax
12a: 3c 2a cmp $0x2a,%al
12c: 74 6c je 19a <matchhere+0x8a>
if(re[0] == '$' && re[1] == '\0')
12e: 80 f9 24 cmp $0x24,%cl
131: 0f b6 1f movzbl (%edi),%ebx
134: 75 08 jne 13e <matchhere+0x2e>
136: 84 c0 test %al,%al
138: 0f 84 81 00 00 00 je 1bf <matchhere+0xaf>
if(*text!='\0' && (re[0]=='.' || re[0]==*text))
13e: 84 db test %bl,%bl
140: 74 09 je 14b <matchhere+0x3b>
142: 38 d9 cmp %bl,%cl
144: 74 3c je 182 <matchhere+0x72>
146: 80 f9 2e cmp $0x2e,%cl
149: 74 37 je 182 <matchhere+0x72>
}
14b: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
14e: 31 c0 xor %eax,%eax
}
150: 5b pop %ebx
151: 5e pop %esi
152: 5f pop %edi
153: 5d pop %ebp
154: c3 ret
155: 8d 76 00 lea 0x0(%esi),%esi
if(re[1] == '*')
158: 8b 75 08 mov 0x8(%ebp),%esi
15b: 0f b6 4e 01 movzbl 0x1(%esi),%ecx
15f: 80 f9 2a cmp $0x2a,%cl
162: 74 3b je 19f <matchhere+0x8f>
if(re[0] == '$' && re[1] == '\0')
164: 3c 24 cmp $0x24,%al
166: 75 04 jne 16c <matchhere+0x5c>
168: 84 c9 test %cl,%cl
16a: 74 4f je 1bb <matchhere+0xab>
if(*text!='\0' && (re[0]=='.' || re[0]==*text))
16c: 0f b6 33 movzbl (%ebx),%esi
16f: 89 f2 mov %esi,%edx
171: 84 d2 test %dl,%dl
173: 74 d6 je 14b <matchhere+0x3b>
175: 3c 2e cmp $0x2e,%al
177: 89 df mov %ebx,%edi
179: 74 04 je 17f <matchhere+0x6f>
17b: 38 c2 cmp %al,%dl
17d: 75 cc jne 14b <matchhere+0x3b>
17f: 0f be c1 movsbl %cl,%eax
return matchhere(re+1, text+1);
182: 83 45 08 01 addl $0x1,0x8(%ebp)
if(re[0] == '\0')
186: 84 c0 test %al,%al
return matchhere(re+1, text+1);
188: 8d 5f 01 lea 0x1(%edi),%ebx
if(re[0] == '\0')
18b: 75 cb jne 158 <matchhere+0x48>
return 1;
18d: b8 01 00 00 00 mov $0x1,%eax
}
192: 8d 65 f4 lea -0xc(%ebp),%esp
195: 5b pop %ebx
196: 5e pop %esi
197: 5f pop %edi
198: 5d pop %ebp
199: c3 ret
if(re[1] == '*')
19a: 89 fb mov %edi,%ebx
19c: 0f be c1 movsbl %cl,%eax
return matchstar(re[0], re+2, text);
19f: 8b 7d 08 mov 0x8(%ebp),%edi
1a2: 83 ec 04 sub $0x4,%esp
1a5: 53 push %ebx
1a6: 8d 57 02 lea 0x2(%edi),%edx
1a9: 52 push %edx
1aa: 50 push %eax
1ab: e8 00 ff ff ff call b0 <matchstar>
1b0: 83 c4 10 add $0x10,%esp
}
1b3: 8d 65 f4 lea -0xc(%ebp),%esp
1b6: 5b pop %ebx
1b7: 5e pop %esi
1b8: 5f pop %edi
1b9: 5d pop %ebp
1ba: c3 ret
1bb: 0f b6 5f 01 movzbl 0x1(%edi),%ebx
return *text == '\0';
1bf: 31 c0 xor %eax,%eax
1c1: 84 db test %bl,%bl
1c3: 0f 94 c0 sete %al
1c6: eb ca jmp 192 <matchhere+0x82>
1c8: 90 nop
1c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000001d0 <match>:
{
1d0: 55 push %ebp
1d1: 89 e5 mov %esp,%ebp
1d3: 56 push %esi
1d4: 53 push %ebx
1d5: 8b 75 08 mov 0x8(%ebp),%esi
1d8: 8b 5d 0c mov 0xc(%ebp),%ebx
if(re[0] == '^')
1db: 80 3e 5e cmpb $0x5e,(%esi)
1de: 75 11 jne 1f1 <match+0x21>
1e0: eb 2e jmp 210 <match+0x40>
1e2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
}while(*text++ != '\0');
1e8: 83 c3 01 add $0x1,%ebx
1eb: 80 7b ff 00 cmpb $0x0,-0x1(%ebx)
1ef: 74 16 je 207 <match+0x37>
if(matchhere(re, text))
1f1: 83 ec 08 sub $0x8,%esp
1f4: 53 push %ebx
1f5: 56 push %esi
1f6: e8 15 ff ff ff call 110 <matchhere>
1fb: 83 c4 10 add $0x10,%esp
1fe: 85 c0 test %eax,%eax
200: 74 e6 je 1e8 <match+0x18>
return 1;
202: b8 01 00 00 00 mov $0x1,%eax
}
207: 8d 65 f8 lea -0x8(%ebp),%esp
20a: 5b pop %ebx
20b: 5e pop %esi
20c: 5d pop %ebp
20d: c3 ret
20e: 66 90 xchg %ax,%ax
return matchhere(re+1, text);
210: 83 c6 01 add $0x1,%esi
213: 89 75 08 mov %esi,0x8(%ebp)
}
216: 8d 65 f8 lea -0x8(%ebp),%esp
219: 5b pop %ebx
21a: 5e pop %esi
21b: 5d pop %ebp
return matchhere(re+1, text);
21c: e9 ef fe ff ff jmp 110 <matchhere>
221: eb 0d jmp 230 <grep>
223: 90 nop
224: 90 nop
225: 90 nop
226: 90 nop
227: 90 nop
228: 90 nop
229: 90 nop
22a: 90 nop
22b: 90 nop
22c: 90 nop
22d: 90 nop
22e: 90 nop
22f: 90 nop
00000230 <grep>:
{
230: 55 push %ebp
231: 89 e5 mov %esp,%ebp
233: 57 push %edi
234: 56 push %esi
235: 53 push %ebx
m = 0;
236: 31 f6 xor %esi,%esi
{
238: 83 ec 1c sub $0x1c,%esp
23b: 90 nop
23c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
while((n = read(fd, buf+m, sizeof(buf)-m-1)) > 0){
240: b8 ff 03 00 00 mov $0x3ff,%eax
245: 83 ec 04 sub $0x4,%esp
248: 29 f0 sub %esi,%eax
24a: 50 push %eax
24b: 8d 86 40 0e 00 00 lea 0xe40(%esi),%eax
251: 50 push %eax
252: ff 75 0c pushl 0xc(%ebp)
255: e8 40 03 00 00 call 59a <read>
25a: 83 c4 10 add $0x10,%esp
25d: 85 c0 test %eax,%eax
25f: 0f 8e bb 00 00 00 jle 320 <grep+0xf0>
m += n;
265: 01 c6 add %eax,%esi
p = buf;
267: bb 40 0e 00 00 mov $0xe40,%ebx
buf[m] = '\0';
26c: c6 86 40 0e 00 00 00 movb $0x0,0xe40(%esi)
273: 89 75 e4 mov %esi,-0x1c(%ebp)
276: 8d 76 00 lea 0x0(%esi),%esi
279: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
while((q = strchr(p, '\n')) != 0){
280: 83 ec 08 sub $0x8,%esp
283: 6a 0a push $0xa
285: 53 push %ebx
286: e8 75 01 00 00 call 400 <strchr>
28b: 83 c4 10 add $0x10,%esp
28e: 85 c0 test %eax,%eax
290: 89 c6 mov %eax,%esi
292: 74 44 je 2d8 <grep+0xa8>
if(match(pattern, p)){
294: 83 ec 08 sub $0x8,%esp
*q = 0;
297: c6 06 00 movb $0x0,(%esi)
29a: 8d 7e 01 lea 0x1(%esi),%edi
if(match(pattern, p)){
29d: 53 push %ebx
29e: ff 75 08 pushl 0x8(%ebp)
2a1: e8 2a ff ff ff call 1d0 <match>
2a6: 83 c4 10 add $0x10,%esp
2a9: 85 c0 test %eax,%eax
2ab: 75 0b jne 2b8 <grep+0x88>
p = q+1;
2ad: 89 fb mov %edi,%ebx
2af: eb cf jmp 280 <grep+0x50>
2b1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
write(1, p, q+1 - p);
2b8: 89 f8 mov %edi,%eax
2ba: 83 ec 04 sub $0x4,%esp
*q = '\n';
2bd: c6 06 0a movb $0xa,(%esi)
write(1, p, q+1 - p);
2c0: 29 d8 sub %ebx,%eax
2c2: 50 push %eax
2c3: 53 push %ebx
p = q+1;
2c4: 89 fb mov %edi,%ebx
write(1, p, q+1 - p);
2c6: 6a 01 push $0x1
2c8: e8 d5 02 00 00 call 5a2 <write>
2cd: 83 c4 10 add $0x10,%esp
2d0: eb ae jmp 280 <grep+0x50>
2d2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p == buf)
2d8: 81 fb 40 0e 00 00 cmp $0xe40,%ebx
2de: 8b 75 e4 mov -0x1c(%ebp),%esi
2e1: 74 2d je 310 <grep+0xe0>
if(m > 0){
2e3: 85 f6 test %esi,%esi
2e5: 0f 8e 55 ff ff ff jle 240 <grep+0x10>
m -= p - buf;
2eb: 89 d8 mov %ebx,%eax
memmove(buf, p, m);
2ed: 83 ec 04 sub $0x4,%esp
m -= p - buf;
2f0: 2d 40 0e 00 00 sub $0xe40,%eax
2f5: 29 c6 sub %eax,%esi
memmove(buf, p, m);
2f7: 56 push %esi
2f8: 53 push %ebx
2f9: 68 40 0e 00 00 push $0xe40
2fe: e8 4d 02 00 00 call 550 <memmove>
303: 83 c4 10 add $0x10,%esp
306: e9 35 ff ff ff jmp 240 <grep+0x10>
30b: 90 nop
30c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
m = 0;
310: 31 f6 xor %esi,%esi
312: e9 29 ff ff ff jmp 240 <grep+0x10>
317: 89 f6 mov %esi,%esi
319: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
}
320: 8d 65 f4 lea -0xc(%ebp),%esp
323: 5b pop %ebx
324: 5e pop %esi
325: 5f pop %edi
326: 5d pop %ebp
327: c3 ret
328: 66 90 xchg %ax,%ax
32a: 66 90 xchg %ax,%ax
32c: 66 90 xchg %ax,%ax
32e: 66 90 xchg %ax,%ax
00000330 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
330: 55 push %ebp
331: 89 e5 mov %esp,%ebp
333: 53 push %ebx
334: 8b 45 08 mov 0x8(%ebp),%eax
337: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
33a: 89 c2 mov %eax,%edx
33c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
340: 83 c1 01 add $0x1,%ecx
343: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
347: 83 c2 01 add $0x1,%edx
34a: 84 db test %bl,%bl
34c: 88 5a ff mov %bl,-0x1(%edx)
34f: 75 ef jne 340 <strcpy+0x10>
;
return os;
}
351: 5b pop %ebx
352: 5d pop %ebp
353: c3 ret
354: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
35a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000360 <strcmp>:
int
strcmp(const char *p, const char *q)
{
360: 55 push %ebp
361: 89 e5 mov %esp,%ebp
363: 53 push %ebx
364: 8b 55 08 mov 0x8(%ebp),%edx
367: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
36a: 0f b6 02 movzbl (%edx),%eax
36d: 0f b6 19 movzbl (%ecx),%ebx
370: 84 c0 test %al,%al
372: 75 1c jne 390 <strcmp+0x30>
374: eb 2a jmp 3a0 <strcmp+0x40>
376: 8d 76 00 lea 0x0(%esi),%esi
379: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
380: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
383: 0f b6 02 movzbl (%edx),%eax
p++, q++;
386: 83 c1 01 add $0x1,%ecx
389: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
38c: 84 c0 test %al,%al
38e: 74 10 je 3a0 <strcmp+0x40>
390: 38 d8 cmp %bl,%al
392: 74 ec je 380 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
394: 29 d8 sub %ebx,%eax
}
396: 5b pop %ebx
397: 5d pop %ebp
398: c3 ret
399: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
3a0: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
3a2: 29 d8 sub %ebx,%eax
}
3a4: 5b pop %ebx
3a5: 5d pop %ebp
3a6: c3 ret
3a7: 89 f6 mov %esi,%esi
3a9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000003b0 <strlen>:
uint
strlen(char *s)
{
3b0: 55 push %ebp
3b1: 89 e5 mov %esp,%ebp
3b3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
3b6: 80 39 00 cmpb $0x0,(%ecx)
3b9: 74 15 je 3d0 <strlen+0x20>
3bb: 31 d2 xor %edx,%edx
3bd: 8d 76 00 lea 0x0(%esi),%esi
3c0: 83 c2 01 add $0x1,%edx
3c3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
3c7: 89 d0 mov %edx,%eax
3c9: 75 f5 jne 3c0 <strlen+0x10>
;
return n;
}
3cb: 5d pop %ebp
3cc: c3 ret
3cd: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
3d0: 31 c0 xor %eax,%eax
}
3d2: 5d pop %ebp
3d3: c3 ret
3d4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
3da: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000003e0 <memset>:
void*
memset(void *dst, int c, uint n)
{
3e0: 55 push %ebp
3e1: 89 e5 mov %esp,%ebp
3e3: 57 push %edi
3e4: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
3e7: 8b 4d 10 mov 0x10(%ebp),%ecx
3ea: 8b 45 0c mov 0xc(%ebp),%eax
3ed: 89 d7 mov %edx,%edi
3ef: fc cld
3f0: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
3f2: 89 d0 mov %edx,%eax
3f4: 5f pop %edi
3f5: 5d pop %ebp
3f6: c3 ret
3f7: 89 f6 mov %esi,%esi
3f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000400 <strchr>:
char*
strchr(const char *s, char c)
{
400: 55 push %ebp
401: 89 e5 mov %esp,%ebp
403: 53 push %ebx
404: 8b 45 08 mov 0x8(%ebp),%eax
407: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
40a: 0f b6 10 movzbl (%eax),%edx
40d: 84 d2 test %dl,%dl
40f: 74 1d je 42e <strchr+0x2e>
if(*s == c)
411: 38 d3 cmp %dl,%bl
413: 89 d9 mov %ebx,%ecx
415: 75 0d jne 424 <strchr+0x24>
417: eb 17 jmp 430 <strchr+0x30>
419: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
420: 38 ca cmp %cl,%dl
422: 74 0c je 430 <strchr+0x30>
for(; *s; s++)
424: 83 c0 01 add $0x1,%eax
427: 0f b6 10 movzbl (%eax),%edx
42a: 84 d2 test %dl,%dl
42c: 75 f2 jne 420 <strchr+0x20>
return (char*)s;
return 0;
42e: 31 c0 xor %eax,%eax
}
430: 5b pop %ebx
431: 5d pop %ebp
432: c3 ret
433: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
439: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000440 <gets>:
char*
gets(char *buf, int max)
{
440: 55 push %ebp
441: 89 e5 mov %esp,%ebp
443: 57 push %edi
444: 56 push %esi
445: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
446: 31 f6 xor %esi,%esi
448: 89 f3 mov %esi,%ebx
{
44a: 83 ec 1c sub $0x1c,%esp
44d: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
450: eb 2f jmp 481 <gets+0x41>
452: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
458: 8d 45 e7 lea -0x19(%ebp),%eax
45b: 83 ec 04 sub $0x4,%esp
45e: 6a 01 push $0x1
460: 50 push %eax
461: 6a 00 push $0x0
463: e8 32 01 00 00 call 59a <read>
if(cc < 1)
468: 83 c4 10 add $0x10,%esp
46b: 85 c0 test %eax,%eax
46d: 7e 1c jle 48b <gets+0x4b>
break;
buf[i++] = c;
46f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
473: 83 c7 01 add $0x1,%edi
476: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
479: 3c 0a cmp $0xa,%al
47b: 74 23 je 4a0 <gets+0x60>
47d: 3c 0d cmp $0xd,%al
47f: 74 1f je 4a0 <gets+0x60>
for(i=0; i+1 < max; ){
481: 83 c3 01 add $0x1,%ebx
484: 3b 5d 0c cmp 0xc(%ebp),%ebx
487: 89 fe mov %edi,%esi
489: 7c cd jl 458 <gets+0x18>
48b: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
48d: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
490: c6 03 00 movb $0x0,(%ebx)
}
493: 8d 65 f4 lea -0xc(%ebp),%esp
496: 5b pop %ebx
497: 5e pop %esi
498: 5f pop %edi
499: 5d pop %ebp
49a: c3 ret
49b: 90 nop
49c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
4a0: 8b 75 08 mov 0x8(%ebp),%esi
4a3: 8b 45 08 mov 0x8(%ebp),%eax
4a6: 01 de add %ebx,%esi
4a8: 89 f3 mov %esi,%ebx
buf[i] = '\0';
4aa: c6 03 00 movb $0x0,(%ebx)
}
4ad: 8d 65 f4 lea -0xc(%ebp),%esp
4b0: 5b pop %ebx
4b1: 5e pop %esi
4b2: 5f pop %edi
4b3: 5d pop %ebp
4b4: c3 ret
4b5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
4b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000004c0 <stat>:
int
stat(char *n, struct stat *st)
{
4c0: 55 push %ebp
4c1: 89 e5 mov %esp,%ebp
4c3: 56 push %esi
4c4: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
4c5: 83 ec 08 sub $0x8,%esp
4c8: 6a 00 push $0x0
4ca: ff 75 08 pushl 0x8(%ebp)
4cd: e8 f0 00 00 00 call 5c2 <open>
if(fd < 0)
4d2: 83 c4 10 add $0x10,%esp
4d5: 85 c0 test %eax,%eax
4d7: 78 27 js 500 <stat+0x40>
return -1;
r = fstat(fd, st);
4d9: 83 ec 08 sub $0x8,%esp
4dc: ff 75 0c pushl 0xc(%ebp)
4df: 89 c3 mov %eax,%ebx
4e1: 50 push %eax
4e2: e8 f3 00 00 00 call 5da <fstat>
close(fd);
4e7: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
4ea: 89 c6 mov %eax,%esi
close(fd);
4ec: e8 b9 00 00 00 call 5aa <close>
return r;
4f1: 83 c4 10 add $0x10,%esp
}
4f4: 8d 65 f8 lea -0x8(%ebp),%esp
4f7: 89 f0 mov %esi,%eax
4f9: 5b pop %ebx
4fa: 5e pop %esi
4fb: 5d pop %ebp
4fc: c3 ret
4fd: 8d 76 00 lea 0x0(%esi),%esi
return -1;
500: be ff ff ff ff mov $0xffffffff,%esi
505: eb ed jmp 4f4 <stat+0x34>
507: 89 f6 mov %esi,%esi
509: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000510 <atoi>:
int
atoi(const char *s)
{
510: 55 push %ebp
511: 89 e5 mov %esp,%ebp
513: 53 push %ebx
514: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
517: 0f be 11 movsbl (%ecx),%edx
51a: 8d 42 d0 lea -0x30(%edx),%eax
51d: 3c 09 cmp $0x9,%al
n = 0;
51f: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
524: 77 1f ja 545 <atoi+0x35>
526: 8d 76 00 lea 0x0(%esi),%esi
529: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
530: 8d 04 80 lea (%eax,%eax,4),%eax
533: 83 c1 01 add $0x1,%ecx
536: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
53a: 0f be 11 movsbl (%ecx),%edx
53d: 8d 5a d0 lea -0x30(%edx),%ebx
540: 80 fb 09 cmp $0x9,%bl
543: 76 eb jbe 530 <atoi+0x20>
return n;
}
545: 5b pop %ebx
546: 5d pop %ebp
547: c3 ret
548: 90 nop
549: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000550 <memmove>:
void*
memmove(void *vdst, void *vsrc, int n)
{
550: 55 push %ebp
551: 89 e5 mov %esp,%ebp
553: 56 push %esi
554: 53 push %ebx
555: 8b 5d 10 mov 0x10(%ebp),%ebx
558: 8b 45 08 mov 0x8(%ebp),%eax
55b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
55e: 85 db test %ebx,%ebx
560: 7e 14 jle 576 <memmove+0x26>
562: 31 d2 xor %edx,%edx
564: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
568: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
56c: 88 0c 10 mov %cl,(%eax,%edx,1)
56f: 83 c2 01 add $0x1,%edx
while(n-- > 0)
572: 39 d3 cmp %edx,%ebx
574: 75 f2 jne 568 <memmove+0x18>
return vdst;
}
576: 5b pop %ebx
577: 5e pop %esi
578: 5d pop %ebp
579: c3 ret
0000057a <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
57a: b8 01 00 00 00 mov $0x1,%eax
57f: cd 40 int $0x40
581: c3 ret
00000582 <exit>:
SYSCALL(exit)
582: b8 02 00 00 00 mov $0x2,%eax
587: cd 40 int $0x40
589: c3 ret
0000058a <wait>:
SYSCALL(wait)
58a: b8 03 00 00 00 mov $0x3,%eax
58f: cd 40 int $0x40
591: c3 ret
00000592 <pipe>:
SYSCALL(pipe)
592: b8 04 00 00 00 mov $0x4,%eax
597: cd 40 int $0x40
599: c3 ret
0000059a <read>:
SYSCALL(read)
59a: b8 05 00 00 00 mov $0x5,%eax
59f: cd 40 int $0x40
5a1: c3 ret
000005a2 <write>:
SYSCALL(write)
5a2: b8 10 00 00 00 mov $0x10,%eax
5a7: cd 40 int $0x40
5a9: c3 ret
000005aa <close>:
SYSCALL(close)
5aa: b8 15 00 00 00 mov $0x15,%eax
5af: cd 40 int $0x40
5b1: c3 ret
000005b2 <kill>:
SYSCALL(kill)
5b2: b8 06 00 00 00 mov $0x6,%eax
5b7: cd 40 int $0x40
5b9: c3 ret
000005ba <exec>:
SYSCALL(exec)
5ba: b8 07 00 00 00 mov $0x7,%eax
5bf: cd 40 int $0x40
5c1: c3 ret
000005c2 <open>:
SYSCALL(open)
5c2: b8 0f 00 00 00 mov $0xf,%eax
5c7: cd 40 int $0x40
5c9: c3 ret
000005ca <mknod>:
SYSCALL(mknod)
5ca: b8 11 00 00 00 mov $0x11,%eax
5cf: cd 40 int $0x40
5d1: c3 ret
000005d2 <unlink>:
SYSCALL(unlink)
5d2: b8 12 00 00 00 mov $0x12,%eax
5d7: cd 40 int $0x40
5d9: c3 ret
000005da <fstat>:
SYSCALL(fstat)
5da: b8 08 00 00 00 mov $0x8,%eax
5df: cd 40 int $0x40
5e1: c3 ret
000005e2 <link>:
SYSCALL(link)
5e2: b8 13 00 00 00 mov $0x13,%eax
5e7: cd 40 int $0x40
5e9: c3 ret
000005ea <mkdir>:
SYSCALL(mkdir)
5ea: b8 14 00 00 00 mov $0x14,%eax
5ef: cd 40 int $0x40
5f1: c3 ret
000005f2 <chdir>:
SYSCALL(chdir)
5f2: b8 09 00 00 00 mov $0x9,%eax
5f7: cd 40 int $0x40
5f9: c3 ret
000005fa <dup>:
SYSCALL(dup)
5fa: b8 0a 00 00 00 mov $0xa,%eax
5ff: cd 40 int $0x40
601: c3 ret
00000602 <getpid>:
SYSCALL(getpid)
602: b8 0b 00 00 00 mov $0xb,%eax
607: cd 40 int $0x40
609: c3 ret
0000060a <sbrk>:
SYSCALL(sbrk)
60a: b8 0c 00 00 00 mov $0xc,%eax
60f: cd 40 int $0x40
611: c3 ret
00000612 <sleep>:
SYSCALL(sleep)
612: b8 0d 00 00 00 mov $0xd,%eax
617: cd 40 int $0x40
619: c3 ret
0000061a <uptime>:
SYSCALL(uptime)
61a: b8 0e 00 00 00 mov $0xe,%eax
61f: cd 40 int $0x40
621: c3 ret
00000622 <cps>:
SYSCALL(cps)
622: b8 16 00 00 00 mov $0x16,%eax
627: cd 40 int $0x40
629: c3 ret
0000062a <chpr>:
SYSCALL(chpr)
62a: b8 17 00 00 00 mov $0x17,%eax
62f: cd 40 int $0x40
631: c3 ret
00000632 <getppid>:
SYSCALL(getppid)
632: b8 18 00 00 00 mov $0x18,%eax
637: cd 40 int $0x40
639: c3 ret
63a: 66 90 xchg %ax,%ax
63c: 66 90 xchg %ax,%ax
63e: 66 90 xchg %ax,%ax
00000640 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
640: 55 push %ebp
641: 89 e5 mov %esp,%ebp
643: 57 push %edi
644: 56 push %esi
645: 53 push %ebx
646: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
649: 85 d2 test %edx,%edx
{
64b: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
64e: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
650: 79 76 jns 6c8 <printint+0x88>
652: f6 45 08 01 testb $0x1,0x8(%ebp)
656: 74 70 je 6c8 <printint+0x88>
x = -xx;
658: f7 d8 neg %eax
neg = 1;
65a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
661: 31 f6 xor %esi,%esi
663: 8d 5d d7 lea -0x29(%ebp),%ebx
666: eb 0a jmp 672 <printint+0x32>
668: 90 nop
669: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
670: 89 fe mov %edi,%esi
672: 31 d2 xor %edx,%edx
674: 8d 7e 01 lea 0x1(%esi),%edi
677: f7 f1 div %ecx
679: 0f b6 92 78 0a 00 00 movzbl 0xa78(%edx),%edx
}while((x /= base) != 0);
680: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
682: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
685: 75 e9 jne 670 <printint+0x30>
if(neg)
687: 8b 45 c4 mov -0x3c(%ebp),%eax
68a: 85 c0 test %eax,%eax
68c: 74 08 je 696 <printint+0x56>
buf[i++] = '-';
68e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
693: 8d 7e 02 lea 0x2(%esi),%edi
696: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
69a: 8b 7d c0 mov -0x40(%ebp),%edi
69d: 8d 76 00 lea 0x0(%esi),%esi
6a0: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
6a3: 83 ec 04 sub $0x4,%esp
6a6: 83 ee 01 sub $0x1,%esi
6a9: 6a 01 push $0x1
6ab: 53 push %ebx
6ac: 57 push %edi
6ad: 88 45 d7 mov %al,-0x29(%ebp)
6b0: e8 ed fe ff ff call 5a2 <write>
while(--i >= 0)
6b5: 83 c4 10 add $0x10,%esp
6b8: 39 de cmp %ebx,%esi
6ba: 75 e4 jne 6a0 <printint+0x60>
putc(fd, buf[i]);
}
6bc: 8d 65 f4 lea -0xc(%ebp),%esp
6bf: 5b pop %ebx
6c0: 5e pop %esi
6c1: 5f pop %edi
6c2: 5d pop %ebp
6c3: c3 ret
6c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
6c8: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
6cf: eb 90 jmp 661 <printint+0x21>
6d1: eb 0d jmp 6e0 <printf>
6d3: 90 nop
6d4: 90 nop
6d5: 90 nop
6d6: 90 nop
6d7: 90 nop
6d8: 90 nop
6d9: 90 nop
6da: 90 nop
6db: 90 nop
6dc: 90 nop
6dd: 90 nop
6de: 90 nop
6df: 90 nop
000006e0 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
6e0: 55 push %ebp
6e1: 89 e5 mov %esp,%ebp
6e3: 57 push %edi
6e4: 56 push %esi
6e5: 53 push %ebx
6e6: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
6e9: 8b 75 0c mov 0xc(%ebp),%esi
6ec: 0f b6 1e movzbl (%esi),%ebx
6ef: 84 db test %bl,%bl
6f1: 0f 84 b3 00 00 00 je 7aa <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
6f7: 8d 45 10 lea 0x10(%ebp),%eax
6fa: 83 c6 01 add $0x1,%esi
state = 0;
6fd: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
6ff: 89 45 d4 mov %eax,-0x2c(%ebp)
702: eb 2f jmp 733 <printf+0x53>
704: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
708: 83 f8 25 cmp $0x25,%eax
70b: 0f 84 a7 00 00 00 je 7b8 <printf+0xd8>
write(fd, &c, 1);
711: 8d 45 e2 lea -0x1e(%ebp),%eax
714: 83 ec 04 sub $0x4,%esp
717: 88 5d e2 mov %bl,-0x1e(%ebp)
71a: 6a 01 push $0x1
71c: 50 push %eax
71d: ff 75 08 pushl 0x8(%ebp)
720: e8 7d fe ff ff call 5a2 <write>
725: 83 c4 10 add $0x10,%esp
728: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
72b: 0f b6 5e ff movzbl -0x1(%esi),%ebx
72f: 84 db test %bl,%bl
731: 74 77 je 7aa <printf+0xca>
if(state == 0){
733: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
735: 0f be cb movsbl %bl,%ecx
738: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
73b: 74 cb je 708 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
73d: 83 ff 25 cmp $0x25,%edi
740: 75 e6 jne 728 <printf+0x48>
if(c == 'd'){
742: 83 f8 64 cmp $0x64,%eax
745: 0f 84 05 01 00 00 je 850 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
74b: 81 e1 f7 00 00 00 and $0xf7,%ecx
751: 83 f9 70 cmp $0x70,%ecx
754: 74 72 je 7c8 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
756: 83 f8 73 cmp $0x73,%eax
759: 0f 84 99 00 00 00 je 7f8 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
75f: 83 f8 63 cmp $0x63,%eax
762: 0f 84 08 01 00 00 je 870 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
768: 83 f8 25 cmp $0x25,%eax
76b: 0f 84 ef 00 00 00 je 860 <printf+0x180>
write(fd, &c, 1);
771: 8d 45 e7 lea -0x19(%ebp),%eax
774: 83 ec 04 sub $0x4,%esp
777: c6 45 e7 25 movb $0x25,-0x19(%ebp)
77b: 6a 01 push $0x1
77d: 50 push %eax
77e: ff 75 08 pushl 0x8(%ebp)
781: e8 1c fe ff ff call 5a2 <write>
786: 83 c4 0c add $0xc,%esp
789: 8d 45 e6 lea -0x1a(%ebp),%eax
78c: 88 5d e6 mov %bl,-0x1a(%ebp)
78f: 6a 01 push $0x1
791: 50 push %eax
792: ff 75 08 pushl 0x8(%ebp)
795: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
798: 31 ff xor %edi,%edi
write(fd, &c, 1);
79a: e8 03 fe ff ff call 5a2 <write>
for(i = 0; fmt[i]; i++){
79f: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
7a3: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
7a6: 84 db test %bl,%bl
7a8: 75 89 jne 733 <printf+0x53>
}
}
}
7aa: 8d 65 f4 lea -0xc(%ebp),%esp
7ad: 5b pop %ebx
7ae: 5e pop %esi
7af: 5f pop %edi
7b0: 5d pop %ebp
7b1: c3 ret
7b2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
7b8: bf 25 00 00 00 mov $0x25,%edi
7bd: e9 66 ff ff ff jmp 728 <printf+0x48>
7c2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
7c8: 83 ec 0c sub $0xc,%esp
7cb: b9 10 00 00 00 mov $0x10,%ecx
7d0: 6a 00 push $0x0
7d2: 8b 7d d4 mov -0x2c(%ebp),%edi
7d5: 8b 45 08 mov 0x8(%ebp),%eax
7d8: 8b 17 mov (%edi),%edx
7da: e8 61 fe ff ff call 640 <printint>
ap++;
7df: 89 f8 mov %edi,%eax
7e1: 83 c4 10 add $0x10,%esp
state = 0;
7e4: 31 ff xor %edi,%edi
ap++;
7e6: 83 c0 04 add $0x4,%eax
7e9: 89 45 d4 mov %eax,-0x2c(%ebp)
7ec: e9 37 ff ff ff jmp 728 <printf+0x48>
7f1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
7f8: 8b 45 d4 mov -0x2c(%ebp),%eax
7fb: 8b 08 mov (%eax),%ecx
ap++;
7fd: 83 c0 04 add $0x4,%eax
800: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
803: 85 c9 test %ecx,%ecx
805: 0f 84 8e 00 00 00 je 899 <printf+0x1b9>
while(*s != 0){
80b: 0f b6 01 movzbl (%ecx),%eax
state = 0;
80e: 31 ff xor %edi,%edi
s = (char*)*ap;
810: 89 cb mov %ecx,%ebx
while(*s != 0){
812: 84 c0 test %al,%al
814: 0f 84 0e ff ff ff je 728 <printf+0x48>
81a: 89 75 d0 mov %esi,-0x30(%ebp)
81d: 89 de mov %ebx,%esi
81f: 8b 5d 08 mov 0x8(%ebp),%ebx
822: 8d 7d e3 lea -0x1d(%ebp),%edi
825: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
828: 83 ec 04 sub $0x4,%esp
s++;
82b: 83 c6 01 add $0x1,%esi
82e: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
831: 6a 01 push $0x1
833: 57 push %edi
834: 53 push %ebx
835: e8 68 fd ff ff call 5a2 <write>
while(*s != 0){
83a: 0f b6 06 movzbl (%esi),%eax
83d: 83 c4 10 add $0x10,%esp
840: 84 c0 test %al,%al
842: 75 e4 jne 828 <printf+0x148>
844: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
847: 31 ff xor %edi,%edi
849: e9 da fe ff ff jmp 728 <printf+0x48>
84e: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
850: 83 ec 0c sub $0xc,%esp
853: b9 0a 00 00 00 mov $0xa,%ecx
858: 6a 01 push $0x1
85a: e9 73 ff ff ff jmp 7d2 <printf+0xf2>
85f: 90 nop
write(fd, &c, 1);
860: 83 ec 04 sub $0x4,%esp
863: 88 5d e5 mov %bl,-0x1b(%ebp)
866: 8d 45 e5 lea -0x1b(%ebp),%eax
869: 6a 01 push $0x1
86b: e9 21 ff ff ff jmp 791 <printf+0xb1>
putc(fd, *ap);
870: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
873: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
876: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
878: 6a 01 push $0x1
ap++;
87a: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
87d: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
880: 8d 45 e4 lea -0x1c(%ebp),%eax
883: 50 push %eax
884: ff 75 08 pushl 0x8(%ebp)
887: e8 16 fd ff ff call 5a2 <write>
ap++;
88c: 89 7d d4 mov %edi,-0x2c(%ebp)
88f: 83 c4 10 add $0x10,%esp
state = 0;
892: 31 ff xor %edi,%edi
894: e9 8f fe ff ff jmp 728 <printf+0x48>
s = "(null)";
899: bb 6e 0a 00 00 mov $0xa6e,%ebx
while(*s != 0){
89e: b8 28 00 00 00 mov $0x28,%eax
8a3: e9 72 ff ff ff jmp 81a <printf+0x13a>
8a8: 66 90 xchg %ax,%ax
8aa: 66 90 xchg %ax,%ax
8ac: 66 90 xchg %ax,%ax
8ae: 66 90 xchg %ax,%ax
000008b0 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
8b0: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
8b1: a1 20 0e 00 00 mov 0xe20,%eax
{
8b6: 89 e5 mov %esp,%ebp
8b8: 57 push %edi
8b9: 56 push %esi
8ba: 53 push %ebx
8bb: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
8be: 8d 4b f8 lea -0x8(%ebx),%ecx
8c1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
8c8: 39 c8 cmp %ecx,%eax
8ca: 8b 10 mov (%eax),%edx
8cc: 73 32 jae 900 <free+0x50>
8ce: 39 d1 cmp %edx,%ecx
8d0: 72 04 jb 8d6 <free+0x26>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
8d2: 39 d0 cmp %edx,%eax
8d4: 72 32 jb 908 <free+0x58>
break;
if(bp + bp->s.size == p->s.ptr){
8d6: 8b 73 fc mov -0x4(%ebx),%esi
8d9: 8d 3c f1 lea (%ecx,%esi,8),%edi
8dc: 39 fa cmp %edi,%edx
8de: 74 30 je 910 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
8e0: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
8e3: 8b 50 04 mov 0x4(%eax),%edx
8e6: 8d 34 d0 lea (%eax,%edx,8),%esi
8e9: 39 f1 cmp %esi,%ecx
8eb: 74 3a je 927 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
8ed: 89 08 mov %ecx,(%eax)
freep = p;
8ef: a3 20 0e 00 00 mov %eax,0xe20
}
8f4: 5b pop %ebx
8f5: 5e pop %esi
8f6: 5f pop %edi
8f7: 5d pop %ebp
8f8: c3 ret
8f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
900: 39 d0 cmp %edx,%eax
902: 72 04 jb 908 <free+0x58>
904: 39 d1 cmp %edx,%ecx
906: 72 ce jb 8d6 <free+0x26>
{
908: 89 d0 mov %edx,%eax
90a: eb bc jmp 8c8 <free+0x18>
90c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
910: 03 72 04 add 0x4(%edx),%esi
913: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
916: 8b 10 mov (%eax),%edx
918: 8b 12 mov (%edx),%edx
91a: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
91d: 8b 50 04 mov 0x4(%eax),%edx
920: 8d 34 d0 lea (%eax,%edx,8),%esi
923: 39 f1 cmp %esi,%ecx
925: 75 c6 jne 8ed <free+0x3d>
p->s.size += bp->s.size;
927: 03 53 fc add -0x4(%ebx),%edx
freep = p;
92a: a3 20 0e 00 00 mov %eax,0xe20
p->s.size += bp->s.size;
92f: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
932: 8b 53 f8 mov -0x8(%ebx),%edx
935: 89 10 mov %edx,(%eax)
}
937: 5b pop %ebx
938: 5e pop %esi
939: 5f pop %edi
93a: 5d pop %ebp
93b: c3 ret
93c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000940 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
940: 55 push %ebp
941: 89 e5 mov %esp,%ebp
943: 57 push %edi
944: 56 push %esi
945: 53 push %ebx
946: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
949: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
94c: 8b 15 20 0e 00 00 mov 0xe20,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
952: 8d 78 07 lea 0x7(%eax),%edi
955: c1 ef 03 shr $0x3,%edi
958: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
95b: 85 d2 test %edx,%edx
95d: 0f 84 9d 00 00 00 je a00 <malloc+0xc0>
963: 8b 02 mov (%edx),%eax
965: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
968: 39 cf cmp %ecx,%edi
96a: 76 6c jbe 9d8 <malloc+0x98>
96c: 81 ff 00 10 00 00 cmp $0x1000,%edi
972: bb 00 10 00 00 mov $0x1000,%ebx
977: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
97a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
981: eb 0e jmp 991 <malloc+0x51>
983: 90 nop
984: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
988: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
98a: 8b 48 04 mov 0x4(%eax),%ecx
98d: 39 f9 cmp %edi,%ecx
98f: 73 47 jae 9d8 <malloc+0x98>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
991: 39 05 20 0e 00 00 cmp %eax,0xe20
997: 89 c2 mov %eax,%edx
999: 75 ed jne 988 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
99b: 83 ec 0c sub $0xc,%esp
99e: 56 push %esi
99f: e8 66 fc ff ff call 60a <sbrk>
if(p == (char*)-1)
9a4: 83 c4 10 add $0x10,%esp
9a7: 83 f8 ff cmp $0xffffffff,%eax
9aa: 74 1c je 9c8 <malloc+0x88>
hp->s.size = nu;
9ac: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
9af: 83 ec 0c sub $0xc,%esp
9b2: 83 c0 08 add $0x8,%eax
9b5: 50 push %eax
9b6: e8 f5 fe ff ff call 8b0 <free>
return freep;
9bb: 8b 15 20 0e 00 00 mov 0xe20,%edx
if((p = morecore(nunits)) == 0)
9c1: 83 c4 10 add $0x10,%esp
9c4: 85 d2 test %edx,%edx
9c6: 75 c0 jne 988 <malloc+0x48>
return 0;
}
}
9c8: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
9cb: 31 c0 xor %eax,%eax
}
9cd: 5b pop %ebx
9ce: 5e pop %esi
9cf: 5f pop %edi
9d0: 5d pop %ebp
9d1: c3 ret
9d2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
9d8: 39 cf cmp %ecx,%edi
9da: 74 54 je a30 <malloc+0xf0>
p->s.size -= nunits;
9dc: 29 f9 sub %edi,%ecx
9de: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
9e1: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
9e4: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
9e7: 89 15 20 0e 00 00 mov %edx,0xe20
}
9ed: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
9f0: 83 c0 08 add $0x8,%eax
}
9f3: 5b pop %ebx
9f4: 5e pop %esi
9f5: 5f pop %edi
9f6: 5d pop %ebp
9f7: c3 ret
9f8: 90 nop
9f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
a00: c7 05 20 0e 00 00 24 movl $0xe24,0xe20
a07: 0e 00 00
a0a: c7 05 24 0e 00 00 24 movl $0xe24,0xe24
a11: 0e 00 00
base.s.size = 0;
a14: b8 24 0e 00 00 mov $0xe24,%eax
a19: c7 05 28 0e 00 00 00 movl $0x0,0xe28
a20: 00 00 00
a23: e9 44 ff ff ff jmp 96c <malloc+0x2c>
a28: 90 nop
a29: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
prevp->s.ptr = p->s.ptr;
a30: 8b 08 mov (%eax),%ecx
a32: 89 0a mov %ecx,(%edx)
a34: eb b1 jmp 9e7 <malloc+0xa7>
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "test_utils/cpu_test_utils.hpp"
#include "ngraph_functions/builders.hpp"
#include "ngraph_functions/utils/ngraph_helpers.hpp"
using namespace InferenceEngine;
using namespace CPUTestUtils;
namespace CPULayerTestsDefinitions {
namespace {
int pooledH;
int pooledW;
float spatialScale;
int samplingRatio;
std::pair<std::vector<float>, std::vector<size_t>> proposal;
std::string mode;
std::vector<size_t> inputShape;
} // namespace
typedef std::tuple<
int, // bin's column count
int, // bin's row count
float, // scale for given region considering actual input size
int, // pooling ratio
std::pair<std::vector<float>, std::vector<size_t>>, // united proposal vector of coordinates and indexes
std::string, // pooling mode
std::vector<size_t> // feature map shape
> ROIAlignSpecificParams;
typedef std::tuple<
ROIAlignSpecificParams,
InferenceEngine::Precision, // Net precision
LayerTestsUtils::TargetDevice // Device name
> ROIAlignLayerTestParams;
typedef std::tuple<
CPULayerTestsDefinitions::ROIAlignLayerTestParams,
CPUSpecificParams> ROIAlignLayerCPUTestParamsSet;
class ROIAlignLayerCPUTest : public testing::WithParamInterface<ROIAlignLayerCPUTestParamsSet>,
virtual public LayerTestsUtils::LayerTestsCommon, public CPUTestsBase {
public:
static std::string getTestCaseName(testing::TestParamInfo<ROIAlignLayerCPUTestParamsSet> obj) {
CPULayerTestsDefinitions::ROIAlignLayerTestParams basicParamsSet;
CPUSpecificParams cpuParams;
std::tie(basicParamsSet, cpuParams) = obj.param;
std::string td;
Precision netPr;
ROIAlignSpecificParams roiPar;
std::tie(roiPar, netPr, td) = basicParamsSet;
std::tie(pooledH, pooledW, spatialScale, samplingRatio,
proposal, mode, inputShape) = roiPar;
std::ostringstream result;
result << "ROIAlignTest_";
result << std::to_string(obj.index);
result << "pooledH=" << pooledH << "_";
result << "pooledW=" << pooledW << "_";
result << "spatialScale=" << spatialScale << "_";
result << "samplingRatio=" << samplingRatio << "_";
result << (netPr == Precision::FP32 ? "FP32" : "BF16") << "_";
result << mode << "_";
result << CPUTestsBase::getTestCaseName(cpuParams);
return result.str();
}
protected:
void SetUp() override {
CPULayerTestsDefinitions::ROIAlignLayerTestParams basicParamsSet;
CPUSpecificParams cpuParams;
std::tie(basicParamsSet, cpuParams) = this->GetParam();
std::tie(inFmts, outFmts, priority, selectedType) = cpuParams;
CPULayerTestsDefinitions::ROIAlignSpecificParams roiAlignParams;
auto netPrecision = InferenceEngine::Precision::UNSPECIFIED;
std::tie(roiAlignParams, netPrecision, targetDevice) = basicParamsSet;
inPrc = outPrc = netPrecision;
std::tie(pooledH, pooledW, spatialScale, samplingRatio,
proposal, mode, inputShape) = roiAlignParams;
std::vector<float> proposalVector = proposal.first;
std::vector<size_t> roiIdxVector = proposal.second;
ngraph::Shape coordsShape = { proposalVector.size() / 4, 4 };
ngraph::Shape idxVectorShape = { roiIdxVector.size() };
auto roisIdx = ngraph::builder::makeConstant<size_t>(ngraph::element::i32, idxVectorShape, roiIdxVector);
auto coords = ngraph::builder::makeConstant<float>(ngraph::element::f32, coordsShape, proposalVector);
auto params = ngraph::builder::makeParams(ngraph::element::f32, {inputShape});
auto roialign = std::make_shared<ngraph::opset3::ROIAlign>(params[0], coords, roisIdx, pooledH, pooledW,
samplingRatio, spatialScale, mode);
roialign->get_rt_info() = getCPUInfo();
selectedType = std::string("unknown_") + inPrc.name();
threshold = 1e-2;
const ngraph::ResultVector results{std::make_shared<ngraph::opset3::Result>(roialign)};
function = std::make_shared<ngraph::Function>(results, params, "ROIAlign");
functionRefs = ngraph::clone_function(*function);
}
};
TEST_P(ROIAlignLayerCPUTest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
Run();
CheckPluginRelatedResults(executableNetwork, "ROIAlign");
}
namespace {
/* CPU PARAMS */
std::vector<CPUSpecificParams> filterCPUInfoForDevice() {
std::vector<CPUSpecificParams> resCPUParams;
resCPUParams.push_back(CPUSpecificParams{{nchw, nc, x}, {nchw}, {}, {}});
resCPUParams.push_back(CPUSpecificParams{{nhwc, nc, x}, {nhwc}, {}, {}});
if (with_cpu_x86_avx512f()) {
resCPUParams.push_back(CPUSpecificParams{{nChw16c, nc, x}, {nChw16c}, {}, {}});
} else if (with_cpu_x86_avx2() || with_cpu_x86_sse42()) {
resCPUParams.push_back(CPUSpecificParams{{nChw8c, nc, x}, {nChw8c}, {}, {}});
}
return resCPUParams;
}
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32,
InferenceEngine::Precision::BF16
};
const std::vector<int> spatialBinXVector = { 2 };
const std::vector<int> spatialBinYVector = { 2 };
const std::vector<float> spatialScaleVector = { 1.0f };
const std::vector<int> poolingRatioVector = { 7 };
const std::vector<std::string> modeVector = {
"avg",
"max"
};
const std::vector<std::vector<size_t>> inputShapeVector = {
SizeVector({ 2, 18, 20, 20 }),
SizeVector({ 2, 4, 20, 20 }),
SizeVector({ 2, 4, 20, 40 }),
SizeVector({ 10, 1, 20, 20 })
};
const std::vector<std::pair<std::vector<float>, std::vector<size_t>>> propVector = {
{{ 1, 1, 19, 19, 1, 1, 19, 19, }, { 0, 1 }},
{{ 1, 1, 19, 19 }, { 1 }}
};
const auto roiAlignParams = ::testing::Combine(
::testing::ValuesIn(spatialBinXVector), // bin's column count
::testing::ValuesIn(spatialBinYVector), // bin's row count
::testing::ValuesIn(spatialScaleVector), // scale for given region considering actual input size
::testing::ValuesIn(poolingRatioVector), // pooling ratio for bin
::testing::ValuesIn(propVector), // united vector of coordinates and batch id's
::testing::ValuesIn(modeVector), // pooling mode
::testing::ValuesIn(inputShapeVector) // feature map shape
);
INSTANTIATE_TEST_SUITE_P(smoke_ROIAlignLayoutTest, ROIAlignLayerCPUTest,
::testing::Combine(
::testing::Combine(
roiAlignParams,
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_CPU)),
::testing::ValuesIn(filterCPUInfoForDevice())),
ROIAlignLayerCPUTest::getTestCaseName);
} // namespace
} // namespace CPULayerTestsDefinitions
|
.global s_prepare_buffers
s_prepare_buffers:
push %r14
push %r15
push %r9
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x17726, %rbp
cmp $27556, %r9
mov (%rbp), %r15w
nop
nop
nop
nop
cmp $39142, %r14
lea addresses_WC_ht+0xc9be, %rsi
lea addresses_WT_ht+0x16826, %rdi
nop
nop
nop
cmp $59017, %rax
mov $27, %rcx
rep movsw
nop
add %rcx, %rcx
lea addresses_UC_ht+0x120a6, %r14
nop
sub $34433, %rax
movb (%r14), %r9b
sub $5261, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r9
pop %r15
pop %r14
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r15
push %r9
push %rax
push %rcx
// Load
lea addresses_normal+0x10b26, %rcx
clflush (%rcx)
nop
nop
nop
nop
nop
add $61128, %r15
mov (%rcx), %r9
add %r15, %r15
// Faulty Load
lea addresses_WT+0x12f26, %rcx
nop
nop
nop
sub $35700, %r15
movups (%rcx), %xmm2
vpextrq $1, %xmm2, %rax
lea oracles, %r11
and $0xff, %rax
shlq $12, %rax
mov (%r11,%rax,1), %rax
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 10, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
; size_t getdelim_unlocked(char **lineptr, size_t *n, int delimiter, FILE *stream)
SECTION code_clib
SECTION code_stdio
PUBLIC getdelim_unlocked_callee
EXTERN asm_getdelim_unlocked
getdelim_unlocked_callee:
pop hl
pop ix
pop bc
pop de
ex (sp),hl
jp asm_getdelim_unlocked
|
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2010 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
// A wrapper for Rappture applications.
// Similar to the standard wrapper except:
//
// - Doesn't contain main(); must be called from a main program
// that parses the Rappture control file
// - parse the app's stdout (in a separate thread);
// look for "progress markers", convert to fraction done
#include <stdio.h>
#include <vector>
#include <string>
#ifdef _WIN32
#include "boinc_win.h"
#include "win_util.h"
#else
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "procinfo.h"
#endif
#include "boinc_api.h"
#include "diagnostics.h"
#include "filesys.h"
#include "parse.h"
#include "str_util.h"
#include "str_replace.h"
#include "util.h"
#include "error_numbers.h"
#include "wrappture.h"
#define POLL_PERIOD 1.0
using std::vector;
using std::string;
struct TASK {
string application;
string stdin_filename;
string stdout_filename;
string stderr_filename;
string checkpoint_filename;
// name of task's checkpoint file, if any
string fraction_done_filename;
// name of file where app will write its fraction done
string command_line;
double weight;
// contribution of this task to overall fraction done
double final_cpu_time;
double starting_cpu;
// how much CPU time was used by tasks before this in the job file
bool suspended;
double wall_cpu_time;
// for estimating CPU time on Win98/ME and Mac
#ifdef _WIN32
HANDLE pid_handle;
DWORD pid;
HANDLE thread_handle;
struct _stat last_stat; // mod time of checkpoint file
#else
int pid;
struct stat last_stat;
#endif
bool stat_first;
bool poll(int& status);
int run(int argc, char** argv);
void kill();
void stop();
void resume();
double cpu_time();
inline bool has_checkpointed() {
bool changed = false;
if (checkpoint_filename.size() == 0) return false;
struct stat new_stat;
int retval = stat(checkpoint_filename.c_str(), &new_stat);
if (retval) return false;
if (!stat_first && new_stat.st_mtime != last_stat.st_mtime) {
changed = true;
}
stat_first = false;
last_stat.st_mtime = new_stat.st_mtime;
return changed;
}
inline double fraction_done() {
if (fraction_done_filename.size() == 0) return 0;
FILE* f = fopen(fraction_done_filename.c_str(), "r");
if (!f) return 0;
double frac;
int n = fscanf(f, "%lf", &frac);
fclose(f);
if (n != 1) return 0;
if (frac < 0) return 0;
if (frac > 1) return 1;
return frac;
}
};
APP_INIT_DATA aid;
double fraction_done, checkpoint_cpu_time;
#ifdef _WIN32
// CreateProcess() takes HANDLEs for the stdin/stdout.
// We need to use CreateFile() to get them. Ugh.
//
HANDLE win_fopen(const char* path, const char* mode) {
SECURITY_ATTRIBUTES sa;
memset(&sa, 0, sizeof(sa));
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
if (!strcmp(mode, "r")) {
return CreateFile(
path,
GENERIC_READ,
FILE_SHARE_READ,
&sa,
OPEN_EXISTING,
0, 0
);
} else if (!strcmp(mode, "w")) {
return CreateFile(
path,
GENERIC_WRITE,
FILE_SHARE_WRITE,
&sa,
OPEN_ALWAYS,
0, 0
);
} else if (!strcmp(mode, "a")) {
HANDLE hAppend = CreateFile(
path,
GENERIC_WRITE,
FILE_SHARE_WRITE,
&sa,
OPEN_ALWAYS,
0, 0
);
SetFilePointer(hAppend, 0, NULL, FILE_END);
return hAppend;
} else {
return 0;
}
}
#endif
void slash_to_backslash(char* p) {
while (1) {
char* q = strchr(p, '/');
if (!q) break;
*q = '\\';
}
}
int TASK::run(int argct, char** argvt) {
string stdout_path, stdin_path, stderr_path;
char app_path[1024], buf[256];
if (checkpoint_filename.size()) {
boinc_delete_file(checkpoint_filename.c_str());
}
if (fraction_done_filename.size()) {
boinc_delete_file(fraction_done_filename.c_str());
}
strcpy(buf, application.c_str());
char* p = strstr(buf, "$PROJECT_DIR");
if (p) {
p += strlen("$PROJECT_DIR");
sprintf(app_path, "%s%s", aid.project_dir, p);
} else {
boinc_resolve_filename(buf, app_path, sizeof(app_path));
}
// Append wrapper's command-line arguments to those in the job file.
//
for (int i=1; i<argct; i++){
command_line += string(" ");
command_line += argvt[i];
}
fprintf(stderr, "%s wrapper: running %s (%s)\n",
boinc_msg_prefix(buf, sizeof(buf)), app_path, command_line.c_str()
);
#ifdef _WIN32
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
string command;
slash_to_backslash(app_path);
memset(&process_info, 0, sizeof(process_info));
memset(&startup_info, 0, sizeof(startup_info));
command = string("\"") + app_path + string("\" ") + command_line;
// pass std handles to app
//
startup_info.dwFlags = STARTF_USESTDHANDLES;
if (stdout_filename != "") {
boinc_resolve_filename_s(stdout_filename.c_str(), stdout_path);
startup_info.hStdOutput = win_fopen(stdout_path.c_str(), "a");
}
if (stdin_filename != "") {
boinc_resolve_filename_s(stdin_filename.c_str(), stdin_path);
startup_info.hStdInput = win_fopen(stdin_path.c_str(), "r");
}
if (stderr_filename != "") {
boinc_resolve_filename_s(stderr_filename.c_str(), stderr_path);
startup_info.hStdError = win_fopen(stderr_path.c_str(), "a");
} else {
startup_info.hStdError = win_fopen(STDERR_FILE, "a");
}
if (!CreateProcess(
app_path,
(LPSTR)command.c_str(),
NULL,
NULL,
TRUE, // bInheritHandles
CREATE_NO_WINDOW|IDLE_PRIORITY_CLASS,
NULL,
NULL,
&startup_info,
&process_info
)) {
char error_msg[1024];
windows_error_string(error_msg, sizeof(error_msg));
fprintf(stderr, "can't run app: %s\n", error_msg);
return ERR_EXEC;
}
pid_handle = process_info.hProcess;
pid = process_info.dwProcessId;
thread_handle = process_info.hThread;
SetThreadPriority(thread_handle, THREAD_PRIORITY_IDLE);
#else
int retval, argc;
char progname[256];
char* argv[256];
char arglist[4096];
FILE* stdout_file;
FILE* stdin_file;
FILE* stderr_file;
pid = fork();
if (pid == -1) {
perror("fork(): ");
return ERR_FORK;
}
if (pid == 0) {
// we're in the child process here
//
// open stdout, stdin if file names are given
// NOTE: if the application is restartable,
// we should deal with atomicity somehow
//
if (stdout_filename != "") {
boinc_resolve_filename_s(stdout_filename.c_str(), stdout_path);
stdout_file = freopen(stdout_path.c_str(), "a", stdout);
if (!stdout_file) return ERR_FOPEN;
}
if (stdin_filename != "") {
boinc_resolve_filename_s(stdin_filename.c_str(), stdin_path);
stdin_file = freopen(stdin_path.c_str(), "r", stdin);
if (!stdin_file) return ERR_FOPEN;
}
if (stderr_filename != "") {
boinc_resolve_filename_s(stderr_filename.c_str(), stderr_path);
stderr_file = freopen(stderr_path.c_str(), "a", stderr);
if (!stderr_file) return ERR_FOPEN;
}
// construct argv
// TODO: use malloc instead of stack var
//
argv[0] = app_path;
strlcpy(arglist, command_line.c_str(), sizeof(arglist));
argc = parse_command_line(arglist, argv+1);
setpriority(PRIO_PROCESS, 0, PROCESS_IDLE_PRIORITY);
retval = execv(app_path, argv);
perror("execv() failed: ");
exit(ERR_EXEC);
}
#endif
wall_cpu_time = 0;
suspended = false;
return 0;
}
bool TASK::poll(int& status) {
if (!suspended) wall_cpu_time += POLL_PERIOD;
#ifdef _WIN32
unsigned long exit_code;
if (GetExitCodeProcess(pid_handle, &exit_code)) {
if (exit_code != STILL_ACTIVE) {
status = exit_code;
final_cpu_time = cpu_time();
return true;
}
}
#else
int wpid, stat;
struct rusage ru;
wpid = wait4(pid, &status, WNOHANG, &ru);
if (wpid) {
final_cpu_time = (float)ru.ru_utime.tv_sec + ((float)ru.ru_utime.tv_usec)/1e+6;
return true;
}
#endif
return false;
}
void TASK::kill() {
#ifdef _WIN32
TerminateProcess(pid_handle, -1);
#else
::kill(pid, SIGKILL);
#endif
}
void TASK::stop() {
#ifdef _WIN32
suspend_or_resume_threads(pid, 0, false);
#else
::kill(pid, SIGSTOP);
#endif
suspended = true;
}
void TASK::resume() {
#ifdef _WIN32
suspend_or_resume_threads(pid, 0, true);
#else
::kill(pid, SIGCONT);
#endif
suspended = false;
}
void poll_boinc_messages(TASK& task) {
BOINC_STATUS status;
boinc_get_status(&status);
if (status.no_heartbeat) {
task.kill();
exit(0);
}
if (status.quit_request) {
task.kill();
exit(0);
}
if (status.abort_request) {
task.kill();
exit(0);
}
if (status.suspended) {
if (!task.suspended) {
task.stop();
}
} else {
if (task.suspended) {
task.resume();
}
}
}
double TASK::cpu_time() {
#ifdef _WIN32
double x;
int retval = boinc_process_cpu_time(pid_handle, x);
if (retval) return wall_cpu_time;
return x;
#elif defined(__APPLE__)
// There's no easy way to get another process's CPU time in Mac OS X
//
return wall_cpu_time;
#else
return linux_cpu_time(pid);
#endif
}
void send_status_message(
TASK& task, double frac_done, double checkpoint_cpu_time
) {
double current_cpu_time = task.starting_cpu + task.cpu_time();
boinc_report_app_status(
current_cpu_time,
checkpoint_cpu_time,
frac_done
);
}
#define PROGRESS_MARKER "=RAPPTURE-PROGRESS=>"
// the following runs in a thread and parses the app's stdout file,
// looking for progress tags
//
#ifdef _WIN32
DWORD WINAPI parse_app_stdout(void*) {
#else
static void block_sigalrm() {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGALRM);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
}
// we create a thread to parse the stdout from the worker app
//
static void* parse_app_stdout(void*) {
block_sigalrm();
#endif
char buf[1024];
FILE* f;
while (1) {
f = boinc_fopen("rappture_stdout.txt", "r");
if (f) break;
boinc_sleep(1.);
}
while (1) {
if (fgets(buf, sizeof(buf), f)) {
if (strstr(buf, PROGRESS_MARKER)) {
fraction_done = atof(buf+strlen(PROGRESS_MARKER))/100;
}
} else {
boinc_sleep(1.);
}
}
}
int create_parser_thread() {
#ifdef _WIN32
DWORD parser_thread_id;
if (!CreateThread(NULL, 0, parse_app_stdout, 0, 0, &parser_thread_id)) {
return ERR_THREAD;
}
#else
pthread_t parser_thread_handle;
pthread_attr_t thread_attrs;
pthread_attr_init(&thread_attrs);
pthread_attr_setstacksize(&thread_attrs, 16384);
int retval = pthread_create(
&parser_thread_handle, &thread_attrs, parse_app_stdout, NULL
);
if (retval) {
return ERR_THREAD;
}
#endif
return 0;
}
int boinc_run_rappture_app(const char* program, const char* cmdline) {
TASK task;
int retval;
BOINC_OPTIONS options;
memset(&options, 0, sizeof(options));
options.main_program = true;
options.check_heartbeat = true;
options.handle_process_control = true;
boinc_init_options(&options);
task.application = program;
task.command_line = cmdline;
task.stdout_filename = "rappture_stdout.txt";
retval = task.run(0, 0);
create_parser_thread();
while (1) {
int status;
if (task.poll(status)) {
if (status) {
boinc_finish(EXIT_CHILD_FAILED);
}
break;
}
poll_boinc_messages(task);
send_status_message(task, fraction_done, checkpoint_cpu_time);
boinc_sleep(POLL_PERIOD);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.