text stringlengths 1 1.05M |
|---|
; A170939: 4^n-2^n+2.
; 2,4,14,58,242,994,4034,16258,65282,261634,1047554,4192258,16773122,67100674,268419074,1073709058,4294901762,17179738114,68719214594,274877382658,1099510579202,4398044413954,17592181850114,70368735789058,281474959933442,1125899873288194
mov $1,2
pow $1,$0
bin $1,2
mul $1,2
add $1,2
mov $0,$1
|
// Copyright (c) 2011-2019 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 <qt/carpinchoamountfield.h>
#include <qt/carpinchounits.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/qvaluecombobox.h>
#include <QApplication>
#include <QAbstractSpinBox>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
/** QSpinBox that uses fixed-point numbers internally and uses our own
* formatting/parsing functions.
*/
class AmountSpinBox: public QAbstractSpinBox
{
Q_OBJECT
public:
explicit AmountSpinBox(QWidget *parent):
QAbstractSpinBox(parent)
{
setAlignment(Qt::AlignRight);
connect(lineEdit(), &QLineEdit::textEdited, this, &AmountSpinBox::valueChanged);
}
QValidator::State validate(QString &text, int &pos) const override
{
if(text.isEmpty())
return QValidator::Intermediate;
bool valid = false;
parse(text, &valid);
/* Make sure we return Intermediate so that fixup() is called on defocus */
return valid ? QValidator::Intermediate : QValidator::Invalid;
}
void fixup(QString &input) const override
{
bool valid;
CAmount val;
if (input.isEmpty() && !m_allow_empty) {
valid = true;
val = m_min_amount;
} else {
valid = false;
val = parse(input, &valid);
}
if (valid) {
val = qBound(m_min_amount, val, m_max_amount);
input = CARPINCHOUnits::format(currentUnit, val, false, CARPINCHOUnits::SeparatorStyle::ALWAYS);
lineEdit()->setText(input);
}
}
CAmount value(bool *valid_out=nullptr) const
{
return parse(text(), valid_out);
}
void setValue(const CAmount& value)
{
lineEdit()->setText(CARPINCHOUnits::format(currentUnit, value, false, CARPINCHOUnits::SeparatorStyle::ALWAYS));
Q_EMIT valueChanged();
}
void SetAllowEmpty(bool allow)
{
m_allow_empty = allow;
}
void SetMinValue(const CAmount& value)
{
m_min_amount = value;
}
void SetMaxValue(const CAmount& value)
{
m_max_amount = value;
}
void stepBy(int steps) override
{
bool valid = false;
CAmount val = value(&valid);
val = val + steps * singleStep;
val = qBound(m_min_amount, val, m_max_amount);
setValue(val);
}
void setDisplayUnit(int unit)
{
bool valid = false;
CAmount val = value(&valid);
currentUnit = unit;
lineEdit()->setPlaceholderText(CARPINCHOUnits::format(currentUnit, m_min_amount, false, CARPINCHOUnits::SeparatorStyle::ALWAYS));
if(valid)
setValue(val);
else
clear();
}
void setSingleStep(const CAmount& step)
{
singleStep = step;
}
QSize minimumSizeHint() const override
{
if(cachedMinimumSizeHint.isEmpty())
{
ensurePolished();
const QFontMetrics fm(fontMetrics());
int h = lineEdit()->minimumSizeHint().height();
int w = GUIUtil::TextWidth(fm, CARPINCHOUnits::format(CARPINCHOUnits::CHO, CARPINCHOUnits::maxMoney(), false, CARPINCHOUnits::SeparatorStyle::ALWAYS));
w += 2; // cursor blinking space
QStyleOptionSpinBox opt;
initStyleOption(&opt);
QSize hint(w, h);
QSize extra(35, 6);
opt.rect.setSize(hint + extra);
extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
QStyle::SC_SpinBoxEditField, this).size();
// get closer to final result by repeating the calculation
opt.rect.setSize(hint + extra);
extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
QStyle::SC_SpinBoxEditField, this).size();
hint += extra;
hint.setHeight(h);
opt.rect = rect();
cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
.expandedTo(QApplication::globalStrut());
}
return cachedMinimumSizeHint;
}
private:
int currentUnit{CARPINCHOUnits::CHO};
CAmount singleStep{CAmount(100000)}; // satoshis
mutable QSize cachedMinimumSizeHint;
bool m_allow_empty{true};
CAmount m_min_amount{CAmount(0)};
CAmount m_max_amount{CARPINCHOUnits::maxMoney()};
/**
* Parse a string into a number of base monetary units and
* return validity.
* @note Must return 0 if !valid.
*/
CAmount parse(const QString &text, bool *valid_out=nullptr) const
{
CAmount val = 0;
bool valid = CARPINCHOUnits::parse(currentUnit, text, &val);
if(valid)
{
if(val < 0 || val > CARPINCHOUnits::maxMoney())
valid = false;
}
if(valid_out)
*valid_out = valid;
return valid ? val : 0;
}
protected:
bool event(QEvent *event) override
{
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Comma)
{
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
return QAbstractSpinBox::event(&periodKeyEvent);
}
}
return QAbstractSpinBox::event(event);
}
StepEnabled stepEnabled() const override
{
if (isReadOnly()) // Disable steps when AmountSpinBox is read-only
return StepNone;
if (text().isEmpty()) // Allow step-up with empty field
return StepUpEnabled;
StepEnabled rv = StepNone;
bool valid = false;
CAmount val = value(&valid);
if (valid) {
if (val > m_min_amount)
rv |= StepDownEnabled;
if (val < m_max_amount)
rv |= StepUpEnabled;
}
return rv;
}
Q_SIGNALS:
void valueChanged();
};
#include <qt/carpinchoamountfield.moc>
CARPINCHOAmountField::CARPINCHOAmountField(QWidget *parent) :
QWidget(parent),
amount(nullptr)
{
amount = new AmountSpinBox(this);
amount->setLocale(QLocale::c());
amount->installEventFilter(this);
amount->setMaximumWidth(240);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new CARPINCHOUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, &AmountSpinBox::valueChanged, this, &CARPINCHOAmountField::valueChanged);
connect(unit, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &CARPINCHOAmountField::unitChanged);
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void CARPINCHOAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
void CARPINCHOAmountField::setEnabled(bool fEnabled)
{
amount->setEnabled(fEnabled);
unit->setEnabled(fEnabled);
}
bool CARPINCHOAmountField::validate()
{
bool valid = false;
value(&valid);
setValid(valid);
return valid;
}
void CARPINCHOAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
bool CARPINCHOAmountField::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// Clear invalid flag on focus
setValid(true);
}
return QWidget::eventFilter(object, event);
}
QWidget *CARPINCHOAmountField::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, amount);
QWidget::setTabOrder(amount, unit);
return unit;
}
CAmount CARPINCHOAmountField::value(bool *valid_out) const
{
return amount->value(valid_out);
}
void CARPINCHOAmountField::setValue(const CAmount& value)
{
amount->setValue(value);
}
void CARPINCHOAmountField::SetAllowEmpty(bool allow)
{
amount->SetAllowEmpty(allow);
}
void CARPINCHOAmountField::SetMinValue(const CAmount& value)
{
amount->SetMinValue(value);
}
void CARPINCHOAmountField::SetMaxValue(const CAmount& value)
{
amount->SetMaxValue(value);
}
void CARPINCHOAmountField::setReadOnly(bool fReadOnly)
{
amount->setReadOnly(fReadOnly);
}
void CARPINCHOAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, CARPINCHOUnits::UnitRole).toInt();
amount->setDisplayUnit(newUnit);
}
void CARPINCHOAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
void CARPINCHOAmountField::setSingleStep(const CAmount& step)
{
amount->setSingleStep(step);
}
|
; A000932: a(n) = a(n-1) + n*a(n-2); a(0) = a(1) = 1.
; 1,1,3,6,18,48,156,492,1740,6168,23568,91416,374232,1562640,6801888,30241488,139071696,653176992,3156467520,15566830368,78696180768,405599618496,2136915595392,11465706820800,62751681110208,349394351630208,1980938060495616
add $0,1
mov $2,2
mov $3,1
lpb $0
mul $3,$2
mov $2,$1
add $1,$3
mov $3,$0
sub $0,1
lpe
div $1,2
|
#include "Defines.h"
#include "Game.h"
#include "FixedMath.h"
#include "Draw.h"
const char map[MAP_WIDTH * MAP_HEIGHT] PROGMEM =
{
0,0,0,0,0,0,0,0,0,0,8,8,8,8,8,8,
0,3,2,2,2,2,2,2,4,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,1,0,0,3,2,2,4,0,
0,1,0,8,8,8,8,0,6,2,2,5,0,0,1,0,
0,1,0,0,0,8,8,0,0,0,0,0,0,0,1,0,
0,6,2,4,0,8,8,8,8,8,8,8,8,0,1,0,
0,0,0,1,0,8,8,8,0,0,0,0,0,0,1,0,
8,8,0,7,0,8,8,8,0,3,2,2,2,2,5,0,
8,8,0,1,0,8,8,8,0,1,0,0,0,0,0,0,
8,8,0,1,0,8,8,8,0,6,2,2,2,4,0,8,
8,8,0,1,0,8,8,8,0,0,0,0,0,1,0,8,
8,8,0,1,0,8,8,8,8,8,8,8,0,1,0,8,
8,8,0,1,0,8,8,8,8,0,0,0,0,1,0,8,
8,8,0,1,0,0,0,0,0,0,3,2,2,5,0,8,
8,8,0,6,2,2,2,2,2,2,5,0,0,0,0,8,
8,8,0,0,0,0,0,0,0,0,0,0,8,8,8,8,
};
const uint8_t aiMap[] PROGMEM =
{
2,3,3,3,3,3,3,3,3,3,8,8,8,8,8,8,
2,2,2,2,2,2,2,2,3,4,2,3,3,3,3,4,
2,1,1,1,1,1,1,2,3,3,2,2,2,2,3,4,
2,1,4,8,8,8,8,2,2,2,2,1,1,2,3,4,
2,1,4,4,4,8,8,2,1,1,1,1,1,2,3,4,
2,1,4,4,4,8,8,8,8,8,8,8,8,2,3,4,
2,1,1,1,4,8,8,8,3,3,3,3,3,3,3,4,
8,8,2,1,4,8,8,8,2,3,4,4,4,4,4,4,
8,8,2,1,4,8,8,8,2,3,3,3,3,3,3,3,
8,8,2,1,4,8,8,8,2,2,2,2,2,3,4,8,
8,8,2,1,4,8,8,8,2,1,1,1,2,3,4,8,
8,8,2,1,4,8,8,8,8,8,8,8,2,3,4,8,
8,8,2,1,4,8,8,8,8,3,3,3,3,3,4,8,
8,8,2,1,4,3,3,3,3,3,3,4,4,4,4,8,
8,8,2,1,4,4,4,4,4,4,4,4,1,1,4,8,
8,8,1,1,1,1,1,1,1,1,1,1,8,8,8,8,
};
#define MAX_PROGRESS_VALUE 61
const uint8_t progressMap[] PROGMEM =
{
8, 8, 9,10,11,12,13,14,15,15,99,99,99,99,99,99,
8, 8, 9,10,11,12,13,14,15,15,21,21,22,23,24,24,
7, 7, 7,10,11,12,13,14,16,18,21,21,22,23,24,24,
6, 6, 6,99,99,99,99,17,17,18,19,20,20,25,25,25,
5, 5, 3, 2, 2,99,99,17,17,18,19,20,20,26,26,26,
4, 4, 3, 2, 2,99,99,99,99,99,99,99,99,27,27,27,
4, 4, 1, 1, 1,99,99,99,34,34,33,32,31,30,28,28,
99,99, 0, 0, 0,99,99,99,34,34,33,32,31,30,29,29,
99,99,61,61,61,99,99,99,35,35,37,38,39,40,29,29,
99,99,60,60,60,99,99,99,36,36,37,38,39,40,40,99,
99,99,59,59,59,99,99,99,36,36,37,38,39,41,41,99,
99,99,58,58,58,99,99,99,99,99,99,99,42,42,42,99,
99,99,57,57,57,99,99,99,99,47,47,46,45,43,43,99,
99,99,56,56,56,53,52,51,50,49,47,46,45,44,44,99,
99,99,55,55,54,53,52,51,50,49,48,46,45,44,44,99,
99,99,55,55,54,53,52,51,50,49,48,46,99,99,99,99,
};
Player players[NUM_PLAYERS];
uint8_t playerPositions[NUM_PLAYERS];
GameState gameState = GameState::Title;
uint8_t gameTimer = 0;
// For rubber banding
const uint8_t maxRoadSpeeds[NUM_PLAYERS] PROGMEM =
{
MAX_ROAD_SPEED - 0,
MAX_ROAD_SPEED + 10,
MAX_ROAD_SPEED + 15,
MAX_ROAD_SPEED + 20
};
void UpdatePlayers(void);
void SetStartPositions(void);
char GetMap(uint8_t x, uint8_t y)
{
if (x < MAP_WIDTH && y < MAP_HEIGHT)
{
return pgm_read_byte(&map[y * MAP_WIDTH + x]);
}
return 8;
}
void SetStartPositions()
{
int row = 0;
int col = 0;
for (int n = 0; n < NUM_PLAYERS; n++)
{
Player* player = &players[n];
player->oldX = player->x = START_X * FIXED_ONE + (FIXED_ONE / 4) + col * (FIXED_ONE / 2);
player->oldZ = player->z = START_Z * FIXED_ONE + (FIXED_ONE / 4) - row * (FIXED_ONE / 2);
player->angle = FIXED_ANGLE_90 * 2;
player->lap = 1;
player->lapProgress = 0;
player->endingRank = -1;
player->steering = player->acceleration = player->speed = player->turnVelocity = player->rank = player->frame = 0;
col++;
if (col == 2)
{
col = 0;
row++;
}
}
}
void InitGame()
{
SetStartPositions();
ShowMessage(MessageType::None);
}
void UpdateLocalPlayer()
{
uint8_t input = GetInput();
int8_t steering = 0;
if (input & INPUT_LEFT)
steering--;
if (input & INPUT_RIGHT)
steering++;
players[0].steering = steering;
players[0].acceleration = (input & INPUT_B) ? 1 : 0;
}
void TickGame()
{
gameTimer++;
switch (gameState)
{
case GameState::Title:
{
DrawTitle();
if (GetInput() & (INPUT_A | INPUT_B))
{
InitGame();
gameTimer = 0;
gameState = GameState::Begin;
}
return;
}
break;
case GameState::Begin:
{
if (gameTimer < 20)
{
SetLED(0, 0, 0);
}
else if (gameTimer < 40)
{
SetLED(1, 0, 0);
ShowMessage(MessageType::Ready);
}
else if (gameTimer < 60)
{
SetLED(1, 1, 0);
ShowMessage(MessageType::Set);
}
else
{
SetLED(0, 1, 0);
gameState = GameState::Play;
ShowMessage(MessageType::Go);
}
}
break;
case GameState::Play:
if (gameTimer > 80)
{
SetLED(0, 0, 0);
}
UpdateLocalPlayer();
UpdatePlayers();
break;
case GameState::Finished:
{
UpdatePlayers();
switch (players[0].endingRank)
{
case 0:
ShowMessage(MessageType::FirstPlace);
break;
case 1:
ShowMessage(MessageType::SecondPlace);
break;
case 2:
ShowMessage(MessageType::ThirdPlace);
break;
case 3:
ShowMessage(MessageType::FourthPlace);
break;
}
gameTimer++;
if (gameTimer > 200)
{
gameState = GameState::Title;
}
}
break;
}
Render();
}
bool IsBlocked(int16_t x, int16_t z)
{
uint8_t cellX = (uint8_t)(x >> FIXED_SHIFT);
uint8_t cellZ = (uint8_t)(z >> FIXED_SHIFT);
if (cellX < MAP_WIDTH && cellZ < MAP_HEIGHT)
{
uint8_t cell = pgm_read_byte(&map[cellZ * MAP_WIDTH + cellX]);
return cell == 8;
}
return true;
}
void UpdatePlayers()
{
for (int n = 0; n < NUM_PLAYERS; n++)
{
Player* player = &players[n];
uint8_t cellX = (uint8_t)(player->x >> FIXED_SHIFT);
uint8_t cellZ = (uint8_t)(player->z >> FIXED_SHIFT);
uint8_t lapProgress = pgm_read_byte(&progressMap[cellZ * MAP_WIDTH + cellX]);
if (lapProgress != player->lapProgress)
{
if (lapProgress == 0 && player->lapProgress == MAX_PROGRESS_VALUE)
{
player->lap++;
if (n == 0)
{
if (player->lap == 2)
{
ShowMessage(MessageType::Lap2);
}
else if (player->lap == 3)
{
ShowMessage(MessageType::Lap3);
}
else if (player->lap == 4)
{
gameState = GameState::Finished;
gameTimer = 0;
}
}
if (player->lap == 4 && player->endingRank == -1)
{
int8_t endingRank = -1;
for (int x = 0; x < NUM_PLAYERS; x++)
{
if (players[x].endingRank > endingRank)
{
endingRank = players[x].endingRank;
}
}
player->endingRank = endingRank + 1;
}
}
else if (player->lapProgress == 0 && lapProgress == MAX_PROGRESS_VALUE && player->lap > 0)
{
player->lap--;
}
player->lapProgress = lapProgress;
}
// AI
if (n > 0 || gameState == GameState::Finished)
{
uint8_t fwdCellX = (uint8_t)((player->x + FixedSin(player->angle) / 3) >> FIXED_SHIFT);
uint8_t fwdCellZ = (uint8_t)((player->z + FixedCos(player->angle) / 3) >> FIXED_SHIFT);
uint8_t aiCell = pgm_read_byte(&aiMap[fwdCellZ * MAP_WIDTH + fwdCellX]);
uint8_t intendedAngle = player->angle;
switch (aiCell)
{
case 3:
intendedAngle = 0;
break;
case 2:
intendedAngle = FIXED_ANGLE_90;
break;
case 1:
intendedAngle = FIXED_ANGLE_90 * 2;
break;
case 4:
intendedAngle = FIXED_ANGLE_90 * 3;
break;
}
int16_t angleDiff = intendedAngle - player->angle;
if (angleDiff > FIXED_ANGLE_90 * 2)
{
angleDiff -= FIXED_ANGLE_MAX;
}
if (angleDiff < FIXED_ANGLE_90 * -2)
{
angleDiff += FIXED_ANGLE_MAX;
}
if (angleDiff < -5)
{
player->steering = -1;
}
else if (angleDiff > 5)
{
player->steering = 1;
}
else
{
player->steering = 0;
}
//player->acceleration = (angleDiff > -32 && angleDiff < 32) ? 1 : 0;
player->acceleration = (angleDiff > -48 && angleDiff < 48) ? 1 : 0;
}
if (player->steering == 0)
{
if (player->turnVelocity > 0)
{
player->turnVelocity--;
}
else if (player->turnVelocity < 0)
{
player->turnVelocity++;
}
}
else if (player->steering < 0)
{
if (player->turnVelocity > -MAX_TURN_VELOCITY)
{
player->turnVelocity--;
}
}
else if (player->steering > 0)
{
if (player->turnVelocity < MAX_TURN_VELOCITY)
{
player->turnVelocity++;
}
}
uint8_t cell = map[cellZ * MAP_WIDTH + cellX];
player->angle = FIXED_ANGLE_WRAP(player->angle + player->turnVelocity);
int maxSpeed = cell == 0 ? MAX_SIDE_SPEED : (player->steering ? MAX_STEERING_SPEED : pgm_read_byte(&maxRoadSpeeds[player->rank]));
if (player->acceleration > 0)
{
uint8_t frameDelta = player->speed >> 4;
if (frameDelta == 0)
frameDelta = 1;
player->frame += frameDelta;
if (player->speed < maxSpeed)
{
player->speed++;
}
else
{
player->speed--;
}
}
else if (player->speed > 0)
{
player->speed--;
}
//int16_t velX = player->x - player->oldX;
//int16_t velZ = player->z - player->oldZ;
player->oldX = player->x;
player->oldZ = player->z;
//velX = (velX * 240) / 256;
//velZ = (velZ * 240) / 256;
player->x += (FixedSin(player->angle) * player->speed) >> 10;
player->z += (FixedCos(player->angle) * player->speed) >> 10;
}
for (int n = 0; n < NUM_PLAYERS; n++)
{
Player* player = &players[n];
for (int i = n + 1; i < NUM_PLAYERS; i++)
{
Player* other = &players[i];
int16_t diffX = player->x - other->x;
int16_t diffZ = player->z - other->z;
if (diffX < 0) diffX = -diffX;
if (diffZ < 0) diffZ = -diffZ;
if (diffX < PLAYER_SIZE && diffZ < PLAYER_SIZE)
{
if (diffX > diffZ)
{
int16_t centerX = (player->x + other->x) >> 1;
if (player->oldX < other->oldX)
{
player->x = centerX - PLAYER_SIZE;
other->x = centerX + PLAYER_SIZE;
}
else
{
player->x = centerX + PLAYER_SIZE;
other->x = centerX - PLAYER_SIZE;
}
}
else
{
int16_t centerZ = (player->z + other->z) >> 1;
if (player->oldZ < other->oldZ)
{
player->z = centerZ - PLAYER_SIZE;
other->z = centerZ + PLAYER_SIZE;
}
else
{
player->z = centerZ + PLAYER_SIZE;
other->z = centerZ - PLAYER_SIZE;
}
}
}
}
}
for (int n = 0; n < NUM_PLAYERS; n++)
{
Player* player = &players[n];
if (player->x < player->oldX)
{
if (IsBlocked(player->x - PLAYER_SIZE, player->z))
{
player->x = ((player->x - PLAYER_SIZE) & 0xff00) + FIXED_ONE + PLAYER_SIZE;
}
}
else if (player->x > player->oldX)
{
if (IsBlocked(player->x + PLAYER_SIZE, player->z))
{
player->x = ((player->x + PLAYER_SIZE) & 0xff00) - PLAYER_SIZE;
}
}
if (player->z < player->oldZ)
{
if (IsBlocked(player->x, player->z - PLAYER_SIZE))
{
player->z = ((player->z - PLAYER_SIZE) & 0xff00) + FIXED_ONE + PLAYER_SIZE;
}
}
else if (player->z > player->oldZ)
{
if (IsBlocked(player->x, player->z + PLAYER_SIZE))
{
player->z = ((player->z + PLAYER_SIZE) & 0xff00) - PLAYER_SIZE;
}
}
}
for (int p = 0; p < NUM_PLAYERS; p++)
{
bool foundPosition = false;
for (int n = 0; n < p && !foundPosition; n++)
{
if (players[p].lap >= players[playerPositions[n]].lap && players[p].lapProgress > players[playerPositions[n]].lapProgress)
{
for (int i = p; i > n; i--)
{
playerPositions[i] = playerPositions[i - 1];
}
playerPositions[n] = p;
foundPosition = true;
}
}
if (!foundPosition)
{
playerPositions[p] = p;
}
}
for (int n = 0; n < NUM_PLAYERS; n++)
{
players[playerPositions[n]].rank = n;
}
}
/*
void UpdatePlayers()
{
for (int n = 0; n < NUM_PLAYERS; n++)
{
Player* player = &players[n];
if (player->steering == 0)
{
if (player->turnVelocity > 0)
{
player->turnVelocity--;
}
else if (player->turnVelocity < 0)
{
player->turnVelocity++;
}
}
else if (player->steering < 0)
{
if (player->turnVelocity > -MAX_TURN_VELOCITY)
{
player->turnVelocity--;
}
}
else if (player->steering > 0)
{
if (player->turnVelocity < MAX_TURN_VELOCITY)
{
player->turnVelocity++;
}
}
uint8_t cellX = (uint8_t)(player->x >> FIXED_SHIFT);
uint8_t cellZ = (uint8_t)(player->z >> FIXED_SHIFT);
uint8_t cell = map[cellZ * MAP_WIDTH + cellX];
player->angle = FIXED_ANGLE_WRAP(player->angle + player->turnVelocity);
int maxSpeed = cell == 0 ? MAX_SIDE_SPEED : MAX_ROAD_SPEED;
if (player->acceleration > 0)
{
if (player->speed < maxSpeed)
{
player->speed++;
}
else
{
player->speed--;
}
}
else if (player->speed > 0)
{
player->speed--;
}
//int16_t velX = player->x - player->oldX;
//int16_t velZ = player->z - player->oldZ;
player->oldX = player->x;
player->oldZ = player->z;
//velX = (velX * 240) / 256;
//velZ = (velZ * 240) / 256;
player->x += (FixedSin(player->angle) * player->speed) >> 10;
player->z += (FixedCos(player->angle) * player->speed) >> 10;
}
}
*/
|
/*
This program is supposed to be used with the IntallerCollection_***.cs
examples. Provide the exe of this program as input to the
InstallerCollection_***.exe programs.
*/
#using <System.dll>
#using <System.Configuration.Install.dll>
using namespace System;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Configuration::Install;
[RunInstaller(true)]
ref class MyInstaller: public Installer
{
public:
virtual void Install( IDictionary^ savedState ) override
{
Installer::Install( savedState );
Console::WriteLine( "Install ...\n" );
}
virtual void Commit( IDictionary^ savedState ) override
{
Installer::Commit( savedState );
Console::WriteLine( "Committing ...\n" );
}
virtual void Rollback( IDictionary^ savedState ) override
{
Installer::Rollback( savedState );
Console::WriteLine( "RollBack ...\n" );
}
virtual void Uninstall( IDictionary^ savedState ) override
{
Installer::Uninstall( savedState );
Console::WriteLine( "UnInstall ...\n" );
}
};
void main()
{
Console::WriteLine( "This assembly is just an example for the Installer\n" );
}
|
; void *p_forward_list_front(p_forward_list_t *list)
SECTION code_adt_p_forward_list
PUBLIC _p_forward_list_front
EXTERN asm_p_forward_list_front
_p_forward_list_front:
pop af
pop hl
push hl
push af
jp asm_p_forward_list_front
|
; A017354: a(n) = (10*n + 7)^2.
; 49,289,729,1369,2209,3249,4489,5929,7569,9409,11449,13689,16129,18769,21609,24649,27889,31329,34969,38809,42849,47089,51529,56169,61009,66049,71289,76729,82369,88209,94249,100489,106929,113569,120409,127449,134689,142129,149769,157609,165649,173889,182329,190969,199809,208849,218089,227529,237169,247009,257049,267289,277729,288369,299209,310249,321489,332929,344569,356409,368449,380689,393129,405769,418609,431649,444889,458329,471969,485809,499849,514089,528529,543169,558009,573049,588289
mul $0,10
add $0,7
pow $0,2
|
; _init.asm
; jump to kinit
[bits 32]
__init:
extern kinit
jmp kinit
nop
nop
nop |
/* Sirikata
* Trace.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* 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 Sirikata 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 <sirikata/oh/Trace.hpp>
#include "Protocol_ObjectTrace.pbj.hpp"
#include "Protocol_PingTrace.pbj.hpp"
#include <sirikata/core/options/Options.hpp>
namespace Sirikata {
#define TRACE_OBJECT_NAME "trace-object"
#define TRACE_PING_NAME "trace-ping"
OptionValue* OHTrace::mLogObject;
OptionValue* OHTrace::mLogPing;
void OHTrace::InitOptions() {
mLogObject = new OptionValue(TRACE_OBJECT_NAME,"false",Sirikata::OptionValueType<bool>(),"Log object trace data");
mLogPing = new OptionValue(TRACE_PING_NAME,"false",Sirikata::OptionValueType<bool>(),"Log object trace data");
InitializeClassOptions::module(SIRIKATA_OPTIONS_MODULE)
.addOption(mLogObject)
.addOption(mLogPing)
;
}
static void fillTimedMotionVector(Sirikata::Trace::ITimedMotionVector tmv, const TimedMotionVector3f& val) {
tmv.set_t(val.time());
tmv.set_position(val.position());
tmv.set_velocity(val.velocity());
}
// Object
CREATE_TRACE_DEF(OHTrace, prox, mLogObject, const Time& t, const UUID& receiver, const UUID& source, bool entered, const TimedMotionVector3f& loc) {
Sirikata::Trace::Object::ProxUpdate pu;
pu.set_t(t);
pu.set_receiver(receiver);
pu.set_source(source);
pu.set_entered(entered);
Sirikata::Trace::ITimedMotionVector pu_loc = pu.mutable_loc();
fillTimedMotionVector(pu_loc, loc);
mTrace->writeRecord(ProximityTag, pu);
}
CREATE_TRACE_DEF(OHTrace, objectConnected, mLogObject, const Time& t, const UUID& source, const ServerID& sid) {
Sirikata::Trace::Object::Connected co;
co.set_t(t);
co.set_source(source);
co.set_server(sid);
mTrace->writeRecord(ObjectConnectedTag, co);
}
CREATE_TRACE_DEF(OHTrace, objectGenLoc, mLogObject, const Time& t, const UUID& source, const TimedMotionVector3f& loc, const BoundingSphere3f& bnds) {
Sirikata::Trace::Object::GeneratedLoc lu;
lu.set_t(t);
lu.set_source(source);
Sirikata::Trace::ITimedMotionVector lu_loc = lu.mutable_loc();
fillTimedMotionVector(lu_loc, loc);
lu.set_bounds(bnds);
mTrace->writeRecord(ObjectGeneratedLocationTag, lu);
}
CREATE_TRACE_DEF(OHTrace, objectLoc, mLogObject, const Time& t, const UUID& receiver, const UUID& source, const TimedMotionVector3f& loc) {
Sirikata::Trace::Object::LocUpdate lu;
lu.set_t(t);
lu.set_receiver(receiver);
lu.set_source(source);
Sirikata::Trace::ITimedMotionVector lu_loc = lu.mutable_loc();
fillTimedMotionVector(lu_loc, loc);
mTrace->writeRecord(ObjectLocationTag, lu);
}
// Ping
CREATE_TRACE_DEF(OHTrace, pingCreated, mLogPing, const Time& t, const UUID&sender, const Time&dst, const UUID& receiver, uint64 id, double distance, uint32 sz) {
Sirikata::Trace::Ping::Created rec;
rec.set_t(t);
rec.set_sender(sender);
rec.set_received(dst);
rec.set_receiver(receiver);
rec.set_ping_id(id);
rec.set_distance(distance);
rec.set_size(sz);
mTrace->writeRecord(ObjectPingCreatedTag, rec);
}
CREATE_TRACE_DEF(OHTrace, ping, mLogPing, const Time& t, const UUID&sender, const Time&dst, const UUID& receiver, uint64 id, double distance, uint64 uid, uint32 sz) {
Sirikata::Trace::Ping::Sent rec;
rec.set_t(t);
rec.set_sender(sender);
rec.set_received(dst);
rec.set_receiver(receiver);
rec.set_ping_id(id);
rec.set_distance(distance);
rec.set_ping_uid(uid);
rec.set_size(sz);
mTrace->writeRecord(ObjectPingTag, rec);
}
CREATE_TRACE_DEF(OHTrace, hitpoint, mLogPing, const Time& t, const UUID&sender, const Time&dst, const UUID& receiver, double sentHP, double recvHP, double distance, double srcRadius, double dstRadius, uint32 sz) {
Sirikata::Trace::Ping::HitPoint rec;
rec.set_t(t);
rec.set_sender(sender);
rec.set_received(dst);
rec.set_receiver(receiver);
rec.set_sent_hp(sentHP);
rec.set_actual_hp(recvHP);
rec.set_distance(distance);
rec.set_sender_radius(srcRadius);
rec.set_receiver_radius(dstRadius);
rec.set_size(sz);
mTrace->writeRecord(ObjectHitPointTag, rec);
}
} // namespace Sirikata
|
#include "VertexBuffer.h"
namespace Woo {
namespace Graphics {
VertexBuffer::VertexBuffer(GLfloat* data, GLsizei count, GLuint componentCount) : m_componentCount(componentCount) {
glGenBuffers(1, &m_bufferID);
glBindBuffer(GL_ARRAY_BUFFER, m_bufferID);
glBufferData(GL_ARRAY_BUFFER, count*sizeof(float), data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
VertexBuffer::~VertexBuffer()
{
glDeleteBuffers(1, &m_bufferID);
}
void VertexBuffer::Bind() const {
glBindBuffer(GL_ARRAY_BUFFER, m_bufferID);
}
void VertexBuffer::UnBind() const {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
GLuint VertexBuffer::GetComponentCount() const
{
return m_componentCount;
}
}
} |
SECTION code_l
PUBLIC l_minu_bc_dehl
EXTERN l_minu_bc_hl
l_minu_bc_dehl:
; return unsigned minimum of bc and dehl
;
; enter : bc = unsigned 16 bit number
; dehl = unsigned 32 bit number
;
; exit : hl = smaller of the two unsigned numbers
; carry set if dehl was smaller, z flag set if equal
;
; uses : af, hl
ld a,d
or e
jp z, l_minu_bc_hl
ld l,c
ld h,b
ret
|
#include "ofMain.h"
#include "ofApp.h"
//========================================================================
int main( ){
ofSetupOpenGL(1050,850,OF_WINDOW); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp(new ofApp());
}
|
; Copyright (C) 2018 FIX94
;
; This software may be modified and distributed under the terms
; of the MIT license. See the LICENSE file for details.
SECTION "HDR",ROM0[$0]
rstbase:
; if any RST lands here, return
ds $FF
reti
entry:
; 100, goto start
nop
jp _start
SECTION "MAIN",ROM0[$150]
_start:
di
; init stack pointer
ld sp, $CFFF
; make sure lcd is off
ldh a, [$FF40]
bit 7, a
jr z, isoff
; not off, wait for vblank
waitVBlank:
ldh a, [$FF44]
cp 145
jr nz, waitVBlank
; turn off lcd
xor a
ldh [$FF40], a
isoff:
; copy in font
ld hl, $8800
ld de, _8800_bin
ld bc, $400
call _memcpy
ld hl, $8E00
ld de, _8E00_bin
ld bc, $200
call _memcpy
; clear font "space" tile
ld hl, $97F0
xor a
bartileloop:
ld [hl+], a
bit 3, h
jr z, bartileloop
; set font color
ld a, $E4
ldh [$FF47], a
; turn on lcd
ld a, $81
ldh [$FF40], a
; copy in RAM code
ld hl, $C000
ld de, standalone_bin
ld bc, (standalone_bin_end-standalone_bin)
call _memcpy
; jump to RAM code
jp $C000
_memcpy:
inc b
inc c
jr _memcpy_chk
_memcpy_loop:
ld a, [de]
inc de
ld [hl+], a
_memcpy_chk:
dec c
jr nz, _memcpy_loop
dec b
jr nz, _memcpy_loop
ret
; font bin to copy into vram
_8800_bin:
INCBIN "8800.bin"
_8E00_bin:
INCBIN "8E00.bin"
; actual dumper code
standalone_bin:
INCBIN "../standalone.bin"
standalone_bin_end:
; label just for size calc
|
%define BE(a) ( ((((a)>>24)&0xFF) << 0) + ((((a)>>16)&0xFF) << 8) + ((((a)>>8)&0xFF) << 16) + ((((a)>>0)&0xFF) << 24) )
ftyp_start:
dd BE(ftyp_end - ftyp_start)
db "ftyp"
db "isom"
dd BE(0x00)
db "mif1"
ftyp_end:
meta_start:
dd BE(meta_end - meta_start)
db "meta"
dd BE(0)
hdlr_start:
dd BE(hdlr_end - hdlr_start)
db "hdlr"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x00 ; pre_defined(32)
db 0x70, 0x69, 0x63, 0x74 ; handler_type(32) ('pict')
db 0x00, 0x00, 0x00, 0x00 ; reserved1(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved2(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved3(32)
db 0x00 ; name(8)
hdlr_end:
pitm_start:
dd BE(pitm_end - pitm_start)
dd "pitm"
db 0x00 ; "version(8)"
db 0x00, 0x00, 0x00 ; "flags(24)"
db 0x00, 0x0A ; "item_ID(16)"
pitm_end:
iinf_start:
dd BE(iinf_end - iinf_start)
db "iinf"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x01 ; entry_count(16)
infe_start:
dd BE(infe_end - infe_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x0A ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x69, 0x6F, 0x76, 0x6C ; item_type(32) ('iovl')
db 0x00 ; item_name(8)
infe_end:
iinf_end:
iloc_start:
dd BE(iloc_end - iloc_start)
dd "iloc"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x04 ; offset_size(4) length_size(4)
db 0x40 ; base_offset_size(4) ('@') reserved1(4) ('@')
db 0x00, 0x01 ; item_count(16)
db 0x00, 0x0A ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
dd BE(mdat_start - ftyp_start + 8) ; base_offset(32)
db 0x00, 0x01 ; extent_count(16)
; extent_offset(0)
db 0x00, 0x00, 0x00, 0x01 ; extent_length(32)
iloc_end:
iprp_start:
dd BE(iprp_end - iprp_start)
db "iprp"
ipco_start:
dd BE(ipco_end - ipco_start)
db "ipco"
ispe_start:
dd BE(ispe_end - ispe_start)
db "ispe"
dd 0, 0, 0
ispe_end:
ipco_end:
iprp_end:
meta_end:
mdat_start:
dd BE(mdat_end - mdat_start)
db "mdat"
db 0x00 ; 'iovl' version
mdat_end:
; vim: syntax=nasm
|
cmp [$varName], byte 0
je allocate
mov rcx, [$varName]
call free
allocate:
mov rcx, $valLength
call malloc
mov [$varName], rax
mov rcx, [$value]
mov [rax], rcx
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %r9
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0x3b05, %r10
nop
nop
nop
nop
dec %rbx
mov (%r10), %rdx
nop
nop
nop
nop
nop
add $38606, %rcx
lea addresses_D_ht+0x193e5, %r15
xor $20191, %r9
mov $0x6162636465666768, %rdi
movq %rdi, %xmm4
vmovups %ymm4, (%r15)
nop
nop
xor %r10, %r10
lea addresses_UC_ht+0x11c65, %rsi
lea addresses_A_ht+0x1dbb5, %rdi
nop
nop
nop
nop
and $41979, %r9
mov $12, %rcx
rep movsl
nop
nop
xor %r15, %r15
lea addresses_D_ht+0x1c00d, %rsi
lea addresses_UC_ht+0x1d5e5, %rdi
nop
nop
nop
nop
and $22887, %r10
mov $96, %rcx
rep movsb
and $39614, %r15
lea addresses_WT_ht+0x32bd, %r9
xor $9219, %rbx
movb $0x61, (%r9)
nop
nop
nop
nop
nop
sub %r15, %r15
lea addresses_WC_ht+0x1cbe5, %r10
nop
nop
nop
nop
add %r9, %r9
mov (%r10), %si
nop
nop
nop
nop
sub %rdi, %rdi
lea addresses_WC_ht+0x6ee5, %rsi
lea addresses_WC_ht+0x181d, %rdi
sub %r15, %r15
mov $108, %rcx
rep movsq
nop
and $5178, %r9
lea addresses_UC_ht+0x1155, %rbx
nop
nop
nop
nop
xor %r15, %r15
movw $0x6162, (%rbx)
nop
nop
nop
nop
sub $64687, %rdi
lea addresses_normal_ht+0xea65, %rsi
lea addresses_WT_ht+0x1af79, %rdi
nop
nop
nop
nop
xor %r15, %r15
mov $78, %rcx
rep movsb
nop
nop
nop
nop
cmp $19615, %r9
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %rax
push %rbp
push %rbx
push %rsi
// Store
lea addresses_WC+0xe3e5, %rbx
clflush (%rbx)
nop
nop
nop
cmp $58056, %rax
mov $0x5152535455565758, %r14
movq %r14, %xmm6
vmovaps %ymm6, (%rbx)
nop
nop
nop
nop
nop
inc %rbx
// Faulty Load
lea addresses_WC+0xe3e5, %rsi
xor $41791, %r13
vmovups (%rsi), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $0, %xmm2, %r10
lea oracles, %rsi
and $0xff, %r10
shlq $12, %r10
mov (%rsi,%r10,1), %r10
pop %rsi
pop %rbx
pop %rbp
pop %rax
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 32, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': True, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}}
{'00': 13499}
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
SFX_80712_4_Ch4:
dutycycle 204
unknownsfx0x20 8, 245, 0, 6
unknownsfx0x20 2, 210, 56, 6
unknownsfx0x20 2, 194, 48, 6
unknownsfx0x20 2, 194, 40, 6
unknownsfx0x20 2, 178, 32, 6
unknownsfx0x20 2, 178, 16, 6
unknownsfx0x20 2, 162, 24, 6
unknownsfx0x20 2, 178, 16, 6
unknownsfx0x20 8, 193, 32, 6
endchannel
SFX_80739_4_Ch5:
dutycycle 68
unknownsfx0x20 12, 195, 192, 5
unknownsfx0x20 3, 177, 249, 5
unknownsfx0x20 2, 161, 241, 5
unknownsfx0x20 2, 161, 233, 5
unknownsfx0x20 2, 145, 225, 5
unknownsfx0x20 2, 145, 217, 5
unknownsfx0x20 2, 129, 209, 5
unknownsfx0x20 2, 145, 217, 5
unknownsfx0x20 8, 145, 225, 5
SFX_8075f_4_Ch7:
endchannel
|
/*
* Copyright (c) 2017, 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 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.
*/
L0:
(W&~f0.1)jmpi L400
L16:
add (1|M0) a0.0<1>:ud r23.5<0;1,0>:ud 0x50EB100:ud
mov (1|M0) r16.2<1>:ud 0x0:ud
cmp (1|M0) (eq)f1.0 null.0<1>:w r24.2<0;1,0>:ub 0x1:uw
(~f1.0) mov (1|M0) r25.2<1>:f r10.0<0;1,0>:f
(f1.0) mov (1|M0) r25.2<1>:f r10.2<0;1,0>:f
mov (8|M0) r17.0<1>:ud r25.0<8;8,1>:ud
send (1|M0) r80:uw r16:ub 0x2 a0.0
mov (16|M0) r13.0<1>:uw r80.0<16;16,1>:uw
mov (16|M0) r12.0<1>:uw r81.0<16;16,1>:uw
mov (16|M0) r80.0<1>:uw r84.0<16;16,1>:uw
mov (16|M0) r81.0<1>:uw r85.0<16;16,1>:uw
mov (16|M0) r84.0<1>:uw r13.0<16;16,1>:uw
mov (16|M0) r85.0<1>:uw r12.0<16;16,1>:uw
mov (16|M0) r13.0<1>:uw r88.0<16;16,1>:uw
mov (16|M0) r12.0<1>:uw r89.0<16;16,1>:uw
mov (16|M0) r88.0<1>:uw r92.0<16;16,1>:uw
mov (16|M0) r89.0<1>:uw r93.0<16;16,1>:uw
mov (16|M0) r92.0<1>:uw r13.0<16;16,1>:uw
mov (16|M0) r93.0<1>:uw r12.0<16;16,1>:uw
mov (1|M0) a0.8<1>:uw 0xA00:uw
mov (1|M0) a0.9<1>:uw 0xA40:uw
mov (1|M0) a0.10<1>:uw 0xA80:uw
mov (1|M0) a0.11<1>:uw 0xAC0:uw
add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x100:uw
L400:
nop
|
; Utils
; Various utility functions
;
; 2017 Scott Lawrence
;
; This code is free for any use. MIT License, etc.
.module Utils
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Line input routines
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ClearLine
; clear the line buffer
ClearLine:
xor a
ld d,a ; DE = 0000 (index for GetLine)
ld e,a
ld b, #LBUFLEN ; set the buffer length
ld hl, #LBUF ; set the buffer start
clx:
ld (hl),a
inc hl
djnz clx ; zero it all!
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; GetLine Helpers
; output a DING (ctrl-g)
_glDing:
ld a, #CH_BELL
call PutCh
ret
; error return
_glErRet:
call _glDing
ret
; error and continue
_glErCont:
call _glDing
jr GetLine
; output a carraige return (reset on the line) and reprint HL
_glCRPrint:
ld a, #0x0D
call PutCh
ld hl, #str_prompt
call Print
ld hl, #LBUF ; load base
call Print
; now a little hack to make sure we print erased characters
ld a, #CH_SPACE
call PutCh
ld a, #CH_BS
call PutCh
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; interactive get a line/character handler
; stores the input data in the line buffer
GetLine::
call _glCRPrint
ld a, e ; check if line is full
cp #LBUFLEN-1 ; max length (-1 for null ending)
jr z, _glErRet
ret z ; FULL! return!
; we're okay getting more characters
call GetCh
; check for end-of-line cases
cp #CH_CR
ret z
cp #CH_NL
ret z
; check for backspace/delete keyhits
cp #CH_BS ; backspace
jr z, _glBackspace
cp #CH_DEL ; delete
jr z, _glBackspace
; check for ctrl-u keyhits (clears line)
cp #CH_CTRLU
jr z, _glClearLine
; make sure the character is printable
cp #CH_PRLOW ; less than PRLOW is not printable
jr c, GetLine ; not printable
cp #CH_PRHI+1 ; greater than PRHI is not printable
jr c, _glAdd ; printable!
; too big. redo!
jr GetLine
_glAdd:
; add the new character onto the line
ld hl, #LBUF ; load base
add hl, de ; add index
ld (hl), a
inc de ; inc index
; and get another character
jr GetLine
; handle backspace or delete key being hit
_glBackspace:
ld a, e ; check that we can decrement
cp #0x00
jr z, _glErCont
dec de ; move index back
xor a
ld hl, #LBUF
add hl, de
ld (hl), a ; store a null
jr GetLine ; done
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ctrl-u hit, clear the line
_glClearLine:
xor a
ld d,a ; DE = 0000 (index for GetLine)
ld e,a
ld b, #LBUFLEN ; set the buffer length
ld hl, #LBUF ; set the buffer start
_glcl0:
ld a, (hl)
cp #CH_NULL
jr z, _glclret
ld a, #CH_SPACE ; fill with spaces
ld (hl),a
inc hl
djnz _glcl0 ; zero it all!
_glclret:
; now clear the index
ld hl, #LBUF ; set the buffer start
jr GetLine
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; U_Streq - string equality compare
; compares the string in hl with the string in de
; if equal returns 0
; destructive to a and c
U_Streq::
push hl
push de
_seqLoop:
ld a, (hl)
ld b, a
ld a, (de)
cp a, b
jr nz, _seqNEQ ; not equal!
; if we're here then they're equal
cp a, #0x00 ; check for null
jr z, _seqDone ; it was null! continue
; next character!
inc hl
inc de
jr _seqLoop
; it was null, strings were equal!
_seqDone:
xor a
jr _seqRet
; strings are not equal
_seqNEQ:
ld a, #0x01 ; not equal
_seqRet:
pop de
pop hl
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; NullSpace
; null out the next whitespace (' ') (or null)
; destructive to the data, returns hl intact
U_NullSpace::
push hl
_nlsLoop:
ld a, (hl)
cp #CH_SPACE
jr z, _nlsRetFix
cp #CH_NULL
jr z, _nlsRet
inc hl ; next character...
jr _nlsLoop
_nlsRetFix: ; fix up the ptr with NULL
ld a, #CH_NULL
ld (hl), a
_nlsRet: ; restore hl, return
pop hl
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; NextToken
; advance hl to the next non-whitespace character after a null
U_NextToken::
; advance to next NULL
ld a, (hl)
cp #CH_NULL ; check if it's null
jr z, _nxt2
inc hl ; next character
jr U_NextToken ; do it again
_nxt2:
; it's now pointing to a null
inc hl ; advance it by one
; skip over spaces
ld a, (hl)
cp #CH_SPACE
jr nz, _nxtRet ; not a space, just return
jr _nxt2 ; next character, do it again
_nxtRet:
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IsNextToken
; HL MUST point to the string in-parse
; returns 0 if no more tokens, non zero if there's another (in 'a')
U_IsNextToken::
push hl
call U_NextToken
; we're either pointing at a NULL or a character
; either way, we have our return values.
pop hl
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IsHLZero
; a = 0 if HL == 0x0000
; a = nonzero otherwise
IsHLZero:
ld a, h
cp a, #0x00
ret nz ; return the byte (nonzero)
ld a, l
ret ; return the byte (nonzero)
; I did have some logic in here to compare both bytes and set a
; return value, then i realized that if all i care about is if
; both bytes are zero, I just need to check the first one for
; zero. If it's not, just return it. If it is zero, then just
; load the second byte into a, and you can use that one as the
; return value!
; DerefHL
; Dereference the pointer in HL
; visit the address at HL, and take the data there (16 bit) and
; shove it back into HL.
; only HL will be modified
DerefHL:
push bc
ld c, (hl)
inc hl
ld b, (hl)
push bc
pop hl
pop bc
ret
|
; A016938: a(n) = (6*n + 2)^6.
; 64,262144,7529536,64000000,308915776,1073741824,3010936384,7256313856,15625000000,30840979456,56800235584,98867482624,164206490176,262144000000,404567235136,606355001344,885842380864,1265319018496,1771561000000,2436396322816,3297303959104,4398046511104,5789336458816,7529536000000,9685390482496,12332795428864,15557597153344,19456426971136,24137569000000,29721861554176,36343632130624,44151665987584,53310208315456,64000000000000,76419346977856,90785223184384,107334407093824,126324651851776,148035889000000,172771465793536,200859416110144,232653764952064,268535866540096,308915776000000,354233654641216,404961208827904,461603162442304,524698762940416,594823321000000,672589783760896,758650341657664,853698068844544,958468597212736,1073741824000000,1200343652992576,1339147769319424,1491077447838784,1657107395117056,1838265625000000,2035635367776256,2250357012933184,2483630085505024,2736715256013376,3010936384000000,3307682595151936,3628410392018944,3974645798323264,4347986536861696,4750104241000000,5182746699759616,5647740136496704,6146991521173504,6682490916222016,7256313856000000,7870623759839296,8527674378686464,9229812275335744,9979479338254336,10779215329000000,11631660463230976,12539558025308224,13505757016489984,14533214836718656,15625000000000000,16784294883374656,18014398509481984,19318729362716224,20700828238974976,22164361129000000,23713122135310336,25351036422727744,27082163202494464,28910698749983296,30840979456000000,32877484911678016,35024841026965504,37287823182704704,39671359416303616,42180533641000000,44820588898717696
mul $0,6
add $0,2
pow $0,6
|
%ifdef CONFIG
{
"RegData": {
"XMM0": ["0x4018000000000000", "0x4018000000000000"],
"XMM1": ["0x4018000000000000", "0x4018000000000000"],
"XMM2": ["0x4000000000000000", "0x4000000000000000"]
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0x4008000000000000
mov [rdx + 8 * 0], rax
mov rax, 0x4008000000000000
mov [rdx + 8 * 1], rax
mov rax, 0x4000000000000000
mov [rdx + 8 * 2], rax
mov rax, 0x4000000000000000
mov [rdx + 8 * 3], rax
movapd xmm0, [rdx]
mulpd xmm0, [rdx + 8 * 2]
movapd xmm1, [rdx]
movapd xmm2, [rdx + 8 * 2]
mulpd xmm1, xmm2
hlt
|
; A256249: Partial sums of A006257 (Josephus problem).
; 0,1,2,5,6,9,14,21,22,25,30,37,46,57,70,85,86,89,94,101,110,121,134,149,166,185,206,229,254,281,310,341,342,345,350,357,366,377,390,405,422,441,462,485,510,537,566,597,630,665,702,741,782,825,870,917,966,1017,1070,1125,1182,1241,1302,1365,1366,1369,1374,1381,1390,1401,1414,1429,1446,1465,1486,1509,1534,1561,1590,1621,1654,1689,1726,1765,1806,1849,1894,1941,1990,2041,2094,2149,2206,2265,2326,2389,2454,2521,2590,2661,2734,2809,2886,2965,3046,3129,3214,3301,3390,3481,3574,3669,3766,3865,3966,4069,4174,4281,4390,4501,4614,4729,4846,4965,5086,5209,5334,5461,5462,5465,5470,5477,5486,5497,5510,5525,5542,5561,5582,5605,5630,5657,5686,5717,5750,5785,5822,5861,5902,5945,5990,6037,6086,6137,6190,6245,6302,6361,6422,6485,6550,6617,6686,6757,6830,6905,6982,7061,7142,7225,7310,7397,7486,7577,7670,7765,7862,7961,8062,8165,8270,8377,8486,8597,8710,8825,8942,9061,9182,9305,9430,9557,9686,9817,9950,10085,10222,10361,10502,10645,10790,10937,11086,11237,11390,11545,11702,11861,12022,12185,12350,12517,12686,12857,13030,13205,13382,13561,13742,13925,14110,14297,14486,14677,14870,15065,15262,15461,15662,15865,16070,16277,16486,16697,16910,17125,17342,17561,17782,18005,18230,18457,18686,18917,19150,19385,19622,19861,20102,20345
mov $5,$0
mov $9,$0
lpb $5,1
mov $0,$9
sub $5,1
sub $0,$5
mov $2,2
mov $3,$0
lpb $2,1
mov $4,$3
add $4,$3
sub $8,$8
add $8,1
lpb $4,1
mov $7,$4
trn $4,$8
mul $8,2
lpe
mov $6,1
mov $8,$7
add $8,1
lpb $6,1
trn $6,$8
add $8,6
lpe
div $2,3
lpe
sub $8,7
add $1,$8
lpe
|
DATA SEGMENT
NOTIC DB "Please input the word!",0AH,0DH
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE,DS:DATA
START: MOV AX,DATA
MOV DS,AX
MOV CX,19H
LEA BX,[NOTIC]
AA0: MOV DL,[BX]
MOV AH,2
INT 21H
INC BX
LOOP AA0
AA1: MOV AH,1
INT 21H
CMP AL,1BH
JZ AA3
CMP AL,61H
JS AA2
CMP AL,7AH
JNS AA2
SUB AL,20H
AA2: MOV DL,AL
MOV AH,2
INT 21H
LOOP AA1
AA3: MOV AH,4CH
INT 21H
CODE ENDS
END START |
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from thread_dispatcher.djinni
#include "Runnable.hpp" // my header
namespace djinni_generated {
Runnable::Runnable() : ::djinni::JniInterface<::ledger::core::api::Runnable, Runnable>("co/ledger/core/Runnable$CppProxy") {}
Runnable::~Runnable() = default;
CJNIEXPORT void JNICALL Java_co_ledger_core_Runnable_00024CppProxy_nativeDestroy(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
delete reinterpret_cast<::djinni::CppProxyHandle<::ledger::core::api::Runnable>*>(nativeRef);
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT void JNICALL Java_co_ledger_core_Runnable_00024CppProxy_native_1run(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::ledger::core::api::Runnable>(nativeRef);
ref->run();
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
} // namespace djinni_generated
|
//Optimise
#include <bits/stdc++.h>
using namespace std;
#define multitest 1
#ifdef Debug
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
const long long mod = 1000000007;
auto TimeStart = chrono::steady_clock::now();
const int nax = 2e5 + 10;
string s;
void solve(int t)
{
cin >> s;
int n = s.length();
if (s == "1" || s == "4" || s == "78")
cout << "+";
else if (n >= 2 && s[n - 1] == '5' && s[n - 2] == '3')
cout << "-";
else if (n >= 2 && s[0] == '9' && s[n - 1] == '4')
cout << "*";
else if (n >= 3 && s[0] == '1' && s[1] == '9' && s[2] == '0')
cout << "?";
else
cout << "+";
// if (t)
cout << '\n';
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
#ifdef multitest
cin >> t;
#endif
while (t--)
solve(t);
#ifdef TIME
cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n";
#endif
return 0;
} |
; A015215: Sum of Gaussian binomial coefficients for q=23.
; Submitted by Stefano Spezia
; 1,2,26,1108,318532,310699784,2050802289512,45998820030427216,6982715817685577376784,3602226883731790235442134048,12576944383710950724867108854566304,149227717546908065915667125958905292219712,11983435631995977285043150028521017699457076388928,3270269408854970178585852992103953757893720461655641325696,6040087305991622968762537708180312421701146751547961881632700597888,37911698006081937162358978140470729735899479745891981826262675271104986662144
mov $1,$0
mov $0,0
add $1,1
mov $2,1
lpb $1
sub $1,1
mov $4,$2
mul $2,23
mul $4,$3
add $0,$4
sub $3,$4
add $3,$0
add $3,$2
lpe
mov $0,$3
div $0,529
add $0,1
|
; A207021: Number of nX5 0..1 arrays avoiding 0 0 0 and 0 1 1 horizontally and 0 0 1 and 1 0 1 vertically
; 13,169,624,1586,3315,6123,10374,16484,24921,36205,50908,69654,93119,122031,157170,199368,249509,308529,377416,457210,549003,653939,773214,908076,1059825,1229813,1419444,1630174,1863511,2121015,2404298,2715024,3054909,3425721,3829280,4267458,4742179,5255419,5809206,6405620,7046793,7734909,8472204,9260966,10103535,11002303,11959714,12978264,14060501,15209025,16426488,17715594,19079099,20519811,22040590,23644348,25334049,27112709,28983396,30949230,33013383,35179079,37449594,39828256,42318445,44923593,47647184,50492754,53463891,56564235,59797478,63167364,66677689,70332301,74135100,78090038,82201119,86472399,90907986,95512040,100288773,105242449,110377384,115697946,121208555,126913683,132817854,138925644,145241681,151770645,158517268,165486334,172682679,180111191,187776810,195684528,203839389,212246489,220910976,229838050
mov $2,$0
mov $3,$0
mul $3,$0
sub $3,$0
mov $0,1
mul $2,6
add $2,$3
mov $4,3
add $4,$2
pow $4,2
add $4,$3
add $4,2
lpb $0
sub $0,1
mov $1,7
add $1,$4
lpe
sub $1,18
div $1,6
mul $1,13
add $1,13
mov $0,$1
|
/**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
// Alain 18.12.2014: workaround after VS2013 & intel XE 2015
#ifndef MKL_BLAS
# define MKL_BLAS MKL_DOMAIN_BLAS
#endif
#include <Utils/Bonds/BondOrderCollection.h>
#include <Utils/DataStructures/AtomsOrbitalsIndexes.h>
#include <Utils/DataStructures/DensityMatrix.h>
#include <Utils/DataStructures/MolecularOrbitals.h>
#include <Utils/DataStructures/SingleParticleEnergies.h>
#include <Utils/DataStructures/SpinAdaptedMatrix.h>
#include <Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.h>
#include <Utils/Math/IterativeDiagonalizer/IndirectPreconditionerEvaluator.h>
#include <Utils/Math/IterativeDiagonalizer/IndirectSigmaVectorEvaluator.h>
#include <Utils/Scf/LcaoUtils/LcaoUtils.h>
#include <Eigen/Eigenvalues>
#include <cmath>
#include <iostream>
namespace Scine {
namespace Utils {
namespace LcaoUtils {
void getNumberUnrestrictedElectrons(int& nAlpha, int& nBeta, int nElectrons, int spinMultiplicity) {
assert(nElectrons >= 0);
assert(spinMultiplicity >= 1);
assert(spinMultiplicity <= nElectrons + 1 &&
"Spin multiplicity is invalid with the number of electrons: too few electrons.");
assert((spinMultiplicity + nElectrons) % 2 == 1 &&
"Spin multiplicity is invalid with the number of electrons: they can't have the same parity.");
// NB: system of two equations with two unknowns:
// nAlpha + nBeta = nElectrons_
// nAlpha - nBeta = spinMultiplicity - 1
nAlpha = (nElectrons + spinMultiplicity - 1) / 2;
nBeta = nElectrons - nAlpha;
}
void solveRestrictedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, MolecularOrbitals& coefficientMatrix,
SingleParticleEnergies& singleParticleEnergies) {
if (fockMatrix.restrictedMatrix().size() == 0) {
coefficientMatrix = MolecularOrbitals::createEmptyRestrictedOrbitals();
singleParticleEnergies = SingleParticleEnergies::createEmptyRestrictedEnergies();
return;
}
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;
es.compute(fockMatrix.restrictedMatrix());
coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(es.eigenvectors());
singleParticleEnergies.setRestricted(es.eigenvalues());
}
void solveRestrictedGeneralizedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, const Eigen::MatrixXd& overlapMatrix,
MolecularOrbitals& coefficientMatrix,
SingleParticleEnergies& singleParticleEnergies) {
if (fockMatrix.restrictedMatrix().size() == 0) {
coefficientMatrix = MolecularOrbitals::createEmptyRestrictedOrbitals();
singleParticleEnergies = SingleParticleEnergies::createEmptyRestrictedEnergies();
return;
}
Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> ges;
ges.compute(fockMatrix.restrictedMatrix(), overlapMatrix);
coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(ges.eigenvectors());
singleParticleEnergies.setRestricted(ges.eigenvalues());
}
void solveUnrestrictedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, MolecularOrbitals& coefficientMatrix,
SingleParticleEnergies& singleParticleEnergies) {
if (fockMatrix.alphaMatrix().size() == 0) {
coefficientMatrix = MolecularOrbitals::createEmptyUnrestrictedOrbitals();
singleParticleEnergies = SingleParticleEnergies::createEmptyUnrestrictedEnergies();
return;
}
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;
es.compute(fockMatrix.alphaMatrix());
Eigen::MatrixXd alphaCoefficients = es.eigenvectors();
Eigen::VectorXd alpha = es.eigenvalues();
es.compute(fockMatrix.betaMatrix());
Eigen::MatrixXd betaCoefficients = es.eigenvectors();
Eigen::VectorXd beta = es.eigenvalues();
coefficientMatrix =
MolecularOrbitals::createFromUnrestrictedCoefficients(std::move(alphaCoefficients), std::move(betaCoefficients));
singleParticleEnergies.setUnrestricted(alpha, beta);
}
void solveUnrestrictedGeneralizedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, const Eigen::MatrixXd& overlapMatrix,
MolecularOrbitals& coefficientMatrix,
SingleParticleEnergies& singleParticleEnergies) {
if (fockMatrix.alphaMatrix().size() == 0) {
coefficientMatrix = MolecularOrbitals::createEmptyUnrestrictedOrbitals();
singleParticleEnergies = SingleParticleEnergies::createEmptyUnrestrictedEnergies();
return;
}
Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> ges;
ges.compute(fockMatrix.alphaMatrix(), overlapMatrix);
Eigen::MatrixXd alphaCoefficients = ges.eigenvectors();
Eigen::VectorXd alpha = ges.eigenvalues();
ges.compute(fockMatrix.betaMatrix(), overlapMatrix);
Eigen::MatrixXd betaCoefficients = ges.eigenvectors();
Eigen::VectorXd beta = ges.eigenvalues();
coefficientMatrix =
MolecularOrbitals::createFromUnrestrictedCoefficients(std::move(alphaCoefficients), std::move(betaCoefficients));
singleParticleEnergies.setUnrestricted(alpha, beta);
}
void calculateRestrictedDensityMatrix(DensityMatrix& densityMatrix, const MolecularOrbitals& coefficientMatrix, int nElectrons) {
assert(nElectrons >= 0);
const auto& C = coefficientMatrix.restrictedMatrix();
auto nAOs = C.cols();
Eigen::MatrixXd P = 2 * C.block(0, 0, nAOs, nElectrons / 2) * C.block(0, 0, nAOs, nElectrons / 2).transpose();
if ((nElectrons % 2) != 0) { // if odd number of electrons
P += C.col(nElectrons / 2) * C.col(nElectrons / 2).transpose();
}
densityMatrix.setDensity(std::move(P), nElectrons);
}
void calculateUnrestrictedDensityMatrices(DensityMatrix& densityMatrix, const MolecularOrbitals& coefficientMatrix,
int nElectrons, int spinMultiplicity) {
assert(nElectrons >= 0);
assert(spinMultiplicity >= 1);
int nAlpha, nBeta;
getNumberUnrestrictedElectrons(nAlpha, nBeta, nElectrons, spinMultiplicity);
const auto& cA = coefficientMatrix.alphaMatrix();
const auto& cB = coefficientMatrix.betaMatrix();
auto nAOs = cA.cols();
Eigen::MatrixXd alphaMatrix = cA.block(0, 0, nAOs, nAlpha) * cA.block(0, 0, nAOs, nAlpha).transpose();
Eigen::MatrixXd betaMatrix = cB.block(0, 0, nAOs, nBeta) * cB.block(0, 0, nAOs, nBeta).transpose();
densityMatrix.setDensity(std::move(alphaMatrix), std::move(betaMatrix), nAlpha, nBeta);
}
void calculateRestrictedEnergyWeightedDensityMatrix(Eigen::MatrixXd& energyWeightedDensityMatrix,
const MolecularOrbitals& coefficientMatrix,
const SingleParticleEnergies& singleParticleEnergies, int nElectrons) {
assert(nElectrons >= 0);
const auto& C = coefficientMatrix.restrictedMatrix();
auto nAOs = C.cols();
Eigen::MatrixXd CEn(nAOs, (nElectrons + 1) / 2); // Eigenvector matrix multiplied by energy eigenvalues
for (int i = 0; i < (nElectrons + 1) / 2; i++) {
CEn.col(i) = C.col(i) * singleParticleEnergies.getRestrictedEnergies()[i];
}
energyWeightedDensityMatrix =
2 * C.block(0, 0, nAOs, (nElectrons) / 2) * CEn.block(0, 0, nAOs, (nElectrons) / 2).transpose();
// if odd number of electrons
if ((nElectrons % 2) != 0) {
energyWeightedDensityMatrix += C.col(nElectrons / 2) * CEn.col(nElectrons / 2).transpose();
}
}
void calculateUnrestrictedEnergyWeightedDensityMatrix(Eigen::MatrixXd& energyWeightedDensityMatrix,
const MolecularOrbitals& coefficientMatrix,
const SingleParticleEnergies& singleParticleEnergies,
int nElectrons, int spinMultiplicity) {
assert(nElectrons >= 0);
assert(spinMultiplicity >= 1);
int nAlpha, nBeta;
getNumberUnrestrictedElectrons(nAlpha, nBeta, nElectrons, spinMultiplicity);
const auto& cA = coefficientMatrix.alphaMatrix();
const auto& cB = coefficientMatrix.betaMatrix();
auto nAOs = cA.cols();
Eigen::MatrixXd CEnAlpha(nAOs, nAlpha); // Alpha Eigenvector matrix multiplied by energy eigenvalues
Eigen::MatrixXd CEnBeta(nAOs, nBeta); // Beta Eigenvector matrix multiplied by energy eigenvalues
for (int i = 0; i < nAlpha; i++) {
CEnAlpha.col(i) = cA.col(i) * singleParticleEnergies.getAlphaEnergies()[i];
}
for (int i = 0; i < nBeta; i++) {
CEnBeta.col(i) = cB.col(i) * singleParticleEnergies.getBetaEnergies()[i];
}
energyWeightedDensityMatrix = cA.block(0, 0, nAOs, nAlpha) * CEnAlpha.block(0, 0, nAOs, nAlpha).transpose() +
cB.block(0, 0, nAOs, nBeta) * CEnBeta.block(0, 0, nAOs, nBeta).transpose();
}
void calculateBondOrderMatrix(Utils::BondOrderCollection& bondOrderMatrix, const DensityMatrix& densityMatrix,
const Eigen::MatrixXd& overlapMatrix, const AtomsOrbitalsIndexes& aoIndexes) {
bondOrderMatrix.resize(aoIndexes.getNAtoms());
bondOrderMatrix.setZero();
// Bond order analysis (Mayer bond order)
Eigen::MatrixXd PS = densityMatrix.restrictedMatrix() * overlapMatrix; // TODO: WHAT IF OVERLAP MATRIX IS ONLY
// LOWER-TRIANGULAR?
for (int i = 1; i < aoIndexes.getNAtomicOrbitals(); i++) {
for (int j = 0; j < i; j++) {
PS(i, j) = PS(i, j) * PS(j, i);
}
}
for (int a = 1; a < aoIndexes.getNAtoms(); a++) {
for (int b = 0; b < a; b++) {
double order = PS.block(aoIndexes.getFirstOrbitalIndex(a), aoIndexes.getFirstOrbitalIndex(b),
aoIndexes.getNOrbitals(a), aoIndexes.getNOrbitals(b))
.sum();
bondOrderMatrix.setOrder(a, b, order);
}
}
}
void calculateOrthonormalBondOrderMatrix(Utils::BondOrderCollection& bondOrderMatrix,
const DensityMatrix& densityMatrix, const AtomsOrbitalsIndexes& aoIndexes) {
bondOrderMatrix.resize(aoIndexes.getNAtoms());
bondOrderMatrix.setZero();
// Bond order analysis (Mayer bond order), no need for overlap since it is no generalized eigenvalue problem
const auto& P = densityMatrix.restrictedMatrix();
Eigen::MatrixXd P2 = P.cwiseProduct(P);
for (int a = 1; a < aoIndexes.getNAtoms(); a++) {
for (int b = 0; b < a; b++) {
double order = P2.block(aoIndexes.getFirstOrbitalIndex(a), aoIndexes.getFirstOrbitalIndex(b),
aoIndexes.getNOrbitals(a), aoIndexes.getNOrbitals(b))
.sum();
bondOrderMatrix.setOrder(a, b, order);
}
}
}
void calculateOrthonormalAtomicCharges(std::vector<double>& mullikenCharges, const std::vector<double>& coreCharges,
const DensityMatrix& densityMatrix, const AtomsOrbitalsIndexes& aoIndexes) {
// in the case of an orthonormal basis, the partial charge of an atom is given as
// q_A = Z_A - \sum_{i in A} P_ii
for (int a = 0; a < aoIndexes.getNAtoms(); a++) {
mullikenCharges[a] = coreCharges[a];
int nAOsA = aoIndexes.getNOrbitals(a);
int index = aoIndexes.getFirstOrbitalIndex(a);
double nElectronsOnAtom = densityMatrix.restrictedMatrix().block(index, index, nAOsA, nAOsA).trace();
mullikenCharges[a] = coreCharges[a] - nElectronsOnAtom;
}
}
void calculateMullikenAtomicCharges(std::vector<double>& mullikenCharges, const std::vector<double>& coreCharges,
const DensityMatrix& densityMatrix, const Eigen::MatrixXd& overlapMatrix,
const AtomsOrbitalsIndexes& aoIndexes) {
// Calculation of the Mulliken charges as described in elstner1998
Eigen::MatrixXd D = densityMatrix.restrictedMatrix().cwiseProduct(overlapMatrix); // population matrix
for (int a = 0; a < aoIndexes.getNAtoms(); a++) {
mullikenCharges[a] = coreCharges[a];
int nAOsA = aoIndexes.getNOrbitals(a);
int index = aoIndexes.getFirstOrbitalIndex(a);
for (int mu = 0; mu < nAOsA; mu++) {
for (int nu = 0; nu < aoIndexes.getNAtomicOrbitals(); nu++) {
mullikenCharges[a] -= D(index + mu, nu);
}
}
}
}
} // namespace LcaoUtils
} // namespace Utils
} // namespace Scine
|
; A169545: Number of reduced words of length n in Coxeter group on 4 generators S_i with relations (S_i)^2 = (S_i S_j)^35 = I.
; 1,4,12,36,108,324,972,2916,8748,26244,78732,236196,708588,2125764,6377292,19131876,57395628,172186884,516560652,1549681956,4649045868,13947137604,41841412812,125524238436,376572715308,1129718145924
mov $1,3
pow $1,$0
mul $1,8
div $1,6
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/animation/CSSValueInterpolationType.h"
#include "core/animation/InterpolationEnvironment.h"
#include "core/animation/StringKeyframe.h"
#include "core/css/resolver/StyleBuilder.h"
namespace blink {
class CSSValueNonInterpolableValue : public NonInterpolableValue {
public:
~CSSValueNonInterpolableValue() final { }
static PassRefPtr<CSSValueNonInterpolableValue> create(PassRefPtrWillBeRawPtr<CSSValue> cssValue)
{
return adoptRef(new CSSValueNonInterpolableValue(cssValue));
}
CSSValue* cssValue() const { return m_cssValue.get(); }
DECLARE_NON_INTERPOLABLE_VALUE_TYPE();
private:
CSSValueNonInterpolableValue(PassRefPtrWillBeRawPtr<CSSValue> cssValue)
: m_cssValue(cssValue)
{
ASSERT(m_cssValue);
}
RefPtrWillBePersistent<CSSValue> m_cssValue;
};
DEFINE_NON_INTERPOLABLE_VALUE_TYPE(CSSValueNonInterpolableValue);
DEFINE_NON_INTERPOLABLE_VALUE_TYPE_CASTS(CSSValueNonInterpolableValue);
PassOwnPtr<InterpolationValue> CSSValueInterpolationType::maybeConvertSingle(const PropertySpecificKeyframe& keyframe, const InterpolationEnvironment&, const UnderlyingValue&, ConversionCheckers&) const
{
if (keyframe.isNeutral())
return nullptr;
return InterpolationValue::create(*this, InterpolableList::create(0), CSSValueNonInterpolableValue::create(toCSSPropertySpecificKeyframe(keyframe).value()));
}
void CSSValueInterpolationType::apply(const InterpolableValue&, const NonInterpolableValue* nonInterpolableValue, InterpolationEnvironment& environment) const
{
StyleBuilder::applyProperty(cssProperty(), environment.state(), toCSSValueNonInterpolableValue(nonInterpolableValue)->cssValue());
}
} // namespace blink
|
;;
;; Copyright (c) 2018, Intel Corporation
;;
;; 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.
;;
%include "include/aesni_emu.inc"
%define AES_CBC_ENC_X4 aes_cbc_enc_256_x4_no_aesni
%include "sse/aes_cbc_enc_256_x4.asm"
|
; A033131: Base-4 digits are, in order, the first n terms of the periodic sequence with initial period 1,1,0.
; 1,5,20,81,325,1300,5201,20805,83220,332881,1331525,5326100,21304401,85217605,340870420,1363481681,5453926725,21815706900,87262827601,349051310405,1396205241620,5584820966481,22339283865925,89357135463700,357428541854801,1429714167419205,5718856669676820
mov $1,4
pow $1,$0
mul $1,80
div $1,63
|
////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULib
//
// Copyright (c) 2014-2015, richards-tech, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "RTPressureMS5611.h"
#if defined(MS5611)
RTPressureMS5611::RTPressureMS5611(RTIMUSettings *settings) : RTPressure(settings)
{
m_validReadings = false;
}
RTPressureMS5611::~RTPressureMS5611()
{
}
bool RTPressureMS5611::pressureInit()
{
unsigned char cmd = MS5611_CMD_PROM + 2;
unsigned char data[2];
m_pressureAddr = m_settings->m_I2CPressureAddress;
for (uint8_t offset = 0; offset < 6; offset++)
{
if (!m_settings->HALRead(m_pressureAddr, cmd + (offset * 2), 2, data, "Failed to read MS5611 calibration data"))
return false;
fc[offset] = (((uint16_t)data[0]) << 8) + (uint16_t)data[1];
delay(10);
}
return true;
}
#define MS5611_ADDRESS m_pressureAddr
uint32_t RTPressureMS5611::readRaw(unsigned char command)
{
uint8_t data[3];
if (!m_settings->HALWrite (MS5611_ADDRESS, command, 0, 0, "Failed to start MS5611 pressure conversion")) {
return 0;
}
delay(10);
if (!m_settings->HALRead(MS5611_ADDRESS, MS5611_CMD_ADC, 3, data, "Failed to read MS5611 pressure")) {
return 0;
}
return (((uint32_t)data[0]) << 16) | (((uint32_t)data[1]) << 8) | (uint32_t)data[2];
}
bool RTPressureMS5611::pressureRead(RTIMU_DATA& data)
{
uint32_t D1 = readRaw(MS5611_CMD_CONV_D1);
uint32_t D2 = readRaw(MS5611_CMD_CONV_D2);
int32_t dT = D2 - (uint32_t)fc[4] * 256;
if (D1 == 0 || D2 == 0)
{
data.temperature = data.pressure = 0;
data.pressureValid = data.temperatureValid = false;
return false;
}
int64_t OFF = (int64_t)fc[1] * 65536 + (int64_t)fc[3] * dT / 128;
int64_t SENS = (int64_t)fc[0] * 32768 + (int64_t)fc[2] * dT / 256;
uint32_t P = (D1 * SENS / 2097152 - OFF) / 32768;
data.pressure = (float)P/100.0;
data.pressureValid = true;
data.temperature = tempFromDT(dT);
data.temperatureValid = true;
return true;
}
float RTPressureMS5611::tempFromDT(int32_t dT)
{
int32_t TEMP = 2000 + ((int64_t) dT * fc[5]) / 8388608;
return ((float)TEMP/100);
}
#endif |
;**** A P P L I C A T I O N N O T E A V R 2 0 0 ************************
;*
;* Title: Multiply and Divide Routines
;* Version: 1.1
;* Last updated: 97.07.04
;* Target: AT90Sxxxx (All AVR Devices)
;*
;* Support E-mail: avr@atmel.com
;*
;* DESCRIPTION
;* This Application Note lists subroutines for the following
;* Muliply/Divide applications:
;*
;* 8x8 bit unsigned
;* 8x8 bit signed
;* 16x16 bit unsigned
;* 16x16 bit signed
;* 8/8 bit unsigned
;* 8/8 bit signed
;* 16/16 bit unsigned
;* 16/16 bit signed
;*
;* All routines are Code Size optimized implementations
;*
;***************************************************************************
.include "1200def.inc"
rjmp RESET ;reset handle
;***************************************************************************
;*
;* "mpy8u" - 8x8 Bit Unsigned Multiplication
;*
;* This subroutine multiplies the two register variables mp8u and mc8u.
;* The result is placed in registers m8uH, m8uL
;*
;* Number of words :9 + return
;* Number of cycles :58 + return
;* Low registers used :None
;* High registers used :4 (mp8u,mc8u/m8uL,m8uH,mcnt8u)
;*
;* Note: Result Low byte and the multiplier share the same register.
;* This causes the multiplier to be overwritten by the result.
;*
;***************************************************************************
;***** Subroutine Register Variables
.def mc8u =r16 ;multiplicand
.def mp8u =r17 ;multiplier
.def m8uL =r17 ;result Low byte
.def m8uH =r18 ;result High byte
.def mcnt8u =r19 ;loop counter
;***** Code
mpy8u: clr m8uH ;clear result High byte
ldi mcnt8u,8 ;init loop counter
lsr mp8u ;rotate multiplier
m8u_1: brcc m8u_2 ;carry set
add m8uH,mc8u ; add multiplicand to result High byte
m8u_2: ror m8uH ;rotate right result High byte
ror m8uL ;rotate right result L byte and multiplier
dec mcnt8u ;decrement loop counter
brne m8u_1 ;if not done, loop more
ret
;***************************************************************************
;*
;* "mpy8s" - 8x8 Bit Signed Multiplication
;*
;* This subroutine multiplies signed the two register variables mp8s and
;* mc8s. The result is placed in registers m8sH, m8sL
;* The routine is an implementation of Booth's algorithm. If all 16 bits
;* in the result are needed, avoid calling the routine with
;* -128 ($80) as multiplicand
;*
;* Number of words :10 + return
;* Number of cycles :73 + return
;* Low registers used :None
;* High registers used :4 (mc8s,mp8s/m8sL,m8sH,mcnt8s)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def mc8s =r16 ;multiplicand
.def mp8s =r17 ;multiplier
.def m8sL =r17 ;result Low byte
.def m8sH =r18 ;result High byte
.def mcnt8s =r19 ;loop counter
;***** Code
mpy8s: sub m8sH,m8sH ;clear result High byte and carry
ldi mcnt8s,8 ;init loop counter
m8s_1: brcc m8s_2 ;if carry (previous bit) set
add m8sH,mc8s ; add multiplicand to result High byte
m8s_2: sbrc mp8s,0 ;if current bit set
sub m8sH,mc8s ; subtract multiplicand from result High
asr m8sH ;shift right result High byte
ror m8sL ;shift right result L byte and multiplier
dec mcnt8s ;decrement loop counter
brne m8s_1 ;if not done, loop more
ret
;***************************************************************************
;*
;* "mpy16u" - 16x16 Bit Unsigned Multiplication
;*
;* This subroutine multiplies the two 16-bit register variables
;* mp16uH:mp16uL and mc16uH:mc16uL.
;* The result is placed in m16u3:m16u2:m16u1:m16u0.
;*
;* Number of words :14 + return
;* Number of cycles :153 + return
;* Low registers used :None
;* High registers used :7 (mp16uL,mp16uH,mc16uL/m16u0,mc16uH/m16u1,m16u2,
;* m16u3,mcnt16u)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def mc16uL =r16 ;multiplicand low byte
.def mc16uH =r17 ;multiplicand high byte
.def mp16uL =r18 ;multiplier low byte
.def mp16uH =r19 ;multiplier high byte
.def m16u0 =r18 ;result byte 0 (LSB)
.def m16u1 =r19 ;result byte 1
.def m16u2 =r20 ;result byte 2
.def m16u3 =r21 ;result byte 3 (MSB)
.def mcnt16u =r22 ;loop counter
;***** Code
mpy16u: clr m16u3 ;clear 2 highest bytes of result
clr m16u2
ldi mcnt16u,16 ;init loop counter
lsr mp16uH
ror mp16uL
m16u_1: brcc noad8 ;if bit 0 of multiplier set
add m16u2,mc16uL ;add multiplicand Low to byte 2 of res
adc m16u3,mc16uH ;add multiplicand high to byte 3 of res
noad8: ror m16u3 ;shift right result byte 3
ror m16u2 ;rotate right result byte 2
ror m16u1 ;rotate result byte 1 and multiplier High
ror m16u0 ;rotate result byte 0 and multiplier Low
dec mcnt16u ;decrement loop counter
brne m16u_1 ;if not done, loop more
ret
;***************************************************************************
;*
;* "mpy16s" - 16x16 Bit Signed Multiplication
;*
;* This subroutine multiplies signed the two 16-bit register variables
;* mp16sH:mp16sL and mc16sH:mc16sL.
;* The result is placed in m16s3:m16s2:m16s1:m16s0.
;* The routine is an implementation of Booth's algorithm. If all 32 bits
;* in the result are needed, avoid calling the routine with
;* -32768 ($8000) as multiplicand
;*
;* Number of words :16 + return
;* Number of cycles :210/226 (Min/Max) + return
;* Low registers used :None
;* High registers used :7 (mp16sL,mp16sH,mc16sL/m16s0,mc16sH/m16s1,
;* m16s2,m16s3,mcnt16s)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def mc16sL =r16 ;multiplicand low byte
.def mc16sH =r17 ;multiplicand high byte
.def mp16sL =r18 ;multiplier low byte
.def mp16sH =r19 ;multiplier high byte
.def m16s0 =r18 ;result byte 0 (LSB)
.def m16s1 =r19 ;result byte 1
.def m16s2 =r20 ;result byte 2
.def m16s3 =r21 ;result byte 3 (MSB)
.def mcnt16s =r22 ;loop counter
;***** Code
mpy16s: clr m16s3 ;clear result byte 3
sub m16s2,m16s2 ;clear result byte 2 and carry
ldi mcnt16s,16 ;init loop counter
m16s_1: brcc m16s_2 ;if carry (previous bit) set
add m16s2,mc16sL ; add multiplicand Low to result byte 2
adc m16s3,mc16sH ; add multiplicand High to result byte 3
m16s_2: sbrc mp16sL,0 ;if current bit set
sub m16s2,mc16sL ; sub multiplicand Low from result byte 2
sbrc mp16sL,0 ;if current bit set
sbc m16s3,mc16sH ; sub multiplicand High from result byte 3
asr m16s3 ;shift right result and multiplier
ror m16s2
ror m16s1
ror m16s0
dec mcnt16s ;decrement counter
brne m16s_1 ;if not done, loop more
ret
;***************************************************************************
;*
;* "div8u" - 8/8 Bit Unsigned Division
;*
;* This subroutine divides the two register variables "dd8u" (dividend) and
;* "dv8u" (divisor). The result is placed in "dres8u" and the remainder in
;* "drem8u".
;*
;* Number of words :14
;* Number of cycles :97
;* Low registers used :1 (drem8u)
;* High registers used :3 (dres8u/dd8u,dv8u,dcnt8u)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def drem8u =r15 ;remainder
.def dres8u =r16 ;result
.def dd8u =r16 ;dividend
.def dv8u =r17 ;divisor
.def dcnt8u =r18 ;loop counter
;***** Code
div8u: sub drem8u,drem8u ;clear remainder and carry
ldi dcnt8u,9 ;init loop counter
d8u_1: rol dd8u ;shift left dividend
dec dcnt8u ;decrement counter
brne d8u_2 ;if done
ret ; return
d8u_2: rol drem8u ;shift dividend into remainder
sub drem8u,dv8u ;remainder = remainder - divisor
brcc d8u_3 ;if result negative
add drem8u,dv8u ; restore remainder
clc ; clear carry to be shifted into result
rjmp d8u_1 ;else
d8u_3: sec ; set carry to be shifted into result
rjmp d8u_1
;***************************************************************************
;*
;* "div8s" - 8/8 Bit Signed Division
;*
;* This subroutine divides the two register variables "dd8s" (dividend) and
;* "dv8s" (divisor). The result is placed in "dres8s" and the remainder in
;* "drem8s".
;*
;* Number of words :22
;* Number of cycles :103
;* Low registers used :2 (d8s,drem8s)
;* High registers used :3 (dres8s/dd8s,dv8s,dcnt8s)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def d8s =r14 ;sign register
.def drem8s =r15 ;remainder
.def dres8s =r16 ;result
.def dd8s =r16 ;dividend
.def dv8s =r17 ;divisor
.def dcnt8s =r18 ;loop counter
;***** Code
div8s: mov d8s,dd8s ;move dividend to sign register
eor d8s,dv8s ;xor sign with divisor
sbrc dv8s,7 ;if MSB of divisor set
neg dv8s ; change sign of divisor
sbrc dd8s,7 ;if MSB of dividend set
neg dd8s ; change sign of divisor
sub drem8s,drem8s ;clear remainder and carry
ldi dcnt8s,9 ;init loop counter
d8s_1: rol dd8s ;shift left dividend
dec dcnt8s ;decrement counter
brne d8s_2 ;if done
sbrc d8s,7 ; if MSB of sign register set
neg dres8s ; change sign of result
ret ; return
d8s_2: rol drem8s ;shift dividend into remainder
sub drem8s,dv8s ;remainder = remainder - divisor
brcc d8s_3 ;if result negative
add drem8s,dv8s ; restore remainder
clc ; clear carry to be shifted into result
rjmp d8s_1 ;else
d8s_3: sec ; set carry to be shifted into result
rjmp d8s_1
;***************************************************************************
;*
;* "div16u" - 16/16 Bit Unsigned Division
;*
;* This subroutine divides the two 16-bit numbers
;* "dd8uH:dd8uL" (dividend) and "dv16uH:dv16uL" (divisor).
;* The result is placed in "dres16uH:dres16uL" and the remainder in
;* "drem16uH:drem16uL".
;*
;* Number of words :19
;* Number of cycles :235/251 (Min/Max)
;* Low registers used :2 (drem16uL,drem16uH)
;* High registers used :5 (dres16uL/dd16uL,dres16uH/dd16uH,dv16uL,dv16uH,
;* dcnt16u)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def drem16uL=r14
.def drem16uH=r15
.def dres16uL=r16
.def dres16uH=r17
.def dd16uL =r16
.def dd16uH =r17
.def dv16uL =r18
.def dv16uH =r19
.def dcnt16u =r20
;***** Code
div16u: clr drem16uL ;clear remainder Low byte
sub drem16uH,drem16uH;clear remainder High byte and carry
ldi dcnt16u,17 ;init loop counter
d16u_1: rol dd16uL ;shift left dividend
rol dd16uH
dec dcnt16u ;decrement counter
brne d16u_2 ;if done
ret ; return
d16u_2: rol drem16uL ;shift dividend into remainder
rol drem16uH
sub drem16uL,dv16uL ;remainder = remainder - divisor
sbc drem16uH,dv16uH ;
brcc d16u_3 ;if result negative
add drem16uL,dv16uL ; restore remainder
adc drem16uH,dv16uH
clc ; clear carry to be shifted into result
rjmp d16u_1 ;else
d16u_3: sec ; set carry to be shifted into result
rjmp d16u_1
;***************************************************************************
;*
;* "div16s" - 16/16 Bit Signed Division
;*
;* This subroutine divides signed the two 16 bit numbers
;* "dd16sH:dd16sL" (dividend) and "dv16sH:dv16sL" (divisor).
;* The result is placed in "dres16sH:dres16sL" and the remainder in
;* "drem16sH:drem16sL".
;*
;* Number of words :39
;* Number of cycles :247/263 (Min/Max)
;* Low registers used :3 (d16s,drem16sL,drem16sH)
;* High registers used :7 (dres16sL/dd16sL,dres16sH/dd16sH,dv16sL,dv16sH,
;* dcnt16sH)
;*
;***************************************************************************
;***** Subroutine Register Variables
.def d16s =r13 ;sign register
.def drem16sL=r14 ;remainder low byte
.def drem16sH=r15 ;remainder high byte
.def dres16sL=r16 ;result low byte
.def dres16sH=r17 ;result high byte
.def dd16sL =r16 ;dividend low byte
.def dd16sH =r17 ;dividend high byte
.def dv16sL =r18 ;divisor low byte
.def dv16sH =r19 ;divisor high byte
.def dcnt16s =r20 ;loop counter
;***** Code
div16s: mov d16s,dd16sH ;move dividend High to sign register
eor d16s,dv16sH ;xor divisor High with sign register
sbrs dd16sH,7 ;if MSB in dividend set
rjmp d16s_1
com dd16sH ; change sign of dividend
com dd16sL
subi dd16sL,low(-1)
sbci dd16sL,high(-1)
d16s_1: sbrs dv16sH,7 ;if MSB in divisor set
rjmp d16s_2
com dv16sH ; change sign of divisor
com dv16sL
subi dv16sL,low(-1)
sbci dv16sH,high(-1)
d16s_2: clr drem16sL ;clear remainder Low byte
sub drem16sH,drem16sH;clear remainder High byte and carry
ldi dcnt16s,17 ;init loop counter
d16s_3: rol dd16sL ;shift left dividend
rol dd16sH
dec dcnt16s ;decrement counter
brne d16s_5 ;if done
sbrs d16s,7 ; if MSB in sign register set
rjmp d16s_4
com dres16sH ; change sign of result
com dres16sL
subi dres16sL,low(-1)
sbci dres16sH,high(-1)
d16s_4: ret ; return
d16s_5: rol drem16sL ;shift dividend into remainder
rol drem16sH
sub drem16sL,dv16sL ;remainder = remainder - divisor
sbc drem16sH,dv16sH ;
brcc d16s_6 ;if result negative
add drem16sL,dv16sL ; restore remainder
adc drem16sH,dv16sH
clc ; clear carry to be shifted into result
rjmp d16s_3 ;else
d16s_6: sec ; set carry to be shifted into result
rjmp d16s_3
;****************************************************************************
;*
;* Test Program
;*
;* This program calls all the subroutines as an example of usage and to
;* verify correct verification.
;*
;****************************************************************************
;***** Main Program Register variables
.def temp =r16 ;temporary storage variable
;***** Code
RESET:
;---------------------------------------------------------------
;Include these lines for devices with SRAM
; ldi temp,low(RAMEND)
; out SPL,temp
; ldi temp,high(RAMEND)
; out SPH,temp ;init Stack Pointer
;---------------------------------------------------------------
;***** Multiply Two Unsigned 8-Bit Numbers (250 * 4)
ldi mc8u,250
ldi mp8u,4
rcall mpy8u ;result: m8uH:m8uL = $03e8 (1000)
;***** Multiply Two Signed 8-Bit Numbers (-99 * 88)
ldi mc8s,-99
ldi mp8s,88
rcall mpy8s ;result: m8sH:m8sL = $ddf8 (-8712)
;***** Multiply Two Unsigned 16-Bit Numbers (5050 * 10,000)
ldi mc16uL,low(5050)
ldi mc16uH,high(5050)
ldi mp16uL,low(10000)
ldi mp16uH,high(10000)
rcall mpy16u ;result: m16u3:m16u2:m16u1:m16u0
;=030291a0 (50,500,000)
;***** Multiply Two Signed 16-Bit Numbers (-12345*(-4321))
ldi mc16sL,low(-12345)
ldi mc16sH,high(-12345)
ldi mp16sL,low(-4321)
ldi mp16sH,high(-4321)
rcall mpy16s ;result: m16s3:m16s2:m16s1:m16s0
;=$032df219 (53,342,745)
;***** Divide Two Unsigned 8-Bit Numbers (100/3)
ldi dd8u,100
ldi dv8u,3
rcall div8u ;result: $21 (33)
;remainder: $01 (1)
;***** Divide Two Signed 8-Bit Numbers (-110/-11)
ldi dd8s,-110
ldi dv8s,-11
rcall div8s ;result: $0a (10)
;remainder $00 (0)
;***** Divide Two Unsigned 16-Bit Numbers (50,000/60,000)
ldi dd16uL,low(50000)
ldi dd16uH,high(50000)
ldi dv16uL,low(60000)
ldi dv16uH,high(60000)
rcall div16u ;result: $0000 (0)
;remainder: $c350 (50,000)
;***** Divide Two Signed 16-Bit Numbers (-22,222/10)
ldi dd16sL,low(-22222)
ldi dd16sH,high(-22222)
ldi dv16sL,low(10)
ldi dv16sH,high(10)
rcall div16s ;result: $f752 (-2222)
;remainder: $0002 (2)
forever:rjmp forever
|
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#include <cmath>
#include <eve/constant/valmin.hpp>
#include <eve/constant/valmax.hpp>
int main(int argc, char** argv)
{
auto lmin = eve::valmin(eve::as<EVE_TYPE>());
auto lmax = eve::valmax(eve::as<EVE_TYPE>());
auto const std_is_positive = [](auto x) { return !std::signbit(x); };
EVE_REGISTER_BENCHMARK(std_is_positive, EVE_TYPE
, eve::bench::random<EVE_TYPE>(lmin,lmax));
eve::bench::start_benchmarks(argc, argv);
}
|
Route3_h:
db OVERWORLD ; tileset
db ROUTE_3_HEIGHT, ROUTE_3_WIDTH ; dimensions (y, x)
dw Route3_Blocks ; blocks
dw Route3_TextPointers ; texts
dw Route3_Script ; scripts
db NORTH | WEST ; connections
NORTH_MAP_CONNECTION ROUTE_3, ROUTE_4, 25, 0, Route4_Blocks
WEST_MAP_CONNECTION ROUTE_3, PEWTER_CITY, -3, 1, PewterCity_Blocks
dw Route3_Object ; objects
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Bryce Adelstein-Lelbach
// Copyright (c) 2011-2015 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
#include <hpx/config.hpp>
#include <hpx/hpx_fwd.hpp>
#include <hpx/runtime.hpp>
#include <hpx/exception.hpp>
#include <hpx/runtime/agas/addressing_service.hpp>
#include <hpx/runtime/agas/big_boot_barrier.hpp>
#include <hpx/runtime/agas/component_namespace.hpp>
#include <hpx/runtime/agas/locality_namespace.hpp>
#include <hpx/runtime/agas/primary_namespace.hpp>
#include <hpx/runtime/agas/symbol_namespace.hpp>
#include <hpx/runtime/agas/server/component_namespace.hpp>
#include <hpx/runtime/agas/server/locality_namespace.hpp>
#include <hpx/runtime/agas/server/primary_namespace.hpp>
#include <hpx/runtime/agas/server/symbol_namespace.hpp>
#include <hpx/util/logging.hpp>
#include <hpx/util/runtime_configuration.hpp>
#include <hpx/util/safe_lexical_cast.hpp>
#include <hpx/include/performance_counters.hpp>
#include <hpx/performance_counters/counter_creators.hpp>
#include <hpx/lcos/wait_all.hpp>
#include <hpx/lcos/broadcast.hpp>
#include <boost/format.hpp>
#include <boost/icl/closed_interval.hpp>
#include <boost/lexical_cast.hpp>
namespace hpx { namespace agas
{
struct addressing_service::bootstrap_data_type
{ // {{{
bootstrap_data_type()
: primary_ns_server_()
, locality_ns_server_(&primary_ns_server_)
, component_ns_server_()
, symbol_ns_server_()
{}
void register_counter_types()
{
server::locality_namespace::register_counter_types();
server::locality_namespace::register_global_counter_types();
server::primary_namespace::register_counter_types();
server::primary_namespace::register_global_counter_types();
server::component_namespace::register_counter_types();
server::component_namespace::register_global_counter_types();
server::symbol_namespace::register_counter_types();
server::symbol_namespace::register_global_counter_types();
}
void register_server_instance(char const* servicename)
{
locality_ns_server_.register_server_instance(servicename);
primary_ns_server_.register_server_instance(servicename);
component_ns_server_.register_server_instance(servicename);
symbol_ns_server_.register_server_instance(servicename);
}
void unregister_server_instance(error_code& ec)
{
locality_ns_server_.unregister_server_instance(ec);
if (!ec) primary_ns_server_.unregister_server_instance(ec);
if (!ec) component_ns_server_.unregister_server_instance(ec);
if (!ec) symbol_ns_server_.unregister_server_instance(ec);
}
server::primary_namespace primary_ns_server_;
server::locality_namespace locality_ns_server_;
server::component_namespace component_ns_server_;
server::symbol_namespace symbol_ns_server_;
}; // }}}
struct addressing_service::hosted_data_type
{ // {{{
hosted_data_type()
: primary_ns_server_()
, symbol_ns_server_()
{}
void register_counter_types()
{
server::primary_namespace::register_counter_types();
server::primary_namespace::register_global_counter_types();
server::symbol_namespace::register_counter_types();
server::symbol_namespace::register_global_counter_types();
}
void register_server_instance(char const* servicename
, boost::uint32_t locality_id)
{
primary_ns_server_.register_server_instance(servicename, locality_id);
symbol_ns_server_.register_server_instance(servicename, locality_id);
}
void unregister_server_instance(error_code& ec)
{
primary_ns_server_.unregister_server_instance(ec);
if (!ec) symbol_ns_server_.unregister_server_instance(ec);
}
locality_namespace locality_ns_;
component_namespace component_ns_;
server::primary_namespace primary_ns_server_;
server::symbol_namespace symbol_ns_server_;
}; // }}}
struct addressing_service::gva_cache_key
{ // {{{ gva_cache_key implementation
private:
typedef boost::icl::closed_interval<naming::gid_type, std::less>
key_type;
key_type key_;
public:
gva_cache_key()
: key_()
{}
explicit gva_cache_key(
naming::gid_type const& id_
, boost::uint64_t count_ = 1
)
: key_(naming::detail::get_stripped_gid(id_)
, naming::detail::get_stripped_gid(id_) + (count_ - 1))
{
HPX_ASSERT(count_);
}
naming::gid_type get_gid() const
{
return boost::icl::lower(key_);
}
boost::uint64_t get_count() const
{
naming::gid_type const size = boost::icl::length(key_);
HPX_ASSERT(size.get_msb() == 0);
return size.get_lsb();
}
friend bool operator<(
gva_cache_key const& lhs
, gva_cache_key const& rhs
)
{
return boost::icl::exclusive_less(lhs.key_, rhs.key_);
}
friend bool operator==(
gva_cache_key const& lhs
, gva_cache_key const& rhs
)
{
// Is lhs in rhs?
if (1 == lhs.get_count() && 1 != rhs.get_count())
return boost::icl::contains(rhs.key_, lhs.key_);
// Is rhs in lhs?
else if (1 != lhs.get_count() && 1 == rhs.get_count())
return boost::icl::contains(lhs.key_, rhs.key_);
// Direct hit
return lhs.key_ == rhs.key_;
}
}; // }}}
struct addressing_service::gva_erase_policy
{ // {{{ gva_erase_policy implementation
gva_erase_policy(
naming::gid_type const& id
, boost::uint64_t count
)
: entry(id, count)
{}
typedef std::pair<
gva_cache_key, boost::cache::entries::lfu_entry<gva>
> entry_type;
bool operator()(
entry_type const& p
) const
{
return p.first == entry;
}
gva_cache_key entry;
}; // }}}
addressing_service::addressing_service(
parcelset::parcelhandler& ph
, util::runtime_configuration const& ini_
, runtime_mode runtime_type_
)
: gva_cache_(new gva_cache_type)
, console_cache_(naming::invalid_locality_id)
, max_refcnt_requests_(ini_.get_agas_max_pending_refcnt_requests())
, refcnt_requests_count_(0)
, enable_refcnt_caching_(true)
, refcnt_requests_(new refcnt_requests_type)
, service_type(ini_.get_agas_service_mode())
, runtime_type(runtime_type_)
, caching_(ini_.get_agas_caching_mode())
, range_caching_(caching_ ? ini_.get_agas_range_caching_mode() : false)
, action_priority_(ini_.get_agas_dedicated_server() ?
threads::thread_priority_normal : threads::thread_priority_boost)
, rts_lva_(0)
, mem_lva_(0)
, state_(starting)
, locality_()
{ // {{{
boost::shared_ptr<parcelset::parcelport> pp = ph.get_bootstrap_parcelport();
create_big_boot_barrier(pp ? pp.get() : 0, ph.endpoints(), ini_);
if (caching_)
gva_cache_->reserve(ini_.get_agas_local_cache_size());
if (service_type == service_mode_bootstrap)
{
launch_bootstrap(pp, ph.endpoints(), ini_);
}
} // }}}
void addressing_service::initialize(parcelset::parcelhandler& ph,
boost::uint64_t rts_lva, boost::uint64_t mem_lva)
{ // {{{
rts_lva_ = rts_lva;
mem_lva_ = mem_lva;
// now, boot the parcel port
boost::shared_ptr<parcelset::parcelport> pp = ph.get_bootstrap_parcelport();
if(pp)
pp->run(false);
if (service_type == service_mode_bootstrap)
{
get_big_boot_barrier().wait_bootstrap();
}
else
{
launch_hosted();
get_big_boot_barrier().wait_hosted(
pp->get_locality_name(),
&hosted->primary_ns_server_, &hosted->symbol_ns_server_);
}
set_status(running);
} // }}}
void* addressing_service::get_hosted_primary_ns_ptr() const
{
HPX_ASSERT(0 != hosted.get());
return &hosted->primary_ns_server_;
}
void* addressing_service::get_hosted_symbol_ns_ptr() const
{
HPX_ASSERT(0 != hosted.get());
return &hosted->symbol_ns_server_;
}
void* addressing_service::get_bootstrap_locality_ns_ptr() const
{
HPX_ASSERT(0 != bootstrap.get());
return &bootstrap->locality_ns_server_;
}
void* addressing_service::get_bootstrap_primary_ns_ptr() const
{
HPX_ASSERT(0 != bootstrap.get());
return &bootstrap->primary_ns_server_;
}
void* addressing_service::get_bootstrap_component_ns_ptr() const
{
HPX_ASSERT(0 != bootstrap.get());
return &bootstrap->component_ns_server_;
}
void* addressing_service::get_bootstrap_symbol_ns_ptr() const
{
HPX_ASSERT(0 != bootstrap.get());
return &bootstrap->symbol_ns_server_;
}
namespace detail
{
boost::uint32_t get_number_of_pus_in_cores(boost::uint32_t num_cores);
}
void addressing_service::launch_bootstrap(
boost::shared_ptr<parcelset::parcelport> pp
, parcelset::endpoints_type const & endpoints
, util::runtime_configuration const& ini_
)
{ // {{{
bootstrap = boost::make_shared<bootstrap_data_type>();
runtime& rt = get_runtime();
naming::gid_type const here =
naming::get_gid_from_locality_id(HPX_AGAS_BOOTSTRAP_PREFIX);
// store number of cores used by other processes
boost::uint32_t cores_needed = rt.assign_cores();
boost::uint32_t first_used_core = rt.assign_cores(
pp ? pp->get_locality_name() : "", cores_needed);
util::runtime_configuration& cfg = rt.get_config();
cfg.set_first_used_core(first_used_core);
HPX_ASSERT(pp ? pp->here() == pp->agas_locality(cfg) : true);
rt.assign_cores();
naming::gid_type const locality_gid = bootstrap_locality_namespace_gid();
gva locality_gva(here,
server::locality_namespace::get_component_type(), 1U,
static_cast<void*>(&bootstrap->locality_ns_server_));
locality_ns_addr_ = naming::address(here,
server::locality_namespace::get_component_type(),
static_cast<void*>(&bootstrap->locality_ns_server_));
naming::gid_type const primary_gid = bootstrap_primary_namespace_gid();
gva primary_gva(here,
server::primary_namespace::get_component_type(), 1U,
static_cast<void*>(&bootstrap->primary_ns_server_));
primary_ns_addr_ = naming::address(here,
server::primary_namespace::get_component_type(),
static_cast<void*>(&bootstrap->primary_ns_server_));
naming::gid_type const component_gid = bootstrap_component_namespace_gid();
gva component_gva(here,
server::component_namespace::get_component_type(), 1U,
static_cast<void*>(&bootstrap->component_ns_server_));
component_ns_addr_ = naming::address(here,
server::component_namespace::get_component_type(),
static_cast<void*>(&bootstrap->component_ns_server_));
naming::gid_type const symbol_gid = bootstrap_symbol_namespace_gid();
gva symbol_gva(here,
server::symbol_namespace::get_component_type(), 1U,
static_cast<void*>(&bootstrap->symbol_ns_server_));
symbol_ns_addr_ = naming::address(here,
server::symbol_namespace::get_component_type(),
static_cast<void*>(&bootstrap->symbol_ns_server_));
set_local_locality(here);
rt.get_config().parse("assigned locality",
boost::str(boost::format("hpx.locality!=%1%")
% naming::get_locality_id_from_gid(here)));
boost::uint32_t num_threads = hpx::util::get_entry_as<boost::uint32_t>(
ini_, "hpx.os_threads", 1u);
request locality_req(locality_ns_allocate, endpoints, 4, num_threads); //-V112
bootstrap->locality_ns_server_.remote_service(locality_req);
naming::gid_type runtime_support_gid1(here);
runtime_support_gid1.set_lsb(rt.get_runtime_support_lva());
naming::gid_type runtime_support_gid2(here);
runtime_support_gid2.set_lsb(boost::uint64_t(0));
gva runtime_support_address(here
, components::get_component_type<components::server::runtime_support>()
, 1U, rt.get_runtime_support_lva());
request reqs[] =
{
request(primary_ns_bind_gid, locality_gid, locality_gva
, naming::get_locality_from_gid(locality_gid))
, request(primary_ns_bind_gid, primary_gid, primary_gva
, naming::get_locality_from_gid(primary_gid))
, request(primary_ns_bind_gid, component_gid, component_gva
, naming::get_locality_from_gid(component_gid))
, request(primary_ns_bind_gid, symbol_gid, symbol_gva
, naming::get_locality_from_gid(symbol_gid))
};
for (std::size_t i = 0; i < (sizeof(reqs) / sizeof(request)); ++i)
bootstrap->primary_ns_server_.remote_service(reqs[i]);
register_name("/0/agas/locality#0", here);
if (is_console())
register_name("/0/locality#console", here);
naming::gid_type lower, upper;
get_id_range(HPX_INITIAL_GID_RANGE, lower, upper);
rt.get_id_pool().set_range(lower, upper);
} // }}}
void addressing_service::launch_hosted()
{
hosted = boost::make_shared<hosted_data_type>();
}
void addressing_service::adjust_local_cache_size()
{ // {{{
// adjust the local AGAS cache size for the number of connected localities
if (caching_)
{
util::runtime_configuration const& cfg = get_runtime().get_config();
std::size_t local_cache_size = cfg.get_agas_local_cache_size();
std::size_t local_cache_size_per_thread =
cfg.get_agas_local_cache_size_per_thread();
std::size_t cache_size = (std::max)(local_cache_size,
local_cache_size_per_thread * std::size_t(get_num_overall_threads()));
if (cache_size > gva_cache_->capacity())
gva_cache_->reserve(cache_size);
LAGAS_(info) << (boost::format(
"addressing_service::adjust_local_cache_size, local_cache_size(%1%), "
"local_cache_size_per_thread(%2%), cache_size(%3%)")
% local_cache_size % local_cache_size_per_thread % cache_size);
}
} // }}}
void addressing_service::set_local_locality(naming::gid_type const& g)
{
locality_ = g;
if (is_bootstrap())
bootstrap->primary_ns_server_.set_local_locality(g);
else
hosted->primary_ns_server_.set_local_locality(g);
}
response addressing_service::service(
request const& req
, error_code& ec
)
{ // {{{
if (req.get_action_code() & primary_ns_service)
{
if (is_bootstrap())
return bootstrap->primary_ns_server_.service(req, ec);
return hosted->primary_ns_server_.service(req, ec);
}
else if (req.get_action_code() & component_ns_service)
{
if (is_bootstrap())
return bootstrap->component_ns_server_.service(req, ec);
return hosted->component_ns_.service(req, action_priority_, ec);
}
else if (req.get_action_code() & symbol_ns_service)
{
if (is_bootstrap())
return bootstrap->symbol_ns_server_.service(req, ec);
return hosted->symbol_ns_server_.service(req, ec);
}
else if (req.get_action_code() & locality_ns_service)
{
if (is_bootstrap())
return bootstrap->locality_ns_server_.service(req, ec);
return hosted->locality_ns_.service(req, action_priority_, ec);
}
HPX_THROWS_IF(ec, bad_action_code
, "addressing_service::service"
, "invalid action code encountered in request")
return response();
} // }}}
std::vector<response> addressing_service::bulk_service(
std::vector<request> const& req
, error_code& ec
)
{ // {{{
// FIXME: For now, we just send it to the primary namespace, assuming that
// most requests will end up there anyways. The primary namespace will
// route the requests to other namespaces (and the other namespaces would
// also route requests intended for the primary namespace).
if (is_bootstrap())
return bootstrap->primary_ns_server_.bulk_service(req, ec);
return hosted->primary_ns_server_.bulk_service(req, ec);
} // }}}
bool addressing_service::register_locality(
parcelset::endpoints_type const & endpoints
, naming::gid_type& prefix
, boost::uint32_t num_threads
, error_code& ec
)
{ // {{{
try {
request req(locality_ns_allocate, endpoints, 0, num_threads, prefix);
response rep;
if (is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return false;
prefix = naming::get_gid_from_locality_id(rep.get_locality_id());
{
mutex_type::scoped_lock l(resolved_localities_mtx_);
std::pair<resolved_localities_type::iterator, bool> res
= resolved_localities_.insert(std::make_pair(
prefix
, endpoints
));
HPX_ASSERT(res.second);
}
return true;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::register_locality");
return false;
}
} // }}}
void addressing_service::register_console(parcelset::endpoints_type const & eps)
{
mutex_type::scoped_lock l(resolved_localities_mtx_);
std::pair<resolved_localities_type::iterator, bool> res
= resolved_localities_.insert(std::make_pair(
naming::get_gid_from_locality_id(0)
, eps
));
HPX_ASSERT(res.second);
}
parcelset::endpoints_type const & addressing_service::resolve_locality(
naming::gid_type const & gid
, error_code& ec
)
{ // {{{
mutex_type::scoped_lock l(resolved_localities_mtx_);
resolved_localities_type::iterator it = resolved_localities_.find(gid);
if(it == resolved_localities_.end())
{
// The locality hasn't been requested to be resolved yet. Do it now.
parcelset::endpoints_type endpoints;
request req(locality_ns_resolve_locality, gid);
if(is_bootstrap())
{
endpoints
= bootstrap->locality_ns_server_.service(req, ec).get_endpoints();
if(ec)
{
HPX_THROWS_IF(ec, internal_server_error
, "addressing_service::resolve_locality"
, "could not resolve locality to endpoints");
return resolved_localities_[naming::invalid_gid];
}
}
else
{
{
hpx::util::scoped_unlock<mutex_type::scoped_lock> ul(l);
future<parcelset::endpoints_type> endpoints_future =
hosted->locality_ns_.service_async<parcelset::endpoints_type>(
req
, action_priority_
);
if (0 == threads::get_self_ptr())
{
// this should happen only during bootstrap
// FIXME: Disabled this assert cause it fires. It should not, but doesn't do any harm
//HPX_ASSERT(hpx::is_starting());
while(!endpoints_future.is_ready())
/**/;
}
endpoints = endpoints_future.get(ec);
}
// Search again ... might have been added by a different thread already
it = resolved_localities_.find(gid);
}
if(it == resolved_localities_.end())
{
if(HPX_UNLIKELY(!util::insert_checked(resolved_localities_.insert(
std::make_pair(
gid
, endpoints
)
), it)))
{
HPX_THROWS_IF(ec, internal_server_error
, "addressing_service::resolve_locality"
, "resolved locality insertion failed "
"due to a locking error or memory corruption");
return resolved_localities_[naming::invalid_gid];
}
}
}
return it->second;
} // }}}
// TODO: We need to ensure that the locality isn't unbound while it still holds
// referenced objects.
bool addressing_service::unregister_locality(
naming::gid_type const & gid
, error_code& ec
)
{ // {{{
try {
request req(locality_ns_free, gid);
response rep;
if (is_bootstrap())
bootstrap->unregister_server_instance(ec);
else
hosted->unregister_server_instance(ec);
if (ec)
return false;
if (is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return false;
{
mutex_type::scoped_lock l(resolved_localities_mtx_);
resolved_localities_type::iterator it = resolved_localities_.find(gid);
if(it != resolved_localities_.end())
resolved_localities_.erase(it);
}
return true;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::unregister_locality");
return false;
}
} // }}}
bool addressing_service::get_console_locality(
naming::gid_type& prefix
, error_code& ec
)
{ // {{{
try {
if (get_status() != running)
{
if (&ec != &throws)
ec = make_success_code();
return false;
}
if (is_console())
{
prefix = get_local_locality();
if (&ec != &throws)
ec = make_success_code();
return true;
}
{
mutex_type::scoped_lock lock(console_cache_mtx_);
if (console_cache_ != naming::invalid_locality_id)
{
prefix = naming::get_gid_from_locality_id(console_cache_);
if (&ec != &throws)
ec = make_success_code();
return true;
}
}
std::string key("/0/locality#console");
request req(symbol_ns_resolve, key);
response rep;
if (is_bootstrap())
rep = bootstrap->symbol_ns_server_.service(req, ec);
else
rep = stubs::symbol_namespace::service(key, req, action_priority_, ec);
if (!ec && (rep.get_gid() != naming::invalid_gid) &&
(rep.get_status() == success))
{
prefix = rep.get_gid();
boost::uint32_t console = naming::get_locality_id_from_gid(prefix);
{
mutex_type::scoped_lock lock(console_cache_mtx_);
if (console_cache_ == naming::invalid_locality_id) {
console_cache_ = console;
}
else {
HPX_ASSERT(console_cache_ == console);
}
}
LAGAS_(debug) <<
( boost::format(
"addressing_server::get_console_locality, "
"caching console locality, prefix(%1%)")
% console);
return true;
}
return false;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_console_locality");
return false;
}
} // }}}
bool addressing_service::get_localities(
std::vector<naming::gid_type>& locality_ids
, components::component_type type
, error_code& ec
)
{ // {{{ get_locality_ids implementation
try {
if (type != components::component_invalid)
{
request req(component_ns_resolve_id, type);
response rep;
if (is_bootstrap())
rep = bootstrap->component_ns_server_.service(req, ec);
else
rep = hosted->component_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return false;
const std::vector<boost::uint32_t> p = rep.get_localities();
if (!p.size())
return false;
locality_ids.clear();
for (std::size_t i = 0; i < p.size(); ++i)
locality_ids.push_back(naming::get_gid_from_locality_id(p[i]));
return true;
}
else
{
request req(locality_ns_localities);
response rep;
if (is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return false;
const std::vector<boost::uint32_t> p = rep.get_localities();
if (!p.size())
return false;
locality_ids.clear();
for (std::size_t i = 0; i < p.size(); ++i)
locality_ids.push_back(naming::get_gid_from_locality_id(p[i]));
return true;
}
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_locality_ids");
return false;
}
} // }}}
std::map<naming::gid_type, parcelset::endpoints_type>
addressing_service::get_resolved_localities(error_code& ec)
{ // {{{ get_resolved_localities_async implementation
request req(locality_ns_resolved_localities);
response rep;
if(is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if(ec || success != rep.get_status())
{
HPX_THROWS_IF(ec, internal_server_error
, "addressing_service::get_reolved_localities"
, "unable to received resolved the locality endpoints");
return std::map<naming::gid_type, parcelset::endpoints_type>();
}
return rep.get_resolved_localities();
} //}}}
///////////////////////////////////////////////////////////////////////////////
boost::uint32_t addressing_service::get_num_localities(
components::component_type type
, error_code& ec
)
{ // {{{ get_num_localities implementation
try {
if (type == components::component_invalid)
{
request req(locality_ns_num_localities, type);
response rep;
if (is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return boost::uint32_t(-1);
return rep.get_num_localities();
}
request req(component_ns_num_localities, type);
response rep;
if (is_bootstrap())
rep = bootstrap->component_ns_server_.service(req, ec);
else
rep = hosted->component_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return boost::uint32_t(-1);
return rep.get_num_localities();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_num_localities");
}
return boost::uint32_t(-1);
} // }}}
lcos::future<boost::uint32_t> addressing_service::get_num_localities_async(
components::component_type type
)
{ // {{{ get_num_localities implementation
if (type == components::component_invalid)
{
naming::id_type const target = bootstrap_locality_namespace_id();
request req(locality_ns_num_localities, type);
return stubs::locality_namespace::service_async<boost::uint32_t>(target, req);
}
naming::id_type const target = bootstrap_component_namespace_id();
request req(component_ns_num_localities, type);
return stubs::component_namespace::service_async<boost::uint32_t>(target, req);
} // }}}
///////////////////////////////////////////////////////////////////////////////
boost::uint32_t addressing_service::get_num_overall_threads(
error_code& ec
)
{ // {{{ get_num_overall_threads implementation
try {
request req(locality_ns_num_threads);
response rep;
if (is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return boost::uint32_t(0);
return rep.get_num_overall_threads();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_num_overall_threads");
}
return boost::uint32_t(0);
} // }}}
lcos::future<boost::uint32_t> addressing_service::get_num_overall_threads_async()
{ // {{{
naming::id_type const target = bootstrap_locality_namespace_id();
request req(locality_ns_num_threads);
return stubs::locality_namespace::service_async<boost::uint32_t>(target, req);
} // }}}
std::vector<boost::uint32_t> addressing_service::get_num_threads(
error_code& ec
)
{ // {{{ get_num_threads implementation
try {
request req(locality_ns_num_threads);
response rep;
if (is_bootstrap())
rep = bootstrap->locality_ns_server_.service(req, ec);
else
rep = hosted->locality_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return std::vector<boost::uint32_t>();
return rep.get_num_threads();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_num_threads");
}
return std::vector<boost::uint32_t>();
} // }}}
lcos::future<std::vector<boost::uint32_t> > addressing_service::get_num_threads_async()
{ // {{{
naming::id_type const target = bootstrap_locality_namespace_id();
request req(locality_ns_num_threads);
return stubs::locality_namespace::service_async<
std::vector<boost::uint32_t> >(target, req);
} // }}}
///////////////////////////////////////////////////////////////////////////////
components::component_type addressing_service::get_component_id(
std::string const& name
, error_code& ec
)
{ /// {{{
try {
request req(component_ns_bind_name, name);
response rep;
if (is_bootstrap())
rep = bootstrap->component_ns_server_.service(req, ec);
else
rep = hosted->component_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status()))
return components::component_invalid;
return rep.get_component_type();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_component_id");
return components::component_invalid;
}
} // }}}
void addressing_service::iterate_types(
iterate_types_function_type const& f
, error_code& ec
)
{ // {{{
try {
request req(component_ns_iterate_types, f);
if (is_bootstrap())
bootstrap->component_ns_server_.service(req, ec);
else
hosted->component_ns_.service(req, action_priority_, ec);
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::iterate_types");
}
} // }}}
std::string addressing_service::get_component_type_name(
components::component_type id
, error_code& ec
)
{ // {{{
try {
request req(component_ns_get_component_type_name, id);
response rep;
if (is_bootstrap())
rep = bootstrap->component_ns_server_.service(req, ec);
else
rep = hosted->component_ns_.service(req, action_priority_, ec);
return rep.get_component_typename();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::iterate_types");
}
return "<unknown>";
} // }}}
components::component_type addressing_service::register_factory(
boost::uint32_t prefix
, std::string const& name
, error_code& ec
)
{ // {{{
try {
request req(component_ns_bind_prefix, name, prefix);
response rep;
if (is_bootstrap())
rep = bootstrap->component_ns_server_.service(req, ec);
else
rep = hosted->component_ns_.service(req, action_priority_, ec);
if (ec || (success != rep.get_status() && no_success != rep.get_status()))
return components::component_invalid;
return rep.get_component_type();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::register_factory");
return components::component_invalid;
}
} // }}}
///////////////////////////////////////////////////////////////////////////////
bool addressing_service::get_id_range(
boost::uint64_t count
, naming::gid_type& lower_bound
, naming::gid_type& upper_bound
, error_code& ec
)
{ // {{{ get_id_range implementation
try {
// parcelset::endpoints_type() is an obsolete, dummy argument
request req(primary_ns_allocate
, parcelset::endpoints_type()
, count
, boost::uint32_t(-1));
response rep;
if (is_bootstrap())
rep = bootstrap->primary_ns_server_.service(req, ec);
else
rep = hosted->primary_ns_server_.service(req, ec);
error const s = rep.get_status();
if (ec || (success != s && repeated_request != s))
return false;
lower_bound = rep.get_lower_bound();
upper_bound = rep.get_upper_bound();
return success == s;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::get_id_range");
return false;
}
} // }}}
bool addressing_service::bind_range_local(
naming::gid_type const& lower_id
, boost::uint64_t count
, naming::address const& baseaddr
, boost::uint64_t offset
, error_code& ec
)
{ // {{{ bind_range implementation
try {
naming::gid_type const& prefix = baseaddr.locality_;
// Create a global virtual address from the legacy calling convention
// parameters
gva const g(prefix, baseaddr.type_, count, baseaddr.address_, offset);
request req(primary_ns_bind_gid, lower_id, g,
naming::get_locality_from_gid(lower_id));
response rep;
if (is_bootstrap())
rep = bootstrap->primary_ns_server_.service(req, ec);
else
rep = hosted->primary_ns_server_.service(req, ec);
error const s = rep.get_status();
if (ec || (success != s && repeated_request != s))
return false;
if(range_caching_)
{
// Put the range into the cache.
update_cache_entry(lower_id, g, ec);
}
else
{
// Only put the first GID in the range into the cache
gva const first_g = g.resolve(lower_id, lower_id);
update_cache_entry(lower_id, first_g, ec);
}
if (ec)
return false;
return true;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::bind_range_local");
return false;
}
} // }}}
bool addressing_service::bind_postproc(
future<response> f, naming::gid_type const& lower_id, gva const& g
)
{
response rep = f.get();
error const s = rep.get_status();
if (success != s && repeated_request != s)
return false;
if(range_caching_)
{
// Put the range into the cache.
update_cache_entry(lower_id, g);
}
else
{
// Only put the first GID in the range into the cache
gva const first_g = g.resolve(lower_id, lower_id);
update_cache_entry(lower_id, first_g);
}
return true;
}
hpx::future<bool> addressing_service::bind_range_async(
naming::gid_type const& lower_id
, boost::uint64_t count
, naming::address const& baseaddr
, boost::uint64_t offset
, naming::gid_type const& locality
)
{
// ask server
naming::gid_type const& prefix = baseaddr.locality_;
// Create a global virtual address from the legacy calling convention
// parameters.
gva const g(prefix, baseaddr.type_, count, baseaddr.address_, offset);
naming::id_type target(
stubs::primary_namespace::get_service_instance(lower_id)
, naming::id_type::unmanaged);
request req(primary_ns_bind_gid, lower_id, g, locality);
response rep;
using util::placeholders::_1;
future<response> f =
stubs::primary_namespace::service_async<response>(target, req);
return f.then(
util::bind(&addressing_service::bind_postproc, this, _1, lower_id, g)
);
}
bool addressing_service::unbind_range_local(
naming::gid_type const& lower_id
, boost::uint64_t count
, naming::address& addr
, error_code& ec
)
{ // {{{ unbind_range implementation
try {
request req(primary_ns_unbind_gid, lower_id, count);
response rep;
// if (get_status() == running &&
// naming::get_locality_id_from_gid(lower_id) !=
// naming::get_locality_id_from_gid(locality_))
// {
// naming::id_type target(
// stubs::primary_namespace::get_service_instance(lower_id)
// , naming::id_type::unmanaged);
//
// rep = stubs::primary_namespace::service(
// target, req, threads::thread_priority_default, ec);
// }
// else
if (is_bootstrap())
rep = bootstrap->primary_ns_server_.service(req, ec);
else
rep = hosted->primary_ns_server_.service(req, ec);
if (ec || (success != rep.get_status()))
return false;
// I'm afraid that this will break the first form of paged caching,
// so it's commented out for now.
//cache_mutex_type::scoped_lock lock(hosted->gva_cache_mtx_);
//gva_erase_policy ep(lower_id, count);
//hosted->gva_cache_->erase(ep);
gva const& gaddr = rep.get_gva();
addr.locality_ = gaddr.prefix;
addr.type_ = gaddr.type;
addr.address_ = gaddr.lva();
return true;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::unbind_range_local");
return false;
}
} // }}}
/// This function will test whether the given address refers to an object
/// living on the locality of the caller. We rely completely on the local AGAS
/// cache and local AGAS instance, assuming that everything which is not in
/// the cache is not local.
// bool addressing_service::is_local_address(
// naming::gid_type const& id
// , naming::address& addr
// , error_code& ec
// )
// {
// // Resolve the address of the GID.
//
// // NOTE: We do not throw here for a reason; it is perfectly valid for the
// // GID to not be found in the local AGAS instance.
// if (!resolve(id, addr, ec) || ec)
// return false;
//
// return addr.locality_ == get_here();
// }
bool addressing_service::is_local_address_cached(
naming::gid_type const& id
, naming::address& addr
, error_code& ec
)
{
// Try to resolve the address of the GID from the locally available
// information.
// NOTE: We do not throw here for a reason; it is perfectly valid for the
// GID to not be found in the cache.
if (!resolve_cached(id, addr, ec) || ec)
{
if (ec) return false;
// try also the local part of AGAS before giving up
if (!resolve_full_local(id, addr, ec) || ec)
return false;
}
return addr.locality_ == get_local_locality();
}
// Return true if at least one address is local.
// bool addressing_service::is_local_address(
// naming::gid_type const* gids
// , naming::address* addrs
// , std::size_t size
// , boost::dynamic_bitset<>& locals
// , error_code& ec
// )
// {
// // Try the cache
// if (caching_)
// {
// bool all_resolved = resolve_cached(gids, addrs, size, locals, ec);
// if (ec)
// return false;
// if (all_resolved)
// return locals.any(); // all destinations resolved
// }
//
// if (!resolve_full(gids, addrs, size, locals, ec) || ec)
// return false;
//
// return locals.any();
// }
bool addressing_service::is_local_lva_encoded_address(
boost::uint64_t msb
)
{
// NOTE: This should still be migration safe.
return naming::detail::strip_internal_bits_from_gid(msb) ==
get_local_locality().get_msb();
}
bool addressing_service::resolve_locally_known_addresses(
naming::gid_type const& id
, naming::address& addr
)
{
// LVA-encoded GIDs (located on this machine)
boost::uint64_t lsb = id.get_lsb();
boost::uint64_t msb = naming::detail::strip_internal_bits_from_gid(id.get_msb());
if (is_local_lva_encoded_address(msb))
{
addr.locality_ = get_local_locality();
// An LSB of 0 references the runtime support component
HPX_ASSERT(rts_lva_);
if (0 == lsb || lsb == rts_lva_)
{
addr.type_ = components::component_runtime_support;
addr.address_ = rts_lva_;
}
else
{
HPX_ASSERT(mem_lva_);
addr.type_ = components::component_memory;
addr.address_ = mem_lva_;
}
return true;
}
// authoritative AGAS component address resolution
if (HPX_AGAS_LOCALITY_NS_MSB == msb && HPX_AGAS_LOCALITY_NS_LSB == lsb)
{
addr = locality_ns_addr_;
return true;
}
if (HPX_AGAS_PRIMARY_NS_MSB == msb && HPX_AGAS_PRIMARY_NS_LSB == lsb)
{
addr = primary_ns_addr_;
return true;
}
if (HPX_AGAS_COMPONENT_NS_MSB == msb && HPX_AGAS_COMPONENT_NS_LSB == lsb)
{
addr = component_ns_addr_;
return true;
}
if (HPX_AGAS_SYMBOL_NS_MSB == msb && HPX_AGAS_SYMBOL_NS_LSB == lsb)
{
addr = symbol_ns_addr_;
return true;
}
return false;
} // }}}
bool addressing_service::resolve_full_local(
naming::gid_type const& id
, naming::address& addr
, error_code& ec
)
{ // {{{ resolve implementation
try {
// special cases
if (resolve_locally_known_addresses(id, addr))
return true;
request req(primary_ns_resolve_gid, id);
response rep;
if (is_bootstrap())
rep = bootstrap->primary_ns_server_.service(req, ec);
else
rep = hosted->primary_ns_server_.service(req, ec);
if (ec || (success != rep.get_status()))
return false;
// Resolve the gva to the real resolved address (which is just a gva
// with as fully resolved LVA and an offset of zero).
naming::gid_type base_gid = rep.get_base_gid();
gva const base_gva = rep.get_gva();
gva const g = base_gva.resolve(id, base_gid);
addr.locality_ = g.prefix;
addr.type_ = g.type;
addr.address_ = g.lva();
if (addr.address_)
{
if(range_caching_)
{
// Put the range into the cache.
update_cache_entry(base_gid, base_gva, ec);
}
else
{
// Put the fully resolved gva into the cache.
update_cache_entry(id, g, ec);
}
}
else
{
remove_cache_entry(id, ec);
}
if (ec)
return false;
if (&ec != &throws)
ec = make_success_code();
return true;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::resolve_full_local");
return false;
}
} // }}}
bool addressing_service::resolve_cached(
naming::gid_type const& id
, naming::address& addr
, error_code& ec
)
{ // {{{ resolve_cached implementation
// special cases
if (resolve_locally_known_addresses(id, addr))
return true;
if (ec) return false;
// If caching is disabled, bail
if (!caching_)
{
if (&ec != &throws)
ec = make_success_code();
return false;
}
// first look up the requested item in the cache
gva_cache_key k(id);
gva_cache_key idbase;
gva_cache_type::entry_type e;
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
// force routing if target object was migrated
if (was_object_migrated_locked(id))
return false;
// Check if the entry is currently in the cache
if (gva_cache_->get_entry(k, idbase, e))
{
const boost::uint64_t id_msb =
naming::detail::strip_internal_bits_from_gid(id.get_msb());
if (HPX_UNLIKELY(id_msb != idbase.get_gid().get_msb()))
{
HPX_THROWS_IF(ec, internal_server_error
, "addressing_service::resolve_cached"
, "bad entry in cache, MSBs of GID base and GID do not match");
return false;
}
gva const& g = e.get();
addr.locality_ = g.prefix;
addr.type_ = g.type;
addr.address_ = g.lva(id, idbase.get_gid());
lock.unlock();
if (&ec != &throws)
ec = make_success_code();
/*
LAGAS_(debug) <<
( boost::format(
"addressing_service::resolve_cached, "
"cache hit for address %1%, lva %2% (base %3%, lva %4%)")
% id
% reinterpret_cast<void*>(addr.address_)
% idbase.get_gid()
% reinterpret_cast<void*>(g.lva()));
*/
return true;
}
if (&ec != &throws)
ec = make_success_code();
LAGAS_(debug) <<
( boost::format(
"addressing_service::resolve_cached, "
"cache miss for address %1%")
% id);
return false;
} // }}}
hpx::future<naming::address> addressing_service::resolve_async(
naming::gid_type const& gid
)
{
if (!gid)
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::resolve_async",
"invalid reference id");
return make_ready_future(naming::address());
}
// Try the cache.
if (caching_)
{
naming::address addr;
error_code ec;
if (resolve_cached(gid, addr, ec))
return make_ready_future(addr);
if (ec)
{
return hpx::make_exceptional_future<naming::address>(
hpx::detail::access_exception(ec));
}
}
// now try the AGAS service
return resolve_full_async(gid);
}
hpx::future<naming::id_type> addressing_service::get_colocation_id_async(
naming::id_type const& id
)
{
if (!id)
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::get_colocation_id_async",
"invalid reference id");
return make_ready_future(naming::invalid_id);
}
agas::request req(agas::primary_ns_resolve_gid, id.get_gid());
naming::id_type service_target(
agas::stubs::primary_namespace::get_service_instance(id.get_gid())
, naming::id_type::unmanaged);
return stubs::primary_namespace::service_async<naming::id_type>(
service_target, req);
}
///////////////////////////////////////////////////////////////////////////////
naming::address addressing_service::resolve_full_postproc(
future<response> f, naming::gid_type const& id
)
{
naming::address addr;
response rep = f.get();
if (success != rep.get_status())
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::resolve_full_postproc",
"could no resolve global id");
return addr;
}
// Resolve the gva to the real resolved address (which is just a gva
// with as fully resolved LVA and and offset of zero).
naming::gid_type base_gid = rep.get_base_gid();
gva const base_gva = rep.get_gva();
gva const g = base_gva.resolve(id, base_gid);
addr.locality_ = g.prefix;
addr.type_ = g.type;
addr.address_ = g.lva();
if(range_caching_)
{
// Put the range into the cache.
update_cache_entry(base_gid, base_gva);
}
else
{
// Put the fully resolved gva into the cache.
update_cache_entry(id, g);
}
return addr;
}
hpx::future<naming::address> addressing_service::resolve_full_async(
naming::gid_type const& gid
)
{
if (!gid)
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::resolve_full_async",
"invalid reference id");
return make_ready_future(naming::address());
}
// handle special cases
naming::address addr;
if (resolve_locally_known_addresses(gid, addr))
return make_ready_future(addr);
// ask server
request req(primary_ns_resolve_gid, gid);
naming::id_type target(
stubs::primary_namespace::get_service_instance(gid)
, naming::id_type::unmanaged);
using util::placeholders::_1;
future<response> f =
stubs::primary_namespace::service_async<response>(target, req);
return f.then(
util::bind(&addressing_service::resolve_full_postproc, this, _1, gid)
);
}
///////////////////////////////////////////////////////////////////////////////
bool addressing_service::resolve_full_local(
naming::gid_type const* gids
, naming::address* addrs
, std::size_t count
, boost::dynamic_bitset<>& locals
, error_code& ec
)
{
locals.resize(count);
try {
std::vector<request> reqs;
reqs.reserve(count);
// special cases
for (std::size_t i = 0; i != count; ++i)
{
if (!addrs[i])
{
bool is_local = resolve_locally_known_addresses(gids[i], addrs[i]);
locals.set(i, is_local);
}
else
{
locals.set(i, true);
}
if (!addrs[i] && !locals.test(i))
{
reqs.push_back(request(primary_ns_resolve_gid, gids[i]));
}
}
if (reqs.empty()) {
// all gids have been resolved
if (&ec != &throws)
ec = make_success_code();
return true;
}
std::vector<response> reps;
if (is_bootstrap())
reps = bootstrap->primary_ns_server_.bulk_service(reqs, ec);
else
reps = hosted->primary_ns_server_.bulk_service(reqs, ec);
if (ec)
return false;
std::size_t j = 0;
for (std::size_t i = 0; i != count; ++i)
{
if (addrs[i] || locals.test(i))
continue;
HPX_ASSERT(j < reps.size());
if (success != reps[j].get_status())
return false;
// Resolve the gva to the real resolved address (which is just a gva
// with as fully resolved LVA and and offset of zero).
naming::gid_type base_gid = reps[j].get_base_gid();
gva const base_gva = reps[j].get_gva();
gva const g = base_gva.resolve(gids[i], base_gid);
naming::address& addr = addrs[i];
addr.locality_ = g.prefix;
addr.type_ = g.type;
addr.address_ = g.lva();
if(range_caching_)
{
// Put the range into the cache.
update_cache_entry(base_gid, base_gva, ec);
}
else
{
// Put the fully resolved gva into the cache.
update_cache_entry(gids[i], g, ec);
}
if (ec)
return false;
++j;
}
if (&ec != &throws)
ec = make_success_code();
return true;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::resolve_full");
return false;
}
}
bool addressing_service::resolve_cached(
naming::gid_type const* gids
, naming::address* addrs
, std::size_t count
, boost::dynamic_bitset<>& locals
, error_code& ec
)
{
locals.resize(count);
std::size_t resolved = 0;
for (std::size_t i = 0; i != count; ++i)
{
if (!addrs[i] && !locals.test(i))
{
bool was_resolved = resolve_cached(gids[i], addrs[i], ec);
if (ec)
return false;
if (was_resolved)
++resolved;
if (addrs[i].locality_ == get_local_locality())
locals.set(i, true);
}
else if (addrs[i].locality_ == get_local_locality())
{
++resolved;
locals.set(i, true);
}
}
return resolved == count; // returns whether all have been resolved
}
///////////////////////////////////////////////////////////////////////////////
void addressing_service::route(
parcelset::parcel const& p
, util::function_nonser<void(boost::system::error_code const&,
parcelset::parcel const&)> const& f
)
{
// compose request
request req(primary_ns_route, p);
naming::id_type const* ids = p.get_destinations();
naming::id_type const target(
stubs::primary_namespace::get_service_instance(ids[0])
, naming::id_type::unmanaged);
typedef server::primary_namespace::service_action action_type;
// Determine whether the gid is local or remote
naming::address addr;
if (is_local_address_cached(target.get_gid(), addr))
{
// route through the local AGAS service instance
applier::detail::apply_l_p<action_type>(
target, addr, action_priority_, req);
f(boost::system::error_code(), parcelset::parcel()); // invoke callback
return;
}
// apply remotely, route through main AGAS service if the destination is
// a service instance
if (!addr)
{
if (stubs::primary_namespace::is_service_instance(ids[0]) ||
stubs::symbol_namespace::is_service_instance(ids[0]))
{
// construct wrapper parcel
naming::id_type const route_target(
bootstrap_primary_namespace_gid(), naming::id_type::unmanaged);
parcelset::parcel route_p(
route_target, primary_ns_addr_
, new hpx::actions::transfer_action<action_type>(action_priority_,
req));
// send to the main AGAS instance for routing
hpx::applier::get_applier().get_parcel_handler().put_parcel(route_p, f);
return;
}
}
// apply directly as we have the resolved destination address
applier::detail::apply_r_p_cb<action_type>(std::move(addr), target,
action_priority_, f, req);
}
///////////////////////////////////////////////////////////////////////////////
// The parameter 'compensated_credit' holds the amount of credits to be added
// to the acknowledged number of credits. The compensated credits are non-zero
// if there was a pending decref request at the point when the incref was sent.
// The pending decref was subtracted from the amount of credits to incref.
boost::int64_t addressing_service::synchronize_with_async_incref(
hpx::future<boost::int64_t> fut
, naming::id_type const& id
, boost::int64_t compensated_credit
)
{
return fut.get() + compensated_credit;
}
lcos::future<boost::int64_t> addressing_service::incref_async(
naming::gid_type const& gid
, boost::int64_t credit
, naming::id_type const& keep_alive
)
{ // {{{ incref implementation
if (HPX_UNLIKELY(0 == threads::get_self_ptr()))
{
// reschedule this call as an HPX thread
lcos::future<boost::int64_t> (
addressing_service::*incref_async_ptr)(
naming::gid_type const&
, boost::int64_t
, naming::id_type const&
) = &addressing_service::incref_async;
return async(incref_async_ptr, this, gid, credit, keep_alive);
}
if (HPX_UNLIKELY(0 >= credit))
{
HPX_THROW_EXCEPTION(bad_parameter
, "addressing_service::incref_async"
, boost::str(boost::format("invalid credit count of %1%") % credit));
return lcos::future<boost::int64_t>();
}
HPX_ASSERT(keep_alive != naming::invalid_id);
typedef refcnt_requests_type::value_type mapping;
// Some examples of calculating the compensated credits below
//
// case pending credits remaining sent to compensated
// no decref decrefs AGAS credits
// ------+---------+---------+------------+--------+-------------
// 1 0 10 0 0 10
// 2 10 9 1 0 10
// 3 10 10 0 0 10
// 4 10 11 0 1 10
std::pair<naming::gid_type, boost::int64_t> pending_incref;
bool has_pending_incref = false;
boost::int64_t pending_decrefs = 0;
{
mutex_type::scoped_lock l(refcnt_requests_mtx_);
typedef refcnt_requests_type::iterator iterator;
naming::gid_type raw = naming::detail::get_stripped_gid(gid);
iterator matches = refcnt_requests_->find(raw);
if (matches != refcnt_requests_->end())
{
pending_decrefs = matches->second;
matches->second += credit;
// Increment requests need to be handled immediately.
// If the given incref was fully compensated by a pending decref
// (i.e. match_data is less than 0) then there is no need
// to do anything more.
if (matches->second > 0)
{
// credit > decrefs (case no 4): store the remaining incref to
// be handled below.
pending_incref = mapping(matches->first, matches->second);
has_pending_incref = true;
refcnt_requests_->erase(matches);
}
else if (matches->second == 0)
{
// credit == decref (case no. 3): if the incref offsets any
// pending decref, just remove the pending decref request.
refcnt_requests_->erase(matches);
}
else
{
// credit < decref (case no. 2): do nothing
}
}
else
{
// case no. 1
pending_incref = mapping(raw, credit);
has_pending_incref = true;
}
}
if (!has_pending_incref)
{
// no need to talk to AGAS, acknowledge the incref immediately
return hpx::make_ready_future(pending_decrefs);
}
naming::gid_type const e_lower = pending_incref.first;
request req(primary_ns_increment_credit, e_lower, pending_incref.second);
naming::id_type target(
stubs::primary_namespace::get_service_instance(e_lower)
, naming::id_type::unmanaged);
lcos::future<boost::int64_t> f =
stubs::primary_namespace::service_async<boost::int64_t>(target, req);
// pass the amount of compensated decrefs to the callback
using util::placeholders::_1;
return f.then(
util::bind(&addressing_service::synchronize_with_async_incref,
this, _1, keep_alive, pending_decrefs));
} // }}}
///////////////////////////////////////////////////////////////////////////////
void addressing_service::decref(
naming::gid_type const& gid
, boost::int64_t credit
, error_code& ec
)
{ // {{{ decref implementation
if (HPX_UNLIKELY(0 == threads::get_self_ptr()))
{
// reschedule this call as an HPX thread
void (addressing_service::*decref_ptr)(
naming::gid_type const&
, boost::int64_t
, error_code&
) = &addressing_service::decref;
threads::register_thread_nullary(
util::bind(decref_ptr, this, gid, credit, boost::ref(throws)),
"addressing_service::decref", threads::pending, true,
threads::thread_priority_normal, std::size_t(-1),
threads::thread_stacksize_default, ec);
return;
}
if (HPX_UNLIKELY(credit <= 0))
{
HPX_THROWS_IF(ec, bad_parameter
, "addressing_service::decref"
, boost::str(boost::format("invalid credit count of %1%") % credit));
return;
}
try {
naming::gid_type raw = naming::detail::get_stripped_gid(gid);
mutex_type::scoped_lock l(refcnt_requests_mtx_);
// Match the decref request with entries in the incref table
typedef refcnt_requests_type::iterator iterator;
typedef refcnt_requests_type::value_type mapping;
iterator matches = refcnt_requests_->find(raw);
if (matches != refcnt_requests_->end())
{
matches->second -= credit;
}
else
{
std::pair<iterator, bool> p =
refcnt_requests_->insert(mapping(raw, -credit));
if (HPX_UNLIKELY(!p.second))
{
l.unlock();
HPX_THROWS_IF(ec, bad_parameter
, "addressing_service::decref"
, boost::str(boost::format("couldn't insert decref request "
"for %1% (%2%)") % raw % credit));
return;
}
}
send_refcnt_requests(l, ec);
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::decref");
}
} // }}}
///////////////////////////////////////////////////////////////////////////////
bool addressing_service::register_name(
std::string const& name
, naming::gid_type const& id
, error_code& ec
)
{ // {{{
try {
request req(symbol_ns_bind, name, id);
response rep;
if (is_bootstrap() && name.size() >= 2 && name[1] == '0' && name[0] == '/')
rep = bootstrap->symbol_ns_server_.service(req, ec);
else
rep = stubs::symbol_namespace::service(name, req, action_priority_, ec);
return !ec && (success == rep.get_status());
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::register_name");
return false;
}
} // }}}
static bool correct_credit_on_failure(future<bool> f, naming::id_type id,
boost::int64_t mutable_gid_credit, boost::int64_t new_gid_credit)
{
// Return the credit to the GID if the operation failed
if (f.has_exception() && mutable_gid_credit != 0)
{
naming::detail::add_credit_to_gid(id.get_gid(), new_gid_credit);
return false;
}
return true;
}
lcos::future<bool> addressing_service::register_name_async(
std::string const& name
, naming::id_type const& id
)
{ // {{{
// We need to modify the reference count.
naming::gid_type& mutable_gid = const_cast<naming::id_type&>(id).get_gid();
naming::gid_type new_gid = naming::detail::split_gid_if_needed(mutable_gid);
request req(symbol_ns_bind, name, new_gid);
future<bool> f = stubs::symbol_namespace::service_async<bool>(
name, req, action_priority_);
boost::int64_t new_credit = naming::detail::get_credit_from_gid(new_gid);
if (new_credit != 0)
{
using util::placeholders::_1;
return f.then(
util::bind(correct_credit_on_failure, _1, id,
HPX_GLOBALCREDIT_INITIAL, new_credit)
);
}
return f;
} // }}}
///////////////////////////////////////////////////////////////////////////////
bool addressing_service::unregister_name(
std::string const& name
, naming::gid_type& id
, error_code& ec
)
{ // {{{
try {
request req(symbol_ns_unbind, name);
response rep;
if (is_bootstrap() && name.size() >= 2 && name[1] == '0' && name[0] == '/')
rep = bootstrap->symbol_ns_server_.service(req, ec);
else
rep = stubs::symbol_namespace::service(name, req, action_priority_, ec);
if (!ec && (success == rep.get_status()))
{
id = rep.get_gid();
return true;
}
return false;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::unregister_name");
return false;
}
} // }}}
lcos::future<naming::id_type> addressing_service::unregister_name_async(
std::string const& name
)
{ // {{{
request req(symbol_ns_unbind, name);
return stubs::symbol_namespace::service_async<naming::id_type>(
name, req, action_priority_);
} // }}}
///////////////////////////////////////////////////////////////////////////////
bool addressing_service::resolve_name(
std::string const& name
, naming::gid_type& id
, error_code& ec
)
{ // {{{
try {
request req(symbol_ns_resolve, name);
response rep;
if (is_bootstrap() && name.size() >= 2 && name[1] == '0' && name[0] == '/')
rep = bootstrap->symbol_ns_server_.service(req, ec);
else
rep = stubs::symbol_namespace::service(name, req, action_priority_, ec);
if (!ec && (success == rep.get_status()))
{
id = rep.get_gid();
return true;
}
else
return false;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::resolve_name");
return false;
}
} // }}}
lcos::future<naming::id_type> addressing_service::resolve_name_async(
std::string const& name
)
{ // {{{
request req(symbol_ns_resolve, name);
return stubs::symbol_namespace::service_async<naming::id_type>(
name, req, action_priority_);
} // }}}
namespace detail
{
hpx::future<hpx::id_type> on_register_event(hpx::future<bool> f,
lcos::promise<hpx::id_type, naming::gid_type> p)
{
if (!f.get())
{
HPX_THROW_EXCEPTION(bad_request,
"hpx::agas::detail::on_register_event",
"request 'symbol_ns_on_event' failed");
return hpx::future<hpx::id_type>();
}
return p.get_future();
}
}
future<hpx::id_type> addressing_service::on_symbol_namespace_event(
std::string const& name, namespace_action_code evt,
bool call_for_past_events)
{
if (evt != symbol_ns_bind)
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::on_symbol_namespace_event",
"invalid event type");
return hpx::future<hpx::id_type>();
}
lcos::promise<naming::id_type, naming::gid_type> p;
request req(symbol_ns_on_event, name, evt, call_for_past_events, p.get_gid());
hpx::future<bool> f = stubs::symbol_namespace::service_async<bool>(
name, req, action_priority_);
using util::placeholders::_1;
return f.then(util::bind(&detail::on_register_event, _1, std::move(p)));
}
}}
///////////////////////////////////////////////////////////////////////////////
typedef hpx::agas::server::symbol_namespace::service_action
symbol_namespace_service_action;
HPX_REGISTER_BROADCAST_ACTION_DECLARATION(symbol_namespace_service_action)
HPX_REGISTER_BROADCAST_ACTION(symbol_namespace_service_action)
namespace hpx { namespace agas
{
namespace detail
{
std::vector<hpx::id_type> find_all_symbol_namespace_services()
{
std::vector<hpx::id_type> ids;
for (hpx::id_type const& id : hpx::find_all_localities())
{
ids.push_back(hpx::id_type(
agas::stubs::symbol_namespace::get_service_instance(id),
id_type::unmanaged));
}
return ids;
}
}
/// Invoke the supplied hpx::function for every registered global name
bool addressing_service::iterate_ids(
iterate_names_function_type const& f
, error_code& ec
)
{ // {{{
try {
request req(symbol_ns_iterate_names, f);
symbol_namespace_service_action act;
lcos::broadcast(act, detail::find_all_symbol_namespace_services(), req).get(ec);
return !ec;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::iterate_ids");
return false;
}
} // }}}
void addressing_service::insert_cache_entry(
naming::gid_type const& gid
, gva const& g
, error_code& ec
)
{ // {{{
if (!caching_)
{
// If caching is disabled, we silently pretend success.
return;
}
try {
// The entry in AGAS for a locality's RTS component has a count of 0,
// so we convert it to 1 here so that the cache doesn't break.
const boost::uint64_t count = (g.count ? g.count : 1);
LAGAS_(debug) <<
( boost::format(
"addressing_service::insert_cache_entry, gid(%1%), count(%2%)")
% gid % count);
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
const gva_cache_key key(gid, count);
if (!gva_cache_->insert(key, g))
{
// Figure out who we collided with.
gva_cache_key idbase;
gva_cache_type::entry_type e;
if (!gva_cache_->get_entry(key, idbase, e))
{
// This is impossible under sane conditions.
HPX_THROWS_IF(ec, invalid_data
, "addressing_service::insert_cache_entry"
, "data corruption or lock error occurred in cache");
return;
}
LAGAS_(warning) <<
( boost::format(
"addressing_service::insert_cache_entry, "
"aborting insert due to key collision in cache, "
"new_gid(%1%), new_count(%2%), old_gid(%3%), old_count(%4%)"
) % gid % count % idbase.get_gid() % idbase.get_count());
}
if (&ec != &throws)
ec = make_success_code();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::insert_cache_entry");
}
} // }}}
bool check_for_collisions(
addressing_service::gva_cache_key const& new_key
, addressing_service::gva_cache_key const& old_key
)
{
return (new_key.get_gid() == old_key.get_gid())
&& (new_key.get_count() == old_key.get_count());
}
void addressing_service::update_cache_entry(
naming::gid_type const& gid
, gva const& g
, error_code& ec
)
{ // {{{
if (!caching_)
{
// If caching is disabled, we silently pretend success.
return;
}
if (naming::get_locality_id_from_gid(gid) ==
naming::get_locality_id_from_gid(locality_))
{
// we prefer not to store any local items in the AGAS cache
return;
}
try {
// The entry in AGAS for a locality's RTS component has a count of 0,
// so we convert it to 1 here so that the cache doesn't break.
const boost::uint64_t count = (g.count ? g.count : 1);
LAGAS_(debug) <<
( boost::format(
"addressing_service::update_cache_entry, gid(%1%), count(%2%)"
) % gid % count);
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
const gva_cache_key key(gid, count);
if (!gva_cache_->update_if(key, g, check_for_collisions))
{
// Figure out who we collided with.
gva_cache_key idbase;
gva_cache_type::entry_type e;
if (!gva_cache_->get_entry(key, idbase, e))
{
// This is impossible under sane conditions.
HPX_THROWS_IF(ec, invalid_data
, "addressing_service::update_cache_entry"
, "data corruption or lock error occurred in cache");
return;
}
LAGAS_(warning) <<
( boost::format(
"addressing_service::update_cache_entry, "
"aborting update due to key collision in cache, "
"new_gid(%1%), new_count(%2%), old_gid(%3%), old_count(%4%)"
) % gid % count % idbase.get_gid() % idbase.get_count());
}
if (&ec != &throws)
ec = make_success_code();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::update_cache_entry");
}
} // }}}
void addressing_service::clear_cache(
error_code& ec
)
{ // {{{
if (!caching_)
{
// If caching is disabled, we silently pretend success.
return;
}
try {
LAGAS_(warning) << "addressing_service::clear_cache, clearing cache";
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
gva_cache_->clear();
if (&ec != &throws)
ec = make_success_code();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::clear_cache");
}
} // }}}
void addressing_service::remove_cache_entry(
naming::gid_type const& gid
, error_code& ec
)
{
// If caching is disabled, we silently pretend success.
if (!caching_)
return;
try {
LAGAS_(warning) << "addressing_service::remove_cache_entry";
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
gva_cache_->erase(
[&gid](std::pair<gva_cache_key, gva_entry_type> const& p)
{
return gid == p.first.get_gid();
});
if (&ec != &throws)
ec = make_success_code();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::clear_cache");
}
}
// Disable refcnt caching during shutdown
void addressing_service::start_shutdown(error_code& ec)
{
// If caching is disabled, we silently pretend success.
if (!caching_)
return;
mutex_type::scoped_lock l(refcnt_requests_mtx_);
enable_refcnt_caching_ = false;
send_refcnt_requests_sync(l, ec);
}
namespace detail
{
// get action code from counter type
namespace_action_code retrieve_action_code(
std::string const& name
, error_code& ec
)
{
performance_counters::counter_path_elements p;
performance_counters::get_counter_path_elements(name, p, ec);
if (ec) return invalid_request;
if (p.objectname_ != "agas")
{
HPX_THROWS_IF(ec, bad_parameter, "retrieve_action_code",
"unknown performance counter (unrelated to AGAS)");
return invalid_request;
}
// component_ns
for (std::size_t i = 0;
i != num_component_namespace_services;
++i)
{
if (p.countername_ == component_namespace_services[i].name_)
return component_namespace_services[i].code_;
}
// locality_ns
for (std::size_t i = 0;
i != num_locality_namespace_services;
++i)
{
if (p.countername_ == locality_namespace_services[i].name_)
return locality_namespace_services[i].code_;
}
// primary_ns
for (std::size_t i = 0;
i != num_primary_namespace_services;
++i)
{
if (p.countername_ == primary_namespace_services[i].name_)
return primary_namespace_services[i].code_;
}
// symbol_ns
for (std::size_t i = 0;
i != num_symbol_namespace_services;
++i)
{
if (p.countername_ == symbol_namespace_services[i].name_)
return symbol_namespace_services[i].code_;
}
HPX_THROWS_IF(ec, bad_parameter, "retrieve_action_code",
"unknown performance counter (unrelated to AGAS)");
return invalid_request;
}
// get service action code from counter type
namespace_action_code retrieve_action_service_code(
std::string const& name
, error_code& ec
)
{
performance_counters::counter_path_elements p;
performance_counters::get_counter_path_elements(name, p, ec);
if (ec) return invalid_request;
if (p.objectname_ != "agas")
{
HPX_THROWS_IF(ec, bad_parameter, "retrieve_action_service_code",
"unknown performance counter (unrelated to AGAS)");
return invalid_request;
}
// component_ns
for (std::size_t i = 0;
i != num_component_namespace_services;
++i)
{
if (p.countername_ == component_namespace_services[i].name_)
return component_namespace_services[i].service_code_;
}
// locality_ns
for (std::size_t i = 0;
i != num_locality_namespace_services;
++i)
{
if (p.countername_ == locality_namespace_services[i].name_)
return locality_namespace_services[i].service_code_;
}
// primary_ns
for (std::size_t i = 0;
i != num_primary_namespace_services;
++i)
{
if (p.countername_ == primary_namespace_services[i].name_)
return primary_namespace_services[i].service_code_;
}
// symbol_ns
for (std::size_t i = 0;
i != num_symbol_namespace_services;
++i)
{
if (p.countername_ == symbol_namespace_services[i].name_)
return symbol_namespace_services[i].service_code_;
}
HPX_THROWS_IF(ec, bad_parameter, "retrieve_action_service_code",
"unknown performance counter (unrelated to AGAS)");
return invalid_request;
}
}
bool addressing_service::retrieve_statistics_counter(
std::string const& name
, naming::gid_type& counter
, error_code& ec
)
{
try {
// retrieve counter type
namespace_action_code service_code =
detail::retrieve_action_service_code(name, ec);
if (invalid_request == service_code) return false;
// compose request
request req(service_code, name);
response rep;
if (is_bootstrap() && name.size() >= 2 && name[1] == '0' && name[0] == '/')
rep = bootstrap->symbol_ns_server_.service(req, ec);
else
rep = stubs::symbol_namespace::service(name, req, action_priority_, ec);
if (!ec && (success == rep.get_status()))
{
counter = rep.get_statistics_counter();
return true;
}
return false;
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e, "addressing_service::query_statistics");
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
// Helper functions to access the current cache statistics
boost::uint64_t addressing_service::get_cache_hits(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().hits(reset);
}
boost::uint64_t addressing_service::get_cache_misses(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().misses(reset);
}
boost::uint64_t addressing_service::get_cache_evictions(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().evictions(reset);
}
boost::uint64_t addressing_service::get_cache_insertions(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().insertions(reset);
}
///////////////////////////////////////////////////////////////////////////////
boost::uint64_t addressing_service::get_cache_get_entry_count(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_get_entry_count(reset);
}
boost::uint64_t addressing_service::get_cache_insert_entry_count(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_insert_entry_count(reset);
}
boost::uint64_t addressing_service::get_cache_update_entry_count(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_update_entry_count(reset);
}
boost::uint64_t addressing_service::get_cache_erase_entry_count(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_erase_entry_count(reset);
}
boost::uint64_t addressing_service::get_cache_get_entry_time(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_get_entry_time(reset);
}
boost::uint64_t addressing_service::get_cache_insert_entry_time(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_insert_entry_time(reset);
}
boost::uint64_t addressing_service::get_cache_update_entry_time(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_update_entry_time(reset);
}
boost::uint64_t addressing_service::get_cache_erase_entry_time(bool reset)
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return gva_cache_->get_statistics().get_erase_entry_time(reset);
}
/// Install performance counter types exposing properties from the local cache.
void addressing_service::register_counter_types()
{ // {{{
// install
util::function_nonser<boost::int64_t(bool)> cache_hits(
boost::bind(&addressing_service::get_cache_hits, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_misses(
boost::bind(&addressing_service::get_cache_misses, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_evictions(
boost::bind(&addressing_service::get_cache_evictions, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_insertions(
boost::bind(&addressing_service::get_cache_insertions, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_get_entry_count(
boost::bind(&addressing_service::get_cache_get_entry_count, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_insert_entry_count(
boost::bind(&addressing_service::get_cache_insert_entry_count, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_update_entry_count(
boost::bind(&addressing_service::get_cache_update_entry_count, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_erase_entry_count(
boost::bind(&addressing_service::get_cache_erase_entry_count, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_get_entry_time(
boost::bind(&addressing_service::get_cache_get_entry_time, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_insert_entry_time(
boost::bind(&addressing_service::get_cache_insert_entry_time, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_update_entry_time(
boost::bind(&addressing_service::get_cache_update_entry_time, this, ::_1));
util::function_nonser<boost::int64_t(bool)> cache_erase_entry_time(
boost::bind(&addressing_service::get_cache_erase_entry_time, this, ::_1));
performance_counters::generic_counter_type_data const counter_types[] =
{
{ "/agas/count/cache/hits", performance_counters::counter_raw,
"returns the number of cache hits while accessing the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_hits, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/misses", performance_counters::counter_raw,
"returns the number of cache misses while accessing the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_misses, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/evictions", performance_counters::counter_raw,
"returns the number of cache evictions from the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_evictions, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/insertions", performance_counters::counter_raw,
"returns the number of cache insertions into the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_insertions, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/get_entry", performance_counters::counter_raw,
"returns the number of invocations of get_entry function of the "
"AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_get_entry_count, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/insert_entry", performance_counters::counter_raw,
"returns the number of invocations of insert_entry function of the "
"AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_insert_entry_count, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/update_entry", performance_counters::counter_raw,
"returns the number of invocations of update_entry function of the "
"AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_update_entry_count, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/count/cache/erase_entry", performance_counters::counter_raw,
"returns the number of invocations of erase_entry function of the "
"AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_erase_entry_count, _2),
&performance_counters::locality_counter_discoverer,
""
},
{ "/agas/time/cache/get_entry", performance_counters::counter_raw,
"returns the the overall time spent executing of the get_entry API "
"function of the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_get_entry_count, _2),
&performance_counters::locality_counter_discoverer,
"ns"
},
{ "/agas/time/cache/insert_entry", performance_counters::counter_raw,
"returns the the overall time spent executing of the insert_entry API "
"function of the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_insert_entry_count, _2),
&performance_counters::locality_counter_discoverer,
"ns"
},
{ "/agas/time/cache/update_entry", performance_counters::counter_raw,
"returns the the overall time spent executing of the update_entry API "
"function of the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_update_entry_count, _2),
&performance_counters::locality_counter_discoverer,
"ns"
},
{ "/agas/time/cache/erase_entry", performance_counters::counter_raw,
"returns the the overall time spent executing of the erase_entry API "
"function of the AGAS cache",
HPX_PERFORMANCE_COUNTER_V1,
boost::bind(&performance_counters::locality_raw_counter_creator,
_1, cache_erase_entry_count, _2),
&performance_counters::locality_counter_discoverer,
"ns"
}
};
performance_counters::install_counter_types(
counter_types, sizeof(counter_types)/sizeof(counter_types[0]));
if (is_bootstrap()) {
// install counters for services
bootstrap->register_counter_types();
// always register root server as 'locality#0'
bootstrap->register_server_instance("locality#0/");
}
else {
// install counters for services
hosted->register_counter_types();
boost::uint32_t locality_id =
naming::get_locality_id_from_gid(get_local_locality());
std::string str("locality#" + boost::lexical_cast<std::string>(locality_id) + "/");
hosted->register_server_instance(str.c_str(), locality_id);
}
} // }}}
void addressing_service::garbage_collect_non_blocking(
error_code& ec
)
{
mutex_type::scoped_lock l(refcnt_requests_mtx_, boost::try_to_lock);
if (!l) return; // no need to compete for garbage collection
send_refcnt_requests_non_blocking(l, ec);
}
void addressing_service::garbage_collect(
error_code& ec
)
{
mutex_type::scoped_lock l(refcnt_requests_mtx_, boost::try_to_lock);
if (!l) return; // no need to compete for garbage collection
send_refcnt_requests_sync(l, ec);
}
void addressing_service::send_refcnt_requests(
addressing_service::mutex_type::scoped_lock& l
, error_code& ec
)
{
if (!l.owns_lock())
{
HPX_THROWS_IF(ec, lock_error
, "addressing_service::send_refcnt_requests"
, "mutex is not locked");
return;
}
if (!enable_refcnt_caching_ || max_refcnt_requests_ == ++refcnt_requests_count_)
send_refcnt_requests_non_blocking(l, ec);
else if (&ec != &throws)
ec = make_success_code();
}
#if defined(HPX_HAVE_AGAS_DUMP_REFCNT_ENTRIES)
void dump_refcnt_requests(
addressing_service::mutex_type::scoped_lock& l
, addressing_service::refcnt_requests_type const& requests
, const char* func_name
)
{
std::stringstream ss;
ss << ( boost::format(
"%1%, dumping client-side refcnt table, requests(%2%):")
% func_name % requests.size());
typedef addressing_service::refcnt_requests_type::const_reference
const_reference;
for (const_reference e : requests)
{
// The [client] tag is in there to make it easier to filter
// through the logs.
ss << ( boost::format(
"\n [client] gid(%1%), credits(%2%)")
% e.first
% e.second);
}
LAGAS_(debug) << ss.str();
}
#endif
void addressing_service::send_refcnt_requests_non_blocking(
addressing_service::mutex_type::scoped_lock& l
, error_code& ec
)
{
try {
if (refcnt_requests_->empty())
{
l.unlock();
return;
}
boost::shared_ptr<refcnt_requests_type> p(new refcnt_requests_type);
p.swap(refcnt_requests_);
refcnt_requests_count_ = 0;
l.unlock();
LAGAS_(info) << (boost::format(
"addressing_service::send_refcnt_requests_non_blocking, "
"requests(%1%)")
% p->size());
#if defined(HPX_HAVE_AGAS_DUMP_REFCNT_ENTRIES)
if (LAGAS_ENABLED(debug))
dump_refcnt_requests(l, *p,
"addressing_service::send_refcnt_requests_non_blocking");
#endif
// collect all requests for each locality
typedef std::map<naming::id_type, std::vector<request> > requests_type;
requests_type requests;
for (refcnt_requests_type::const_reference e : *p)
{
HPX_ASSERT(e.second < 0);
naming::gid_type raw(e.first);
request const req(primary_ns_decrement_credit, raw, raw, e.second);
naming::id_type target(
stubs::primary_namespace::get_service_instance(raw)
, naming::id_type::unmanaged);
requests[target].push_back(req);
}
// send requests to all locality
requests_type::const_iterator end = requests.end();
for (requests_type::const_iterator it = requests.begin(); it != end; ++it)
{
stubs::primary_namespace::bulk_service_non_blocking(
(*it).first, (*it).second, action_priority_);
}
if (&ec != &throws)
ec = make_success_code();
}
catch (hpx::exception const& e) {
HPX_RETHROWS_IF(ec, e,
"addressing_service::send_refcnt_requests_non_blocking");
}
}
std::vector<hpx::future<std::vector<response> > >
addressing_service::send_refcnt_requests_async(
addressing_service::mutex_type::scoped_lock& l
)
{
if (refcnt_requests_->empty())
{
l.unlock();
return std::vector<hpx::future<std::vector<response> > >();
}
boost::shared_ptr<refcnt_requests_type> p(new refcnt_requests_type);
p.swap(refcnt_requests_);
refcnt_requests_count_ = 0;
l.unlock();
LAGAS_(info) << (boost::format(
"addressing_service::send_refcnt_requests_async, "
"requests(%1%)")
% p->size());
#if defined(HPX_HAVE_AGAS_DUMP_REFCNT_ENTRIES)
if (LAGAS_ENABLED(debug))
dump_refcnt_requests(l, *p,
"addressing_service::send_refcnt_requests_sync");
#endif
// collect all requests for each locality
typedef std::map<naming::id_type, std::vector<request> > requests_type;
requests_type requests;
std::vector<hpx::future<std::vector<response> > > lazy_results;
for (refcnt_requests_type::const_reference e : *p)
{
HPX_ASSERT(e.second < 0);
naming::gid_type raw(e.first);
request const req(primary_ns_decrement_credit, raw, raw, e.second);
naming::id_type target(
stubs::primary_namespace::get_service_instance(raw)
, naming::id_type::unmanaged);
requests[target].push_back(req);
}
// send requests to all locality
requests_type::const_iterator end = requests.end();
for (requests_type::const_iterator it = requests.begin(); it != end; ++it)
{
lazy_results.push_back(
stubs::primary_namespace::bulk_service_async(
(*it).first, (*it).second, action_priority_));
}
return lazy_results;
}
void addressing_service::send_refcnt_requests_sync(
addressing_service::mutex_type::scoped_lock& l
, error_code& ec
)
{
std::vector<hpx::future<std::vector<response> > > lazy_results =
send_refcnt_requests_async(l);
wait_all(lazy_results);
for (hpx::future<std::vector<response> >& f : lazy_results)
{
std::vector<response> const& reps = f.get();
for (response const& rep : reps)
{
if (success != rep.get_status())
{
HPX_THROWS_IF(ec, rep.get_status(),
"addressing_service::send_refcnt_requests_sync",
"could not decrement reference count (reported error" +
hpx::get_error_what(ec) + ", " +
hpx::get_error_file_name(ec) + "(" +
boost::lexical_cast<std::string>(
hpx::get_error_line_number(ec)) + "))");
return;
}
}
}
if (&ec != &throws)
ec = make_success_code();
}
hpx::future<std::pair<naming::id_type, naming::address> >
addressing_service::begin_migration_async(
naming::id_type const& id
, naming::id_type const& target_locality
)
{
typedef std::pair<naming::id_type, naming::address> result_type;
if (!id)
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::begin_migration_async",
"invalid reference id");
return make_ready_future(result_type(naming::invalid_id, naming::address()));
}
naming::gid_type gid = id.get_gid();
// insert the object's new locality into the map of migrated objects
{
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
migrated_objects_table_.insert(gid);
}
agas::request req(agas::primary_ns_begin_migration, gid);
naming::id_type service_target(
agas::stubs::primary_namespace::get_service_instance(gid)
, naming::id_type::unmanaged);
return stubs::primary_namespace::service_async<
std::pair<naming::id_type, naming::address>
>(service_target, req);
}
hpx::future<bool> addressing_service::end_migration_async(
naming::id_type const& id
)
{
if (!id)
{
HPX_THROW_EXCEPTION(bad_parameter,
"addressing_service::end_migration_async",
"invalid reference id");
return make_ready_future(false);
}
agas::request req(agas::primary_ns_end_migration, id.get_gid());
naming::id_type service_target(
agas::stubs::primary_namespace::get_service_instance(id.get_gid())
, naming::id_type::unmanaged);
return stubs::primary_namespace::service_async<bool>(
service_target, req);
}
bool addressing_service::was_object_migrated_locked(
naming::gid_type const& id
)
{
return
migrated_objects_table_.find(id) !=
migrated_objects_table_.end();
}
bool addressing_service::was_object_migrated(
naming::id_type const* ids
, std::size_t size)
{
#if !defined(HPX_SUPPORT_MULTIPLE_PARCEL_DESTINATIONS)
HPX_ASSERT(1 == size);
cache_mutex_type::scoped_lock lock(gva_cache_mtx_);
return was_object_migrated_locked(ids[0].get_gid());
#else
// #FIXME: it's not really clear how to handle this situation
HPX_ASSERT(false);
return false;
#endif
}
}}
///////////////////////////////////////////////////////////////////////////////
namespace hpx
{
namespace detail
{
inline std::string name_from_basename(char const* basename, std::size_t idx)
{
std::string name;
if (basename[0] != '/')
name += '/';
name += basename;
if (name[name.size()-1] != '/')
name += '/';
name += boost::lexical_cast<std::string>(idx);
return name;
}
}
///////////////////////////////////////////////////////////////////////////
std::vector<hpx::future<hpx::id_type> >
find_all_ids_from_basename(char const* basename, std::size_t num_ids)
{
if (0 == basename)
{
HPX_THROW_EXCEPTION(bad_parameter,
"hpx::find_all_ids_from_basename",
"no basename specified");
}
std::vector<hpx::future<hpx::id_type> > results;
for(std::size_t i = 0; i != num_ids; ++i)
{
std::string name = detail::name_from_basename(basename, i);
results.push_back(agas::on_symbol_namespace_event(
name, agas::symbol_ns_bind, true));
}
return results;
}
std::vector<hpx::future<hpx::id_type> >
find_ids_from_basename(char const* basename,
std::vector<std::size_t> const& ids)
{
if (0 == basename)
{
HPX_THROW_EXCEPTION(bad_parameter,
"hpx::find_ids_from_basename",
"no basename specified");
}
std::vector<hpx::future<hpx::id_type> > results;
for (std::size_t i : ids)
{
std::string name = detail::name_from_basename(basename, i);
results.push_back(agas::on_symbol_namespace_event(
name, agas::symbol_ns_bind, true));
}
return results;
}
hpx::future<hpx::id_type> find_id_from_basename(char const* basename,
std::size_t sequence_nr)
{
if (0 == basename)
{
HPX_THROW_EXCEPTION(bad_parameter,
"hpx::find_id_from_basename",
"no basename specified");
}
if (sequence_nr == std::size_t(~0U))
sequence_nr = std::size_t(naming::get_locality_id_from_id(find_here()));
std::string name = detail::name_from_basename(basename, sequence_nr);
return agas::on_symbol_namespace_event(name, agas::symbol_ns_bind, true);
}
hpx::future<bool> register_id_with_basename(char const* basename,
hpx::id_type id, std::size_t sequence_nr)
{
if (0 == basename)
{
HPX_THROW_EXCEPTION(bad_parameter,
"hpx::register_id_with_basename",
"no basename specified");
}
if (sequence_nr == std::size_t(~0U))
sequence_nr = std::size_t(naming::get_locality_id_from_id(find_here()));
std::string name = detail::name_from_basename(basename, sequence_nr);
return agas::register_name(name, id);
}
hpx::future<hpx::id_type> unregister_id_with_basename(
char const* basename, std::size_t sequence_nr)
{
if (0 == basename)
{
HPX_THROW_EXCEPTION(bad_parameter,
"hpx::unregister_id_with_basename",
"no basename specified");
}
if (sequence_nr == std::size_t(~0U))
sequence_nr = std::size_t(naming::get_locality_id_from_id(find_here()));
std::string name = detail::name_from_basename(basename, sequence_nr);
return agas::unregister_name(name);
}
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchcore/proton/common/statusreport.h>
namespace proton {
TEST("require that default status report works")
{
StatusReport sr(StatusReport::Params("foo"));
EXPECT_EQUAL("foo", sr.getComponent());
EXPECT_EQUAL(StatusReport::DOWN, sr.getState());
EXPECT_EQUAL("", sr.getInternalState());
EXPECT_EQUAL("", sr.getInternalConfigState());
EXPECT_FALSE(sr.hasProgress());
EXPECT_EQUAL("", sr.getMessage());
EXPECT_EQUAL("state=", sr.getInternalStatesStr());
}
TEST("require that custom status report works")
{
StatusReport sr(StatusReport::Params("foo").
state(StatusReport::UPOK).
internalState("mystate").
internalConfigState("myconfigstate").
progress(65).
message("mymessage"));
EXPECT_EQUAL("foo", sr.getComponent());
EXPECT_EQUAL(StatusReport::UPOK, sr.getState());
EXPECT_EQUAL("mystate", sr.getInternalState());
EXPECT_EQUAL("myconfigstate", sr.getInternalConfigState());
EXPECT_TRUE(sr.hasProgress());
EXPECT_EQUAL(65, sr.getProgress());
EXPECT_EQUAL("mymessage", sr.getMessage());
EXPECT_EQUAL("state=mystate configstate=myconfigstate", sr.getInternalStatesStr());
}
} // namespace proton
TEST_MAIN() { TEST_RUN_ALL(); }
|
; A247215: Integers k such that 3k+1 and 6k+1 are both squares.
; 0,8,280,9520,323408,10986360,373212840,12678250208,430687294240,14630689753960,497012764340408,16883803297819920,573552299361536880,19483894374994434008,661878856450449219400,22484397224940279025600,763807626791519037651008,25946974913686707001108680,881433339438556519000044120,29942786565997234939000391408,1017173309904467431407013263760,34553949750185895432899450576440,1173817118196415977287174306335208,39875228068927957332331026964820640,1354583937225354133321967742497566560
seq $0,2315 ; NSW numbers: a(n) = 6*a(n-1) - a(n-2); also a(n)^2 - 2*b(n)^2 = -1 with b(n)=A001653(n+1).
pow $0,2
div $0,6
|
; Licensed to the .NET Foundation under one or more agreements.
; The .NET Foundation licenses this file to you under the MIT license.
; See the LICENSE file in the project root for more information.
; ==++==
;
;
; ==--==
; ***********************************************************************
; File: JIThelp.asm
;
; ***********************************************************************
;
; *** NOTE: If you make changes to this file, propagate the changes to
; jithelp.s in this directory
; This contains JITinterface routines that are 100% x86 assembly
.586
.model flat
include asmconstants.inc
option casemap:none
.code
;
; <TODO>@TODO Switch to g_ephemeral_low and g_ephemeral_high
; @TODO instead of g_lowest_address, g_highest address</TODO>
;
ARGUMENT_REG1 equ ecx
ARGUMENT_REG2 equ edx
g_ephemeral_low TEXTEQU <_g_ephemeral_low>
g_ephemeral_high TEXTEQU <_g_ephemeral_high>
g_lowest_address TEXTEQU <_g_lowest_address>
g_highest_address TEXTEQU <_g_highest_address>
g_card_table TEXTEQU <_g_card_table>
WriteBarrierAssert TEXTEQU <_WriteBarrierAssert@8>
JIT_LLsh TEXTEQU <_JIT_LLsh@0>
JIT_LRsh TEXTEQU <_JIT_LRsh@0>
JIT_LRsz TEXTEQU <_JIT_LRsz@0>
JIT_LMul TEXTEQU <@JIT_LMul@16>
JIT_Dbl2LngOvf TEXTEQU <@JIT_Dbl2LngOvf@8>
JIT_Dbl2Lng TEXTEQU <@JIT_Dbl2Lng@8>
JIT_Dbl2IntSSE2 TEXTEQU <@JIT_Dbl2IntSSE2@8>
JIT_Dbl2LngP4x87 TEXTEQU <@JIT_Dbl2LngP4x87@8>
JIT_Dbl2LngSSE3 TEXTEQU <@JIT_Dbl2LngSSE3@8>
JIT_InternalThrowFromHelper TEXTEQU <@JIT_InternalThrowFromHelper@4>
JIT_WriteBarrierReg_PreGrow TEXTEQU <_JIT_WriteBarrierReg_PreGrow@0>
JIT_WriteBarrierReg_PostGrow TEXTEQU <_JIT_WriteBarrierReg_PostGrow@0>
JIT_TailCall TEXTEQU <_JIT_TailCall@0>
JIT_TailCallLeave TEXTEQU <_JIT_TailCallLeave@0>
JIT_TailCallVSDLeave TEXTEQU <_JIT_TailCallVSDLeave@0>
JIT_TailCallHelper TEXTEQU <_JIT_TailCallHelper@4>
JIT_TailCallReturnFromVSD TEXTEQU <_JIT_TailCallReturnFromVSD@0>
EXTERN g_ephemeral_low:DWORD
EXTERN g_ephemeral_high:DWORD
EXTERN g_lowest_address:DWORD
EXTERN g_highest_address:DWORD
EXTERN g_card_table:DWORD
ifdef _DEBUG
EXTERN WriteBarrierAssert:PROC
endif ; _DEBUG
EXTERN JIT_InternalThrowFromHelper:PROC
ifdef FEATURE_HIJACK
EXTERN JIT_TailCallHelper:PROC
endif
EXTERN _g_TailCallFrameVptr:DWORD
EXTERN @JIT_FailFast@0:PROC
EXTERN _s_gsCookie:DWORD
EXTERN @JITutil_IsInstanceOfInterface@8:PROC
EXTERN @JITutil_ChkCastInterface@8:PROC
EXTERN @JITutil_IsInstanceOfAny@8:PROC
EXTERN @JITutil_ChkCastAny@8:PROC
ifdef FEATURE_IMPLICIT_TLS
EXTERN _GetThread@0:PROC
endif
ifdef WRITE_BARRIER_CHECK
; Those global variables are always defined, but should be 0 for Server GC
g_GCShadow TEXTEQU <?g_GCShadow@@3PAEA>
g_GCShadowEnd TEXTEQU <?g_GCShadowEnd@@3PAEA>
EXTERN g_GCShadow:DWORD
EXTERN g_GCShadowEnd:DWORD
INVALIDGCVALUE equ 0CCCCCCCDh
endif
EXTERN _COMPlusEndCatch@20:PROC
.686P
.XMM
; The following macro is needed because of a MASM issue with the
; movsd mnemonic
;
$movsd MACRO op1, op2
LOCAL begin_movsd, end_movsd
begin_movsd:
movupd op1, op2
end_movsd:
org begin_movsd
db 0F2h
org end_movsd
ENDM
.586
; The following macro is used to match the JITs
; multi-byte NOP sequence
$nop3 MACRO
db 090h
db 090h
db 090h
ENDM
;***
;JIT_WriteBarrier* - GC write barrier helper
;
;Purpose:
; Helper calls in order to assign an object to a field
; Enables book-keeping of the GC.
;
;Entry:
; EDX - address of ref-field (assigned to)
; the resp. other reg - RHS of assignment
;
;Exit:
;
;Uses:
; EDX is destroyed.
;
;Exceptions:
;
;*******************************************************************************
; The code here is tightly coupled with AdjustContextForWriteBarrier, if you change
; anything here, you might need to change AdjustContextForWriteBarrier as well
WriteBarrierHelper MACRO rg
ALIGN 4
;; The entry point is the fully 'safe' one in which we check if EDX (the REF
;; begin updated) is actually in the GC heap
PUBLIC _JIT_CheckedWriteBarrier&rg&@0
_JIT_CheckedWriteBarrier&rg&@0 PROC
;; check in the REF being updated is in the GC heap
cmp edx, g_lowest_address
jb WriteBarrier_NotInHeap_&rg
cmp edx, g_highest_address
jae WriteBarrier_NotInHeap_&rg
;; fall through to unchecked routine
;; note that its entry point also happens to be aligned
ifdef WRITE_BARRIER_CHECK
;; This entry point is used when you know the REF pointer being updated
;; is in the GC heap
PUBLIC _JIT_DebugWriteBarrier&rg&@0
_JIT_DebugWriteBarrier&rg&@0:
endif
ifdef _DEBUG
push edx
push ecx
push eax
push rg
push edx
call WriteBarrierAssert
pop eax
pop ecx
pop edx
endif ;_DEBUG
; in the !WRITE_BARRIER_CHECK case this will be the move for all
; addresses in the GCHeap, addresses outside the GCHeap will get
; taken care of below at WriteBarrier_NotInHeap_&rg
ifndef WRITE_BARRIER_CHECK
mov DWORD PTR [edx], rg
endif
ifdef WRITE_BARRIER_CHECK
; Test dest here so if it is bad AV would happen before we change register/stack
; status. This makes job of AdjustContextForWriteBarrier easier.
cmp [edx], 0
;; ALSO update the shadow GC heap if that is enabled
; Make ebp into the temporary src register. We need to do this so that we can use ecx
; in the calculation of the shadow GC address, but still have access to the src register
push ecx
push ebp
mov ebp, rg
; if g_GCShadow is 0, don't perform the check
cmp g_GCShadow, 0
je WriteBarrier_NoShadow_&rg
mov ecx, edx
sub ecx, g_lowest_address ; U/V
jb WriteBarrier_NoShadow_&rg
add ecx, [g_GCShadow]
cmp ecx, [g_GCShadowEnd]
ja WriteBarrier_NoShadow_&rg
; TODO: In Orcas timeframe if we move to P4+ only on X86 we should enable
; mfence barriers on either side of these two writes to make sure that
; they stay as close together as possible
; edx contains address in GC
; ecx contains address in ShadowGC
; ebp temporarially becomes the src register
;; When we're writing to the shadow GC heap we want to be careful to minimize
;; the risk of a race that can occur here where the GC and ShadowGC don't match
mov DWORD PTR [edx], ebp
mov DWORD PTR [ecx], ebp
;; We need a scratch register to verify the shadow heap. We also need to
;; construct a memory barrier so that the write to the shadow heap happens
;; before the read from the GC heap. We can do both by using SUB/XCHG
;; rather than PUSH.
;;
;; TODO: Should be changed to a push if the mfence described above is added.
;;
sub esp, 4
xchg [esp], eax
;; As part of our race avoidance (see above) we will now check whether the values
;; in the GC and ShadowGC match. There is a possibility that we're wrong here but
;; being overaggressive means we might mask a case where someone updates GC refs
;; without going to a write barrier, but by its nature it will be indeterminant
;; and we will find real bugs whereas the current implementation is indeterminant
;; but only leads to investigations that find that this code is fundamentally flawed
mov eax, [edx]
cmp [ecx], eax
je WriteBarrier_CleanupShadowCheck_&rg
mov [ecx], INVALIDGCVALUE
WriteBarrier_CleanupShadowCheck_&rg:
pop eax
jmp WriteBarrier_ShadowCheckEnd_&rg
WriteBarrier_NoShadow_&rg:
; If we come here then we haven't written the value to the GC and need to.
; ebp contains rg
; We restore ebp/ecx immediately after this, and if either of them is the src
; register it will regain its value as the src register.
mov DWORD PTR [edx], ebp
WriteBarrier_ShadowCheckEnd_&rg:
pop ebp
pop ecx
endif
cmp rg, g_ephemeral_low
jb WriteBarrier_NotInEphemeral_&rg
cmp rg, g_ephemeral_high
jae WriteBarrier_NotInEphemeral_&rg
shr edx, 10
add edx, [g_card_table]
cmp BYTE PTR [edx], 0FFh
jne WriteBarrier_UpdateCardTable_&rg
ret
WriteBarrier_UpdateCardTable_&rg:
mov BYTE PTR [edx], 0FFh
ret
WriteBarrier_NotInHeap_&rg:
; If it wasn't in the heap then we haven't updated the dst in memory yet
mov DWORD PTR [edx], rg
WriteBarrier_NotInEphemeral_&rg:
; If it is in the GC Heap but isn't in the ephemeral range we've already
; updated the Heap with the Object*.
ret
_JIT_CheckedWriteBarrier&rg&@0 ENDP
ENDM
;***
;JIT_ByRefWriteBarrier* - GC write barrier helper
;
;Purpose:
; Helper calls in order to assign an object to a byref field
; Enables book-keeping of the GC.
;
;Entry:
; EDI - address of ref-field (assigned to)
; ESI - address of the data (source)
; ECX can be trashed
;
;Exit:
;
;Uses:
; EDI and ESI are incremented by a DWORD
;
;Exceptions:
;
;*******************************************************************************
; The code here is tightly coupled with AdjustContextForWriteBarrier, if you change
; anything here, you might need to change AdjustContextForWriteBarrier as well
ByRefWriteBarrierHelper MACRO
ALIGN 4
PUBLIC _JIT_ByRefWriteBarrier@0
_JIT_ByRefWriteBarrier@0 PROC
;;test for dest in range
mov ecx, [esi]
cmp edi, g_lowest_address
jb ByRefWriteBarrier_NotInHeap
cmp edi, g_highest_address
jae ByRefWriteBarrier_NotInHeap
ifndef WRITE_BARRIER_CHECK
;;write barrier
mov [edi],ecx
endif
ifdef WRITE_BARRIER_CHECK
; Test dest here so if it is bad AV would happen before we change register/stack
; status. This makes job of AdjustContextForWriteBarrier easier.
cmp [edi], 0
;; ALSO update the shadow GC heap if that is enabled
; use edx for address in GC Shadow,
push edx
;if g_GCShadow is 0, don't do the update
cmp g_GCShadow, 0
je ByRefWriteBarrier_NoShadow
mov edx, edi
sub edx, g_lowest_address ; U/V
jb ByRefWriteBarrier_NoShadow
add edx, [g_GCShadow]
cmp edx, [g_GCShadowEnd]
ja ByRefWriteBarrier_NoShadow
; TODO: In Orcas timeframe if we move to P4+ only on X86 we should enable
; mfence barriers on either side of these two writes to make sure that
; they stay as close together as possible
; edi contains address in GC
; edx contains address in ShadowGC
; ecx is the value to assign
;; When we're writing to the shadow GC heap we want to be careful to minimize
;; the risk of a race that can occur here where the GC and ShadowGC don't match
mov DWORD PTR [edi], ecx
mov DWORD PTR [edx], ecx
;; We need a scratch register to verify the shadow heap. We also need to
;; construct a memory barrier so that the write to the shadow heap happens
;; before the read from the GC heap. We can do both by using SUB/XCHG
;; rather than PUSH.
;;
;; TODO: Should be changed to a push if the mfence described above is added.
;;
sub esp, 4
xchg [esp], eax
;; As part of our race avoidance (see above) we will now check whether the values
;; in the GC and ShadowGC match. There is a possibility that we're wrong here but
;; being overaggressive means we might mask a case where someone updates GC refs
;; without going to a write barrier, but by its nature it will be indeterminant
;; and we will find real bugs whereas the current implementation is indeterminant
;; but only leads to investigations that find that this code is fundamentally flawed
mov eax, [edi]
cmp [edx], eax
je ByRefWriteBarrier_CleanupShadowCheck
mov [edx], INVALIDGCVALUE
ByRefWriteBarrier_CleanupShadowCheck:
pop eax
jmp ByRefWriteBarrier_ShadowCheckEnd
ByRefWriteBarrier_NoShadow:
; If we come here then we haven't written the value to the GC and need to.
mov DWORD PTR [edi], ecx
ByRefWriteBarrier_ShadowCheckEnd:
pop edx
endif
;;test for *src in ephemeral segement
cmp ecx, g_ephemeral_low
jb ByRefWriteBarrier_NotInEphemeral
cmp ecx, g_ephemeral_high
jae ByRefWriteBarrier_NotInEphemeral
mov ecx, edi
add esi,4
add edi,4
shr ecx, 10
add ecx, [g_card_table]
cmp byte ptr [ecx], 0FFh
jne ByRefWriteBarrier_UpdateCardTable
ret
ByRefWriteBarrier_UpdateCardTable:
mov byte ptr [ecx], 0FFh
ret
ByRefWriteBarrier_NotInHeap:
; If it wasn't in the heap then we haven't updated the dst in memory yet
mov [edi],ecx
ByRefWriteBarrier_NotInEphemeral:
; If it is in the GC Heap but isn't in the ephemeral range we've already
; updated the Heap with the Object*.
add esi,4
add edi,4
ret
_JIT_ByRefWriteBarrier@0 ENDP
ENDM
;*******************************************************************************
; Write barrier wrappers with fcall calling convention
;
UniversalWriteBarrierHelper MACRO name
ALIGN 4
PUBLIC @JIT_&name&@8
@JIT_&name&@8 PROC
mov eax,edx
mov edx,ecx
jmp _JIT_&name&EAX@0
@JIT_&name&@8 ENDP
ENDM
; WriteBarrierStart and WriteBarrierEnd are used to determine bounds of
; WriteBarrier functions so can determine if got AV in them.
;
PUBLIC _JIT_WriteBarrierGroup@0
_JIT_WriteBarrierGroup@0 PROC
ret
_JIT_WriteBarrierGroup@0 ENDP
ifdef FEATURE_USE_ASM_GC_WRITE_BARRIERS
; Only define these if we're using the ASM GC write barriers; if this flag is not defined,
; we'll use C++ versions of these write barriers.
UniversalWriteBarrierHelper <CheckedWriteBarrier>
UniversalWriteBarrierHelper <WriteBarrier>
endif
WriteBarrierHelper <EAX>
WriteBarrierHelper <EBX>
WriteBarrierHelper <ECX>
WriteBarrierHelper <ESI>
WriteBarrierHelper <EDI>
WriteBarrierHelper <EBP>
ByRefWriteBarrierHelper
; This is the first function outside the "keep together range". Used by BBT scripts.
PUBLIC _JIT_WriteBarrierGroup_End@0
_JIT_WriteBarrierGroup_End@0 PROC
ret
_JIT_WriteBarrierGroup_End@0 ENDP
;*********************************************************************/
; In cases where we support it we have an optimized GC Poll callback. Normall (when we're not trying to
; suspend for GC, the CORINFO_HELP_POLL_GC helper points to this nop routine. When we're ready to suspend
; for GC, we whack the Jit Helper table entry to point to the real helper. When we're done with GC we
; whack it back.
PUBLIC @JIT_PollGC_Nop@0
@JIT_PollGC_Nop@0 PROC
ret
@JIT_PollGC_Nop@0 ENDP
;*********************************************************************/
;llshl - long shift left
;
;Purpose:
; Does a Long Shift Left (signed and unsigned are identical)
; Shifts a long left any number of bits.
;
; NOTE: This routine has been adapted from the Microsoft CRTs.
;
;Entry:
; EDX:EAX - long value to be shifted
; ECX - number of bits to shift by
;
;Exit:
; EDX:EAX - shifted value
;
ALIGN 16
PUBLIC JIT_LLsh
JIT_LLsh PROC
; Handle shifts of between bits 0 and 31
cmp ecx, 32
jae short LLshMORE32
shld edx,eax,cl
shl eax,cl
ret
; Handle shifts of between bits 32 and 63
LLshMORE32:
; The x86 shift instructions only use the lower 5 bits.
mov edx,eax
xor eax,eax
shl edx,cl
ret
JIT_LLsh ENDP
;*********************************************************************/
;LRsh - long shift right
;
;Purpose:
; Does a signed Long Shift Right
; Shifts a long right any number of bits.
;
; NOTE: This routine has been adapted from the Microsoft CRTs.
;
;Entry:
; EDX:EAX - long value to be shifted
; ECX - number of bits to shift by
;
;Exit:
; EDX:EAX - shifted value
;
ALIGN 16
PUBLIC JIT_LRsh
JIT_LRsh PROC
; Handle shifts of between bits 0 and 31
cmp ecx, 32
jae short LRshMORE32
shrd eax,edx,cl
sar edx,cl
ret
; Handle shifts of between bits 32 and 63
LRshMORE32:
; The x86 shift instructions only use the lower 5 bits.
mov eax,edx
sar edx, 31
sar eax,cl
ret
JIT_LRsh ENDP
;*********************************************************************/
; LRsz:
;Purpose:
; Does a unsigned Long Shift Right
; Shifts a long right any number of bits.
;
; NOTE: This routine has been adapted from the Microsoft CRTs.
;
;Entry:
; EDX:EAX - long value to be shifted
; ECX - number of bits to shift by
;
;Exit:
; EDX:EAX - shifted value
;
ALIGN 16
PUBLIC JIT_LRsz
JIT_LRsz PROC
; Handle shifts of between bits 0 and 31
cmp ecx, 32
jae short LRszMORE32
shrd eax,edx,cl
shr edx,cl
ret
; Handle shifts of between bits 32 and 63
LRszMORE32:
; The x86 shift instructions only use the lower 5 bits.
mov eax,edx
xor edx,edx
shr eax,cl
ret
JIT_LRsz ENDP
;*********************************************************************/
; LMul:
;Purpose:
; Does a long multiply (same for signed/unsigned)
;
; NOTE: This routine has been adapted from the Microsoft CRTs.
;
;Entry:
; Parameters are passed on the stack:
; 1st pushed: multiplier (QWORD)
; 2nd pushed: multiplicand (QWORD)
;
;Exit:
; EDX:EAX - product of multiplier and multiplicand
;
ALIGN 16
PUBLIC JIT_LMul
JIT_LMul PROC
; AHI, BHI : upper 32 bits of A and B
; ALO, BLO : lower 32 bits of A and B
;
; ALO * BLO
; ALO * BHI
; + BLO * AHI
; ---------------------
mov eax,[esp + 8] ; AHI
mov ecx,[esp + 16] ; BHI
or ecx,eax ;test for both hiwords zero.
mov ecx,[esp + 12] ; BLO
jnz LMul_hard ;both are zero, just mult ALO and BLO
mov eax,[esp + 4]
mul ecx
ret 16 ; callee restores the stack
LMul_hard:
push ebx
mul ecx ;eax has AHI, ecx has BLO, so AHI * BLO
mov ebx,eax ;save result
mov eax,[esp + 8] ; ALO
mul dword ptr [esp + 20] ;ALO * BHI
add ebx,eax ;ebx = ((ALO * BHI) + (AHI * BLO))
mov eax,[esp + 8] ; ALO ;ecx = BLO
mul ecx ;so edx:eax = ALO*BLO
add edx,ebx ;now edx has all the LO*HI stuff
pop ebx
ret 16 ; callee restores the stack
JIT_LMul ENDP
;*********************************************************************/
; JIT_Dbl2LngOvf
;Purpose:
; converts a double to a long truncating toward zero (C semantics)
; with check for overflow
;
; uses stdcall calling conventions
;
PUBLIC JIT_Dbl2LngOvf
JIT_Dbl2LngOvf PROC
fnclex
fld qword ptr [esp+4]
push ecx
push ecx
fstp qword ptr [esp]
call JIT_Dbl2Lng
mov ecx,eax
fnstsw ax
test ax,01h
jnz Dbl2LngOvf_throw
mov eax,ecx
ret 8
Dbl2LngOvf_throw:
mov ECX, CORINFO_OverflowException_ASM
call JIT_InternalThrowFromHelper
ret 8
JIT_Dbl2LngOvf ENDP
;*********************************************************************/
; JIT_Dbl2Lng
;Purpose:
; converts a double to a long truncating toward zero (C semantics)
;
; uses stdcall calling conventions
;
; note that changing the rounding mode is very expensive. This
; routine basiclly does the truncation sematics without changing
; the rounding mode, resulting in a win.
;
PUBLIC JIT_Dbl2Lng
JIT_Dbl2Lng PROC
fld qword ptr[ESP+4] ; fetch arg
lea ecx,[esp-8]
sub esp,16 ; allocate frame
and ecx,-8 ; align pointer on boundary of 8
fld st(0) ; duplciate top of stack
fistp qword ptr[ecx] ; leave arg on stack, also save in temp
fild qword ptr[ecx] ; arg, round(arg) now on stack
mov edx,[ecx+4] ; high dword of integer
mov eax,[ecx] ; low dword of integer
test eax,eax
je integer_QNaN_or_zero
arg_is_not_integer_QNaN:
fsubp st(1),st ; TOS=d-round(d),
; { st(1)=st(1)-st & pop ST }
test edx,edx ; what's sign of integer
jns positive
; number is negative
; dead cycle
; dead cycle
fstp dword ptr[ecx] ; result of subtraction
mov ecx,[ecx] ; dword of difference(single precision)
add esp,16
xor ecx,80000000h
add ecx,7fffffffh ; if difference>0 then increment integer
adc eax,0 ; inc eax (add CARRY flag)
adc edx,0 ; propagate carry flag to upper bits
ret 8
positive:
fstp dword ptr[ecx] ;17-18 ; result of subtraction
mov ecx,[ecx] ; dword of difference (single precision)
add esp,16
add ecx,7fffffffh ; if difference<0 then decrement integer
sbb eax,0 ; dec eax (subtract CARRY flag)
sbb edx,0 ; propagate carry flag to upper bits
ret 8
integer_QNaN_or_zero:
test edx,7fffffffh
jnz arg_is_not_integer_QNaN
fstp st(0) ;; pop round(arg)
fstp st(0) ;; arg
add esp,16
ret 8
JIT_Dbl2Lng ENDP
;*********************************************************************/
; JIT_Dbl2LngP4x87
;Purpose:
; converts a double to a long truncating toward zero (C semantics)
;
; uses stdcall calling conventions
;
; This code is faster on a P4 than the Dbl2Lng code above, but is
; slower on a PIII. Hence we choose this code when on a P4 or above.
;
PUBLIC JIT_Dbl2LngP4x87
JIT_Dbl2LngP4x87 PROC
arg1 equ <[esp+0Ch]>
sub esp, 8 ; get some local space
fld qword ptr arg1 ; fetch arg
fnstcw word ptr arg1 ; store FPCW
movzx eax, word ptr arg1 ; zero extend - wide
or ah, 0Ch ; turn on OE and DE flags
mov dword ptr [esp], eax ; store new FPCW bits
fldcw word ptr [esp] ; reload FPCW with new bits
fistp qword ptr [esp] ; convert
mov eax, dword ptr [esp] ; reload FP result
mov edx, dword ptr [esp+4] ;
fldcw word ptr arg1 ; reload original FPCW value
add esp, 8 ; restore stack
ret 8
JIT_Dbl2LngP4x87 ENDP
;*********************************************************************/
; JIT_Dbl2LngSSE3
;Purpose:
; converts a double to a long truncating toward zero (C semantics)
;
; uses stdcall calling conventions
;
; This code is faster than the above P4 x87 code for Intel processors
; equal or later than Core2 and Atom that have SSE3 support
;
.686P
.XMM
PUBLIC JIT_Dbl2LngSSE3
JIT_Dbl2LngSSE3 PROC
arg1 equ <[esp+0Ch]>
sub esp, 8 ; get some local space
fld qword ptr arg1 ; fetch arg
fisttp qword ptr [esp] ; convert
mov eax, dword ptr [esp] ; reload FP result
mov edx, dword ptr [esp+4]
add esp, 8 ; restore stack
ret 8
JIT_Dbl2LngSSE3 ENDP
.586
;*********************************************************************/
; JIT_Dbl2IntSSE2
;Purpose:
; converts a double to a long truncating toward zero (C semantics)
;
; uses stdcall calling conventions
;
; This code is even faster than the P4 x87 code for Dbl2LongP4x87,
; but only returns a 32 bit value (only good for int).
;
.686P
.XMM
PUBLIC JIT_Dbl2IntSSE2
JIT_Dbl2IntSSE2 PROC
$movsd xmm0, [esp+4]
cvttsd2si eax, xmm0
ret 8
JIT_Dbl2IntSSE2 ENDP
.586
;*********************************************************************/
; This is the small write barrier thunk we use when we know the
; ephemeral generation is higher in memory than older generations.
; The 0x0F0F0F0F values are bashed by the two functions above.
; This the generic version - wherever the code says ECX,
; the specific register is patched later into a copy
; Note: do not replace ECX by EAX - there is a smaller encoding for
; the compares just for EAX, which won't work for other registers.
;
; READ THIS!!!!!!
; it is imperative that the addresses of of the values that we overwrite
; (card table, ephemeral region ranges, etc) are naturally aligned since
; there are codepaths that will overwrite these values while the EE is running.
;
PUBLIC JIT_WriteBarrierReg_PreGrow
JIT_WriteBarrierReg_PreGrow PROC
mov DWORD PTR [edx], ecx
cmp ecx, 0F0F0F0F0h
jb NoWriteBarrierPre
shr edx, 10
nop ; padding for alignment of constant
cmp byte ptr [edx+0F0F0F0F0h], 0FFh
jne WriteBarrierPre
NoWriteBarrierPre:
ret
nop ; padding for alignment of constant
nop ; padding for alignment of constant
WriteBarrierPre:
mov byte ptr [edx+0F0F0F0F0h], 0FFh
ret
JIT_WriteBarrierReg_PreGrow ENDP
;*********************************************************************/
; This is the larger write barrier thunk we use when we know that older
; generations may be higher in memory than the ephemeral generation
; The 0x0F0F0F0F values are bashed by the two functions above.
; This the generic version - wherever the code says ECX,
; the specific register is patched later into a copy
; Note: do not replace ECX by EAX - there is a smaller encoding for
; the compares just for EAX, which won't work for other registers.
; NOTE: we need this aligned for our validation to work properly
ALIGN 4
PUBLIC JIT_WriteBarrierReg_PostGrow
JIT_WriteBarrierReg_PostGrow PROC
mov DWORD PTR [edx], ecx
cmp ecx, 0F0F0F0F0h
jb NoWriteBarrierPost
cmp ecx, 0F0F0F0F0h
jae NoWriteBarrierPost
shr edx, 10
nop ; padding for alignment of constant
cmp byte ptr [edx+0F0F0F0F0h], 0FFh
jne WriteBarrierPost
NoWriteBarrierPost:
ret
nop ; padding for alignment of constant
nop ; padding for alignment of constant
WriteBarrierPost:
mov byte ptr [edx+0F0F0F0F0h], 0FFh
ret
JIT_WriteBarrierReg_PostGrow ENDP
;*********************************************************************/
;
; a fake virtual stub dispatch register indirect callsite
$nop3
call dword ptr [eax]
PUBLIC JIT_TailCallReturnFromVSD
JIT_TailCallReturnFromVSD:
ifdef _DEBUG
nop ; blessed callsite
endif
call VSDHelperLabel ; keep call-ret count balanced.
VSDHelperLabel:
; Stack at this point :
; ...
; m_ReturnAddress
; m_regs
; m_CallerAddress
; m_pThread
; vtbl
; GSCookie
; &VSDHelperLabel
OffsetOfTailCallFrame = 8
; ebx = pThread
ifdef _DEBUG
mov esi, _s_gsCookie ; GetProcessGSCookie()
cmp dword ptr [esp+OffsetOfTailCallFrame-SIZEOF_GSCookie], esi
je TailCallFrameGSCookieIsValid
call @JIT_FailFast@0
TailCallFrameGSCookieIsValid:
endif
; remove the padding frame from the chain
mov esi, dword ptr [esp+OffsetOfTailCallFrame+4] ; esi = TailCallFrame::m_Next
mov dword ptr [ebx + Thread_m_pFrame], esi
; skip the frame
add esp, 20 ; &VSDHelperLabel, GSCookie, vtbl, m_Next, m_CallerAddress
pop edi ; restore callee saved registers
pop esi
pop ebx
pop ebp
ret ; return to m_ReturnAddress
;------------------------------------------------------------------------------
;
PUBLIC JIT_TailCall
JIT_TailCall PROC
; the stack layout at this point is:
;
; ebp+8+4*nOldStackArgs <- end of argument destination
; ... ...
; ebp+8+ old args (size is nOldStackArgs)
; ... ...
; ebp+8 <- start of argument destination
; ebp+4 ret addr
; ebp+0 saved ebp
; ebp-c saved ebx, esi, edi (if have callee saved regs = 1)
;
; other stuff (local vars) in the jitted callers' frame
;
; esp+20+4*nNewStackArgs <- end of argument source
; ... ...
; esp+20+ new args (size is nNewStackArgs) to be passed to the target of the tail-call
; ... ...
; esp+20 <- start of argument source
; esp+16 nOldStackArgs
; esp+12 nNewStackArgs
; esp+8 flags (1 = have callee saved regs, 2 = virtual stub dispatch)
; esp+4 target addr
; esp+0 retaddr
;
; If you change this function, make sure you update code:TailCallStubManager as well.
RetAddr equ 0
TargetAddr equ 4
nNewStackArgs equ 12
nOldStackArgs equ 16
NewArgs equ 20
; extra space is incremented as we push things on the stack along the way
ExtraSpace = 0
call _GetThread@0; eax = Thread*
push eax ; Thread*
; save ArgumentRegisters
push ecx
push edx
ExtraSpace = 12 ; pThread, ecx, edx
ifdef FEATURE_HIJACK
; Make sure that the EE does have the return address patched. So we can move it around.
test dword ptr [eax+Thread_m_State], TS_Hijacked_ASM
jz NoHijack
; JIT_TailCallHelper(Thread *)
push eax
call JIT_TailCallHelper ; this is __stdcall
NoHijack:
endif
mov edx, dword ptr [esp+ExtraSpace+JIT_TailCall_StackOffsetToFlags] ; edx = flags
mov eax, dword ptr [esp+ExtraSpace+nOldStackArgs] ; eax = nOldStackArgs
mov ecx, dword ptr [esp+ExtraSpace+nNewStackArgs] ; ecx = nNewStackArgs
; restore callee saved registers
; <TODO>@TODO : esp based - doesnt work with localloc</TODO>
test edx, 1
jz NoCalleeSaveRegisters
mov edi, dword ptr [ebp-4] ; restore edi
mov esi, dword ptr [ebp-8] ; restore esi
mov ebx, dword ptr [ebp-12] ; restore ebx
NoCalleeSaveRegisters:
push dword ptr [ebp+4] ; save the original return address for later
push edi
push esi
ExtraSpace = 24 ; pThread, ecx, edx, orig retaddr, edi, esi
CallersEsi = 0
CallersEdi = 4
OrigRetAddr = 8
pThread = 20
lea edi, [ebp+8+4*eax] ; edi = the end of argument destination
lea esi, [esp+ExtraSpace+NewArgs+4*ecx] ; esi = the end of argument source
mov ebp, dword ptr [ebp] ; restore ebp (do not use ebp as scratch register to get a good stack trace in debugger)
test edx, 2
jnz VSDTailCall
; copy the arguments to the final destination
test ecx, ecx
jz ArgumentsCopied
ArgumentCopyLoop:
; At this point, this is the value of the registers :
; edi = end of argument dest
; esi = end of argument source
; ecx = nNewStackArgs
mov eax, dword ptr [esi-4]
sub edi, 4
sub esi, 4
mov dword ptr [edi], eax
dec ecx
jnz ArgumentCopyLoop
ArgumentsCopied:
; edi = the start of argument destination
mov eax, dword ptr [esp+4+4] ; return address
mov ecx, dword ptr [esp+ExtraSpace+TargetAddr] ; target address
mov dword ptr [edi-4], eax ; return address
mov dword ptr [edi-8], ecx ; target address
lea eax, [edi-8] ; new value for esp
pop esi
pop edi
pop ecx ; skip original return address
pop edx
pop ecx
mov esp, eax
PUBLIC JIT_TailCallLeave ; add a label here so that TailCallStubManager can access it
JIT_TailCallLeave:
retn ; Will branch to targetAddr. This matches the
; "call" done by JITted code, keeping the
; call-ret count balanced.
;----------------------------------------------------------------------
VSDTailCall:
;----------------------------------------------------------------------
; For the Virtual Stub Dispatch, we create a fake callsite to fool
; the callsite probes. In order to create the call site, we need to insert TailCallFrame
; if we do not have one already.
;
; ecx = nNewStackArgs
; esi = the end of argument source
; edi = the end of argument destination
;
; The stub has pushed the following onto the stack at this point :
; pThread, ecx, edx, orig retaddr, edi, esi
cmp dword ptr [esp+OrigRetAddr], JIT_TailCallReturnFromVSD
jz VSDTailCallFrameInserted_DoSlideUpArgs ; There is an exiting TailCallFrame that can be reused
; try to allocate space for the frame / check whether there is enough space
; If there is sufficient space, we will setup the frame and then slide
; the arguments up the stack. Else, we first need to slide the arguments
; down the stack to make space for the TailCallFrame
sub edi, (SIZEOF_GSCookie + SIZEOF_TailCallFrame)
cmp edi, esi
jae VSDSpaceForFrameChecked
; There is not sufficient space to wedge in the TailCallFrame without
; overwriting the new arguments.
; We need to allocate the extra space on the stack,
; and slide down the new arguments
mov eax, esi
sub eax, edi
sub esp, eax
mov eax, ecx ; to subtract the size of arguments
mov edx, ecx ; for counter
neg eax
; copy down the arguments to the final destination, need to copy all temporary storage as well
add edx, (ExtraSpace+NewArgs)/4
lea esi, [esi+4*eax-(ExtraSpace+NewArgs)]
lea edi, [edi+4*eax-(ExtraSpace+NewArgs)]
VSDAllocFrameCopyLoop:
mov eax, dword ptr [esi]
mov dword ptr [edi], eax
add esi, 4
add edi, 4
dec edx
jnz VSDAllocFrameCopyLoop
; the argument source and destination are same now
mov esi, edi
VSDSpaceForFrameChecked:
; At this point, we have enough space on the stack for the TailCallFrame,
; and we may already have slided down the arguments
mov eax, _s_gsCookie ; GetProcessGSCookie()
mov dword ptr [edi], eax ; set GSCookie
mov eax, _g_TailCallFrameVptr ; vptr
mov edx, dword ptr [esp+OrigRetAddr] ; orig return address
mov dword ptr [edi+SIZEOF_GSCookie], eax ; TailCallFrame::vptr
mov dword ptr [edi+SIZEOF_GSCookie+28], edx ; TailCallFrame::m_ReturnAddress
mov eax, dword ptr [esp+CallersEdi] ; restored edi
mov edx, dword ptr [esp+CallersEsi] ; restored esi
mov dword ptr [edi+SIZEOF_GSCookie+12], eax ; TailCallFrame::m_regs::edi
mov dword ptr [edi+SIZEOF_GSCookie+16], edx ; TailCallFrame::m_regs::esi
mov dword ptr [edi+SIZEOF_GSCookie+20], ebx ; TailCallFrame::m_regs::ebx
mov dword ptr [edi+SIZEOF_GSCookie+24], ebp ; TailCallFrame::m_regs::ebp
mov ebx, dword ptr [esp+pThread] ; ebx = pThread
mov eax, dword ptr [ebx+Thread_m_pFrame]
lea edx, [edi+SIZEOF_GSCookie]
mov dword ptr [edi+SIZEOF_GSCookie+4], eax ; TailCallFrame::m_pNext
mov dword ptr [ebx+Thread_m_pFrame], edx ; hook the new frame into the chain
; setup ebp chain
lea ebp, [edi+SIZEOF_GSCookie+24] ; TailCallFrame::m_regs::ebp
; Do not copy arguments again if they are in place already
; Otherwise, we will need to slide the new arguments up the stack
cmp esi, edi
jne VSDTailCallFrameInserted_DoSlideUpArgs
; At this point, we must have already previously slided down the new arguments,
; or the TailCallFrame is a perfect fit
; set the caller address
mov edx, dword ptr [esp+ExtraSpace+RetAddr] ; caller address
mov dword ptr [edi+SIZEOF_GSCookie+8], edx ; TailCallFrame::m_CallerAddress
; adjust edi as it would by copying
neg ecx
lea edi, [edi+4*ecx]
jmp VSDArgumentsCopied
VSDTailCallFrameInserted_DoSlideUpArgs:
; set the caller address
mov edx, dword ptr [esp+ExtraSpace+RetAddr] ; caller address
mov dword ptr [edi+SIZEOF_GSCookie+8], edx ; TailCallFrame::m_CallerAddress
; copy the arguments to the final destination
test ecx, ecx
jz VSDArgumentsCopied
VSDArgumentCopyLoop:
mov eax, dword ptr [esi-4]
sub edi, 4
sub esi, 4
mov dword ptr [edi], eax
dec ecx
jnz VSDArgumentCopyLoop
VSDArgumentsCopied:
; edi = the start of argument destination
mov ecx, dword ptr [esp+ExtraSpace+TargetAddr] ; target address
mov dword ptr [edi-4], JIT_TailCallReturnFromVSD ; return address
mov dword ptr [edi-12], ecx ; address of indirection cell
mov ecx, [ecx]
mov dword ptr [edi-8], ecx ; target address
; skip original return address and saved esi, edi
add esp, 12
pop edx
pop ecx
lea esp, [edi-12] ; new value for esp
pop eax
PUBLIC JIT_TailCallVSDLeave ; add a label here so that TailCallStubManager can access it
JIT_TailCallVSDLeave:
retn ; Will branch to targetAddr. This matches the
; "call" done by JITted code, keeping the
; call-ret count balanced.
JIT_TailCall ENDP
;------------------------------------------------------------------------------
; HCIMPL2_VV(float, JIT_FltRem, float dividend, float divisor)
@JIT_FltRem@8 proc public
fld dword ptr [esp+4] ; divisor
fld dword ptr [esp+8] ; dividend
fremloop:
fprem
fstsw ax
fwait
sahf
jp fremloop ; Continue while the FPU status bit C2 is set
fxch ; swap, so divisor is on top and result is in st(1)
fstp ST(0) ; Pop the divisor from the FP stack
retn 8 ; Return value is in st(0)
@JIT_FltRem@8 endp
; HCIMPL2_VV(float, JIT_DblRem, float dividend, float divisor)
@JIT_DblRem@16 proc public
fld qword ptr [esp+4] ; divisor
fld qword ptr [esp+12] ; dividend
fremloopd:
fprem
fstsw ax
fwait
sahf
jp fremloopd ; Continue while the FPU status bit C2 is set
fxch ; swap, so divisor is on top and result is in st(1)
fstp ST(0) ; Pop the divisor from the FP stack
retn 16 ; Return value is in st(0)
@JIT_DblRem@16 endp
;------------------------------------------------------------------------------
g_SystemInfo TEXTEQU <?g_SystemInfo@@3U_SYSTEM_INFO@@A>
g_SpinConstants TEXTEQU <?g_SpinConstants@@3USpinConstants@@A>
g_pSyncTable TEXTEQU <?g_pSyncTable@@3PAVSyncTableEntry@@A>
JITutil_MonEnterWorker TEXTEQU <@JITutil_MonEnterWorker@4>
JITutil_MonReliableEnter TEXTEQU <@JITutil_MonReliableEnter@8>
JITutil_MonTryEnter TEXTEQU <@JITutil_MonTryEnter@12>
JITutil_MonExitWorker TEXTEQU <@JITutil_MonExitWorker@4>
JITutil_MonContention TEXTEQU <@JITutil_MonContention@4>
JITutil_MonReliableContention TEXTEQU <@JITutil_MonReliableContention@8>
JITutil_MonSignal TEXTEQU <@JITutil_MonSignal@4>
JIT_InternalThrow TEXTEQU <@JIT_InternalThrow@4>
EXTRN g_SystemInfo:BYTE
EXTRN g_SpinConstants:BYTE
EXTRN g_pSyncTable:DWORD
EXTRN JITutil_MonEnterWorker:PROC
EXTRN JITutil_MonReliableEnter:PROC
EXTRN JITutil_MonTryEnter:PROC
EXTRN JITutil_MonExitWorker:PROC
EXTRN JITutil_MonContention:PROC
EXTRN JITutil_MonReliableContention:PROC
EXTRN JITutil_MonSignal:PROC
EXTRN JIT_InternalThrow:PROC
ifdef MON_DEBUG
ifdef TRACK_SYNC
EnterSyncHelper TEXTEQU <_EnterSyncHelper@8>
LeaveSyncHelper TEXTEQU <_LeaveSyncHelper@8>
EXTRN EnterSyncHelper:PROC
EXTRN LeaveSyncHelper:PROC
endif ;TRACK_SYNC
endif ;MON_DEBUG
; The following macro is needed because MASM returns
; "instruction prefix not allowed" error message for
; rep nop mnemonic
$repnop MACRO
db 0F3h
db 090h
ENDM
; Safe ThreadAbort does not abort a thread if it is running finally or has lock counts.
; At the time we call Monitor.Enter, we initiate the abort if we can.
; We do not need to do the same for Monitor.Leave, since most of time, Monitor.Leave is called
; during finally.
;**********************************************************************
; This is a frameless helper for entering a monitor on a object.
; The object is in ARGUMENT_REG1. This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
; ***** NOTE: if you make any changes to this routine, build with MON_DEBUG undefined
; to make sure you don't break the non-debug build. This is very fragile code.
; Also, propagate the changes to jithelp.s which contains the same helper and assembly code
; (in AT&T syntax) for gnu assembler.
@JIT_MonEnterWorker@4 proc public
; Initialize delay value for retry with exponential backoff
push ebx
mov ebx, dword ptr g_SpinConstants+SpinConstants_dwInitialDuration
; We need yet another register to avoid refetching the thread object
push esi
; Check if the instance is NULL.
test ARGUMENT_REG1, ARGUMENT_REG1
jz MonEnterFramedLockHelper
call _GetThread@0
mov esi,eax
; Check if we can abort here
mov eax, [esi+Thread_m_State]
and eax, TS_CatchAtSafePoint_ASM
jz MonEnterRetryThinLock
; go through the slow code path to initiate ThreadAbort.
jmp MonEnterFramedLockHelper
MonEnterRetryThinLock:
; Fetch the object header dword
mov eax, [ARGUMENT_REG1-SyncBlockIndexOffset_ASM]
; Check whether we have the "thin lock" layout, the lock is free and the spin lock bit not set
; SBLK_COMBINED_MASK_ASM = BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK + SBLK_MASK_LOCK_THREADID + SBLK_MASK_LOCK_RECLEVEL
test eax, SBLK_COMBINED_MASK_ASM
jnz MonEnterNeedMoreTests
; Everything is fine - get the thread id to store in the lock
mov edx, [esi+Thread_m_ThreadId]
; If the thread id is too large, we need a syncblock for sure
cmp edx, SBLK_MASK_LOCK_THREADID_ASM
ja MonEnterFramedLockHelper
; We want to store a new value with the current thread id set in the low 10 bits
or edx,eax
lock cmpxchg dword ptr [ARGUMENT_REG1-SyncBlockIndexOffset_ASM], edx
jnz MonEnterPrepareToWaitThinLock
; Everything went fine and we're done
add [esi+Thread_m_dwLockCount],1
pop esi
pop ebx
ret
MonEnterNeedMoreTests:
; Ok, it's not the simple case - find out which case it is
test eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX_ASM
jnz MonEnterHaveHashOrSyncBlockIndex
; The header is transitioning or the lock - treat this as if the lock was taken
test eax, BIT_SBLK_SPIN_LOCK_ASM
jnz MonEnterPrepareToWaitThinLock
; Here we know we have the "thin lock" layout, but the lock is not free.
; It could still be the recursion case - compare the thread id to check
mov edx,eax
and edx, SBLK_MASK_LOCK_THREADID_ASM
cmp edx, [esi+Thread_m_ThreadId]
jne MonEnterPrepareToWaitThinLock
; Ok, the thread id matches, it's the recursion case.
; Bump up the recursion level and check for overflow
lea edx, [eax+SBLK_LOCK_RECLEVEL_INC_ASM]
test edx, SBLK_MASK_LOCK_RECLEVEL_ASM
jz MonEnterFramedLockHelper
; Try to put the new recursion level back. If the header was changed in the meantime,
; we need a full retry, because the layout could have changed.
lock cmpxchg [ARGUMENT_REG1-SyncBlockIndexOffset_ASM], edx
jnz MonEnterRetryHelperThinLock
; Everything went fine and we're done
pop esi
pop ebx
ret
MonEnterPrepareToWaitThinLock:
; If we are on an MP system, we try spinning for a certain number of iterations
cmp dword ptr g_SystemInfo+SYSTEM_INFO_dwNumberOfProcessors,1
jle MonEnterFramedLockHelper
; exponential backoff: delay by approximately 2*ebx clock cycles (on a PIII)
mov eax, ebx
MonEnterdelayLoopThinLock:
$repnop ; indicate to the CPU that we are spin waiting (useful for some Intel P4 multiprocs)
dec eax
jnz MonEnterdelayLoopThinLock
; next time, wait a factor longer
imul ebx, dword ptr g_SpinConstants+SpinConstants_dwBackoffFactor
cmp ebx, dword ptr g_SpinConstants+SpinConstants_dwMaximumDuration
jle MonEnterRetryHelperThinLock
jmp MonEnterFramedLockHelper
MonEnterRetryHelperThinLock:
jmp MonEnterRetryThinLock
MonEnterHaveHashOrSyncBlockIndex:
; If we have a hash code already, we need to create a sync block
test eax, BIT_SBLK_IS_HASHCODE_ASM
jnz MonEnterFramedLockHelper
; Ok, we have a sync block index - just and out the top bits and grab the syncblock index
and eax, MASK_SYNCBLOCKINDEX_ASM
; Get the sync block pointer.
mov ARGUMENT_REG2, dword ptr g_pSyncTable
mov ARGUMENT_REG2, [ARGUMENT_REG2+eax*SizeOfSyncTableEntry_ASM+SyncTableEntry_m_SyncBlock]
; Check if the sync block has been allocated.
test ARGUMENT_REG2, ARGUMENT_REG2
jz MonEnterFramedLockHelper
; Get a pointer to the lock object.
lea ARGUMENT_REG2, [ARGUMENT_REG2+SyncBlock_m_Monitor]
; Attempt to acquire the lock.
MonEnterRetrySyncBlock:
mov eax, [ARGUMENT_REG2+AwareLock_m_MonitorHeld]
test eax,eax
jne MonEnterHaveWaiters
; Common case, lock isn't held and there are no waiters. Attempt to
; gain ownership ourselves.
mov ARGUMENT_REG1,1
lock cmpxchg [ARGUMENT_REG2+AwareLock_m_MonitorHeld], ARGUMENT_REG1
jnz MonEnterRetryHelperSyncBlock
; Success. Save the thread object in the lock and increment the use count.
mov dword ptr [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
inc dword ptr [esi+Thread_m_dwLockCount]
inc dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG2 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop esi
pop ebx
ret
; It's possible to get here with waiters but no lock held, but in this
; case a signal is about to be fired which will wake up a waiter. So
; for fairness sake we should wait too.
; Check first for recursive lock attempts on the same thread.
MonEnterHaveWaiters:
; Is mutex already owned by current thread?
cmp [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
jne MonEnterPrepareToWait
; Yes, bump our use count.
inc dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG2 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop esi
pop ebx
ret
MonEnterPrepareToWait:
; If we are on an MP system, we try spinning for a certain number of iterations
cmp dword ptr g_SystemInfo+SYSTEM_INFO_dwNumberOfProcessors,1
jle MonEnterHaveWaiters1
; exponential backoff: delay by approximately 2*ebx clock cycles (on a PIII)
mov eax,ebx
MonEnterdelayLoop:
$repnop ; indicate to the CPU that we are spin waiting (useful for some Intel P4 multiprocs)
dec eax
jnz MonEnterdelayLoop
; next time, wait a factor longer
imul ebx, dword ptr g_SpinConstants+SpinConstants_dwBackoffFactor
cmp ebx, dword ptr g_SpinConstants+SpinConstants_dwMaximumDuration
jle MonEnterRetrySyncBlock
MonEnterHaveWaiters1:
pop esi
pop ebx
; Place AwareLock in arg1 then call contention helper.
mov ARGUMENT_REG1, ARGUMENT_REG2
jmp JITutil_MonContention
MonEnterRetryHelperSyncBlock:
jmp MonEnterRetrySyncBlock
; ECX has the object to synchronize on
MonEnterFramedLockHelper:
pop esi
pop ebx
jmp JITutil_MonEnterWorker
@JIT_MonEnterWorker@4 endp
;**********************************************************************
; This is a frameless helper for entering a monitor on a object, and
; setting a flag to indicate that the lock was taken.
; The object is in ARGUMENT_REG1. The flag is in ARGUMENT_REG2.
; This tries the normal case (no blocking or object allocation) in line
; and calls a framed helper for the other cases.
; ***** NOTE: if you make any changes to this routine, build with MON_DEBUG undefined
; to make sure you don't break the non-debug build. This is very fragile code.
; Also, propagate the changes to jithelp.s which contains the same helper and assembly code
; (in AT&T syntax) for gnu assembler.
@JIT_MonReliableEnter@8 proc public
; Initialize delay value for retry with exponential backoff
push ebx
mov ebx, dword ptr g_SpinConstants+SpinConstants_dwInitialDuration
; Put pbLockTaken in edi
push edi
mov edi, ARGUMENT_REG2
; We need yet another register to avoid refetching the thread object
push esi
; Check if the instance is NULL.
test ARGUMENT_REG1, ARGUMENT_REG1
jz MonReliableEnterFramedLockHelper
call _GetThread@0
mov esi,eax
; Check if we can abort here
mov eax, [esi+Thread_m_State]
and eax, TS_CatchAtSafePoint_ASM
jz MonReliableEnterRetryThinLock
; go through the slow code path to initiate ThreadAbort.
jmp MonReliableEnterFramedLockHelper
MonReliableEnterRetryThinLock:
; Fetch the object header dword
mov eax, [ARGUMENT_REG1-SyncBlockIndexOffset_ASM]
; Check whether we have the "thin lock" layout, the lock is free and the spin lock bit not set
; SBLK_COMBINED_MASK_ASM = BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK + SBLK_MASK_LOCK_THREADID + SBLK_MASK_LOCK_RECLEVEL
test eax, SBLK_COMBINED_MASK_ASM
jnz MonReliableEnterNeedMoreTests
; Everything is fine - get the thread id to store in the lock
mov edx, [esi+Thread_m_ThreadId]
; If the thread id is too large, we need a syncblock for sure
cmp edx, SBLK_MASK_LOCK_THREADID_ASM
ja MonReliableEnterFramedLockHelper
; We want to store a new value with the current thread id set in the low 10 bits
or edx,eax
lock cmpxchg dword ptr [ARGUMENT_REG1-SyncBlockIndexOffset_ASM], edx
jnz MonReliableEnterPrepareToWaitThinLock
; Everything went fine and we're done
add [esi+Thread_m_dwLockCount],1
; Set *pbLockTaken=true
mov byte ptr [edi],1
pop esi
pop edi
pop ebx
ret
MonReliableEnterNeedMoreTests:
; Ok, it's not the simple case - find out which case it is
test eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX_ASM
jnz MonReliableEnterHaveHashOrSyncBlockIndex
; The header is transitioning or the lock - treat this as if the lock was taken
test eax, BIT_SBLK_SPIN_LOCK_ASM
jnz MonReliableEnterPrepareToWaitThinLock
; Here we know we have the "thin lock" layout, but the lock is not free.
; It could still be the recursion case - compare the thread id to check
mov edx,eax
and edx, SBLK_MASK_LOCK_THREADID_ASM
cmp edx, [esi+Thread_m_ThreadId]
jne MonReliableEnterPrepareToWaitThinLock
; Ok, the thread id matches, it's the recursion case.
; Bump up the recursion level and check for overflow
lea edx, [eax+SBLK_LOCK_RECLEVEL_INC_ASM]
test edx, SBLK_MASK_LOCK_RECLEVEL_ASM
jz MonReliableEnterFramedLockHelper
; Try to put the new recursion level back. If the header was changed in the meantime,
; we need a full retry, because the layout could have changed.
lock cmpxchg [ARGUMENT_REG1-SyncBlockIndexOffset_ASM], edx
jnz MonReliableEnterRetryHelperThinLock
; Everything went fine and we're done
; Set *pbLockTaken=true
mov byte ptr [edi],1
pop esi
pop edi
pop ebx
ret
MonReliableEnterPrepareToWaitThinLock:
; If we are on an MP system, we try spinning for a certain number of iterations
cmp dword ptr g_SystemInfo+SYSTEM_INFO_dwNumberOfProcessors,1
jle MonReliableEnterFramedLockHelper
; exponential backoff: delay by approximately 2*ebx clock cycles (on a PIII)
mov eax, ebx
MonReliableEnterdelayLoopThinLock:
$repnop ; indicate to the CPU that we are spin waiting (useful for some Intel P4 multiprocs)
dec eax
jnz MonReliableEnterdelayLoopThinLock
; next time, wait a factor longer
imul ebx, dword ptr g_SpinConstants+SpinConstants_dwBackoffFactor
cmp ebx, dword ptr g_SpinConstants+SpinConstants_dwMaximumDuration
jle MonReliableEnterRetryHelperThinLock
jmp MonReliableEnterFramedLockHelper
MonReliableEnterRetryHelperThinLock:
jmp MonReliableEnterRetryThinLock
MonReliableEnterHaveHashOrSyncBlockIndex:
; If we have a hash code already, we need to create a sync block
test eax, BIT_SBLK_IS_HASHCODE_ASM
jnz MonReliableEnterFramedLockHelper
; Ok, we have a sync block index - just and out the top bits and grab the syncblock index
and eax, MASK_SYNCBLOCKINDEX_ASM
; Get the sync block pointer.
mov ARGUMENT_REG2, dword ptr g_pSyncTable
mov ARGUMENT_REG2, [ARGUMENT_REG2+eax*SizeOfSyncTableEntry_ASM+SyncTableEntry_m_SyncBlock]
; Check if the sync block has been allocated.
test ARGUMENT_REG2, ARGUMENT_REG2
jz MonReliableEnterFramedLockHelper
; Get a pointer to the lock object.
lea ARGUMENT_REG2, [ARGUMENT_REG2+SyncBlock_m_Monitor]
; Attempt to acquire the lock.
MonReliableEnterRetrySyncBlock:
mov eax, [ARGUMENT_REG2+AwareLock_m_MonitorHeld]
test eax,eax
jne MonReliableEnterHaveWaiters
; Common case, lock isn't held and there are no waiters. Attempt to
; gain ownership ourselves.
mov ARGUMENT_REG1,1
lock cmpxchg [ARGUMENT_REG2+AwareLock_m_MonitorHeld], ARGUMENT_REG1
jnz MonReliableEnterRetryHelperSyncBlock
; Success. Save the thread object in the lock and increment the use count.
mov dword ptr [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
inc dword ptr [esi+Thread_m_dwLockCount]
inc dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
; Set *pbLockTaken=true
mov byte ptr [edi],1
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG2 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop esi
pop edi
pop ebx
ret
; It's possible to get here with waiters but no lock held, but in this
; case a signal is about to be fired which will wake up a waiter. So
; for fairness sake we should wait too.
; Check first for recursive lock attempts on the same thread.
MonReliableEnterHaveWaiters:
; Is mutex already owned by current thread?
cmp [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
jne MonReliableEnterPrepareToWait
; Yes, bump our use count.
inc dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
; Set *pbLockTaken=true
mov byte ptr [edi],1
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG2 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop esi
pop edi
pop ebx
ret
MonReliableEnterPrepareToWait:
; If we are on an MP system, we try spinning for a certain number of iterations
cmp dword ptr g_SystemInfo+SYSTEM_INFO_dwNumberOfProcessors,1
jle MonReliableEnterHaveWaiters1
; exponential backoff: delay by approximately 2*ebx clock cycles (on a PIII)
mov eax,ebx
MonReliableEnterdelayLoop:
$repnop ; indicate to the CPU that we are spin waiting (useful for some Intel P4 multiprocs)
dec eax
jnz MonReliableEnterdelayLoop
; next time, wait a factor longer
imul ebx, dword ptr g_SpinConstants+SpinConstants_dwBackoffFactor
cmp ebx, dword ptr g_SpinConstants+SpinConstants_dwMaximumDuration
jle MonReliableEnterRetrySyncBlock
MonReliableEnterHaveWaiters1:
; Place AwareLock in arg1, pbLockTaken in arg2, then call contention helper.
mov ARGUMENT_REG1, ARGUMENT_REG2
mov ARGUMENT_REG2, edi
pop esi
pop edi
pop ebx
jmp JITutil_MonReliableContention
MonReliableEnterRetryHelperSyncBlock:
jmp MonReliableEnterRetrySyncBlock
; ECX has the object to synchronize on
MonReliableEnterFramedLockHelper:
mov ARGUMENT_REG2, edi
pop esi
pop edi
pop ebx
jmp JITutil_MonReliableEnter
@JIT_MonReliableEnter@8 endp
;************************************************************************
; This is a frameless helper for trying to enter a monitor on a object.
; The object is in ARGUMENT_REG1 and a timeout in ARGUMENT_REG2. This tries the
; normal case (no object allocation) in line and calls a framed helper for the
; other cases.
; ***** NOTE: if you make any changes to this routine, build with MON_DEBUG undefined
; to make sure you don't break the non-debug build. This is very fragile code.
; Also, propagate the changes to jithelp.s which contains the same helper and assembly code
; (in AT&T syntax) for gnu assembler.
@JIT_MonTryEnter@12 proc public
; Save the timeout parameter.
push ARGUMENT_REG2
; Initialize delay value for retry with exponential backoff
push ebx
mov ebx, dword ptr g_SpinConstants+SpinConstants_dwInitialDuration
; The thin lock logic needs another register to store the thread
push esi
; Check if the instance is NULL.
test ARGUMENT_REG1, ARGUMENT_REG1
jz MonTryEnterFramedLockHelper
; Check if the timeout looks valid
cmp ARGUMENT_REG2,-1
jl MonTryEnterFramedLockHelper
; Get the thread right away, we'll need it in any case
call _GetThread@0
mov esi,eax
; Check if we can abort here
mov eax, [esi+Thread_m_State]
and eax, TS_CatchAtSafePoint_ASM
jz MonTryEnterRetryThinLock
; go through the slow code path to initiate ThreadAbort.
jmp MonTryEnterFramedLockHelper
MonTryEnterRetryThinLock:
; Get the header dword and check its layout
mov eax, [ARGUMENT_REG1-SyncBlockIndexOffset_ASM]
; Check whether we have the "thin lock" layout, the lock is free and the spin lock bit not set
; SBLK_COMBINED_MASK_ASM = BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK + SBLK_MASK_LOCK_THREADID + SBLK_MASK_LOCK_RECLEVEL
test eax, SBLK_COMBINED_MASK_ASM
jnz MonTryEnterNeedMoreTests
; Ok, everything is fine. Fetch the thread id and make sure it's small enough for thin locks
mov edx, [esi+Thread_m_ThreadId]
cmp edx, SBLK_MASK_LOCK_THREADID_ASM
ja MonTryEnterFramedLockHelper
; Try to put our thread id in there
or edx,eax
lock cmpxchg [ARGUMENT_REG1-SyncBlockIndexOffset_ASM],edx
jnz MonTryEnterRetryHelperThinLock
; Got the lock - everything is fine"
add [esi+Thread_m_dwLockCount],1
pop esi
; Delay value no longer needed
pop ebx
; Timeout parameter not needed, ditch it from the stack.
add esp,4
mov eax, [esp+4]
mov byte ptr [eax], 1
ret 4
MonTryEnterNeedMoreTests:
; Ok, it's not the simple case - find out which case it is
test eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX_ASM
jnz MonTryEnterHaveSyncBlockIndexOrHash
; The header is transitioning or the lock is taken
test eax, BIT_SBLK_SPIN_LOCK_ASM
jnz MonTryEnterRetryHelperThinLock
mov edx, eax
and edx, SBLK_MASK_LOCK_THREADID_ASM
cmp edx, [esi+Thread_m_ThreadId]
jne MonTryEnterPrepareToWaitThinLock
; Ok, the thread id matches, it's the recursion case.
; Bump up the recursion level and check for overflow
lea edx, [eax+SBLK_LOCK_RECLEVEL_INC_ASM]
test edx, SBLK_MASK_LOCK_RECLEVEL_ASM
jz MonTryEnterFramedLockHelper
; Try to put the new recursion level back. If the header was changed in the meantime,
; we need a full retry, because the layout could have changed.
lock cmpxchg [ARGUMENT_REG1-SyncBlockIndexOffset_ASM],edx
jnz MonTryEnterRetryHelperThinLock
; Everything went fine and we're done
pop esi
pop ebx
; Timeout parameter not needed, ditch it from the stack.
add esp, 4
mov eax, [esp+4]
mov byte ptr [eax], 1
ret 4
MonTryEnterPrepareToWaitThinLock:
; If we are on an MP system, we try spinning for a certain number of iterations
cmp dword ptr g_SystemInfo+SYSTEM_INFO_dwNumberOfProcessors,1
jle MonTryEnterFramedLockHelper
; exponential backoff: delay by approximately 2*ebx clock cycles (on a PIII)
mov eax, ebx
MonTryEnterdelayLoopThinLock:
$repnop ; indicate to the CPU that we are spin waiting (useful for some Intel P4 multiprocs)
dec eax
jnz MonTryEnterdelayLoopThinLock
; next time, wait a factor longer
imul ebx, dword ptr g_SpinConstants+SpinConstants_dwBackoffFactor
cmp ebx, dword ptr g_SpinConstants+SpinConstants_dwMaximumDuration
jle MonTryEnterRetryHelperThinLock
jmp MonTryEnterWouldBlock
MonTryEnterRetryHelperThinLock:
jmp MonTryEnterRetryThinLock
MonTryEnterHaveSyncBlockIndexOrHash:
; If we have a hash code already, we need to create a sync block
test eax, BIT_SBLK_IS_HASHCODE_ASM
jnz MonTryEnterFramedLockHelper
; Just and out the top bits and grab the syncblock index
and eax, MASK_SYNCBLOCKINDEX_ASM
; Get the sync block pointer.
mov ARGUMENT_REG2, dword ptr g_pSyncTable
mov ARGUMENT_REG2, [ARGUMENT_REG2+eax*SizeOfSyncTableEntry_ASM+SyncTableEntry_m_SyncBlock]
; Check if the sync block has been allocated.
test ARGUMENT_REG2, ARGUMENT_REG2
jz MonTryEnterFramedLockHelper
; Get a pointer to the lock object.
lea ARGUMENT_REG2, [ARGUMENT_REG2+SyncBlock_m_Monitor]
MonTryEnterRetrySyncBlock:
; Attempt to acquire the lock.
mov eax, [ARGUMENT_REG2+AwareLock_m_MonitorHeld]
test eax,eax
jne MonTryEnterHaveWaiters
; We need another scratch register for what follows, so save EBX now so"
; we can use it for that purpose."
push ebx
; Common case, lock isn't held and there are no waiters. Attempt to
; gain ownership ourselves.
mov ebx,1
lock cmpxchg [ARGUMENT_REG2+AwareLock_m_MonitorHeld],ebx
pop ebx
jnz MonTryEnterRetryHelperSyncBlock
; Success. Save the thread object in the lock and increment the use count.
mov dword ptr [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
inc dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
inc dword ptr [esi+Thread_m_dwLockCount]
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG2 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop esi
pop ebx
; Timeout parameter not needed, ditch it from the stack."
add esp,4
mov eax, [esp+4]
mov byte ptr [eax], 1
ret 4
; It's possible to get here with waiters but no lock held, but in this
; case a signal is about to be fired which will wake up a waiter. So
; for fairness sake we should wait too.
; Check first for recursive lock attempts on the same thread.
MonTryEnterHaveWaiters:
; Is mutex already owned by current thread?
cmp [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
jne MonTryEnterPrepareToWait
; Yes, bump our use count.
inc dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG2 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop esi
pop ebx
; Timeout parameter not needed, ditch it from the stack.
add esp,4
mov eax, [esp+4]
mov byte ptr [eax], 1
ret 4
MonTryEnterPrepareToWait:
; If we are on an MP system, we try spinning for a certain number of iterations
cmp dword ptr g_SystemInfo+SYSTEM_INFO_dwNumberOfProcessors,1
jle MonTryEnterWouldBlock
; exponential backoff: delay by approximately 2*ebx clock cycles (on a PIII)
mov eax, ebx
MonTryEnterdelayLoop:
$repnop ; indicate to the CPU that we are spin waiting (useful for some Intel P4 multiprocs)
dec eax
jnz MonTryEnterdelayLoop
; next time, wait a factor longer
imul ebx, dword ptr g_SpinConstants+SpinConstants_dwBackoffFactor
cmp ebx, dword ptr g_SpinConstants+SpinConstants_dwMaximumDuration
jle MonTryEnterRetrySyncBlock
; We would need to block to enter the section. Return failure if
; timeout is zero, else call the framed helper to do the blocking
; form of TryEnter."
MonTryEnterWouldBlock:
pop esi
pop ebx
pop ARGUMENT_REG2
test ARGUMENT_REG2, ARGUMENT_REG2
jnz MonTryEnterBlock
mov eax, [esp+4]
mov byte ptr [eax], 0
ret 4
MonTryEnterRetryHelperSyncBlock:
jmp MonTryEnterRetrySyncBlock
MonTryEnterFramedLockHelper:
; ARGUMENT_REG1 has the object to synchronize on, must retrieve the
; timeout parameter from the stack.
pop esi
pop ebx
pop ARGUMENT_REG2
MonTryEnterBlock:
jmp JITutil_MonTryEnter
@JIT_MonTryEnter@12 endp
;**********************************************************************
; This is a frameless helper for exiting a monitor on a object.
; The object is in ARGUMENT_REG1. This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
; ***** NOTE: if you make any changes to this routine, build with MON_DEBUG undefined
; to make sure you don't break the non-debug build. This is very fragile code.
; Also, propagate the changes to jithelp.s which contains the same helper and assembly code
; (in AT&T syntax) for gnu assembler.
@JIT_MonExitWorker@4 proc public
; The thin lock logic needs an additional register to hold the thread, unfortunately
push esi
; Check if the instance is NULL.
test ARGUMENT_REG1, ARGUMENT_REG1
jz MonExitFramedLockHelper
call _GetThread@0
mov esi,eax
MonExitRetryThinLock:
; Fetch the header dword and check its layout and the spin lock bit
mov eax, [ARGUMENT_REG1-SyncBlockIndexOffset_ASM]
;BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX_SPIN_LOCK_ASM = BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX + BIT_SBLK_SPIN_LOCK
test eax, BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX_SPIN_LOCK_ASM
jnz MonExitNeedMoreTests
; Ok, we have a "thin lock" layout - check whether the thread id matches
mov edx,eax
and edx, SBLK_MASK_LOCK_THREADID_ASM
cmp edx, [esi+Thread_m_ThreadId]
jne MonExitFramedLockHelper
; Check the recursion level
test eax, SBLK_MASK_LOCK_RECLEVEL_ASM
jne MonExitDecRecursionLevel
; It's zero - we're leaving the lock.
; So try to put back a zero thread id.
; edx and eax match in the thread id bits, and edx is zero elsewhere, so the xor is sufficient
xor edx,eax
lock cmpxchg [ARGUMENT_REG1-SyncBlockIndexOffset_ASM],edx
jnz MonExitRetryHelperThinLock
; We're done
sub [esi+Thread_m_dwLockCount],1
pop esi
ret
MonExitDecRecursionLevel:
lea edx, [eax-SBLK_LOCK_RECLEVEL_INC_ASM]
lock cmpxchg [ARGUMENT_REG1-SyncBlockIndexOffset_ASM],edx
jnz MonExitRetryHelperThinLock
; We're done
pop esi
ret
MonExitNeedMoreTests:
;Forward all special cases to the slow helper
;BIT_SBLK_IS_HASHCODE_OR_SPIN_LOCK_ASM = BIT_SBLK_IS_HASHCODE + BIT_SBLK_SPIN_LOCK
test eax, BIT_SBLK_IS_HASHCODE_OR_SPIN_LOCK_ASM
jnz MonExitFramedLockHelper
; Get the sync block index and use it to compute the sync block pointer
mov ARGUMENT_REG2, dword ptr g_pSyncTable
and eax, MASK_SYNCBLOCKINDEX_ASM
mov ARGUMENT_REG2, [ARGUMENT_REG2+eax*SizeOfSyncTableEntry_ASM+SyncTableEntry_m_SyncBlock]
; was there a sync block?
test ARGUMENT_REG2, ARGUMENT_REG2
jz MonExitFramedLockHelper
; Get a pointer to the lock object.
lea ARGUMENT_REG2, [ARGUMENT_REG2+SyncBlock_m_Monitor]
; Check if lock is held.
cmp [ARGUMENT_REG2+AwareLock_m_HoldingThread],esi
jne MonExitFramedLockHelper
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG1 ; preserve regs
push ARGUMENT_REG2
push ARGUMENT_REG2 ; AwareLock
push [esp+8] ; return address
call LeaveSyncHelper
pop ARGUMENT_REG2 ; restore regs
pop ARGUMENT_REG1
endif ;TRACK_SYNC
endif ;MON_DEBUG
; Reduce our recursion count.
dec dword ptr [ARGUMENT_REG2+AwareLock_m_Recursion]
jz MonExitLastRecursion
pop esi
ret
MonExitRetryHelperThinLock:
jmp MonExitRetryThinLock
MonExitFramedLockHelper:
pop esi
jmp JITutil_MonExitWorker
; This is the last count we held on this lock, so release the lock.
MonExitLastRecursion:
dec dword ptr [esi+Thread_m_dwLockCount]
mov dword ptr [ARGUMENT_REG2+AwareLock_m_HoldingThread],0
MonExitRetry:
mov eax, [ARGUMENT_REG2+AwareLock_m_MonitorHeld]
lea esi, [eax-1]
lock cmpxchg [ARGUMENT_REG2+AwareLock_m_MonitorHeld], esi
jne MonExitRetryHelper
pop esi
test eax,0FFFFFFFEh
jne MonExitMustSignal
ret
MonExitMustSignal:
mov ARGUMENT_REG1, ARGUMENT_REG2
jmp JITutil_MonSignal
MonExitRetryHelper:
jmp MonExitRetry
@JIT_MonExitWorker@4 endp
;**********************************************************************
; This is a frameless helper for entering a static monitor on a class.
; The methoddesc is in ARGUMENT_REG1. This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
; Note we are changing the methoddesc parameter to a pointer to the
; AwareLock.
; ***** NOTE: if you make any changes to this routine, build with MON_DEBUG undefined
; to make sure you don't break the non-debug build. This is very fragile code.
; Also, propagate the changes to jithelp.s which contains the same helper and assembly code
; (in AT&T syntax) for gnu assembler.
@JIT_MonEnterStatic@4 proc public
; We need another scratch register for what follows, so save EBX now so
; we can use it for that purpose.
push ebx
; Attempt to acquire the lock
MonEnterStaticRetry:
mov eax, [ARGUMENT_REG1+AwareLock_m_MonitorHeld]
test eax,eax
jne MonEnterStaticHaveWaiters
; Common case, lock isn't held and there are no waiters. Attempt to
; gain ownership ourselves.
mov ebx,1
lock cmpxchg [ARGUMENT_REG1+AwareLock_m_MonitorHeld],ebx
jnz MonEnterStaticRetryHelper
pop ebx
; Success. Save the thread object in the lock and increment the use count.
call _GetThread@0
mov [ARGUMENT_REG1+AwareLock_m_HoldingThread], eax
inc dword ptr [ARGUMENT_REG1+AwareLock_m_Recursion]
inc dword ptr [eax+Thread_m_dwLockCount]
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG1 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
ret
; It's possible to get here with waiters but no lock held, but in this
; case a signal is about to be fired which will wake up a waiter. So
; for fairness sake we should wait too.
; Check first for recursive lock attempts on the same thread.
MonEnterStaticHaveWaiters:
; Get thread but preserve EAX (contains cached contents of m_MonitorHeld).
push eax
call _GetThread@0
mov ebx,eax
pop eax
; Is mutex already owned by current thread?
cmp [ARGUMENT_REG1+AwareLock_m_HoldingThread],ebx
jne MonEnterStaticPrepareToWait
; Yes, bump our use count.
inc dword ptr [ARGUMENT_REG1+AwareLock_m_Recursion]
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG1 ; AwareLock
push [esp+4] ; return address
call EnterSyncHelper
endif ;TRACK_SYNC
endif ;MON_DEBUG
pop ebx
ret
MonEnterStaticPrepareToWait:
pop ebx
; ARGUMENT_REG1 should have AwareLock. Call contention helper.
jmp JITutil_MonContention
MonEnterStaticRetryHelper:
jmp MonEnterStaticRetry
@JIT_MonEnterStatic@4 endp
;**********************************************************************
; A frameless helper for exiting a static monitor on a class.
; The methoddesc is in ARGUMENT_REG1. This tries the normal case (no
; blocking or object allocation) in line and calls a framed helper
; for the other cases.
; Note we are changing the methoddesc parameter to a pointer to the
; AwareLock.
; ***** NOTE: if you make any changes to this routine, build with MON_DEBUG undefined
; to make sure you don't break the non-debug build. This is very fragile code.
; Also, propagate the changes to jithelp.s which contains the same helper and assembly code
; (in AT&T syntax) for gnu assembler.
@JIT_MonExitStatic@4 proc public
ifdef MON_DEBUG
ifdef TRACK_SYNC
push ARGUMENT_REG1 ; preserve regs
push ARGUMENT_REG1 ; AwareLock
push [esp+8] ; return address
call LeaveSyncHelper
pop [ARGUMENT_REG1] ; restore regs
endif ;TRACK_SYNC
endif ;MON_DEBUG
; Check if lock is held.
call _GetThread@0
cmp [ARGUMENT_REG1+AwareLock_m_HoldingThread],eax
jne MonExitStaticLockError
; Reduce our recursion count.
dec dword ptr [ARGUMENT_REG1+AwareLock_m_Recursion]
jz MonExitStaticLastRecursion
ret
; This is the last count we held on this lock, so release the lock.
MonExitStaticLastRecursion:
; eax must have the thread object
dec dword ptr [eax+Thread_m_dwLockCount]
mov dword ptr [ARGUMENT_REG1+AwareLock_m_HoldingThread],0
push ebx
MonExitStaticRetry:
mov eax, [ARGUMENT_REG1+AwareLock_m_MonitorHeld]
lea ebx, [eax-1]
lock cmpxchg [ARGUMENT_REG1+AwareLock_m_MonitorHeld],ebx
jne MonExitStaticRetryHelper
pop ebx
test eax,0FFFFFFFEh
jne MonExitStaticMustSignal
ret
MonExitStaticMustSignal:
jmp JITutil_MonSignal
MonExitStaticRetryHelper:
jmp MonExitStaticRetry
; Throw a synchronization lock exception.
MonExitStaticLockError:
mov ARGUMENT_REG1, CORINFO_SynchronizationLockException_ASM
jmp JIT_InternalThrow
@JIT_MonExitStatic@4 endp
; PatchedCodeStart and PatchedCodeEnd are used to determine bounds of patched code.
;
_JIT_PatchedCodeStart@0 proc public
ret
_JIT_PatchedCodeStart@0 endp
;
; Optimized TLS getters
;
ALIGN 4
ifndef FEATURE_IMPLICIT_TLS
_GetThread@0 proc public
; This will be overwritten at runtime with optimized GetThread implementation
jmp short _GetTLSDummy@0
; Just allocate space that will be filled in at runtime
db (TLS_GETTER_MAX_SIZE_ASM - 2) DUP (0CCh)
_GetThread@0 endp
ALIGN 4
_GetAppDomain@0 proc public
; This will be overwritten at runtime with optimized GetAppDomain implementation
jmp short _GetTLSDummy@0
; Just allocate space that will be filled in at runtime
db (TLS_GETTER_MAX_SIZE_ASM - 2) DUP (0CCh)
_GetAppDomain@0 endp
_GetTLSDummy@0 proc public
xor eax,eax
ret
_GetTLSDummy@0 endp
ALIGN 4
_ClrFlsGetBlock@0 proc public
; This will be overwritten at runtime with optimized ClrFlsGetBlock implementation
jmp short _GetTLSDummy@0
; Just allocate space that will be filled in at runtime
db (TLS_GETTER_MAX_SIZE_ASM - 2) DUP (0CCh)
_ClrFlsGetBlock@0 endp
endif
;**********************************************************************
; Write barriers generated at runtime
PUBLIC _JIT_PatchedWriteBarrierGroup@0
_JIT_PatchedWriteBarrierGroup@0 PROC
ret
_JIT_PatchedWriteBarrierGroup@0 ENDP
PatchedWriteBarrierHelper MACRO rg
ALIGN 8
PUBLIC _JIT_WriteBarrier&rg&@0
_JIT_WriteBarrier&rg&@0 PROC
; Just allocate space that will be filled in at runtime
db (48) DUP (0CCh)
_JIT_WriteBarrier&rg&@0 ENDP
ENDM
PatchedWriteBarrierHelper <EAX>
PatchedWriteBarrierHelper <EBX>
PatchedWriteBarrierHelper <ECX>
PatchedWriteBarrierHelper <ESI>
PatchedWriteBarrierHelper <EDI>
PatchedWriteBarrierHelper <EBP>
PUBLIC _JIT_PatchedWriteBarrierGroup_End@0
_JIT_PatchedWriteBarrierGroup_End@0 PROC
ret
_JIT_PatchedWriteBarrierGroup_End@0 ENDP
_JIT_PatchedCodeLast@0 proc public
ret
_JIT_PatchedCodeLast@0 endp
; This is the first function outside the "keep together range". Used by BBT scripts.
_JIT_PatchedCodeEnd@0 proc public
ret
_JIT_PatchedCodeEnd@0 endp
; This is the ASM portion of JIT_IsInstanceOfInterface. For all the bizarre cases, it quickly
; fails and falls back on the JITutil_IsInstanceOfAny helper. So all failure cases take
; the slow path, too.
;
; ARGUMENT_REG1 = array or interface to check for.
; ARGUMENT_REG2 = instance to be cast.
ALIGN 16
PUBLIC @JIT_IsInstanceOfInterface@8
@JIT_IsInstanceOfInterface@8 PROC
test ARGUMENT_REG2, ARGUMENT_REG2
jz IsNullInst
mov eax, [ARGUMENT_REG2] ; get MethodTable
push ebx
push esi
movzx ebx, word ptr [eax+MethodTable_m_wNumInterfaces]
; check if this MT implements any interfaces
test ebx, ebx
jz IsInstanceOfInterfaceDoBizarre
; move Interface map ptr into eax
mov eax, [eax+MethodTable_m_pInterfaceMap]
IsInstanceOfInterfaceTop:
; eax -> current InterfaceInfo_t entry in interface map list
ifdef FEATURE_PREJIT
mov esi, [eax]
test esi, 1
; Move the deference out of line so that this jump is correctly predicted for the case
; when there is no indirection
jnz IsInstanceOfInterfaceIndir
cmp ARGUMENT_REG1, esi
else
cmp ARGUMENT_REG1, [eax]
endif
je IsInstanceOfInterfaceFound
IsInstanceOfInterfaceNext:
add eax, SIZEOF_InterfaceInfo_t
dec ebx
jnz IsInstanceOfInterfaceTop
; fall through to DoBizarre
IsInstanceOfInterfaceDoBizarre:
pop esi
pop ebx
mov eax, [ARGUMENT_REG2] ; get MethodTable
test dword ptr [eax+MethodTable_m_dwFlags], NonTrivialInterfaceCastFlags
jnz IsInstanceOfInterfaceNonTrivialCast
IsNullInst:
xor eax,eax
ret
ifdef FEATURE_PREJIT
IsInstanceOfInterfaceIndir:
cmp ARGUMENT_REG1,[esi-1]
jne IsInstanceOfInterfaceNext
endif
IsInstanceOfInterfaceFound:
pop esi
pop ebx
mov eax, ARGUMENT_REG2 ; the successful instance
ret
IsInstanceOfInterfaceNonTrivialCast:
jmp @JITutil_IsInstanceOfInterface@8
@JIT_IsInstanceOfInterface@8 endp
; This is the ASM portion of JIT_ChkCastInterface. For all the bizarre cases, it quickly
; fails and falls back on the JITutil_ChkCastAny helper. So all failure cases take
; the slow path, too.
;
; ARGUMENT_REG1 = array or interface to check for.
; ARGUMENT_REG2 = instance to be cast.
ALIGN 16
PUBLIC @JIT_ChkCastInterface@8
@JIT_ChkCastInterface@8 PROC
test ARGUMENT_REG2, ARGUMENT_REG2
jz ChkCastInterfaceIsNullInst
mov eax, [ARGUMENT_REG2] ; get MethodTable
push ebx
push esi
movzx ebx, word ptr [eax+MethodTable_m_wNumInterfaces]
; speculatively move Interface map ptr into eax
mov eax, [eax+MethodTable_m_pInterfaceMap]
; check if this MT implements any interfaces
test ebx, ebx
jz ChkCastInterfaceDoBizarre
ChkCastInterfaceTop:
; eax -> current InterfaceInfo_t entry in interface map list
ifdef FEATURE_PREJIT
mov esi, [eax]
test esi, 1
; Move the deference out of line so that this jump is correctly predicted for the case
; when there is no indirection
jnz ChkCastInterfaceIndir
cmp ARGUMENT_REG1, esi
else
cmp ARGUMENT_REG1, [eax]
endif
je ChkCastInterfaceFound
ChkCastInterfaceNext:
add eax, SIZEOF_InterfaceInfo_t
dec ebx
jnz ChkCastInterfaceTop
; fall through to DoBizarre
ChkCastInterfaceDoBizarre:
pop esi
pop ebx
jmp @JITutil_ChkCastInterface@8
ifdef FEATURE_PREJIT
ChkCastInterfaceIndir:
cmp ARGUMENT_REG1,[esi-1]
jne ChkCastInterfaceNext
endif
ChkCastInterfaceFound:
pop esi
pop ebx
ChkCastInterfaceIsNullInst:
mov eax, ARGUMENT_REG2 ; either null, or the successful instance
ret
@JIT_ChkCastInterface@8 endp
; Note that the debugger skips this entirely when doing SetIP,
; since COMPlusCheckForAbort should always return 0. Excep.cpp:LeaveCatch
; asserts that to be true. If this ends up doing more work, then the
; debugger may need additional support.
; void __stdcall JIT_EndCatch();
JIT_EndCatch PROC stdcall public
; make temp storage for return address, and push the address of that
; as the last arg to COMPlusEndCatch
mov ecx, [esp]
push ecx;
push esp;
; push the rest of COMPlusEndCatch's args, right-to-left
push esi
push edi
push ebx
push ebp
call _COMPlusEndCatch@20 ; returns old esp value in eax, stores jump address
; now eax = new esp, [esp] = new eip
pop edx ; edx = new eip
mov esp, eax ; esp = new esp
jmp edx ; eip = new eip
JIT_EndCatch ENDP
end
|
; A281593: a(n) = b(n) - Sum_{j=0..n-1} b(n) with b(n) = binomial(2*n, n).
; 1,1,3,11,41,153,573,2157,8163,31043,118559,454479,1747771,6740059,26055459,100939779,391785129,1523230569,5931153429,23126146629,90282147849,352846964649,1380430179489,5405662979649,21186405207549,83101804279101,326199124351701,1281301484103605,5036113233567821,19805998531587981,77936047097367325,306835237222905565,1208602671654973923,4762782823786058595,18776967430994103855,74057162297175795807,292197146940686884147,1153302630722639535571,4553662150744648470507,17985435722557157776907,71058614717495270207327,280828778099614638912927,1110170102613922285902567,4389902215213895578478727,17363301426851235821298927,68693711951034944813046447,271834318817987271405881247,1075944560279039223290142687,4259609293454997630614514747,16867087524703256716501737147,66803207552305736245853377203,264629373327921801608230822803,1048477511720382072901774070715,4154870874080735171716585491963,16467605248393673202275293155243,65279254795412648118617120173035,258814862622382723927789906529955,1026290038541008555653351654532899,4070198664213341672737306838576595,16144460057751528940623111820777875,64045969482805613256839038138097091,254108085234340018379251771622764611
lpb $0
mov $2,$0
sub $0,2
add $2,$0
bin $2,$0
add $0,1
add $1,$2
lpe
mul $1,2
add $1,1
mov $0,$1
|
/*** For more information please refer to files in the COPYRIGHT directory ***/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <assert.h>
#include "irodsFs.hpp"
#include "iFuseLib.hpp"
#include "iFuseOper.hpp"
#include "irods_hashtable.h"
#include "irods_list.h"
#include "iFuseLib.Lock.hpp"
#undef USE_BOOST
#ifdef USE_BOOST
/*boost::mutex DescLock;*/
/* boost::mutex ConnLock;*/
boost::mutex* PathCacheLock = new boost::mutex();
/* boost::mutex FileCacheLock; */
boost::thread* ConnManagerThr;
boost::mutex* ConnManagerLock = new boost::mutex();
boost::mutex* WaitForConnLock = new boost::mutex();
boost::condition_variable ConnManagerCond;
#else
/*pthread_mutex_t DescLock;*/
/*pthread_mutex_t ConnLock;*/
//pthread_mutex_t PathCacheLock;
/* pthread_mutex_t FileCacheLock; */
pthread_t ConnManagerThr;
pthread_mutex_t ConnManagerLock;
pthread_mutex_t WaitForConnLock;
pthread_cond_t ConnManagerCond;
#endif
#ifdef USE_BOOST
/*#define LOCK(Lock) ((Lock).lock())
#define UNLOCK(Lock) ((Lock).unlock())
#define INIT_STRUCT_LOCK(s) ((s).mutex = new boost::mutex) // JMC :: necessary since no ctor/dtor on struct
#define LOCK_STRUCT(s) LOCK(*((s).mutex))
#define UNLOCK_STRUCT(s) UNLOCK(*((s).mutex))
#define FREE_STRUCT_LOCK(s) \
delete (s).mutex; \
(s).mutex = 0;*/
void releaseFuseConnLock( iFuseConn_t *tmpIFuseConn ) {
/* don't unlock. it will cause delete to fail */
FREE_STRUCT_LOCK( *tmpIFuseConn );
}
void initConnReqWaitMutex( connReqWait_t *myConnReqWait ) {
myConnReqWait->mutex = new boost::mutex;
}
void deleteConnReqWaitMutex( connReqWait_t *myConnReqWait ) {
delete myConnReqWait->mutex;
}
void timeoutWait( boost::mutex** ConnManagerLock, boost::condition_variable *ConnManagerCond, int sleepTime ) {
boost::system_time const tt = boost::get_system_time() + boost::posix_time::seconds( sleepTime );
boost::unique_lock< boost::mutex > boost_lock( **ConnManagerLock );
ConnManagerCond->timed_wait( boost_lock, tt );
}
void untimedWait( boost::mutex** ConnManagerLock, boost::condition_variable *ConnManagerCond ) {
boost::unique_lock< boost::mutex > boost_lock( **ConnManagerLock );
ConnManagerCond->wait( boost_lock );
}
void notifyWait( boost::mutex **ConnManagerLock, boost::condition_variable *ConnManagerCond ) {
ConnManagerCond->notify_all( );
}
#else
/*#define UNLOCK(Lock) (pthread_mutex_unlock (&(Lock)))
#define LOCK(Lock) (pthread_mutex_lock (&(Lock)))
#define INIT_STRUCT_LOCK(s) (pthread_mutex_init (&((s).lock), NULL))
#define LOCK_STRUCT(s) LOCK((s).lock)
#define UNLOCK_STRUCT(s) UNLOCK((s).lock)
#define FREE_STRUCT_LOCK(s) \
pthread_mutex_destroy (&((s).lock))*/
void releaseFuseConnLock( iFuseConn_t *tmpIFuseConn ) {
UNLOCK_STRUCT( *tmpIFuseConn );
FREE_STRUCT_LOCK( *tmpIFuseConn );
}
void initConnReqWaitMutex( connReqWait_t *myConnReqWait ) {
pthread_mutex_init( &myConnReqWait->mutex, NULL );
pthread_cond_init( &myConnReqWait->cond, NULL );
}
void deleteConnReqWaitMutex( connReqWait_t *myConnReqWait ) {
pthread_mutex_destroy( &myConnReqWait->mutex );
}
void timeoutWait( pthread_mutex_t *ConnManagerLock, pthread_cond_t *ConnManagerCond, int sleepTime ) {
struct timespec timeout;
bzero( &timeout, sizeof( timeout ) );
timeout.tv_sec = time( 0 ) + sleepTime;
pthread_mutex_lock( ConnManagerLock );
pthread_cond_timedwait( ConnManagerCond, ConnManagerLock, &timeout );
pthread_mutex_unlock( ConnManagerLock );
}
void untimedWait( pthread_mutex_t *ConnManagerLock, pthread_cond_t *ConnManagerCond ) {
pthread_mutex_lock( ConnManagerLock );
pthread_cond_wait( ConnManagerCond, ConnManagerLock );
pthread_mutex_unlock( ConnManagerLock );
}
void notifyWait( pthread_mutex_t *mutex, pthread_cond_t *cond ) {
pthread_mutex_lock( mutex );
pthread_cond_signal( cond );
pthread_mutex_unlock( mutex );
}
#endif
|
; A051064: 3^a(n) exactly divides 3n. Or, 3-adic valuation of 3n.
; 1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,4,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,4,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,5,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,4,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,4,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,5,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,4,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,4,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,3,1,1,2,1,1,2,1,1,6,1,1,2,1,1,2,1
add $0,1
mov $2,$0
lpb $2,1
add $1,362880
mov $3,$2
bin $3,3
gcd $2,$3
lpe
div $1,362880
add $1,1
|
; A101084: Numbers k such that 97*k + 101 is a prime.
; Submitted by Christian Krause
; 0,6,8,14,18,30,36,50,86,90,96,110,114,116,126,128,134,138,140,156,158,174,186,194,200,204,218,236,258,260,266,278,294,296,300,314,326,336,338,344,348,354,366,368,378,398,420,428,468,470,476,498,504,516,524,530,534,560,578,590,594,608,614,630,638,674,678,684,686,698,704,708,720,728,740,744,756,764,768,786,788,806,830,846,854,896,908,926,950,954,968,984,998,1014,1020,1026,1028,1038,1040,1056
mov $1,2
mov $2,$0
add $2,2
pow $2,2
lpb $2
add $1,48
sub $2,2
mov $3,$1
mul $3,2
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,49
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
mul $0,2
sub $0,198
div $0,97
|
USE32
global __context_switch
extern __context_switch_delegate
section .text
__context_switch:
; retrieve stack location
;pop ebx
; delegate reference
;pop ecx
; create stack frame
push ebp
mov ebp, esp
; save special purpose stuff
push esi
push edi
; save current ESP for later
mov eax, esp
; change to new stack
mov esp, ecx
and esp, 0xfffffff0
; room for arguments
sub esp, 16
; store old ESP on new stack
mov DWORD [esp ], eax
; delegate
mov DWORD [esp+4], edx
; call function that can call delegates
call __context_switch_delegate
; restore old stack
mov esp, [esp]
; restore special stuff
pop edi
pop esi
; return to origin
pop ebp
ret
|
#include <chrono>
#include <memory>
#include <string>
#include "common/filesystem/filesystem_impl.h"
#include "common/filter/auth/client_ssl.h"
#include "common/http/message_impl.h"
#include "common/network/address_impl.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/ssl/mocks.h"
#include "test/mocks/thread_local/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::InSequence;
using testing::Invoke;
using testing::Return;
using testing::ReturnNew;
using testing::ReturnRef;
using testing::WithArg;
namespace Filter {
namespace Auth {
namespace ClientSsl {
TEST(ClientSslAuthAllowedPrincipalsTest, EmptyString) {
AllowedPrincipals principals;
principals.add("");
EXPECT_EQ(0UL, principals.size());
}
class ClientSslAuthFilterTest : public testing::Test {
public:
ClientSslAuthFilterTest()
: request_(&cm_.async_client_), interval_timer_(new Event::MockTimer(&dispatcher_)) {}
~ClientSslAuthFilterTest() { tls_.shutdownThread(); }
void setup() {
std::string json = R"EOF(
{
"auth_api_cluster": "vpn",
"stat_prefix": "vpn",
"ip_white_list": [ "1.2.3.4/32" ]
}
)EOF";
Json::ObjectPtr loader = Json::Factory::LoadFromString(json);
EXPECT_CALL(cm_, get("vpn"));
setupRequest();
config_ = Config::create(*loader, tls_, cm_, dispatcher_, stats_store_, random_);
createAuthFilter();
}
void createAuthFilter() {
filter_callbacks_.connection_.callbacks_.clear();
instance_.reset(new Instance(config_));
instance_->initializeReadFilterCallbacks(filter_callbacks_);
}
void setupRequest() {
EXPECT_CALL(cm_, httpAsyncClientForCluster("vpn")).WillOnce(ReturnRef(cm_.async_client_));
EXPECT_CALL(cm_.async_client_, send_(_, _, _))
.WillOnce(
Invoke([this](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks,
Optional<std::chrono::milliseconds>) -> Http::AsyncClient::Request* {
callbacks_ = &callbacks;
return &request_;
}));
}
NiceMock<ThreadLocal::MockInstance> tls_;
Upstream::MockClusterManager cm_;
Event::MockDispatcher dispatcher_;
Http::MockAsyncClientRequest request_;
ConfigSharedPtr config_;
NiceMock<Network::MockReadFilterCallbacks> filter_callbacks_;
std::unique_ptr<Instance> instance_;
Event::MockTimer* interval_timer_;
Http::AsyncClient::Callbacks* callbacks_;
Ssl::MockConnection ssl_;
Stats::IsolatedStoreImpl stats_store_;
NiceMock<Runtime::MockRandomGenerator> random_;
};
TEST_F(ClientSslAuthFilterTest, NoCluster) {
std::string json = R"EOF(
{
"auth_api_cluster": "bad_cluster",
"stat_prefix": "bad_cluster"
}
)EOF";
Json::ObjectPtr loader = Json::Factory::LoadFromString(json);
EXPECT_CALL(cm_, get("bad_cluster")).WillOnce(Return(nullptr));
EXPECT_THROW(Config::create(*loader, tls_, cm_, dispatcher_, stats_store_, random_),
EnvoyException);
}
TEST_F(ClientSslAuthFilterTest, BadClientSslAuthConfig) {
std::string json_string = R"EOF(
{
"stat_prefix": "my_stat_prefix",
"auth_api_cluster" : "fake_cluster",
"ip_white_list": ["192.168.3.0/24"],
"test" : "a"
}
)EOF";
Json::ObjectPtr json_config = Json::Factory::LoadFromString(json_string);
EXPECT_THROW(Config::create(*json_config, tls_, cm_, dispatcher_, stats_store_, random_),
Json::Exception);
}
TEST_F(ClientSslAuthFilterTest, NoSsl) {
setup();
Buffer::OwnedImpl dummy("hello");
// Check no SSL case, mulitple iterations.
EXPECT_CALL(filter_callbacks_.connection_, ssl()).WillOnce(Return(nullptr));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onNewConnection());
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy));
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_no_ssl").value());
EXPECT_CALL(request_, cancel());
}
TEST_F(ClientSslAuthFilterTest, Ssl) {
InSequence s;
setup();
Buffer::OwnedImpl dummy("hello");
// Create a new filter for an SSL connection, with no backing auth data yet.
createAuthFilter();
ON_CALL(filter_callbacks_.connection_, ssl()).WillByDefault(Return(&ssl_));
Network::Address::Ipv4Instance remote_address("192.168.1.1");
EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(remote_address));
EXPECT_CALL(ssl_, sha256PeerCertificateDigest()).WillOnce(Return("digest"));
EXPECT_CALL(filter_callbacks_.connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::Connected);
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::RemoteClose);
// Respond.
EXPECT_CALL(*interval_timer_, enableTimer(_));
Http::MessagePtr message(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}));
message->body().reset(new Buffer::OwnedImpl(Filesystem::fileReadToEnd(
TestEnvironment::runfilesPath("test/common/filter/auth/test_data/vpn_response_1.json"))));
callbacks_->onSuccess(std::move(message));
EXPECT_EQ(1U, stats_store_.gauge("auth.clientssl.vpn.total_principals").value());
// Create a new filter for an SSL connection with an authorized cert.
createAuthFilter();
EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(remote_address));
EXPECT_CALL(ssl_, sha256PeerCertificateDigest())
.WillOnce(Return("1b7d42ef0025ad89c1c911d6c10d7e86a4cb7c5863b2980abcbad1895f8b5314"));
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
EXPECT_CALL(filter_callbacks_, continueReading());
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::Connected);
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy));
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::RemoteClose);
// White list case.
createAuthFilter();
Network::Address::Ipv4Instance remote_address2("1.2.3.4");
EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(remote_address2));
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
EXPECT_CALL(filter_callbacks_, continueReading());
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::Connected);
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy));
filter_callbacks_.connection_.raiseEvents(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.update_success").value());
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_ip_white_list").value());
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_digest_match").value());
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_digest_no_match").value());
// Interval timer fires.
setupRequest();
interval_timer_->callback_();
// Error response.
EXPECT_CALL(*interval_timer_, enableTimer(_));
message.reset(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "503"}}}));
callbacks_->onSuccess(std::move(message));
// Interval timer fires.
setupRequest();
interval_timer_->callback_();
// Parsing error
EXPECT_CALL(*interval_timer_, enableTimer(_));
message.reset(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}));
message->body().reset(new Buffer::OwnedImpl("bad_json"));
callbacks_->onSuccess(std::move(message));
// Interval timer fires.
setupRequest();
interval_timer_->callback_();
// No response failure.
EXPECT_CALL(*interval_timer_, enableTimer(_));
callbacks_->onFailure(Http::AsyncClient::FailureReason::Reset);
// Interval timer fires, cannot obtain async client.
EXPECT_CALL(cm_, httpAsyncClientForCluster("vpn")).WillOnce(ReturnRef(cm_.async_client_));
EXPECT_CALL(cm_.async_client_, send_(_, _, _))
.WillOnce(
Invoke([&](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks,
const Optional<std::chrono::milliseconds>&) -> Http::AsyncClient::Request* {
callbacks.onSuccess(Http::MessagePtr{new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "503"}}})});
return nullptr;
}));
EXPECT_CALL(*interval_timer_, enableTimer(_));
interval_timer_->callback_();
EXPECT_EQ(4U, stats_store_.counter("auth.clientssl.vpn.update_failure").value());
}
} // ClientSsl
} // Auth
} // Filter
|
; A114003: Rows sums of triangle A114002.
; 1,3,3,5,3,7,3,7,5,7,3,11,3,7,7,9,3,11,3,11,7,7,3,15,5,7,7,11,3,15,3,11,7,7,7,17,3,7,7,15,3,15,3,11,11,7,3,19,5,11,7,11,3,15,7,15,7,7,3,23,3,7,11,13,7,15,3,11,7,15,3,23,3,7,11,11,7,15,3,19,9,7,3,23,7,7,7,15,3,23,7,11,7,7,7,23,3,11,11,17,3,15,3,15,15,7,3,23,3,15,7,19,3,15,7,11,11,7,7,31,5,7,7,11,7,23,3,15,7,15,3,23,7,7,15,15,3,15,3,23,7,7,7,29,7,7,11,11,3,23,3,15,11,15,7,23,3,7,7,23,7,19,3,11,15,7,3,31,5,15,11,11,3,15,11,19,7,7,3,35,3,15,7,15,7,15,7,11,15,15,3,27,3,7,15,17,3,23,3,23,7,7,7,23,7,7,11,19,7,31,3,11,7,7,7,31,7,7,7,23,7,15,3,23,17,7,3,23,3,15,15,15,3,23,7,11,7,15,3,39,3,11,11,11,11,15,7,15,7,15
mov $5,2
mov $7,$0
lpb $5,1
sub $5,1
add $0,$5
sub $0,1
mov $2,$0
mov $4,$0
mov $6,2
lpb $2,1
add $4,2
lpb $4,1
trn $4,$2
add $6,1
lpe
sub $2,1
add $4,$0
lpe
mov $3,$5
lpb $3,1
mov $1,$6
sub $3,1
lpe
lpe
lpb $7,1
sub $1,$6
mov $7,0
lpe
sub $1,2
mul $1,2
add $1,1
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# 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.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 5, 0x90
.globl EncryptCBC_RIJ128_AES_NI
.type EncryptCBC_RIJ128_AES_NI, @function
EncryptCBC_RIJ128_AES_NI:
push %ebp
mov %esp, %ebp
push %esi
push %edi
movl (28)(%ebp), %edx
movl (8)(%ebp), %esi
movl (20)(%ebp), %ecx
movl (16)(%ebp), %eax
movl (12)(%ebp), %edi
movdqu (%edx), %xmm0
movl (24)(%ebp), %edx
.p2align 5, 0x90
.Lblks_loopgas_1:
movdqu (%esi), %xmm1
movdqa (%ecx), %xmm4
pxor %xmm1, %xmm0
pxor %xmm4, %xmm0
movdqa (16)(%ecx), %xmm4
add $(16), %ecx
sub $(1), %eax
.p2align 5, 0x90
.Lcipher_loopgas_1:
aesenc %xmm4, %xmm0
movdqa (16)(%ecx), %xmm4
add $(16), %ecx
sub $(1), %eax
jnz .Lcipher_loopgas_1
aesenclast %xmm4, %xmm0
movdqu %xmm0, (%edi)
movl (20)(%ebp), %ecx
movl (16)(%ebp), %eax
add $(16), %esi
add $(16), %edi
sub $(16), %edx
jnz .Lblks_loopgas_1
pop %edi
pop %esi
pop %ebp
ret
.Lfe1:
.size EncryptCBC_RIJ128_AES_NI, .Lfe1-(EncryptCBC_RIJ128_AES_NI)
|
@0
D=M
@23
D;JLE
@16
M=D
@16384
D=A
@17
M=D
@17
A=M
M=-1
@17
D=M
@32
D=D+A
@17
M=D
@16
MD=M-1
@10
D;JGT
@23
0;JMP |
li s0, 0x400b0000
li x10, 20
sw x10, 0x0(s0)
sw x10, 16(s0)
li x11, 2
sw x11, 0x4(s0)
sw x11, 20(s0)
li x12, 3
sw x12, 0x8(s0)
sw x12, 24(s0)
li x13, 1
sw x13, 0xc(s0)
sw x13, 28(s0)
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 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 <miner.h>
#include <amount.h>
#include <chain.h>
#include <chainparams.h>
#include <coins.h>
#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <policy/feerate.h>
#include <policy/policy.h>
#include <pow.h>
#include <pos.h>
#include <primitives/transaction.h>
#include <shutdown.h>
#include <timedata.h>
#include <util/convert.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <net.h>
#include <key_io.h>
#ifdef ENABLE_WALLET
#include <wallet/wallet.h>
#endif
#include <algorithm>
#include <utility>
#include <validation.h>
#include <util/threadnames.h>
#include <thread>
#include <boost/thread/thread.hpp>
unsigned int nMaxStakeLookahead = MAX_STAKE_LOOKAHEAD;
unsigned int nBytecodeTimeBuffer = BYTECODE_TIME_BUFFER;
unsigned int nStakeTimeBuffer = STAKE_TIME_BUFFER;
unsigned int nMinerSleep = STAKER_POLLING_PERIOD;
unsigned int nMinerWaitWalidBlock = STAKER_WAIT_FOR_WALID_BLOCK;
unsigned int nMinerWaitBestBlockHeader = STAKER_WAIT_FOR_BEST_BLOCK_HEADER;
void updateMinerParams(int nHeight, const Consensus::Params& consensusParams, bool minDifficulty)
{
static unsigned int timeDownscale = 1;
static unsigned int timeDefault = 1;
// Sleep for 20 seconds when mining with minimum difficulty to avoid creating blocks every 4 seconds
if(minDifficulty && nMinerSleep != STAKER_POLLING_PERIOD_MIN_DIFFICULTY)
{
nMinerSleep = STAKER_POLLING_PERIOD_MIN_DIFFICULTY;
}
}
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, consensusParams, pblock->IsProofOfStake());
return nNewTime - nOldTime;
}
BlockAssembler::Options::Options() {
blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
}
BlockAssembler::BlockAssembler(const CTxMemPool& mempool, const CChainParams& params, const Options& options)
: chainparams(params),
m_mempool(mempool)
{
blockMinFeeRate = options.blockMinFeeRate;
// Limit weight to between 4K and dgpMaxBlockWeight-4K for sanity:
nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(dgpMaxBlockWeight - 4000, options.nBlockMaxWeight));
}
static BlockAssembler::Options DefaultOptions()
{
// Block resource limits
// If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
BlockAssembler::Options options;
options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
CAmount n = 0;
if (gArgs.IsArgSet("-blockmintxfee") && ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n)) {
options.blockMinFeeRate = CFeeRate(n);
} else {
options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
}
return options;
}
BlockAssembler::BlockAssembler(const CTxMemPool& mempool, const CChainParams& params)
: BlockAssembler(mempool, params, DefaultOptions()) {}
#ifdef ENABLE_WALLET
BlockAssembler::BlockAssembler(const CTxMemPool& mempool, const CChainParams& params, CWallet *_pwallet)
: BlockAssembler(mempool, params)
{
pwallet = _pwallet;
}
#endif
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockWeight = 4000;
nBlockSigOpsCost = 400;
fIncludeWitness = false;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
}
void BlockAssembler::RebuildRefundTransaction(){
int refundtx=0; //0 for coinbase in PoW
if(pblock->IsProofOfStake()){
refundtx=1; //1 for coinstake in PoS
}
CMutableTransaction contrTx(originalRewardTx);
contrTx.vout[refundtx].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
contrTx.vout[refundtx].nValue -= bceResult.refundSender;
int i=contrTx.vout.size();
contrTx.vout.resize(contrTx.vout.size()+bceResult.refundOutputs.size());
for(CTxOut& vout : bceResult.refundOutputs){
contrTx.vout[i]=vout;
i++;
}
pblock->vtx[refundtx] = MakeTransactionRef(std::move(contrTx));
}
Optional<int64_t> BlockAssembler::m_last_block_num_txs{nullopt};
Optional<int64_t> BlockAssembler::m_last_block_weight{nullopt};
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx, bool fProofOfStake, int64_t* pTotalFees, int32_t txProofTime, int32_t nTimeLimit)
{
int64_t nTimeStart = GetTimeMicros();
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
this->nTimeLimit = nTimeLimit;
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
// Add dummy coinstake tx as second transaction
if(fProofOfStake)
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
#ifdef ENABLE_WALLET
if(pwallet && pwallet->IsStakeClosing())
return nullptr;
#endif
LOCK2(cs_main, m_mempool.cs);
CBlockIndex* pindexPrev = ::ChainActive().Tip();
assert(pindexPrev != nullptr);
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
if(txProofTime == 0) {
txProofTime = GetAdjustedTime();
}
if(fProofOfStake)
txProofTime &= ~chainparams.GetConsensus().StakeTimestampMask(nHeight);
pblock->nTime = txProofTime;
if (!fProofOfStake)
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, chainparams.GetConsensus(), fProofOfStake);
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization).
// Note that the mempool would accept transactions with witness data before
// IsWitnessEnabled, but we would only ever mine blocks after IsWitnessEnabled
// unless there is a massive block reorganization with the witness softfork
// not activated.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus());
int64_t nTime1 = GetTimeMicros();
m_last_block_num_txs = nBlockTx;
m_last_block_weight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
if (fProofOfStake)
{
// Make the coinbase tx empty in case of proof of stake
coinbaseTx.vout[0].SetEmpty();
}
else
{
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
}
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
originalRewardTx = coinbaseTx;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
// Create coinstake transaction.
if(fProofOfStake)
{
CMutableTransaction coinstakeTx;
coinstakeTx.vout.resize(2);
coinstakeTx.vout[0].SetEmpty();
coinstakeTx.vout[1].scriptPubKey = scriptPubKeyIn;
originalRewardTx = coinstakeTx;
pblock->vtx[1] = MakeTransactionRef(std::move(coinstakeTx));
//this just makes CBlock::IsProofOfStake to return true
//real prevoutstake info is filled in later in SignBlock
pblock->prevoutStake.n=0;
}
//////////////////////////////////////////////////////// eqpay
EqPayDGP eqpayDGP(globalState.get(), fGettingValuesDGP);
globalSealEngine->setEqPaySchedule(eqpayDGP.getGasSchedule(nHeight));
uint32_t blockSizeDGP = eqpayDGP.getBlockSize(nHeight);
minGasPrice = eqpayDGP.getMinGasPrice(nHeight);
if(gArgs.IsArgSet("-staker-min-tx-gas-price")) {
CAmount stakerMinGasPrice;
if(ParseMoney(gArgs.GetArg("-staker-min-tx-gas-price", ""), stakerMinGasPrice)) {
minGasPrice = std::max(minGasPrice, (uint64_t)stakerMinGasPrice);
}
}
hardBlockGasLimit = eqpayDGP.getBlockGasLimit(nHeight);
softBlockGasLimit = gArgs.GetArg("-staker-soft-block-gas-limit", hardBlockGasLimit);
softBlockGasLimit = std::min(softBlockGasLimit, hardBlockGasLimit);
txGasLimit = gArgs.GetArg("-staker-max-tx-gas-limit", softBlockGasLimit);
nBlockMaxWeight = blockSizeDGP ? blockSizeDGP * WITNESS_SCALE_FACTOR : nBlockMaxWeight;
dev::h256 oldHashStateRoot(globalState->rootHash());
dev::h256 oldHashUTXORoot(globalState->rootHashUTXO());
////////////////////////////////////////////////// deploy offline staking contract
if(nHeight == chainparams.GetConsensus().nOfflineStakeHeight){
globalState->deployDelegationsContract();
}
/////////////////////////////////////////////////
int nPackagesSelected = 0;
int nDescendantsUpdated = 0;
addPackageTxs(nPackagesSelected, nDescendantsUpdated, minGasPrice);
pblock->hashStateRoot = uint256(h256Touint(dev::h256(globalState->rootHash())));
pblock->hashUTXORoot = uint256(h256Touint(dev::h256(globalState->rootHashUTXO())));
globalState->setRoot(oldHashStateRoot);
globalState->setRootUTXO(oldHashUTXORoot);
//this should already be populated by AddBlock in case of contracts, but if no contracts
//then it won't get populated
RebuildRefundTransaction();
////////////////////////////////////////////////////////
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus(), fProofOfStake);
pblocktemplate->vTxFees[0] = -nFees;
LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
// The total fee is the Fees minus the Refund
if (pTotalFees)
*pTotalFees = nFees - bceResult.refundSender;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
BlockValidationState state;
if (!fProofOfStake && !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
}
int64_t nTime2 = GetTimeMicros();
LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
return std::move(pblocktemplate);
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateEmptyBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx, bool fProofOfStake, int64_t* pTotalFees, int32_t nTime)
{
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
// Add dummy coinstake tx as second transaction
if(fProofOfStake)
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
#ifdef ENABLE_WALLET
if(pwallet && pwallet->IsStakeClosing())
return nullptr;
#endif
LOCK2(cs_main, m_mempool.cs);
CBlockIndex* pindexPrev = ::ChainActive().Tip();
assert(pindexPrev != nullptr);
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
uint32_t txProofTime = nTime == 0 ? GetAdjustedTime() : nTime;
if(fProofOfStake)
txProofTime &= ~chainparams.GetConsensus().StakeTimestampMask(nHeight);
pblock->nTime = txProofTime;
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
m_last_block_num_txs = nBlockTx;
m_last_block_weight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
if (fProofOfStake)
{
// Make the coinbase tx empty in case of proof of stake
coinbaseTx.vout[0].SetEmpty();
}
else
{
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
}
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
originalRewardTx = coinbaseTx;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
// Create coinstake transaction.
if(fProofOfStake)
{
CMutableTransaction coinstakeTx;
coinstakeTx.vout.resize(2);
coinstakeTx.vout[0].SetEmpty();
coinstakeTx.vout[1].scriptPubKey = scriptPubKeyIn;
originalRewardTx = coinstakeTx;
pblock->vtx[1] = MakeTransactionRef(std::move(coinstakeTx));
//this just makes CBlock::IsProofOfStake to return true
//real prevoutstake info is filled in later in SignBlock
pblock->prevoutStake.n=0;
}
//////////////////////////////////////////////////////// eqpay
//state shouldn't change here for an empty block, but if it's not valid it'll fail in CheckBlock later
pblock->hashStateRoot = uint256(h256Touint(dev::h256(globalState->rootHash())));
pblock->hashUTXORoot = uint256(h256Touint(dev::h256(globalState->rootHashUTXO())));
RebuildRefundTransaction();
////////////////////////////////////////////////////////
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus(), fProofOfStake);
pblocktemplate->vTxFees[0] = -nFees;
// The total fee is the Fees minus the Refund
if (pTotalFees)
*pTotalFees = nFees - bceResult.refundSender;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
if (!fProofOfStake)
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, chainparams.GetConsensus(), fProofOfStake);
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
BlockValidationState state;
if (!fProofOfStake && !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
}
return std::move(pblocktemplate);
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
return false;
if (nBlockSigOpsCost + packageSigOpsCost >= (uint64_t)dgpMaxBlockSigOps)
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - premature witness (in case segwit transactions are added to mempool before
// segwit activation)
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
for (CTxMemPool::txiter it : package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && it->GetTx().HasWitness())
return false;
}
return true;
}
bool BlockAssembler::AttemptToAddContractToBlock(CTxMemPool::txiter iter, uint64_t minGasPrice) {
if (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit - nBytecodeTimeBuffer) {
return false;
}
if (gArgs.GetBoolArg("-disablecontractstaking", false))
{
// Contract staking is disabled for the staker
return false;
}
dev::h256 oldHashStateRoot(globalState->rootHash());
dev::h256 oldHashUTXORoot(globalState->rootHashUTXO());
// operate on local vars first, then later apply to `this`
uint64_t nBlockWeight = this->nBlockWeight;
uint64_t nBlockSigOpsCost = this->nBlockSigOpsCost;
unsigned int contractflags = GetContractScriptFlags(nHeight, chainparams.GetConsensus());
EqPayTxConverter convert(iter->GetTx(), NULL, &pblock->vtx, contractflags);
ExtractEqPayTX resultConverter;
if(!convert.extractionEqPayTransactions(resultConverter)){
//this check already happens when accepting txs into mempool
//therefore, this can only be triggered by using raw transactions on the staker itself
LogPrintf("AttemptToAddContractToBlock(): Fail to extract contacts from tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
std::vector<EqPayTransaction> eqpayTransactions = resultConverter.first;
dev::u256 txGas = 0;
for(EqPayTransaction eqpayTransaction : eqpayTransactions){
txGas += eqpayTransaction.gas();
if(txGas > txGasLimit) {
// Limit the tx gas limit by the soft limit if such a limit has been specified.
LogPrintf("AttemptToAddContractToBlock(): The gas needed is bigger than -staker-max-tx-gas-limit for the contract tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
if(bceResult.usedGas + eqpayTransaction.gas() > softBlockGasLimit){
// If this transaction's gasLimit could cause block gas limit to be exceeded, then don't add it
// Log if the contract is the only contract tx
if(bceResult.usedGas == 0)
LogPrintf("AttemptToAddContractToBlock(): The gas needed is bigger than -staker-soft-block-gas-limit for the contract tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
if(eqpayTransaction.gasPrice() < minGasPrice){
//if this transaction's gasPrice is less than the current DGP minGasPrice don't add it
LogPrintf("AttemptToAddContractToBlock(): The gas price is less than -staker-min-tx-gas-price for the contract tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
}
// We need to pass the DGP's block gas limit (not the soft limit) since it is consensus critical.
ByteCodeExec exec(*pblock, eqpayTransactions, hardBlockGasLimit, ::ChainActive().Tip());
if(!exec.performByteCode()){
//error, don't add contract
globalState->setRoot(oldHashStateRoot);
globalState->setRootUTXO(oldHashUTXORoot);
LogPrintf("AttemptToAddContractToBlock(): Perform byte code fails for the contract tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
ByteCodeExecResult testExecResult;
if(!exec.processingResults(testExecResult)){
globalState->setRoot(oldHashStateRoot);
globalState->setRootUTXO(oldHashUTXORoot);
LogPrintf("AttemptToAddContractToBlock(): Processing results fails for the contract tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
if(bceResult.usedGas + testExecResult.usedGas > softBlockGasLimit){
// If this transaction could cause block gas limit to be exceeded, then don't add it
globalState->setRoot(oldHashStateRoot);
globalState->setRootUTXO(oldHashUTXORoot);
// Log if the contract is the only contract tx
if(bceResult.usedGas == 0)
LogPrintf("AttemptToAddContractToBlock(): The gas used is bigger than -staker-soft-block-gas-limit for the contract tx %s\n", iter->GetTx().GetHash().ToString());
return false;
}
//apply contractTx costs to local state
nBlockWeight += iter->GetTxWeight();
nBlockSigOpsCost += iter->GetSigOpCost();
//apply value-transfer txs to local state
for (CTransaction &t : testExecResult.valueTransfers) {
nBlockWeight += GetTransactionWeight(t);
nBlockSigOpsCost += GetLegacySigOpCount(t);
}
int proofTx = pblock->IsProofOfStake() ? 1 : 0;
//calculate sigops from new refund/proof tx
//first, subtract old proof tx
nBlockSigOpsCost -= GetLegacySigOpCount(*pblock->vtx[proofTx]);
// manually rebuild refundtx
CMutableTransaction contrTx(*pblock->vtx[proofTx]);
int i=contrTx.vout.size();
contrTx.vout.resize(contrTx.vout.size()+testExecResult.refundOutputs.size());
for(CTxOut& vout : testExecResult.refundOutputs){
contrTx.vout[i]=vout;
i++;
}
nBlockSigOpsCost += GetLegacySigOpCount(contrTx);
//all contract costs now applied to local state
//Check if block will be too big or too expensive with this contract execution
if (nBlockSigOpsCost * WITNESS_SCALE_FACTOR > (uint64_t)dgpMaxBlockSigOps ||
nBlockWeight > dgpMaxBlockWeight) {
//contract will not be added to block, so revert state to before we tried
globalState->setRoot(oldHashStateRoot);
globalState->setRootUTXO(oldHashUTXORoot);
return false;
}
//block is not too big, so apply the contract execution and it's results to the actual block
//apply local bytecode to global bytecode state
bceResult.usedGas += testExecResult.usedGas;
bceResult.refundSender += testExecResult.refundSender;
bceResult.refundOutputs.insert(bceResult.refundOutputs.end(), testExecResult.refundOutputs.begin(), testExecResult.refundOutputs.end());
bceResult.valueTransfers = std::move(testExecResult.valueTransfers);
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
this->nBlockWeight += iter->GetTxWeight();
++nBlockTx;
this->nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
for (CTransaction &t : bceResult.valueTransfers) {
pblock->vtx.emplace_back(MakeTransactionRef(std::move(t)));
this->nBlockWeight += GetTransactionWeight(t);
this->nBlockSigOpsCost += GetLegacySigOpCount(t);
++nBlockTx;
}
//calculate sigops from new refund/proof tx
this->nBlockSigOpsCost -= GetLegacySigOpCount(*pblock->vtx[proofTx]);
RebuildRefundTransaction();
this->nBlockSigOpsCost += GetLegacySigOpCount(*pblock->vtx[proofTx]);
bceResult.valueTransfers.clear();
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
nBlockWeight += iter->GetTxWeight();
++nBlockTx;
nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
LogPrintf("fee %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
int nDescendantsUpdated = 0;
for (CTxMemPool::txiter it : alreadyAdded) {
CTxMemPool::setEntries descendants;
m_mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
for (CTxMemPool::txiter desc : descendants) {
if (alreadyAdded.count(desc))
continue;
++nDescendantsUpdated;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
return nDescendantsUpdated;
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert(it != m_mempool.mapTx.end());
return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated, uint64_t minGasPrice)
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score_or_gas_price>::type::iterator mi = m_mempool.mapTx.get<ancestor_score_or_gas_price>().begin();
CTxMemPool::txiter iter;
// Limit the number of attempts to add transactions to the block when it is
// close to full; this is just a simple heuristic to finish quickly if the
// mempool has a lot of entries.
const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
int64_t nConsecutiveFailed = 0;
while (mi != m_mempool.mapTx.get<ancestor_score_or_gas_price>().end() || !mapModifiedTx.empty()) {
if(nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit){
//no more time to add transactions, just exit
return;
}
// First try to find a new transaction in mapTx to evaluate.
if (mi != m_mempool.mapTx.get<ancestor_score_or_gas_price>().end() &&
SkipMapTxEntry(m_mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score_or_gas_price>().begin();
if (mi == m_mempool.mapTx.get<ancestor_score_or_gas_price>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = m_mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score_or_gas_price>().end() &&
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOpsCost = modit->nSigOpCostWithAncestors;
}
if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOpsCost)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit);
failedTx.insert(iter);
}
++nConsecutiveFailed;
if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
nBlockMaxWeight - 4000) {
// Give up if we're close to full and haven't succeeded in a while
break;
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
m_mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// This transaction will make it in; reset the failed counter.
nConsecutiveFailed = 0;
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, sortedEntries);
bool wasAdded=true;
for (size_t i=0; i<sortedEntries.size(); ++i) {
if(!wasAdded || (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit))
{
//if out of time, or earlier ancestor failed, then skip the rest of the transactions
mapModifiedTx.erase(sortedEntries[i]);
wasAdded=false;
continue;
}
const CTransaction& tx = sortedEntries[i]->GetTx();
if(wasAdded) {
if (tx.HasCreateOrCall()) {
wasAdded = AttemptToAddContractToBlock(sortedEntries[i], minGasPrice);
if(!wasAdded){
if(fUsingModified) {
//this only needs to be done once to mark the whole package (everything in sortedEntries) as failed
mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit);
failedTx.insert(iter);
}
}
} else {
AddToBlock(sortedEntries[i]);
}
}
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
if(!wasAdded){
//skip UpdatePackages if a transaction failed to be added (match TestPackage logic)
continue;
}
++nPackagesSelected;
// Update transactions that depend on each of these
nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(*pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce));
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
#ifdef ENABLE_WALLET
//////////////////////////////////////////////////////////////////////////////
//
// Proof of Stake miner
//
//
// Looking for suitable coins for creating new block.
//
class DelegationFilterBase : public IDelegationFilter
{
public:
bool GetKey(const std::string& strAddress, uint160& keyId)
{
CTxDestination destination = DecodeDestination(strAddress);
if (!IsValidDestination(destination)) {
return false;
}
const PKHash *pkhash = boost::get<PKHash>(&destination);
if (!pkhash) {
return false;
}
keyId = uint160(*pkhash);
return true;
}
};
class DelegationsStaker : public DelegationFilterBase
{
public:
enum StakerType
{
STAKER_NORMAL = 0,
STAKER_ALLOWLIST = 1,
STAKER_EXCLUDELIST = 2,
};
DelegationsStaker(CWallet *_pwallet):
pwallet(_pwallet),
cacheHeight(0),
type(StakerType::STAKER_NORMAL),
spk_man(0)
{
spk_man = _pwallet->GetLegacyScriptPubKeyMan();
// Get allow list
for (const std::string& strAddress : gArgs.GetArgs("-stakingallowlist"))
{
uint160 keyId;
if(GetKey(strAddress, keyId))
{
if(std::find(allowList.begin(), allowList.end(), keyId) == allowList.end())
allowList.push_back(keyId);
}
else
{
LogPrint(BCLog::COINSTAKE, "Fail to add %s to stake allow list\n", strAddress);
}
}
// Get exclude list
for (const std::string& strAddress : gArgs.GetArgs("-stakingexcludelist"))
{
uint160 keyId;
if(GetKey(strAddress, keyId))
{
if(std::find(excludeList.begin(), excludeList.end(), keyId) == excludeList.end())
excludeList.push_back(keyId);
}
else
{
LogPrint(BCLog::COINSTAKE, "Fail to add %s to stake exclude list\n", strAddress);
}
}
// Set staker type
if(allowList.size() > 0)
{
type = StakerType::STAKER_ALLOWLIST;
}
else if(excludeList.size() > 0)
{
type = StakerType::STAKER_EXCLUDELIST;
}
}
bool Match(const DelegationEvent& event) const
{
bool mine = spk_man->HaveKey(CKeyID(event.item.staker));
if(!mine)
return false;
CSuperStakerInfo info;
if(pwallet->GetSuperStaker(info, event.item.staker) && info.fCustomConfig)
{
return CheckAddressList(info.nDelegateAddressType, info.delegateAddressList, info.delegateAddressList, event);
}
return CheckAddressList(type, allowList, excludeList, event);
}
bool CheckAddressList(const int& _type, const std::vector<uint160>& _allowList, const std::vector<uint160>& _excludeList, const DelegationEvent& event) const
{
switch (_type) {
case STAKER_NORMAL:
return true;
case STAKER_ALLOWLIST:
return std::count(_allowList.begin(), _allowList.end(), event.item.delegate);
case STAKER_EXCLUDELIST:
return std::count(_excludeList.begin(), _excludeList.end(), event.item.delegate) == 0;
default:
break;
}
return false;
}
void Update(int32_t nHeight)
{
if(pwallet->fUpdatedSuperStaker)
{
// Clear cache if updated
cacheHeight = 0;
cacheDelegationsStaker.clear();
pwallet->fUpdatedSuperStaker = false;
}
std::map<uint160, Delegation> delegations_staker;
int checkpointSpan = Params().GetConsensus().CheckpointSpan(nHeight);
if(nHeight <= checkpointSpan)
{
// Get delegations from events
std::vector<DelegationEvent> events;
eqpayDelegations.FilterDelegationEvents(events, *this);
delegations_staker = eqpayDelegations.DelegationsFromEvents(events);
}
else
{
// Update the cached delegations for the staker, older then the sync checkpoint (500 blocks)
int cpsHeight = nHeight - checkpointSpan;
if(cacheHeight < cpsHeight)
{
std::vector<DelegationEvent> events;
eqpayDelegations.FilterDelegationEvents(events, *this, cacheHeight, cpsHeight);
eqpayDelegations.UpdateDelegationsFromEvents(events, cacheDelegationsStaker);
cacheHeight = cpsHeight;
}
// Update the wallet delegations
std::vector<DelegationEvent> events;
eqpayDelegations.FilterDelegationEvents(events, *this, cacheHeight + 1);
delegations_staker = cacheDelegationsStaker;
eqpayDelegations.UpdateDelegationsFromEvents(events, delegations_staker);
}
pwallet->updateDelegationsStaker(delegations_staker);
}
private:
CWallet *pwallet;
EqPayDelegation eqpayDelegations;
int32_t cacheHeight;
std::map<uint160, Delegation> cacheDelegationsStaker;
std::vector<uint160> allowList;
std::vector<uint160> excludeList;
int type;
LegacyScriptPubKeyMan* spk_man;
};
class MyDelegations : public DelegationFilterBase
{
public:
MyDelegations(CWallet *_pwallet):
pwallet(_pwallet),
cacheHeight(0),
cacheAddressHeight(0),
spk_man(0)
{
spk_man = _pwallet->GetLegacyScriptPubKeyMan();
}
bool Match(const DelegationEvent& event) const
{
return spk_man->HaveKey(CKeyID(event.item.delegate));
}
void Update(interfaces::Chain::Lock& locked_chain, int32_t nHeight)
{
if(fLogEvents)
{
// When log events are enabled, search the log events to get complete list of my delegations
int checkpointSpan = Params().GetConsensus().CheckpointSpan(nHeight);
if(nHeight <= checkpointSpan)
{
// Get delegations from events
std::vector<DelegationEvent> events;
eqpayDelegations.FilterDelegationEvents(events, *this);
pwallet->m_my_delegations = eqpayDelegations.DelegationsFromEvents(events);
}
else
{
// Update the cached delegations for the staker, older then the sync checkpoint (500 blocks)
int cpsHeight = nHeight - checkpointSpan;
if(cacheHeight < cpsHeight)
{
std::vector<DelegationEvent> events;
eqpayDelegations.FilterDelegationEvents(events, *this, cacheHeight, cpsHeight);
eqpayDelegations.UpdateDelegationsFromEvents(events, cacheMyDelegations);
cacheHeight = cpsHeight;
}
// Update the wallet delegations
std::vector<DelegationEvent> events;
eqpayDelegations.FilterDelegationEvents(events, *this, cacheHeight + 1);
pwallet->m_my_delegations = cacheMyDelegations;
eqpayDelegations.UpdateDelegationsFromEvents(events, pwallet->m_my_delegations);
}
}
else
{
// Log events are not enabled, search the available addresses for list of my delegations
if(cacheHeight != nHeight)
{
cacheMyDelegations.clear();
// Address map
std::map<uint160, bool> mapAddress;
// Get all addreses with coins
SelectAddress(locked_chain, mapAddress, nHeight);
// Get all addreses for delegations in the GUI
for(auto item : pwallet->mapDelegation)
{
uint160 address = item.second.delegateAddress;
if(spk_man->HaveKey(CKeyID(address)))
{
if (mapAddress.find(address) == mapAddress.end())
{
mapAddress[address] = false;
}
}
}
// Search my delegations in the addresses
for(auto item: mapAddress)
{
Delegation delegation;
uint160 address = item.first;
if(eqpayDelegations.GetDelegation(address, delegation) && EqPayDelegation::VerifyDelegation(address, delegation))
{
cacheMyDelegations[address] = delegation;
}
}
// Update my delegations list
pwallet->m_my_delegations = cacheMyDelegations;
cacheHeight = nHeight;
}
}
}
void SelectAddress(interfaces::Chain::Lock& locked_chain, std::map<uint160, bool>& mapAddress, int32_t nHeight)
{
if(cacheAddressHeight < nHeight)
{
pwallet->SelectAddress(locked_chain, mapAddress);
pwallet->mapAddressUnspentCache = mapAddress;
if(pwallet->fUpdateAddressUnspentCache == false)
pwallet->fUpdateAddressUnspentCache = true;
cacheAddressHeight = nHeight + 100;
}
else
{
mapAddress = pwallet->mapAddressUnspentCache;
}
}
private:
CWallet *pwallet;
EqPayDelegation eqpayDelegations;
int32_t cacheHeight;
int32_t cacheAddressHeight;
std::map<uint160, Delegation> cacheMyDelegations;
LegacyScriptPubKeyMan* spk_man;
};
bool CheckStake(const std::shared_ptr<const CBlock> pblock, CWallet& wallet)
{
uint256 proofHash, hashTarget;
uint256 hashBlock = pblock->GetHash();
if(!pblock->IsProofOfStake())
return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex());
// verify hash target and signature of coinstake tx
{
auto locked_chain = wallet.chain().lock();
BlockValidationState state;
if (!CheckProofOfStake(::BlockIndex()[pblock->hashPrevBlock], state, *pblock->vtx[1], pblock->nBits, pblock->nTime, pblock->GetProofOfDelegation(), pblock->prevoutStake, proofHash, hashTarget, ::ChainstateActive().CoinsTip()))
return error("CheckStake() : proof-of-stake checking failed %s",state.GetRejectReason());
}
//// debug print
LogPrint(BCLog::COINSTAKE, "CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex(), proofHash.GetHex(), hashTarget.GetHex());
LogPrint(BCLog::COINSTAKE, "%s\n", pblock->ToString());
LogPrint(BCLog::COINSTAKE, "out %s\n", FormatMoney(pblock->vtx[1]->GetValueOut()));
// Found a solution
{
auto locked_chain = wallet.chain().lock();
if (pblock->hashPrevBlock != ::ChainActive().Tip()->GetBlockHash())
return error("CheckStake() : generated block is stale");
LOCK(wallet.cs_wallet);
for(const CTxIn& vin : pblock->vtx[1]->vin) {
if (wallet.IsSpent(vin.prevout.hash, vin.prevout.n)) {
return error("CheckStake() : generated block became invalid due to stake UTXO being spent");
}
}
}
// Process this block the same as if we had received it from another node
bool fNewBlock = false;
if (!ProcessNewBlock(Params(), pblock, true, &fNewBlock))
return error("CheckStake() : ProcessBlock, block not accepted");
return true;
}
bool SleepStaker(CWallet *pwallet, u_int64_t milliseconds)
{
u_int64_t seconds = milliseconds / 1000;
milliseconds %= 1000;
for(unsigned int i = 0; i < seconds; i++)
{
if(!pwallet->IsStakeClosing())
UninterruptibleSleep(std::chrono::seconds{1});
else
return false;
}
if(milliseconds)
{
if(!pwallet->IsStakeClosing())
UninterruptibleSleep(std::chrono::milliseconds{milliseconds});
else
return false;
}
return !pwallet->IsStakeClosing();
}
/**
* @brief The IStakeMiner class Miner interface
*/
class IStakeMiner
{
public:
/**
* @brief init Initialize the miner
* @param pwallet Wallet to use
* @param connman Nodes that connect
*/
virtual void Init(CWallet *pwallet, CConnman* connman) = 0;
/**
* @brief run Run the miner
*/
virtual void Run() = 0;
/**
* @brief ~IStakeMiner Destructor
*/
virtual ~IStakeMiner() {};
};
class SolveItem
{
public:
SolveItem(const COutPoint& _prevoutStake, const uint32_t& _blockTime, const bool& _delegate):
prevoutStake(_prevoutStake),
blockTime(_blockTime),
delegate(_delegate)
{}
COutPoint prevoutStake;
uint32_t blockTime = 0;
bool delegate = false;
};
class StakeMinerPriv
{
public:
CWallet *pwallet = 0;
CConnman* connman = 0;
bool fTryToSync = true;
bool regtestMode = false;
bool minDifficulty = false;
bool fSuperStake = false;
const Consensus::Params& consensusParams;
int nOfflineStakeHeight = 0;
bool fDelegationsContract = false;
bool fEmergencyStaking = false;
bool fAggressiveStaking = false;
bool fError = false;
int numThreads = 1;
boost::thread_group threads;
mutable RecursiveMutex cs_worker;
public:
DelegationsStaker delegationsStaker;
MyDelegations myDelegations;
public:
int32_t nHeight = 0;
uint32_t stakeTimestampMask = 1;
int64_t nTotalFees = 0;
bool haveCoinsForStake = false;
bool forceUpdate = false;
CBlockIndex* pindexPrev = 0;
CAmount nTargetValue = 0;
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
std::vector<COutPoint> setSelectedCoins;
std::vector<COutPoint> setDelegateCoins;
std::vector<COutPoint> prevouts;
std::map<uint32_t, bool> mapSolveBlockTime;
std::multimap<uint256, SolveItem> mapSolvedBlock;
std::map<uint32_t, std::vector<COutPoint>> mapSolveSelectedCoins;
std::map<uint32_t, std::vector<COutPoint>> mapSolveDelegateCoins;
uint32_t beginningTime = 0;
uint32_t endingTime = 0;
uint32_t waitBestHeaderAttempts = 0;
std::shared_ptr<CBlock> pblock;
std::unique_ptr<CBlockTemplate> pblocktemplate;
std::shared_ptr<CBlock> pblockfilled;
std::unique_ptr<CBlockTemplate> pblocktemplatefilled;
public:
StakeMinerPriv(CWallet *_pwallet, CConnman* _connman):
pwallet(_pwallet),
connman(_connman),
consensusParams(Params().GetConsensus()),
delegationsStaker(_pwallet),
myDelegations(_pwallet)
{
// Make this thread recognisable as the mining thread
std::string threadName = "eqpaystake";
if(pwallet && pwallet->GetName() != "")
{
threadName = threadName + "-" + pwallet->GetName();
}
util::ThreadRename(threadName.c_str());
regtestMode = Params().MineBlocksOnDemand();
minDifficulty = consensusParams.fPowAllowMinDifficultyBlocks;
fSuperStake = gArgs.GetBoolArg("-superstaking", DEFAULT_SUPER_STAKE);
nOfflineStakeHeight = consensusParams.nOfflineStakeHeight;
fDelegationsContract = !consensusParams.delegationsAddress.IsNull();
fEmergencyStaking = gArgs.GetBoolArg("-emergencystaking", false);
fAggressiveStaking = gArgs.IsArgSet("-aggressive-staking");
int maxWaitForBestHeader = gArgs.GetArg("-maxstakerwaitforbestheader", DEFAULT_MAX_STAKER_WAIT_FOR_BEST_BLOCK_HEADER);
if(maxWaitForBestHeader > 0)
{
waitBestHeaderAttempts = maxWaitForBestHeader / nMinerWaitBestBlockHeader;
}
if(pwallet) numThreads = pwallet->m_num_threads;
}
void clearCache()
{
nHeight = 0;
stakeTimestampMask = 1;
nTotalFees = 0;
haveCoinsForStake = false;
forceUpdate = false;
pindexPrev = 0;
nTargetValue = 0;
setCoins.clear();
setSelectedCoins.clear();
setDelegateCoins.clear();
prevouts.clear();
mapSolveBlockTime.clear();
mapSolvedBlock.clear();
mapSolveSelectedCoins.clear();
mapSolveDelegateCoins.clear();
beginningTime = 0;
endingTime = 0;
pblock.reset();
pblocktemplate.reset();
pblockfilled.reset();
pblocktemplatefilled.reset();
}
};
class StakeMiner : public IStakeMiner
{
private:
StakeMinerPriv *d = 0;
public:
void Init(CWallet *pwallet, CConnman* connman)
{
d = new StakeMinerPriv(pwallet, connman);
}
void Run()
{
SetThreadPriority(THREAD_PRIORITY_LOWEST);
while (Next()) {
// Is ready for mining
if(!IsReady()) continue;
// Cache mining data
if(!CacheData()) continue;
// Check if miner have coins for staking
if(HaveCoinsForStake())
{
// Look for possibility to create a block
d->beginningTime = GetAdjustedTime();
d->beginningTime &= ~d->stakeTimestampMask;
d->endingTime = d->beginningTime + nMaxStakeLookahead;
for(uint32_t blockTime = d->beginningTime; blockTime < d->endingTime; blockTime += d->stakeTimestampMask+1)
{
// Update status bar
UpdateStatusBar(blockTime);
// Check cached data
if(IsCachedDataOld())
break;
// Check if block can be created
if(CanCreateBlock(blockTime))
{
// Create new block
if(!CreateNewBlock(blockTime)) break;
// Sign new block
if(SignNewBlock(blockTime)) break;
}
}
}
// Miner sleep before the next try
Sleep(nMinerSleep);
}
}
~StakeMiner()
{
if(d)
{
delete d;
d = 0;
}
}
protected:
bool Next()
{
return d && d->pwallet && !d->pwallet->IsStakeClosing() && !d->fError;
}
bool Sleep(u_int64_t milliseconds)
{
return SleepStaker(d->pwallet, milliseconds);
}
bool IsStale(std::shared_ptr<CBlock> pblock)
{
if(d->pwallet->IsStakeClosing())
return false;
auto locked_chain = d->pwallet->chain().lock();
CBlockIndex* tip = ::ChainActive().Tip();
return tip != d->pindexPrev || tip->GetBlockHash() != pblock->hashPrevBlock;
}
bool IsReady()
{
// Check if wallet is ready
while (d->pwallet->IsLocked() || !d->pwallet->m_enabled_staking || fReindex || fImporting)
{
d->pwallet->m_last_coin_stake_search_interval = 0;
if(!Sleep(10000))
return false;
}
// Wait for node connections
// Don't disable PoS mining for no connections if in regtest mode
if(!d->minDifficulty && !d->fEmergencyStaking) {
while (d->connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0 || ::ChainstateActive().IsInitialBlockDownload()) {
d->pwallet->m_last_coin_stake_search_interval = 0;
d->fTryToSync = true;
if(!Sleep(1000))
return false;
}
if (d->fTryToSync) {
d->fTryToSync = false;
if (d->connman->GetNodeCount(CConnman::CONNECTIONS_ALL) < 3 ||
::ChainActive().Tip()->GetBlockTime() < GetTime() - 10 * 60) {
Sleep(60000);
return false;
}
}
}
// Check if cached data is old
uint32_t blokTime = GetAdjustedTime();
blokTime &= ~d->stakeTimestampMask;
if(!IsCachedDataOld() && d->endingTime >= blokTime)
{
Sleep(100);
return false;
}
// Wait for PoW block time in regtest mode
if(d->regtestMode) {
bool waitForBlockTime = false;
{
if(d->pwallet->IsStakeClosing()) return false;
auto locked_chain = d->pwallet->chain().lock();
CBlockIndex* tip = ::ChainActive().Tip();
if(tip && tip->IsProofOfWork() && tip->GetBlockTime() > GetTime()) {
waitForBlockTime = true;
}
}
// Wait for generated PoW block time
if(waitForBlockTime) {
Sleep(10000);
return false;
}
}
return true;
}
bool IsCachedDataOld()
{
if(d->pwallet->IsStakeClosing()) return false;
if(d->pindexPrev == 0 || d->forceUpdate) return true;
auto locked_chain = d->pwallet->chain().lock();
return ::ChainActive().Tip() != d->pindexPrev;
}
bool WaitBestHeader()
{
if(d->pwallet->IsStakeClosing()) return false;
if(d->fEmergencyStaking || d->fAggressiveStaking) return false;
auto locked_chain = d->pwallet->chain().lock();
CBlockIndex* tip = ::ChainActive().Tip();
if(pindexBestHeader!= 0 &&
tip != 0 &&
tip != pindexBestHeader &&
tip->nHeight < pindexBestHeader->nHeight)
{
return true;
}
return false;
}
bool SyncWithMiners()
{
// Try sync with mines
for(size_t i = 0; i < d->waitBestHeaderAttempts; i++)
{
if(WaitBestHeader())
{
if(!Sleep(nMinerWaitBestBlockHeader))
return false;
}
else
{
break;
}
}
return true;
}
bool UpdateData()
{
if(d->pwallet->IsStakeClosing()) return false;
auto locked_chain = d->pwallet->chain().lock();
LOCK(d->pwallet->cs_wallet);
d->clearCache();
CAmount nBalance = d->pwallet->GetBalance().m_mine_trusted;
d->nTargetValue = nBalance - d->pwallet->m_reserve_balance;
CAmount nValueIn = 0;
d->pindexPrev = ::ChainActive().Tip();
int32_t nHeightTip = ::ChainActive().Height();
d->nHeight = nHeightTip + 1;
updateMinerParams(d->nHeight, d->consensusParams, d->minDifficulty);
bool fOfflineStakeEnabled = (d->nHeight > d->nOfflineStakeHeight) && d->fDelegationsContract;
if(fOfflineStakeEnabled)
{
d->myDelegations.Update(*locked_chain, nHeightTip);
}
d->pwallet->SelectCoinsForStaking(*locked_chain, d->nTargetValue, d->setCoins, nValueIn);
if(d->fSuperStake && fOfflineStakeEnabled)
{
d->delegationsStaker.Update(nHeightTip);
std::map<uint160, CAmount> mDelegateWeight;
d->pwallet->SelectDelegateCoinsForStaking(*locked_chain, d->setDelegateCoins, mDelegateWeight);
d->pwallet->updateDelegationsWeight(mDelegateWeight);
d->pwallet->updateHaveCoinSuperStaker(d->setCoins);
}
d->stakeTimestampMask = d->consensusParams.StakeTimestampMask(d->nHeight);
d->haveCoinsForStake = d->setCoins.size() > 0 || d->pwallet->CanSuperStake(d->setCoins, d->setDelegateCoins);
if(d->haveCoinsForStake)
{
// Create an empty block. No need to process transactions until we know we can create a block
d->nTotalFees = 0;
d->pblocktemplate = std::unique_ptr<CBlockTemplate>(BlockAssembler(mempool, Params(), d->pwallet).CreateEmptyBlock(CScript(), true, true, &d->nTotalFees));
if (!d->pblocktemplate.get()) {
d->fError = true;
return false;
}
d->pblock = std::make_shared<CBlock>(d->pblocktemplate->block);
d->prevouts.insert(d->prevouts.end(), d->setDelegateCoins.begin(), d->setDelegateCoins.end());
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : d->setCoins)
{
d->prevouts.push_back(COutPoint(pcoin.first->GetHash(), pcoin.second));
}
d->pwallet->UpdateMinerStakeCache(true, d->prevouts, d->pindexPrev);
}
d->beginningTime = GetAdjustedTime();
d->beginningTime &= ~d->stakeTimestampMask;
d->endingTime = d->beginningTime + nMaxStakeLookahead;
return true;
}
bool CacheData()
{
if(IsCachedDataOld())
{
if(!UpdateData())
return false;
}
return !d->pwallet->IsStakeClosing();
}
bool HaveCoinsForStake()
{
return d->haveCoinsForStake;
}
void UpdateStatusBar(const uint32_t& blockTime)
{
// The information is needed for status bar to determine if the staker is trying to create block and when it will be created approximately,
if(d->pwallet->m_last_coin_stake_search_time == 0) d->pwallet->m_last_coin_stake_search_time = GetAdjustedTime(); // startup timestamp
// nLastCoinStakeSearchInterval > 0 mean that the staker is running
int64_t searchInterval = blockTime - d->pwallet->m_last_coin_stake_search_time;
if(searchInterval > 0) d->pwallet->m_last_coin_stake_search_interval = searchInterval;
}
void SloveBlock(uint32_t blockTime, size_t delegateSize, size_t from, size_t to)
{
std::multimap<uint256, SolveItem> tmpSolvedBlock;
for(size_t i = from; i < to; i++)
{
const COutPoint &prevoutStake = d->prevouts[i];
uint256 hashProofOfStake;
if (CheckKernelCache(d->pindexPrev, d->pblock->nBits, blockTime, prevoutStake, d->pwallet->minerStakeCache, hashProofOfStake))
{
bool delegate = i < delegateSize;
tmpSolvedBlock.insert(std::make_pair(hashProofOfStake, SolveItem(prevoutStake, blockTime, delegate)));
}
}
if(tmpSolvedBlock.size() > 0)
{
LOCK(d->cs_worker);
d->mapSolveBlockTime[blockTime] = true;
d->mapSolvedBlock.insert(tmpSolvedBlock.begin(), tmpSolvedBlock.end());
}
}
void SloveBlock(const uint32_t& blockTime)
{
// Init variables
size_t listSize = d->prevouts.size();
size_t delegateSize = d->setDelegateCoins.size();
// Solve block
int numThreads = std::min(d->numThreads, (int)listSize);
if(listSize < 1000 || numThreads < 2)
{
SloveBlock(blockTime, delegateSize, 0, listSize);
}
else
{
size_t chunk = listSize / numThreads;
for(int i = 0; i < numThreads; i++)
{
size_t from = i * chunk;
size_t to = i == (numThreads -1) ? listSize : from + chunk;
d->threads.create_thread([this, blockTime, delegateSize, from, to]{SloveBlock(blockTime, delegateSize, from, to);});
}
d->threads.join_all();
}
// Populate the list with the potential solwed blocks
for (auto it = d->mapSolvedBlock.begin(); it != d->mapSolvedBlock.end(); ++it)
{
const SolveItem& item = (*it).second;
if(item.delegate)
{
d->mapSolveDelegateCoins[item.blockTime].push_back(item.prevoutStake);
}
else
{
d->mapSolveSelectedCoins[item.blockTime].push_back(item.prevoutStake);
}
}
}
bool CanCreateBlock(const uint32_t& blockTime)
{
d->pblock->nTime = blockTime;
if(d->mapSolveBlockTime.find(blockTime) == d->mapSolveBlockTime.end())
{
d->mapSolveBlockTime[blockTime] = false;
SloveBlock(blockTime);
}
return d->mapSolveBlockTime[blockTime];
}
bool CreateNewBlock(const uint32_t& blockTime)
{
// increase priority so we can build the full PoS block ASAP to ensure the timestamp doesn't expire
SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
if (IsStale(d->pblock)) {
//another block was received while building ours, scrap progress
LogPrintf("ThreadStakeMiner(): Valid future PoS block was orphaned before becoming valid\n");
return false;
}
// Try to create an empty PoS block to get the address of the block creator for contracts
if (!SignBlock(d->pblock, *(d->pwallet), d->nTotalFees, blockTime, d->setCoins, d->mapSolveSelectedCoins[blockTime], d->mapSolveDelegateCoins[blockTime], true, true))
return false;
// Create a block that's properly populated with transactions
d->pblocktemplatefilled = std::unique_ptr<CBlockTemplate>(
BlockAssembler(mempool, Params(), d->pwallet).CreateNewBlock(d->pblock->vtx[1]->vout[1].scriptPubKey, true, true, &(d->nTotalFees),
blockTime, FutureDrift(GetAdjustedTime(), d->nHeight, d->consensusParams) - nStakeTimeBuffer));
if (!d->pblocktemplatefilled.get()) {
d->fError = true;
return false;
}
if (IsStale(d->pblock)) {
//another block was received while building ours, scrap progress
LogPrintf("ThreadStakeMiner(): Valid future PoS block was orphaned before becoming valid\n");
return false;
}
// Sign the full block and use the timestamp from earlier for a valid stake
d->pblockfilled = std::make_shared<CBlock>(d->pblocktemplatefilled->block);
return true;
}
bool SignNewBlock(const uint32_t& blockTime)
{
// Try to sign the block once at specific time with the same cached data
d->mapSolveBlockTime[blockTime] = false;
if (SignBlock(d->pblockfilled, *(d->pwallet), d->nTotalFees, blockTime, d->setCoins, d->mapSolveSelectedCoins[blockTime], d->mapSolveDelegateCoins[blockTime], true)) {
// Should always reach here unless we spent too much time processing transactions and the timestamp is now invalid
// CheckStake also does CheckBlock and AcceptBlock to propogate it to the network
bool validBlock = false;
while(!validBlock) {
if (IsStale(d->pblockfilled)) {
//another block was received while building ours, scrap progress
LogPrintf("ThreadStakeMiner(): Valid future PoS block was orphaned before becoming valid\n");
break;
}
//check timestamps
if (d->pblockfilled->GetBlockTime() <= d->pindexPrev->GetBlockTime() ||
FutureDrift(d->pblockfilled->GetBlockTime(), d->nHeight, d->consensusParams) < d->pindexPrev->GetBlockTime()) {
LogPrintf("ThreadStakeMiner(): Valid PoS block took too long to create and has expired\n");
break; //timestamp too late, so ignore
}
if (d->pblockfilled->GetBlockTime() > FutureDrift(GetAdjustedTime(), d->nHeight, d->consensusParams)) {
if (d->fAggressiveStaking) {
//if being agressive, then check more often to publish immediately when valid. This might allow you to find more blocks,
//but also increases the chance of broadcasting invalid blocks and getting DoS banned by nodes,
//or receiving more stale/orphan blocks than normal. Use at your own risk.
if(!Sleep(100)) break;
}else{
//too early, so wait 3 seconds and try again
if(!Sleep(nMinerWaitWalidBlock)) break;
}
continue;
}
//if there is mined block by other staker wait for it to download
if(!SyncWithMiners()) break;
validBlock=true;
}
if(validBlock) {
if(!CheckStake(d->pblockfilled, *(d->pwallet)))
d->forceUpdate = true;
// Update the search time when new valid block is created, needed for status bar icon
d->pwallet->m_last_coin_stake_search_time = d->pblockfilled->GetBlockTime();
}
return true;
}
//return back to low priority
SetThreadPriority(THREAD_PRIORITY_LOWEST);
return false;
}
};
IStakeMiner *createMiner()
{
return new StakeMiner();
}
void ThreadStakeMiner(CWallet *pwallet, CConnman* connman)
{
IStakeMiner* miner = createMiner();
miner->Init(pwallet, connman);
miner->Run();
delete miner;
miner = 0;
}
void StartStaking(bool fStake, CWallet *pwallet, CConnman* connman, boost::thread_group*& stakeThread)
{
if (stakeThread != nullptr)
{
stakeThread->interrupt_all();
stakeThread->join_all();
delete stakeThread;
stakeThread = nullptr;
}
if(fStake)
{
stakeThread = new boost::thread_group();
stakeThread->create_thread(boost::bind(&ThreadStakeMiner, pwallet, connman));
}
}
void RefreshDelegates(CWallet *pwallet, bool refreshMyDelegates, bool refreshStakerDelegates)
{
if(pwallet && (refreshMyDelegates || refreshStakerDelegates))
{
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
DelegationsStaker delegationsStaker(pwallet);
MyDelegations myDelegations(pwallet);
int nOfflineStakeHeight = Params().GetConsensus().nOfflineStakeHeight;
bool fDelegationsContract = !Params().GetConsensus().delegationsAddress.IsNull();
int32_t nHeight = ::ChainActive().Height();
bool fOfflineStakeEnabled = ((nHeight + 1) > nOfflineStakeHeight) && fDelegationsContract;
if(fOfflineStakeEnabled)
{
if(refreshMyDelegates)
{
myDelegations.Update(*locked_chain, nHeight);
}
if(refreshStakerDelegates)
{
bool fUpdatedSuperStaker = pwallet->fUpdatedSuperStaker;
delegationsStaker.Update(nHeight);
pwallet->fUpdatedSuperStaker = fUpdatedSuperStaker;
}
}
}
}
// Solo Miner
double hashrate = 0.;
bool fGenerateSolo = false;
static int64_t timeElapsed = 30000;
double dHashesPerMin = 0.0;
int64_t nHPSTimerStart = 0;
bool CheckWork(CBlock* pblock)
{
arith_uint256 hashBlock = UintToArith256(pblock->GetWorkHash());
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
CBlockIndex* pindexPrev = ::ChainActive().Tip();
if (hashBlock > hashTarget){
return error("CheckWork() : proof-of-work not meeting target");
} else {
if (pblock->hashPrevBlock != pindexPrev->GetBlockHash()){
return error("CheckWork() : generated block is stale");
}
pblock->print();
LogPrintf("New proof-of-work block found with: %s coins generated.\n", FormatMoney(pblock->vtx[0]->vout[0].nValue).c_str());
// Process this block the same as if we had received it from another node
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr))
return error("CheckWork() : ProcessBlock, block not accepted");
}
return true;
}
static // Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return GetTotalBlocksEstimate(Params().Checkpoints());
}
void Miner(CWallet *pwallet, CConnman* connman)
{
LogPrintf("Miner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
util::ThreadRename("eqpay-solo-miner");
// Each thread has it's own nonce
ReserveDestination reservedest(pwallet, DEFAULT_ADDRESS_TYPE);
CTxDestination dest;
bool ret = reservedest.GetReservedDestination(dest, true);
if (!ret)
{
return;
}
CScript scriptChange;
scriptChange = GetScriptForDestination(dest);
unsigned int nExtraNonce = 0;
try
{
while (fGenerateSolo)
{
while (::ChainstateActive().IsInitialBlockDownload() || connman->GetNodeCount(CConnman::CONNECTIONS_ALL) < 1 || ::ChainActive().Tip()->nHeight < GetNumBlocksOfPeers()){
LogPrintf("Mining inactive while chain is syncing...\n");
UninterruptibleSleep(std::chrono::milliseconds{5000});
break;
}
// Create new block
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = ::ChainActive().Tip();
std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(mempool, Params()).CreateNewBlock(scriptChange, true, false, nullptr, 0, GetAdjustedTime() + POW_MINER_MAX_TIME));
if (!pblocktemplate.get())
return;
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
LogPrintf("Miner thread running on block %s (%lu bytes)\n", pindexPrev->nHeight, ::GetSerializeSize(*pblock, PROTOCOL_VERSION));
// Search
int64_t nStart = GetTime();
uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
while (fGenerateSolo)
{
unsigned int nHashesDone = 0;
if (fGenerateSolo)
{
if (CheckProofOfWork(pblock->GetWorkHash(), pblock->nBits, Params().GetConsensus()))
{
// Found a solution
LogPrintf("Miner found a solution\n");
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
}
nHashesDone += 1;
pblock->nNonce += 1;
}
// Hash meter
static int64_t nHashCounter;
{
static RecursiveMutex cs;
{
LOCK(cs);
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > timeElapsed)
{
dHashesPerMin = 60000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
updateHashrate(dHashesPerMin);
LogPrintf("Total local hashrate: %6.0f hashes/min\n", hashrate);
}
}
}
// Check for stop or if block needs to be rebuilt
boost::this_thread::interruption_point();
if (!fGenerateSolo)
break;
if (ShutdownRequested())
return;
if (connman->GetNodeCount(CConnman::CONNECTIONS_ALL) < 1)
break;
if (pblock->nNonce >= 0xffff0000)
break;
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != ::ChainActive().Tip())
break;
// Update nTime every few seconds
UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
}
}
}
catch (boost::thread_interrupted)
{
hashrate = 0;
nExtraNonce = 0;
LogPrintf("Miner terminated\n");
throw;
}
}
void GenerateSolo(bool fGenerate, CWallet *pwallet, CConnman* connman, boost::thread_group*& minerThreads, int nThreads)
{
fGenerateSolo = fGenerate;
if (minerThreads != nullptr)
{
minerThreads->interrupt_all();
minerThreads->join_all();
delete minerThreads;
minerThreads = nullptr;
}
if (fGenerate)
{
minerThreads = new boost::thread_group();
for (int i = 0; i < nThreads; i++)
minerThreads->create_thread(boost::bind(&Miner, pwallet, connman));
}
}
void updateHashrate(double nHashrate)
{
hashrate = nHashrate;
}
#endif
|
; A129954: Second differences of A129952.
; 1,3,6,14,32,72,160,352,768,1664,3584,7680,16384,34816,73728,155648,327680,688128,1441792,3014656,6291456,13107200,27262976,56623104,117440512,243269632,503316480,1040187392,2147483648,4429185024,9126805504,18790481920,38654705664,79456894976,163208757248,335007449088,687194767360,1408749273088,2886218022912,5909874999296,12094627905536,24739011624960,50577534877696,103354093010944,211106232532992,431008558088192,879609302220800,1794402976530432,3659174697238528,7459086882832384
mov $1,2
pow $1,$0
add $0,4
mul $1,$0
div $1,2
add $1,1
div $1,2
mov $0,$1
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CheckEncryption.h"
#include "FileDeviceUtils.h"
#include "Utils.h"
#include "VolumeManager.h"
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/unique_fd.h>
#include <cutils/iosched_policy.h>
#include <private/android_filesystem_config.h>
#include <sstream>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
using android::base::unique_fd;
using android::base::ReadFileToString;
using android::base::WriteStringToFile;
namespace android {
namespace vold {
constexpr uint32_t max_extents = 32;
constexpr size_t bytecount = 8;
constexpr int repeats = 256;
bool check_file(const std::string& needle) {
LOG(DEBUG) << "checkEncryption check_file: " << needle;
auto haystack = android::vold::BlockDeviceForPath(needle);
if (haystack.empty()) {
LOG(ERROR) << "Failed to find device for path: " << needle;
return false;
}
std::string randombytes;
if (ReadRandomBytes(bytecount, randombytes) != 0) {
LOG(ERROR) << "Failed to read random bytes";
return false;
}
std::string randomhex;
StrToHex(randombytes, randomhex);
std::ostringstream os;
for (int i = 0; i < repeats; i++) os << randomhex;
auto towrite = os.str();
if (access(needle.c_str(), F_OK) == 0) {
if (unlink(needle.c_str()) != 0) {
PLOG(ERROR) << "Failed to unlink " << needle;
return false;
}
}
LOG(DEBUG) << "Writing to " << needle;
if (!WriteStringToFile(towrite, needle)) {
PLOG(ERROR) << "Failed to write " << needle;
return false;
}
sync();
unique_fd haystack_fd(open(haystack.c_str(), O_RDONLY | O_CLOEXEC));
if (haystack_fd.get() == -1) {
PLOG(ERROR) << "Failed to open " << haystack;
return false;
}
auto fiemap = PathFiemap(needle, max_extents);
std::string area;
for (uint32_t i = 0; i < fiemap->fm_mapped_extents; i++) {
auto xt = &(fiemap->fm_extents[i]);
LOG(DEBUG) << "Extent " << i << " at " << xt->fe_physical << " length " << xt->fe_length;
if (lseek64(haystack_fd.get(), xt->fe_physical, SEEK_SET) == -1) {
PLOG(ERROR) << "Failed lseek";
return false;
}
auto toread = xt->fe_length;
while (toread > 0) {
char buf[BUFSIZ];
size_t wlen =
static_cast<size_t>(std::min(static_cast<typeof(toread)>(sizeof(buf)), toread));
auto l = read(haystack_fd.get(), buf, wlen);
if (l < 1) {
PLOG(ERROR) << "Failed read";
if (errno != EINTR) {
return false;
}
}
area.append(buf, l);
toread -= l;
}
}
LOG(DEBUG) << "Searching " << area.size() << " bytes of " << needle;
LOG(DEBUG) << "First position of blob: " << area.find(randomhex);
return true;
}
int CheckEncryption(const std::string& path) {
auto deNeedle(path);
deNeedle += "/misc";
if (android::vold::PrepareDir(deNeedle, 01771, AID_SYSTEM, AID_MISC)) {
return -1;
}
deNeedle += "/vold";
if (android::vold::PrepareDir(deNeedle, 0700, AID_ROOT, AID_ROOT)) {
return -1;
}
deNeedle += "/checkEncryption";
auto neNeedle(path);
neNeedle += "/unencrypted/checkEncryption";
check_file(deNeedle);
check_file(neNeedle);
return 0;
}
} // namespace vold
} // namespace android
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
ld a, ff
ldff(45), a
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld hl, fea0
lbegin_fill_oam:
dec l
ld(hl), a
jrnz lbegin_fill_oam
ld hl, fe00
ld d, 10
ld a, d
ld(hl), a
inc l
ld a, 09
ld(hl), a
ld a, 97
ldff(40), a
call lwaitly_b
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 97
ldff(45), a
ld c, 41
ld a, 04
ldff(43), a
.text@1000
lstatint:
nop
.text@151c
ldff a, (c)
and a, 03
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
|
; A088992: Derangement numbers d(n,5) where d(n,k) = k(n-1)(d(n-1,k) + d(n-2,k)), with d(0,k) = 1 and d(1,k) = 0.
; Submitted by Jamie Morken(s1)
; 1,0,5,50,825,17500,458125,14268750,515440625,21188375000,976671703125,49893003906250,2797832158515625,170863509745312500,11287987223748828125,802119551344589843750,61005565392625400390625,4944614795517599218750000
mov $3,1
lpb $0
sub $0,1
mul $3,$0
mov $2,$3
add $3,$1
mov $1,$2
mul $3,5
lpe
mov $0,$3
|
mov ah, 0x0e ; tty mode
mov bp, 0x8000 ; this is an address far away from 0x7c00 so that we don't get overwritten
mov sp, bp ; if the stack is empty then sp points to bp
push 'A'
push 'B'
push 'C'
; to show how the stack grows downwards
mov al, [0x7ffe] ; 0x8000 - 2
int 0x10 ; prints A
mov al, [0x7ffc] ; 0x8000 - 4
int 0x10 ; prints B
mov al, [0x7ffa] ; 0x8000 - 6
int 0x10 ; prints C
; however, don't try to access [0x8000] now, because it won't work
; 0x8000 is just the base address and doesn't contain anything
mov al, [0x8000]
int 0x10
; recover our characters using the standard procedure: 'pop'
; We can only pop full words so we need an auxiliary register to manipulate
; the lower byte
pop bx
mov al, bl
int 0x10 ; prints C
pop bx
mov al, bl
int 0x10 ; prints B
pop bx
mov al, bl
int 0x10 ; prints A
jmp $
times 510-($-$$) db 0
dw 0xaa55
|
default rel
bits 64
segment .data
format_length db 'length is %lf', 0xa, 0 ; lf for double in c99
format_distance db 'distance is %lf', 0xa, 0
format_inner db 'dot product is %lf', 0xa, 0
v1x dd 5.0
v1y dd 6.0
v1z dd 7.0
v2x dd 8.0
v2y dd 9.0
v2z dd 10.0
segment .text
extern printf
extern _CRT_INIT
extern ExitProcess
global length_vec3
global distance_vec3
global inner_product_vec3
global main
inner_product_vec3: ; float inner_product_vec3(float x1, float y1, float z1, float x2, float y2, float z2)
.y2 equ 0
.z2 equ 4
; TODO: Is this a good idea? should I take the variables before/after setting up the stack frame?
; How can I get the 48 value for rbp to make this an actual function?
movss xmm5, [rbp - 48 + .z2]
movss xmm4, [rbp - 48 + .y2]
push rbp
mov rbp, rsp
sub rsp, 32
mulss xmm0, xmm3 ; x1 * x2
mulss xmm1, xmm4 ; y1 * y2
mulss xmm2, xmm5 ; z1 * z2
addss xmm1, xmm2
addss xmm0, xmm1
leave
ret
length_vec3: ; float length_vec3(float x, float y, float z)
push rbp
mov rbp, rsp
sub rsp, 32
mulss xmm0, xmm0
mulss xmm1, xmm1
mulss xmm2, xmm2
addss xmm0, xmm2
addss xmm0, xmm1
sqrtss xmm0, xmm0 ; Return value is also here since float is non-scalar type.
leave
ret
distance_vec3: ; float distance_vec3(float x1, float y1, float z1, float x2, float y2, float z2)
.y2 equ 0
.z2 equ 4
; TODO: Is this a good idea? should I take the variables before/after setting up the stack frame?
; How can I get the 48 value for rbp to make this an actual function?
movss xmm5, [rbp - 48 + .z2]
movss xmm4, [rbp - 48 + .y2]
push rbp
mov rbp, rsp
sub rsp, 32
; At this point:
; xmm0: x1, xmm1: y1, xmm2: z1 xmm3: x2, rsp + 32: y2, rsp + 36: z2
subss xmm0, xmm3 ; x1 - x2
mulss xmm0, xmm0 ; (x1 - x2) ^ 2
subss xmm1, xmm4 ; y1 - y2
mulss xmm1, xmm1 ; (y1 - y2) ^ 2
subss xmm2, xmm5
mulss xmm2, xmm2
addss xmm0, xmm2
addss xmm0, xmm1 ; (x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2
sqrtss xmm0, xmm0
leave
ret
main:
.y2 equ 0
.z2 equ 4
push rbp
mov rbp, rsp
sub rsp, 48
call _CRT_INIT ; Needed since our entry point is not _DllMainCRTStartup. See https://msdn.microsoft.com/en-us/library/708by912.aspx
movss xmm0, [v1x] ; 1st 3d vector
movss xmm1, [v1y]
movss xmm2, [v1z]
call length_vec3
lea rcx, [format_length] ; Place address of format string in rcx
; Remember, printf actually expects a double, so we need to convert the float
; return value to a double before printing
cvtss2sd xmm0, xmm0
movq rdx, xmm0
call printf
; Just clear so it's easier for debugging. This would be silly to do for real.
xorps xmm0, xmm0
xorps xmm1, xmm1
xorps xmm2, xmm2
; Next example: distance calcuation
; Calling convention: additional arguments are pushed onto the stack in reversed order (right-to-left).
; Last 2 params go on stack
movss xmm0, [v2z]
movss [rsp + .z2], xmm0
movss xmm0, [v2y]
movss [rsp + .y2], xmm0
; First 4 params go in registers
movss xmm3, [v2x]
movss xmm2, [v1z]
movss xmm1, [v1y]
movss xmm0, [v1x] ; 1st 3d vector
call distance_vec3
; print distance result
lea rcx, [format_distance]
cvtss2sd xmm0, xmm0
movq rdx, xmm0
call printf
; Next example: inner product calculation
xorps xmm0, xmm0
xorps xmm1, xmm1
xorps xmm2, xmm2
; Last 2 params go on stack
movss xmm0, [v2z]
movss [rsp + .z2], xmm0
movss xmm0, [v2y]
movss [rsp + .y2], xmm0
; First 4 params go in registers
movss xmm3, [v2x]
movss xmm2, [v1z]
movss xmm1, [v1y]
movss xmm0, [v1x]
call inner_product_vec3
; print dot product
lea rcx, [format_inner]
cvtss2sd xmm0, xmm0
movq rdx, xmm0
call printf
xor eax, eax ; return 0
call ExitProcess
|
; A071578: Number of iterations of Pi(n) needed to reach 1, where Pi(x) denotes the number of primes <= x.
; 0,1,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
pow $0,8
add $0,2
div $0,3
mov $1,4
mov $2,3
lpb $0
div $0,$2
div $0,20
add $1,3
mul $2,5
lpe
mul $1,6
sub $1,24
div $1,18
|
setrepeat 2
frame 0, 05
frame 1, 05
frame 2, 05
frame 3, 05
frame 4, 05
frame 5, 05
dorepeat 1
endanim
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 4.0.0 #11528 (MINGW64)
;--------------------------------------------------------
; MODULE 04_for
.optsdcc -mgbz80
; Generated using the rgbds tokens.
; We have to define these here as sdcc doesn't make them global by default
GLOBAL __mulschar
GLOBAL __muluchar
GLOBAL __mulint
GLOBAL __divschar
GLOBAL __divuchar
GLOBAL __divsint
GLOBAL __divuint
GLOBAL __modschar
GLOBAL __moduchar
GLOBAL __modsint
GLOBAL __moduint
GLOBAL __mullong
GLOBAL __modslong
GLOBAL __divslong
GLOBAL banked_call
GLOBAL banked_ret
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
GLOBAL _variable
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
SECTION "src/04-for.c_DATA",BSS
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
SECTION "DABS (ABS)",CODE
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
SECTION "HOME",CODE
SECTION "GSINIT",CODE
SECTION "GSFINAL",CODE
SECTION "GSINIT",CODE
;--------------------------------------------------------
; Home
;--------------------------------------------------------
SECTION "src/04-for.c_HOME",HOME
SECTION "src/04-for.c_HOME",HOME
;--------------------------------------------------------
; code
;--------------------------------------------------------
SECTION "src/04-for.c_CODE",CODE
;src/04-for.c:3: void variable(void)
; ---------------------------------
; Function variable
; ---------------------------------
_variable::
;src/04-for.c:6: for (i = 0; i < 10; ++i) {
xor a, a
.l00106:
.l00107:
.l00108:
.l00109:
.l00110:
.l00102:
;src/04-for.c:7: j = i;
ld hl, _j
ld [hl], a
.l00103:
;src/04-for.c:6: for (i = 0; i < 10; ++i) {
inc a
cp a, $0A
jp C, .l00102
.l00101:
;src/04-for.c:10: return;
.l00104:
;src/04-for.c:11: }
ret
SECTION "src/04-for.c_CODE",CODE
SECTION "CABS (ABS)",CODE
|
; A214392: If n mod 4 = 0 then a(n) = n/4, otherwise a(n) = n.
; 0,1,2,3,1,5,6,7,2,9,10,11,3,13,14,15,4,17,18,19,5,21,22,23,6,25,26,27,7,29,30,31,8,33,34,35,9,37,38,39,10,41,42,43,11,45,46,47,12,49,50,51,13,53,54,55,14,57,58,59,15,61,62,63,16,65,66,67,17,69,70,71,18,73,74,75,19,77,78,79,20,81,82,83,21,85,86,87,22,89,90,91,23,93,94,95,24,97,98,99
dif $0,4
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_WEED_CONTEXT_PARSE_CONTEXT_TERMINAL_CHAR_TYPE_HPP
#define SPROUT_WEED_CONTEXT_PARSE_CONTEXT_TERMINAL_CHAR_TYPE_HPP
#include <iterator>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/iterator/next.hpp>
#include <sprout/tuple/tuple.hpp>
#include <sprout/weed/eval_result.hpp>
#include <sprout/weed/expr/tag.hpp>
#include <sprout/weed/traits/type/is_char_type.hpp>
#include <sprout/weed/traits/expr/tag_of.hpp>
#include <sprout/weed/traits/parser/attribute_of.hpp>
#include <sprout/weed/context/parse_context_fwd.hpp>
namespace sprout {
namespace weed {
//
// parse_context::eval
//
template<typename Iterator>
template<typename Expr>
struct parse_context<Iterator>::eval<
Expr,
typename std::enable_if<
std::is_same<
typename sprout::weed::traits::tag_of<Expr>::type,
sprout::weed::tag::terminal
>::value
&& sprout::weed::traits::is_char_type<
typename sprout::tuples::tuple_element<0, typename Expr::args_type>::type
>::value
>::type
> {
private:
typedef sprout::weed::parse_context<Iterator> context_type;
public:
typedef sprout::weed::unused attribute_type;
typedef sprout::weed::eval_result<context_type, Iterator, attribute_type> result_type;
public:
SPROUT_CONSTEXPR result_type operator()(
Expr const& expr,
context_type const& ctx
) const
{
typedef typename std::iterator_traits<Iterator>::value_type elem_type;
return ctx.begin() != ctx.end()
&& *ctx.begin() == elem_type(sprout::tuples::get<0>(expr.args()))
? result_type(
true,
sprout::next(ctx.begin()),
attribute_type(),
context_type(ctx, sprout::next(ctx.begin()))
)
: result_type(false, ctx.begin(), attribute_type(), ctx)
;
}
};
} // namespace weed
} // namespace sprout
#endif // #ifndef SPROUT_WEED_CONTEXT_PARSE_CONTEXT_TERMINAL_CHAR_TYPE_HPP
|
; A186288: Adjusted joint rank sequence of (f(i)) and (g(j)) with f(i) before g(j) when f(i)=g(j), where f and g are the squares and pentagonal numbers. Complement of A186289.
; 1,3,5,7,9,11,12,14,16,18,20,21,23,25,27,29,31,32,34,36,38,40,41,43,45,47,49,51,52,54,56,58,60,61,63,65,67,69,71,72,74,76,78,80,81,83,85,87,89,90,92,94,96,98,100,101,103,105,107,109,110,112,114,116,118,120,121,123,125,127,129,130,132,134,136,138,140,141,143,145,147,149,150,152,154,156,158,160,161,163,165,167,169,170,172,174,176,178,179,181
add $0,1
mov $2,$0
mul $2,$0
lpb $2,1
add $0,1
sub $2,$3
trn $2,1
add $3,3
lpe
mov $1,$0
sub $1,1
|
[WiiULauncher0US]
moduleMatches = 0x90DAC5CE
; Unconditionally branch DriverD3D::LimitFramerate immediately
0x2E47110 = blr
[WiiULauncher0EU]
moduleMatches = 0x8F7D2702
; Unconditionally branch DriverD3D::LimitFramerate immediately
0x2E470F0 = blr
[WiiULauncher0JP]
moduleMatches = 0x0D395735
; Unconditionally branch DriverD3D::LimitFramerate immediately
0x2E46EAC = blr
[WiiULauncher16]
moduleMatches = 0x113CC316
; Unconditionally branch DriverD3D::LimitFramerate immediately
0x2E47148 = blr
|
; A180146: Eight rooks and one berserker on a 3 X 3 chessboard. G.f.: 1/(1 - 4*x - 3*x^2 + 6*x^3).
; Submitted by Jamie Morken(w4)
; 1,4,19,82,361,1576,6895,30142,131797,576244,2519515,11016010,48165121,210591424,920764999,4025843542,17602120621,76961423116,336496993075,1471259517922,6432760512217,28125838644184,122974079005855
lpb $0
sub $0,1
mul $2,2
mov $3,$2
mul $4,3
add $4,1
mov $2,$4
add $4,$3
lpe
mov $0,$4
mul $0,3
add $0,1
|
<%
from pwnlib.shellcraft.thumb.linux import syscall
%>
<%page args="dev, ubuf"/>
<%docstring>
Invokes the syscall ustat. See 'man 2 ustat' for more information.
Arguments:
dev(dev_t): dev
ubuf(ustat): ubuf
</%docstring>
${syscall('SYS_ustat', dev, ubuf)}
|
; A154249: a(n) = ( (8 + sqrt(7))^n - (8 - sqrt(7))^n )/(2*sqrt(7)).
; Submitted by Jamie Morken(s4)
; 1,16,199,2272,25009,270640,2904727,31049152,331216993,3529670224,37595354983,400334476960,4262416397329,45379597170544,483115820080951,5143216082574208,54753855576573121,582898372518440080,6205404192430373383,66061259845334889568,703272118556826950257,7486862085725142498736,79703282613863143815127,848501382935477178614080,9032935017977435660363041,96162381460316771384806096,1023720807340354509516204199,10898277174207616183325319712,116020348768921651890781476049,1235123781372912307802960393200
add $0,1
mov $2,1
mov $3,$0
lpb $3
mul $1,$3
mul $2,$3
add $1,$2
mul $2,3
mul $4,3
cmp $6,0
add $5,$6
div $1,$5
div $2,$5
add $2,$1
add $4,$1
mul $1,6
sub $3,1
mov $6,0
lpe
mov $0,$4
|
; A201595: E.g.f. satisfies: A(x) = exp(x*A(x)) * cosh(x*A(x)).
; Submitted by Jon Maiga
; 1,1,4,28,288,3936,67328,1385728,33372160,921118720,28677169152,994360565760,38007586684928,1587878686621696,71990467473965056,3520403893852831744,184707311409882464256,10350444842488122310656,616975843658373414256640,38981881007475178476666880,2602328737760876702495408128,183032278851485663490721447936,13528267790363668348208072884224,1048317721370259837907947170562048,84988009231198326577070393784270848,7194375050406563702557128829557538816,634782764692119050428977879127611670528
seq $0,349562 ; Number of labeled rooted forests with 2-colored leaves.
dif $0,2
|
; $Id: remainder.asm 69111 2017-10-17 14:26:02Z vboxsync $
;; @file
; IPRT - No-CRT remainder - AMD64 & X86.
;
;
; 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.
;
; 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.
;
%include "iprt/asmdefs.mac"
BEGINCODE
;;
; See SUS.
; @returns st(0)
; @param rd1 [ebp + 8h] xmm0
; @param rd2 [ebp + 10h] xmm1
BEGINPROC RT_NOCRT(remainder)
push xBP
mov xBP, xSP
sub xSP, 20h
;int3
%ifdef RT_ARCH_AMD64
movsd [rsp + 10h], xmm1
movsd [rsp], xmm0
fld qword [rsp + 10h]
fld qword [rsp]
%else
fld qword [ebp + 10h]
fld qword [ebp + 8h]
%endif
fprem1
fstsw ax
test ah, 04h
jnz .done
fstp st1
.done:
%ifdef RT_ARCH_AMD64
fstp qword [rsp]
movsd xmm0, [rsp]
%endif
leave
ret
ENDPROC RT_NOCRT(remainder)
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/swf/model/ActivityTaskCancelRequestedEventAttributes.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SWF
{
namespace Model
{
ActivityTaskCancelRequestedEventAttributes::ActivityTaskCancelRequestedEventAttributes() :
m_decisionTaskCompletedEventId(0),
m_decisionTaskCompletedEventIdHasBeenSet(false),
m_activityIdHasBeenSet(false)
{
}
ActivityTaskCancelRequestedEventAttributes::ActivityTaskCancelRequestedEventAttributes(const JsonValue& jsonValue) :
m_decisionTaskCompletedEventId(0),
m_decisionTaskCompletedEventIdHasBeenSet(false),
m_activityIdHasBeenSet(false)
{
*this = jsonValue;
}
ActivityTaskCancelRequestedEventAttributes& ActivityTaskCancelRequestedEventAttributes::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("decisionTaskCompletedEventId"))
{
m_decisionTaskCompletedEventId = jsonValue.GetInt64("decisionTaskCompletedEventId");
m_decisionTaskCompletedEventIdHasBeenSet = true;
}
if(jsonValue.ValueExists("activityId"))
{
m_activityId = jsonValue.GetString("activityId");
m_activityIdHasBeenSet = true;
}
return *this;
}
JsonValue ActivityTaskCancelRequestedEventAttributes::Jsonize() const
{
JsonValue payload;
if(m_decisionTaskCompletedEventIdHasBeenSet)
{
payload.WithInt64("decisionTaskCompletedEventId", m_decisionTaskCompletedEventId);
}
if(m_activityIdHasBeenSet)
{
payload.WithString("activityId", m_activityId);
}
return payload;
}
} // namespace Model
} // namespace SWF
} // namespace Aws |
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0xe31d, %r12
nop
nop
nop
cmp $9778, %rax
movb $0x61, (%r12)
nop
and %r10, %r10
lea addresses_UC_ht+0xb725, %rsi
lea addresses_WT_ht+0x7a25, %rdi
clflush (%rsi)
add $20323, %r12
mov $41, %rcx
rep movsq
and $37430, %rdi
lea addresses_A_ht+0xfd25, %rcx
nop
nop
nop
add $63228, %rsi
mov $0x6162636465666768, %rdi
movq %rdi, (%rcx)
nop
nop
cmp %rsi, %rsi
lea addresses_UC_ht+0x10d63, %r10
nop
nop
nop
nop
dec %rdx
movb $0x61, (%r10)
sub $30165, %rsi
lea addresses_A_ht+0x6b7d, %rcx
nop
nop
nop
nop
nop
and %rdi, %rdi
movb $0x61, (%rcx)
nop
nop
inc %r12
lea addresses_A_ht+0x198a5, %rsi
lea addresses_normal_ht+0x10925, %rdi
nop
nop
and %r12, %r12
mov $46, %rcx
rep movsl
nop
nop
nop
nop
nop
inc %rdx
lea addresses_WC_ht+0x1c405, %rsi
lea addresses_normal_ht+0x2795, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
sub $26755, %r12
mov $114, %rcx
rep movsb
xor $134, %r12
lea addresses_D_ht+0xd4a5, %rcx
nop
and $6894, %r10
movups (%rcx), %xmm6
vpextrq $0, %xmm6, %rsi
nop
nop
nop
nop
nop
cmp %rcx, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r13
push %rax
push %rcx
push %rdx
push %rsi
// Load
lea addresses_D+0x1f541, %rcx
add $36514, %rax
vmovups (%rcx), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $1, %xmm6, %rsi
xor $49193, %rax
// Store
lea addresses_RW+0x14a25, %rsi
clflush (%rsi)
nop
nop
nop
add $28746, %r10
mov $0x5152535455565758, %r12
movq %r12, %xmm6
movaps %xmm6, (%rsi)
nop
nop
nop
nop
sub %rcx, %rcx
// Store
mov $0x7cd910000000abd, %rdx
nop
nop
nop
nop
nop
dec %r13
mov $0x5152535455565758, %rcx
movq %rcx, %xmm7
movups %xmm7, (%rdx)
nop
nop
and %r13, %r13
// Store
lea addresses_A+0xfd5, %rcx
nop
nop
nop
nop
add %r12, %r12
movl $0x51525354, (%rcx)
sub %rcx, %rcx
// Load
lea addresses_normal+0xcf45, %r13
sub %rax, %rax
mov (%r13), %edx
nop
nop
nop
sub %rcx, %rcx
// Load
lea addresses_UC+0x525, %r10
nop
nop
xor $36792, %rdx
mov (%r10), %si
nop
nop
nop
dec %rax
// Load
lea addresses_PSE+0x11585, %rax
nop
nop
dec %rcx
movups (%rax), %xmm2
vpextrq $0, %xmm2, %r10
nop
nop
nop
nop
nop
inc %r12
// Store
lea addresses_UC+0x525, %r12
clflush (%r12)
nop
nop
inc %r13
movw $0x5152, (%r12)
// Exception!!!
nop
nop
mov (0), %r12
nop
xor $55240, %rdx
// Store
lea addresses_US+0x7125, %rax
nop
and $16309, %rdx
movw $0x5152, (%rax)
nop
nop
nop
sub %rdx, %rdx
// Store
lea addresses_WT+0x1a8e5, %r13
and $22916, %rdx
movl $0x51525354, (%r13)
nop
sub $35180, %r13
// Store
lea addresses_normal+0x18be1, %rdx
lfence
mov $0x5152535455565758, %rsi
movq %rsi, %xmm7
movups %xmm7, (%rdx)
// Exception!!!
nop
mov (0), %rcx
nop
nop
nop
nop
nop
cmp $5639, %rsi
// Faulty Load
lea addresses_UC+0x525, %rsi
xor $17300, %r13
vmovups (%rsi), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $0, %xmm2, %rax
lea oracles, %r12
and $0xff, %rax
shlq $12, %rax
mov (%r12,%rax,1), %rax
pop %rsi
pop %rdx
pop %rcx
pop %rax
pop %r13
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC', 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D', 'congruent': 2}}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 16, 'type': 'addresses_RW', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_NC', 'congruent': 2}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_A', 'congruent': 4}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_normal', 'congruent': 5}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': True, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC', 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_PSE', 'congruent': 3}}
{'dst': {'same': True, 'NT': True, 'AVXalign': True, 'size': 2, 'type': 'addresses_UC', 'congruent': 0}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': True, 'AVXalign': True, 'size': 2, 'type': 'addresses_US', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal', 'congruent': 1}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal_ht', 'congruent': 3}, 'OP': 'STOR'}
{'dst': {'same': True, 'congruent': 8, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_A_ht', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_UC_ht', 'congruent': 1}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_A_ht', 'congruent': 3}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 7, 'type': 'addresses_A_ht'}}
{'dst': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 2}}
{'44': 1}
44
*/
|
; A092366: Coefficient of x^n in expansion of (1+n*x+n*x^2)^n.
; Submitted by Jamie Morken(w4)
; 1,1,8,81,1120,19375,400896,9630411,262955008,8032730715,271175200000,10017828457483,401738097475584,17371952344599385,805429080795852800,39844314853048828125,2094272851244149112832,116526044312704751752451,6840974132824521501536256,422529086252663879730166275,27384766103150141440000000000,1858048798262886933447112503309,131697841349187204667031850713088,9732722669230221349798695732755249,748612372916605291696873679722905600,59833246802873737402260303497314453125
mov $4,$0
add $0,1
lpb $0
sub $0,1
mov $2,$4
sub $2,$1
bin $2,$1
mov $3,$4
bin $3,$1
add $1,1
mul $3,$2
mul $5,$4
add $5,$3
lpe
mov $0,$5
|
#include "world.h"
#include <zenload/zCMesh.h>
#include <fstream>
#include <functional>
#include <Tempest/Log>
#include <Tempest/Painter>
#include "gothic.h"
#include "focus.h"
#include "resources.h"
#include "game/serialize.h"
#include "graphics/skeleton.h"
using namespace Tempest;
World::World(GameSession& game,const RendererStorage &storage, std::string file, uint8_t isG2, std::function<void(int)> loadProgress)
:wname(std::move(file)),game(game),wsound(game,*this),wobj(*this) {
using namespace Daedalus::GameState;
ZenLoad::ZenParser parser(wname,Resources::vdfsIndex());
loadProgress(1);
parser.readHeader();
loadProgress(10);
ZenLoad::oCWorldData world;
parser.readWorld(world,isG2==2);
ZenLoad::PackedMesh mesh;
ZenLoad::zCMesh* worldMesh = parser.getWorldMesh();
worldMesh->packMesh(mesh, 1.f, false);
loadProgress(50);
wdynamic.reset(new DynamicWorld(*this,mesh));
wview.reset (new WorldView(*this,mesh,storage));
loadProgress(70);
wmatrix.reset(new WayMatrix(*this,world.waynet));
if(1){
for(auto& vob:world.rootVobs)
loadVob(vob,true);
}
wmatrix->buildIndex();
bsp = std::move(world.bspTree);
bspSectors.resize(bsp.sectors.size());
wobj.triggerOnStart(true);
loadProgress(100);
}
World::World(GameSession &game, const RendererStorage &storage,
Serialize &fin, uint8_t isG2, std::function<void(int)> loadProgress)
:wname(fin.read<std::string>()),game(game),wsound(game,*this),wobj(*this) {
using namespace Daedalus::GameState;
ZenLoad::ZenParser parser(wname,Resources::vdfsIndex());
loadProgress(1);
parser.readHeader();
loadProgress(10);
ZenLoad::oCWorldData world;
parser.readWorld(world,isG2==2);
ZenLoad::PackedMesh mesh;
ZenLoad::zCMesh* worldMesh = parser.getWorldMesh();
worldMesh->packMesh(mesh, 1.f, false);
loadProgress(50);
wdynamic.reset(new DynamicWorld(*this,mesh));
wview.reset (new WorldView(*this,mesh,storage));
loadProgress(70);
wmatrix.reset(new WayMatrix(*this,world.waynet));
if(1){
for(auto& vob:world.rootVobs)
loadVob(vob,false);
}
wmatrix->buildIndex();
bsp = std::move(world.bspTree);
bspSectors.resize(bsp.sectors.size());
wobj.triggerOnStart(false);
loadProgress(100);
}
void World::createPlayer(const char *cls) {
npcPlayer = addNpc(cls,wmatrix->startPoint().name.c_str());
if(npcPlayer!=nullptr) {
npcPlayer->setProcessPolicy(Npc::ProcessPolicy::Player);
game.script()->setInstanceNPC("HERO",*npcPlayer);
}
}
void World::insertPlayer(std::unique_ptr<Npc> &&npc,const char* waypoint) {
if(npc==nullptr)
return;
npcPlayer = wobj.insertPlayer(std::move(npc),waypoint);
if(npcPlayer!=nullptr)
game.script()->setInstanceNPC("HERO",*npcPlayer);
}
void World::postInit() {
// NOTE: level inspector override player stats globaly
// lvlInspector.reset(new Npc(*this,script().getSymbolIndex("PC_Levelinspektor"),""));
// game.script()->inserNpc("Snapper",wmatrix->startPoint().name.c_str());
}
void World::load(Serialize &fin) {
fin.setContext(this);
wobj.load(fin);
uint32_t sz=0;
fin.read(sz);
std::string tag;
for(size_t i=0;i<sz;++i) {
int32_t guild=GIL_NONE;
fin.read(tag,guild);
if(auto p = portalAt(tag))
p->guild = guild;
}
npcPlayer = wobj.findHero();
if(npcPlayer!=nullptr)
game.script()->setInstanceNPC("HERO",*npcPlayer);
}
void World::save(Serialize &fout) {
fout.setContext(this);
fout.write(wname);
wobj.save(fout);
fout.write(uint32_t(bspSectors.size()));
for(size_t i=0;i<bspSectors.size();++i) {
fout.write(bsp.sectors[i].name,bspSectors[i].guild);
}
}
uint32_t World::npcId(const void *ptr) const {
return wobj.npcId(ptr);
}
uint32_t World::itmId(const void *ptr) const {
return wobj.itmId(ptr);
}
Npc *World::npcById(uint32_t id) {
if(id<wobj.npcCount())
return &wobj.npc(id);
return nullptr;
}
Item *World::itmById(uint32_t id) {
if(id<wobj.itmCount())
return &wobj.itm(id);
return nullptr;
}
MeshObjects::Mesh World::getView(const std::string &visual) const {
return getView(visual,0,0,0);
}
MeshObjects::Mesh World::getView(const std::string &visual, int32_t headTex, int32_t teetTex, int32_t bodyColor) const {
return view()->getView(visual,headTex,teetTex,bodyColor);
}
PfxObjects::Emitter World::getView(const ParticleFx *decl) const {
return view()->getView(decl);
}
MeshObjects::Mesh World::getStaticView(const std::string &visual, int32_t tex) const {
return view()->getStaticView(visual,tex);
}
DynamicWorld::Item World::getPhysic(const std::string& visual) {
if(auto sk=Resources::loadSkeleton(visual))
return physic()->ghostObj(sk->bboxCol[0],sk->bboxCol[1]);
ZMath::float3 zero={};
return physic()->ghostObj(zero,zero);
}
const VisualFx *World::loadVisualFx(const char *name) {
return game.loadVisualFx(name);
}
const ParticleFx* World::loadParticleFx(const char *name) {
return game.loadParticleFx(name);
}
void World::updateAnimation() {
static bool doAnim=true;
if(!doAnim)
return;
wobj.updateAnimation();
}
void World::resetPositionToTA() {
wobj.resetPositionToTA();
}
std::unique_ptr<Npc> World::takeHero() {
return wobj.takeNpc(npcPlayer);
}
Npc *World::findNpcByInstance(size_t instance) {
return wobj.findNpcByInstance(instance);
}
const std::string& World::roomAt(const std::array<float,3> &arr) {
static std::string empty;
if(bsp.nodes.empty())
return empty;
const float x=arr[0], y=arr[1], z=arr[2];
const ZenLoad::zCBspNode* node=&bsp.nodes[0];
while(true) {
const float* v = node->plane.v;
float sgn = v[0]*x + v[1]*y + v[2]*z - v[3];
uint32_t next = (sgn>0) ? node->front : node->back;
if(next>=bsp.nodes.size())
break;
node = &bsp.nodes[next];
}
if(node->bbox3dMin.x <= x && x <node->bbox3dMax.x &&
node->bbox3dMin.y <= y && y <node->bbox3dMax.y &&
node->bbox3dMin.z <= z && z <node->bbox3dMax.z) {
return roomAt(*node);
}
return empty;
}
const std::string& World::roomAt(const ZenLoad::zCBspNode& node) {
std::string* ret=nullptr;
size_t count=0;
auto id = &node-bsp.nodes.data();(void)id;
for(auto& i:bsp.sectors) {
for(auto r:i.bspNodeIndices)
if(r<bsp.leafIndices.size()){
size_t idx = bsp.leafIndices[r];
if(idx>=bsp.nodes.size())
continue;
if(&bsp.nodes[idx]==&node) {
ret = &i.name;
count++;
}
}
}
if(count==1) {
// TODO: portals
return *ret;
}
static std::string empty;
return empty;
}
World::BspSector* World::portalAt(const std::string &tag) {
if(tag.empty())
return nullptr;
for(size_t i=0;i<bsp.sectors.size();++i)
if(bsp.sectors[i].name==tag)
return &bspSectors[i];
return nullptr;
}
void World::tick(uint64_t dt) {
static bool doTicks=true;
if(!doTicks)
return;
wobj.tick(dt);
wdynamic->tick(dt);
wview->tick(dt);
if(auto pl = player())
wsound.tick(*pl);
}
uint64_t World::tickCount() const {
return game.tickCount();
}
void World::setDayTime(int32_t h, int32_t min) {
gtime now = game.time();
auto day = now.day();
gtime dayTime = now.timeInDay();
gtime next = gtime(h,min);
if(dayTime<=next){
game.setTime(gtime(day,h,min));
} else {
game.setTime(gtime(day+1,h,min));
}
wobj.resetPositionToTA();
}
gtime World::time() const {
return game.time();
}
Daedalus::PARSymbol &World::getSymbol(const char *s) const {
return game.script()->getSymbol(s);
}
size_t World::getSymbolIndex(const char *s) const {
return game.script()->getSymbolIndex(s);
}
Focus World::validateFocus(const Focus &def) {
Focus ret = def;
ret.npc = wobj.validateNpc(ret.npc);
ret.interactive = wobj.validateInteractive(ret.interactive);
ret.item = wobj.validateItem(ret.item);
return ret;
}
Focus World::findFocus(const Npc &pl, const Focus& def, const Tempest::Matrix4x4 &v, int w, int h) {
const Daedalus::GEngineClasses::C_Focus* fptr=&game.script()->focusNorm();
auto opt = WorldObjects::NoFlg;
auto coll = TARGET_COLLECT_FOCUS;
switch(pl.weaponState()) {
case WeaponState::Fist:
case WeaponState::W1H:
case WeaponState::W2H:
fptr = &game.script()->focusMele();
opt = WorldObjects::NoDeath;
break;
case WeaponState::Bow:
case WeaponState::CBow:
fptr = &game.script()->focusRange();
opt = WorldObjects::NoDeath;
break;
case WeaponState::Mage:{
fptr = &game.script()->focusMage();
int32_t id = player()->inventory().activeWeapon()->spellId();
auto& spl = script().getSpell(id);
coll = TargetCollect(spl.targetCollectAlgo);
opt = WorldObjects::NoDeath;
break;
}
case WeaponState::NoWeapon:
fptr = &game.script()->focusNorm();
break;
}
auto& policy = *fptr;
WorldObjects::SearchOpt optNpc {policy.npc_range1, policy.npc_range2, policy.npc_azi, coll, opt};
WorldObjects::SearchOpt optMob {policy.mob_range1, policy.mob_range2, policy.mob_azi, coll };
WorldObjects::SearchOpt optItm {policy.item_range1, policy.item_range2, policy.item_azi, coll };
auto n = policy.npc_prio <0 ? nullptr : wobj.findNpc (pl,def.npc, v,w,h, optNpc);
auto inter = policy.mob_prio <0 ? nullptr : wobj.findInteractive(pl,def.interactive,v,w,h, optMob);
auto it = policy.item_prio<0 ? nullptr : wobj.findItem (pl,def.item, v,w,h, optItm);
if(policy.npc_prio>=policy.item_prio &&
policy.npc_prio>=policy.mob_prio) {
if(n)
return Focus(*n);
if(policy.item_prio>=policy.mob_prio && it)
return Focus(*it);
return inter ? Focus(*inter) : Focus();
}
if(policy.mob_prio>=policy.item_prio &&
policy.mob_prio>=policy.npc_prio) {
if(inter)
return Focus(*inter);
if(policy.npc_prio>=policy.item_prio && n)
return Focus(*n);
return it ? Focus(*it) : Focus();
}
if(policy.item_prio>=policy.mob_prio &&
policy.item_prio>=policy.npc_prio) {
if(it)
return Focus(*it);
if(policy.npc_prio>=policy.mob_prio && n)
return Focus(*n);
return inter ? Focus(*inter) : Focus();
}
return Focus();
}
Focus World::findFocus(const Focus &def, const Tempest::Matrix4x4 &mvp, int w, int h) {
if(npcPlayer==nullptr)
return Focus();
return findFocus(*npcPlayer,def,mvp,w,h);
}
Interactive *World::aviableMob(const Npc &pl, const std::string &name) {
return wobj.aviableMob(pl,name);
}
void World::triggerEvent(const TriggerEvent &e) {
wobj.triggerEvent(e);
}
void World::changeWorld(const std::string& world, const std::string& wayPoint) {
game.changeWorld(world,wayPoint);
}
void World::marchInteractives(Tempest::Painter &p,const Tempest::Matrix4x4& mvp,int w,int h) const {
wobj.marchInteractives(p,mvp,w,h);
}
void World::marchPoints(Painter &p, const Matrix4x4 &mvp, int w, int h) const {
wmatrix->marchPoints(p,mvp,w,h);
}
AiOuputPipe *World::openDlgOuput(Npc &player, Npc &npc) {
return game.openDlgOuput(player,npc);
}
void World::aiOutputSound(Npc &player, const std::string &msg) {
wsound.aiOutput(player.position(),msg);
}
bool World::aiIsDlgFinished() {
return game.aiIsDlgFinished();
}
void World::printScreen(const char *msg, int x, int y, int time, const Font &font) {
game.printScreen(msg,x,y,time,font);
}
void World::print(const char *msg) {
game.print(msg);
}
Npc *World::addNpc(const char *name, const char *at) {
size_t id = script().getSymbolIndex(name);
if(id==size_t(-1))
return nullptr;
return wobj.addNpc(id,at);
}
Npc *World::addNpc(size_t npcInstance, const char *at) {
return wobj.addNpc(npcInstance,at);
}
Item *World::addItem(size_t itemInstance, const char *at) {
return wobj.addItem(itemInstance,at);
}
Item *World::takeItem(Item &it) {
return wobj.takeItem(it);
}
void World::removeItem(Item& it) {
wobj.removeItem(it);
}
size_t World::hasItems(const std::string &tag, size_t itemCls) {
return wobj.hasItems(tag,itemCls);
}
Bullet& World::shootBullet(size_t itmId, float x, float y, float z, float dx, float dy, float dz) {
return wobj.shootBullet(itmId,x,y,z,dx,dy,dz);
}
void World::sendPassivePerc(Npc &self, Npc &other, Npc &victum, int32_t perc) {
wobj.sendPassivePerc(self,other,victum,perc);
}
void World::sendPassivePerc(Npc &self, Npc &other, Npc &victum, Item &item, int32_t perc) {
wobj.sendPassivePerc(self,other,victum,item,perc);
}
void World::emitWeaponsSound(Npc &self, Npc &other) {
/*
WO - Wood
ME - Metal
ST - Stone
FL - Flesh
WA - Water
EA - Earth
SA - Sand
UD - Undefined
*/
// ItemMaterial
static std::initializer_list<const char*> mat={
"WO",
"ST",
"ME",
"FL", //"LE", //MAT_LEATHER,
"SA" //MAT_CLAY,
"ST", //MAT_GLAS,
};
auto p0 = self.position();
auto p1 = other.position();
const char* selfMt="";
const char* othMt ="FL";
if(self.isMonster()) // CS_AM?
selfMt = "JA"; else //Jaws
selfMt = "FI"; //Fist
if(auto a = self.inventory().activeWeapon()){
int32_t m = a->handle()->material;
if(m==ItemMaterial::MAT_WOOD)
selfMt = "WO"; else
selfMt = "ME";
}
if(auto a = other.currentArmour()){
int32_t m = a->handle()->material;
if(0<=m && size_t(m)<mat.size())
othMt = *(mat.begin()+m);
}
char buf[128]={};
if(self.isMonster() || self.inventory().activeWeapon()==nullptr)
std::snprintf(buf,sizeof(buf),"CS_MAM_%s_%s",selfMt,othMt); else
std::snprintf(buf,sizeof(buf),"CS_IAM_%s_%s",selfMt,othMt);
wsound.emitSound(buf, 0.5f*(p0[0]+p1[0]), 0.5f*(p0[1]+p1[1]), 0.5f*(p0[2]+p1[2]),2500.f,nullptr);
}
void World::emitLandHitSound(float x,float y,float z,uint8_t m0, uint8_t m1) {
// ItemMaterial
static const char* mat[]={
"WO",
"ST",
"ME",
"FL", //"LE", //MAT_LEATHER,
"SA" //MAT_CLAY,
"ST", //MAT_GLAS,
};
const char *sm0 = "ME";
const char *sm1 = "ME";
sm0 = mat[m0];
sm1 = mat[m1];
char buf[128]={};
std::snprintf(buf,sizeof(buf),"CS_IHL_%s_%s",sm0,sm1);
wsound.emitSound(buf, x,y,z,2500.f,nullptr);
}
void World::emitBlockSound(Npc &self, Npc &other) {
// ItemMaterial
auto p0 = self.position();
auto p1 = other.position();
const char* selfMt="ME";
const char* othMt ="ME";
if(self.isMonster())
selfMt = "JA"; else //Jaws
selfMt = "FI"; //Fist
if(auto a = self.inventory().activeWeapon()){
int32_t m = a->handle()->material;
if(m==ItemMaterial::MAT_WOOD)
selfMt = "WO"; else
selfMt = "ME";
}
if(auto a = other.inventory().activeWeapon()){
int32_t m = a->handle()->material;
if(m==ItemMaterial::MAT_WOOD)
selfMt = "WO"; else
selfMt = "ME";
}
char buf[128]={};
std::snprintf(buf,sizeof(buf),"CS_IAI_%s_%s",selfMt,othMt);
wsound.emitSound(buf, 0.5f*(p0[0]+p1[0]), 0.5f*(p0[1]+p1[1]), 0.5f*(p0[2]+p1[2]),2500.f,nullptr);
}
bool World::isInListenerRange(const std::array<float,3> &pos) const {
return wsound.isInListenerRange(pos);
}
void World::emitDlgSound(const char* s, float x, float y, float z, float range, uint64_t& timeLen) {
wsound.emitDlgSound(s,x,y,z,range,timeLen);
}
void World::emitSoundEffect(const char *s, float x, float y, float z, float range, GSoundEffect* slot) {
wsound.emitSound(s,x,y,z,range,slot);
}
void World::emitSoundRaw(const char *s, float x, float y, float z, float range, GSoundEffect *slot) {
wsound.emitSoundRaw(s,x,y,z,range,slot);
}
void World::takeSoundSlot(GSoundEffect &&eff) {
wsound.takeSoundSlot(std::move(eff));
}
void World::tickSlot(GSoundEffect &slot) {
wsound.tickSlot(slot);
}
const WayPoint *World::findPoint(const char *name) const {
return wmatrix->findPoint(name);
}
const WayPoint* World::findWayPoint(const std::array<float,3> &pos) const {
return findWayPoint(pos[0],pos[1],pos[2]);
}
const WayPoint* World::findWayPoint(float x, float y, float z) const {
return wmatrix->findWayPoint(x,y,z);
}
const WayPoint *World::findFreePoint(const Npc &npc, const char *name) const {
if(auto p = npc.currentWayPoint()){
if(p->isFreePoint() && p->checkName(name)) {
return p;
}
}
return findFreePoint(npc.position(),name);
}
const WayPoint *World::findFreePoint(const std::array<float,3> &pos,const char* name) const {
return findFreePoint(pos[0],pos[1],pos[2],name);
}
const WayPoint *World::findFreePoint(float x, float y, float z, const char *name) const {
return wmatrix->findFreePoint(x,y,z,name);
}
const WayPoint *World::findNextFreePoint(const Npc &n, const char *name) const {
auto pos = n.position();
return wmatrix->findNextFreePoint(pos[0],pos[1],pos[2],name,n.currentWayPoint());
}
const WayPoint *World::findNextPoint(const WayPoint &pos) const {
return wmatrix->findNextPoint(pos.x,pos.y,pos.z);
}
void World::detectNpcNear(std::function<void (Npc &)> f) {
wobj.detectNpcNear(f);
}
void World::detectNpc(const std::array<float,3> p, const float r, std::function<void (Npc &)> f) {
wobj.detectNpc(p[0],p[1],p[2],r,f);
}
void World::detectNpc(const float x, const float y, const float z, const float r, std::function<void(Npc&)> f) {
wobj.detectNpc(x,y,z,r,f);
}
WayPath World::wayTo(const Npc &pos, const WayPoint &end) const {
auto p = pos.position();
auto point = pos.currentWayPoint();
if(point && !point->isFreePoint() && MoveAlgo::isClose(pos.position(),*point)){
return wmatrix->wayTo(*point,end);
}
return wmatrix->wayTo(p[0],p[1],p[2],end);
}
WayPath World::wayTo(float npcX, float npcY, float npcZ, const WayPoint &end) const {
return wmatrix->wayTo(npcX,npcY,npcZ,end);
}
GameScript &World::script() const {
return *game.script();
}
void World::assignRoomToGuild(const std::string &r, int32_t guildId) {
std::string room = r;
for(auto& i:room)
i = char(std::toupper(i));
if(auto rx=portalAt(room)){
rx->guild=guildId;
return;
}
Log::d("room not found: ",room);
}
int32_t World::guildOfRoom(const std::array<float,3> &pos) {
const std::string& tg = roomAt(pos);
if(auto room=portalAt(tg)) {
if(room->guild==GIL_PUBLIC) //FIXME: proper portal implementation
return room->guild;
}
return GIL_NONE;
}
void World::loadVob(ZenLoad::zCVobData &vob,bool startup) {
for(auto& i:vob.childVobs)
loadVob(i,startup);
vob.childVobs.clear(); // because of move
if(vob.vobType==ZenLoad::zCVobData::VT_zCVob) {
addStatic(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_oCMOB) {
// Irdotar bow-triggers
// focusOverride=true
// Graves/Pointers
// see focusName
// Tempest::Log::d("unexpected vob class ",vob.objectClass);
if(vob.oCMOB.focusName.size()>0)
addInteractive(vob); else
addStatic(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_oCMobFire){
addStatic(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_oCMobBed ||
vob.vobType==ZenLoad::zCVobData::VT_oCMobDoor ||
vob.vobType==ZenLoad::zCVobData::VT_oCMobInter ||
vob.vobType==ZenLoad::zCVobData::VT_oCMobContainer ||
vob.vobType==ZenLoad::zCVobData::VT_oCMobSwitch){
addInteractive(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCVobLevelCompo){
return;
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCMover){
wobj.addTrigger(std::move(vob));
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCCodeMaster ||
vob.vobType==ZenLoad::zCVobData::VT_zCTrigger ||
vob.vobType==ZenLoad::zCVobData::VT_zCTriggerList ||
vob.vobType==ZenLoad::zCVobData::VT_zCTriggerScript ||
vob.vobType==ZenLoad::zCVobData::VT_oCTriggerWorldStart ||
vob.vobType==ZenLoad::zCVobData::VT_oCTriggerChangeLevel){
wobj.addTrigger(std::move(vob));
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCMessageFilter) {
wobj.addTrigger(std::move(vob));
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCVobStartpoint) {
float dx = vob.rotationMatrix.v[2].x;
float dy = vob.rotationMatrix.v[2].y;
float dz = vob.rotationMatrix.v[2].z;
wmatrix->addStartPoint(vob.position.x,vob.position.y,vob.position.z,dx,dy,dz,vob.vobName.c_str());
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCVobSpot) {
float dx = vob.rotationMatrix.v[2].x;
float dy = vob.rotationMatrix.v[2].y;
float dz = vob.rotationMatrix.v[2].z;
wmatrix->addFreePoint(vob.position.x,vob.position.y,vob.position.z,dx,dy,dz,vob.vobName.c_str());
}
else if(vob.vobType==ZenLoad::zCVobData::VT_oCItem) {
if(startup)
addItem(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_zCVobSound ||
vob.vobType==ZenLoad::zCVobData::VT_zCVobSoundDaytime) {
wsound.addSound(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_oCZoneMusic) {
wsound.addZone(vob);
}
else if(vob.vobType==ZenLoad::zCVobData::VT_oCZoneMusicDefault) {
wsound.setDefaultZone(vob);
}
else if(vob.objectClass=="zCVobAnimate:zCVob" || // ork flags
vob.objectClass=="zCPFXControler:zCVob"){
addStatic(vob); //TODO: morph animation
}
else if(vob.objectClass=="oCTouchDamage:zCTouchDamage:zCVob" ||
vob.objectClass=="oCMobLadder:oCMobInter:oCMOB:zCVob"){
// NOT IMPLEMENTED
}
else if(vob.objectClass=="zCVobLight:zCVob" ||
vob.objectClass=="zCVobLensFlare:zCVob" ||
vob.objectClass=="zCZoneVobFarPlane:zCVob" ||
vob.objectClass=="zCZoneVobFarPlaneDefault:zCZoneVobFarPlane:zCVob" ||
vob.objectClass=="zCZoneZFog:zCVob" ||
vob.objectClass=="zCZoneZFogDefault:zCZoneZFog:zCVob") {
// WONT-IMPLEMENT
}
else {
static std::unordered_set<std::string> cls;
if(cls.find(vob.objectClass)==cls.end()){
cls.insert(vob.objectClass);
Tempest::Log::d("unknown vob class ",vob.objectClass);
}
}
}
void World::addStatic(const ZenLoad::zCVobData &vob) {
wview->addStatic(vob);
}
void World::addInteractive(const ZenLoad::zCVobData &vob) {
wobj.addInteractive(vob);
}
void World::addItem(const ZenLoad::zCVobData &vob) {
wobj.addItem(vob);
}
|
.byte $01 ; Unknown purpose
.byte OBJ_BUZZYBEATLE, $0A, $17
.byte OBJ_PATOOIE, $10, $16
.byte OBJ_GREENPIRANHA, $2C, $12
.byte OBJ_PARAGOOMBA, $3E, $10
.byte OBJ_PARAGOOMBAWITHMICROS, $40, $10
.byte OBJ_PARAGOOMBA, $42, $10
.byte OBJ_PARAGOOMBAWITHMICROS, $44, $10
.byte OBJ_PARAGOOMBA, $46, $10
.byte OBJ_PARAGOOMBAWITHMICROS, $50, $10
.byte OBJ_PARAGOOMBA, $55, $16
.byte OBJ_PARAGOOMBAWITHMICROS, $5C, $16
.byte OBJ_PARAGOOMBA, $5D, $16
.byte OBJ_PARAGOOMBAWITHMICROS, $5E, $16
.byte OBJ_PARAGOOMBA, $5F, $16
.byte OBJ_PARAGOOMBAWITHMICROS, $60, $16
.byte OBJ_ENDLEVELCARD, $68, $15
.byte $FF ; Terminator
|
; A022341: Odd Fibbinary numbers; also 4*Fibbinary(n) + 1.
; Submitted by Christian Krause
; 1,5,9,17,21,33,37,41,65,69,73,81,85,129,133,137,145,149,161,165,169,257,261,265,273,277,289,293,297,321,325,329,337,341,513,517,521,529,533,545,549,553,577,581,585,593,597,641,645,649,657,661,673,677,681,1025,1029,1033,1041,1045,1057,1061,1065,1089,1093,1097,1105,1109,1153,1157,1161,1169,1173,1185,1189,1193,1281,1285,1289,1297,1301,1313,1317,1321,1345,1349,1353,1361,1365,2049,2053,2057,2065,2069,2081,2085,2089,2113,2117,2121
seq $0,22340 ; Even Fibbinary numbers (A003714); also 2*Fibbinary(n).
mul $0,2
add $0,1
|
; PPU registers
; http://wiki.nesdev.com/w/index.php/PPU_registers
PPUCTRL = $2000
PPUMASK = $2001
PPUSTATUS = $2002
OAMADDR = $2003
OAMDATA = $2004
PPUSCROLL = $2005
PPUADDR = $2006
PPUDATA = $2007
OAMDMA = $4014
; APU registers
; http://wiki.nesdev.com/w/index.php/APU
APU_SQUARE1_ENVELOPE = $4000
APU_SQUARE1_PERIOD = $4001
APU_SQUARE1_TIMER_LOW = $4002
APU_SQUARE1_LENGTH_CNT = $4003
APU_TRIANGLE_LINEAR_CNT = $4008
APU_TRIANGLE_TIMER_LOW = $400a
APU_TRIANGLE_LENGTH_CNT = $400b
APU_NOISE_ENVELOPE = $400c
APU_NOISE_PERIOD = $400e
APU_NOISE_LENGTH_CNT = $400f
APU_DMC_FLAGS = $4010
APU_STATUS = $4015
APU_FRAMECNT = $4017
; Controller ports
CONTROLLER_A = $4016
CONTROLLER_B = $4017
|
; A197916: Related to the periodic sequence A171654.
; 0,1,6,7,2,3,8,9,4,5,10,11,6,7,12,13,8,9,14,15,10,11,16,17,12,13,18,19,14,15,20,21,16,17,22,23,18,19,24,25,20,21,26,27,22,23,28,29,24,25,30,31,26,27,32,33,28,29,34,35,30,31,36,37,32,33,38,39
mov $1,$0
mov $2,$0
add $2,4
mov $3,$0
add $3,4
lpb $0
sub $3,$1
add $3,$0
sub $0,2
mov $1,$3
mov $3,$2
lpe
|
/****************************************************************************
*
* Copyright (c) 2012-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mavlink_receiver.cpp
* MAVLink protocol message receive and dispatch
*
* @author Lorenz Meier <lorenz@px4.io>
* @author Anton Babushkin <anton@px4.io>
* @author Thomas Gubler <thomas@px4.io>
*/
#include <airspeed/airspeed.h>
#include <commander/px4_custom_mode.h>
#include <conversion/rotation.h>
#include <drivers/drv_rc_input.h>
#include <ecl/geo/geo.h>
#include <systemlib/px4_macros.h>
#include <math.h>
#include <poll.h>
#ifdef CONFIG_NET
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#ifndef __PX4_POSIX
#include <termios.h>
#endif
#include "mavlink_command_sender.h"
#include "mavlink_main.h"
#include "mavlink_receiver.h"
#include <lib/drivers/device/Device.hpp> // For DeviceId union
#ifdef CONFIG_NET
#define MAVLINK_RECEIVER_NET_ADDED_STACK 1360
#else
#define MAVLINK_RECEIVER_NET_ADDED_STACK 0
#endif
using matrix::wrap_2pi;
MavlinkReceiver::~MavlinkReceiver()
{
delete _tune_publisher;
delete _px4_accel;
delete _px4_baro;
delete _px4_gyro;
delete _px4_mag;
}
MavlinkReceiver::MavlinkReceiver(Mavlink *parent) :
ModuleParams(nullptr),
_mavlink(parent),
_mavlink_ftp(parent),
_mavlink_log_handler(parent),
_mission_manager(parent),
_parameters_manager(parent),
_mavlink_timesync(parent)
{
}
void
MavlinkReceiver::acknowledge(uint8_t sysid, uint8_t compid, uint16_t command, uint8_t result)
{
vehicle_command_ack_s command_ack{};
command_ack.timestamp = hrt_absolute_time();
command_ack.command = command;
command_ack.result = result;
command_ack.target_system = sysid;
command_ack.target_component = compid;
_cmd_ack_pub.publish(command_ack);
}
void
MavlinkReceiver::handle_message(mavlink_message_t *msg)
{
switch (msg->msgid) {
case MAVLINK_MSG_ID_COMMAND_LONG:
handle_message_command_long(msg);
break;
case MAVLINK_MSG_ID_COMMAND_INT:
handle_message_command_int(msg);
break;
case MAVLINK_MSG_ID_COMMAND_ACK:
handle_message_command_ack(msg);
break;
case MAVLINK_MSG_ID_OPTICAL_FLOW_RAD:
handle_message_optical_flow_rad(msg);
break;
case MAVLINK_MSG_ID_PING:
handle_message_ping(msg);
break;
case MAVLINK_MSG_ID_SET_MODE:
handle_message_set_mode(msg);
break;
case MAVLINK_MSG_ID_ATT_POS_MOCAP:
handle_message_att_pos_mocap(msg);
break;
case MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED:
handle_message_set_position_target_local_ned(msg);
break;
case MAVLINK_MSG_ID_SET_POSITION_TARGET_GLOBAL_INT:
handle_message_set_position_target_global_int(msg);
break;
case MAVLINK_MSG_ID_SET_ATTITUDE_TARGET:
handle_message_set_attitude_target(msg);
break;
case MAVLINK_MSG_ID_SET_ACTUATOR_CONTROL_TARGET:
handle_message_set_actuator_control_target(msg);
break;
case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE:
handle_message_vision_position_estimate(msg);
break;
case MAVLINK_MSG_ID_ODOMETRY:
handle_message_odometry(msg);
break;
case MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN:
handle_message_set_gps_global_origin(msg);
break;
case MAVLINK_MSG_ID_RADIO_STATUS:
handle_message_radio_status(msg);
break;
case MAVLINK_MSG_ID_MANUAL_CONTROL:
handle_message_manual_control(msg);
break;
case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE:
handle_message_rc_channels_override(msg);
break;
case MAVLINK_MSG_ID_HEARTBEAT:
handle_message_heartbeat(msg);
break;
case MAVLINK_MSG_ID_DISTANCE_SENSOR:
handle_message_distance_sensor(msg);
break;
case MAVLINK_MSG_ID_FOLLOW_TARGET:
handle_message_follow_target(msg);
break;
case MAVLINK_MSG_ID_LANDING_TARGET:
handle_message_landing_target(msg);
break;
case MAVLINK_MSG_ID_CELLULAR_STATUS:
handle_message_cellular_status(msg);
break;
case MAVLINK_MSG_ID_ADSB_VEHICLE:
handle_message_adsb_vehicle(msg);
break;
case MAVLINK_MSG_ID_UTM_GLOBAL_POSITION:
handle_message_utm_global_position(msg);
break;
case MAVLINK_MSG_ID_COLLISION:
handle_message_collision(msg);
break;
case MAVLINK_MSG_ID_GPS_RTCM_DATA:
handle_message_gps_rtcm_data(msg);
break;
case MAVLINK_MSG_ID_BATTERY_STATUS:
handle_message_battery_status(msg);
break;
case MAVLINK_MSG_ID_SERIAL_CONTROL:
handle_message_serial_control(msg);
break;
case MAVLINK_MSG_ID_LOGGING_ACK:
handle_message_logging_ack(msg);
break;
case MAVLINK_MSG_ID_PLAY_TUNE:
handle_message_play_tune(msg);
break;
case MAVLINK_MSG_ID_PLAY_TUNE_V2:
handle_message_play_tune_v2(msg);
break;
case MAVLINK_MSG_ID_OBSTACLE_DISTANCE:
handle_message_obstacle_distance(msg);
break;
case MAVLINK_MSG_ID_TRAJECTORY_REPRESENTATION_BEZIER:
handle_message_trajectory_representation_bezier(msg);
break;
case MAVLINK_MSG_ID_TRAJECTORY_REPRESENTATION_WAYPOINTS:
handle_message_trajectory_representation_waypoints(msg);
break;
case MAVLINK_MSG_ID_ONBOARD_COMPUTER_STATUS:
handle_message_onboard_computer_status(msg);
break;
case MAVLINK_MSG_ID_GENERATOR_STATUS:
handle_message_generator_status(msg);
break;
case MAVLINK_MSG_ID_STATUSTEXT:
handle_message_statustext(msg);
break;
#if !defined(CONSTRAINED_FLASH)
case MAVLINK_MSG_ID_NAMED_VALUE_FLOAT:
handle_message_named_value_float(msg);
break;
case MAVLINK_MSG_ID_DEBUG:
handle_message_debug(msg);
break;
case MAVLINK_MSG_ID_DEBUG_VECT:
handle_message_debug_vect(msg);
break;
case MAVLINK_MSG_ID_DEBUG_FLOAT_ARRAY:
handle_message_debug_float_array(msg);
break;
#endif // !CONSTRAINED_FLASH
default:
break;
}
/*
* Only decode hil messages in HIL mode.
*
* The HIL mode is enabled by the HIL bit flag
* in the system mode. Either send a set mode
* COMMAND_LONG message or a SET_MODE message
*
* Accept HIL GPS messages if use_hil_gps flag is true.
* This allows to provide fake gps measurements to the system.
*/
if (_mavlink->get_hil_enabled()) {
switch (msg->msgid) {
case MAVLINK_MSG_ID_HIL_SENSOR:
handle_message_hil_sensor(msg);
break;
case MAVLINK_MSG_ID_HIL_STATE_QUATERNION:
handle_message_hil_state_quaternion(msg);
break;
case MAVLINK_MSG_ID_HIL_OPTICAL_FLOW:
handle_message_hil_optical_flow(msg);
break;
default:
break;
}
}
if (_mavlink->get_hil_enabled() || (_mavlink->get_use_hil_gps() && msg->sysid == mavlink_system.sysid)) {
switch (msg->msgid) {
case MAVLINK_MSG_ID_HIL_GPS:
handle_message_hil_gps(msg);
break;
default:
break;
}
}
/* If we've received a valid message, mark the flag indicating so.
This is used in the '-w' command-line flag. */
_mavlink->set_has_received_messages(true);
}
bool
MavlinkReceiver::evaluate_target_ok(int command, int target_system, int target_component)
{
/* evaluate if this system should accept this command */
bool target_ok = false;
switch (command) {
case MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES:
case MAV_CMD_REQUEST_PROTOCOL_VERSION:
/* broadcast and ignore component */
target_ok = (target_system == 0) || (target_system == mavlink_system.sysid);
break;
default:
target_ok = (target_system == mavlink_system.sysid) && ((target_component == mavlink_system.compid)
|| (target_component == MAV_COMP_ID_ALL));
break;
}
return target_ok;
}
void
MavlinkReceiver::handle_message_command_long(mavlink_message_t *msg)
{
/* command */
mavlink_command_long_t cmd_mavlink;
mavlink_msg_command_long_decode(msg, &cmd_mavlink);
vehicle_command_s vcmd{};
vcmd.timestamp = hrt_absolute_time();
/* Copy the content of mavlink_command_long_t cmd_mavlink into command_t cmd */
vcmd.param1 = cmd_mavlink.param1;
vcmd.param2 = cmd_mavlink.param2;
vcmd.param3 = cmd_mavlink.param3;
vcmd.param4 = cmd_mavlink.param4;
vcmd.param5 = (double)cmd_mavlink.param5;
vcmd.param6 = (double)cmd_mavlink.param6;
vcmd.param7 = cmd_mavlink.param7;
vcmd.command = cmd_mavlink.command;
vcmd.target_system = cmd_mavlink.target_system;
vcmd.target_component = cmd_mavlink.target_component;
vcmd.source_system = msg->sysid;
vcmd.source_component = msg->compid;
vcmd.confirmation = cmd_mavlink.confirmation;
vcmd.from_external = true;
handle_message_command_both(msg, cmd_mavlink, vcmd);
}
void
MavlinkReceiver::handle_message_command_int(mavlink_message_t *msg)
{
/* command */
mavlink_command_int_t cmd_mavlink;
mavlink_msg_command_int_decode(msg, &cmd_mavlink);
vehicle_command_s vcmd{};
vcmd.timestamp = hrt_absolute_time();
/* Copy the content of mavlink_command_int_t cmd_mavlink into command_t cmd */
vcmd.param1 = cmd_mavlink.param1;
vcmd.param2 = cmd_mavlink.param2;
vcmd.param3 = cmd_mavlink.param3;
vcmd.param4 = cmd_mavlink.param4;
vcmd.param5 = ((double)cmd_mavlink.x) / 1e7;
vcmd.param6 = ((double)cmd_mavlink.y) / 1e7;
vcmd.param7 = cmd_mavlink.z;
vcmd.command = cmd_mavlink.command;
vcmd.target_system = cmd_mavlink.target_system;
vcmd.target_component = cmd_mavlink.target_component;
vcmd.source_system = msg->sysid;
vcmd.source_component = msg->compid;
vcmd.confirmation = false;
vcmd.from_external = true;
handle_message_command_both(msg, cmd_mavlink, vcmd);
}
template <class T>
void MavlinkReceiver::handle_message_command_both(mavlink_message_t *msg, const T &cmd_mavlink,
const vehicle_command_s &vehicle_command)
{
bool target_ok = evaluate_target_ok(cmd_mavlink.command, cmd_mavlink.target_system, cmd_mavlink.target_component);
bool send_ack = true;
uint8_t result = vehicle_command_ack_s::VEHICLE_RESULT_ACCEPTED;
if (!target_ok) {
acknowledge(msg->sysid, msg->compid, cmd_mavlink.command, vehicle_command_ack_s::VEHICLE_RESULT_FAILED);
return;
}
// First we handle legacy support requests which were used before we had
// the generic MAV_CMD_REQUEST_MESSAGE.
if (cmd_mavlink.command == MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES) {
result = handle_request_message_command(MAVLINK_MSG_ID_AUTOPILOT_VERSION);
} else if (cmd_mavlink.command == MAV_CMD_REQUEST_PROTOCOL_VERSION) {
result = handle_request_message_command(MAVLINK_MSG_ID_PROTOCOL_VERSION);
} else if (cmd_mavlink.command == MAV_CMD_GET_HOME_POSITION) {
result = handle_request_message_command(MAVLINK_MSG_ID_HOME_POSITION);
} else if (cmd_mavlink.command == MAV_CMD_REQUEST_FLIGHT_INFORMATION) {
result = handle_request_message_command(MAVLINK_MSG_ID_FLIGHT_INFORMATION);
} else if (cmd_mavlink.command == MAV_CMD_REQUEST_STORAGE_INFORMATION) {
result = handle_request_message_command(MAVLINK_MSG_ID_STORAGE_INFORMATION);
} else if (cmd_mavlink.command == MAV_CMD_SET_MESSAGE_INTERVAL) {
if (set_message_interval((int)roundf(cmd_mavlink.param1), cmd_mavlink.param2, cmd_mavlink.param3)) {
result = vehicle_command_ack_s::VEHICLE_RESULT_FAILED;
}
} else if (cmd_mavlink.command == MAV_CMD_GET_MESSAGE_INTERVAL) {
get_message_interval((int)roundf(cmd_mavlink.param1));
} else if (cmd_mavlink.command == MAV_CMD_REQUEST_MESSAGE) {
uint16_t message_id = (uint16_t)roundf(vehicle_command.param1);
result = handle_request_message_command(message_id,
vehicle_command.param2, vehicle_command.param3, vehicle_command.param4,
vehicle_command.param5, vehicle_command.param6, vehicle_command.param7);
} else if (cmd_mavlink.command == MAV_CMD_SET_CAMERA_ZOOM) {
struct actuator_controls_s actuator_controls = {};
actuator_controls.timestamp = hrt_absolute_time();
for (size_t i = 0; i < 8; i++) {
actuator_controls.control[i] = NAN;
}
switch ((int)(cmd_mavlink.param1 + 0.5f)) {
case vehicle_command_s::VEHICLE_CAMERA_ZOOM_TYPE_RANGE:
actuator_controls.control[actuator_controls_s::INDEX_CAMERA_ZOOM] = cmd_mavlink.param2 / 50.0f - 1.0f;
break;
case vehicle_command_s::VEHICLE_CAMERA_ZOOM_TYPE_STEP:
case vehicle_command_s::VEHICLE_CAMERA_ZOOM_TYPE_CONTINUOUS:
case vehicle_command_s::VEHICLE_CAMERA_ZOOM_TYPE_FOCAL_LENGTH:
default:
send_ack = false;
}
_actuator_controls_pubs[actuator_controls_s::GROUP_INDEX_GIMBAL].publish(actuator_controls);
} else if (cmd_mavlink.command == MAV_CMD_INJECT_FAILURE) {
if (_mavlink->failure_injection_enabled()) {
_cmd_pub.publish(vehicle_command);
send_ack = false;
} else {
result = vehicle_command_ack_s::VEHICLE_RESULT_DENIED;
send_ack = true;
}
} else {
send_ack = false;
if (msg->sysid == mavlink_system.sysid && msg->compid == mavlink_system.compid) {
PX4_WARN("ignoring CMD with same SYS/COMP (%d/%d) ID", mavlink_system.sysid, mavlink_system.compid);
return;
}
if (cmd_mavlink.command == MAV_CMD_LOGGING_START) {
// check that we have enough bandwidth available: this is given by the configured logger topics
// and rates. The 5000 is somewhat arbitrary, but makes sure that we cannot enable log streaming
// on a radio link
if (_mavlink->get_data_rate() < 5000) {
send_ack = true;
result = vehicle_command_ack_s::VEHICLE_RESULT_DENIED;
_mavlink->send_statustext_critical("Not enough bandwidth to enable log streaming");
} else {
// we already instanciate the streaming object, because at this point we know on which
// mavlink channel streaming was requested. But in fact it's possible that the logger is
// not even running. The main mavlink thread takes care of this by waiting for an ack
// from the logger.
_mavlink->try_start_ulog_streaming(msg->sysid, msg->compid);
}
} else if (cmd_mavlink.command == MAV_CMD_LOGGING_STOP) {
_mavlink->request_stop_ulog_streaming();
} else if (cmd_mavlink.command == MAV_CMD_DO_CHANGE_SPEED) {
vehicle_control_mode_s control_mode{};
_control_mode_sub.copy(&control_mode);
if (control_mode.flag_control_offboard_enabled) {
// Not differentiating between airspeed and groundspeed yet
set_offb_cruising_speed(cmd_mavlink.param2);
}
}
if (!send_ack) {
_cmd_pub.publish(vehicle_command);
}
}
if (send_ack) {
acknowledge(msg->sysid, msg->compid, cmd_mavlink.command, result);
}
}
uint8_t MavlinkReceiver::handle_request_message_command(uint16_t message_id, float param2, float param3, float param4,
float param5, float param6, float param7)
{
bool stream_found = false;
bool message_sent = false;
for (const auto &stream : _mavlink->get_streams()) {
if (stream->get_id() == message_id) {
stream_found = true;
message_sent = stream->request_message(param2, param3, param4, param5, param6, param7);
break;
}
}
if (!stream_found) {
// If we don't find the stream, we can configure it with rate 0 and then trigger it once.
const char *stream_name = get_stream_name(message_id);
if (stream_name != nullptr) {
_mavlink->configure_stream_threadsafe(stream_name, 0.0f);
// Now we try again to send it.
for (const auto &stream : _mavlink->get_streams()) {
if (stream->get_id() == message_id) {
message_sent = stream->request_message(param2, param3, param4, param5, param6, param7);
break;
}
}
}
}
return (message_sent ? vehicle_command_ack_s::VEHICLE_RESULT_ACCEPTED : vehicle_command_ack_s::VEHICLE_RESULT_DENIED);
}
void
MavlinkReceiver::handle_message_command_ack(mavlink_message_t *msg)
{
mavlink_command_ack_t ack;
mavlink_msg_command_ack_decode(msg, &ack);
MavlinkCommandSender::instance().handle_mavlink_command_ack(ack, msg->sysid, msg->compid, _mavlink->get_channel());
vehicle_command_ack_s command_ack{};
command_ack.timestamp = hrt_absolute_time();
command_ack.result_param2 = ack.result_param2;
command_ack.command = ack.command;
command_ack.result = ack.result;
command_ack.from_external = true;
command_ack.result_param1 = ack.progress;
command_ack.target_system = ack.target_system;
command_ack.target_component = ack.target_component;
_cmd_ack_pub.publish(command_ack);
// TODO: move it to the same place that sent the command
if (ack.result != MAV_RESULT_ACCEPTED && ack.result != MAV_RESULT_IN_PROGRESS) {
if (msg->compid == MAV_COMP_ID_CAMERA) {
PX4_WARN("Got unsuccessful result %d from camera", ack.result);
}
}
}
void
MavlinkReceiver::handle_message_optical_flow_rad(mavlink_message_t *msg)
{
/* optical flow */
mavlink_optical_flow_rad_t flow;
mavlink_msg_optical_flow_rad_decode(msg, &flow);
optical_flow_s f{};
f.timestamp = hrt_absolute_time();
f.time_since_last_sonar_update = flow.time_delta_distance_us;
f.integration_timespan = flow.integration_time_us;
f.pixel_flow_x_integral = flow.integrated_x;
f.pixel_flow_y_integral = flow.integrated_y;
f.gyro_x_rate_integral = flow.integrated_xgyro;
f.gyro_y_rate_integral = flow.integrated_ygyro;
f.gyro_z_rate_integral = flow.integrated_zgyro;
f.gyro_temperature = flow.temperature;
f.ground_distance_m = flow.distance;
f.quality = flow.quality;
f.sensor_id = flow.sensor_id;
f.max_flow_rate = _param_sens_flow_maxr.get();
f.min_ground_distance = _param_sens_flow_minhgt.get();
f.max_ground_distance = _param_sens_flow_maxhgt.get();
/* read flow sensor parameters */
const Rotation flow_rot = (Rotation)_param_sens_flow_rot.get();
/* rotate measurements according to parameter */
float zero_val = 0.0f;
rotate_3f(flow_rot, f.pixel_flow_x_integral, f.pixel_flow_y_integral, zero_val);
rotate_3f(flow_rot, f.gyro_x_rate_integral, f.gyro_y_rate_integral, f.gyro_z_rate_integral);
_flow_pub.publish(f);
/* Use distance value for distance sensor topic */
if (flow.distance > 0.0f) { // negative values signal invalid data
distance_sensor_s d{};
device::Device::DeviceId device_id;
device_id.devid_s.bus = device::Device::DeviceBusType::DeviceBusType_MAVLINK;
device_id.devid_s.devtype = DRV_DIST_DEVTYPE_MAVLINK;
device_id.devid_s.address = msg->sysid;
d.timestamp = f.timestamp;
d.min_distance = 0.3f;
d.max_distance = 5.0f;
d.current_distance = flow.distance; /* both are in m */
d.type = distance_sensor_s::MAV_DISTANCE_SENSOR_ULTRASOUND;
d.device_id = device_id.devid;
d.orientation = distance_sensor_s::ROTATION_DOWNWARD_FACING;
d.variance = 0.0;
_flow_distance_sensor_pub.publish(d);
}
}
void
MavlinkReceiver::handle_message_hil_optical_flow(mavlink_message_t *msg)
{
/* optical flow */
mavlink_hil_optical_flow_t flow;
mavlink_msg_hil_optical_flow_decode(msg, &flow);
optical_flow_s f{};
f.timestamp = hrt_absolute_time(); // XXX we rely on the system time for now and not flow.time_usec;
f.integration_timespan = flow.integration_time_us;
f.pixel_flow_x_integral = flow.integrated_x;
f.pixel_flow_y_integral = flow.integrated_y;
f.gyro_x_rate_integral = flow.integrated_xgyro;
f.gyro_y_rate_integral = flow.integrated_ygyro;
f.gyro_z_rate_integral = flow.integrated_zgyro;
f.time_since_last_sonar_update = flow.time_delta_distance_us;
f.ground_distance_m = flow.distance;
f.quality = flow.quality;
f.sensor_id = flow.sensor_id;
f.gyro_temperature = flow.temperature;
_flow_pub.publish(f);
/* Use distance value for distance sensor topic */
distance_sensor_s d{};
device::Device::DeviceId device_id;
device_id.devid_s.bus = device::Device::DeviceBusType::DeviceBusType_MAVLINK;
device_id.devid_s.devtype = DRV_DIST_DEVTYPE_MAVLINK;
device_id.devid_s.address = msg->sysid;
d.timestamp = hrt_absolute_time();
d.min_distance = 0.3f;
d.max_distance = 5.0f;
d.current_distance = flow.distance; /* both are in m */
d.type = distance_sensor_s::MAV_DISTANCE_SENSOR_LASER;
d.device_id = device_id.devid;
d.orientation = distance_sensor_s::ROTATION_DOWNWARD_FACING;
d.variance = 0.0;
_flow_distance_sensor_pub.publish(d);
}
void
MavlinkReceiver::handle_message_set_mode(mavlink_message_t *msg)
{
mavlink_set_mode_t new_mode;
mavlink_msg_set_mode_decode(msg, &new_mode);
union px4_custom_mode custom_mode;
custom_mode.data = new_mode.custom_mode;
vehicle_command_s vcmd{};
vcmd.timestamp = hrt_absolute_time();
/* copy the content of mavlink_command_long_t cmd_mavlink into command_t cmd */
vcmd.param1 = (float)new_mode.base_mode;
vcmd.param2 = (float)custom_mode.main_mode;
vcmd.param3 = (float)custom_mode.sub_mode;
vcmd.command = vehicle_command_s::VEHICLE_CMD_DO_SET_MODE;
vcmd.target_system = new_mode.target_system;
vcmd.target_component = MAV_COMP_ID_ALL;
vcmd.source_system = msg->sysid;
vcmd.source_component = msg->compid;
vcmd.confirmation = true;
vcmd.from_external = true;
_cmd_pub.publish(vcmd);
}
void
MavlinkReceiver::handle_message_distance_sensor(mavlink_message_t *msg)
{
mavlink_distance_sensor_t dist_sensor;
mavlink_msg_distance_sensor_decode(msg, &dist_sensor);
distance_sensor_s ds{};
device::Device::DeviceId device_id;
device_id.devid_s.bus = device::Device::DeviceBusType::DeviceBusType_MAVLINK;
device_id.devid_s.devtype = DRV_DIST_DEVTYPE_MAVLINK;
device_id.devid_s.address = dist_sensor.id;
ds.timestamp = hrt_absolute_time(); /* Use system time for now, don't trust sender to attach correct timestamp */
ds.min_distance = static_cast<float>(dist_sensor.min_distance) * 1e-2f; /* cm to m */
ds.max_distance = static_cast<float>(dist_sensor.max_distance) * 1e-2f; /* cm to m */
ds.current_distance = static_cast<float>(dist_sensor.current_distance) * 1e-2f; /* cm to m */
ds.variance = dist_sensor.covariance * 1e-4f; /* cm^2 to m^2 */
ds.h_fov = dist_sensor.horizontal_fov;
ds.v_fov = dist_sensor.vertical_fov;
ds.q[0] = dist_sensor.quaternion[0];
ds.q[1] = dist_sensor.quaternion[1];
ds.q[2] = dist_sensor.quaternion[2];
ds.q[3] = dist_sensor.quaternion[3];
ds.type = dist_sensor.type;
ds.device_id = device_id.devid;
ds.orientation = dist_sensor.orientation;
// MAVLink DISTANCE_SENSOR signal_quality value of 0 means unset/unknown
// quality value. Also it comes normalised between 1 and 100 while the uORB
// signal quality is normalised between 0 and 100.
ds.signal_quality = dist_sensor.signal_quality == 0 ? -1 : 100 * (dist_sensor.signal_quality - 1) / 99;
_distance_sensor_pub.publish(ds);
}
void
MavlinkReceiver::handle_message_att_pos_mocap(mavlink_message_t *msg)
{
mavlink_att_pos_mocap_t mocap;
mavlink_msg_att_pos_mocap_decode(msg, &mocap);
vehicle_odometry_s mocap_odom{};
mocap_odom.timestamp = hrt_absolute_time();
mocap_odom.timestamp_sample = _mavlink_timesync.sync_stamp(mocap.time_usec);
mocap_odom.x = mocap.x;
mocap_odom.y = mocap.y;
mocap_odom.z = mocap.z;
mocap_odom.q[0] = mocap.q[0];
mocap_odom.q[1] = mocap.q[1];
mocap_odom.q[2] = mocap.q[2];
mocap_odom.q[3] = mocap.q[3];
const size_t URT_SIZE = sizeof(mocap_odom.pose_covariance) / sizeof(mocap_odom.pose_covariance[0]);
static_assert(URT_SIZE == (sizeof(mocap.covariance) / sizeof(mocap.covariance[0])),
"Odometry Pose Covariance matrix URT array size mismatch");
for (size_t i = 0; i < URT_SIZE; i++) {
mocap_odom.pose_covariance[i] = mocap.covariance[i];
}
mocap_odom.velocity_frame = vehicle_odometry_s::LOCAL_FRAME_FRD;
mocap_odom.vx = NAN;
mocap_odom.vy = NAN;
mocap_odom.vz = NAN;
mocap_odom.rollspeed = NAN;
mocap_odom.pitchspeed = NAN;
mocap_odom.yawspeed = NAN;
mocap_odom.velocity_covariance[0] = NAN;
_mocap_odometry_pub.publish(mocap_odom);
}
void
MavlinkReceiver::handle_message_set_position_target_local_ned(mavlink_message_t *msg)
{
mavlink_set_position_target_local_ned_t set_position_target_local_ned;
mavlink_msg_set_position_target_local_ned_decode(msg, &set_position_target_local_ned);
const bool values_finite =
PX4_ISFINITE(set_position_target_local_ned.x) &&
PX4_ISFINITE(set_position_target_local_ned.y) &&
PX4_ISFINITE(set_position_target_local_ned.z) &&
PX4_ISFINITE(set_position_target_local_ned.vx) &&
PX4_ISFINITE(set_position_target_local_ned.vy) &&
PX4_ISFINITE(set_position_target_local_ned.vz) &&
PX4_ISFINITE(set_position_target_local_ned.afx) &&
PX4_ISFINITE(set_position_target_local_ned.afy) &&
PX4_ISFINITE(set_position_target_local_ned.afz) &&
PX4_ISFINITE(set_position_target_local_ned.yaw);
/* Only accept messages which are intended for this system */
if ((mavlink_system.sysid == set_position_target_local_ned.target_system ||
set_position_target_local_ned.target_system == 0) &&
(mavlink_system.compid == set_position_target_local_ned.target_component ||
set_position_target_local_ned.target_component == 0) &&
values_finite) {
offboard_control_mode_s offboard_control_mode{};
/* convert mavlink type (local, NED) to uORB offboard control struct */
offboard_control_mode.ignore_position = (bool)(set_position_target_local_ned.type_mask &
(POSITION_TARGET_TYPEMASK_X_IGNORE
| POSITION_TARGET_TYPEMASK_Y_IGNORE
| POSITION_TARGET_TYPEMASK_Z_IGNORE));
offboard_control_mode.ignore_alt_hold = (bool)(set_position_target_local_ned.type_mask &
POSITION_TARGET_TYPEMASK_Z_IGNORE);
offboard_control_mode.ignore_velocity = (bool)(set_position_target_local_ned.type_mask &
(POSITION_TARGET_TYPEMASK_VX_IGNORE
| POSITION_TARGET_TYPEMASK_VY_IGNORE
| POSITION_TARGET_TYPEMASK_VZ_IGNORE));
offboard_control_mode.ignore_acceleration_force = (bool)(set_position_target_local_ned.type_mask &
(POSITION_TARGET_TYPEMASK_AX_IGNORE
| POSITION_TARGET_TYPEMASK_AY_IGNORE
| POSITION_TARGET_TYPEMASK_AZ_IGNORE));
/* yaw ignore flag mapps to ignore_attitude */
offboard_control_mode.ignore_attitude = (bool)(set_position_target_local_ned.type_mask &
POSITION_TARGET_TYPEMASK_YAW_IGNORE);
offboard_control_mode.ignore_bodyrate_x = (bool)(set_position_target_local_ned.type_mask &
POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE);
offboard_control_mode.ignore_bodyrate_y = (bool)(set_position_target_local_ned.type_mask &
POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE);
offboard_control_mode.ignore_bodyrate_z = (bool)(set_position_target_local_ned.type_mask &
POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE);
/* yaw ignore flag mapps to ignore_attitude */
bool is_force_sp = (bool)(set_position_target_local_ned.type_mask & POSITION_TARGET_TYPEMASK_FORCE_SET);
bool is_takeoff_sp = (bool)(set_position_target_local_ned.type_mask & 0x1000);
bool is_land_sp = (bool)(set_position_target_local_ned.type_mask & 0x2000);
bool is_loiter_sp = (bool)(set_position_target_local_ned.type_mask & 0x3000);
bool is_idle_sp = (bool)(set_position_target_local_ned.type_mask & 0x4000);
bool is_gliding_sp = (bool)(set_position_target_local_ned.type_mask &
(POSITION_TARGET_TYPEMASK_Z_IGNORE
| POSITION_TARGET_TYPEMASK_VZ_IGNORE
| POSITION_TARGET_TYPEMASK_AZ_IGNORE));
offboard_control_mode.timestamp = hrt_absolute_time();
_offboard_control_mode_pub.publish(offboard_control_mode);
/* If we are in offboard control mode and offboard control loop through is enabled
* also publish the setpoint topic which is read by the controller */
if (_mavlink->get_forward_externalsp()) {
vehicle_control_mode_s control_mode{};
_control_mode_sub.copy(&control_mode);
if (control_mode.flag_control_offboard_enabled) {
if (is_force_sp && offboard_control_mode.ignore_position &&
offboard_control_mode.ignore_velocity) {
PX4_WARN("force setpoint not supported");
} else {
/* It's not a pure force setpoint: publish to setpoint triplet topic */
position_setpoint_triplet_s pos_sp_triplet{};
pos_sp_triplet.timestamp = hrt_absolute_time();
pos_sp_triplet.previous.valid = false;
pos_sp_triplet.next.valid = false;
pos_sp_triplet.current.valid = true;
/* Order of statements matters. Takeoff can override loiter.
* See https://github.com/mavlink/mavlink/pull/670 for a broader conversation. */
if (is_loiter_sp) {
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_LOITER;
} else if (is_takeoff_sp) {
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_TAKEOFF;
} else if (is_land_sp) {
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_LAND;
} else if (is_idle_sp) {
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_IDLE;
} else if (is_gliding_sp) {
pos_sp_triplet.current.cruising_throttle = 0.0f;
} else {
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_POSITION;
}
/* set the local pos values */
if (!offboard_control_mode.ignore_position) {
pos_sp_triplet.current.position_valid = true;
pos_sp_triplet.current.x = set_position_target_local_ned.x;
pos_sp_triplet.current.y = set_position_target_local_ned.y;
pos_sp_triplet.current.z = set_position_target_local_ned.z;
pos_sp_triplet.current.cruising_speed = get_offb_cruising_speed();
} else {
pos_sp_triplet.current.position_valid = false;
}
/* set the local vel values */
if (!offboard_control_mode.ignore_velocity) {
pos_sp_triplet.current.velocity_valid = true;
pos_sp_triplet.current.vx = set_position_target_local_ned.vx;
pos_sp_triplet.current.vy = set_position_target_local_ned.vy;
pos_sp_triplet.current.vz = set_position_target_local_ned.vz;
pos_sp_triplet.current.velocity_frame = set_position_target_local_ned.coordinate_frame;
} else {
pos_sp_triplet.current.velocity_valid = false;
}
if (!offboard_control_mode.ignore_alt_hold) {
pos_sp_triplet.current.alt_valid = true;
pos_sp_triplet.current.z = set_position_target_local_ned.z;
} else {
pos_sp_triplet.current.alt_valid = false;
}
/* set the local acceleration values if the setpoint type is 'local pos' and none
* of the accelerations fields is set to 'ignore' */
if (!offboard_control_mode.ignore_acceleration_force) {
pos_sp_triplet.current.acceleration_valid = true;
pos_sp_triplet.current.a_x = set_position_target_local_ned.afx;
pos_sp_triplet.current.a_y = set_position_target_local_ned.afy;
pos_sp_triplet.current.a_z = set_position_target_local_ned.afz;
pos_sp_triplet.current.acceleration_is_force = is_force_sp;
} else {
pos_sp_triplet.current.acceleration_valid = false;
}
/* set the yaw sp value */
if (!offboard_control_mode.ignore_attitude) {
pos_sp_triplet.current.yaw_valid = true;
pos_sp_triplet.current.yaw = set_position_target_local_ned.yaw;
} else {
pos_sp_triplet.current.yaw_valid = false;
}
/* set the yawrate sp value */
if (!(offboard_control_mode.ignore_bodyrate_x ||
offboard_control_mode.ignore_bodyrate_y ||
offboard_control_mode.ignore_bodyrate_z)) {
pos_sp_triplet.current.yawspeed_valid = true;
pos_sp_triplet.current.yawspeed = set_position_target_local_ned.yaw_rate;
} else {
pos_sp_triplet.current.yawspeed_valid = false;
}
//XXX handle global pos setpoints (different MAV frames)
_pos_sp_triplet_pub.publish(pos_sp_triplet);
}
}
}
}
}
void
MavlinkReceiver::handle_message_set_position_target_global_int(mavlink_message_t *msg)
{
mavlink_set_position_target_global_int_t set_position_target_global_int;
mavlink_msg_set_position_target_global_int_decode(msg, &set_position_target_global_int);
const bool values_finite =
PX4_ISFINITE(set_position_target_global_int.alt) &&
PX4_ISFINITE(set_position_target_global_int.vx) &&
PX4_ISFINITE(set_position_target_global_int.vy) &&
PX4_ISFINITE(set_position_target_global_int.vz) &&
PX4_ISFINITE(set_position_target_global_int.afx) &&
PX4_ISFINITE(set_position_target_global_int.afy) &&
PX4_ISFINITE(set_position_target_global_int.afz) &&
PX4_ISFINITE(set_position_target_global_int.yaw);
/* Only accept messages which are intended for this system */
if ((mavlink_system.sysid == set_position_target_global_int.target_system ||
set_position_target_global_int.target_system == 0) &&
(mavlink_system.compid == set_position_target_global_int.target_component ||
set_position_target_global_int.target_component == 0) &&
values_finite) {
offboard_control_mode_s offboard_control_mode{};
/* convert mavlink type (local, NED) to uORB offboard control struct */
offboard_control_mode.ignore_position = (bool)(set_position_target_global_int.type_mask &
(POSITION_TARGET_TYPEMASK_X_IGNORE
| POSITION_TARGET_TYPEMASK_Y_IGNORE
| POSITION_TARGET_TYPEMASK_Z_IGNORE));
offboard_control_mode.ignore_alt_hold = (bool)(set_position_target_global_int.type_mask &
POSITION_TARGET_TYPEMASK_Z_IGNORE);
offboard_control_mode.ignore_velocity = (bool)(set_position_target_global_int.type_mask &
(POSITION_TARGET_TYPEMASK_VX_IGNORE
| POSITION_TARGET_TYPEMASK_VY_IGNORE
| POSITION_TARGET_TYPEMASK_VZ_IGNORE));
offboard_control_mode.ignore_acceleration_force = (bool)(set_position_target_global_int.type_mask &
(POSITION_TARGET_TYPEMASK_AX_IGNORE
| POSITION_TARGET_TYPEMASK_AY_IGNORE
| POSITION_TARGET_TYPEMASK_AZ_IGNORE));
/* yaw ignore flag mapps to ignore_attitude */
offboard_control_mode.ignore_attitude = (bool)(set_position_target_global_int.type_mask &
POSITION_TARGET_TYPEMASK_YAW_IGNORE);
offboard_control_mode.ignore_bodyrate_x = (bool)(set_position_target_global_int.type_mask &
POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE);
offboard_control_mode.ignore_bodyrate_y = (bool)(set_position_target_global_int.type_mask &
POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE);
offboard_control_mode.ignore_bodyrate_z = (bool)(set_position_target_global_int.type_mask &
POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE);
bool is_force_sp = (bool)(set_position_target_global_int.type_mask & POSITION_TARGET_TYPEMASK_FORCE_SET);
offboard_control_mode.timestamp = hrt_absolute_time();
_offboard_control_mode_pub.publish(offboard_control_mode);
/* If we are in offboard control mode and offboard control loop through is enabled
* also publish the setpoint topic which is read by the controller */
if (_mavlink->get_forward_externalsp()) {
vehicle_control_mode_s control_mode{};
_control_mode_sub.copy(&control_mode);
if (control_mode.flag_control_offboard_enabled) {
if (is_force_sp && offboard_control_mode.ignore_position &&
offboard_control_mode.ignore_velocity) {
PX4_WARN("force setpoint not supported");
} else {
/* It's not a pure force setpoint: publish to setpoint triplet topic */
position_setpoint_triplet_s pos_sp_triplet{};
pos_sp_triplet.timestamp = hrt_absolute_time();
pos_sp_triplet.previous.valid = false;
pos_sp_triplet.next.valid = false;
pos_sp_triplet.current.valid = true;
/* Order of statements matters. Takeoff can override loiter.
* See https://github.com/mavlink/mavlink/pull/670 for a broader conversation. */
if (set_position_target_global_int.type_mask & 0x3000) { //Loiter setpoint
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_LOITER;
} else if (set_position_target_global_int.type_mask & 0x1000) { //Takeoff setpoint
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_TAKEOFF;
} else if (set_position_target_global_int.type_mask & 0x2000) { //Land setpoint
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_LAND;
} else if (set_position_target_global_int.type_mask & 0x4000) { //Idle setpoint
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_IDLE;
} else {
pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_POSITION;
}
/* set the local pos values */
vehicle_local_position_s local_pos{};
if (!offboard_control_mode.ignore_position && _vehicle_local_position_sub.copy(&local_pos)) {
if (!globallocalconverter_initialized()) {
globallocalconverter_init(local_pos.ref_lat, local_pos.ref_lon,
local_pos.ref_alt, local_pos.ref_timestamp);
pos_sp_triplet.current.position_valid = false;
} else {
float target_altitude;
if (set_position_target_global_int.coordinate_frame == MAV_FRAME_GLOBAL_RELATIVE_ALT_INT) {
target_altitude = set_position_target_global_int.alt + local_pos.ref_alt;
} else {
target_altitude = set_position_target_global_int.alt; //MAV_FRAME_GLOBAL_INT
}
globallocalconverter_tolocal(set_position_target_global_int.lat_int / 1e7,
set_position_target_global_int.lon_int / 1e7, target_altitude,
&pos_sp_triplet.current.x, &pos_sp_triplet.current.y, &pos_sp_triplet.current.z);
pos_sp_triplet.current.cruising_speed = get_offb_cruising_speed();
pos_sp_triplet.current.position_valid = true;
}
} else {
pos_sp_triplet.current.position_valid = false;
}
/* set the local velocity values */
if (!offboard_control_mode.ignore_velocity) {
pos_sp_triplet.current.velocity_valid = true;
pos_sp_triplet.current.vx = set_position_target_global_int.vx;
pos_sp_triplet.current.vy = set_position_target_global_int.vy;
pos_sp_triplet.current.vz = set_position_target_global_int.vz;
pos_sp_triplet.current.velocity_frame = set_position_target_global_int.coordinate_frame;
} else {
pos_sp_triplet.current.velocity_valid = false;
}
if (!offboard_control_mode.ignore_alt_hold) {
pos_sp_triplet.current.alt_valid = true;
} else {
pos_sp_triplet.current.alt_valid = false;
}
/* set the local acceleration values if the setpoint type is 'local pos' and none
* of the accelerations fields is set to 'ignore' */
if (!offboard_control_mode.ignore_acceleration_force) {
pos_sp_triplet.current.acceleration_valid = true;
pos_sp_triplet.current.a_x = set_position_target_global_int.afx;
pos_sp_triplet.current.a_y = set_position_target_global_int.afy;
pos_sp_triplet.current.a_z = set_position_target_global_int.afz;
pos_sp_triplet.current.acceleration_is_force = is_force_sp;
} else {
pos_sp_triplet.current.acceleration_valid = false;
}
/* set the yaw setpoint */
if (!offboard_control_mode.ignore_attitude) {
pos_sp_triplet.current.yaw_valid = true;
pos_sp_triplet.current.yaw = set_position_target_global_int.yaw;
} else {
pos_sp_triplet.current.yaw_valid = false;
}
/* set the yawrate sp value */
if (!(offboard_control_mode.ignore_bodyrate_x ||
offboard_control_mode.ignore_bodyrate_y ||
offboard_control_mode.ignore_bodyrate_z)) {
pos_sp_triplet.current.yawspeed_valid = true;
pos_sp_triplet.current.yawspeed = set_position_target_global_int.yaw_rate;
} else {
pos_sp_triplet.current.yawspeed_valid = false;
}
_pos_sp_triplet_pub.publish(pos_sp_triplet);
}
}
}
}
}
void
MavlinkReceiver::handle_message_set_actuator_control_target(mavlink_message_t *msg)
{
mavlink_set_actuator_control_target_t set_actuator_control_target;
mavlink_msg_set_actuator_control_target_decode(msg, &set_actuator_control_target);
bool values_finite =
PX4_ISFINITE(set_actuator_control_target.controls[0]) &&
PX4_ISFINITE(set_actuator_control_target.controls[1]) &&
PX4_ISFINITE(set_actuator_control_target.controls[2]) &&
PX4_ISFINITE(set_actuator_control_target.controls[3]) &&
PX4_ISFINITE(set_actuator_control_target.controls[4]) &&
PX4_ISFINITE(set_actuator_control_target.controls[5]) &&
PX4_ISFINITE(set_actuator_control_target.controls[6]) &&
PX4_ISFINITE(set_actuator_control_target.controls[7]);
if ((mavlink_system.sysid == set_actuator_control_target.target_system ||
set_actuator_control_target.target_system == 0) &&
(mavlink_system.compid == set_actuator_control_target.target_component ||
set_actuator_control_target.target_component == 0) &&
values_finite) {
#if defined(ENABLE_LOCKSTEP_SCHEDULER)
PX4_ERR("SET_ACTUATOR_CONTROL_TARGET not supported with lockstep enabled");
PX4_ERR("Please disable lockstep for actuator offboard control:");
PX4_ERR("https://dev.px4.io/master/en/simulation/#disable-lockstep-simulation");
return;
#endif
/* Ignore all setpoints except when controlling the gimbal(group_mlx==2) as we are setting raw actuators here */
bool ignore_setpoints = bool(set_actuator_control_target.group_mlx != 2);
offboard_control_mode_s offboard_control_mode{};
offboard_control_mode.ignore_thrust = ignore_setpoints;
offboard_control_mode.ignore_attitude = ignore_setpoints;
offboard_control_mode.ignore_bodyrate_x = ignore_setpoints;
offboard_control_mode.ignore_bodyrate_y = ignore_setpoints;
offboard_control_mode.ignore_bodyrate_z = ignore_setpoints;
offboard_control_mode.ignore_position = ignore_setpoints;
offboard_control_mode.ignore_velocity = ignore_setpoints;
offboard_control_mode.ignore_acceleration_force = ignore_setpoints;
offboard_control_mode.timestamp = hrt_absolute_time();
_offboard_control_mode_pub.publish(offboard_control_mode);
/* If we are in offboard control mode, publish the actuator controls */
vehicle_control_mode_s control_mode{};
_control_mode_sub.copy(&control_mode);
if (control_mode.flag_control_offboard_enabled) {
actuator_controls_s actuator_controls{};
actuator_controls.timestamp = hrt_absolute_time();
/* Set duty cycles for the servos in the actuator_controls message */
for (size_t i = 0; i < 8; i++) {
actuator_controls.control[i] = set_actuator_control_target.controls[i];
}
switch (set_actuator_control_target.group_mlx) {
case 0:
_actuator_controls_pubs[0].publish(actuator_controls);
break;
case 1:
_actuator_controls_pubs[1].publish(actuator_controls);
break;
case 2:
_actuator_controls_pubs[2].publish(actuator_controls);
break;
case 3:
_actuator_controls_pubs[3].publish(actuator_controls);
break;
default:
break;
}
}
}
}
void
MavlinkReceiver::handle_message_set_gps_global_origin(mavlink_message_t *msg)
{
mavlink_set_gps_global_origin_t origin;
mavlink_msg_set_gps_global_origin_decode(msg, &origin);
if (!globallocalconverter_initialized() && (origin.target_system == _mavlink->get_system_id())) {
/* Set reference point conversion of local coordiantes <--> global coordinates */
globallocalconverter_init((double)origin.latitude * 1.0e-7, (double)origin.longitude * 1.0e-7,
(float)origin.altitude * 1.0e-3f, hrt_absolute_time());
_global_ref_timestamp = hrt_absolute_time();
}
handle_request_message_command(MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN);
}
void
MavlinkReceiver::handle_message_vision_position_estimate(mavlink_message_t *msg)
{
mavlink_vision_position_estimate_t ev;
mavlink_msg_vision_position_estimate_decode(msg, &ev);
vehicle_odometry_s visual_odom{};
visual_odom.timestamp = hrt_absolute_time();
visual_odom.timestamp_sample = _mavlink_timesync.sync_stamp(ev.usec);
visual_odom.x = ev.x;
visual_odom.y = ev.y;
visual_odom.z = ev.z;
matrix::Quatf q(matrix::Eulerf(ev.roll, ev.pitch, ev.yaw));
q.copyTo(visual_odom.q);
visual_odom.local_frame = vehicle_odometry_s::LOCAL_FRAME_NED;
const size_t URT_SIZE = sizeof(visual_odom.pose_covariance) / sizeof(visual_odom.pose_covariance[0]);
static_assert(URT_SIZE == (sizeof(ev.covariance) / sizeof(ev.covariance[0])),
"Odometry Pose Covariance matrix URT array size mismatch");
for (size_t i = 0; i < URT_SIZE; i++) {
visual_odom.pose_covariance[i] = ev.covariance[i];
}
visual_odom.velocity_frame = vehicle_odometry_s::LOCAL_FRAME_FRD;
visual_odom.vx = NAN;
visual_odom.vy = NAN;
visual_odom.vz = NAN;
visual_odom.rollspeed = NAN;
visual_odom.pitchspeed = NAN;
visual_odom.yawspeed = NAN;
visual_odom.velocity_covariance[0] = NAN;
_visual_odometry_pub.publish(visual_odom);
}
void
MavlinkReceiver::handle_message_odometry(mavlink_message_t *msg)
{
mavlink_odometry_t odom;
mavlink_msg_odometry_decode(msg, &odom);
vehicle_odometry_s odometry{};
odometry.timestamp = hrt_absolute_time();
odometry.timestamp_sample = _mavlink_timesync.sync_stamp(odom.time_usec);
/* The position is in a local FRD frame */
odometry.x = odom.x;
odometry.y = odom.y;
odometry.z = odom.z;
/**
* The quaternion of the ODOMETRY msg represents a rotation from body frame
* to a local frame
*/
matrix::Quatf q_body_to_local(odom.q);
q_body_to_local.normalize();
q_body_to_local.copyTo(odometry.q);
// pose_covariance
static constexpr size_t POS_URT_SIZE = sizeof(odometry.pose_covariance) / sizeof(odometry.pose_covariance[0]);
static_assert(POS_URT_SIZE == (sizeof(odom.pose_covariance) / sizeof(odom.pose_covariance[0])),
"Odometry Pose Covariance matrix URT array size mismatch");
// velocity_covariance
static constexpr size_t VEL_URT_SIZE = sizeof(odometry.velocity_covariance) / sizeof(odometry.velocity_covariance[0]);
static_assert(VEL_URT_SIZE == (sizeof(odom.velocity_covariance) / sizeof(odom.velocity_covariance[0])),
"Odometry Velocity Covariance matrix URT array size mismatch");
// TODO: create a method to simplify covariance copy
for (size_t i = 0; i < POS_URT_SIZE; i++) {
odometry.pose_covariance[i] = odom.pose_covariance[i];
}
/**
* PX4 expects the body's linear velocity in the local frame,
* the linear velocity is rotated from the odom child_frame to the
* local NED frame. The angular velocity needs to be expressed in the
* body (fcu_frd) frame.
*/
if (odom.child_frame_id == MAV_FRAME_BODY_FRD) {
odometry.velocity_frame = vehicle_odometry_s::BODY_FRAME_FRD;
odometry.vx = odom.vx;
odometry.vy = odom.vy;
odometry.vz = odom.vz;
odometry.rollspeed = odom.rollspeed;
odometry.pitchspeed = odom.pitchspeed;
odometry.yawspeed = odom.yawspeed;
for (size_t i = 0; i < VEL_URT_SIZE; i++) {
odometry.velocity_covariance[i] = odom.velocity_covariance[i];
}
} else {
PX4_ERR("Body frame %u not supported. Unable to publish velocity", odom.child_frame_id);
}
/**
* Supported local frame of reference is MAV_FRAME_LOCAL_NED or MAV_FRAME_LOCAL_FRD
* The supported sources of the data/tesimator type are MAV_ESTIMATOR_TYPE_VISION,
* MAV_ESTIMATOR_TYPE_VIO and MAV_ESTIMATOR_TYPE_MOCAP
*
* @note Regarding the local frames of reference, the appropriate EKF_AID_MASK
* should be set in order to match a frame aligned (NED) or not aligned (FRD)
* with true North
*/
if (odom.frame_id == MAV_FRAME_LOCAL_NED || odom.frame_id == MAV_FRAME_LOCAL_FRD) {
if (odom.frame_id == MAV_FRAME_LOCAL_NED) {
odometry.local_frame = vehicle_odometry_s::LOCAL_FRAME_NED;
} else {
odometry.local_frame = vehicle_odometry_s::LOCAL_FRAME_FRD;
}
if (odom.estimator_type == MAV_ESTIMATOR_TYPE_MOCAP) {
_mocap_odometry_pub.publish(odometry);
} else {
// MAV_ESTIMATOR_TYPE_VISION, MAV_ESTIMATOR_TYPE_VIO
// publish anything else for now
_visual_odometry_pub.publish(odometry);
}
} else {
PX4_ERR("Local frame %u not supported. Unable to publish pose and velocity", odom.frame_id);
}
}
void MavlinkReceiver::fill_thrust(float *thrust_body_array, uint8_t vehicle_type, float thrust)
{
// Fill correct field by checking frametype
// TODO: add as needed
switch (_mavlink->get_system_type()) {
case MAV_TYPE_GENERIC:
break;
case MAV_TYPE_FIXED_WING:
case MAV_TYPE_GROUND_ROVER:
thrust_body_array[0] = thrust;
break;
case MAV_TYPE_QUADROTOR:
case MAV_TYPE_HEXAROTOR:
case MAV_TYPE_OCTOROTOR:
case MAV_TYPE_TRICOPTER:
case MAV_TYPE_HELICOPTER:
case MAV_TYPE_COAXIAL:
thrust_body_array[2] = -thrust;
break;
case MAV_TYPE_SUBMARINE:
thrust_body_array[0] = thrust;
break;
case MAV_TYPE_VTOL_DUOROTOR:
case MAV_TYPE_VTOL_QUADROTOR:
case MAV_TYPE_VTOL_TILTROTOR:
case MAV_TYPE_VTOL_RESERVED2:
case MAV_TYPE_VTOL_RESERVED3:
case MAV_TYPE_VTOL_RESERVED4:
case MAV_TYPE_VTOL_RESERVED5:
switch (vehicle_type) {
case vehicle_status_s::VEHICLE_TYPE_FIXED_WING:
thrust_body_array[0] = thrust;
break;
case vehicle_status_s::VEHICLE_TYPE_ROTARY_WING:
thrust_body_array[2] = -thrust;
break;
default:
// This should never happen
break;
}
break;
}
}
void
MavlinkReceiver::handle_message_set_attitude_target(mavlink_message_t *msg)
{
mavlink_set_attitude_target_t set_attitude_target;
mavlink_msg_set_attitude_target_decode(msg, &set_attitude_target);
bool values_finite =
PX4_ISFINITE(set_attitude_target.q[0]) &&
PX4_ISFINITE(set_attitude_target.q[1]) &&
PX4_ISFINITE(set_attitude_target.q[2]) &&
PX4_ISFINITE(set_attitude_target.q[3]) &&
PX4_ISFINITE(set_attitude_target.thrust) &&
PX4_ISFINITE(set_attitude_target.body_roll_rate) &&
PX4_ISFINITE(set_attitude_target.body_pitch_rate) &&
PX4_ISFINITE(set_attitude_target.body_yaw_rate);
/* Only accept messages which are intended for this system */
if ((mavlink_system.sysid == set_attitude_target.target_system ||
set_attitude_target.target_system == 0) &&
(mavlink_system.compid == set_attitude_target.target_component ||
set_attitude_target.target_component == 0) &&
values_finite) {
offboard_control_mode_s offboard_control_mode{};
/* set correct ignore flags for thrust field: copy from mavlink message */
offboard_control_mode.ignore_thrust = (bool)(set_attitude_target.type_mask & ATTITUDE_TARGET_TYPEMASK_THROTTLE_IGNORE);
/*
* The tricky part in parsing this message is that the offboard sender *can* set attitude and thrust
* using different messages. Eg.: First send set_attitude_target containing the attitude and ignore
* bits set for everything else and then send set_attitude_target containing the thrust and ignore bits
* set for everything else.
*/
/*
* if attitude or body rate have been used (not ignored) previously and this message only sends
* throttle and has the ignore bits set for attitude and rates don't change the flags for attitude and
* body rates to keep the controllers running
*/
bool ignore_bodyrate_msg_x = (bool)(set_attitude_target.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_ROLL_RATE_IGNORE);
bool ignore_bodyrate_msg_y = (bool)(set_attitude_target.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_PITCH_RATE_IGNORE);
bool ignore_bodyrate_msg_z = (bool)(set_attitude_target.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_YAW_RATE_IGNORE);
bool ignore_attitude_msg = (bool)(set_attitude_target.type_mask & ATTITUDE_TARGET_TYPEMASK_ATTITUDE_IGNORE);
if ((ignore_bodyrate_msg_x || ignore_bodyrate_msg_y ||
ignore_bodyrate_msg_z) &&
ignore_attitude_msg && !offboard_control_mode.ignore_thrust) {
/* Message want's us to ignore everything except thrust: only ignore if previously ignored */
offboard_control_mode.ignore_bodyrate_x = ignore_bodyrate_msg_x && offboard_control_mode.ignore_bodyrate_x;
offboard_control_mode.ignore_bodyrate_y = ignore_bodyrate_msg_y && offboard_control_mode.ignore_bodyrate_y;
offboard_control_mode.ignore_bodyrate_z = ignore_bodyrate_msg_z && offboard_control_mode.ignore_bodyrate_z;
offboard_control_mode.ignore_attitude = ignore_attitude_msg && offboard_control_mode.ignore_attitude;
} else {
offboard_control_mode.ignore_bodyrate_x = ignore_bodyrate_msg_x;
offboard_control_mode.ignore_bodyrate_y = ignore_bodyrate_msg_y;
offboard_control_mode.ignore_bodyrate_z = ignore_bodyrate_msg_z;
offboard_control_mode.ignore_attitude = ignore_attitude_msg;
}
offboard_control_mode.ignore_position = true;
offboard_control_mode.ignore_velocity = true;
offboard_control_mode.ignore_acceleration_force = true;
offboard_control_mode.timestamp = hrt_absolute_time();
_offboard_control_mode_pub.publish(offboard_control_mode);
/* If we are in offboard control mode and offboard control loop through is enabled
* also publish the setpoint topic which is read by the controller */
if (_mavlink->get_forward_externalsp()) {
vehicle_control_mode_s control_mode{};
_control_mode_sub.copy(&control_mode);
if (control_mode.flag_control_offboard_enabled) {
vehicle_status_s vehicle_status{};
_vehicle_status_sub.copy(&vehicle_status);
/* Publish attitude setpoint if attitude and thrust ignore bits are not set */
if (!(offboard_control_mode.ignore_attitude)) {
vehicle_attitude_setpoint_s att_sp = {};
att_sp.timestamp = hrt_absolute_time();
if (!ignore_attitude_msg) { // only copy att sp if message contained new data
matrix::Quatf q(set_attitude_target.q);
q.copyTo(att_sp.q_d);
matrix::Eulerf euler{q};
att_sp.roll_body = euler.phi();
att_sp.pitch_body = euler.theta();
att_sp.yaw_body = euler.psi();
att_sp.yaw_sp_move_rate = 0.0f;
}
if (!offboard_control_mode.ignore_thrust) { // don't overwrite thrust if it's invalid
fill_thrust(att_sp.thrust_body, vehicle_status.vehicle_type, set_attitude_target.thrust);
}
// Publish attitude setpoint
if (vehicle_status.is_vtol && (vehicle_status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING)) {
_mc_virtual_att_sp_pub.publish(att_sp);
} else if (vehicle_status.is_vtol && (vehicle_status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING)) {
_fw_virtual_att_sp_pub.publish(att_sp);
} else {
_att_sp_pub.publish(att_sp);
}
}
/* Publish attitude rate setpoint if bodyrate and thrust ignore bits are not set */
if (!offboard_control_mode.ignore_bodyrate_x ||
!offboard_control_mode.ignore_bodyrate_y ||
!offboard_control_mode.ignore_bodyrate_z) {
vehicle_rates_setpoint_s rates_sp{};
rates_sp.timestamp = hrt_absolute_time();
// only copy att rates sp if message contained new data
if (!ignore_bodyrate_msg_x) {
rates_sp.roll = set_attitude_target.body_roll_rate;
}
if (!ignore_bodyrate_msg_y) {
rates_sp.pitch = set_attitude_target.body_pitch_rate;
}
if (!ignore_bodyrate_msg_z) {
rates_sp.yaw = set_attitude_target.body_yaw_rate;
}
if (!offboard_control_mode.ignore_thrust) { // don't overwrite thrust if it's invalid
fill_thrust(rates_sp.thrust_body, vehicle_status.vehicle_type, set_attitude_target.thrust);
}
_rates_sp_pub.publish(rates_sp);
}
}
}
}
}
void
MavlinkReceiver::handle_message_radio_status(mavlink_message_t *msg)
{
/* telemetry status supported only on first ORB_MULTI_MAX_INSTANCES mavlink channels */
if (_mavlink->get_channel() < (mavlink_channel_t)ORB_MULTI_MAX_INSTANCES) {
mavlink_radio_status_t rstatus;
mavlink_msg_radio_status_decode(msg, &rstatus);
radio_status_s status{};
status.timestamp = hrt_absolute_time();
status.rssi = rstatus.rssi;
status.remote_rssi = rstatus.remrssi;
status.txbuf = rstatus.txbuf;
status.noise = rstatus.noise;
status.remote_noise = rstatus.remnoise;
status.rxerrors = rstatus.rxerrors;
status.fix = rstatus.fixed;
_mavlink->update_radio_status(status);
_radio_status_pub.publish(status);
}
}
void
MavlinkReceiver::handle_message_ping(mavlink_message_t *msg)
{
mavlink_ping_t ping;
mavlink_msg_ping_decode(msg, &ping);
if ((ping.target_system == 0) &&
(ping.target_component == 0)) { // This is a ping request. Return it to the system which requested the ping.
ping.target_system = msg->sysid;
ping.target_component = msg->compid;
mavlink_msg_ping_send_struct(_mavlink->get_channel(), &ping);
} else if ((ping.target_system == mavlink_system.sysid) &&
(ping.target_component ==
mavlink_system.compid)) { // This is a returned ping message from this system. Calculate latency from it.
const hrt_abstime now = hrt_absolute_time();
// Calculate round trip time
float rtt_ms = (now - ping.time_usec) / 1000.0f;
// Update ping statistics
struct Mavlink::ping_statistics_s &pstats = _mavlink->get_ping_statistics();
pstats.last_ping_time = now;
if (pstats.last_ping_seq == 0 && ping.seq > 0) {
// This is the first reply we are receiving from an offboard system.
// We may have been broadcasting pings for some time before it came online,
// and these do not count as dropped packets.
// Reset last_ping_seq counter for correct packet drop detection
pstats.last_ping_seq = ping.seq - 1;
}
// We can only count dropped packets after the first message
if (ping.seq > pstats.last_ping_seq) {
pstats.dropped_packets += ping.seq - pstats.last_ping_seq - 1;
}
pstats.last_ping_seq = ping.seq;
pstats.last_rtt = rtt_ms;
pstats.mean_rtt = (rtt_ms + pstats.mean_rtt) / 2.0f;
pstats.max_rtt = fmaxf(rtt_ms, pstats.max_rtt);
pstats.min_rtt = pstats.min_rtt > 0.0f ? fminf(rtt_ms, pstats.min_rtt) : rtt_ms;
/* Ping status is supported only on first ORB_MULTI_MAX_INSTANCES mavlink channels */
if (_mavlink->get_channel() < (mavlink_channel_t)ORB_MULTI_MAX_INSTANCES) {
ping_s uorb_ping_msg{};
uorb_ping_msg.timestamp = now;
uorb_ping_msg.ping_time = ping.time_usec;
uorb_ping_msg.ping_sequence = ping.seq;
uorb_ping_msg.dropped_packets = pstats.dropped_packets;
uorb_ping_msg.rtt_ms = rtt_ms;
uorb_ping_msg.system_id = msg->sysid;
uorb_ping_msg.component_id = msg->compid;
_ping_pub.publish(uorb_ping_msg);
}
}
}
void
MavlinkReceiver::handle_message_battery_status(mavlink_message_t *msg)
{
if ((msg->sysid != mavlink_system.sysid) || (msg->compid == mavlink_system.compid)) {
// ignore battery status coming from other systems or from the autopilot itself
return;
}
// external battery measurements
mavlink_battery_status_t battery_mavlink;
mavlink_msg_battery_status_decode(msg, &battery_mavlink);
battery_status_s battery_status{};
battery_status.timestamp = hrt_absolute_time();
float voltage_sum = 0.0f;
uint8_t cell_count = 0;
while (battery_mavlink.voltages[cell_count] < UINT16_MAX && cell_count < 10) {
battery_status.voltage_cell_v[cell_count] = (float)(battery_mavlink.voltages[cell_count]) / 1000.0f;
voltage_sum += battery_status.voltage_cell_v[cell_count];
cell_count++;
}
battery_status.voltage_v = voltage_sum;
battery_status.voltage_filtered_v = voltage_sum;
battery_status.current_a = battery_status.current_filtered_a = (float)(battery_mavlink.current_battery) / 100.0f;
battery_status.current_filtered_a = battery_status.current_a;
battery_status.remaining = (float)battery_mavlink.battery_remaining / 100.0f;
battery_status.discharged_mah = (float)battery_mavlink.current_consumed;
battery_status.cell_count = cell_count;
battery_status.temperature = (float)battery_mavlink.temperature;
battery_status.connected = true;
// Set the battery warning based on remaining charge.
// Note: Smallest values must come first in evaluation.
if (battery_status.remaining < _param_bat_emergen_thr.get()) {
battery_status.warning = battery_status_s::BATTERY_WARNING_EMERGENCY;
} else if (battery_status.remaining < _param_bat_crit_thr.get()) {
battery_status.warning = battery_status_s::BATTERY_WARNING_CRITICAL;
} else if (battery_status.remaining < _param_bat_low_thr.get()) {
battery_status.warning = battery_status_s::BATTERY_WARNING_LOW;
}
_battery_pub.publish(battery_status);
}
void
MavlinkReceiver::handle_message_serial_control(mavlink_message_t *msg)
{
mavlink_serial_control_t serial_control_mavlink;
mavlink_msg_serial_control_decode(msg, &serial_control_mavlink);
// we only support shell commands
if (serial_control_mavlink.device != SERIAL_CONTROL_DEV_SHELL
|| (serial_control_mavlink.flags & SERIAL_CONTROL_FLAG_REPLY)) {
return;
}
MavlinkShell *shell = _mavlink->get_shell();
if (shell) {
// we ignore the timeout, EXCLUSIVE & BLOCKING flags of the SERIAL_CONTROL message
if (serial_control_mavlink.count > 0) {
shell->write(serial_control_mavlink.data, serial_control_mavlink.count);
}
// if no response requested, assume the shell is no longer used
if ((serial_control_mavlink.flags & SERIAL_CONTROL_FLAG_RESPOND) == 0) {
_mavlink->close_shell();
}
}
}
void
MavlinkReceiver::handle_message_logging_ack(mavlink_message_t *msg)
{
mavlink_logging_ack_t logging_ack;
mavlink_msg_logging_ack_decode(msg, &logging_ack);
MavlinkULog *ulog_streaming = _mavlink->get_ulog_streaming();
if (ulog_streaming) {
ulog_streaming->handle_ack(logging_ack);
}
}
void
MavlinkReceiver::handle_message_play_tune(mavlink_message_t *msg)
{
mavlink_play_tune_t play_tune;
mavlink_msg_play_tune_decode(msg, &play_tune);
if ((mavlink_system.sysid == play_tune.target_system || play_tune.target_system == 0) &&
(mavlink_system.compid == play_tune.target_component || play_tune.target_component == 0)) {
// Let's make sure the input is 0 terminated, so we don't ever overrun it.
play_tune.tune2[sizeof(play_tune.tune2) - 1] = '\0';
schedule_tune(play_tune.tune);
}
}
void
MavlinkReceiver::handle_message_play_tune_v2(mavlink_message_t *msg)
{
mavlink_play_tune_v2_t play_tune_v2;
mavlink_msg_play_tune_v2_decode(msg, &play_tune_v2);
if ((mavlink_system.sysid == play_tune_v2.target_system || play_tune_v2.target_system == 0) &&
(mavlink_system.compid == play_tune_v2.target_component || play_tune_v2.target_component == 0)) {
if (play_tune_v2.format != TUNE_FORMAT_QBASIC1_1) {
PX4_ERR("Tune format %d not supported", play_tune_v2.format);
return;
}
// Let's make sure the input is 0 terminated, so we don't ever overrun it.
play_tune_v2.tune[sizeof(play_tune_v2.tune) - 1] = '\0';
schedule_tune(play_tune_v2.tune);
}
}
void MavlinkReceiver::schedule_tune(const char *tune)
{
// We only allocate the TunePublisher object if we ever use it but we
// don't remove it to avoid fragmentation over time.
if (_tune_publisher == nullptr) {
_tune_publisher = new TunePublisher();
if (_tune_publisher == nullptr) {
PX4_ERR("Could not allocate tune publisher");
return;
}
}
const hrt_abstime now = hrt_absolute_time();
_tune_publisher->set_tune_string(tune, now);
// Send first one straightaway.
_tune_publisher->publish_next_tune(now);
}
void
MavlinkReceiver::handle_message_obstacle_distance(mavlink_message_t *msg)
{
mavlink_obstacle_distance_t mavlink_obstacle_distance;
mavlink_msg_obstacle_distance_decode(msg, &mavlink_obstacle_distance);
obstacle_distance_s obstacle_distance{};
obstacle_distance.timestamp = hrt_absolute_time();
obstacle_distance.sensor_type = mavlink_obstacle_distance.sensor_type;
memcpy(obstacle_distance.distances, mavlink_obstacle_distance.distances, sizeof(obstacle_distance.distances));
if (mavlink_obstacle_distance.increment_f > 0.f) {
obstacle_distance.increment = mavlink_obstacle_distance.increment_f;
} else {
obstacle_distance.increment = (float)mavlink_obstacle_distance.increment;
}
obstacle_distance.min_distance = mavlink_obstacle_distance.min_distance;
obstacle_distance.max_distance = mavlink_obstacle_distance.max_distance;
obstacle_distance.angle_offset = mavlink_obstacle_distance.angle_offset;
obstacle_distance.frame = mavlink_obstacle_distance.frame;
_obstacle_distance_pub.publish(obstacle_distance);
}
void
MavlinkReceiver::handle_message_trajectory_representation_bezier(mavlink_message_t *msg)
{
mavlink_trajectory_representation_bezier_t trajectory;
mavlink_msg_trajectory_representation_bezier_decode(msg, &trajectory);
vehicle_trajectory_bezier_s trajectory_bezier{};
trajectory_bezier.timestamp = _mavlink_timesync.sync_stamp(trajectory.time_usec);
for (int i = 0; i < vehicle_trajectory_bezier_s::NUMBER_POINTS; ++i) {
trajectory_bezier.control_points[i].position[0] = trajectory.pos_x[i];
trajectory_bezier.control_points[i].position[1] = trajectory.pos_y[i];
trajectory_bezier.control_points[i].position[2] = trajectory.pos_z[i];
trajectory_bezier.control_points[i].delta = trajectory.delta[i];
trajectory_bezier.control_points[i].yaw = trajectory.pos_yaw[i];
}
trajectory_bezier.bezier_order = math::min(trajectory.valid_points, vehicle_trajectory_bezier_s::NUMBER_POINTS);
_trajectory_bezier_pub.publish(trajectory_bezier);
}
void
MavlinkReceiver::handle_message_trajectory_representation_waypoints(mavlink_message_t *msg)
{
mavlink_trajectory_representation_waypoints_t trajectory;
mavlink_msg_trajectory_representation_waypoints_decode(msg, &trajectory);
vehicle_trajectory_waypoint_s trajectory_waypoint{};
trajectory_waypoint.timestamp = hrt_absolute_time();
const int number_valid_points = trajectory.valid_points;
for (int i = 0; i < vehicle_trajectory_waypoint_s::NUMBER_POINTS; ++i) {
trajectory_waypoint.waypoints[i].position[0] = trajectory.pos_x[i];
trajectory_waypoint.waypoints[i].position[1] = trajectory.pos_y[i];
trajectory_waypoint.waypoints[i].position[2] = trajectory.pos_z[i];
trajectory_waypoint.waypoints[i].velocity[0] = trajectory.vel_x[i];
trajectory_waypoint.waypoints[i].velocity[1] = trajectory.vel_y[i];
trajectory_waypoint.waypoints[i].velocity[2] = trajectory.vel_z[i];
trajectory_waypoint.waypoints[i].acceleration[0] = trajectory.acc_x[i];
trajectory_waypoint.waypoints[i].acceleration[1] = trajectory.acc_y[i];
trajectory_waypoint.waypoints[i].acceleration[2] = trajectory.acc_z[i];
trajectory_waypoint.waypoints[i].yaw = trajectory.pos_yaw[i];
trajectory_waypoint.waypoints[i].yaw_speed = trajectory.vel_yaw[i];
trajectory_waypoint.waypoints[i].type = UINT8_MAX;
}
for (int i = 0; i < number_valid_points; ++i) {
trajectory_waypoint.waypoints[i].point_valid = true;
}
for (int i = number_valid_points; i < vehicle_trajectory_waypoint_s::NUMBER_POINTS; ++i) {
trajectory_waypoint.waypoints[i].point_valid = false;
}
_trajectory_waypoint_pub.publish(trajectory_waypoint);
}
int
MavlinkReceiver::decode_switch_pos_n(uint16_t buttons, unsigned sw)
{
bool on = (buttons & (1 << sw));
if (sw < MOM_SWITCH_COUNT) {
bool last_on = (_mom_switch_state & (1 << sw));
/* first switch is 2-pos, rest is 2 pos */
unsigned state_count = (sw == 0) ? 3 : 2;
/* only transition on low state */
if (!on && (on != last_on)) {
_mom_switch_pos[sw]++;
if (_mom_switch_pos[sw] == state_count) {
_mom_switch_pos[sw] = 0;
}
}
/* state_count - 1 is the number of intervals and 1000 is the range,
* with 2 states 0 becomes 0, 1 becomes 1000. With
* 3 states 0 becomes 0, 1 becomes 500, 2 becomes 1000,
* and so on for more states.
*/
return (_mom_switch_pos[sw] * 1000) / (state_count - 1) + 1000;
} else {
/* return the current state */
return on * 1000 + 1000;
}
}
void
MavlinkReceiver::handle_message_rc_channels_override(mavlink_message_t *msg)
{
mavlink_rc_channels_override_t man;
mavlink_msg_rc_channels_override_decode(msg, &man);
// Check target
if (man.target_system != 0 && man.target_system != _mavlink->get_system_id()) {
return;
}
// fill uORB message
input_rc_s rc{};
// metadata
rc.timestamp = hrt_absolute_time();
rc.timestamp_last_signal = rc.timestamp;
rc.rssi = RC_INPUT_RSSI_MAX;
rc.rc_failsafe = false;
rc.rc_lost = false;
rc.rc_lost_frame_count = 0;
rc.rc_total_frame_count = 1;
rc.rc_ppm_frame_length = 0;
rc.input_source = input_rc_s::RC_INPUT_SOURCE_MAVLINK;
// channels
rc.values[0] = man.chan1_raw;
rc.values[1] = man.chan2_raw;
rc.values[2] = man.chan3_raw;
rc.values[3] = man.chan4_raw;
rc.values[4] = man.chan5_raw;
rc.values[5] = man.chan6_raw;
rc.values[6] = man.chan7_raw;
rc.values[7] = man.chan8_raw;
rc.values[8] = man.chan9_raw;
rc.values[9] = man.chan10_raw;
rc.values[10] = man.chan11_raw;
rc.values[11] = man.chan12_raw;
rc.values[12] = man.chan13_raw;
rc.values[13] = man.chan14_raw;
rc.values[14] = man.chan15_raw;
rc.values[15] = man.chan16_raw;
rc.values[16] = man.chan17_raw;
rc.values[17] = man.chan18_raw;
// check how many channels are valid
for (int i = 17; i >= 0; i--) {
const bool ignore_max = rc.values[i] == UINT16_MAX; // ignore any channel with value UINT16_MAX
const bool ignore_zero = (i > 7) && (rc.values[i] == 0); // ignore channel 8-18 if value is 0
if (ignore_max || ignore_zero) {
// set all ignored values to zero
rc.values[i] = 0;
} else {
// first channel to not ignore -> set count considering zero-based index
rc.channel_count = i + 1;
break;
}
}
// publish uORB message
_rc_pub.publish(rc);
}
void
MavlinkReceiver::handle_message_manual_control(mavlink_message_t *msg)
{
mavlink_manual_control_t man;
mavlink_msg_manual_control_decode(msg, &man);
// Check target
if (man.target != 0 && man.target != _mavlink->get_system_id()) {
return;
}
if (_mavlink->should_generate_virtual_rc_input()) {
input_rc_s rc{};
rc.timestamp = hrt_absolute_time();
rc.timestamp_last_signal = rc.timestamp;
rc.channel_count = 8;
rc.rc_failsafe = false;
rc.rc_lost = false;
rc.rc_lost_frame_count = 0;
rc.rc_total_frame_count = 1;
rc.rc_ppm_frame_length = 0;
rc.input_source = input_rc_s::RC_INPUT_SOURCE_MAVLINK;
rc.rssi = RC_INPUT_RSSI_MAX;
rc.values[0] = man.x / 2 + 1500; // roll
rc.values[1] = man.y / 2 + 1500; // pitch
rc.values[2] = man.r / 2 + 1500; // yaw
rc.values[3] = math::constrain(man.z / 0.9f + 800.0f, 1000.0f, 2000.0f); // throttle
/* decode all switches which fit into the channel mask */
unsigned max_switch = (sizeof(man.buttons) * 8);
unsigned max_channels = (sizeof(rc.values) / sizeof(rc.values[0]));
if (max_switch > (max_channels - 4)) {
max_switch = (max_channels - 4);
}
/* fill all channels */
for (unsigned i = 0; i < max_switch; i++) {
rc.values[i + 4] = decode_switch_pos_n(man.buttons, i);
}
_mom_switch_state = man.buttons;
_rc_pub.publish(rc);
} else {
manual_control_setpoint_s manual{};
manual.timestamp = hrt_absolute_time();
manual.x = man.x / 1000.0f;
manual.y = man.y / 1000.0f;
manual.r = man.r / 1000.0f;
manual.z = man.z / 1000.0f;
manual.data_source = manual_control_setpoint_s::SOURCE_MAVLINK_0 + _mavlink->get_instance_id();
_manual_control_setpoint_pub.publish(manual);
}
}
void
MavlinkReceiver::handle_message_heartbeat(mavlink_message_t *msg)
{
/* telemetry status supported only on first TELEMETRY_STATUS_ORB_ID_NUM mavlink channels */
if (_mavlink->get_channel() < (mavlink_channel_t)ORB_MULTI_MAX_INSTANCES) {
const hrt_abstime now = hrt_absolute_time();
mavlink_heartbeat_t hb;
mavlink_msg_heartbeat_decode(msg, &hb);
const bool same_system = (msg->sysid == mavlink_system.sysid);
if (same_system || hb.type == MAV_TYPE_GCS) {
switch (hb.type) {
case MAV_TYPE_ANTENNA_TRACKER:
_heartbeat_type_antenna_tracker = now;
break;
case MAV_TYPE_GCS:
_heartbeat_type_gcs = now;
break;
case MAV_TYPE_ONBOARD_CONTROLLER:
_heartbeat_type_onboard_controller = now;
break;
case MAV_TYPE_GIMBAL:
_heartbeat_type_gimbal = now;
break;
case MAV_TYPE_ADSB:
_heartbeat_type_adsb = now;
break;
case MAV_TYPE_CAMERA:
_heartbeat_type_camera = now;
break;
default:
PX4_DEBUG("unhandled HEARTBEAT MAV_TYPE: %d from SYSID: %d, COMPID: %d", hb.type, msg->sysid, msg->compid);
}
switch (msg->compid) {
case MAV_COMP_ID_TELEMETRY_RADIO:
_heartbeat_component_telemetry_radio = now;
break;
case MAV_COMP_ID_LOG:
_heartbeat_component_log = now;
break;
case MAV_COMP_ID_OSD:
_heartbeat_component_osd = now;
break;
case MAV_COMP_ID_OBSTACLE_AVOIDANCE:
_heartbeat_component_obstacle_avoidance = now;
_mavlink->telemetry_status().avoidance_system_healthy = (hb.system_status == MAV_STATE_ACTIVE);
break;
case MAV_COMP_ID_VISUAL_INERTIAL_ODOMETRY:
_heartbeat_component_visual_inertial_odometry = now;
break;
case MAV_COMP_ID_PAIRING_MANAGER:
_heartbeat_component_pairing_manager = now;
break;
case MAV_COMP_ID_UDP_BRIDGE:
_heartbeat_component_udp_bridge = now;
break;
case MAV_COMP_ID_UART_BRIDGE:
_heartbeat_component_uart_bridge = now;
break;
default:
PX4_DEBUG("unhandled HEARTBEAT MAV_TYPE: %d from SYSID: %d, COMPID: %d", hb.type, msg->sysid, msg->compid);
}
CheckHeartbeats(now, true);
}
}
}
int
MavlinkReceiver::set_message_interval(int msgId, float interval, int data_rate)
{
if (msgId == MAVLINK_MSG_ID_HEARTBEAT) {
return PX4_ERROR;
}
if (data_rate > 0) {
_mavlink->set_data_rate(data_rate);
}
// configure_stream wants a rate (msgs/second), so convert here.
float rate = 0.f;
if (interval < -0.00001f) {
rate = 0.f; // stop the stream
} else if (interval > 0.00001f) {
rate = 1000000.0f / interval;
} else {
rate = -2.f; // set default rate
}
bool found_id = false;
if (msgId != 0) {
const char *stream_name = get_stream_name(msgId);
if (stream_name != nullptr) {
_mavlink->configure_stream_threadsafe(stream_name, rate);
found_id = true;
}
}
return (found_id ? PX4_OK : PX4_ERROR);
}
void
MavlinkReceiver::get_message_interval(int msgId)
{
unsigned interval = 0;
for (const auto &stream : _mavlink->get_streams()) {
if (stream->get_id() == msgId) {
interval = stream->get_interval();
break;
}
}
// send back this value...
mavlink_msg_message_interval_send(_mavlink->get_channel(), msgId, interval);
}
void
MavlinkReceiver::handle_message_hil_sensor(mavlink_message_t *msg)
{
mavlink_hil_sensor_t hil_sensor;
mavlink_msg_hil_sensor_decode(msg, &hil_sensor);
const uint64_t timestamp = hrt_absolute_time();
// temperature only updated with baro
float temperature = NAN;
if ((hil_sensor.fields_updated & SensorSource::BARO) == SensorSource::BARO) {
temperature = hil_sensor.temperature;
}
// gyro
if ((hil_sensor.fields_updated & SensorSource::GYRO) == SensorSource::GYRO) {
if (_px4_gyro == nullptr) {
// 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
_px4_gyro = new PX4Gyroscope(1310988);
}
if (_px4_gyro != nullptr) {
if (PX4_ISFINITE(temperature)) {
_px4_gyro->set_temperature(temperature);
}
_px4_gyro->update(timestamp, hil_sensor.xgyro, hil_sensor.ygyro, hil_sensor.zgyro);
}
}
// accelerometer
if ((hil_sensor.fields_updated & SensorSource::ACCEL) == SensorSource::ACCEL) {
if (_px4_accel == nullptr) {
// 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
_px4_accel = new PX4Accelerometer(1310988);
}
if (_px4_accel != nullptr) {
if (PX4_ISFINITE(temperature)) {
_px4_accel->set_temperature(temperature);
}
_px4_accel->update(timestamp, hil_sensor.xacc, hil_sensor.yacc, hil_sensor.zacc);
}
}
// magnetometer
if ((hil_sensor.fields_updated & SensorSource::MAG) == SensorSource::MAG) {
if (_px4_mag == nullptr) {
// 197388: DRV_MAG_DEVTYPE_MAGSIM, BUS: 3, ADDR: 1, TYPE: SIMULATION
_px4_mag = new PX4Magnetometer(197388);
}
if (_px4_mag != nullptr) {
if (PX4_ISFINITE(temperature)) {
_px4_mag->set_temperature(temperature);
}
_px4_mag->update(timestamp, hil_sensor.xmag, hil_sensor.ymag, hil_sensor.zmag);
}
}
// baro
if ((hil_sensor.fields_updated & SensorSource::BARO) == SensorSource::BARO) {
if (_px4_baro == nullptr) {
// 6620172: DRV_BARO_DEVTYPE_BAROSIM, BUS: 1, ADDR: 4, TYPE: SIMULATION
_px4_baro = new PX4Barometer(6620172);
}
if (_px4_baro != nullptr) {
_px4_baro->set_temperature(hil_sensor.temperature);
_px4_baro->update(timestamp, hil_sensor.abs_pressure);
}
}
// differential pressure
if ((hil_sensor.fields_updated & SensorSource::DIFF_PRESS) == SensorSource::DIFF_PRESS) {
differential_pressure_s report{};
report.timestamp = timestamp;
report.temperature = hil_sensor.temperature;
report.differential_pressure_filtered_pa = hil_sensor.diff_pressure * 100.0f; // convert from millibar to bar;
report.differential_pressure_raw_pa = hil_sensor.diff_pressure * 100.0f; // convert from millibar to bar;
_differential_pressure_pub.publish(report);
}
// battery status
{
battery_status_s hil_battery_status{};
hil_battery_status.timestamp = timestamp;
hil_battery_status.voltage_v = 11.5f;
hil_battery_status.voltage_filtered_v = 11.5f;
hil_battery_status.current_a = 10.0f;
hil_battery_status.discharged_mah = -1.0f;
_battery_pub.publish(hil_battery_status);
}
}
void
MavlinkReceiver::handle_message_hil_gps(mavlink_message_t *msg)
{
mavlink_hil_gps_t gps;
mavlink_msg_hil_gps_decode(msg, &gps);
const uint64_t timestamp = hrt_absolute_time();
sensor_gps_s hil_gps{};
hil_gps.timestamp_time_relative = 0;
hil_gps.time_utc_usec = gps.time_usec;
hil_gps.timestamp = timestamp;
hil_gps.lat = gps.lat;
hil_gps.lon = gps.lon;
hil_gps.alt = gps.alt;
hil_gps.eph = (float)gps.eph * 1e-2f; // from cm to m
hil_gps.epv = (float)gps.epv * 1e-2f; // from cm to m
hil_gps.s_variance_m_s = 0.1f;
hil_gps.vel_m_s = (float)gps.vel * 1e-2f; // from cm/s to m/s
hil_gps.vel_n_m_s = gps.vn * 1e-2f; // from cm to m
hil_gps.vel_e_m_s = gps.ve * 1e-2f; // from cm to m
hil_gps.vel_d_m_s = gps.vd * 1e-2f; // from cm to m
hil_gps.vel_ned_valid = true;
hil_gps.cog_rad = ((gps.cog == 65535) ? NAN : wrap_2pi(math::radians(gps.cog * 1e-2f)));
hil_gps.fix_type = gps.fix_type;
hil_gps.satellites_used = gps.satellites_visible; //TODO: rename mavlink_hil_gps_t sats visible to used?
hil_gps.heading = NAN;
hil_gps.heading_offset = NAN;
_gps_pub.publish(hil_gps);
}
void
MavlinkReceiver::handle_message_follow_target(mavlink_message_t *msg)
{
mavlink_follow_target_t follow_target_msg;
mavlink_msg_follow_target_decode(msg, &follow_target_msg);
follow_target_s follow_target_topic{};
follow_target_topic.timestamp = hrt_absolute_time();
follow_target_topic.lat = follow_target_msg.lat * 1e-7;
follow_target_topic.lon = follow_target_msg.lon * 1e-7;
follow_target_topic.alt = follow_target_msg.alt;
_follow_target_pub.publish(follow_target_topic);
}
void
MavlinkReceiver::handle_message_landing_target(mavlink_message_t *msg)
{
mavlink_landing_target_t landing_target;
mavlink_msg_landing_target_decode(msg, &landing_target);
if (landing_target.position_valid && landing_target.frame == MAV_FRAME_LOCAL_NED) {
landing_target_pose_s landing_target_pose{};
landing_target_pose.timestamp = _mavlink_timesync.sync_stamp(landing_target.time_usec);
landing_target_pose.abs_pos_valid = true;
landing_target_pose.x_abs = landing_target.x;
landing_target_pose.y_abs = landing_target.y;
landing_target_pose.z_abs = landing_target.z;
_landing_target_pose_pub.publish(landing_target_pose);
} else {
irlock_report_s irlock_report{};
irlock_report.timestamp = hrt_absolute_time();
irlock_report.signature = landing_target.target_num;
irlock_report.pos_x = landing_target.angle_x;
irlock_report.pos_y = landing_target.angle_y;
irlock_report.size_x = landing_target.size_x;
irlock_report.size_y = landing_target.size_y;
_irlock_report_pub.publish(irlock_report);
}
}
void
MavlinkReceiver::handle_message_cellular_status(mavlink_message_t *msg)
{
mavlink_cellular_status_t status;
mavlink_msg_cellular_status_decode(msg, &status);
cellular_status_s cellular_status{};
cellular_status.timestamp = hrt_absolute_time();
cellular_status.status = status.status;
cellular_status.failure_reason = status.failure_reason;
cellular_status.type = status.type;
cellular_status.quality = status.quality;
cellular_status.mcc = status.mcc;
cellular_status.mnc = status.mnc;
cellular_status.lac = status.lac;
_cellular_status_pub.publish(cellular_status);
}
void
MavlinkReceiver::handle_message_adsb_vehicle(mavlink_message_t *msg)
{
mavlink_adsb_vehicle_t adsb;
mavlink_msg_adsb_vehicle_decode(msg, &adsb);
transponder_report_s t{};
t.timestamp = hrt_absolute_time();
t.icao_address = adsb.ICAO_address;
t.lat = adsb.lat * 1e-7;
t.lon = adsb.lon * 1e-7;
t.altitude_type = adsb.altitude_type;
t.altitude = adsb.altitude / 1000.0f;
t.heading = adsb.heading / 100.0f / 180.0f * M_PI_F - M_PI_F;
t.hor_velocity = adsb.hor_velocity / 100.0f;
t.ver_velocity = adsb.ver_velocity / 100.0f;
memcpy(&t.callsign[0], &adsb.callsign[0], sizeof(t.callsign));
t.emitter_type = adsb.emitter_type;
t.tslc = adsb.tslc;
t.squawk = adsb.squawk;
t.flags = transponder_report_s::PX4_ADSB_FLAGS_RETRANSLATE; //Unset in receiver already broadcast its messages
if (adsb.flags & ADSB_FLAGS_VALID_COORDS) { t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_COORDS; }
if (adsb.flags & ADSB_FLAGS_VALID_ALTITUDE) { t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_ALTITUDE; }
if (adsb.flags & ADSB_FLAGS_VALID_HEADING) { t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_HEADING; }
if (adsb.flags & ADSB_FLAGS_VALID_VELOCITY) { t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_VELOCITY; }
if (adsb.flags & ADSB_FLAGS_VALID_CALLSIGN) { t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_CALLSIGN; }
if (adsb.flags & ADSB_FLAGS_VALID_SQUAWK) { t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_SQUAWK; }
//PX4_INFO("code: %d callsign: %s, vel: %8.4f, tslc: %d", (int)t.ICAO_address, t.callsign, (double)t.hor_velocity, (int)t.tslc);
_transponder_report_pub.publish(t);
}
void
MavlinkReceiver::handle_message_utm_global_position(mavlink_message_t *msg)
{
mavlink_utm_global_position_t utm_pos;
mavlink_msg_utm_global_position_decode(msg, &utm_pos);
px4_guid_t px4_guid;
#ifndef BOARD_HAS_NO_UUID
board_get_px4_guid(px4_guid);
#else
// TODO Fill ID with something reasonable
memset(&px4_guid[0], 0, sizeof(px4_guid));
#endif /* BOARD_HAS_NO_UUID */
//Ignore selfpublished UTM messages
if (sizeof(px4_guid) == sizeof(utm_pos.uas_id) && memcmp(px4_guid, utm_pos.uas_id, sizeof(px4_guid_t)) != 0) {
// Convert cm/s to m/s
float vx = utm_pos.vx / 100.0f;
float vy = utm_pos.vy / 100.0f;
float vz = utm_pos.vz / 100.0f;
transponder_report_s t{};
t.timestamp = hrt_absolute_time();
mav_array_memcpy(t.uas_id, utm_pos.uas_id, sizeof(px4_guid_t));
t.lat = utm_pos.lat * 1e-7;
t.lon = utm_pos.lon * 1e-7;
t.altitude = utm_pos.alt / 1000.0f;
t.altitude_type = ADSB_ALTITUDE_TYPE_GEOMETRIC;
// UTM_GLOBAL_POSIION uses NED (north, east, down) coordinates for velocity, in cm / s.
t.heading = atan2f(vy, vx);
t.hor_velocity = sqrtf(vy * vy + vx * vx);
t.ver_velocity = -vz;
// TODO: Callsign
// For now, set it to all 0s. This is a null-terminated string, so not explicitly giving it a null
// terminator could cause problems.
memset(&t.callsign[0], 0, sizeof(t.callsign));
t.emitter_type = ADSB_EMITTER_TYPE_UAV; // TODO: Is this correct?x2?
// The Mavlink docs do not specify what to do if tslc (time since last communication) is out of range of
// an 8-bit int, or if this is the first communication.
// Here, I assume that if this is the first communication, tslc = 0.
// If tslc > 255, then tslc = 255.
unsigned long time_passed = (t.timestamp - _last_utm_global_pos_com) / 1000000;
if (_last_utm_global_pos_com == 0) {
time_passed = 0;
} else if (time_passed > UINT8_MAX) {
time_passed = UINT8_MAX;
}
t.tslc = (uint8_t) time_passed;
t.flags = 0;
if (utm_pos.flags & UTM_DATA_AVAIL_FLAGS_POSITION_AVAILABLE) {
t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_COORDS;
}
if (utm_pos.flags & UTM_DATA_AVAIL_FLAGS_ALTITUDE_AVAILABLE) {
t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_ALTITUDE;
}
if (utm_pos.flags & UTM_DATA_AVAIL_FLAGS_HORIZONTAL_VELO_AVAILABLE) {
t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_HEADING;
t.flags |= transponder_report_s::PX4_ADSB_FLAGS_VALID_VELOCITY;
}
// Note: t.flags has deliberately NOT set VALID_CALLSIGN or VALID_SQUAWK, because UTM_GLOBAL_POSITION does not
// provide these.
_transponder_report_pub.publish(t);
_last_utm_global_pos_com = t.timestamp;
}
}
void
MavlinkReceiver::handle_message_collision(mavlink_message_t *msg)
{
mavlink_collision_t collision;
mavlink_msg_collision_decode(msg, &collision);
collision_report_s collision_report{};
collision_report.timestamp = hrt_absolute_time();
collision_report.src = collision.src;
collision_report.id = collision.id;
collision_report.action = collision.action;
collision_report.threat_level = collision.threat_level;
collision_report.time_to_minimum_delta = collision.time_to_minimum_delta;
collision_report.altitude_minimum_delta = collision.altitude_minimum_delta;
collision_report.horizontal_minimum_delta = collision.horizontal_minimum_delta;
_collision_report_pub.publish(collision_report);
}
void
MavlinkReceiver::handle_message_gps_rtcm_data(mavlink_message_t *msg)
{
mavlink_gps_rtcm_data_t gps_rtcm_data_msg;
mavlink_msg_gps_rtcm_data_decode(msg, &gps_rtcm_data_msg);
gps_inject_data_s gps_inject_data_topic{};
gps_inject_data_topic.len = math::min((int)sizeof(gps_rtcm_data_msg.data),
(int)sizeof(uint8_t) * gps_rtcm_data_msg.len);
gps_inject_data_topic.flags = gps_rtcm_data_msg.flags;
memcpy(gps_inject_data_topic.data, gps_rtcm_data_msg.data,
math::min((int)sizeof(gps_inject_data_topic.data), (int)sizeof(uint8_t) * gps_inject_data_topic.len));
_gps_inject_data_pub.publish(gps_inject_data_topic);
}
void
MavlinkReceiver::handle_message_hil_state_quaternion(mavlink_message_t *msg)
{
mavlink_hil_state_quaternion_t hil_state;
mavlink_msg_hil_state_quaternion_decode(msg, &hil_state);
const uint64_t timestamp = hrt_absolute_time();
/* airspeed */
{
airspeed_s airspeed{};
airspeed.timestamp = timestamp;
airspeed.indicated_airspeed_m_s = hil_state.ind_airspeed * 1e-2f;
airspeed.true_airspeed_m_s = hil_state.true_airspeed * 1e-2f;
_airspeed_pub.publish(airspeed);
}
/* attitude */
{
vehicle_attitude_s hil_attitude{};
hil_attitude.timestamp = timestamp;
matrix::Quatf q(hil_state.attitude_quaternion);
q.copyTo(hil_attitude.q);
_attitude_pub.publish(hil_attitude);
}
/* global position */
{
vehicle_global_position_s hil_global_pos{};
hil_global_pos.timestamp = timestamp;
hil_global_pos.lat = hil_state.lat / ((double)1e7);
hil_global_pos.lon = hil_state.lon / ((double)1e7);
hil_global_pos.alt = hil_state.alt / 1000.0f;
hil_global_pos.eph = 2.0f;
hil_global_pos.epv = 4.0f;
_global_pos_pub.publish(hil_global_pos);
}
/* local position */
{
double lat = hil_state.lat * 1e-7;
double lon = hil_state.lon * 1e-7;
if (!_hil_local_proj_inited) {
_hil_local_proj_inited = true;
_hil_local_alt0 = hil_state.alt / 1000.0f;
map_projection_init(&_hil_local_proj_ref, lat, lon);
}
float x = 0.0f;
float y = 0.0f;
map_projection_project(&_hil_local_proj_ref, lat, lon, &x, &y);
vehicle_local_position_s hil_local_pos{};
hil_local_pos.timestamp = timestamp;
hil_local_pos.ref_timestamp = _hil_local_proj_ref.timestamp;
hil_local_pos.ref_lat = math::radians(_hil_local_proj_ref.lat_rad);
hil_local_pos.ref_lon = math::radians(_hil_local_proj_ref.lon_rad);
hil_local_pos.ref_alt = _hil_local_alt0;
hil_local_pos.xy_valid = true;
hil_local_pos.z_valid = true;
hil_local_pos.v_xy_valid = true;
hil_local_pos.v_z_valid = true;
hil_local_pos.x = x;
hil_local_pos.y = y;
hil_local_pos.z = _hil_local_alt0 - hil_state.alt / 1000.0f;
hil_local_pos.vx = hil_state.vx / 100.0f;
hil_local_pos.vy = hil_state.vy / 100.0f;
hil_local_pos.vz = hil_state.vz / 100.0f;
matrix::Eulerf euler{matrix::Quatf(hil_state.attitude_quaternion)};
hil_local_pos.heading = euler.psi();
hil_local_pos.xy_global = true;
hil_local_pos.z_global = true;
hil_local_pos.vxy_max = INFINITY;
hil_local_pos.vz_max = INFINITY;
hil_local_pos.hagl_min = INFINITY;
hil_local_pos.hagl_max = INFINITY;
_local_pos_pub.publish(hil_local_pos);
}
/* accelerometer */
{
if (_px4_accel == nullptr) {
// 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
_px4_accel = new PX4Accelerometer(1310988);
if (_px4_accel == nullptr) {
PX4_ERR("PX4Accelerometer alloc failed");
}
}
if (_px4_accel != nullptr) {
// accel in mG
_px4_accel->set_scale(CONSTANTS_ONE_G / 1000.0f);
_px4_accel->update(timestamp, hil_state.xacc, hil_state.yacc, hil_state.zacc);
}
}
/* gyroscope */
{
if (_px4_gyro == nullptr) {
// 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
_px4_gyro = new PX4Gyroscope(1310988);
if (_px4_gyro == nullptr) {
PX4_ERR("PX4Gyroscope alloc failed");
}
}
if (_px4_gyro != nullptr) {
_px4_gyro->update(timestamp, hil_state.rollspeed, hil_state.pitchspeed, hil_state.yawspeed);
}
}
/* battery status */
{
battery_status_s hil_battery_status{};
hil_battery_status.timestamp = timestamp;
hil_battery_status.voltage_v = 11.1f;
hil_battery_status.voltage_filtered_v = 11.1f;
hil_battery_status.current_a = 10.0f;
hil_battery_status.discharged_mah = -1.0f;
_battery_pub.publish(hil_battery_status);
}
}
#if !defined(CONSTRAINED_FLASH)
void
MavlinkReceiver::handle_message_named_value_float(mavlink_message_t *msg)
{
mavlink_named_value_float_t debug_msg;
mavlink_msg_named_value_float_decode(msg, &debug_msg);
debug_key_value_s debug_topic{};
debug_topic.timestamp = hrt_absolute_time();
memcpy(debug_topic.key, debug_msg.name, sizeof(debug_topic.key));
debug_topic.key[sizeof(debug_topic.key) - 1] = '\0'; // enforce null termination
debug_topic.value = debug_msg.value;
_debug_key_value_pub.publish(debug_topic);
}
void
MavlinkReceiver::handle_message_debug(mavlink_message_t *msg)
{
mavlink_debug_t debug_msg;
mavlink_msg_debug_decode(msg, &debug_msg);
debug_value_s debug_topic{};
debug_topic.timestamp = hrt_absolute_time();
debug_topic.ind = debug_msg.ind;
debug_topic.value = debug_msg.value;
_debug_value_pub.publish(debug_topic);
}
void
MavlinkReceiver::handle_message_debug_vect(mavlink_message_t *msg)
{
mavlink_debug_vect_t debug_msg;
mavlink_msg_debug_vect_decode(msg, &debug_msg);
debug_vect_s debug_topic{};
debug_topic.timestamp = hrt_absolute_time();
memcpy(debug_topic.name, debug_msg.name, sizeof(debug_topic.name));
debug_topic.name[sizeof(debug_topic.name) - 1] = '\0'; // enforce null termination
debug_topic.x = debug_msg.x;
debug_topic.y = debug_msg.y;
debug_topic.z = debug_msg.z;
_debug_vect_pub.publish(debug_topic);
}
void
MavlinkReceiver::handle_message_debug_float_array(mavlink_message_t *msg)
{
mavlink_debug_float_array_t debug_msg;
mavlink_msg_debug_float_array_decode(msg, &debug_msg);
debug_array_s debug_topic{};
debug_topic.timestamp = hrt_absolute_time();
debug_topic.id = debug_msg.array_id;
memcpy(debug_topic.name, debug_msg.name, sizeof(debug_topic.name));
debug_topic.name[sizeof(debug_topic.name) - 1] = '\0'; // enforce null termination
for (size_t i = 0; i < debug_array_s::ARRAY_SIZE; i++) {
debug_topic.data[i] = debug_msg.data[i];
}
_debug_array_pub.publish(debug_topic);
}
#endif // !CONSTRAINED_FLASH
void
MavlinkReceiver::handle_message_onboard_computer_status(mavlink_message_t *msg)
{
mavlink_onboard_computer_status_t status_msg;
mavlink_msg_onboard_computer_status_decode(msg, &status_msg);
onboard_computer_status_s onboard_computer_status_topic{};
onboard_computer_status_topic.timestamp = hrt_absolute_time();
onboard_computer_status_topic.uptime = status_msg.uptime;
onboard_computer_status_topic.type = status_msg.type;
memcpy(onboard_computer_status_topic.cpu_cores, status_msg.cpu_cores, sizeof(status_msg.cpu_cores));
memcpy(onboard_computer_status_topic.cpu_combined, status_msg.cpu_combined, sizeof(status_msg.cpu_combined));
memcpy(onboard_computer_status_topic.gpu_cores, status_msg.gpu_cores, sizeof(status_msg.gpu_cores));
memcpy(onboard_computer_status_topic.gpu_combined, status_msg.gpu_combined, sizeof(status_msg.gpu_combined));
onboard_computer_status_topic.temperature_board = status_msg.temperature_board;
memcpy(onboard_computer_status_topic.temperature_core, status_msg.temperature_core,
sizeof(status_msg.temperature_core));
memcpy(onboard_computer_status_topic.fan_speed, status_msg.fan_speed, sizeof(status_msg.fan_speed));
onboard_computer_status_topic.ram_usage = status_msg.ram_usage;
onboard_computer_status_topic.ram_total = status_msg.ram_total;
memcpy(onboard_computer_status_topic.storage_type, status_msg.storage_type, sizeof(status_msg.storage_type));
memcpy(onboard_computer_status_topic.storage_usage, status_msg.storage_usage, sizeof(status_msg.storage_usage));
memcpy(onboard_computer_status_topic.storage_total, status_msg.storage_total, sizeof(status_msg.storage_total));
memcpy(onboard_computer_status_topic.link_type, status_msg.link_type, sizeof(status_msg.link_type));
memcpy(onboard_computer_status_topic.link_tx_rate, status_msg.link_tx_rate, sizeof(status_msg.link_tx_rate));
memcpy(onboard_computer_status_topic.link_rx_rate, status_msg.link_rx_rate, sizeof(status_msg.link_rx_rate));
memcpy(onboard_computer_status_topic.link_tx_max, status_msg.link_tx_max, sizeof(status_msg.link_tx_max));
memcpy(onboard_computer_status_topic.link_rx_max, status_msg.link_rx_max, sizeof(status_msg.link_rx_max));
_onboard_computer_status_pub.publish(onboard_computer_status_topic);
}
void MavlinkReceiver::handle_message_generator_status(mavlink_message_t *msg)
{
mavlink_generator_status_t status_msg;
mavlink_msg_generator_status_decode(msg, &status_msg);
generator_status_s generator_status{};
generator_status.timestamp = hrt_absolute_time();
generator_status.status = status_msg.status;
generator_status.battery_current = status_msg.battery_current;
generator_status.load_current = status_msg.load_current;
generator_status.power_generated = status_msg.power_generated;
generator_status.bus_voltage = status_msg.bus_voltage;
generator_status.bat_current_setpoint = status_msg.bat_current_setpoint;
generator_status.runtime = status_msg.runtime;
generator_status.time_until_maintenance = status_msg.time_until_maintenance;
generator_status.generator_speed = status_msg.generator_speed;
generator_status.rectifier_temperature = status_msg.rectifier_temperature;
generator_status.generator_temperature = status_msg.generator_temperature;
_generator_status_pub.publish(generator_status);
}
void MavlinkReceiver::handle_message_statustext(mavlink_message_t *msg)
{
if (msg->sysid == mavlink_system.sysid) {
// log message from the same system
mavlink_statustext_t statustext;
mavlink_msg_statustext_decode(msg, &statustext);
log_message_s log_message{};
log_message.severity = statustext.severity;
log_message.timestamp = hrt_absolute_time();
snprintf(log_message.text, sizeof(log_message.text),
"[mavlink: component %d] %." STRINGIFY(MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN) "s", msg->compid, statustext.text);
_log_message_pub.publish(log_message);
}
}
void MavlinkReceiver::CheckHeartbeats(const hrt_abstime &t, bool force)
{
// check HEARTBEATs for timeout
static constexpr uint64_t TIMEOUT = telemetry_status_s::HEARTBEAT_TIMEOUT_US;
if (t <= TIMEOUT) {
return;
}
if ((t >= _last_heartbeat_check + (TIMEOUT / 2)) || force) {
telemetry_status_s &tstatus = _mavlink->telemetry_status();
tstatus.heartbeat_type_antenna_tracker = (t <= TIMEOUT + _heartbeat_type_antenna_tracker);
tstatus.heartbeat_type_gcs = (t <= TIMEOUT + _heartbeat_type_gcs);
tstatus.heartbeat_type_onboard_controller = (t <= TIMEOUT + _heartbeat_type_onboard_controller);
tstatus.heartbeat_type_gimbal = (t <= TIMEOUT + _heartbeat_type_gimbal);
tstatus.heartbeat_type_adsb = (t <= TIMEOUT + _heartbeat_type_adsb);
tstatus.heartbeat_type_camera = (t <= TIMEOUT + _heartbeat_type_camera);
tstatus.heartbeat_component_telemetry_radio = (t <= TIMEOUT + _heartbeat_component_telemetry_radio);
tstatus.heartbeat_component_log = (t <= TIMEOUT + _heartbeat_component_log);
tstatus.heartbeat_component_osd = (t <= TIMEOUT + _heartbeat_component_osd);
tstatus.heartbeat_component_obstacle_avoidance = (t <= TIMEOUT + _heartbeat_component_obstacle_avoidance);
tstatus.heartbeat_component_vio = (t <= TIMEOUT + _heartbeat_component_visual_inertial_odometry);
tstatus.heartbeat_component_pairing_manager = (t <= TIMEOUT + _heartbeat_component_pairing_manager);
tstatus.heartbeat_component_udp_bridge = (t <= TIMEOUT + _heartbeat_component_udp_bridge);
tstatus.heartbeat_component_uart_bridge = (t <= TIMEOUT + _heartbeat_component_uart_bridge);
_mavlink->telemetry_status_updated();
_last_heartbeat_check = t;
}
}
/**
* Receive data from UART/UDP
*/
void
MavlinkReceiver::Run()
{
/* set thread name */
{
char thread_name[17];
snprintf(thread_name, sizeof(thread_name), "mavlink_rcv_if%d", _mavlink->get_instance_id());
px4_prctl(PR_SET_NAME, thread_name, px4_getpid());
}
// make sure mavlink app has booted before we start processing anything (parameter sync, etc)
while (!_mavlink->boot_complete()) {
if (hrt_elapsed_time(&_mavlink->get_first_start_time()) > 20_s) {
PX4_ERR("system boot did not complete in 20 seconds");
_mavlink->set_boot_complete();
}
px4_usleep(100000);
}
// poll timeout in ms. Also defines the max update frequency of the mission & param manager, etc.
const int timeout = 10;
#if defined(__PX4_POSIX)
/* 1500 is the Wifi MTU, so we make sure to fit a full packet */
uint8_t buf[1600 * 5];
#elif defined(CONFIG_NET)
/* 1500 is the Wifi MTU, so we make sure to fit a full packet */
uint8_t buf[1000];
#else
/* the serial port buffers internally as well, we just need to fit a small chunk */
uint8_t buf[64];
#endif
mavlink_message_t msg;
struct pollfd fds[1] = {};
if (_mavlink->get_protocol() == Protocol::SERIAL) {
fds[0].fd = _mavlink->get_uart_fd();
fds[0].events = POLLIN;
}
#if defined(MAVLINK_UDP)
struct sockaddr_in srcaddr = {};
socklen_t addrlen = sizeof(srcaddr);
if (_mavlink->get_protocol() == Protocol::UDP) {
fds[0].fd = _mavlink->get_socket_fd();
fds[0].events = POLLIN;
}
#endif // MAVLINK_UDP
ssize_t nread = 0;
hrt_abstime last_send_update = 0;
while (!_mavlink->_task_should_exit) {
// check for parameter updates
if (_parameter_update_sub.updated()) {
// clear update
parameter_update_s pupdate;
_parameter_update_sub.copy(&pupdate);
// update parameters from storage
updateParams();
}
int ret = poll(&fds[0], 1, timeout);
if (ret > 0) {
if (_mavlink->get_protocol() == Protocol::SERIAL) {
/* non-blocking read. read may return negative values */
nread = ::read(fds[0].fd, buf, sizeof(buf));
if (nread == -1 && errno == ENOTCONN) { // Not connected (can happen for USB)
usleep(100000);
}
}
#if defined(MAVLINK_UDP)
else if (_mavlink->get_protocol() == Protocol::UDP) {
if (fds[0].revents & POLLIN) {
nread = recvfrom(_mavlink->get_socket_fd(), buf, sizeof(buf), 0, (struct sockaddr *)&srcaddr, &addrlen);
}
struct sockaddr_in &srcaddr_last = _mavlink->get_client_source_address();
int localhost = (127 << 24) + 1;
if (!_mavlink->get_client_source_initialized()) {
// set the address either if localhost or if 3 seconds have passed
// this ensures that a GCS running on localhost can get a hold of
// the system within the first N seconds
hrt_abstime stime = _mavlink->get_start_time();
if ((stime != 0 && (hrt_elapsed_time(&stime) > 3_s))
|| (srcaddr_last.sin_addr.s_addr == htonl(localhost))) {
srcaddr_last.sin_addr.s_addr = srcaddr.sin_addr.s_addr;
srcaddr_last.sin_port = srcaddr.sin_port;
_mavlink->set_client_source_initialized();
PX4_INFO("partner IP: %s", inet_ntoa(srcaddr.sin_addr));
}
}
}
// only start accepting messages on UDP once we're sure who we talk to
if (_mavlink->get_protocol() != Protocol::UDP || _mavlink->get_client_source_initialized()) {
#endif // MAVLINK_UDP
/* if read failed, this loop won't execute */
for (ssize_t i = 0; i < nread; i++) {
if (mavlink_parse_char(_mavlink->get_channel(), buf[i], &msg, &_status)) {
_total_received_counter++;
/* check if we received version 2 and request a switch. */
if (!(_mavlink->get_status()->flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1)) {
/* this will only switch to proto version 2 if allowed in settings */
_mavlink->set_proto_version(2);
}
/* handle generic messages and commands */
handle_message(&msg);
/* handle packet with mission manager */
_mission_manager.handle_message(&msg);
/* handle packet with parameter component */
_parameters_manager.handle_message(&msg);
if (_mavlink->ftp_enabled()) {
/* handle packet with ftp component */
_mavlink_ftp.handle_message(&msg);
}
/* handle packet with log component */
_mavlink_log_handler.handle_message(&msg);
/* handle packet with timesync component */
_mavlink_timesync.handle_message(&msg);
/* handle packet with parent object */
_mavlink->handle_message(&msg);
// calculate lost messages for this system id
bool px4_sysid_index_found = false;
int px4_sysid_index = 0;
if (msg.sysid != mavlink_system.sysid) {
for (int sys_id = 1; sys_id < MAX_REMOTE_SYSTEM_IDS; sys_id++) {
if (_system_id_map[sys_id] == msg.sysid) {
// slot found
px4_sysid_index_found = true;
px4_sysid_index = sys_id;
break;
}
}
// otherwise record newly seen system id in first available slot
if (!px4_sysid_index_found) {
for (int sys_id = 1; sys_id < MAX_REMOTE_SYSTEM_IDS; sys_id++) {
if (_system_id_map[sys_id] == 0) {
// slot available
px4_sysid_index_found = true;
px4_sysid_index = sys_id;
_system_id_map[sys_id] = msg.sysid;
break;
}
}
}
if (!px4_sysid_index_found) {
PX4_ERR("not enough system id slots (%d)", MAX_REMOTE_SYSTEM_IDS);
}
} else {
px4_sysid_index_found = true;
}
// find PX4 component id
uint8_t px4_comp_id = 0;
bool px4_comp_id_found = false;
for (int id = 0; id < COMP_ID_MAX; id++) {
if (supported_component_map[id] == msg.compid) {
px4_comp_id = id;
px4_comp_id_found = true;
break;
}
}
if (!px4_comp_id_found) {
PX4_WARN("unsupported component id, msgid: %d, sysid: %d compid: %d", msg.msgid, msg.sysid, msg.compid);
}
if (px4_comp_id_found && px4_sysid_index_found) {
// Increase receive counter
_total_received_supported_counter++;
uint8_t last_seq = _last_index[px4_sysid_index][px4_comp_id];
uint8_t expected_seq = last_seq + 1;
// Determine what the next expected sequence number is, accounting for
// never having seen a message for this system/component pair.
if (!_sys_comp_present[px4_sysid_index][px4_comp_id]) {
_sys_comp_present[px4_sysid_index][px4_comp_id] = true;
last_seq = msg.seq;
expected_seq = msg.seq;
}
// And if we didn't encounter that sequence number, record the error
if (msg.seq != expected_seq) {
int lost_messages = 0;
// Account for overflow during packet loss
if (msg.seq < expected_seq) {
lost_messages = (msg.seq + 255) - expected_seq;
} else {
lost_messages = msg.seq - expected_seq;
}
// Log how many were lost
_total_lost_counter += lost_messages;
}
// And update the last sequence number for this system/component pair
_last_index[px4_sysid_index][px4_comp_id] = msg.seq;
// Calculate new loss ratio
const float total_sent = _total_received_supported_counter + _total_lost_counter;
float rx_loss_percent = (_total_lost_counter / total_sent) * 100.f;
_running_loss_percent = (rx_loss_percent * 0.5f) + (_running_loss_percent * 0.5f);
}
}
}
/* count received bytes (nread will be -1 on read error) */
if (nread > 0) {
_mavlink->count_rxbytes(nread);
telemetry_status_s &tstatus = _mavlink->telemetry_status();
tstatus.rx_message_count = _total_received_counter;
tstatus.rx_message_count_supported = _total_received_supported_counter;
tstatus.rx_message_lost_count = _total_lost_counter;
tstatus.rx_message_lost_rate = _running_loss_percent;
if (_mavlink_status_last_buffer_overrun != _status.buffer_overrun) {
tstatus.rx_buffer_overruns++;
_mavlink_status_last_buffer_overrun = _status.buffer_overrun;
}
if (_mavlink_status_last_parse_error != _status.parse_error) {
tstatus.rx_parse_errors++;
_mavlink_status_last_parse_error = _status.parse_error;
}
if (_mavlink_status_last_packet_rx_drop_count != _status.packet_rx_drop_count) {
tstatus.rx_packet_drop_count++;
_mavlink_status_last_packet_rx_drop_count = _status.packet_rx_drop_count;
}
}
#if defined(MAVLINK_UDP)
}
#endif // MAVLINK_UDP
} else if (ret == -1) {
usleep(10000);
}
const hrt_abstime t = hrt_absolute_time();
CheckHeartbeats(t);
if (t - last_send_update > timeout * 1000) {
_mission_manager.check_active_mission();
_mission_manager.send();
_parameters_manager.send();
if (_mavlink->ftp_enabled()) {
_mavlink_ftp.send();
}
_mavlink_log_handler.send();
last_send_update = t;
}
if (_tune_publisher != nullptr) {
_tune_publisher->publish_next_tune(t);
}
}
}
void *
MavlinkReceiver::start_helper(void *context)
{
MavlinkReceiver rcv{(Mavlink *)context};
rcv.Run();
return nullptr;
}
void
MavlinkReceiver::receive_start(pthread_t *thread, Mavlink *parent)
{
pthread_attr_t receiveloop_attr;
pthread_attr_init(&receiveloop_attr);
struct sched_param param;
(void)pthread_attr_getschedparam(&receiveloop_attr, ¶m);
param.sched_priority = SCHED_PRIORITY_MAX - 80;
(void)pthread_attr_setschedparam(&receiveloop_attr, ¶m);
pthread_attr_setstacksize(&receiveloop_attr,
PX4_STACK_ADJUSTED(sizeof(MavlinkReceiver) + 2840 + MAVLINK_RECEIVER_NET_ADDED_STACK));
pthread_create(thread, &receiveloop_attr, MavlinkReceiver::start_helper, (void *)parent);
pthread_attr_destroy(&receiveloop_attr);
}
float
MavlinkReceiver::get_offb_cruising_speed()
{
vehicle_status_s vehicle_status{};
_vehicle_status_sub.copy(&vehicle_status);
if (vehicle_status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING && _offb_cruising_speed_mc > 0.0f) {
return _offb_cruising_speed_mc;
} else if (vehicle_status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING && _offb_cruising_speed_fw > 0.0f) {
return _offb_cruising_speed_fw;
} else {
return -1.0f;
}
}
void
MavlinkReceiver::set_offb_cruising_speed(float speed)
{
vehicle_status_s vehicle_status{};
_vehicle_status_sub.copy(&vehicle_status);
if (vehicle_status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING) {
_offb_cruising_speed_mc = speed;
} else {
_offb_cruising_speed_fw = speed;
}
}
|
;
; Copyright (C) 2019 Intel Corporation. All rights reserved.
; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
;
.386
.model flat
.code
_invokeNative PROC
push ebp
mov ebp,esp
mov ecx, [ebp+16] ; ecx = argc */
mov edx, [ebp+12] ; edx = argv */
test ecx, ecx
jz skip_push_args ; if ecx == 0, skip pushing arguments */
lea edx, [edx+ecx*4-4] ; edx = edx + ecx * 4 - 4 */
sub edx,esp ; edx = edx - esp */
loop_push:
push [esp+edx]
loop loop_push ; loop ecx counts */
skip_push_args:
mov edx, [ebp+8] ; edx = func_ptr */
call edx
leave
ret
_invokeNative ENDP
END |
; A294970: Numerators of the partial sums for the Catalan constant A006752: Sum_{k=0..n} ((-1)^k)/(2*k+1)^2, n >= 0.
; Submitted by Christian Krause
; 1,8,209,10016,91369,10956424,1863641881,1854623872,538015351033,193637145687688,194117166024913,102476291858462752,2566386635039604121,23062916917686411464,19421109407275720721849,18642496069331249273291264,18661195480065271610416889,18644572085543352977657864,25544782843398200551543421441,25526454212104235663244470816,42937847378745340745016659342321,79345217140479094317168157867000904,79388006801494454461345825067051129,175281457960945145613153151493014238336
mul $0,2
mov $1,1
lpb $0
mov $2,$0
sub $0,2
add $2,1
pow $2,2
mul $3,$2
add $3,$1
mul $1,$2
mul $3,-1
lpe
add $1,$3
gcd $3,$1
div $1,$3
mov $0,$1
|
; A088689: Jacobsthal numbers modulo 3.
; 0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1,0,2,2,0,1,1
mov $1,$0
gcd $0,2
mul $1,$0
mod $1,3
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Image.hpp>
# include <Siv3D/ImageFormat.hpp>
namespace s3d
{
class ImageFormat_PPM : public IImageFormat
{
public:
ImageFormat format() const override;
const Array<String>& possibleExtexsions() const override;
bool isHeader(const uint8(&bytes)[16]) const override;
Size getSize(const IReader& reader) const override;
Image decode(IReader& reader) const override;
bool encode(const Image& image, IWriter& writer) const override;
bool encode(const Image& image, IWriter& writer, PPMType format) const;
bool save(const Image& image, const FilePath& path) const override;
bool save(const Image& image, const FilePath& path, PPMType format) const;
};
}
|
; Copyright (c) Teemu Suutari
bits 32
[section .text.onekpaq.cfunc32]
%ifidn __OUTPUT_FORMAT__, elf32
global onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_shift
onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_shift: equ onekpaq_decompressor.shift
global onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]
onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]:
%else
global _onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_shift
_onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_shift: equ onekpaq_decompressor.shift
global _onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]
_onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]:
%endif
pushad
mov ebx,[byte esp+32+4]
mov edi,[byte esp+32+8]
int3
;%define DEBUG_BUILD
%include "onekpaq_decompressor32.asm"
popad
ret
%ifidn __OUTPUT_FORMAT__, elf32
global onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_end
onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_end:
%else
global _onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_end
_onekpaq_decompressor_mode%[ONEKPAQ_DECOMPRESSOR_MODE]_end:
%endif
__SECT__
;; ---------------------------------------------------------------------------
|
;
; Sharp OZ family functions
;
; ported from the OZ-7xx SDK by by Alexander R. Pruss
; by Stefano Bodrato - Oct. 2003
;
;
; gfx functions
;
; put byte into the display at offset
;
; void ozdisplayputbyte(int offset, char byte);
;
;
; ------
; $Id: ozdisplayputbyte.asm,v 1.2 2015/01/19 01:33:01 pauloscustodio Exp $
;
PUBLIC ozdisplayputbyte
EXTERN ozactivepage
ozdisplayputbyte:
ld c,3
in e,(c)
inc c
in d,(c)
ld hl,(ozactivepage)
out (c),h
dec c
out (c),l
pop hl ;; return address
exx
;pop hl ;; offset
;pop bc ;; value
pop bc ;; offset
pop hl ;; value
ld a,h
add a,0a0h
ld h,a
ld (hl),c
push bc
push hl
exx
out (c),e
inc c
out (c),d
jp (hl)
|
#if !defined(h_ebd0ee89_622d_4af1_9a9d_d0e057debe86)
#define h_ebd0ee89_622d_4af1_9a9d_d0e057debe86
#include <log4cpp/LayoutAppender.hh>
#include <log4cpp/TriggeringEventEvaluator.hh>
#include <list>
#include <memory>
LOG4CPP_NS_BEGIN
class LOG4CPP_EXPORT BufferingAppender : public LayoutAppender
{
public:
BufferingAppender(const std::string name, unsigned long max_size, std::auto_ptr<Appender> sink,
std::auto_ptr<TriggeringEventEvaluator> evaluator);
virtual void close() { sink_->close(); }
bool getLossy() const { return lossy_; }
void setLossy(bool lossy) { lossy_ = lossy; }
protected:
virtual void _append(const LoggingEvent& event);
private:
typedef std::list<LoggingEvent> queue_t;
queue_t queue_;
unsigned long max_size_;
std::auto_ptr<Appender> sink_;
std::auto_ptr<TriggeringEventEvaluator> evaluator_;
bool lossy_;
void dump();
};
LOG4CPP_NS_END
#endif // h_ebd0ee89_622d_4af1_9a9d_d0e057debe86
|
SECTION rodata_font
SECTION rodata_font_fzx
PUBLIC _ff_dkud4_Font07
_ff_dkud4_Font07:
BINARY "font/fzx/fonts/dkud4/Font07/font07.fzx"
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
namespace armnn
{
class TensorShape;
class TensorInfo;
class Tensor;
class ConstTensor;
}
|
; A001860: Number of series-reduced planted trees with n+9 nodes and 4 internal nodes.
; 0,3,12,29,57,99,157,234,333,456,606,786,998,1245,1530,1855,2223,2637,3099,3612,4179,4802,5484,6228,7036,7911,8856,9873,10965,12135,13385,14718,16137,17644,19242,20934,22722,24609,26598,28691,30891,33201,35623,38160,40815,43590,46488,49512,52664,55947,59364,62917,66609,70443,74421,78546,82821,87248,91830,96570,101470,106533,111762,117159,122727,128469,134387,140484,146763,153226,159876,166716,173748,180975,188400,196025,203853,211887,220129,228582,237249,246132,255234,264558,274106,283881,293886,304123,314595,325305,336255,347448,358887,370574,382512,394704,407152,419859,432828,446061,459561,473331,487373,501690,516285,531160,546318,561762,577494,593517,609834,626447,643359,660573,678091,695916,714051,732498,751260,770340,789740,809463,829512,849889,870597,891639,913017,934734,956793,979196,1001946,1025046,1048498,1072305,1096470,1120995,1145883,1171137,1196759,1222752,1249119,1275862,1302984,1330488,1358376,1386651,1415316,1444373,1473825,1503675,1533925,1564578,1595637,1627104,1658982,1691274,1723982,1757109,1790658,1824631,1859031,1893861,1929123,1964820,2000955,2037530,2074548,2112012,2149924,2188287,2227104,2266377,2306109,2346303,2386961,2428086,2469681,2511748,2554290,2597310,2640810,2684793,2729262,2774219,2819667,2865609,2912047,2958984,3006423,3054366,3102816,3151776,3201248,3251235,3301740,3352765,3404313,3456387,3508989,3562122,3615789,3669992,3724734,3780018,3835846,3892221,3949146,4006623,4064655,4123245,4182395,4242108,4302387,4363234,4424652,4486644,4549212,4612359,4676088,4740401,4805301,4870791,4936873,5003550,5070825,5138700,5207178,5276262,5345954,5416257,5487174,5558707,5630859,5703633,5777031,5851056,5925711,6000998,6076920,6153480,6230680,6308523,6387012,6466149,6545937,6626379,6707477,6789234,6871653,6954736
mov $12,$0
mov $14,$0
lpb $14
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
lpb $11
mov $0,$9
sub $11,1
sub $0,$11
mul $0,8
mov $1,2
add $1,$0
div $1,3
add $10,$1
lpe
add $13,$10
lpe
mov $1,$13
|
.size 8000
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
xor a, a
ldff(24), a
ldff(25), a
ldff(26), a
ld a, 80
ldff(26), a
ld b, 05
ld c, 07
lwaitbegin:
dec b
jrnz lwaitbegin
dec c
jrnz lwaitbegin
nop
nop
nop
nop
ld a, 20
ldff(10), a
ld a, f0
ldff(12), a
ld a, 00
ldff(13), a
ld a, 87
ldff(14), a
ld b, f2
ld c, 10
lwait:
dec b
jrnz lwait
dec c
jrnz lwait
nop
nop
nop
nop
xor a, a
ldff(10), a
ld a, 77
ldff(24), a
ld a, 11
ldff(25), a
limbo:
jr limbo
|
; A033402: [ 82/n ].
; 82,41,27,20,16,13,11,10,9,8,7,6,6,5,5,5,4,4,4,4,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,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,0,0,0,0,0,0,0,0,0
add $0,1
mov $1,82
div $1,$0
|
; A204427: Infinite matrix: f(i,j)=(2i+j+2 mod 3), read by antidiagonals.
; 2,0,1,1,2,0,2,0,1,2,0,1,2,0,1,1,2,0,1,2,0,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,1,2,0,1,2,0,1,2,0,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,1,2,0,1,2,0,1,2,0,1,2,0,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1
seq $0,131421 ; Triangle read by rows (n>=1, 1<=k<=n): T(n,k) = 2*(n+k) - 3.
mul $0,56
mod $0,3
|
;
; Plot pixel at (x,y) coordinate.
SECTION code_clib
PUBLIC w_plotpixel
EXTERN __fp1100_mode
defc NEEDplot = 1
.w_plotpixel
ld a,(__fp1100_mode)
bit 1,a
jr z,hires
ld h,l
ld l,e
INCLUDE "gfx/gencon/pixel.inc"
hires:
INCLUDE "w_pixel.inc"
|
.MODEL SMALL
.STACK 100H
.DATA
A DB "ODD$"
B DB "EVEN$"
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
MOV AH,1
INT 21H
MOV BL,AL
CMP BL,'1'
JE ODD
CMP BL,'3'
JE ODD
CMP BL, '2'
JE EVEN
CMP BL,'4'
JE EVEN
ODD:
MOV AH,9
MOV DL, OFFSET A
INT 21H
JMP EXIT
EVEN:
MOV AH,9
MOV DL,OFFSET B
INT 21H
JMP EXIT
EXIT:
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN |
; Palate flip (PAL OPCode Test) by Refraction
;
; r0 = Scratchpad
; r1 = Scratchpad
; r2 = Scratchpad
; r3 = Player Lives
; r4 = Scratchpad
; r5 = General Purpose (Random number destination)
; r6 = Frame counter
; r7 = Spawn Timer
; r8 = memory address for current data (sprite/position information)
; r9 = current alien
; ra = current sprite X-Axis
; rb = current sprite Y-Axis
; rc = current ship position (X Axis only, ship doesnt move up :P)
; rd = player score
; re = current level
; rf = aliens killed
; base memory location for alien information = alieninfo
; each 32 bit location contains
; status=lower 16bit lower byte, X=upper 16bit upper byte, Y upper 16bit lower byte
; status = (0 = not active/available 1-2 = active 3-6 = exploding frame)
importbin bullet.bin 0 32 spr_bullet ;Bullet Sprite 8x8
importbin alien.bin 0 256 spr_alien ;Alien Sprite Animation 16x32
importbin aliendie.bin 0 512 spr_aliendie ;Alien Death Sprite Animation 16x64
importbin ship.bin 0 128 spr_ship ;Ship Sprite 16x16
importbin shipdie.bin 0 512 spr_shipdie ;Ship Death Sprite Animation 16x64
importbin original.bin 0 48 pallate ;Original C16 palatte
importbin font.bin 0 3072 font ;Font data
importbin logo.bin 0 2500 logo ;kickass logo!
:init
ldi r6, 0 ;reset frame counter
ldi r3, 3 ;start with 3 lives, customary i guess :P
ldi re, 1 ;start on level 1, customary also i guess :P
ldi rd, 0 ;score reset to 0
stm r3, player_lives
stm re, current_level
stm rd, current_score
:startmenu
vblnk
cls
ldm r0, #FFF0
tsti r0, #20 ; AND check "Start" bit
jnz newgamestart
spr #3232
ldi rb, 95 ; Y = 95
ldi ra, 110 ; X = 110
ldi r8, logo ;awesomeness right here
drw ra, rb, r8 ;drawing of awesomeness
addi r6, 1 ;frame count
cmpi r6, 20 ;frame count
jbe startmenu
ldi rb, 200 ; Y = 116 (half way down)
ldi ra, 110 ; X = 110 (half way across)
ldi r8, press_start_ascii
call draw_string
cmpi r6, 40 ;frame count
jbe startmenu
jmp init
:newgamestart
ldi r7, 120 ;set spawn speed
ldi r8, spawn_timer ;point to spawn timer
stm r7, r8 ;set the spawn timer
:showlevel
ldi r6, 0 ;reset frame counter
ldi r4, 512 ;zero amount
addi r4, font ;Apply offset to font address
:showlevel_loop
vblnk
cls
ldi rb, 116 ; Y = 116 (half way down)
ldi ra, 120 ; X = 120 (half way across)
ldi r8, player_level_ascii
call draw_string
spr #0804 ;Set 8x8 pixel sprites
ldm r1, current_level ;Load characted from memory
call counter_under_hundred
addi r6, 1 ;add a frame
cmpi r6, 180 ; wait 3 seconds before restart
jnz showlevel_loop
:start
ldi r6, 0 ;frame counter to zero
ldi rc, 160 ;ship always starts in the middle, cos it always has done xD
ldi r9, 0 ;set current alien to zero
ldi r0, 0 ;clear reg for alien clearing
ldi r8, alieninfo ;grab current alien status mem location
clear_aliens:
stm r0, r8 ;Store inactive in current alien status
addi r8, 6 ;Move memory pointer to next alien
addi r9, 1 ;Increment which alien we're dealing with
cmpi r9, 15 ;All possible aliens delt with?
jnz clear_aliens ;they arent so lets try the next one
ldi r8, bulletfired ;grab bullet status mem location
stm r0, r8 ;Store not fired in bullet status
bgc 0
:main_loop
cls
call handle_statusbar
call handle_controller
call handle_ship
call handle_bullet
call handle_aliens
:main_loop_difficulty_inc
;Difficulty check
mov r2, re ;grab current level
muli r2, 10 ;multiply it by 10 to find target score
cmp r2, rd ; compare multiplied score with player score
jnz main_loop_death
cmpi re, 12
jae main_loop_death
addi re, 1 ;increase difficulty!
stm re, current_level
subi r7, 10 ;lower spawn timer
ldi r6, 0 ;reset the frame counter
stm r7, spawn_timer ;set the spawn timer
jmp showlevel
:main_loop_death
cmpi rc, #5000 ;check if we've exploded
jae game_ended
vblnk
addi r6, 1 ;add a frame
jmp main_loop
:game_ended
subi r3, 1
stm r3, player_lives
ldi r6, 0 ;reset frame counter
:game_end_loop
vblnk
addi r6, 1 ;add a frame
cmpi r6, 60 ; wait 3 seconds before restart
jnz game_end_loop
cmpi r3, 0
jnz newgamestart
:game_over_screen
ldi r6, 0 ;reset frame counter
:game_over_loop
vblnk
cls
ldi rb, 116 ; Y = 116 (half way down)
ldi ra, 80 ; X = 120 (half way across)
ldi r8, game_over_ascii
call draw_string
ldi rb, 130 ; Y = 116 (half way down)
ldi ra, 80 ; X = 80 (half way across)
ldi r8, you_scored_ascii
call draw_string
ldi r8, current_score
call draw_counter_numbers
drw ra, rb, r4 ;Draw 8x8 character on the set coordinates
addi r6, 1 ;add a frame
cmpi r6, 180 ; wait 3 seconds before restart
jz init
jmp game_over_loop
;Stolen and modified from Shendo's Music Maker
:draw_string ;Draw string on screen
spr #0804 ;Set 8x8 pixel sprites
ldm r1, r8 ;Load characted from memory
andi r1, #FF ;Only the lo byte is needed
cmpi r1, 255 ;Remove terminator
jz returnsub ;Terminator reached, break subroutine
subi r1, 32
muli r1, 32 ;Each character is 32 bytes long
addi r1, font ;Apply offset to font address
drw ra, rb, r1 ;Draw 8x8 character on the set coordinates
addi r8, 1 ;Increase memory offset
addi ra, 9 ;Increase X coordinate
jmp draw_string ;loop around, we have text left!
:draw_counter_numbers ;Draw numbers on screen
spr #0804 ;Set 8x8 pixel sprites
ldm r1, r8 ;Load characted from memory
ldi r4, 512 ;zero amount
addi r4, font ;Apply offset to font address
cmpi r1, 1000
jb counter_under_thousandz
mov r2, r1 ;copy the number
divi r2, 1000 ;divide it by 1000 to get number of 1000's
muli r2, 1000 ;multiply it backup
sub r1, r2
divi r2, 1000
addi r2, 16
muli r2, 32 ;Each character is 32 bytes long
addi r2, font ;Apply offset to font address
drw ra, rb, r2 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
jmp counter_under_thousand
:counter_under_thousandz
drw ra, rb, r4 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
:counter_under_thousand
cmpi r1, 100
jb counter_under_hundredz
mov r2, r1 ;copy the number
divi r2, 100 ;divide it by 10 to get number of 10's
muli r2, 100 ;multiply it backup
sub r1, r2
divi r2, 100
addi r2, 16
muli r2, 32 ;Each character is 32 bytes long
addi r2, font ;Apply offset to font address
drw ra, rb, r2 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
jmp counter_under_hundred
:counter_under_hundredz
drw ra, rb, r4 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
:counter_under_hundred
cmpi r1, 10
jb counter_under_tenz
mov r2, r1 ;copy the number
divi r2, 10 ;divide it by 10 to get number of 10's
muli r2, 10 ;multiply it backup
sub r1, r2 ;take that value off the original amount
divi r2, 10
addi r2, 16
muli r2, 32 ;Each character is 32 bytes long
addi r2, font ;Apply offset to font address
drw ra, rb, r2 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
jmp counter_under_ten
:counter_under_tenz
drw ra, rb, r4 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
:counter_under_ten
addi r1, 16
muli r1, 32 ;Each character is 32 bytes long
addi r1, font ;Apply offset to font address
drw ra, rb, r1 ;Draw 8x8 character on the set coordinates
addi ra, 9 ;Increase X coordinate
ret
;Subroutines
:handle_statusbar
ldi rb, 2 ; Y = 2 (Very top mild offset)
ldi ra, 2 ; X = 0 (Far left)
ldi r8, player_score_ascii
call draw_string
ldi r8, current_score
call draw_counter_numbers
drw ra, rb, r4 ;Draw 8x8 character on the set coordinates
ldi ra, 120 ; X = 120 (Half way along)
ldi r8, player_level_ascii
call draw_string
ldm r1, current_level ;Load characted from memory
call counter_under_hundred
ldi ra, 240 ; X = 240 (most way along)
ldi r8, player_lives_ascii
call draw_string
ldm r1, player_lives ;Load characted from memory
call counter_under_hundred
ret
:handle_controller
ldm r0, #FFF0
tsti r0, 4 ; AND check "left" bit
jnz move_left
tsti r0, 8 ; AND check "right" bit
jnz move_right
tsti r0, 64 ;AND check "A button" bit
jnz fire_bullet
ret
:handle_ship
call draw_ship
ret
:handle_aliens
call spawn_alien
call draw_alien
call move_alien
ret
:handle_bullet
ldm r0, bulletfired
cmpi r0, 1 ;check if a bullet was fired
jnz returnsub ;it wasnt so escape
spr #0804 ;width is half of real width 8x8
ldm ra, bulletposx ;load in bullet x-axis
ldm rb, bulletposy ;load in bullet y-axis
subi rb, 8 ;move it up the screen 4 pixels
stm rb, bulletposy ;store new y position
ldi r8, spr_bullet ;point to bullet sprite
drw ra, rb, r8 ; ra=x, rb=y, r8=sprite memory location
;bullet collision handled on alien
cmpi rb, 10 ;check if bullet went off the top of the screen
ja bullet_sound
ldi r0, 0
stm r0, bulletfired ;it did so clear it and store status
:bullet_sound
ldm r0, bullet_fire_snd ;Load in the ship death frequency
cmpi r0, #100
jbe returnsub
sng #00, #61F0 ;set up the noise sound
ldi r1, bullet_fire_snd ; Point to the sound for playback
snp r1, 30 ;Play it for 20ms
subi r0, 200 ;reduce frequency.
stm r0, bullet_fire_snd ;save the new frequency
ret
:fire_bullet
ldm r0, bulletfired
cmpi r0, 1 ;check if a bullet was fired
jz returnsub
ldi r0, 1 ;it hasnt so lets set it as fired
stm r0, bulletfired
ldi r0, 224 ;set bullet to go from current ship height + 8px
stm r0, bulletposy
mov r0, rc ;get current ship pos
andi r0, #fff ;filter out the "crashed" part :P tho this shouldnt happen anyway
addi r0, 4 ;make it look like its coming from the middle of the ship
stm r0, bulletposx
sng #00, #61F0 ;set up the noise sound
ldi r0, #05DC ;Load in the ship death frequency
ldi r1, bullet_fire_snd ; Point to the sound for playback
snp r1, 20 ;Play it for 20ms
subi r0, 100 ;reduce frequency.
stm r0, bullet_fire_snd ;save the new frequency
ret
:move_left
mov r0, rc
andi r0, #fff
cmpi r0, 0 ;make sure were not at far left as we can go.
jz returnsub ;if we are, dont move!
subi rc, 4 ; move left 1 pixel
ret
:move_right
mov r0, rc
andi r0, #fff
cmpi r0, 304 ;make sure were not at far right as we can go.
jz returnsub ;if we are, dont move!
addi rc, 4 ; move right 1 pixel
ret
:get_status
ldi r8 alieninfo ;grab current alien status mem location
ldi r4, 6 ;alien multiplier
mul r9, r4, r4 ;multiply "current alien"
add r8, r4 ;add the offset to alien address
ldm r4, r8 ;read it in
ret
:get_coords
ldi r8 alieninfo ;grab current alien status mem location
ldi r4, 6 ;alien multiplier
mul r9, r4, r4 ;multiply "current alien"
addi r4, 2 ;point to xy location
add r8, r4 ;add the offset to alien address
ldm r4, r8 ;read it in
ret
:randomize_sprite
call get_status
cmpi r4, 3
jae alien_explode
subi r4, 1 ;take 1 off the status (incase its 2)
muli r4, 128 ;create the offset
mov r1, r8 ;save the alieninfo address
ldi r8, spr_alien ;point to alien sprite
add r8, r4 ;point to the correct animation frame
mov r0, r6 ;grab the current frame counter;
andi r0, #f ;check every 15 frames
cmpi r0, 0 ;see if our masked value is 0
jnz returnsub
rnd r5, #0001 ;generate random number (which part of animation)
addi r5, 1 ;add 1 as we never want zero
stm r5, r1
ret
:alien_explode
mov r0, r4 ;save status
addi r4, 1 ;increase to next frame value
subi r0, 3 ;bring current frame down from offset
muli r0, 128 ;multiply for offset
ldi r8, spr_aliendie ;point to alien death sprite
add r8, r0
ldi r2 alieninfo ;grab current alien status mem location
ldi r1, 6 ;alien multiplier
mul r9, r1, r1 ;multiply "current alien"
add r2, r1 ;add the offset to alien address
cmpi r4, 6
jz alien_dead
stm r4, r2 ;store the new status
ret
:alien_dead
ldi r4, 0
stm r4, r2 ;store the new status
ret
:draw_alien
spr #1008 ;width is half of real width
ldi r9, 0 ;set the current alien to beginning
:drawalienloop
call get_status
cmpi r4, 0 ;test for a status other than 0, if one exists, this alien is here
jz drawaliennext ;alien is not active, try the next
addi r8, 2 ;point it to the y after the status
ldm rb, r8 ;read in y to the register
addi r8, 2 ;point it to the x axis
ldm ra, r8 ;read in y to the register
call randomize_sprite ;choose an alien sprite
drw ra, rb, r8 ; ra=x, rb=y, r8=sprite memory location
jae drawaliennext
cmpi rb, 208
jbe alien_killed
ori rc, #1000 ;else its our poor ship :(
sng #00, #F3F8 ;set up the noise sound
ldi r0, ship_death_snd ;Load in the ship death frequency
snp r0, 100 ;Play it for 1000ms
:drawaliennext
addi r9, 1 ;Increment which alien we're dealing with
cmpi r9, 15 ;All possible aliens delt with?
jnz drawalienloop ;they arent so lets try the next one
ret
:alien_killed
ldi r8 alieninfo ;grab current alien status mem location
ldi r4, 6 ;alien multiplier
mul r9, r4, r4 ;multiply "current alien"
add r8, r4 ;add the offset to alien address
ldi r0, 3 ;alien is killed
stm r0, r8 ;save new status
sng #00, #F3F8 ;set up the noise sound
ldi r0, alien_death_snd ;Load in the ship death frequency
snp r0, 100 ;Play it for 100ms
ldm r0 bulletfired
cmpi r0, 0 ;check if there was actually a bullet
jz drawaliennext ;there wasnt so dont score the player
addi rd, 1 ;increase score
stm rd, current_score
ldi r0, 0
stm r0, bulletfired ;get rid of the bullet
jmp drawaliennext
:move_alien
ldi r9, 0 ;set the current alien to beginning
:moveloop
call get_status
cmpi r4, 0 ;test for a status other than 0, if one exists, this alien is here
jz movenext ;alien is not active, try the next
cmpi r4, 3 ;test for a status other than 0, if one exists, this alien is here
jae movenext ;alien is dead, try the next
addi r8, 2 ;point it to the y after the status
ldm r4, r8 ;read it in
addi r4, 1 ;move our alien down 1 pixel
stm, r4, r8 ;put it back in memory
cmpi r4, 240 ;has it gone of the screen?
jnz movenext ;hasnt gone off screen so dont disable
subi r8, 2 ;point it to the status for current alien
ldi r4, 0 ;put 0 in temp register
stm r4, r8 ;set the active flag for current alien to 0
:movenext
addi r9, 1 ;Increment which alien we're dealing with
cmpi r9, 15 ;All possible aliens delt with?
jnz moveloop ;they arent so lets try the next one
ret ;we have our aliens moved!
:spawnnext
addi r9, 1 ;Increment which alien we're dealing with
cmpi r9, 15 ;All possible aliens delt with?
jnz spawn_loop ;they arent so lets try the next one
ret ;we have our aliens!
:spawn_alien
cmp r6, r7 ;see if we've hit the spawn time
jnz returnsub ;we havent yet so don't spawn
ldi r9, 0 ;set the current alien to beginning
ldi r6, 0 ;reset spawn timer
:spawn_loop
call get_status
cmpi r4, 0 ;test for a status other than 0, if one exists, this alien is here
jnz spawnnext ;alien is active, don't spawn one, try the next
ldi r4, 1 ;set as active
stm r4, r8 ;store the active status in memory
addi r8, 2 ;point it to the y after the status
ldi r4, 10 ;clear reg to 10 pixels down
stm r4, r8 ;store y axis memory for this alien
rnd r5, 19 ;generate random number up to 14! (max 19x16=306 x-axis)
muli r5, 16 ;multiply it to get our x value
addi r8, 2 ;look at x axis
stm r5, r8 ;store x axis memory for this alien
jmp returnsub ;we spawned an alien, so come out
:draw_ship
spr #1008 ;width is half of real width
ldi rb, 224 ;Ship always drawn at the bottom
ldi r8, spr_ship ;load mem address of ship sprite in to memory
mov ra, rc ;Ship x position
cmpi ra, #1000
jb draw_ship_finish
;we've exploded so change the picture
mov r0, rc ;grab ship register again
shr r0, 12 ;move the bit down
subi r0, 1 ;align offset
muli r0, 128 ;multiply the offset
ldi r8, spr_shipdie ;change to the ship death animation
add r8, r0 ;add it on to sprite address
addi rc, #1000 ;increment frame
:draw_ship_finish
andi ra, #fff
drw ra, rb, r8 ; ra=x, rb=y, r8=sprite memory location
ret
:returnsub
ret
;Making aliens explode.
; cmpi rb, 210
; jnz drawaliennext
; ldi r8 alieninfo ;grab current alien status mem location
; ldi r4, 6 ;alien multiplier
; mul r9, r4, r4 ;multiply "current alien"
; add r8, r4 ;add the offset to alien address
; ldi r4, 3
; stm r4, r8
;MADE UP MEMORY BLOCKS
:player_lives
db #00
db 255
:current_level
db #00
db 255
:current_score
db #00
db 255
:bulletfired
db #00
db #00
:bulletposx
db #00
db #00
:bulletposy
db #00
db #00
:you_scored_ascii
db "You Scored:"
db 255
:game_over_ascii
db "Game Over!"
db 255
:press_start_ascii
db "PRESS START"
db 255
:player_score_ascii
db "Score:"
db 255
:player_lives_ascii
db "Lives:"
db 255
:player_level_ascii
db "Level:"
db 255
:spawn_timer
db 120
:zero_amount
db #00
db #00
:ship_death_snd
db #DC
db #02
:alien_death_snd
db #DC
db #05
:bullet_fire_snd
db #DC
db #05
:alieninfo
db #00 ;Alien 1
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 2
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 3
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 4
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 5
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 6
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 7
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 8
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 9
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 10
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 11
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 12
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 13
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 14
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 15
db #00
db #00
db #00
db #00
db #00
db #00 ;Alien 16
db #00
db #00
db #00 |
class Solution
{
public:
double findMedianSortedArrays (std::vector<int> &nums1, std::vector<int> &nums2)
{
if (nums1.empty() || nums2.empty())
{
auto &nums_nonempty {(nums2.empty()) ? nums1 : nums2};
if (nums_nonempty.size() & 1)
{
return nums_nonempty[nums_nonempty.size() / 2];
}
else
{
auto offset {(nums_nonempty.size() / 2) - 1};
return (nums_nonempty[offset] + nums_nonempty[offset + 1]) / 2.0;
}
}
auto size_12 {nums1.size() + nums2.size()};
auto middle_offset_12 {(size_12 - 1) / 2};
auto &nums_shorter {(nums1.size() <= nums2.size()) ? nums1 : nums2};
auto &nums_longer {(nums1.size() <= nums2.size()) ? nums2 : nums1};
auto lower_offset_12
{
nums_shorter.size() +
std::distance
(
nums_longer.begin(),
std::lower_bound
(
nums_longer.begin(),
nums_longer.end(),
*nums_shorter.rbegin()
)
) - 1
};
auto offset_longer {middle_offset_12 - nums_shorter.size()};
if (lower_offset_12 < middle_offset_12)
{
if (size_12 & 1)
{
return nums_longer[offset_longer];
}
else
{
return (nums_longer[offset_longer] + nums_longer[offset_longer + 1]) / 2.0;
}
}
else if (lower_offset_12 == middle_offset_12)
{
if (size_12 & 1)
{
return *nums_shorter.rbegin();
}
else
{
return (*nums_shorter.rbegin() + nums_longer[offset_longer + 1]) / 2.0;
}
}
auto upper_offset_12
{
std::distance
(
nums_longer.begin(),
std::upper_bound
(
nums_longer.begin(),
nums_longer.end(),
*nums_shorter.begin()
)
)
};
if (size_12 & 1)
{
if (middle_offset_12 < upper_offset_12)
{
return nums_longer[middle_offset_12];
}
else if (middle_offset_12 == upper_offset_12)
{
return *nums_shorter.begin();
}
}
else
{
if (middle_offset_12 + 1 < upper_offset_12)
{
return (nums_longer[middle_offset_12] + nums_longer[middle_offset_12 + 1]) / 2.0;
}
else if (middle_offset_12 + 1 == upper_offset_12)
{
return (*nums_shorter.begin() + nums_longer[middle_offset_12]) / 2.0;
}
}
int left {};
auto right {nums_shorter.size() - 1};
auto offset_shorter {(nums_shorter.size() - 1) / 2};
offset_longer = (nums_longer.size() - 1) / 2;
while (true)
{
if (nums_shorter[offset_shorter] <= nums_longer[offset_longer])
{
if ((offset_shorter + 1) == nums_shorter.size() || nums_longer[offset_longer] <= nums_shorter[offset_shorter + 1])
{
if (nums_shorter.size() & 1 && nums_longer.size() & 1)
{
if (offset_longer == 0 || nums_longer[offset_longer - 1] < nums_shorter[offset_shorter])
{
return (nums_shorter[offset_shorter] + nums_longer[offset_longer]) / 2.0;
}
else
{
return (nums_longer[offset_longer - 1] + nums_longer[offset_longer]) / 2.0;
}
}
else if ((nums_shorter.size() & 1) ^ (nums_longer.size() & 1))
{
return nums_longer[offset_longer];
}
else
{
if ((offset_shorter + 1) == nums_shorter.size() || nums_longer[offset_longer + 1] <= nums_shorter[offset_shorter + 1])
{
return (nums_longer[offset_longer] + nums_longer[offset_longer + 1]) / 2.0;
}
else
{
return (nums_longer[offset_longer] + nums_shorter[offset_shorter + 1]) / 2.0;
}
}
}
else
{
left = offset_shorter + 1;
offset_shorter = (left + right) / 2;
offset_longer -= (offset_shorter - left + 1);
}
}
else
{
if (nums_shorter[offset_shorter] <= nums_longer[offset_longer + 1])
{
if (nums_shorter.size() & 1 && nums_longer.size() & 1)
{
if (offset_shorter == 0 || nums_shorter[offset_shorter - 1] < nums_longer[offset_longer])
{
return (nums_shorter[offset_shorter] + nums_longer[offset_longer]) / 2.0;
}
else
{
return (nums_shorter[offset_shorter - 1] + nums_shorter[offset_shorter]) / 2.0;
}
}
else if ((nums_shorter.size() & 1) ^ (nums_longer.size() & 1))
{
return nums_shorter[offset_shorter];
}
else
{
if ((offset_shorter + 1) == nums_shorter.size() || nums_longer[offset_longer + 1] <= nums_shorter[offset_shorter + 1])
{
return (nums_shorter[offset_shorter] + nums_longer[offset_longer + 1]) / 2.0;
}
else
{
return (nums_shorter[offset_shorter] + nums_shorter[offset_shorter + 1]) / 2.0;
}
}
}
else
{
right = offset_shorter - 1;
offset_shorter = (left + right) / 2;
offset_longer += (right - offset_shorter + 1);
}
}
}
return 0;
}
};
|
SECTION code_clib
SECTION code_l_sccz80
PUBLIC l_mult
PUBLIC l_mult_u
PUBLIC l_mult_0
; Entry: hl = value1
; de = value2
; Exit: hl = value1 * value2
.l_mult
.l_mult_u
ld bc,hl
.l_mult_0
defb 0xf7 ; mul : hlbc = bc * de
ld hl,bc
ret
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %rax
push %rbp
push %rbx
push %rcx
// Store
lea addresses_normal+0x1cc52, %rbp
nop
nop
nop
nop
and %r13, %r13
mov $0x5152535455565758, %rcx
movq %rcx, %xmm3
vmovups %ymm3, (%rbp)
nop
nop
and %r12, %r12
// Store
lea addresses_UC+0x1fe52, %rcx
clflush (%rcx)
nop
nop
nop
nop
sub $59453, %rax
mov $0x5152535455565758, %rbx
movq %rbx, %xmm7
movups %xmm7, (%rcx)
nop
nop
nop
nop
nop
cmp %r13, %r13
// Store
mov $0xc9e, %rbx
nop
nop
sub %r12, %r12
mov $0x5152535455565758, %rcx
movq %rcx, (%rbx)
nop
cmp %rax, %rax
// Store
lea addresses_RW+0x12938, %r13
nop
nop
inc %rax
mov $0x5152535455565758, %r11
movq %r11, %xmm1
movaps %xmm1, (%r13)
sub %rbp, %rbp
// Load
lea addresses_normal+0x1145a, %r13
nop
sub %rbp, %rbp
mov (%r13), %rbx
add $56423, %rbp
// Faulty Load
lea addresses_UC+0xb452, %r11
nop
nop
add $48311, %rax
mov (%r11), %cx
lea oracles, %rbp
and $0xff, %rcx
shlq $12, %rcx
mov (%rbp,%rcx,1), %rcx
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': True, 'same': False, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_normal', 'AVXalign': False, 'size': 32}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_UC', 'AVXalign': False, 'size': 16}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_P', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_RW', 'AVXalign': True, 'size': 16}}
{'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_normal', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'00': 3}
00 00 00
*/
|
SECTION code_l_sdcc
PUBLIC __mulint
GLOBAL l_mul16
__mulint:
ld hl,sp+2
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld a,(hl+)
ld h,(hl)
ld l,a
;; Parameters:
;; HL, DE (left, right irrelivent)
ld b,h
ld c,l
jp l_mul16
|
; int __CALLEE__ vfprintf_callee(FILE *stream, const char *format, void *arg_ptr)
; 05.2008 aralbrec
PUBLIC vfprintf_callee
EXTERN stdio_outchar, stdio_atou, jumptbl_printf, stdio_nextarg, stdio_error_eacces_mc, stdio_error_mc
PUBLIC ASMDISP_VFPRINTF_CALLEE, LIBDISP_VFPRINTF_CALLEE
INCLUDE "../stdio.def"
.vfprintf_callee
pop hl
pop bc
pop de
pop ix
push hl
.asmentry
; enter : ix = FILE *
; de = format string
; bc = & parameter list (arg_ptr)
; exit : hl = number of chars output to stream, carry reset
; hl = -1 and carry if error
bit 1,(ix+3) ; open for output?
jp z, stdio_error_eacces_mc
.libentry
; second entry point with ix equal to function address
;
; enter : ix = FILE *
; de = format string
; bc = & parameter list (arg_ptr)
; exit : hl = number of chars output to stream
; hl = -1 and carry if error
ld hl,-STDIO_TEMPBUFSIZE
add hl,sp
ld sp,hl
push bc
exx
ld bc,0
exx
; bc' = number of chars output to stream = 0
; ix = FILE *
; de = format string
; stack = buffer (STDIO_TEMPBUFSIZE bytes), & parameter list
.formatloop
; de = pointer in format string
; stack = & parameter list
ld a,(de) ; next format char
or a ; reached the end of the format string?
jr z, exitnoerror
inc de
cp '%'
jr z, specifier
.ordinarychar
call stdio_outchar ; output a char onto the stream
jp nc, formatloop ; loop if no stream error detected
.exitwitherror
ld hl,STDIO_TEMPBUFSIZE + 2 ; remove items from stack
add hl,sp
ld sp,hl
jp stdio_error_mc
.exitnoerror
ld hl,STDIO_TEMPBUFSIZE + 2 ; remove items from stack
add hl,sp
ld sp,hl
exx
push bc
exx
pop hl ; hl = number of chars written on stream
or a
ret
.specifier ; '%' already consumed
; read format parameters
; %{flags}{* | width}[.{* | prec}] [l] "bcdeEfFinopPsuxX"
ld c,0
; de = pointer in format string
; c = flags [-+ O#PLN]
; stack = & parameter list
.flagloop
ld a,(de) ; potential flag char
ld hl,flags
ld b,5
.flagsrch
cp (hl) ; flag char found in table?
inc hl ; move past table flag char
jr z, flagfound
inc hl ; move past table flag bitmask
djnz flagsrch ; loop until flag char not found
.width
; a = current format string char
; de = pointer in format string
; c = flags [-+ O#PLN]
; stack = & parameter list
cp '*'
jr nz, readwidth
; asterisk means width comes from parameter list
pop hl
dec hl
ld b,(hl)
dec hl
push hl
inc de ; consume *
jp dot
.flagfound
ld a,(hl) ; read bitmask from table
inc hl
or c
ld c,a ; set flag register
inc de ; next format string char
jp flagloop
.readwidth ; read width from format string
push bc
call stdio_atou
pop bc
ld b,l
.dot
; b = width
; de = pointer in format string
; c = flags [-+ O#PLN]
; stack = & parameter list
ld h,1 ; h = default precision = 1
ld a,(de)
cp '.'
jr nz, formatchar
inc de ; consume .
set 2,c ; indicate precision present in flags
ld a,(de)
cp '*'
jr nz, readprec
; asterisk means precision comes from parameter list
pop hl
dec hl
ld a,(hl)
dec hl
push hl
ld h,a
inc de ; consume *
jp formatchar
.readprec ; read precision from format string
push bc
call stdio_atou
pop bc
ld h,l
.formatchar
; b = width
; h = precision
; de = pointer in format string
; c = flags [-+ O#PLN]
; stack = & parameter list
ld a,(de) ; check for long specifier
cp 'l'
jr nz, nolongspec
inc de ; consume the 'l'
set 1,c ; set long flag
.nolongspec
push hl
ld hl,jumptbl_printf
ex de,hl
; b = width
; hl = pointer in format string
; c = flags [-+ O#PLN]
; de = & jumptbl_printf
; stack = & parameter list, precision (MSB)
.specsrch
ld a,(de) ; table's format char
or a
jr z, fmtcharerror
cp (hl)
jr z, fmtcharfound
inc de ; next table entry
inc de
inc de
inc de
jp specsrch
.fmtcharerror
; unrecognized format char
pop af
ex de,hl
ld a,(de)
cp '%' ; did we see %%
ld a,'%'
jp nz, ordinarychar ; if no, output % but don't advance past the unknown fmt char
inc de ; if %% advance past the second %
jp ordinarychar
.fmtcharfound
inc hl ; consume format char
; b = width
; hl = pointer in format string
; c = flags [-+ O#PLN]
; de = & jumptbl_printf.fmtchar
; stack = & parameter list, precision (MSB)
pop af
ex (sp),hl
call doformat
; return here after formatted output done
; hl = & parameter list
; stack = pointer in format string
; carry set if error on stream, ERRNO set appropriately
pop de
push hl
; de = format string
; stack = & parameter list
jp nc, formatloop ; no error in stream
jp exitwitherror
.doformat
inc de
push de
; a = precision (default 1)
; b = width (default 0)
; c = flags [-+ O#PLN]
; hl = & parameter list
; stack = pointer in format string, ret, format function address
call stdio_nextarg ; get first 16-bit parameter
.callfmtfunc
; set-up for formatted output functions
;
; enter : ix = FILE *
; a = precision (default 1)
; b = width (default 0)
; c = flags [-+ O#PLN]
; de = 16-bit parameter (most significant word if long)
; hl = & parameter list
; bc' = total num chars output on stream thus far
; carry flag reset (important for %x, %lx)
; stack = output buffer, ptr in format string, ret
; on exit : bc' = total num chars output on stream thus far
; hl = & parameter list
; carry set if error on stream, ERRNO set appropriately
;
; MUST NOT ALTER EXX REGISTERS FOR SPRINTF FAMILY
or a ; clear carry
bit 7,d ; set negative flag if de < 0
ret z ; doing it here saves a few bytes
set 0,c
ret ; ret calls formatted output function
.flags
defb '-', 128
defb '+', 64
defb ' ', 32
defb '0', 16
defb '#', 8
defc ASMDISP_VFPRINTF_CALLEE = # asmentry - vfprintf_callee
defc LIBDISP_VFPRINTF_CALLEE = # libentry - vfprintf_callee
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcb/v20180608/model/LogServiceInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcb::V20180608::Model;
using namespace std;
LogServiceInfo::LogServiceInfo() :
m_logsetNameHasBeenSet(false),
m_logsetIdHasBeenSet(false),
m_topicNameHasBeenSet(false),
m_topicIdHasBeenSet(false),
m_regionHasBeenSet(false)
{
}
CoreInternalOutcome LogServiceInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("LogsetName") && !value["LogsetName"].IsNull())
{
if (!value["LogsetName"].IsString())
{
return CoreInternalOutcome(Error("response `LogServiceInfo.LogsetName` IsString=false incorrectly").SetRequestId(requestId));
}
m_logsetName = string(value["LogsetName"].GetString());
m_logsetNameHasBeenSet = true;
}
if (value.HasMember("LogsetId") && !value["LogsetId"].IsNull())
{
if (!value["LogsetId"].IsString())
{
return CoreInternalOutcome(Error("response `LogServiceInfo.LogsetId` IsString=false incorrectly").SetRequestId(requestId));
}
m_logsetId = string(value["LogsetId"].GetString());
m_logsetIdHasBeenSet = true;
}
if (value.HasMember("TopicName") && !value["TopicName"].IsNull())
{
if (!value["TopicName"].IsString())
{
return CoreInternalOutcome(Error("response `LogServiceInfo.TopicName` IsString=false incorrectly").SetRequestId(requestId));
}
m_topicName = string(value["TopicName"].GetString());
m_topicNameHasBeenSet = true;
}
if (value.HasMember("TopicId") && !value["TopicId"].IsNull())
{
if (!value["TopicId"].IsString())
{
return CoreInternalOutcome(Error("response `LogServiceInfo.TopicId` IsString=false incorrectly").SetRequestId(requestId));
}
m_topicId = string(value["TopicId"].GetString());
m_topicIdHasBeenSet = true;
}
if (value.HasMember("Region") && !value["Region"].IsNull())
{
if (!value["Region"].IsString())
{
return CoreInternalOutcome(Error("response `LogServiceInfo.Region` IsString=false incorrectly").SetRequestId(requestId));
}
m_region = string(value["Region"].GetString());
m_regionHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void LogServiceInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_logsetNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LogsetName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_logsetName.c_str(), allocator).Move(), allocator);
}
if (m_logsetIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LogsetId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_logsetId.c_str(), allocator).Move(), allocator);
}
if (m_topicNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TopicName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_topicName.c_str(), allocator).Move(), allocator);
}
if (m_topicIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TopicId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_topicId.c_str(), allocator).Move(), allocator);
}
if (m_regionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Region";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_region.c_str(), allocator).Move(), allocator);
}
}
string LogServiceInfo::GetLogsetName() const
{
return m_logsetName;
}
void LogServiceInfo::SetLogsetName(const string& _logsetName)
{
m_logsetName = _logsetName;
m_logsetNameHasBeenSet = true;
}
bool LogServiceInfo::LogsetNameHasBeenSet() const
{
return m_logsetNameHasBeenSet;
}
string LogServiceInfo::GetLogsetId() const
{
return m_logsetId;
}
void LogServiceInfo::SetLogsetId(const string& _logsetId)
{
m_logsetId = _logsetId;
m_logsetIdHasBeenSet = true;
}
bool LogServiceInfo::LogsetIdHasBeenSet() const
{
return m_logsetIdHasBeenSet;
}
string LogServiceInfo::GetTopicName() const
{
return m_topicName;
}
void LogServiceInfo::SetTopicName(const string& _topicName)
{
m_topicName = _topicName;
m_topicNameHasBeenSet = true;
}
bool LogServiceInfo::TopicNameHasBeenSet() const
{
return m_topicNameHasBeenSet;
}
string LogServiceInfo::GetTopicId() const
{
return m_topicId;
}
void LogServiceInfo::SetTopicId(const string& _topicId)
{
m_topicId = _topicId;
m_topicIdHasBeenSet = true;
}
bool LogServiceInfo::TopicIdHasBeenSet() const
{
return m_topicIdHasBeenSet;
}
string LogServiceInfo::GetRegion() const
{
return m_region;
}
void LogServiceInfo::SetRegion(const string& _region)
{
m_region = _region;
m_regionHasBeenSet = true;
}
bool LogServiceInfo::RegionHasBeenSet() const
{
return m_regionHasBeenSet;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.